All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.
Rust
feat(memory): instruction files, Memory locations settings and a User memory view
Corey Chiu575f702b9ef7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5c80f83..0f9d81e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,12 +2,14 @@## [Unreleased]-- New: Memory page — the notes coding agents keep for themselves on this machine (Claude Code's per-project auto-memory, Codex's memories and per-session summaries, ZCode's project memory) in one place, grouped by project with the sidebar switching to memory navigation. Read-only: open a file in its own app to change it-- New: `wake_list_memories` in the MCP server and `wake-cli memories` list those files for other agents; `wake_get_session` reads one by its `wake://memory/…` reference and `wake_search` also surfaces memory files that mention the query-- Update: the sidebar switches between Sessions, Memory, Insights and Clean Up from an icon strip at the bottom; Refresh moved into each page header+- 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 memory+- New: Settings → Memory locations shows every source the Memory page reads, with a switch per source, your own folders or files, and Restore defaults+- New: `wake_list_memories` and `wake-cli memories` list those files for other agents; `wake_get_session` reads one by its `wake://memory/…` reference and `wake_search` also surfaces memory files that mention the query+- Update: the sidebar switches between Sessions, Memory, Insights and Clean Up from an icon strip at the bottom; Refresh moved into each page header, and on the Memory page it re-reads only the memory locations+- Update: sidebar polish — a spinner and progress bar while a refresh runs, collapse arrows in front of the Agents and Projects headers, and one consistent gap between icons and labels throughout the app- Fix: a search term of one or two characters no longer crashes Wake when a matching message contains characters such as Ω, İ or K before the match-- Update: Codex sub-agents started with `spawn_agent` are indexed again, nested under the session that spawned them and titled with their task name; the parent's conversation that Codex copies into each sub-agent is folded away so it is only indexed once. The guardian auto-review, `/review`, compaction and memory-consolidation threads stay excluded. In the MCP tools and `wake-cli`, a session now names its parent and lists its child sessions, for every agent that has them (#42, thanks @ShadowySpirits). Existing indexes are re-read once after upgrading-- New: ZCode (Z.ai's GLM-5.3 desktop harness) sessions are indexed from its local database — titles, models, tool calls and token counts included. Forks and side chats are listed like any other conversation; sub-agent runs and conversations imported from Claude Code are left out so nothing appears twice. Read-only, and no Open In: the app has no command line to resume from+- Update: Codex sub-agents started with `spawn_agent` are indexed again, nested under the session that spawned them and titled with their task name; the parent conversation Codex copies into each one is folded away so it is indexed once, and the guardian auto-review, `/review`, compaction and memory-consolidation threads stay excluded. In the MCP tools and `wake-cli`, a session now names its parent and lists its child sessions (#42, thanks @ShadowySpirits). Existing indexes are re-read once after upgrading+- New: ZCode (Z.ai's GLM-5.3 desktop harness) sessions are indexed from its local database — titles, models, tool calls and token counts included; forks and side chats are listed, sub-agent runs and conversations imported from Claude Code are left out. Read-only, and no Open In: the app has no command line to resume from## [0.7.0] — 2026-09-16diff --git a/DESIGN.md b/DESIGN.mdindex 31e92d5..07c8d75 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -94,7 +94,7 @@ Wake 的目标不是展示技术感,而是让用户在几秒内重新找到并**颜色三级制**:`foreground`(主文字)/`muted_foreground`(全部辅助文字)/`primary`(强调与激活)。不引入第四种文字灰;不在 muted 色上叠 opacity。-**间距刻度(4px 网格)**:`SPACE_XS/SM/MD/LG/XL/XXL` = 4/8/12/16/20/24,定义在 `ui.rs`。新代码引用常量或显式 `px()`;**对齐敏感处禁用 rem 间距类**——`p_2p5` 实为 8.75px、`p_3` 实为 10.5px(rem=14 折算),均不在网格上,是对齐失真的来源。存量 rem 类已于 2026-08-24 全量迁移完毕,代码中不再允许出现 rem 间距类(`p_0` 例外,零无幽灵值)。+**间距刻度(4px 网格)**:`SPACE_XS/SM/MD/LG/XL/XXL` = 4/8/12/16/20/24,定义在 `ui.rs`。新代码引用常量或显式 `px()`;**对齐敏感处禁用 rem 间距类**——`p_2p5` 实为 8.75px、`p_3` 实为 10.5px(rem=14 折算),均不在网格上,是对齐失真的来源。存量 rem 类已于 2026-08-24 全量迁移完毕,代码中不再允许出现 rem 间距类(`p_0` 例外,零无幽灵值)。**图标与紧随其后文字的间距只有一个值 `ICON_TEXT_GAP` = 6px**(侧栏行与组头、列表元信息行、详情 / 阅读面头部与元信息行、⌘K 结果、Insights 榜单、Open In 菜单、状态行、设置页与清理页的行;用户 2026-09-22 定统一,原先 4 / 6 / 7 / 8 / 12 各处不一);它故意不在 4px 网格上:品牌 PNG 没有留白、8px 显得空,lucide 线条图标自带约 1.5px 留白、6px 几何间距视觉约 7.5px。卡片级的 24px 头像(清理历史的记录卡)不在此列。**侧栏中轴(x = 26.75)**:traffic lights 定位 (20,11),红灯实测直径 13.5px,中心即 **26.75**。侧栏所有行首元素的**视觉中心**压在这条竖线上,而非左缘对齐:@@ -103,15 +103,15 @@ Wake 的目标不是展示技术感,而是让用户在几秒内重新找到并| 容器内边距 | `SIDEBAR_EDGE` | 10 | 行 hover/选中胶囊的左右留白 || 行首槽位 | `LEAD_BOX` | 18 | 最大前导元素(品牌图)尺寸,槽内**居中** || 行左内边距 | `LEAD_INSET` | 7.75 | 26.75 − 9(槽位半宽) − 10 |-| 组头左内边距 | `GROUP_HEAD_INSET` | 12.125 | 由首字母字形中心反推(Body 常规下 A 宽 8.25、P 宽 7.25,两者中心恰好重合) |+| 组头(Agents / Projects) | `LEAD_INSET + (LEAD_BOX − 15) / 2` | 9.25 | 15px 折叠 chevron 按自己的框居中压轴,不占 18px 槽位(2026-09-22 起;原先靠首字母字形宽度反推 `GROUP_HEAD_INSET` = 12.125,已删) || 标题左内边距 | `TITLE_INSET` | 9 | 由 "Wake" 的 W 反推(Heading semibold,W 宽 14.25、左承距 0.5) || 分组项缩进 | `SUB_INDENT` | 12 | 分组项行首中心落在 38.75,表达从属 |三条硬约束:1. **中心对齐与左缘对齐是同一个自由度,只能满足一个。** 选了中心,18px 品牌图的左缘就落在 17.75,比红灯左缘还靠左 2.25——这是预期结果,不是错位。同理分组项一旦缩进就不再压轴。-2. **`GROUP_HEAD_INSET` / `TITLE_INSET` 不是间距,是从字形宽度反推的值**,组头或标题的字号、字重一改立即失效,必须重新实测字形再算(11px semibold 时需 13.25/13.0,Body 常规时变成 12.125)。-3. **2x 屏光栅化步长是 0.5px,别往小数点后继续调。** 实测 `GROUP_HEAD_INSET` 取 12.125 落位 −0.125,改成 12.25 反而跳到 +0.375——两者落进不同物理像素。全部元素落在 ±0.375 以内即为达标。+2. **`TITLE_INSET` 不是间距,是从字形宽度反推的值**,标题的字号、字重一改立即失效,必须重新实测字形再算(组头原先同理:11px semibold 时需 13.25、Body 常规时 12.125——2026-09-22 组头改为 chevron 领头后不再依赖字形)。+3. **2x 屏光栅化步长是 0.5px,别往小数点后继续调。** 当年组头内边距取 12.125 落位 −0.125,改成 12.25 反而跳到 +0.375——两者落进不同物理像素。全部元素落在 ±0.375 以内即为达标。**行高两级**(侧栏纵向层级的来源):主导航 `ROW_HEIGHT` 32px + Body 14,分组展开项 `ROW_HEIGHT_SUB` 26px + Caption 12。圆角均 8px。@@ -133,11 +133,11 @@ macOS 不设置横跨三栏的自定义 header。主窗口透明标题栏高 44p- **每行必须有行首元素**,由 `RowLead` 枚举强制(`Icon` 或 `Brand` 两态,无 `None`):主导航用 Lucide 单线图标,agent 行用品牌 PNG,项目行用 `folder.svg`。槽位定宽 `LEAD_BOX` 管右侧文字起点统一,槽内居中管中轴对齐。- 线条图标比实心品牌图视觉轻,同档里给小一号:分组项 Lucide 14 / 品牌图 18,主导航 Lucide 15。- 行内容 = 行首元素 + 标题 + 计数;计数一律 Label 档 muted。-- 组头 "Agents"/"Projects" 用 Body 档常规字重 + muted 色(与主导航同字号同字重,仅靠颜色和"无行首图标"区分——加粗会让组头压过它统辖的行),带 13px chevron 可折叠。-- 底部工具条常驻,总高 44px(含顶部 1px hairline),两端分置的**纯图标条**(2026-09-21 三轮定稿:六个一样的 ghost 图标挤一排分不出层级;带边框底色的分段盒子放在侧栏里像一个走错地方的表单控件——参照 Zed 状态栏 / Xcode 导航条,不带盒子):按钮统一 28×28、6px 圆角、14px 图标、2px 间距;**左端**——Sessions(messages-square,双气泡;单气泡的 message-square 留给消息级用途)/ Memory(brain)/ Insights(chart-column)三颗页切换,再接 brush-cleaning "Clean Up Sessions"(它是叠在会话视图上的模式,也靠左),当前页(或打开中的清理)那颗用侧栏行的选中色(`sidebar_accent` 底 + `sidebar_accent_foreground` 图标)做圆角底,与导航行选中态同一套语言;**右端只有齿轮 "Settings"**。左内边距 12.75 = 26.75(侧栏中轴)− 14(按钮半宽):最左那颗图标的中心与红绿灯红灯中心、导航行行首在同一条轴上。未选中的一律透明底、muted 图标,hover 才出色。**Refresh 不在工具条**:它住在每页页头右端(All Sessions 页头在 Sort 左侧,Memory / Insights 页头单独一个;tooltip 就叫 "Refresh"),三页同一条全库重扫、不分页——Memory 与 Insights 的数据都是扫描收尾派生的;扫描进行中转圈并禁用,⌘R 仍是同一条路。Settings 同时进入 Wake 菜单并绑定 `⌘,`(其他平台 `Ctrl+,`),保持单例窗口。-- Settings 默认 820×600,采用 180px 窄侧栏 + 内容页结构,固定为 General / Locations / Remote hosts / Connect / Data / Updates / About 七项(Connect 为 0.5.0 新增,插在 Remote hosts 与 Data 之间——两页都是"把 Wake 接到外部"的集成面,Data 之后是纯本地信息);About 与功能设置分离并钉在侧栏底部,Wake 菜单的 About Wake 直达同一页。About 沿用 Kooky/Birth 的信息顺序:产品图标、名称、版本、tagline、GitHub、短分隔线、版权/许可证与作者署名。Updates 是独立功能页,仅在用户点击页面按钮或 macOS Wake 菜单的 Check for Updates 时读取 GitHub 最新正式 Release 元数据,明确呈现检查中/最新版/有新版/失败四种状态;有新版时打开 Release 页供用户下载,不后台检查、不自行覆盖应用包。内部常规文字按钮统一沿用主界面的 24px 高、6px 圆角和主题交互色,普通页面动作使用 muted 填充 + hairline;发现新版后的 View Update 是需要用户继续完成的主操作,使用 32px 高 primary 填充和轻阴影。Appearance 分段选择器也使用同一材质。General 只放真实可用的全局偏好,当前为持久化的 System / Light / Dark 外观选择与 Language(跟随系统或固定某个语言包,0.5.2 起);不提供默认 “Open In” 终端。Data 只展示 Wake 本地存储位置、会话数与磁盘占用并提供文件管理器入口,不重复放刷新或清库动作;常规 Refresh 的唯一入口仍是主侧栏底部。Locations 页按 AgentId 声明序以 agent 分组,品牌名只在组头出现一次;本机有数据的组优先,未检测到的 agent 默认收进可展开区。每条路径以路径为主信息、会话数/不可用状态为 muted 副信息,最右为逐路径开关;停用时只降低文字层级,开关与菜单保持完整对比度。行本身不承担编辑,`…` 菜单集中 Edit / Show in Finder / 自定义 Remove。顶部操作为低强调的 Add location,Restore defaults 收进页级 `…` 菜单且无偏离时禁用。添加/编辑仍复用 agent 下拉 + 可手输路径 + 目录选择表单;关闭 location 后保留配置、停止扫描/监听并从会话与搜索结果排除,重新开启即增量扫回;纯路径管理不做内容校验。Remote hosts 页沿用 Locations 的版式:标题 + 说明,右侧低强调的 Sync now / Add host;host 列表为单张 popover 底圆角卡,一行一台(名字为主信息、同步状态为 muted 副信息,失败用 danger),`…` 菜单集中 Sync now / Remove,最右为开关;添加走与 location 同材质的单字段表单弹窗,SSH 前提说明放在字段下方。列表与详情页的远程会话以 `@host` 徽章标识:列表行为 primary 淡底填充胶囊(与 muted 项目胶囊区分),详情页与 model/source 同排用 primary 描边。Connect 页沿用 Data 页的版式,**只放状态与动作,不放文档**(用户 2026-09-08 三轮定稿:平级双卡带代码块、嵌套同卡、缩进从属卡都试过,根源是设置窗里塞了 README 内容,怎么排都像教程):标题 + 一句说明(不点名 MCP、不写 read-only 声明);「MCP server」卡 84px 一行显示 wake-mcp 名称与 mono 字体的 `~/…` 路径,右侧 Copy path,不放"Ready"状态行,只在找不到二进制时给一行 danger 文案;「MCP clients」卡三行(Claude Code / Codex / Cursor),17px 品牌图标领行、客户端名为主信息、用法提示为 muted 副信息、右侧是 ghost 的 Show/Hide 切换(chevron 图标 + 文案,muted 前景,用户 2026-09-08 追加)加 Copy command / Copy config;代码块**默认收起**,展开后出现在该行下方、左缘对齐到文字轴(行内边距 16 + 图标 17 + 间距 12),secondary 填充 + 主题圆角的 mono 逐行渲染,Settings 重开即复位。0.6.x 起页面是**四个区块**(用户 2026-09-11 定稿):MCP server / MCP clients / Command line / Skill——MCP server / Command line / Skill 各一张 84px 信息卡、MCP clients 仍是三行客户端列表(wake-mcp、wake-cli 是二进制名与 mono 路径 + Copy path;wake-cli 那张在 Copy path **左侧**多一个 Copy command,复制「把它放进 PATH」的那行命令——右侧留给两张卡同名的 Copy path,纵向才对得齐;deb/tar 已装进 `…/bin` 或 Windows 上没有可粘命令时这个按钮不出现;Skill 是 `npx skills add …` + Copy command),区块标题为「Agents」时看不出这块特指 MCP,故改名 MCP clients 与上方 MCP server 成对。**说明性 caption 一律不放**——那正是"设置窗里塞 README"的复发形态;Setup guide 链接改挂在区块标题右端,规则是**每个面的第一个区块挂自己的文档**:MCP server → docs/mcp.md,Command line → docs/cli.md(MCP clients 与 Skill 分属这两个面的第二块,不重复挂)。四块之后整页**超过一屏、需要滚动**——2026-09-08 那条"一屏放下"的约束随第三、四个区块作废,滚动容器本来就在(`flex_1().min_h_0().overflow_y_scroll()`),卡片记得 `flex_shrink_0` 否则会被压扁。复制反馈是按钮原地变 "Copied"(check 图标)1.6s 后复原,**不弹通知**——gpui-component 的 toast 在窗口失活或被悬停时暂停自动关闭,在 Settings 从属窗里经常就挂着不走(用户 2026-09-08 反馈),且主界面的 Copy Session ID / Copy code 本来就不弹;页面只展示不代写别家配置。-- 工具条内的**状态行"常态沉默"**:仅刷新中或监听不可用时出现在按钮行上方;文案须可 truncate,窄侧栏放不下长句(故为 "Live updates off" 而非带操作建议的整句)。-- 手动 Refresh 始终后台运行;进度复用侧栏状态行,完成后发通知,不用模态框阻断浏览、搜索或阅读。+- 组头 "Agents"/"Projects" 用 Body 档常规字重 + muted 色(与主导航同字号同字重,仅靠颜色区分——加粗会让组头压过它统辖的行)。行首是 13px 的折叠 chevron(收起指右、展开指下),坐在与导航行同一个 18px 行首槽位里、中心压 26.75 轴(用户 2026-09-22 定:箭头放到开头,对准上面菜单的图标与红绿灯的红灯;原先 chevron 跟在文字后);chevron 取 15px(与导航行图标同档,描边粗细一致),**不占 18px 槽位、按自己的框居中压轴**,再接统一的 `ICON_TEXT_GAP`——槽位居中再接同一间距,墨迹到文字会比导航行空出一截(chevron 墨迹只有约 5px 宽,用户同日"间隔太大");按框压轴后墨迹到文字视觉约 10.9px 与导航行相当,文字起点比导航行标签左 1.5px。+- 底部工具条常驻,总高 44px(含顶部 1px hairline),两端分置的**纯图标条**(2026-09-21 三轮定稿:六个一样的 ghost 图标挤一排分不出层级;带边框底色的分段盒子放在侧栏里像一个走错地方的表单控件——参照 Zed 状态栏 / Xcode 导航条,不带盒子):按钮统一 28×28、6px 圆角、14px 图标、2px 间距;**左端**——Sessions(messages-square,双气泡;单气泡的 message-square 留给消息级用途)/ Memory(brain)/ Insights(chart-column)三颗页切换,再接 brush-cleaning "Clean Up Sessions"(它是叠在会话视图上的模式,也靠左),当前页(或打开中的清理)那颗用侧栏行的选中色(`sidebar_accent` 底 + `sidebar_accent_foreground` 图标)做圆角底,与导航行选中态同一套语言;**右端只有齿轮 "Settings"**。左内边距 12.75 = 26.75(侧栏中轴)− 14(按钮半宽):最左那颗图标的中心与红绿灯红灯中心、导航行行首在同一条轴上。未选中的一律透明底、muted 图标,hover 才出色。**Refresh 不在工具条**:它住在每页页头右端(All Sessions 页头在 Sort 左侧,Memory / Insights 页头单独一个;tooltip 就叫 "Refresh"),会话页与 Insights 走整库重扫(Insights 的数据是扫描收尾派生的),Memory 页只同步记忆(读 Settings → Memory locations 的当下配置,不重扫会话;用户 2026-09-22 定各刷各的);进行中转圈并禁用,⌘R 恒为刷会话。Settings 同时进入 Wake 菜单并绑定 `⌘,`(其他平台 `Ctrl+,`),保持单例窗口。+- Settings 默认 820×600,采用 180px 窄侧栏 + 内容页结构,固定为 General / Session locations / Memory locations / Remote hosts / Connect / Data / Updates / About 八项(侧栏项原叫 Locations,有了 Memory locations 后改成与页标题一致的 Session locations,用户 2026-09-21 定)(Connect 为 0.5.0 新增,插在 Remote hosts 与 Data 之间——两页都是"把 Wake 接到外部"的集成面,Data 之后是纯本地信息;Memory locations 是记忆可见层二期加的,紧挨 Locations——两页都是"Wake 读哪里");About 与功能设置分离并钉在侧栏底部,Wake 菜单的 About Wake 直达同一页。About 沿用 Kooky/Birth 的信息顺序:产品图标、名称、版本、tagline、GitHub、短分隔线、版权/许可证与作者署名。Updates 是独立功能页,仅在用户点击页面按钮或 macOS Wake 菜单的 Check for Updates 时读取 GitHub 最新正式 Release 元数据,明确呈现检查中/最新版/有新版/失败四种状态;有新版时打开 Release 页供用户下载,不后台检查、不自行覆盖应用包。内部常规文字按钮统一沿用主界面的 24px 高、6px 圆角和主题交互色,普通页面动作使用 muted 填充 + hairline;发现新版后的 View Update 是需要用户继续完成的主操作,使用 32px 高 primary 填充和轻阴影。Appearance 分段选择器也使用同一材质。General 只放真实可用的全局偏好,当前为持久化的 System / Light / Dark 外观选择与 Language(跟随系统或固定某个语言包,0.5.2 起);不提供默认 “Open In” 终端。Data 只展示 Wake 本地存储位置、会话数与磁盘占用并提供文件管理器入口,不重复放刷新或清库动作;常规 Refresh 的唯一入口仍是主侧栏底部。Locations 页按 AgentId 声明序以 agent 分组,品牌名只在组头出现一次;本机有数据的组优先,未检测到的 agent 默认收进可展开区。每条路径以路径为主信息、会话数/不可用状态为 muted 副信息,最右为逐路径开关;停用时只降低文字层级,开关与菜单保持完整对比度。行本身不承担编辑,`…` 菜单集中 Edit / Show in Finder / 自定义 Remove。顶部操作为低强调的 Add location,Restore defaults 收进页级 `…` 菜单且无偏离时禁用。添加/编辑仍复用 agent 下拉 + 可手输路径 + 目录选择表单;关闭 location 后保留配置、停止扫描/监听并从会话与搜索结果排除,重新开启即增量扫回;纯路径管理不做内容校验。**Memory locations 页与 Locations 同版式**(2026-09-21 记忆可见层二期):标题 "Memory locations" + 一句说明 + 右侧 Add location + 页级 `…` 里的 Restore defaults;按 AgentId 声明序分组,一行一个记忆来源——各家默认的(Claude 的 auto-memory 树与 `~/.claude/CLAUDE.md`、Codex 的 memories 目录、逐线程库、`~/.codex/AGENTS.md` 与 `rules/`、Gemini 的 `~/.gemini/GEMINI.md`、ZCode 的记忆树)、项目根模式(`<project>/CLAUDE.md`、`<project>/.cursor/rules` 一类,原样显示占位符)与用户加的自定义目录/文件;路径为主信息、文件数(或 "Not found")为 muted 副信息,最右逐来源开关;`…` 菜单:默认来源只有 Show in Finder(项目模式连这个也没有),自定义来源多 Edit / Remove。添加/编辑与 Session locations 是同一个表单(`open_path_form`),差别是字段叫 "Folder or file"、选择器也收文件。改动不换 roster,只补一轮增量扫描,记忆流随之更新。Remote hosts 页沿用 Locations 的版式:标题 + 说明,右侧低强调的 Sync now / Add host;host 列表为单张 popover 底圆角卡,一行一台(名字为主信息、同步状态为 muted 副信息,失败用 danger),`…` 菜单集中 Sync now / Remove,最右为开关;添加走与 location 同材质的单字段表单弹窗,SSH 前提说明放在字段下方。列表与详情页的远程会话以 `@host` 徽章标识:列表行为 primary 淡底填充胶囊(与 muted 项目胶囊区分),详情页与 model/source 同排用 primary 描边。Connect 页沿用 Data 页的版式,**只放状态与动作,不放文档**(用户 2026-09-08 三轮定稿:平级双卡带代码块、嵌套同卡、缩进从属卡都试过,根源是设置窗里塞了 README 内容,怎么排都像教程):标题 + 一句说明(不点名 MCP、不写 read-only 声明);「MCP server」卡 84px 一行显示 wake-mcp 名称与 mono 字体的 `~/…` 路径,右侧 Copy path,不放"Ready"状态行,只在找不到二进制时给一行 danger 文案;「MCP clients」卡三行(Claude Code / Codex / Cursor),17px 品牌图标领行、客户端名为主信息、用法提示为 muted 副信息、右侧是 ghost 的 Show/Hide 切换(chevron 图标 + 文案,muted 前景,用户 2026-09-08 追加)加 Copy command / Copy config;代码块**默认收起**,展开后出现在该行下方、左缘对齐到文字轴(行内边距 16 + 图标 17 + 间距 12),secondary 填充 + 主题圆角的 mono 逐行渲染,Settings 重开即复位。0.6.x 起页面是**四个区块**(用户 2026-09-11 定稿):MCP server / MCP clients / Command line / Skill——MCP server / Command line / Skill 各一张 84px 信息卡、MCP clients 仍是三行客户端列表(wake-mcp、wake-cli 是二进制名与 mono 路径 + Copy path;wake-cli 那张在 Copy path **左侧**多一个 Copy command,复制「把它放进 PATH」的那行命令——右侧留给两张卡同名的 Copy path,纵向才对得齐;deb/tar 已装进 `…/bin` 或 Windows 上没有可粘命令时这个按钮不出现;Skill 是 `npx skills add …` + Copy command),区块标题为「Agents」时看不出这块特指 MCP,故改名 MCP clients 与上方 MCP server 成对。**说明性 caption 一律不放**——那正是"设置窗里塞 README"的复发形态;Setup guide 链接改挂在区块标题右端,规则是**每个面的第一个区块挂自己的文档**:MCP server → docs/mcp.md,Command line → docs/cli.md(MCP clients 与 Skill 分属这两个面的第二块,不重复挂)。四块之后整页**超过一屏、需要滚动**——2026-09-08 那条"一屏放下"的约束随第三、四个区块作废,滚动容器本来就在(`flex_1().min_h_0().overflow_y_scroll()`),卡片记得 `flex_shrink_0` 否则会被压扁。复制反馈是按钮原地变 "Copied"(check 图标)1.6s 后复原,**不弹通知**——gpui-component 的 toast 在窗口失活或被悬停时暂停自动关闭,在 Settings 从属窗里经常就挂着不走(用户 2026-09-08 反馈),且主界面的 Copy Session ID / Copy code 本来就不弹;页面只展示不代写别家配置。+- 工具条内的**状态行"常态沉默"**:仅刷新中或监听不可用时出现在按钮行上方;文案须可 truncate,窄侧栏放不下长句(故为 "Live updates off" 而非带操作建议的整句)。刷新中行首是与页头 Refresh 按钮 loading 态同一个 Spinner(12px、muted 色),文字下方 8px 处一条 3px 进度条(`Progress`,primary 色、轨道同色 20%;会话扫描按 done/total 定值,总数未知 / 记忆同步 / 远程同步走不定值滑动;2026-09-22 用户要的),出错时行首回到静态 refresh-cw 图标。+- 手动 Refresh 始终后台运行;进度复用侧栏状态行,完成后发通知("Sessions refreshed" / "Memory refreshed"),不用模态框阻断浏览、搜索或阅读。- 不把项目包装成卡片,不堆叠分支、时间或重复图标。项目行不加彩色标识——同一图标重复十几次不传递信息。### 会话流@@ -223,11 +223,11 @@ emoji 不再承担界面或正文结构图标职责。### Memory-侧栏底部工具条的 Memory 钮(brain 图标)进入;与 Insights 同为**整页目的地**——打开时替换会话流与阅读区,工具条的 Sessions 钮落回 All Sessions。页头右端有 Refresh。只读:agent 自己写下的记忆文档(Claude Code 的 auto-memory、Codex 的 memories 与逐会话摘要、ZCode 的项目记忆),列、搜(MCP / CLI)、读,不编辑、不同步、不删除,要改一个 Reveal 就到。+侧栏底部工具条的 Memory 钮(brain 图标)进入;与 Insights 同为**整页目的地**——打开时替换会话流与阅读区,工具条的 Sessions 钮落回 All Sessions。页头右端有 Refresh——**只同步记忆**(读 Settings → Memory locations 的当下配置,不重扫会话、不碰远程、不弹进度框;用户 2026-09-22 定"memory 的只刷 memory、session 的只刷 session"),按钮进行中转圈禁用。只读:agent 自己写下的记忆文档(Claude Code 的 auto-memory、Codex 的 memories 与逐会话摘要、ZCode 的项目记忆),列、搜(MCP / CLI)、读,不编辑、不同步、不删除,要改一个 Reveal 就到。-- **侧栏在这一页换成记忆的导航**(2026-09-21 用户定,"侧栏还是会话的内容"很怪):All Sessions / Starred 与 Agents / Projects 两块让位给 All Memory 一行(file-text 图标)+ Agents / Projects 两组(曾在顶上加过一行 brain + "Memory" 的模式标题,底部工具条能点亮当前页之后用户定没必要,已去掉),行与组头是会话侧栏的同一套组件、同一个单选模型(agent 与项目互斥,再点一次回到全部),计数按**记忆文件数**而不是会话数;Projects 按最近更新排,没归属的 "Unknown project" 垫底;折叠状态与会话侧栏共用。底部工具条与搜索框原样保留,进页时筛选从全部开始。-- **版式与会话页同形**(2026-09-21 第七轮:整页宽页头压着两栏"看着很奇怪"):左列 = 会话流同宽(336px、`colors.list` 底)+ 列内 `library_header`(88px:标题 = 当前侧栏筛选——All Memory / agent 名 / 项目名,Label 副行 "N memory files",右端 Refresh)+ 记忆流;右侧 = 阅读面。-- **记忆流按项目分组、平铺**(2026-09-21 第九至十三轮:先做成可折叠的树——chevron、收起、子行缩进、竖线——用户逐项否掉,最后定"不折叠、不缩进,组头用会话流时间分割线的样式"):组头与会话流的 Today / Yesterday 分割线同款——Label 11 medium muted 的项目名(User-level / Unknown project)+ 右侧低对比度 hairline,32px 高,不放图标与计数;文档行是标准行盒,不缩进。组顺序 = 项目按路径 → Unknown project → User-level。行盒模型同会话行:高亮面 `SPACE_SM` 外距,内缩 = ListItem 自带的 12/4 加行内容的 4/8(没有 ListItem,两层加成一层写 16/12),文档行两行(Body 14 medium 标题一行,按显示宽度截断、Hover 全名;Label 11 第二行 = 品牌图 15px(线程级再加 "session memory" 徽章,远程加 `@host`;项目名由节点说明,子行不重复挂)+ 弹性空隙 + 右对齐更新时间,Hover 精确时间),选中 `list_active`、悬停 `list_hover`。列表 gpui::list 虚拟化,刷新保滚动位置、换筛选回顶部。Unknown project 只剩目录已不在磁盘上的那几份:Claude 项目目录没有会话时按目录名在本机文件系统上反推路径(`decode_project_dir`,只对默认根)。+- **侧栏在这一页换成记忆的导航**(2026-09-21 用户定,"侧栏还是会话的内容"很怪):All Sessions / Starred 与 Agents / Projects 两块让位给 All Memory 一行(file-text 图标)+ User memory 一行(user 图标,会话侧栏 Starred 的同位:只列用户记忆,计数为零不挂徽章,再点一次回到全部;用户 2026-09-22 定"应该在 All Memory 下加一个 User memory 的菜单")+ Agents / Projects 两组(曾在顶上加过一行 brain + "Memory" 的模式标题,底部工具条能点亮当前页之后用户定没必要,已去掉),行与组头是会话侧栏的同一套组件、同一个单选模型(agent 与项目互斥,再点一次回到全部),计数按**记忆文件数**而不是会话数;Projects 按最近更新排,没归属的 "Unknown project" 垫底,**项目行只算项目记忆**(用户记忆对每个项目都成立,曾把它加进每个项目行,用户 2026-09-22 定拿掉、归到 User memory 一行;Agents 行仍含用户记忆);折叠状态与会话侧栏共用。底部工具条与搜索框原样保留,进页时筛选从全部开始。+- **版式与会话页同形**(2026-09-21 第七轮:整页宽页头压着两栏"看着很奇怪"):左列 = 会话流同宽(336px、`colors.list` 底)+ 列内 `library_header`(88px:标题 = 当前侧栏筛选——All Memory / User memory / agent 名 / 项目名,Label 副行 "N memory files",右端 Refresh)+ 记忆流;右侧 = 阅读面。+- **记忆流与会话流同一套分组**(2026-09-21 第九至十四轮:先做成按项目的可折叠树——chevron、收起、子行缩进、竖线——用户逐项否掉,改成平铺的项目组头;行上挂了项目徽章之后组头也多余了,最终定"和会话列表一样"):User memory 单独一组置顶(会话列表 Pinned 的同位——它对每个项目都成立,混进时间线"有点奇怪",用户同日定;侧栏选了 User memory 行时整页都是它,不画这个组头、照时间分),其余按更新时间倒序,Today / Yesterday / Earlier this week / 月份的分割线(`session_group_label` 同一函数),Label 11 medium muted + 右侧低对比度 hairline,32px 高;文档行是标准行盒,不缩进,项目由行内徽章说明。行盒模型同会话行:高亮面 `SPACE_SM` 外距,内缩 = ListItem 自带的 12/4 加行内容的 4/8(没有 ListItem,两层加成一层写 16/12),文档行两行(Body 14 medium 标题一行,按显示宽度截断、Hover 全名;Label 11 第二行 = 品牌图 15px + 项目徽章(会话行同款 muted 胶囊,文案:项目名 / User memory / Unknown project(层级词沿用 Claude Code 文档的 User memory / Project memory,用户 2026-09-21 定)——曾因组头已说明而不挂,用户 2026-09-21 定要与会话行一致)+ 线程级的 "session memory"、远程的 `@host`(指令文件不另挂徽章——文件名已说明身份,"instructions" 徽章试过、用户定拿掉)+ 弹性空隙 + 右对齐更新时间,Hover 精确时间),选中 `list_active`、悬停 `list_hover`。列表 gpui::list 虚拟化,刷新保滚动位置、换筛选回顶部。Unknown project 只剩目录已不在磁盘上的那几份:Claude 项目目录没有会话时按目录名在本机文件系统上反推路径(`decode_project_dir`,只对默认根)。- 阅读面头部是详情头部同款:44px 上下文行(品牌图 15 + agent 名 + 可点击的归属徽章(在文件管理器中打开项目),右端 Reveal / Copy path 两个 16px ghost 图标钮)→ 22px semibold 标题(可换行,最小 44px)→ Label 11 muted 两行元信息(file-text 图标 + `~` 折叠的文件路径;calendar 图标 + "Updated …",Hover 精确时间),`background` 底、hairline 收底、兼窗口拖拽区;正文 `popover` 底、720px 阅读宽居中、24px 阅读轴、上留 16 下留 24(与消息流首末条同数),与消息正文同一套 Markdown 渲染(相对链接按记忆文件所在目录解析)。- 列表非空时恒有选中项(重载落到第一份),正文后台读磁盘、读到前居中 Spinner,文件被 agent 改过重读。空库时左列只有页头,右侧 `empty_state_card`("No memory files yet" + 一句说明它们从哪来)。diff --git a/PRODUCT.md b/PRODUCT.mdindex dd6d439..3e519bc 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`;记忆的项目归属按它挂的会话在读时解析,永远跟着索引走。不编辑、不同步、不删除——写别家数据破铁律,要改一个 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 首扫就退让)、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/crates/wake-core/src/adapters/claude.rs b/crates/wake-core/src/adapters/claude.rsindex eca1321..a4eaafb 100644--- a/crates/wake-core/src/adapters/claude.rs+++ b/crates/wake-core/src/adapters/claude.rs@@ -27,11 +27,14 @@ const KNOWN_SKIP_TYPES: &[&str] = &[pub struct ClaudeAdapter {root: PathBuf,+ /// `~/.claude`(全局 CLAUDE.md 的所在);直接选中 projects 目录的自定义根 / 远程+ /// 镜像没有 home——不越界摸父目录(不变量 8⑨)+ home: Option<PathBuf>,/// 默认根(本机自己的 ~/.claude):项目目录名才能在本机文件系统上反推——目录名/// 指的是写下会话的那台机器上的路径,自定义根(别处拷来的、远程镜像)反推不得local: bool,/// auto-memory 文档,按目录指纹缓存(每轮扫描都会列,指纹没变不重读)- memories: MtimeCache<Vec<MemoryDoc>>,+ memories: super::MemoryCache,/// 目录名 → 反推出的项目路径,进程内记住(含反推失败):反推要从 `/` 逐层/// read_dir + stat,答案又几乎不变,每轮扫描重走一遍是白费;目录后来才出现的/// 极少数情况重启即可@@ -40,18 +43,35 @@ pub struct ClaudeAdapter {impl ClaudeAdapter {pub fn new() -> Self {- let root = super::home_dir()- .unwrap_or_default()- .join(".claude")- .join("projects");+ let home = super::home_dir().unwrap_or_default().join(".claude");Self {- root,+ root: home.join("projects"),+ home: Some(home),local: true,- memories: MtimeCache::new(),+ memories: super::MemoryCache::new(),decoded: std::sync::Mutex::new(HashMap::new()),}}+ /// auto-memory 树 `projects/<dir>/memory/*.md` 展开成读取单元:每个项目目录的记忆+ /// 挂到该目录最新的会话上(见 newest_session_key);目录里没有会话(Claude 按+ /// cleanupPeriodDays 清过)就从目录名在本机磁盘上反推项目路径(decode_project_dir,+ /// 只对默认根),反推不出才落 Unknown project。projects/ 不在 = 没有记忆;列不出来+ ///(权限、I/O、fd 耗尽)是"不知道",报 Err 让 scanner 冻结这一来源——折成空会把+ /// 库里 Claude 的记忆整组删光(2026-09-21 review)+ fn tree_units(&self, source: &MemorySource) -> Result<Vec<super::MemoryUnit>> {+ super::project_tree_units(source, |project| {+ let session_key = newest_session_key(&project.path()).unwrap_or_default();+ let project_path = if session_key.is_empty() && self.local {+ self.project_path_of_dir(&project.file_name().to_string_lossy())+ .unwrap_or_default()+ } else {+ String::new()+ };+ (session_key, project_path)+ })+ }+/// `decode_project_dir` 的记忆版fn project_path_of_dir(&self, name: &str) -> Option<String> {let mut cache = self.decoded.lock().unwrap();@@ -702,59 +722,51 @@ impl AgentAdapter for ClaudeAdapter {Some(self.session_paths(meta))}- fn list_memories(&self) -> Result<Vec<MemoryDoc>> {- // auto-memory:projects/<dir>/memory/*.md(MEMORY.md 索引 + 逐条主题文件)。- // 每个项目目录的记忆挂到该目录最新的会话上(见 newest_session_key);目录里- // 没有会话(Claude 按 cleanupPeriodDays 清过)就从目录名在本机磁盘上反推- // 项目路径(decode_project_dir,只对默认根),反推不出才落 Unknown project- // projects/ 不在 = 没有记忆;列不出来(权限、I/O、fd 耗尽)是"不知道",报 Err- // 让 scanner 冻结这一组——折成空会把库里 Claude 的记忆整组删光(2026-09-21 review)- let projects = match fs::read_dir(&self.root) {- Ok(projects) => projects,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),- Err(e) => return Err(anyhow::Error::new(e).context(self.root.display().to_string())),- };- let mut dirs: Vec<super::MemoryDir> = projects- .flatten()- .filter_map(|project| {- let dir = project.path().join("memory");- if !dir.is_dir() {- return None;- }- let session_key = newest_session_key(&project.path()).unwrap_or_default();- let project_path = if session_key.is_empty() && self.local {- self.project_path_of_dir(&project.file_name().to_string_lossy())- .unwrap_or_default()- } else {- String::new()- };- Some(super::MemoryDir {- scope: MemoryScope::Project,- session_key,- project_path,- dir,- })- })- .collect();- dirs.sort_by(|a, b| a.dir.cmp(&b.dir));- super::cached_memory_docs(&self.memories, AgentId::ClaudeCode, &dirs)+ fn memory_sources(&self) -> Vec<MemorySource> {+ // auto-memory 树(agent 记的、按项目)+ 全局 CLAUDE.md(用户写的指令,对每个+ // 项目都成立);项目根下的 CLAUDE.md 由 project_instruction_sources 给+ let mut v = vec![MemorySource {+ agent: AgentId::ClaudeCode,+ kind: MemorySourceKind::ProjectTree,+ path: self.root.clone(),+ }];+ if let Some(home) = &self.home {+ v.push(MemorySource {+ agent: AgentId::ClaudeCode,+ kind: MemorySourceKind::File,+ path: home.join("CLAUDE.md"),+ });+ }+ v}- fn memory_roots(&self) -> Vec<PathBuf> {- vec![self.root.clone()]+ fn list_memories(+ &self,+ sources: &[MemorySource],+ projects: &[PathBuf],+ ) -> Result<Vec<MemoryDoc>> {+ super::memory_docs_with_tree(+ &self.memories,+ AgentId::ClaudeCode,+ sources,+ projects,+ |tree| self.tree_units(tree),+ )}fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {- // 选中 `~/.claude` 形态(含 projects/)或直接选中 projects 目录都认- let root = if dir.join("projects").is_dir() {- dir.join("projects")+ // 选中 `~/.claude` 形态(含 projects/)或直接选中 projects 目录都认;只有前者+ // 有 home(全局 CLAUDE.md 的所在),裸 projects 目录不摸父目录+ let (root, home) = if dir.join("projects").is_dir() {+ (dir.join("projects"), Some(dir))} else {- dir+ (dir, None)};Box::new(Self {root,+ home,local: false,- memories: MtimeCache::new(),+ memories: super::MemoryCache::new(),decoded: std::sync::Mutex::new(HashMap::new()),})}diff --git a/crates/wake-core/src/adapters/codex.rs b/crates/wake-core/src/adapters/codex.rsindex ea2667a..a67b9d3 100644--- a/crates/wake-core/src/adapters/codex.rs+++ b/crates/wake-core/src/adapters/codex.rs@@ -24,7 +24,7 @@ pub struct CodexAdapter {home: Option<PathBuf>,/// memories/*.md 按目录指纹缓存、memories_1.sqlite 的线程记忆按库戳缓存/// (每轮扫描都会列,没变不重读)- memories: MtimeCache<Vec<MemoryDoc>>,+ memories: super::MemoryCache,thread_memories: MtimeCache<Vec<MemoryDoc>>,}@@ -44,7 +44,7 @@ impl CodexAdapter {scan_archived: true,links_cache: MtimeCache::new(),home: Some(root),- memories: MtimeCache::new(),+ memories: super::MemoryCache::new(),thread_memories: MtimeCache::new(),}}@@ -991,13 +991,18 @@ fn build_meta(r: &SessionFileRef, p: &CodexParse, archived_dir: &Path) -> Sessio/// 不记——把一次瞬时失败缓存成"没有"会让库里的线程记忆整组被删,而戳不动就再也/// 不读(Codex 不在跑时文件 mtime 是静止的)。schema 按 2026-09 的库推断,本机零/// 行、未经真数据验证-fn thread_memories(db: &Path, cache: &MtimeCache<Vec<MemoryDoc>>) -> Option<Vec<MemoryDoc>> {- cache.get_or_try_build(super::sqlite_ro::db_cache_stamp(db), || {- read_thread_memories(db)+fn thread_memories(+ source: &MemorySource,+ cache: &MtimeCache<Vec<MemoryDoc>>,+) -> Option<Vec<MemoryDoc>> {+ cache.get_or_try_build(super::sqlite_ro::db_cache_stamp(&source.path), || {+ read_thread_memories(&source.path, &source.id())})}-fn read_thread_memories(db: &Path) -> Option<Vec<MemoryDoc>> {+/// `source` 是来源 id(memories.source 列),由调用方从 MemorySource 取——别在这里按路径+/// 重新拼一遍(id 规则一变这里就静默对不上,2026-09-22 /simplify)+fn read_thread_memories(db: &Path, source: &str) -> Option<Vec<MemoryDoc>> {if !db.is_file() {return Some(Vec::new());}@@ -1073,6 +1078,7 @@ fn read_thread_memories(db: &Path) -> Option<Vec<MemoryDoc>> {// 秒还是毫秒未验证,交 epoch_ms 统一裁定updated_at: epoch_ms(generated),size_bytes: body.len() as i64,+ source: source.to_string(),path,body,});@@ -1177,6 +1183,11 @@ impl AgentAdapter for CodexAdapter {Some(r)}+ fn parent_links_global(&self) -> bool {+ // thread_spawn_edges 是 home 里的一张总表,parent 的胜出文件可能归同家另一个 location+ true+ }+fn manages_parent_links(&self) -> bool {true}@@ -1252,35 +1263,44 @@ impl AgentAdapter for CodexAdapter {Some(self.session_paths(meta))}- fn list_memories(&self) -> Result<Vec<MemoryDoc>> {- // memories/ 与 memories_1.sqlite 是 CODEX_HOME 直属;只选了 sessions 目录或- // 裸 rollout 拷贝的自定义根没有 home,那里就没有记忆(不摸父目录)+ fn memory_sources(&self) -> Vec<MemorySource> {+ // memories/ 与 memories_1.sqlite(agent 记的)、AGENTS.md 与 rules/*.rules(用户+ // 写的指令)都是 CODEX_HOME 直属;只选了 sessions 目录或裸 rollout 拷贝的自定义+ // 根没有 home,那里就没有记忆(不摸父目录)。项目根下的 AGENTS.md 由+ // project_instruction_sources 给let Some(home) = &self.home else {- return Ok(Vec::new());+ return Vec::new();};- let mut out = super::cached_memory_docs(- &self.memories,- AgentId::Codex,- &[super::MemoryDir {- scope: MemoryScope::User,- session_key: String::new(),- project_path: String::new(),- dir: home.join("memories"),- }],- )?;- let db = home.join("memories_1.sqlite");- let threads = thread_memories(&db, &self.thread_memories)- .ok_or_else(|| anyhow::anyhow!("{} exists but could not be read", db.display()))?;- out.extend(threads);- Ok(out)+ let source = |kind, rel: &str| MemorySource {+ agent: AgentId::Codex,+ kind,+ path: home.join(rel),+ };+ vec![+ source(MemorySourceKind::Dir { ext: "md" }, "memories"),+ source(MemorySourceKind::ThreadDb, "memories_1.sqlite"),+ source(MemorySourceKind::File, "AGENTS.md"),+ source(MemorySourceKind::Dir { ext: "rules" }, "rules"),+ ]}- fn memory_roots(&self) -> Vec<PathBuf> {- // 线程记忆的虚拟路径 `<db>#<thread_id>` 以库路径开头,按前缀就能认- self.home- .as_ref()- .map(|home| vec![home.join("memories"), home.join("memories_1.sqlite")])- .unwrap_or_default()+ fn list_memories(+ &self,+ sources: &[MemorySource],+ projects: &[PathBuf],+ ) -> Result<Vec<MemoryDoc>> {+ let mut out =+ super::generic_memory_docs(&self.memories, AgentId::Codex, sources, projects)?;+ if let Some(db) = sources+ .iter()+ .find(|s| s.kind == MemorySourceKind::ThreadDb)+ {+ let threads = thread_memories(db, &self.thread_memories).ok_or_else(|| {+ anyhow::anyhow!("{} exists but could not be read", db.path.display())+ })?;+ out.extend(threads);+ }+ Ok(out)}fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {@@ -1309,7 +1329,7 @@ impl AgentAdapter for CodexAdapter {scan_archived: true,links_cache: MtimeCache::new(),home,- memories: MtimeCache::new(),+ memories: super::MemoryCache::new(),thread_memories: MtimeCache::new(),})}@@ -1334,7 +1354,7 @@ impl AgentAdapter for CodexAdapter {scan_archived: self.scan_archived && !roots.contains(&self.archived_dir),links_cache: MtimeCache::new(),home: self.home.clone(),- memories: MtimeCache::new(),+ memories: super::MemoryCache::new(),thread_memories: MtimeCache::new(),}))}diff --git a/crates/wake-core/src/adapters/copilot.rs b/crates/wake-core/src/adapters/copilot.rsindex 79ecc18..f1101ee 100644--- a/crates/wake-core/src/adapters/copilot.rs+++ b/crates/wake-core/src/adapters/copilot.rs@@ -16,6 +16,8 @@ pub struct CopilotAdapter {/// rows() 的全表聚合较贵,按 db mtime 缓存一轮扫描内的重复调用/// (list_session_files 与 quick_meta 各调一次)rows_cache: Mutex<Option<(i64, Vec<CopilotRow>)>>,+ /// 指令文件(项目根下的)与自定义来源按指纹缓存,每轮扫描只 stat+ memories: super::MemoryCache,}impl CopilotAdapter {@@ -26,6 +28,7 @@ impl CopilotAdapter {.join(".copilot").join("session-store.db"),rows_cache: Mutex::new(None),+ memories: super::MemoryCache::new(),}}@@ -243,6 +246,15 @@ impl AgentAdapter for CopilotAdapter {})}+ fn list_memories(+ &self,+ sources: &[MemorySource],+ projects: &[PathBuf],+ ) -> Result<Vec<MemoryDoc>> {+ // 只有项目指令文件与用户加的自定义来源;trait 默认实现没处放缓存、每轮都重读+ super::generic_memory_docs(&self.memories, AgentId::Copilot, sources, projects)+ }+fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// 手输/预填的就是库文件路径时直接认,不再往下拼(Codex review)let db = if dir.is_file() {@@ -253,6 +265,7 @@ impl AgentAdapter for CopilotAdapter {Box::new(Self {db,rows_cache: Mutex::new(None),+ memories: super::MemoryCache::new(),})}diff --git a/crates/wake-core/src/adapters/cursor.rs b/crates/wake-core/src/adapters/cursor.rsindex 1d1079d..46101d8 100644--- a/crates/wake-core/src/adapters/cursor.rs+++ b/crates/wake-core/src/adapters/cursor.rs@@ -20,6 +20,8 @@ use std::path::{Path, PathBuf};pub struct CursorAdapter {root: PathBuf,metadata_db: Option<PathBuf>,+ /// 指令文件(项目根下的 .cursor/rules、.cursorrules)与自定义来源按指纹缓存,每轮扫描只 stat+ memories: super::MemoryCache,}impl CursorAdapter {@@ -30,6 +32,7 @@ impl CursorAdapter {.join(".cursor").join("projects"),metadata_db: Some(cursor_ide::default_db_path()),+ memories: super::MemoryCache::new(),}}@@ -559,6 +562,15 @@ impl AgentAdapter for CursorAdapter {Some(self.session_paths(meta))}+ fn list_memories(+ &self,+ sources: &[MemorySource],+ projects: &[PathBuf],+ ) -> Result<Vec<MemoryDoc>> {+ // 只有项目指令文件与用户加的自定义来源;trait 默认实现没处放缓存、每轮都重读+ super::generic_memory_docs(&self.memories, AgentId::Cursor, sources, projects)+ }+fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// 选中 `~/.cursor` 形态(含 projects/)或直接选中 projects 目录都认let root = if dir.join("projects").is_dir() {@@ -570,6 +582,7 @@ impl AgentAdapter for CursorAdapter {root,// 自定义目录也用于远程缓存,不能混用本机 IDE 元数据。metadata_db: None,+ memories: super::MemoryCache::new(),})}@@ -617,6 +630,7 @@ impl AgentAdapter for CursorAdapter {Some(Box::new(Self {root: PathBuf::new(),metadata_db: None,+ memories: super::MemoryCache::new(),}))} else {None@@ -658,6 +672,7 @@ mod tests {let adapter = CursorAdapter {root,metadata_db: Some(db),+ memories: crate::adapters::MemoryCache::new(),};let r = adapter.file_ref(&file).unwrap();(dir, adapter, r)@@ -860,6 +875,7 @@ mod tests {let adapters: Vec<Box<dyn AgentAdapter>> = vec![Box::new(CursorAdapter {root,metadata_db: Some(metadata_db),+ memories: crate::adapters::MemoryCache::new(),})];let events = Events::default();run_scan(&adapters, &store, &events, false).unwrap();diff --git a/crates/wake-core/src/adapters/cursor_ide.rs b/crates/wake-core/src/adapters/cursor_ide.rsindex 6511206..be2b55b 100644--- a/crates/wake-core/src/adapters/cursor_ide.rs+++ b/crates/wake-core/src/adapters/cursor_ide.rs@@ -336,7 +336,24 @@ const BUBBLE_ASSISTANT: i64 = 2;/// `composerHeaders.isSubagent=1` 的行带 `subagentInfo.parentComposerId`。/// 这张表只覆盖较新的会话,老会话查不到父子关系——不是错误,照常列为顶层。fn parent_links_from(db: &std::path::Path) -> Option<Vec<(String, String)>> {+ // 没装 Cursor(库不在)、老版本没有 composerHeaders 表 = 确定没有关系;库在、表在但读+ // 不出才是"不知道"——原先三种都给 None,没装 Cursor 的机器每轮都把 Cursor 的父子+ // 关系冻住、子代理会话永远进不了根列表(2026-09-22 review)+ if !db.is_file() {+ return Some(Vec::new());+ }let ro = open_sqlite_ro(db, "cursor-ide")?;+ let has_table: bool = ro+ .conn+ .query_row(+ "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'composerHeaders')",+ [],+ |r| r.get(0),+ )+ .ok()?;+ if !has_table {+ return Some(Vec::new());+ }let mut stmt = ro.conn.prepare(diff --git a/crates/wake-core/src/adapters/gemini.rs b/crates/wake-core/src/adapters/gemini.rsindex b3bb780..60ebc07 100644--- a/crates/wake-core/src/adapters/gemini.rs+++ b/crates/wake-core/src/adapters/gemini.rs@@ -15,6 +15,10 @@ use std::path::{Path, PathBuf};pub struct GeminiAdapter {root: PathBuf,projects_json: PathBuf,+ /// `~/.gemini`(全局 GEMINI.md 的所在);直接选中 tmp 目录的自定义根 / 远程镜像没有+ home: Option<PathBuf>,+ /// 指令文件(全局 GEMINI.md + 项目根的 GEMINI.md)按指纹缓存+ memories: super::MemoryCache,/// slug → 项目路径映射,按 projects.json mtime 缓存(全量刷新时逐会话调用)slug_cache: std::sync::Mutex<Option<(i64, HashMap<String, String>)>>,}@@ -25,6 +29,8 @@ impl GeminiAdapter {Self {root: home.join("tmp"),projects_json: home.join("projects.json"),+ home: Some(home),+ memories: super::MemoryCache::new(),slug_cache: std::sync::Mutex::new(None),}}@@ -279,6 +285,7 @@ impl AgentAdapter for GeminiAdapter {fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// `~/.gemini` 形态(含 tmp/)则 projects.json 在其顶层;直接选中 tmp// 形态则上一层找。侧档必须相对 dir 派生,落回默认家就会拿错 cwd 映射+ let home = dir.join("tmp").is_dir().then(|| dir.clone());let (root, projects_json) = if dir.join("tmp").is_dir() {(dir.join("tmp"), dir.join("projects.json"))} else {@@ -291,6 +298,8 @@ impl AgentAdapter for GeminiAdapter {Box::new(Self {root,projects_json,+ home,+ memories: super::MemoryCache::new(),slug_cache: std::sync::Mutex::new(None),})}@@ -298,4 +307,28 @@ impl AgentAdapter for GeminiAdapter {fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}++ fn memory_sources(&self) -> Vec<MemorySource> {+ // Gemini 没有 agent 自己记的记忆目录;`save_memory` 工具追加的 "Gemini Added+ // Memories" 段就在全局 GEMINI.md 里,整个文件按用户写的指令列。项目根下的+ // GEMINI.md 由 project_instruction_sources 给+ self.home+ .as_ref()+ .map(|home| {+ vec![MemorySource {+ agent: AgentId::Gemini,+ kind: MemorySourceKind::File,+ path: home.join("GEMINI.md"),+ }]+ })+ .unwrap_or_default()+ }++ fn list_memories(+ &self,+ sources: &[MemorySource],+ projects: &[PathBuf],+ ) -> Result<Vec<MemoryDoc>> {+ super::generic_memory_docs(&self.memories, AgentId::Gemini, sources, projects)+ }}diff --git a/crates/wake-core/src/adapters/hermes.rs b/crates/wake-core/src/adapters/hermes.rsindex f48c753..edb6826 100644--- a/crates/wake-core/src/adapters/hermes.rs+++ b/crates/wake-core/src/adapters/hermes.rs@@ -507,6 +507,12 @@ impl AgentAdapter for HermesAdapter {fn parent_links(&self) -> Option<Vec<(String, String)>> {let mut links = Vec::new();for db in &self.dbs {+ // 库文件不在 = 确定没有关系(远程镜像每台 host 都挂 .hermes,多数没装);库在但+ // 读不出才是"不知道"——原先一律 None,没装 Hermes 的机器每轮都把本地真实的+ // /branch 关系冻住(2026-09-22 review)+ if !db.path.is_file() {+ continue;+ }let rows = Self::rows(db)?;let ids: std::collections::HashSet<&str> = rows.iter().map(|r| r.id.as_str()).collect();links.extend(rows.iter().filter_map(|r| {diff --git a/crates/wake-core/src/adapters/kiro.rs b/crates/wake-core/src/adapters/kiro.rsindex 55ddd43..8bfe859 100644--- a/crates/wake-core/src/adapters/kiro.rs+++ b/crates/wake-core/src/adapters/kiro.rs@@ -12,6 +12,8 @@ use std::path::{Path, PathBuf};/// data:{content:[{kind:text,data}],meta:{timestamp:unix秒}}};.history 忽略。pub struct KiroAdapter {root: PathBuf,+ /// 指令文件(项目根下的)与自定义来源按指纹缓存,每轮扫描只 stat+ memories: super::MemoryCache,}impl KiroAdapter {@@ -22,6 +24,7 @@ impl KiroAdapter {.join(".kiro").join("sessions").join("cli"),+ memories: super::MemoryCache::new(),}}}@@ -191,6 +194,15 @@ impl AgentAdapter for KiroAdapter {})}+ fn list_memories(+ &self,+ sources: &[MemorySource],+ projects: &[PathBuf],+ ) -> Result<Vec<MemoryDoc>> {+ // 只有项目指令文件与用户加的自定义来源;trait 默认实现没处放缓存、每轮都重读+ super::generic_memory_docs(&self.memories, AgentId::Kiro, sources, projects)+ }+fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// `~/.kiro`/`~/.kiro/sessions`/`~/.kiro/sessions/cli` 三层都认let root = if dir.join("sessions").join("cli").is_dir() {@@ -200,7 +212,10 @@ impl AgentAdapter for KiroAdapter {} else {dir};- Box::new(Self { root })+ Box::new(Self {+ root,+ memories: super::MemoryCache::new(),+ })}fn data_roots(&self) -> Vec<PathBuf> {diff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rsindex 3e037a6..e4c7851 100644--- a/crates/wake-core/src/adapters/mod.rs+++ b/crates/wake-core/src/adapters/mod.rs@@ -110,21 +110,32 @@ pub trait AgentAdapter: Send + Sync {fn cleanup_paths(&self, _meta: &SessionMeta) -> Option<Vec<String>> {None}- /// 本家 agent 自己写下的记忆文档(Claude Code 的 auto-memory 目录、Codex 的- /// memories)——Wake 只读:列出、搜索、阅读。默认没有。正文整份带上(记忆是- /// 小 Markdown),但每轮扫描都会调,实现方要**先 stat 后读**:指纹没变就交- /// `MtimeCache`(`cached_memory_docs`),缺根返回 Ok(空);scanner 在每轮扫描- /// 收尾按 (agent, host) 整组替换入库,消失的文件随之出库。项目归属不在这里+ /// 读这些来源的记忆文档——Wake 只读:列出、搜索、阅读。`sources` 已按用户配置+ /// 裁决过(停用的不在、自定义的与项目模式在),`projects` 是已索引的本地项目根,+ /// 给项目模式展开(远程实例传空)。正文整份带上(都是小文件),但每轮扫描都会调,+ /// 实现方要**先 stat 后读**:指纹没变就交 `MtimeCache`(`cached_memory_docs`),+ /// 缺根返回 Ok(空)、读失败报 Err(scanner 只冻结这些来源的行);scanner 在每轮+ /// 扫描收尾按 (agent, host) 整组替换入库,消失的文件随之出库。项目归属不在这里/// 算:填 `session_key` 指向所属会话,读库时按它连 sessions 表解析(见 MemoryDoc)。- /// 远程装饰器必须转发并改写 key / host / session_key- fn list_memories(&self) -> Result<Vec<MemoryDoc>> {- Ok(Vec::new())+ /// 默认实现读通用形态(目录 / 文件 / 项目模式)、不缓存——没有自家记忆的 agent+ /// 只有被用户加了自定义来源或有项目指令文件时才走到。远程装饰器必须转发并改写+ /// key / host / session_key+ fn list_memories(+ &self,+ sources: &[MemorySource],+ projects: &[std::path::PathBuf],+ ) -> Result<Vec<MemoryDoc>> {+ cached_memory_docs(+ &MemoryCache::new(),+ self.agent(),+ &generic_units(sources, projects),+ )}- /// `list_memories` 读的根(目录,或 SQLite 型的库文件;虚拟路径以库路径开头):- /// 同 (agent, host) 有多个实例时,某个实例 `list_memories` 报 Err,scanner 只冻结- /// 它这些根下的行(不删不改),其余实例照常对账——否则一个坏 location 会让默认- /// 实例的记忆永远停在上次(2026-09-21 review)。实现了 list_memories 就要给- fn memory_roots(&self) -> Vec<std::path::PathBuf> {+ /// 本实例默认读记忆的来源(Settings → Memory locations 的行):按实例的根派生,+ /// 不看存不存在。项目模式(`<project>/CLAUDE.md` 一类)不在这里报——那是 agent 级+ /// 的,由 `project_instruction_sources` 给、scanner 只挂到该家第一个本地实例上。+ /// 停用 / 自定义由 scanner 按 store 的配置裁决后经 `list_memories` 交回。默认没有+ fn memory_sources(&self) -> Vec<MemorySource> {Vec::new()}/// 一轮扫描开始前刷新 adapter 的跨会话快照。默认 adapter 没有这类状态。@@ -190,6 +201,14 @@ pub trait AgentAdapter: Send + Sync {fn dedup_rank(&self) -> u8 {0}+ /// `parent_links` 报的边是不是一张**全局**总表(Codex 的 state DB `thread_spawn_edges`+ /// 在 home 里,parent 的胜出文件可能归同家另一个 location)。默认 false = 边车长在+ /// parent 自己的 location 里(Grok),scanner 只认"报边者拥有 parent"的边;true 的才+ /// 走"parent 在库里就接受"的兜底——对 location 级边车放开兜底,备份目录里过期的边车+ /// 会把用户已解除的关系重新挂上(2026-09-22 review)。远程装饰器必须转发+ fn parent_links_global(&self) -> bool {+ false+ }}/// 入库前的自定义根归一化:把用户选中的目录整形成本家"该存哪一层"的形态。@@ -505,68 +524,434 @@ pub(crate) fn units_from_messages(messages: &[TranscriptMessage]) -> Vec<IndexUn.collect()}-/// 一个装 Markdown 记忆文件的目录(Claude 的 projects/<dir>/memory、Codex 的-/// memories):目录里的 `*.md` 各成一份 MemoryDoc,`session_key` 是归属锚点-/// (Claude 给该项目目录里最新的会话,项目路径读库时按它解析;用户级留空)-pub(crate) struct MemoryDir {+/// 记忆的一个读取单元:一个目录直属的 `*.<ext>`,或单个文件,带归属元数据。来源+/// (`MemorySource`)展开成单元——Claude 的记忆树按项目目录各一份,项目模式按每个+/// 已索引项目根各一份(`generic_units`)。`session_key` 是归属锚点(Claude 给该项目+/// 目录里最新的会话,项目路径读库时按它解析;用户级留空)+pub(crate) struct MemoryUnit {pub scope: MemoryScope,+ /// 所属来源的 id(memories.source 列;停用出库、读失败冻结、Settings 计数都按它)+ pub source: String,pub session_key: String,- /// adapter 自己就知道的项目路径(Claude 目录里没会话时从目录名反推);空 = 交给锚点+ /// adapter 自己就知道的项目路径(Claude 目录里没会话时从目录名反推、项目模式的+ /// 项目根);空 = 交给锚点pub project_path: String,- pub dir: std::path::PathBuf,+ pub place: UnitPlace,}-/// 几个记忆目录的文档,经 `MtimeCache` 缓存:每轮只 stat(路径 + mtime + size +-/// 锚点拼成指纹),指纹没变就交上一轮读好的那份,变了才重读正文——`list_memories`-/// 每轮扫描都会调,159 份文件每轮都读是白费(2026-09-17 /simplify)。非 UTF-8 的-/// 文件不是记忆,跳过;别的读取失败(权限、I/O)整轮报 Err、不缓存——scanner 对-/// Err 是跳过该组不动库,下一轮再试;缓存成"少了这份"会让库里那行被删且指纹不变-/// 就再也不读(Codex review 2026-09-17)-pub(crate) fn cached_memory_docs(- cache: &parse_utils::MtimeCache<Vec<MemoryDoc>>,+pub(crate) enum UnitPlace {+ Dir {+ dir: std::path::PathBuf,+ ext: &'static str,+ },+ File(std::path::PathBuf),+ /// 用户加的路径:stat 到是目录就读直属 `*.<ext>`,是文件就读它自己(`Custom` 来源)+ Path {+ path: std::path::PathBuf,+ ext: &'static str,+ },+}++impl UnitPlace {+ pub(crate) fn path(&self) -> &Path {+ match self {+ UnitPlace::Dir { dir, .. } => dir,+ UnitPlace::File(path) | UnitPlace::Path { path, .. } => path,+ }+ }++ /// 项目模式的相对路径落到某个项目根下+ fn under(&self, root: &Path) -> UnitPlace {+ match self {+ UnitPlace::Dir { dir, ext } => UnitPlace::Dir {+ dir: root.join(dir),+ ext,+ },+ UnitPlace::File(path) => UnitPlace::File(root.join(path)),+ UnitPlace::Path { path, ext } => UnitPlace::Path {+ path: root.join(path),+ ext,+ },+ }+ }+}++/// 一个来源按形态给出读取位置;记忆树与线程库是各家自己的形态,这里给 None、由 adapter+/// 自己展开。项目模式给的是相对项目根的位置,展开时再 `under` 到每个项目根+fn unit_place(source: &MemorySource) -> Option<UnitPlace> {+ let path = source.path.clone();+ Some(match source.kind {+ MemorySourceKind::Dir { ext } | MemorySourceKind::ProjectDir { ext } => {+ UnitPlace::Dir { dir: path, ext }+ }+ MemorySourceKind::File | MemorySourceKind::ProjectFile => UnitPlace::File(path),+ MemorySourceKind::Custom => UnitPlace::Path { path, ext: "md" },+ MemorySourceKind::ProjectTree | MemorySourceKind::ThreadDb => return None,+ })+}++/// 通用来源(目录 / 文件 / 自定义 / 项目模式)展开成读取单元+pub(crate) fn generic_units(+ sources: &[MemorySource],+ projects: &[std::path::PathBuf],+) -> Vec<MemoryUnit> {+ // 项目根偶尔就是某家的 home(用户在 ~/.codex 里跑过一次 codex):`<project>/AGENTS.md`+ // 会展开成全局那份 `~/.codex/AGENTS.md`——同一文件、同一 key,后写的项目级那份会把+ // 用户级那份顶成 ".codex" 项目的。具体来源(全局文件 / 目录)优先,项目模式展开到+ // 已被它们覆盖的路径就跳过(2026-09-21 用户在本机数据上发现)+ let concrete: std::collections::HashSet<&Path> = sources+ .iter()+ .filter(|s| !s.is_pattern())+ .map(|s| s.path.as_path())+ .collect();+ let mut units = Vec::new();+ for s in sources {+ let Some(place) = unit_place(s) else {+ continue;+ };+ let source = s.id();+ let unit = |project_path: String, place: UnitPlace| MemoryUnit {+ scope: s.scope(),+ source: source.clone(),+ session_key: String::new(),+ project_path,+ place,+ };+ if s.is_pattern() {+ for p in projects {+ let place = place.under(p);+ if concrete.contains(place.path()) {+ continue;+ }+ units.push(unit(p.to_string_lossy().to_string(), place));+ }+ } else {+ units.push(unit(String::new(), place));+ }+ }+ units+}++/// 记忆树 `<root>/<项目目录>/memory/*.md` 展开成单元(Claude auto-memory 与 ZCode 同形):+/// 每个含 memory/ 的子目录一份,`attribute(子目录)` 给 (归属会话 key, 项目路径)。root+/// 不在 = 没有记忆;列不出来(权限、I/O、fd 耗尽)是"不知道",报 Err 让 scanner 冻结这一+/// 来源——折成空会把库里这家的记忆整组删光(2026-09-21 review)。按目录排序,结果稳定+pub(crate) fn project_tree_units(+ source: &MemorySource,+ attribute: impl Fn(&std::fs::DirEntry) -> (String, String),+) -> Result<Vec<MemoryUnit>> {+ let entries = match std::fs::read_dir(&source.path) {+ Ok(entries) => entries,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),+ Err(e) => return Err(anyhow::Error::new(e).context(source.path.display().to_string())),+ };+ let id = source.id();+ let mut units: Vec<MemoryUnit> = Vec::new();+ for entry in entries {+ // 逐项的读取错误也是"不知道"(吞掉会让那个项目的记忆行被当成消失而出库)+ let entry = entry.with_context(|| source.path.display().to_string())?;+ let dir = entry.path().join("memory");+ if !dir.is_dir() {+ continue;+ }+ let (session_key, project_path) = attribute(&entry);+ units.push(MemoryUnit {+ scope: MemoryScope::Project,+ source: id.clone(),+ session_key,+ project_path,+ place: UnitPlace::Dir { dir, ext: "md" },+ });+ }+ units.sort_by(|a, b| a.place.path().cmp(b.place.path()));+ Ok(units)+}++/// `list_memories` 的通用骨架:通用来源展开 + 各家自己的记忆树(有 ProjectTree 来源时+/// 交 `tree` 展开)+ 指纹缓存读取。持 `memories` 缓存的 adapter 都用它,别各写一遍+pub(crate) fn memory_docs_with_tree(+ cache: &MemoryCache,agent: AgentId,- dirs: &[MemoryDir],+ sources: &[MemorySource],+ projects: &[std::path::PathBuf],+ tree: impl FnOnce(&MemorySource) -> Result<Vec<MemoryUnit>>,) -> Result<Vec<MemoryDoc>> {- use std::hash::{Hash as _, Hasher as _};- let mut listing: Vec<(&MemoryDir, Vec<(std::path::PathBuf, i64, i64)>)> = Vec::new();- let mut hasher = std::collections::hash_map::DefaultHasher::new();- for md in dirs {- // 目录不存在 = 没有记忆;列不出来、某项 stat 不到 = 不知道,整轮报 Err——- // 静默当成空会让库里那组被删(与下面读正文失败同一条规矩)- let entries = match std::fs::read_dir(&md.dir) {+ let mut units = generic_units(sources, projects);+ if let Some(t) = sources+ .iter()+ .find(|s| s.kind == MemorySourceKind::ProjectTree)+ {+ units.extend(tree(t)?);+ }+ cached_memory_docs(cache, agent, &units)+}++/// 没有自家记忆树的 adapter 的 `list_memories`:只有通用来源(全局文件、项目指令文件、+/// 自定义路径),经各自的 `memories` 缓存读+pub(crate) fn generic_memory_docs(+ cache: &MemoryCache,+ agent: AgentId,+ sources: &[MemorySource],+ projects: &[std::path::PathBuf],+) -> Result<Vec<MemoryDoc>> {+ cached_memory_docs(cache, agent, &generic_units(sources, projects))+}++/// 各家在项目根下读的指令文件(记忆可见层二期):按 agent 静态给,scanner 只挂到该家+/// 的第一个本地实例上(项目根是本机路径,自定义根 / 远程实例不展开)。文件名来自+/// 各家文档:Claude 的 CLAUDE.md / CLAUDE.local.md,Codex 的 AGENTS.md,Gemini 的+/// GEMINI.md,Cursor 的 .cursor/rules/*.mdc 与旧式 .cursorrules,Kiro 的+/// .kiro/steering/*.md,Copilot 的 .github/copilot-instructions.md+pub fn project_instruction_sources(agent: AgentId) -> Vec<MemorySource> {+ let file = |rel: &str| MemorySource {+ agent,+ kind: MemorySourceKind::ProjectFile,+ path: std::path::PathBuf::from(rel),+ };+ let dir = |rel: &str, ext: &'static str| MemorySource {+ agent,+ kind: MemorySourceKind::ProjectDir { ext },+ path: std::path::PathBuf::from(rel),+ };+ match agent {+ AgentId::ClaudeCode => vec![file("CLAUDE.md"), file("CLAUDE.local.md")],+ AgentId::Codex => vec![file("AGENTS.md")],+ AgentId::Gemini => vec![file("GEMINI.md")],+ AgentId::Cursor => vec![dir(".cursor/rules", "mdc"), file(".cursorrules")],+ AgentId::Kiro => vec![dir(".kiro/steering", "md")],+ AgentId::Copilot => vec![file(".github/copilot-instructions.md")],+ _ => Vec::new(),+ }+}++/// 一个实例这一轮的一个来源,按 Settings → Memory locations 的配置标好开关+pub struct PlannedSource {+ pub source: MemorySource,+ /// 没被用户停用+ pub enabled: bool,+ /// 用户添加的(Settings 里可编辑、可删);默认来源只能开关+ pub custom: bool,+}++/// 一个实例(或没有实例的一家)这一轮要读的来源+pub struct PlannedInstance {+ /// roster 下标;None = 该家没有本地实例(会话 location 全停用了),只剩 agent 级来源+ pub adapter: Option<usize>,+ pub agent: AgentId,+ /// 实例的 host(远程镜像);没有实例的一家恒为本地+ pub host: String,+ pub sources: Vec<PlannedSource>,+}++/// 各家这一轮的记忆来源:实例自己报的默认来源 + **该家第一个本地实例**再挂 agent 级的+/// 项目模式(`project_instruction_sources`)与用户的自定义来源(默认实例在 roster 前段;+/// 默认被移除时落到首个自定义实例),再按停用表标 `enabled`。会话 location 全停用、roster+/// 里没有实例的家,agent 级来源照旧归它(`adapter: None`):项目指令文件与自定义路径不在+/// 被停用的 location 里,不该随它消失,停掉的只是从那个根派生的默认来源——原先这种家直接+/// 从计划里消失,scanner 把它整组删光、Settings 里连自定义行都看不见了(2026-09-22 review)。+/// 这条规矩只在这里:scanner 读 enabled 的,Settings 面板全列(画开关),表单查重也看它——+/// 原先三处各写一遍,GUI 还自己拼来源 id、假定它等于路径(2026-09-22 /simplify)+pub fn memory_source_plan(+ adapters: &[Box<dyn AgentAdapter>],+ customs: &[(AgentId, std::path::PathBuf)],+ disabled: &std::collections::HashSet<(AgentId, String)>,+) -> Vec<PlannedInstance> {+ let agent_level = |agent: AgentId| -> Vec<(MemorySource, bool)> {+ project_instruction_sources(agent)+ .into_iter()+ .map(|s| (s, false))+ .chain(+ customs+ .iter()+ .filter(|(a, _)| *a == agent)+ .map(|(_, path)| (MemorySource::custom(agent, path.clone()), true)),+ )+ .collect()+ };+ let planned = |agent: AgentId, sources: Vec<(MemorySource, bool)>| -> Vec<PlannedSource> {+ sources+ .into_iter()+ .map(|(source, custom)| PlannedSource {+ enabled: !disabled.contains(&(agent, source.id())),+ source,+ custom,+ })+ .collect()+ };+ let mut agent_level_taken: std::collections::HashSet<AgentId> =+ std::collections::HashSet::new();+ let mut plan: Vec<PlannedInstance> = adapters+ .iter()+ .enumerate()+ .map(|(ix, adapter)| {+ let agent = adapter.agent();+ let mut sources: Vec<(MemorySource, bool)> = adapter+ .memory_sources()+ .into_iter()+ .map(|s| (s, false))+ .collect();+ if adapter.host().is_empty() && agent_level_taken.insert(agent) {+ sources.extend(agent_level(agent));+ }+ PlannedInstance {+ adapter: Some(ix),+ agent,+ host: adapter.host().to_string(),+ sources: planned(agent, sources),+ }+ })+ .collect();+ for agent in AgentId::ALL.iter().copied() {+ if agent_level_taken.contains(&agent) {+ continue;+ }+ let sources = agent_level(agent);+ if sources.is_empty() {+ continue;+ }+ plan.push(PlannedInstance {+ adapter: None,+ agent,+ host: String::new(),+ sources: planned(agent, sources),+ });+ }+ plan+}++/// 记忆文档按来源缓存:key = 这次读的来源 id(多个就按序拼),值 = (指纹, docs)。scanner+/// 逐来源调 `list_memories`(一个来源读失败只冻结它自己),单槽的 `MtimeCache` 会在来源+/// 之间来回失效(2026-09-22 review)。失败不缓存+pub(crate) struct MemoryCache(+ std::sync::Mutex<std::collections::HashMap<String, (i64, Vec<MemoryDoc>)>>,+);++impl MemoryCache {+ pub(crate) fn new() -> Self {+ Self(std::sync::Mutex::new(std::collections::HashMap::new()))+ }++ fn get_or_build(+ &self,+ key: &str,+ stamp: i64,+ build: impl FnOnce() -> Result<Vec<MemoryDoc>>,+ ) -> Result<Vec<MemoryDoc>> {+ if let Some((s, docs)) = self.0.lock().unwrap().get(key) {+ if *s == stamp {+ return Ok(docs.clone());+ }+ }+ let docs = build()?;+ self.0+ .lock()+ .unwrap()+ .insert(key.to_string(), (stamp, docs.clone()));+ Ok(docs)+ }+}++/// (路径, mtime, size):读取单元下一份文件的指纹+type FileStamp = (std::path::PathBuf, i64, i64);++/// 一个读取单元下要读的文件:目录列直属 `*.<ext>`,文件就它自己,`Path` 按 stat 到的形状+/// 二选一。不存在 = 没有记忆(None);列不出来、stat 不到 = 不知道,报 Err——静默当成空+/// 会让库里那组被删(与读正文失败同一条规矩)。stat 跟符号链接(与会话枚举的+/// default_file_ref 同判据)+fn unit_files(place: &UnitPlace) -> Result<Option<Vec<FileStamp>>> {+ fn stat(path: &Path) -> Result<Option<std::fs::Metadata>> {+ match std::fs::metadata(path) {+ Ok(meta) => Ok(Some(meta)),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),+ Err(e) => Err(anyhow::Error::new(e).context(path.display().to_string())),+ }+ }+ fn dir_files(dir: &Path, ext: &str) -> Result<Option<Vec<FileStamp>>> {+ let entries = match std::fs::read_dir(dir) {Ok(entries) => entries,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,- Err(e) => return Err(anyhow::Error::new(e).context(md.dir.display().to_string())),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(e) => return Err(anyhow::Error::new(e).context(dir.display().to_string())),};- let mut files: Vec<(std::path::PathBuf, i64, i64)> = Vec::new();+ let mut files = Vec::new();for entry in entries {- let entry = entry.with_context(|| md.dir.display().to_string())?;+ let entry = entry.with_context(|| dir.display().to_string())?;let path = entry.path();- if !path.extension().is_some_and(|x| x == "md") {+ if !path.extension().is_some_and(|x| x == ext) {continue;}- let meta = entry- .metadata()- .with_context(|| path.display().to_string())?;+ // 挂空的符号链接、read_dir 与 stat 之间被 agent 删掉的文件 = 不在,跳过这一项;+ // 别的 stat 失败才是"不知道"(2026-09-22 review)+ let meta = match std::fs::metadata(&path) {+ Ok(meta) => meta,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,+ Err(e) => return Err(anyhow::Error::new(e).context(path.display().to_string())),+ };if meta.is_file() {files.push((path, parse_utils::mtime_ms(&meta), meta.len() as i64));}}+ Ok(Some(files))+ }+ let file = |path: &Path, meta: &std::fs::Metadata| {+ (+ path.to_path_buf(),+ parse_utils::mtime_ms(meta),+ meta.len() as i64,+ )+ };+ match place {+ UnitPlace::Dir { dir, ext } => dir_files(dir, ext),+ UnitPlace::File(path) => Ok(stat(path)?+ .filter(|meta| meta.is_file())+ .map(|meta| vec![file(path, &meta)])),+ UnitPlace::Path { path, ext } => match stat(path)? {+ None => Ok(None),+ Some(meta) if meta.is_dir() => dir_files(path, ext),+ Some(meta) => Ok(Some(vec![file(path, &meta)])),+ },+ }+}++/// 几个记忆目录的文档,经 `MemoryCache` 缓存:每轮只 stat(路径 + mtime + size ++/// 锚点拼成指纹),指纹没变就交上一轮读好的那份,变了才重读正文——`list_memories`+/// 每轮扫描都会调,159 份文件每轮都读是白费(2026-09-17 /simplify)。非 UTF-8 的+/// 文件不是记忆,跳过;别的读取失败(权限、I/O)整轮报 Err、不缓存——scanner 对+/// Err 是跳过该组不动库,下一轮再试;缓存成"少了这份"会让库里那行被删且指纹不变+/// 就再也不读(Codex review 2026-09-17)+pub(crate) fn cached_memory_docs(+ cache: &MemoryCache,+ agent: AgentId,+ units: &[MemoryUnit],+) -> Result<Vec<MemoryDoc>> {+ use std::hash::{Hash as _, Hasher as _};+ // 缓存槽按这次读的来源分:scanner 逐来源调,各来源的指纹互不干扰+ let mut key: Vec<&str> = units.iter().map(|u| u.source.as_str()).collect();+ key.sort_unstable();+ key.dedup();+ let key = key.join("\n");+ let mut listing: Vec<(&MemoryUnit, Vec<FileStamp>)> = Vec::new();+ let mut hasher = std::collections::hash_map::DefaultHasher::new();+ for unit in units {+ let Some(mut files) = unit_files(&unit.place)? else {+ continue;+ };if files.is_empty() {continue;}files.sort();- md.session_key.hash(&mut hasher);- md.project_path.hash(&mut hasher);+ unit.source.hash(&mut hasher);+ unit.session_key.hash(&mut hasher);+ unit.project_path.hash(&mut hasher);files.hash(&mut hasher);- listing.push((md, files));+ listing.push((unit, files));}let stamp = hasher.finish() as i64;- cache.get_or_build_result(stamp, || {+ cache.get_or_build(&key, stamp, || {let mut docs = Vec::new();- for (md, files) in &listing {+ for (unit, files) in &listing {for (path, updated_at, size_bytes) in files {- if let Some(doc) = memory_doc_from_file(agent, md, path, *updated_at, *size_bytes)?+ if let Some(doc) =+ memory_doc_from_file(agent, unit, path, *updated_at, *size_bytes)?{docs.push(doc);}@@ -581,12 +966,12 @@ pub(crate) fn cached_memory_docs(pub const MEMORY_TITLE_MAX: usize = 120;/// 读一份 Markdown 记忆文件成 MemoryDoc:标题取 frontmatter 的 description,其次-/// name,再退文件名;正文原样保留(含 frontmatter,阅读面照渲染)。项目路径不在这里-/// 填(读库时按 session_key 解析)。非 UTF-8 给 Ok(None)(不是记忆),其余读取失败-/// 原样报错+/// name,再退文件名(带扩展名——"CLAUDE.md" / "MEMORY.md" 本身就是它的名字);正文+/// 原样保留(含 frontmatter,阅读面照渲染)。项目路径不在这里填(读库时按 session_key+/// 解析)。非 UTF-8 给 Ok(None)(不是记忆),其余读取失败原样报错fn memory_doc_from_file(agent: AgentId,- dir: &MemoryDir,+ unit: &MemoryUnit,path: &Path,updated_at: i64,size_bytes: i64,@@ -596,8 +981,8 @@ fn memory_doc_from_file(Err(e) if e.kind() == std::io::ErrorKind::InvalidData => return Ok(None),Err(e) => return Err(anyhow::Error::new(e).context(path.display().to_string())),};- let stem = path- .file_stem()+ let fallback = path+ .file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();// description 是一句话,本机实测有 565 字符的:折行、按字符封顶,列表与 MCP 一行@@ -605,24 +990,25 @@ fn memory_doc_from_file(let title = frontmatter_field(&body, "description").or_else(|| frontmatter_field(&body, "name")).map(|t| crate::text::one_line(&t, MEMORY_TITLE_MAX))- .unwrap_or(stem);+ .unwrap_or(fallback);let path_str = path.to_string_lossy().to_string();Ok(Some(MemoryDoc {key: session_key(agent, "", &path_str),agent,host: String::new(),- scope: dir.scope,- project_path: dir.project_path.clone(),- project_name: if dir.project_path.is_empty() {+ scope: unit.scope,+ project_path: unit.project_path.clone(),+ project_name: if unit.project_path.is_empty() {String::new()} else {- parse_utils::project_name_of(&dir.project_path)+ parse_utils::project_name_of(&unit.project_path)},- session_key: dir.session_key.clone(),+ session_key: unit.session_key.clone(),path: path_str,title,updated_at,size_bytes,+ source: unit.source.clone(),body,}))}diff --git a/crates/wake-core/src/adapters/parse_utils.rs b/crates/wake-core/src/adapters/parse_utils.rsindex 307f836..446b70f 100644--- a/crates/wake-core/src/adapters/parse_utils.rs+++ b/crates/wake-core/src/adapters/parse_utils.rs@@ -766,6 +766,15 @@ pub fn tool_call_view(}/// 截断到 max 字符(按 char 边界),返回 (text, truncated)+/// `clip` 的按字符版:预算是字符数——记忆正文多是中文(约 3 字节一字),按字节截会把+/// 9000 字的文件在 6600 字处截断、提示却说"20000 of 9000 characters"(2026-09-22 review)+pub fn clip_chars(s: &str, max_chars: usize) -> (String, bool) {+ match s.char_indices().nth(max_chars) {+ None => (s.to_string(), false),+ Some((end, _)) => (format!("{}\n… (truncated)", &s[..end]), true),+ }+}+pub fn clip(s: &str, max: usize) -> (String, bool) {if s.len() <= max {return (s.to_string(), false);@@ -989,6 +998,15 @@ pub fn make_preview(input: &Value) -> String {mod tests {use super::*;+ #[test]+ fn clip_chars_counts_characters() {+ let s = "记忆正文一共九个字";+ assert_eq!(clip_chars(s, 9), (s.to_string(), false));+ let (cut, truncated) = clip_chars(s, 4);+ assert!(truncated);+ assert!(cut.starts_with("记忆正文\n…"), "{cut}");+ }+const IMAGE_SHAPES: &str = include_str!("../../tests/fixtures/image_content_shapes.json");#[test]diff --git a/crates/wake-core/src/adapters/remote.rs b/crates/wake-core/src/adapters/remote.rsindex ed9f15d..98c16b8 100644--- a/crates/wake-core/src/adapters/remote.rs+++ b/crates/wake-core/src/adapters/remote.rs@@ -144,9 +144,19 @@ impl AgentAdapter for RemoteAdapter {self.inner.session_paths(meta)}- fn list_memories(&self) -> Result<Vec<MemoryDoc>> {- // 记忆的 key 与会话 key 同规矩:agent 段之后插 host;线程级挂的会话 key 同改- let mut docs = self.inner.list_memories()?;+ fn memory_sources(&self) -> Vec<MemorySource> {+ // inner 按缓存挂载点构造,它报的路径已经是缓存内的+ self.inner.memory_sources()+ }++ fn list_memories(+ &self,+ sources: &[MemorySource],+ _projects: &[std::path::PathBuf],+ ) -> Result<Vec<MemoryDoc>> {+ // 项目根是本机路径,远程实例不展开项目模式(传空);记忆的 key 与会话 key+ // 同规矩:agent 段之后插 host,线程级挂的会话 key 同改+ let mut docs = self.inner.list_memories(sources, &[])?;for d in &mut docs {d.key = self.rewrite_key(&d.key);d.host = self.host.clone();@@ -175,11 +185,6 @@ impl AgentAdapter for RemoteAdapter {)}- fn memory_roots(&self) -> Vec<std::path::PathBuf> {- // inner 是按缓存挂载点构造的实例,它报的根已经是缓存内路径- self.inner.memory_roots()- }-fn is_parent_link_event(&self, path: &Path) -> bool {self.inner.is_parent_link_event(path)}@@ -208,6 +213,10 @@ impl AgentAdapter for RemoteAdapter {self.inner.dedup_rank()}+ fn parent_links_global(&self) -> bool {+ self.inner.parent_links_global()+ }+fn excluding_data_roots(&self, roots: &[std::path::PathBuf]) -> Option<Box<dyn AgentAdapter>> {let inner = self.inner.excluding_data_roots(roots)?;Some(Box::new(Self::new(inner, self.host.clone())))diff --git a/crates/wake-core/src/adapters/sqlite_ro.rs b/crates/wake-core/src/adapters/sqlite_ro.rsindex e81d0fc..e2aa36a 100644--- a/crates/wake-core/src/adapters/sqlite_ro.rs+++ b/crates/wake-core/src/adapters/sqlite_ro.rs@@ -29,7 +29,19 @@ pub fn open_sqlite_ro(db: &Path, tag: &str) -> Option<SqliteRo> {return Some(SqliteRo { conn, _tmp: None });}}- let tmp = std::env::temp_dir().join(format!("wake-{tag}-{}", std::process::id()));+ // 目录名带库路径的哈希:同一 tag 的两个实例(Hermes 多档案、Codex 默认 + 自定义根、+ // 多 host 镜像)并发走到这里时不能共用一个目录,否则互相覆盖 db.sqlite、先退出的+ // 一方 remove_dir_all 把另一方的连接从脚下抽走(2026-09-22 review)+ let path_hash = {+ use std::hash::{Hash as _, Hasher as _};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ db.hash(&mut h);+ h.finish()+ };+ let tmp = std::env::temp_dir().join(format!(+ "wake-{tag}-{}-{path_hash:016x}",+ std::process::id()+ ));fs::create_dir_all(&tmp).ok()?;let guard = TempDirGuard(tmp.clone());let db_copy = tmp.join("db.sqlite");diff --git a/crates/wake-core/src/adapters/zcode.rs b/crates/wake-core/src/adapters/zcode.rsindex 6a82724..6367fc4 100644--- a/crates/wake-core/src/adapters/zcode.rs+++ b/crates/wake-core/src/adapters/zcode.rs@@ -83,7 +83,7 @@ pub struct ZcodeAdapter {/// tasks-index 里要藏的会话 id,按它自己的 mtime 缓存hidden_cache: MtimeCache<HashSet<String>>,/// 记忆文档按目录指纹缓存(每轮扫描都会列,没变不重读)- memories: MtimeCache<Vec<MemoryDoc>>,+ memories: super::MemoryCache,}#[derive(Clone)]@@ -163,7 +163,7 @@ impl ZcodeAdapter {home: Some(home),rows_cache: MtimeCache::new(),hidden_cache: MtimeCache::new(),- memories: MtimeCache::new(),+ memories: super::MemoryCache::new(),}}@@ -175,7 +175,7 @@ impl ZcodeAdapter {home: None,rows_cache: MtimeCache::new(),hidden_cache: MtimeCache::new(),- memories: MtimeCache::new(),+ memories: super::MemoryCache::new(),}}@@ -183,6 +183,29 @@ impl ZcodeAdapter {open_sqlite_ro(&self.db, "zcode")}+ /// `cli/memories/projects/<slug>-<hash>/memory/*.md` 展开成读取单元。目录名的 hash+ /// 对应库里会话的 directory(见 memory_dir_hash);库读不出就都对不上,记忆照列、+ /// 落 Unknown project。没这个目录 = 确定没有记忆;别的读取失败报 Err,scanner 只+ /// 冻结这一来源+ fn tree_units(&self, source: &MemorySource) -> Result<Vec<super::MemoryUnit>> {+ let workspaces: HashMap<String, String> = self+ .rows()+ .unwrap_or_default()+ .into_iter()+ .map(|row| (memory_dir_hash(&row.directory), row.directory))+ .collect();+ super::project_tree_units(source, |entry| {+ let project_path = entry+ .file_name()+ .to_str()+ .and_then(|name| name.rsplit_once('-'))+ .and_then(|(_, hash)| workspaces.get(hash))+ .cloned()+ .unwrap_or_default();+ (String::new(), project_path)+ })+ }+/// 行清单。库这一刻读不出(ZCode 原地 migration、copy 梯度失败)交回**上一次读到/// 的**:枚举接口表达不了"不知道",而空清单会让 scanner 把整家会话当"磁盘已删"/// 清掉、下一轮再全部重解析回来;从没读成功过才是 None(2026-09-21 review)@@ -418,7 +441,16 @@ impl AgentAdapter for ZcodeAdapter {}fn list_session_files(&self) -> Result<Vec<SessionFileRef>> {- let rows = self.rows().unwrap_or_default();+ // 库不在 = 没有会话(Ok 空,不变量 8①);库在但从没读成功过(ZCode 常驻、正在原地+ // migration)= 不知道,报 Err 让这一轮扫描停下——折成空会让 seen_paths 清理把整家+ // 会话当"磁盘已删"删掉、下一轮再全部重解析回来(2026-09-22 review)+ let rows = match self.rows() {+ Some(rows) => rows,+ None if self.db.is_file() => {+ anyhow::bail!("{} exists but could not be read", self.db.display())+ }+ None => Vec::new(),+ };let hidden = self.hidden();Ok(rows.into_iter()@@ -457,56 +489,27 @@ impl AgentAdapter for ZcodeAdapter {vec![self.db.clone()]}- fn memory_roots(&self) -> Vec<PathBuf> {+ fn memory_sources(&self) -> Vec<MemorySource> {self.home.as_ref()- .map(|home| vec![home.join(MEMORIES_REL)])+ .map(|home| {+ vec![MemorySource {+ agent: AgentId::Zcode,+ kind: MemorySourceKind::ProjectTree,+ path: home.join(MEMORIES_REL),+ }]+ }).unwrap_or_default()}- fn list_memories(&self) -> Result<Vec<MemoryDoc>> {- let Some(home) = &self.home else {- return Ok(Vec::new());- };- let projects = home.join(MEMORIES_REL);- let entries = match std::fs::read_dir(&projects) {- Ok(entries) => entries,- // 没这个目录 = 确定没有记忆;别的读取失败报 Err,scanner 跳过这一组不动库- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),- Err(e) => return Err(anyhow!("read {}: {e}", projects.display())),- };- // 目录名 `<slug>-<hash>` 的 hash 对应库里会话的 directory(见 memory_dir_hash);- // 库读不出就都对不上,记忆照列、落 Unknown project- let workspaces: HashMap<String, String> = self- .rows()- .unwrap_or_default()- .into_iter()- .map(|row| (memory_dir_hash(&row.directory), row.directory))- .collect();- let mut dirs: Vec<super::MemoryDir> = entries- .flatten()- .filter_map(|entry| {- let dir = entry.path().join("memory");- if !dir.is_dir() {- return None;- }- let project_path = entry- .file_name()- .to_str()- .and_then(|name| name.rsplit_once('-'))- .and_then(|(_, hash)| workspaces.get(hash))- .cloned()- .unwrap_or_default();- Some(super::MemoryDir {- scope: MemoryScope::Project,- session_key: String::new(),- project_path,- dir,- })- })- .collect();- dirs.sort_by(|a, b| a.dir.cmp(&b.dir));- super::cached_memory_docs(&self.memories, AgentId::Zcode, &dirs)+ fn list_memories(+ &self,+ sources: &[MemorySource],+ projects: &[PathBuf],+ ) -> Result<Vec<MemoryDoc>> {+ super::memory_docs_with_tree(&self.memories, AgentId::Zcode, sources, projects, |tree| {+ self.tree_units(tree)+ })}fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rsindex 1cd3007..74cfd76 100644--- a/crates/wake-core/src/db.rs+++ b/crates/wake-core/src/db.rs@@ -147,9 +147,22 @@ CREATE TABLE IF NOT EXISTS memories (title TEXT NOT NULL DEFAULT '',updated_at INTEGER DEFAULT 0,size_bytes INTEGER DEFAULT 0,+ source TEXT NOT NULL DEFAULT '',body TEXT NOT NULL DEFAULT '');CREATE INDEX IF NOT EXISTS idx_memories_group ON memories(agent_id, host);+CREATE TABLE IF NOT EXISTS memory_sources_custom (+ agent TEXT NOT NULL,+ path TEXT NOT NULL,+ added_at INTEGER NOT NULL,+ PRIMARY KEY (agent, path)+);+CREATE TABLE IF NOT EXISTS memory_sources_disabled (+ agent TEXT NOT NULL,+ source TEXT NOT NULL,+ disabled_at INTEGER NOT NULL,+ PRIMARY KEY (agent, source)+);CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(title,body,@@ -226,12 +239,24 @@ fn open_conn(path: &Path) -> Result<Connection> {}// host 迁移(2026-09-01 远程会话加列;空串 = 本地)。老库首扫时既有行// 全部落 '',与远程装饰器生产的非空 host 天然分域,无需回填- if !table_has_column(&conn, NEWEST_COLUMN.0, NEWEST_COLUMN.1)? {+ if !table_has_column(&conn, "sessions", "host")? {conn.execute("ALTER TABLE sessions ADD COLUMN host TEXT NOT NULL DEFAULT ''",[],)?;}+ // 记忆来源列(记忆可见层二期,2026-09-21):source = 所属来源的 id。memories 表还+ // 没发布过,但开发机上的库已按旧 DDL 建过;老行 source 为空,下一轮扫描按来源+ // 指纹重写(开发机上短暂存在过的 origin 列留着不碍事,DDL 与读写都不再提它)+ // 守卫写死列名、不引用 NEWEST_COLUMN:那个常量下次迁移就会改指别的列,这里跟着改指+ // 就会对已迁移的库再 ALTER 一次,duplicate column 让 open_or_rebuild 把好端端的索引+ // 当坏库重建(2026-09-22 review)+ if !table_has_column(&conn, "memories", "source")? {+ conn.execute(+ "ALTER TABLE memories ADD COLUMN source TEXT NOT NULL DEFAULT ''",+ [],+ )?;+ }// 部分索引须在 host 列就位后建(放 DDL 里对未迁移老库会 no such column):// host_counts 的 GROUP BY 从全表扫降为远小于全表的索引扫conn.execute(@@ -257,7 +282,7 @@ fn open_conn(path: &Path) -> Result<Connection> {/// 最近一次迁移加的列——`open_read_only` 用它判断库够不够新。**加新迁移时把/// 这里改成新列**,否则只读入口会放行老库、深处查询才报 no such column-const NEWEST_COLUMN: (&str, &str) = ("sessions", "host");+const NEWEST_COLUMN: (&str, &str) = ("memories", "source");/// 最近一次迁移加的、只读读者会查的表(wake_list_memories 读 memories),与/// NEWEST_COLUMN 同一用途、同一维护规矩const NEWEST_TABLE: &str = "memories";@@ -1433,15 +1458,18 @@ impl Store {agent: AgentId,host: &str,docs: &[MemoryDoc],- frozen: &[std::path::PathBuf],+ frozen: &[String],) -> Result<bool> {let mut conn = self.write.lock().unwrap();let tx = conn.transaction()?;- // key → (id, 指纹);指纹含 session_key 与 project_path,锚点换了(目录里来了- // 更新的会话)同样要重写,否则项目归属定格在首次入库那一刻- let existing: HashMap<String, (i64, (i64, i64, String, String))> = {+ // key → (id, 指纹);指纹 = (updated_at, size, session_key, project_path, source, title):+ // 锚点换了(目录里来了更新的会话)同样要重写,否则项目归属定格在首次入库那一刻;+ // 来源换了(同一文件从自定义变成默认)也重写;标题也在指纹里——标题是从文件派生+ // 的,派生规则换了(2026-09-21 改成文件名带扩展名)文件没变也要跟上,正文不比+ type Stamp = (i64, i64, String, String, String, String);+ let existing: HashMap<String, (i64, Stamp)> = {let mut stmt = tx.prepare_cached(- "SELECT key, id, updated_at, size_bytes, session_key, project_path+ "SELECT key, id, updated_at, size_bytes, session_key, project_path, source, titleFROM memories WHERE agent_id = ?1 AND host = ?2",)?;let rows = stmt.query_map(params![agent.as_str(), host], |r| {@@ -1450,52 +1478,50 @@ impl Store {(r.get::<_, i64>(1)?,(- r.get::<_, i64>(2)?,- r.get::<_, i64>(3)?,- r.get::<_, String>(4)?,- r.get::<_, String>(5)?,+ r.get(2)?,+ r.get(3)?,+ r.get(4)?,+ r.get(5)?,+ r.get(6)?,+ r.get(7)?,),),))})?;rows.collect::<rusqlite::Result<_>>()?};- // 同 key 重复(同家两个实例的根重叠)后者胜:先按 key 收成一份再写,否则- // 前一份写了、后一份与库里相同被跳过,就成了前者胜- let latest: std::collections::BTreeMap<&str, &MemoryDoc> =- docs.iter().map(|d| (d.key.as_str(), d)).collect();+ let unchanged = |s: &Stamp, d: &MemoryDoc| {+ s.0 == d.updated_at+ && s.1 == d.size_bytes+ && s.2 == d.session_key+ && s.3 == d.project_path+ && s.4 == d.source+ && s.5 == d.title+ };+ // 同 key 重复**前者胜**:docs 按来源计划的顺序读入(默认来源 → 项目模式 → 自定义,+ // 默认实例 → 自定义实例),先到的是默认那份——自定义目录盖住默认文件(加 ~/.claude+ // 当自定义目录,里面的 CLAUDE.md 已是默认来源)时计数与开关才落在默认行上,而不是+ // 默认行显示 0 份、关掉也不生效(2026-09-22 review)。先按 key 收成一份再写,不然+ // 写了第一份、第二份与库里相同被跳过,胜负就看谁先到库里+ let mut latest: std::collections::BTreeMap<&str, &MemoryDoc> =+ std::collections::BTreeMap::new();+ for d in docs {+ latest.entry(d.key.as_str()).or_insert(d);+ }let mut changed = false;for d in latest.values() {- let stamp = (- d.updated_at,- d.size_bytes,- d.session_key.clone(),- d.project_path.clone(),- );- if existing.get(&d.key).is_some_and(|(_, s)| *s == stamp) {+ if existing.get(&d.key).is_some_and(|(_, s)| unchanged(s, d)) {continue;}upsert_memory(&tx, d)?;changed = true;}- // `frozen` 是这一轮读失败的实例的根:那些根下的行不删(它们没出现在 docs 里- // 只是因为读不出,不是文件没了)- let frozen: Vec<String> = frozen- .iter()- .map(|p| p.to_string_lossy().to_string())- .collect();+ // `frozen` 是这一轮读失败的实例的来源 id:那些来源的行不删(它们没出现在 docs+ // 里只是因为读不出,不是文件没了)let mut stmt_fts = tx.prepare_cached("DELETE FROM memories_fts WHERE rowid = ?1")?;let mut stmt_row = tx.prepare_cached("DELETE FROM memories WHERE key = ?1")?;- for (key, (id, (_, _, _, _))) in existing.iter() {- if latest.contains_key(key.as_str()) {- continue;- }- let path: String = tx.query_row(- "SELECT path FROM memories WHERE key = ?1",- params![key],- |r| r.get(0),- )?;- if frozen.iter().any(|root| memory_root_covers(root, &path)) {+ for (key, (id, stamp)) in existing.iter() {+ if latest.contains_key(key.as_str()) || frozen.contains(&stamp.4) {continue;}stmt_fts.execute(params![id])?;@@ -1508,6 +1534,145 @@ impl Store {Ok(changed)}+ /// Settings → Memory locations 的计数:每个 (agent, 来源 id) 有多少份+ pub fn memory_source_counts(&self) -> Result<HashMap<(String, String), i64>> {+ let conn = self.read.lock().unwrap();+ let mut stmt =+ conn.prepare_cached("SELECT agent_id, source, COUNT(*) FROM memories GROUP BY 1, 2")?;+ let rows = stmt.query_map([], |r| {+ Ok((+ (r.get::<_, String>(0)?, r.get::<_, String>(1)?),+ r.get::<_, i64>(2)?,+ ))+ })?;+ Ok(rows.collect::<rusqlite::Result<_>>()?)+ }++ /// 已索引的本地项目根(host 为空、路径非空),给记忆的项目模式(`<project>/CLAUDE.md`+ /// 一类)展开;远程会话的项目是别的机器上的路径,不在其中+ pub fn local_project_roots(&self) -> Result<Vec<PathBuf>> {+ let conn = self.read.lock().unwrap();+ let mut stmt = conn.prepare_cached(+ "SELECT DISTINCT project_path FROM sessions+ WHERE host = '' AND project_path != '' ORDER BY project_path",+ )?;+ let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;+ Ok(rows+ .collect::<rusqlite::Result<Vec<_>>>()?+ .into_iter()+ .map(PathBuf::from)+ .collect())+ }++ // ---------- 记忆来源配置(Settings → Memory locations) ----------++ /// 与 Session locations 同一层级的用户数据:自定义来源(目录或文件)与被停用的+ /// 默认来源(按 `MemorySource::id`),重扫不动它。对外只有 `memory_source_overrides`+ /// 一次取齐+ fn list_memory_sources_custom(&self) -> Result<Vec<(String, String)>> {+ let conn = self.read.lock().unwrap();+ let mut stmt = conn.prepare_cached(+ "SELECT agent, path FROM memory_sources_custom ORDER BY added_at, path",+ )?;+ let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }++ pub fn add_memory_source(&self, agent: &str, path: &str) -> Result<()> {+ let conn = self.write.lock().unwrap();+ insert_memory_source(&conn, agent, path)+ }++ /// 删自定义来源,连同它的停用记录(日后重新添加同一路径要按启用开始)+ pub fn remove_memory_source(&self, agent: &str, path: &str) -> Result<()> {+ let mut conn = self.write.lock().unwrap();+ let tx = conn.transaction()?;+ delete_memory_source(&tx, agent, path)?;+ tx.commit()?;+ Ok(())+ }++ /// 编辑自定义来源:删旧记新,一个事务(半程失败不得半生效)+ pub fn replace_memory_source(+ &self,+ old_agent: &str,+ old_path: &str,+ new_agent: &str,+ new_path: &str,+ ) -> Result<()> {+ let mut conn = self.write.lock().unwrap();+ let tx = conn.transaction()?;+ delete_memory_source(&tx, old_agent, old_path)?;+ insert_memory_source(&tx, new_agent, new_path)?;+ tx.commit()?;+ Ok(())+ }++ fn list_memory_sources_disabled(&self) -> Result<Vec<(String, String)>> {+ let conn = self.read.lock().unwrap();+ let mut stmt = conn.prepare_cached(+ "SELECT agent, source FROM memory_sources_disabled ORDER BY disabled_at, source",+ )?;+ let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }++ /// 来源开关的唯一写入口。enabled=true 删停用标记;false 幂等记入+ pub fn set_memory_source_enabled(+ &self,+ agent: &str,+ source: &str,+ enabled: bool,+ ) -> Result<()> {+ let conn = self.write.lock().unwrap();+ if enabled {+ conn.execute(+ "DELETE FROM memory_sources_disabled WHERE agent = ?1 AND source = ?2",+ params![agent, source],+ )?;+ } else {+ conn.execute(+ "INSERT OR IGNORE INTO memory_sources_disabled(agent, source, disabled_at)+ VALUES (?1, ?2, ?3)",+ params![agent, source, now_ms()],+ )?;+ }+ Ok(())+ }++ /// Restore defaults:清空自定义来源与停用记录+ pub fn clear_memory_source_overrides(&self) -> Result<()> {+ let conn = self.write.lock().unwrap();+ conn.execute_batch(+ "DELETE FROM memory_sources_custom;+ DELETE FROM memory_sources_disabled;",+ )?;+ Ok(())+ }++ /// 记忆来源配置一次取齐,解析成模型层类型;未识别的 agent 名静默跳过。停用表给+ /// 集合——调用方都是按 (agent, 来源 id) 查它。scanner 与 Settings 共用。读失败原样+ /// 报 Err:scanner 拿它做"按缺席删",折成"什么都没配置"会删光项目指令文件、把停用的+ /// 来源重新索引进来(2026-09-22 review);Settings 只是显示,自己 unwrap_or_default+ pub fn memory_source_overrides(+ &self,+ ) -> Result<(+ Vec<(AgentId, PathBuf)>,+ std::collections::HashSet<(AgentId, String)>,+ )> {+ let customs = self+ .list_memory_sources_custom()?+ .into_iter()+ .filter_map(|(a, p)| AgentId::from_str(&a).map(|a| (a, PathBuf::from(p))))+ .collect();+ let disabled = self+ .list_memory_sources_disabled()?+ .into_iter()+ .filter_map(|(a, s)| AgentId::from_str(&a).map(|a| (a, s)))+ .collect();+ Ok((customs, disabled))+ }+/// 库里现有记忆的 (agent, host) 分组——scanner 拿它对照当前 roster,不再配置的来源/// (删掉的远程 host、停用的 agent)整组清掉pub fn memory_groups(&self) -> Result<Vec<(AgentId, String)>> {@@ -1526,9 +1691,10 @@ impl Store {/// Memory 页侧栏的计数:agent 按 AgentId 声明序(与会话侧栏同序,计数平局不抖),/// 项目按最近更新降序、没归属的一项(path 为空)垫底。项目按读时解析的归属算,- /// 与 list_memories 同一口径——**用户级记忆对每个项目都成立**,list_memories 在- /// 任何项目筛选下都列它们,所以每个项目行(含 Unknown project)的计数都把用户级- /// 加进去,点开看到多少行、徽章就是多少(2026-09-21 review)+ /// 与 list_memories 同一口径:**项目行只数项目记忆**(GUI 的项目行喂+ /// `UserMemories::Excluded`),用户级另给 `user`——曾把用户级加进每个项目行+ /// (2026-09-21 review),用户 2026-09-22 定用户记忆不进项目、自成一行;两种口径+ /// 下都是点开看到多少行、徽章就是多少pub fn memory_counts(&self) -> Result<MemoryCounts> {let conn = self.read.lock().unwrap();let mut stmt = conn.prepare_cached(&format!(@@ -1574,9 +1740,7 @@ impl Store {p.count += n;p.updated_at = p.updated_at.max(last);}- for p in projects.values_mut() {- p.count += user_level;- }+ counts.user = user_level;counts.agents = agents.into_iter().collect();counts.agents.sort_by_key(|(agent, _)| *agent);counts.projects = projects.into_values().collect();@@ -1591,7 +1755,8 @@ impl Store {}/// 记忆列表:项目级按项目路径成组、组内新到旧,没归属的一组排在项目之后,- /// 用户级(对每个项目都成立)最后;项目筛选下用户级照列。**`limit` 只封项目级**:+ /// 用户级(对每个项目都成立)最后;项目筛选下用户级照列(`f.user` 默认 Alongside,+ /// GUI 的项目行 Excluded、User memory 行 Only)。**`limit` 只封项目级**:/// 用户级排在最后,一刀切的 LIMIT 砍掉的正是筛选特意放进来的那几份(2026-09-21/// review),所以项目级带 LIMIT 查、用户级不限量另查再接上。**行里 body 是空串**/// (`MEMORY_LIST_COLS`),要正文走 `get_memory`@@ -1681,7 +1846,9 @@ impl Store {|r| {Ok(MemoryHit {doc: row_to_memory(r)?,- snippet: r.get(12)?,+ // snippet 是 SELECT 里跟在 memory_cols! 后面的最后一列,按列数取——写死下标加列时+ // 顶错过一次(2026-09-21)+ snippet: r.get(r.as_ref().column_count() - 1)?,})},)?;@@ -2356,7 +2523,7 @@ macro_rules! memory_cols {"m.key, m.agent_id, m.host, m.scope,COALESCE(NULLIF(m.project_path, ''), s.project_path, ''),COALESCE(NULLIF(m.project_name, ''), s.project_name, ''),- m.session_key, m.path, m.title, m.updated_at, m.size_bytes, ",+ m.session_key, m.path, m.title, m.updated_at, m.size_bytes, m.source, ",$body)};@@ -2366,15 +2533,6 @@ const MEMORY_COLS: &str = memory_cols!("m.body");/// 另取,MCP 的 wake_list_memories 只打标题),没必要每次刷新把几百 KB 文本拉出来const MEMORY_LIST_COLS: &str = memory_cols!("''");-/// `path` 在不在这个记忆根下:目录根按分隔符划界,SQLite 型的库文件根认虚拟路径-/// `<db>#<id>`(`replace_memories` 的冻结判据)-fn memory_root_covers(root: &str, path: &str) -> bool {- path == root- || path- .strip_prefix(root)- .is_some_and(|rest| rest.starts_with(std::path::is_separator) || rest.starts_with('#'))-}-fn row_to_memory(r: &rusqlite::Row<'_>) -> rusqlite::Result<MemoryDoc> {let agent: String = r.get(1)?;let scope: String = r.get(3)?;@@ -2390,15 +2548,23 @@ fn row_to_memory(r: &rusqlite::Row<'_>) -> rusqlite::Result<MemoryDoc> {title: r.get(8)?,updated_at: r.get(9)?,size_bytes: r.get(10)?,- body: r.get(11)?,+ source: r.get(11)?,+ body: r.get(12)?,})}/// list_memories / search_memories 共用的筛选谓词(表别名 m):agent 并集;项目并集-/// 之外用户级记忆恒放行——它对每个项目都成立+/// 之外用户级记忆默认放行——它对每个项目都成立;`f.user` 可以把它剔掉(GUI 的+/// 项目行)或只留它(GUI 的 User memory 行)fn memory_filter(f: &MemoryFilter) -> (String, Vec<Box<dyn rusqlite::ToSql>>) {let mut sql = String::new();let mut args: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();+ let user = MemoryScope::User.as_str();+ match f.user {+ UserMemories::Alongside => {}+ UserMemories::Excluded => sql.push_str(&format!(" AND m.scope != '{user}'")),+ UserMemories::Only => sql.push_str(&format!(" AND m.scope = '{user}'")),+ }if !f.agents.is_empty() {sql.push_str(&format!(" AND m.agent_id IN ({})",@@ -2408,9 +2574,14 @@ fn memory_filter(f: &MemoryFilter) -> (String, Vec<Box<dyn rusqlite::ToSql>>) {args.push(Box::new(a.as_str().to_string()));}}+ if let Some(since) = f.updated_since {+ sql.push_str(" AND m.updated_at >= ?");+ args.push(Box::new(since));+ }if f.scopes_projects() {// 项目并集 ∪ 没归属的一组(显式的 unattributed,不拿空串当暗号:空串什么都- // 不匹配)∪ 用户级(对每个项目都成立)+ // 不匹配)∪ 用户级(对每个项目都成立;只有 Alongside 放行——Excluded 上面已+ // 剔掉,Only 与项目筛选本就没有交集)let mut terms: Vec<String> = Vec::new();if !f.project_paths.is_empty() {terms.push(format!(@@ -2424,12 +2595,36 @@ fn memory_filter(f: &MemoryFilter) -> (String, Vec<Box<dyn rusqlite::ToSql>>) {if f.unattributed {terms.push(format!("{MEMORY_PROJECT} = ''"));}- terms.push(format!("m.scope = '{}'", MemoryScope::User.as_str()));+ if f.user == UserMemories::Alongside {+ terms.push(format!("m.scope = '{user}'"));+ }sql.push_str(&format!(" AND ({})", terms.join(" OR ")));}(sql, args)}+/// 自定义记忆来源的两条写语句,add / remove / replace 共用(replace = 同一事务里先删后加)+fn insert_memory_source(conn: &rusqlite::Connection, agent: &str, path: &str) -> Result<()> {+ conn.execute(+ "INSERT OR IGNORE INTO memory_sources_custom(agent, path, added_at) VALUES (?1, ?2, ?3)",+ params![agent, path, now_ms()],+ )?;+ Ok(())+}++/// 连同它的停用记录一起删(日后重新添加同一路径要按启用开始)+fn delete_memory_source(conn: &rusqlite::Connection, agent: &str, path: &str) -> Result<()> {+ conn.execute(+ "DELETE FROM memory_sources_custom WHERE agent = ?1 AND path = ?2",+ params![agent, path],+ )?;+ conn.execute(+ "DELETE FROM memory_sources_disabled WHERE agent = ?1 AND source = ?2",+ params![agent, path],+ )?;+ Ok(())+}+/// 写一份记忆:memories 行按 key 就地更新(id 不变,memories_fts 的 rowid 就是它),/// FTS 那份先按 rowid 删再插。语句都走 prepare_cached——一次冷建一百多份,逐条/// 编译 SQL 白费@@ -2437,13 +2632,13 @@ fn upsert_memory(tx: &rusqlite::Transaction<'_>, d: &MemoryDoc) -> Result<()> {let id: i64 = tx.prepare_cached("INSERT INTO memories(key, agent_id, host, scope, project_path, project_name,- session_key, path, title, updated_at, size_bytes, body)- VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12)+ session_key, path, title, updated_at, size_bytes, source, body)+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13)ON CONFLICT(key) DO UPDATE SET agent_id = excluded.agent_id, host = excluded.host,scope = excluded.scope, project_path = excluded.project_path,project_name = excluded.project_name, session_key = excluded.session_key,path = excluded.path, title = excluded.title, updated_at = excluded.updated_at,- size_bytes = excluded.size_bytes, body = excluded.body+ size_bytes = excluded.size_bytes, source = excluded.source, body = excluded.bodyRETURNING id",)?.query_row(@@ -2459,6 +2654,7 @@ fn upsert_memory(tx: &rusqlite::Transaction<'_>, d: &MemoryDoc) -> Result<()> {d.title,d.updated_at,d.size_bytes,+ d.source,d.body,],|r| r.get::<_, i64>(0),diff --git a/crates/wake-core/src/mcp/tools.rs b/crates/wake-core/src/mcp/tools.rsindex e46bbaa..fa557d2 100644--- a/crates/wake-core/src/mcp/tools.rs+++ b/crates/wake-core/src/mcp/tools.rs@@ -216,7 +216,7 @@ pub fn definitions() -> Vec<Value> {json!({"name": LIST_MEMORIES,"title": "List agent memory files",- "description": "The memory files coding agents keep for themselves on this machine — Claude Code's and ZCode's per-project auto-memory (MEMORY.md and its topic files) and Codex's memories — read-only, grouped by project, user-level ones last. Use it when the user asks what an agent already knows or remembers about a project, or to reuse another agent's notes: decisions, conventions, gotchas. Each entry ends with a `wake://memory/<key>` reference; read one with wake_get_session.",+ "description": "The memory files coding agents keep for themselves on this machine — Claude Code's and ZCode's per-project auto-memory (MEMORY.md and its topic files), Codex's memories — plus the instruction files the user keeps for them (CLAUDE.md, AGENTS.md, GEMINI.md, .cursor/rules, .kiro/steering, copilot-instructions.md), read-only, grouped by project, user memory (the notes that apply to every project) last. Use it when the user asks what an agent already knows or remembers about a project, or to reuse another agent's notes: decisions, conventions, gotchas. Each entry ends with a `wake://memory/<key>` reference; read one with wake_get_session.","inputSchema": {"type": "object","properties": {@@ -613,7 +613,7 @@ fn search(ctx: &ToolContext, args: &Value) -> ToolResult {let (project, unmatched) = memory_project_scope(ctx, args)?;if let Some(text) = unmatched {// 会话没有这个项目,但用户级记忆对每个项目都成立——提示之余照样查一遍- let memory = memory_hits_section(ctx, query, &agents, &project)?;+ let memory = memory_hits_section(ctx, query, &agents, &project, since)?;let mut out = text;if !memory.is_empty() {// 提示文本不带收尾换行,记忆段自带前导空行;没命中就一字不加@@ -646,7 +646,7 @@ fn search(ctx: &ToolContext, args: &Value) -> ToolResult {}let scope = scope_note(&project, &agents, since, false);// 记忆命中是另一类数据,不与会话命中混排,作为尾巴附在两种结果后面- let memory = memory_hits_section(ctx, query, &agents, &project)?;+ let memory = memory_hits_section(ctx, query, &agents, &project, since)?;let mut out = String::new();if order.is_empty() {out.push_str(&format!("No session matches `{query}`{scope}.\n"));@@ -719,13 +719,17 @@ fn memory_hits_section(query: &str,agents: &[AgentId],project: &Option<Vec<String>>,+ since: Option<i64>,) -> Result<String, ToolError> {+ // since 同样约束记忆命中:说了 "in the last 24 hours" 就不能跟着几个月前的笔记let hits = ctx.store.search_memories(query,&MemoryFilter {agents: agents.to_vec(),project_paths: project.clone().unwrap_or_default(),unattributed: false,+ user: UserMemories::Alongside,+ updated_since: since,limit: MEMORY_HITS_IN_SEARCH,},)?;@@ -751,7 +755,7 @@ fn memory_hits_section(fn memory_label(d: &MemoryDoc) -> String {// 标题入库时已按 MEMORY_TITLE_MAX 折行封顶;老库里的行要等文件变了才重读,这里再兜一道let mut s = format!(- "{} · {} · {}",+ "{} · {} · {} memory",one_line(&d.title, crate::adapters::MEMORY_TITLE_MAX),d.agent.display_name(),d.scope.label()@@ -765,7 +769,7 @@ fn memory_label(d: &MemoryDoc) -> String {/// 记忆归属哪一组(列表的组头、搜索命中的归属都用它);分组判据在 `MemoryDoc::group`fn memory_group(d: &MemoryDoc) -> String {match d.group() {- MemoryGroup::User => "User-level (applies to every project)".to_string(),+ MemoryGroup::User => "User memory (applies to every project)".to_string(),MemoryGroup::Unknown => "Unknown project".to_string(),MemoryGroup::Project { path, name } => format!("{path} — {name}"),}@@ -788,6 +792,8 @@ fn list_memories(ctx: &ToolContext, args: &Value) -> ToolResult {agents: agents.clone(),project_paths: project.clone().unwrap_or_default(),unattributed: false,+ user: UserMemories::Alongside,+ updated_since: None,limit,})?;let scope = scope_note(&project, &agents, None, false);@@ -795,18 +801,18 @@ fn list_memories(ctx: &ToolContext, args: &Value) -> ToolResult {if let Some(text) = unmatched {let first_line = text.lines().next().unwrap_or_default();out.push_str(&format!(- "{first_line} Only user-level memory files, which apply everywhere, are listed below.\n\n"+ "{first_line} Only user memory, which applies everywhere, is listed below.\n\n"));}if docs.is_empty() {out.push_str(&format!(- "No memory files{scope}. Claude Code writes them under ~/.claude/projects/<project>/memory/ once it has saved something about a project; Codex keeps its own under ~/.codex/memories/; ZCode under ~/.zcode/cli/memories/projects/. Wake only lists what is there.\n\n"+ "No memory files{scope}. Claude Code writes them under ~/.claude/projects/<project>/memory/ once it has saved something about a project; Codex keeps its own under ~/.codex/memories/; ZCode under ~/.zcode/cli/memories/projects/; instruction files such as CLAUDE.md or AGENTS.md are listed from the project roots Wake has sessions for. Wake only lists what is there.\n\n"));out.push_str(&index_note(ctx.store));return Ok(out);}out.push_str(&format!(- "{} memory file{}{scope}, grouped by project (user-level last; the limit applies to project-level files, user-level ones are always included).\n",+ "{} memory file{}{scope}, grouped by project (user memory last; the limit applies to project memory, user memory is always included).\n",docs.len(),plural(docs.len() as i64)));@@ -864,7 +870,7 @@ fn get_memory(ctx: &ToolContext, key: &str, args: &Value) -> ToolResult {fmt_time(Some(doc.updated_at)),doc.path));- let (text, truncated) = crate::adapters::parse_utils::clip(&body, max_chars);+ let (text, truncated) = crate::adapters::parse_utils::clip_chars(&body, max_chars);out.push_str(&text);if !text.ends_with('\n') {out.push('\n');diff --git a/crates/wake-core/src/models.rs b/crates/wake-core/src/models.rsindex c111e36..55901be 100644--- a/crates/wake-core/src/models.rs+++ b/crates/wake-core/src/models.rs@@ -641,15 +641,20 @@ pub struct MemoryDoc {/// epoch mspub updated_at: i64,pub size_bytes: i64,+ /// 来自哪个来源(`MemorySource::id`):Settings 的计数、停用后的出库、读失败时的+ /// 冻结都按它+ pub source: String,/// 正文原样(含 frontmatter);文件型阅读时先读磁盘,这份是索引与兜底pub body: String,}-/// Memory 页侧栏的导航计数:总数、按 agent、按解析出的项目(用户级记忆只计入-/// 总数与 agent,不属于任何项目;没归属的记在 path 为空的那一项)+/// Memory 页侧栏的导航计数:总数、用户级、按 agent、按解析出的项目(用户级记忆计入+/// 总数、`user` 与 agent,不属于任何项目;没归属的记在 path 为空的那一项)#[derive(Debug, Clone, Default)]pub struct MemoryCounts {pub total: i64,+ /// 用户级(侧栏的 User memory 行)+ pub user: i64,pub agents: Vec<(AgentId, i64)>,pub projects: Vec<MemoryProject>,}@@ -718,26 +723,123 @@ impl MemoryScope {}}- /// 人读标签(MCP 输出用;UI 另过 t())+ /// 人读标签(MCP 输出用;UI 另过 t()),后面接 " memory":User memory / Project+ /// memory / Session memory——沿用 Claude Code 文档的说法(用户 2026-09-21 定)pub fn label(self) -> &'static str {match self {- Self::User => "user-level",+ Self::User => "user",Self::Project => "project",Self::Thread => "session",}}}+/// 记忆来源的形态+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum MemorySourceKind {+ /// 按项目目录的记忆树:`<dir>/<项目目录>/memory/*.md`(Claude auto-memory,ZCode 同形)+ ProjectTree,+ /// 一个目录直属的 `*.<ext>`(Codex 的 memories、`~/.codex/rules/*.rules`)+ Dir { ext: &'static str },+ /// 单个文件(`~/.claude/CLAUDE.md`、`~/.codex/AGENTS.md`、`~/.gemini/GEMINI.md`)+ File,+ /// 用户添加的路径:是目录就读直属 `*.md`,是文件就读它自己——**读的时候才看形状**+ /// (构造不摸磁盘,与别的来源"不看存不存在"同规矩;曾在构造时按 `is_file()` 定成+ /// Dir / File,2026-09-22 /simplify)+ Custom,+ /// Codex memories_1.sqlite 的逐线程摘要+ ThreadDb,+ /// 每个已索引的本地项目根下的一个文件:`<project>/<rel>`+ ProjectFile,+ /// 每个已索引的本地项目根下的一个目录:`<project>/<rel>/*.<ext>`+ ProjectDir { ext: &'static str },+}++/// 记忆的一个来源 = Settings → Memory locations 的一行。各家 adapter 按自己的根报默认+/// 来源(不看存不存在),项目模式由 `adapters::project_instruction_sources` 按 agent+/// 给;用户可停用默认来源、添加自定义的目录或文件(store 记偏离,scanner 每轮按+/// 配置裁决后交给 `list_memories`)。不区分"agent 记的"与"用户写的指令"——曾有过+/// origin 字段与 instructions 徽章,文件名本身已说明身份,用户 2026-09-21 定拿掉+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct MemorySource {+ pub agent: AgentId,+ pub kind: MemorySourceKind,+ /// 目录 / 文件 / 库的绝对路径;项目模式是相对项目根的路径(`CLAUDE.md`、`.cursor/rules`)+ pub path: std::path::PathBuf,+}++impl MemorySource {+ pub fn is_pattern(&self) -> bool {+ matches!(+ self.kind,+ MemorySourceKind::ProjectFile | MemorySourceKind::ProjectDir { .. }+ )+ }++ /// 层级由形态决定:全局目录 / 文件 / 自定义路径是用户级(对每个项目都成立),记忆树+ /// 与项目模式是项目级,线程库是会话级——曾是独立字段,每个构造点填的都是 kind 蕴含+ /// 的值(2026-09-22 /simplify)+ pub fn scope(&self) -> MemoryScope {+ match self.kind {+ MemorySourceKind::Dir { .. } | MemorySourceKind::File | MemorySourceKind::Custom => {+ MemoryScope::User+ }+ MemorySourceKind::ProjectTree+ | MemorySourceKind::ProjectFile+ | MemorySourceKind::ProjectDir { .. } => MemoryScope::Project,+ MemorySourceKind::ThreadDb => MemoryScope::Thread,+ }+ }++ /// 稳定标识:停用记录、memories.source 列、按来源冻结与计数都用它。项目模式带+ /// `<project>/` 前缀,具体路径就是路径本身+ pub fn id(&self) -> String {+ let path = self.path.to_string_lossy();+ if self.is_pattern() {+ format!("<project>/{path}")+ } else {+ path.to_string()+ }+ }++ /// 用户添加的来源(Settings → Memory locations 的 Add location):目录或文件,读时才看+ pub fn custom(agent: AgentId, path: std::path::PathBuf) -> Self {+ Self {+ agent,+ kind: MemorySourceKind::Custom,+ path,+ }+ }+}++/// 用户记忆(对每个项目都成立)在一次筛选里怎么算——它是唯一带特殊语义的层级+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum UserMemories {+ /// 照列,项目筛选下也放行:MCP 的口径,问一个项目的记忆连用户记忆一起给+ #[default]+ Alongside,+ /// 不列:GUI 的项目行只算项目记忆(用户 2026-09-22 定)+ Excluded,+ /// 只列用户记忆:GUI 侧栏的 User memory 行+ Only,+}+/// 记忆列表/搜索的筛选面(Memory 页与 wake_list_memories / wake_search 共用)#[derive(Debug, Clone, Default)]pub struct MemoryFilter {pub agents: Vec<AgentId>,- /// 项目路径并集;空串不匹配任何东西。用户级记忆对每个项目都成立,任何项目筛选- /// 下都列出+ /// 项目路径并集;空串不匹配任何东西。用户级记忆对每个项目都成立,`user` 默认+ /// (Alongside)下任何项目筛选都列出它pub project_paths: Vec<String>,/// 只要没归属(项目解析不出)的那一组——GUI 侧栏的 Unknown project 行;与/// `project_paths` 一起时取并集。显式一位,不拿空串当暗号pub unattributed: bool,+ /// 用户级记忆进不进这次筛选+ pub user: UserMemories,+ /// 只要这个时刻(epoch ms)之后更新过的;None = 不限。wake_search 的 `since` 也约束+ /// 记忆命中——否则 "No session matches … in the last 24 hours" 后面跟着几个月前的+ /// 笔记(2026-09-22 review)+ pub updated_since: Option<i64>,/// 0 = 不限pub limit: i64,}diff --git a/crates/wake-core/src/remote.rs b/crates/wake-core/src/remote.rsindex 71250ef..a8c63ef 100644--- a/crates/wake-core/src/remote.rs+++ b/crates/wake-core/src/remote.rs@@ -68,10 +68,13 @@ pub const REMOTE_LAYOUTS: &[RemoteAgentLayout] = &[".codex/archived_sessions",".codex/state_5.sqlite",".codex/state_5.sqlite-wal",- // 记忆:用户级 Markdown 与逐线程的整合库(list_memories 读)+ // 记忆:用户级 Markdown 与逐线程的整合库(list_memories 读);全局指令+ // AGENTS.md 与 rules/*.rules 同属 home 直属、不是凭证".codex/memories",".codex/memories_1.sqlite",".codex/memories_1.sqlite-wal",+ ".codex/AGENTS.md",+ ".codex/rules",],exclude: &[],},diff --git a/crates/wake-core/src/scanner.rs b/crates/wake-core/src/scanner.rsindex c71fa56..eb46b5b 100644--- a/crates/wake-core/src/scanner.rs+++ b/crates/wake-core/src/scanner.rs@@ -162,6 +162,19 @@ pub fn run_scan(result}+/// 只同步记忆、不碰会话:Memory 页的 Refresh 与 Settings → Memory locations 变更的+/// 收尾(用户 2026-09-22 定"memory 的只刷 memory、session 的只刷 session,不然设置里+/// 分开的 locations 就没意义")。读的是当下的 Memory locations 配置(停用 / 自定义 /+/// 项目模式),与扫描收尾那一步是同一个函数;过同一把 `SCAN_GATE` 与进行中的扫描+/// 串行——它收尾也对 memories 对账,两边别同时写同一组。阻塞执行,调用方放后台;+/// 返回库里有没有改动+pub fn run_memory_sync(adapters: &[Box<dyn AgentAdapter>], store: &Arc<Store>) -> bool {+ let _gate = SCAN_GATE+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ sync_memories(adapters, store)+}+/// 写事务内副本裁决(`Store::write_session_guarded`)用的位次查询:按 file_path/// 找拥有它的实例取 `dedup_rank`;无实例认领的路径落到该家首个实例——与枚举/// 时的候选排序同一把尺子,全量与增量两条写库路径才给出同一个胜者@@ -491,38 +504,92 @@ fn run_scan_inner(/// 整组清掉——否则它们的记忆在会话与缓存都没了之后还能被列出、搜到(Codex review/// 2026-09-17)fn sync_memories(adapters: &[Box<dyn AgentAdapter>], store: &Arc<Store>) -> bool {- /// 一组的收集结果:读成功的实例给文档,读失败的实例给它的根(那些根下的行冻结)+ /// 一组的收集结果:读成功的实例给文档,读失败的实例给它的来源 id(那些来源的行冻结)#[derive(Default)]struct Group {docs: Vec<MemoryDoc>,- frozen: Vec<std::path::PathBuf>,+ frozen: Vec<String>,succeeded: usize,failed: usize,}+ // 三样配置都从库里读:读不出就整轮不动——这一步的本质是"按缺席删",把读失败折成+ // "什么都没配置"会删光项目指令文件、把停用的来源重新索引进来(2026-09-22 review)+ let projects = match store.local_project_roots() {+ Ok(v) => v,+ Err(e) => {+ eprintln!("[scanner] memory sync skipped: project roots unreadable: {e}");+ return false;+ }+ };+ let (customs, disabled) = match store.memory_source_overrides() {+ Ok(v) => v,+ Err(e) => {+ eprintln!("[scanner] memory sync skipped: memory locations unreadable: {e}");+ return false;+ }+ };+ let stored: std::collections::HashSet<(AgentId, String)> = match store.memory_groups() {+ Ok(v) => v.into_iter().collect(),+ Err(e) => {+ eprintln!("[scanner] memory sync skipped: memory groups unreadable: {e}");+ return false;+ }+ };+ // 项目模式(`<project>/CLAUDE.md`)在已索引的本地项目根上展开;停用与自定义来源来自+ // Settings → Memory locations,按实例裁决只在 `memory_source_plan`(Settings 面板与+ // 表单查重看的是同一份)+ let plan = crate::adapters::memory_source_plan(adapters, &customs, &disabled);let mut groups: std::collections::BTreeMap<(AgentId, String), Group> =std::collections::BTreeMap::new();- for (agent, host) in store.memory_groups().unwrap_or_default() {- groups.entry((agent, host)).or_default();+ for key in &stored {+ groups.entry(key.clone()).or_default();}- for adapter in adapters {+ for planned in plan {let group = groups- .entry((adapter.agent(), adapter.host().to_string()))+ .entry((planned.agent, planned.host.clone())).or_default();- match adapter.list_memories() {- Ok(docs) => {- group.docs.extend(docs);- group.succeeded += 1;- }- Err(e) => {- // 同 (agent, host) 的别的实例(默认根 + 自定义根)照常对账,只冻结这个- // 实例根下的行——原先一个实例失败就整组不写,一个坏 location 会让默认- // 实例的记忆永远停在上次(2026-09-21 review)- eprintln!(- "[scanner] memories of {} failed: {e}",- adapter.agent().as_str()- );- group.frozen.extend(adapter.memory_roots());- group.failed += 1;+ let enabled: Vec<MemorySource> = planned+ .sources+ .into_iter()+ .filter(|p| p.enabled)+ .map(|p| p.source)+ .collect();+ if enabled.is_empty() {+ // 没有来源(或全停用)的实例什么都不贡献,但这一组照常对账——停用的来源+ // 的行要随之出库+ group.succeeded += 1;+ continue;+ }+ // 逐来源读:一个来源读失败只冻结它自己的行——挂空的符号链接、TCC 挡住的项目根+ // 不该让整家的记忆停更(2026-09-22 review);缓存按来源分槽,逐个调不比整批贵。+ // 远程实例不展开项目模式(项目根是本机路径):RemoteAdapter 自己给 inner 传空+ for source in enabled {+ let one = std::slice::from_ref(&source);+ let read = match planned.adapter {+ Some(ix) => adapters[ix].list_memories(one, &projects),+ // 该家没有本地实例(会话 location 全停用):项目指令文件与自定义路径照读;+ // 没有实例就没处放缓存,这种配置少见、每轮重读+ None => crate::adapters::generic_memory_docs(+ &crate::adapters::MemoryCache::new(),+ planned.agent,+ one,+ &projects,+ ),+ };+ match read {+ Ok(docs) => {+ group.docs.extend(docs);+ group.succeeded += 1;+ }+ Err(e) => {+ eprintln!(+ "[scanner] memories of {} ({}) failed: {e}",+ planned.agent.as_str(),+ source.id()+ );+ group.frozen.push(source.id());+ group.failed += 1;+ }}}}@@ -532,6 +599,14 @@ fn sync_memories(adapters: &[Box<dyn AgentAdapter>], store: &Arc<Store>) -> boolif group.succeeded == 0 && group.failed > 0 {continue;}+ // 没读到文档、没有冻结、库里也没有这一组:没有账可对,别为二十个实例各开一个+ // 写事务(2026-09-22 /simplify)+ if group.docs.is_empty()+ && group.frozen.is_empty()+ && !stored.contains(&(agent, host.clone()))+ {+ continue;+ }match store.replace_memories(agent, &host, &group.docs, &group.frozen) {Ok(c) => changed |= c,Err(e) => eprintln!(@@ -622,7 +697,10 @@ fn sync_parent_links(adapters: &[Box<dyn AgentAdapter>], store: &Arc<Store>) ->// 上一轮没认领的 child,只要 parent 确实在库里就接受——先来后到按// roster 顺序,权威那一轮的结论不会被这一轮盖掉for (adapter_ix, links) in links_by_adapter.iter().enumerate() {- if adapters[adapter_ix].agent() != agent {+ // 只对全局总表(Codex)放开:location 级边车(Grok)仍只认"报边者拥有 parent",+ // 否则备份目录里过期的边车会把用户已解除的关系每轮重新挂上(2026-09-22 review)+ if adapters[adapter_ix].agent() != agent || !adapters[adapter_ix].parent_links_global()+ {continue;}for (child, parent) in links {diff --git a/crates/wake-core/tests/adapter_contracts.rs b/crates/wake-core/tests/adapter_contracts.rsindex a405f1c..6161f14 100644--- a/crates/wake-core/tests/adapter_contracts.rs+++ b/crates/wake-core/tests/adapter_contracts.rs@@ -57,6 +57,12 @@ static ENV: OnceLock<TestEnv> = OnceLock::new();/// 所有测试的第一步:建假 HOME(含 SQLite fixture 库与 gemini 的/// projects.json)并把 HOME 指过去。必须先于任何 Adapter::new()。+/// 读一个 adapter 的全部默认来源(项目模式除外——那要项目根);契约测试里的+/// "list_memories()" 就是它+fn all_memories(adapter: &Box<dyn AgentAdapter>) -> anyhow::Result<Vec<MemoryDoc>> {+ adapter.list_memories(&adapter.memory_sources(), &[])+}+fn setup() -> &'static TestEnv {ENV.get_or_init(|| {let home = tempfile::Builder::new()@@ -3690,9 +3696,12 @@ fn workbuddy_is_a_codebuddy_twin() {fn claude_lists_project_memories() {setup();let adapter = ClaudeAdapter::new().with_custom_root(fixture("claude/projects"));- let docs = adapter.list_memories().unwrap();+ let docs = all_memories(&adapter).unwrap();let titles: Vec<&str> = docs.iter().map(|d| d.title.as_str()).collect();- assert_eq!(titles, ["MEMORY", "Wake testing conventions for this repo"]);+ assert_eq!(+ titles,+ ["MEMORY.md", "Wake testing conventions for this repo"]+ );let session_keys: Vec<String> = adapter.list_session_files().unwrap()@@ -3725,7 +3734,7 @@ fn claude_lists_project_memories() {"正文原样含 frontmatter");assert!(docs[1].body.contains("name: wake-testing"));- assert_eq!(adapter.list_memories().unwrap(), docs, "指纹没变走缓存");+ assert_eq!(all_memories(&adapter).unwrap(), docs, "指纹没变走缓存");}/// ZCode:`cli/memories/projects/<slug>-<hash>/memory/*.md`(Claude auto-memory 同款@@ -3761,7 +3770,7 @@ fn zcode_lists_project_memories() {fs::create_dir_all(root.join("cli/memories/projects/empty-1111111111111111")).unwrap();let adapter = ZcodeAdapter::new().with_custom_root(root.clone());- let docs = adapter.list_memories().unwrap();+ let docs = all_memories(&adapter).unwrap();let summary: Vec<(&str, &str, &str)> = docs.iter().map(|d| {@@ -3775,8 +3784,8 @@ fn zcode_lists_project_memories() {assert_eq!(summary,[- ("note", "", ""),- ("MEMORY", "/Users/tester/Github/wakefx", "wakefx"),+ ("note.md", "", ""),+ ("MEMORY.md", "/Users/tester/Github/wakefx", "wakefx"),("Prefers pnpm over npm","/Users/tester/Github/wakefx",@@ -3800,7 +3809,7 @@ fn zcode_lists_project_memories() {docs[2].body.contains("name: prefers-pnpm"),"正文原样含 frontmatter");- assert_eq!(adapter.list_memories().unwrap(), docs, "指纹没变走缓存");+ assert_eq!(all_memories(&adapter).unwrap(), docs, "指纹没变走缓存");assert_eq!(wake_core::adapters::zcode::memory_dir_hash("/Users/tester/Github/wakefx/"),"3b44ec0d2ccabf78",@@ -3809,11 +3818,221 @@ fn zcode_lists_project_memories() {// 直接选中 db.sqlite 的裸库拷贝没有 home:不摸父目录,一份都不列let bare = ZcodeAdapter::new().with_custom_root(db.clone());- assert!(bare.list_memories().unwrap().is_empty());+ assert!(all_memories(&bare).unwrap().is_empty());// 没有记忆目录的 home 也是空,不是错let other = tempfile::tempdir().unwrap();let fresh = ZcodeAdapter::new().with_custom_root(other.path().join(".zcode"));- assert!(fresh.list_memories().unwrap().is_empty());+ assert!(all_memories(&fresh).unwrap().is_empty());+}++/// 记忆可见层二期:用户写给 agent 的指令文件也进记忆层——各家 home 里的全局文件+/// (`~/.claude/CLAUDE.md`、`~/.codex/AGENTS.md` + `rules/*.rules`、`~/.gemini/GEMINI.md`)+/// 由各家 `memory_sources` 报,项目根下的(CLAUDE.md / AGENTS.md / GEMINI.md /+/// `.cursor/rules/*.mdc` / `.cursorrules` / `.kiro/steering/*.md` /+/// `.github/copilot-instructions.md`)由 `project_instruction_sources` 按 agent 给、+/// 按已索引的项目根展开。标题是文件名(mdc 有 frontmatter 的取 description),+/// 项目级的 project_path 直接填项目根,来源 id 带 `<project>/` 前缀+#[test]+fn instruction_files_join_the_memory_layer() {+ setup();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ let write_under = |root: &std::path::Path, rel: &str, body: &str| {+ let path = root.join(rel);+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ fs::write(path, body).unwrap();+ };+ let w = |rel: &str, body: &str| write_under(home.path(), rel, body);+ let pw = |rel: &str, body: &str| write_under(project.path(), rel, body);+ w(".claude/CLAUDE.md", "# global claude\n");+ fs::create_dir_all(home.path().join(".claude/projects")).unwrap();+ w(".codex/AGENTS.md", "# global agents\n");+ w(+ ".codex/rules/safety.rules",+ "prefix_rule(prefix=[\"rm\"], decision=\"forbidden\")\n",+ );+ fs::create_dir_all(home.path().join(".codex/sessions")).unwrap();+ w(+ ".gemini/GEMINI.md",+ "## Gemini Added Memories\n- uses supastarter\n",+ );+ fs::create_dir_all(home.path().join(".gemini/tmp")).unwrap();+ pw("CLAUDE.md", "# project claude\n");+ pw("AGENTS.md", "# project agents\n");+ pw("GEMINI.md", "# project gemini\n");+ pw(+ ".cursor/rules/style.mdc",+ "---\ndescription: Use tabs, never spaces\nglobs: *.ts\nalwaysApply: false\n---\n\nTabs.\n",+ );+ pw(".cursorrules", "legacy rules\n");+ pw(".kiro/steering/product.md", "# product\n");+ pw(".github/copilot-instructions.md", "# copilot\n");+ let projects = vec![project.path().to_path_buf()];+ let project_str = project.path().to_string_lossy().to_string();++ // (adapter, 期望的 (标题, scope, 来源 id) 列表——项目级的来源 id 带 <project>/ 前缀)+ let claude = ClaudeAdapter::new().with_custom_root(home.path().join(".claude"));+ let codex = CodexAdapter::new().with_custom_root(home.path().join(".codex"));+ let gemini = GeminiAdapter::new().with_custom_root(home.path().join(".gemini"));+ let cursor = CursorAdapter::new().with_custom_root(project.path().join("nowhere"));+ let kiro = KiroAdapter::new().with_custom_root(project.path().join("nowhere"));+ let copilot = CopilotAdapter::new().with_custom_root(project.path().join("nowhere"));+ let cases: Vec<(&Box<dyn AgentAdapter>, Vec<(&str, MemoryScope, String)>)> = vec![+ (+ &claude,+ vec![+ (+ "CLAUDE.md",+ MemoryScope::User,+ home.path()+ .join(".claude/CLAUDE.md")+ .to_string_lossy()+ .to_string(),+ ),+ (+ "CLAUDE.md",+ MemoryScope::Project,+ "<project>/CLAUDE.md".into(),+ ),+ ],+ ),+ (+ &codex,+ vec![+ (+ "AGENTS.md",+ MemoryScope::User,+ home.path()+ .join(".codex/AGENTS.md")+ .to_string_lossy()+ .to_string(),+ ),+ (+ "safety.rules",+ MemoryScope::User,+ home.path()+ .join(".codex/rules")+ .to_string_lossy()+ .to_string(),+ ),+ (+ "AGENTS.md",+ MemoryScope::Project,+ "<project>/AGENTS.md".into(),+ ),+ ],+ ),+ (+ &gemini,+ vec![+ (+ "GEMINI.md",+ MemoryScope::User,+ home.path()+ .join(".gemini/GEMINI.md")+ .to_string_lossy()+ .to_string(),+ ),+ (+ "GEMINI.md",+ MemoryScope::Project,+ "<project>/GEMINI.md".into(),+ ),+ ],+ ),+ (+ &cursor,+ vec![+ (+ "Use tabs, never spaces",+ MemoryScope::Project,+ "<project>/.cursor/rules".into(),+ ),+ (+ ".cursorrules",+ MemoryScope::Project,+ "<project>/.cursorrules".into(),+ ),+ ],+ ),+ (+ &kiro,+ vec![(+ "product.md",+ MemoryScope::Project,+ "<project>/.kiro/steering".into(),+ )],+ ),+ (+ &copilot,+ vec![(+ "copilot-instructions.md",+ MemoryScope::Project,+ "<project>/.github/copilot-instructions.md".into(),+ )],+ ),+ ];+ for (adapter, expected) in cases {+ let agent = adapter.agent();+ let mut sources = adapter.memory_sources();+ sources.extend(wake_core::adapters::project_instruction_sources(agent));+ // 这些临时 home 里没有 agent 自己记的记忆,列出来的全是指令文件+ let docs: Vec<MemoryDoc> = adapter.list_memories(&sources, &projects).unwrap();+ let got: Vec<(&str, MemoryScope, String)> = docs+ .iter()+ .map(|d| (d.title.as_str(), d.scope, d.source.clone()))+ .collect();+ assert_eq!(got, expected, "{}", agent.as_str());+ for d in &docs {+ assert_eq!(d.agent, agent);+ assert!(+ d.key.starts_with(&format!("{}:", agent.as_str())),+ "{}",+ d.key+ );+ assert!(d.session_key.is_empty(), "指令文件不用锚点");+ if d.scope == MemoryScope::Project {+ assert_eq!(d.project_path, project_str, "项目根直接填进归属");+ assert!(!d.project_name.is_empty());+ } else {+ assert!(d.project_path.is_empty());+ }+ }+ }+ // 项目根就是某家的 home(用户在 ~/.codex 里跑过 codex):`<project>/AGENTS.md` 展开成+ // 全局那份同一个文件,不能把用户级顶成 ".codex" 项目的——具体来源优先,模式跳过+ let mut sources = codex.memory_sources();+ sources.extend(wake_core::adapters::project_instruction_sources(+ AgentId::Codex,+ ));+ let agents_md = home.path().join(".codex/AGENTS.md");+ let docs = codex+ .list_memories(+ &sources,+ &[home.path().join(".codex"), project.path().to_path_buf()],+ )+ .unwrap();+ let same_file: Vec<&MemoryDoc> = docs+ .iter()+ .filter(|d| d.path == agents_md.to_string_lossy())+ .collect();+ assert_eq!(same_file.len(), 1, "{same_file:?}");+ assert_eq!(same_file[0].scope, MemoryScope::User);+ assert_eq!(same_file[0].source, agents_md.to_string_lossy());++ // 项目根传空(远程实例、自定义根)时项目模式什么都不展开,全局的照列+ let mut sources = claude.memory_sources();+ sources.extend(wake_core::adapters::project_instruction_sources(+ AgentId::ClaudeCode,+ ));+ let global_only = claude.list_memories(&sources, &[]).unwrap();+ assert_eq!(global_only.len(), 1);+ // 裸 projects 目录当根:没有 home,全局 CLAUDE.md 不摸父目录+ let bare = ClaudeAdapter::new().with_custom_root(home.path().join(".claude/projects"));+ assert!(bare+ .memory_sources()+ .iter()+ .all(|s| s.kind == MemorySourceKind::ProjectTree));}/// 标题来自 frontmatter 的 description:块标量(`description: >` 换行缩进写)折成一行,@@ -3841,7 +4060,7 @@ fn memory_titles_fold_block_scalars_and_clip() {).unwrap();let adapter = ClaudeAdapter::new().with_custom_root(root.path().to_path_buf());- let docs = adapter.list_memories().unwrap();+ let docs = all_memories(&adapter).unwrap();let titles: Vec<&str> = docs.iter().map(|d| d.title.as_str()).collect();assert_eq!(titles[0], "Prefers pnpm over npm, and never runs db:push");assert!(@@ -3871,7 +4090,7 @@ fn claude_memory_anchor_skips_empty_sessions() {).unwrap();let adapter = ClaudeAdapter::new().with_custom_root(root.path().to_path_buf());- let docs = adapter.list_memories().unwrap();+ let docs = all_memories(&adapter).unwrap();assert_eq!(docs.len(), 1);assert_eq!(docs[0].session_key,@@ -3910,7 +4129,7 @@ fn codex_lists_user_and_thread_memories() {drop(db);let adapter = CodexAdapter::new().with_custom_root(home.path().to_path_buf());- let docs = adapter.list_memories().unwrap();+ let docs = all_memories(&adapter).unwrap();assert_eq!(docs.len(), 3, "空摘要空记忆的线程不列: {docs:?}");// 列的可空性与时间格式是推断的:NULL 正文列与 ISO 文本时间的行照样列,别的行不受影响let nullable = &docs[2];@@ -3922,7 +4141,7 @@ fn codex_lists_user_and_thread_memories() {let user = &docs[0];assert_eq!((user.scope, user.title.as_str()),- (MemoryScope::User, "user-preferences")+ (MemoryScope::User, "user-preferences.md"));assert!(user.project_path.is_empty() && user.session_key.is_empty());let thread = &docs[1];@@ -3940,12 +4159,12 @@ fn codex_lists_user_and_thread_memories() {[0xff, 0xfe, 0x00],).unwrap();- let docs_again = adapter.list_memories().unwrap();+ let docs_again = all_memories(&adapter).unwrap();assert_eq!(docs_again.len(), 3, "{docs_again:?}");// 自定义根只选了 sessions 目录:没有 home,不摸父目录里的 memorieslet sessions_only = CodexAdapter::new().with_custom_root(home.path().join("sessions"));assert!(- sessions_only.list_memories().unwrap().is_empty(),+ all_memories(&sessions_only).unwrap().is_empty(),"sessions 目录当根时不得越界读父目录的记忆");// 库在但读不出(不是 SQLite 文件)= 不知道:整家报 Err、不缓存,scanner 跳过该组;@@ -3954,11 +4173,11 @@ fn codex_lists_user_and_thread_memories() {let good = fs::read(&db_path).unwrap();fs::write(&db_path, b"not a sqlite database").unwrap();assert!(- adapter.list_memories().is_err(),+ all_memories(&adapter).is_err(),"memories_1.sqlite 读不出必须报 Err 而不是当成空");fs::write(&db_path, good).unwrap();- assert_eq!(adapter.list_memories().unwrap().len(), 3);+ assert_eq!(all_memories(&adapter).unwrap().len(), 3);assert!(thread.path.ends_with("memories_1.sqlite#t-0001"),"{}",@@ -3968,5 +4187,17 @@ fn codex_lists_user_and_thread_memories() {// 没有 home 证据的目录:memories 自然为空,不报错let bare = CodexAdapter::new().with_custom_root(home.path().join("elsewhere"));- assert!(bare.list_memories().unwrap().is_empty());+ assert!(all_memories(&bare).unwrap().is_empty());+}++/// 没装 Hermes / Cursor(库不在、表不在)= **确定没有**父子关系(Some 空);只有库在但读不出+/// 才是"不知道"(None)。原先一律 None,没装这两家的机器每轮都把它们(本地真实的 /branch、+/// 子代理)的关系冻住、永不自愈(2026-09-22 review)+#[test]+fn missing_parent_link_stores_mean_no_links_not_unknown() {+ let dir = tempfile::tempdir().unwrap();+ let hermes = HermesAdapter::new().with_custom_root(dir.path().join("nope"));+ assert_eq!(hermes.parent_links(), Some(Vec::new()));+ let cursor = CursorIdeAdapter::new().with_custom_root(dir.path().join("cursor-nope"));+ assert_eq!(cursor.parent_links(), Some(Vec::new()));}diff --git a/crates/wake-core/tests/db_roundtrip.rs b/crates/wake-core/tests/db_roundtrip.rsindex 0022a45..ee2d585 100644--- a/crates/wake-core/tests/db_roundtrip.rs+++ b/crates/wake-core/tests/db_roundtrip.rs@@ -1236,6 +1236,7 @@ fn memory_limit_keeps_user_level_and_counts_and_snippets_agree() {title: key.to_string(),updated_at: updated,size_bytes: body.len() as i64,+ source: String::new(),body: body.to_string(),};let docs = vec![@@ -1302,18 +1303,21 @@ fn memory_limit_keeps_user_level_and_counts_and_snippets_agree() {let counts = store.memory_counts().unwrap();assert_eq!(counts.total, 4);+ assert_eq!(counts.user, 1);assert_eq!(counts.projects.iter().map(|p| (p.path.as_str(), p.count)).collect::<Vec<_>>(),- [("/work/app", 4)],- "项目行的计数含用户级"+ [("/work/app", 3)],+ "项目行只数项目记忆,用户记忆有自己的一行");+ // GUI 的项目行:用户记忆不混进来,徽章 == 点开的行数let opened = store.list_memories(&MemoryFilter {project_paths: vec!["/work/app".into()],+ user: UserMemories::Excluded,..Default::default()}).unwrap();@@ -1322,6 +1326,15 @@ fn memory_limit_keeps_user_level_and_counts_and_snippets_agree() {counts.projects[0].count,"徽章 == 点开的行数");+ // GUI 的 User memory 行:只列用户记忆,徽章同样 == 行数+ let user_only = store+ .list_memories(&MemoryFilter {+ user: UserMemories::Only,+ ..Default::default()+ })+ .unwrap();+ assert_eq!(keys(&user_only), ["claude-code:/m/u.md"]);+ assert_eq!(user_only.len() as i64, counts.user);// 2 个码点走 LIKE 降级;Ω 小写成 ω 后字节数变了,原先拿小写串的字节偏移切原文会 paniclet hits = store@@ -1329,6 +1342,82 @@ fn memory_limit_keeps_user_level_and_counts_and_snippets_agree() {.unwrap();assert_eq!(hits.len(), 1);assert!(hits[0].snippet.contains("二维"), "{}", hits[0].snippet);++ // since 也约束记忆命中(wake_search 说了 "in the last …" 就不能跟着旧笔记):p2 的+ // updated_at 是 2+ let since = |t: i64| MemoryFilter {+ updated_since: Some(t),+ ..Default::default()+ };+ assert!(store+ .search_memories("second", &since(3))+ .unwrap()+ .is_empty());+ assert_eq!(store.search_memories("second", &since(2)).unwrap().len(), 1);+}++/// 记忆来源配置(Settings → Memory locations)往返:自定义增删改、停用开关、+/// Restore defaults;`local_project_roots` 只给本地会话的项目根+#[test]+fn memory_source_overrides_roundtrip() {+ let dir = tempfile::tempdir().unwrap();+ let store = Store::open(&dir.path().join("t.db")).unwrap();+ store.add_memory_source("claude-code", "/notes/a").unwrap();+ store.add_memory_source("claude-code", "/notes/a").unwrap();+ store.add_memory_source("codex", "/notes/b.md").unwrap();+ store+ .set_memory_source_enabled("claude-code", "<project>/CLAUDE.md", false)+ .unwrap();+ store+ .set_memory_source_enabled("claude-code", "<project>/CLAUDE.md", false)+ .unwrap();+ let (customs, disabled) = store.memory_source_overrides().unwrap();+ assert_eq!(+ customs,+ [+ (AgentId::ClaudeCode, std::path::PathBuf::from("/notes/a")),+ (AgentId::Codex, std::path::PathBuf::from("/notes/b.md"))+ ]+ );+ assert_eq!(+ disabled,+ std::collections::HashSet::from([(AgentId::ClaudeCode, "<project>/CLAUDE.md".to_string())])+ );+ store+ .replace_memory_source("claude-code", "/notes/a", "gemini", "/notes/c")+ .unwrap();+ store.remove_memory_source("codex", "/notes/b.md").unwrap();+ store+ .set_memory_source_enabled("claude-code", "<project>/CLAUDE.md", true)+ .unwrap();+ let (customs, disabled) = store.memory_source_overrides().unwrap();+ assert_eq!(+ customs,+ [(AgentId::Gemini, std::path::PathBuf::from("/notes/c"))]+ );+ assert!(disabled.is_empty());+ store.clear_memory_source_overrides().unwrap();+ assert!(store.memory_source_overrides().unwrap().0.is_empty());++ // 本地项目根:远程会话与没有项目的会话不算+ let mut local = meta("claude-code:local-1", "local");+ local.project_path = "/work/app".into();+ let mut remote = meta("codex:devbox:r-1", "remote");+ remote.agent = AgentId::Codex;+ remote.host = "devbox".into();+ remote.project_path = "/home/me/app".into();+ let mut orphan = meta("codex:o-1", "orphan");+ orphan.agent = AgentId::Codex;+ orphan.project_path = String::new();+ for s in [&local, &remote, &orphan] {+ store+ .write_session_guarded(s, 1, &[], &|_| 0, None)+ .unwrap();+ }+ assert_eq!(+ store.local_project_roots().unwrap(),+ [std::path::PathBuf::from("/work/app")]+ );}#[test]@@ -1348,6 +1437,7 @@ fn memories_replace_list_and_search() {title: title.to_string(),updated_at: updated,size_bytes: body.len() as i64,+ source: String::new(),body: body.to_string(),}};@@ -1475,6 +1565,7 @@ fn memories_resolve_their_project_through_the_anchor_session() {title: "Anchored".to_string(),updated_at: 10,size_bytes: 4,+ source: String::new(),body: "body".to_string(),};let orphan = MemoryDoc {@@ -1534,6 +1625,7 @@ fn memories_resolve_their_project_through_the_anchor_session() {// 侧栏计数与列表同一口径:总数、按 agent、按解析出的项目(没归属的垫底)let counts = store.memory_counts().unwrap();assert_eq!(counts.total, 2);+ assert_eq!(counts.user, 0);assert_eq!(counts.agents, vec![(AgentId::ClaudeCode, 2)]);assert_eq!(counts@@ -1553,14 +1645,15 @@ fn memories_resolve_their_project_through_the_anchor_session() {assert_eq!(project_of(&anchored.key), "/work/app-renamed");// 锚点换了(目录里来了更新的会话)是改动,同 key 重写;正文与时间没变也要写。- // 同 key 重复(同家两个实例的根重叠)后者胜——前面那份与库里相同也不算数+ // 同 key 重复(同家两个实例的根重叠、自定义目录盖住默认文件)**前者胜**——docs 按+ // 来源计划的顺序读入,先到的是默认那份;后面那份与库里相同也不算数let mut moved = anchored.clone();moved.session_key = "claude-code:s2".to_string();assert!(store.replace_memories(AgentId::ClaudeCode,"",- &[anchored.clone(), moved.clone()],+ &[moved.clone(), anchored.clone()],&[]).unwrap());diff --git a/crates/wake-core/tests/scanner_finale.rs b/crates/wake-core/tests/scanner_finale.rsindex 45eaa63..ecad120 100644--- a/crates/wake-core/tests/scanner_finale.rs+++ b/crates/wake-core/tests/scanner_finale.rs@@ -170,6 +170,7 @@ fn memories_of_sources_gone_from_the_roster_are_pruned() {title: "prefs".to_string(),updated_at: 1,size_bytes: 4,+ source: String::new(),body: "body".to_string(),};store@@ -688,18 +689,31 @@ impl AgentAdapter for MemoryStub {fn with_custom_root(&self, _: std::path::PathBuf) -> Box<dyn AgentAdapter> {unreachable!("not used in scans")}- fn list_memories(&self) -> Result<Vec<MemoryDoc>> {+ fn memory_sources(&self) -> Vec<MemorySource> {+ vec![MemorySource {+ agent: AgentId::ClaudeCode,+ kind: MemorySourceKind::Dir { ext: "md" },+ path: self.root.join("memory"),+ }]+ }+ fn list_memories(+ &self,+ _sources: &[MemorySource],+ _projects: &[std::path::PathBuf],+ ) -> Result<Vec<MemoryDoc>> {if self.fail {bail!("simulated unreadable memory directory")}Ok(self.docs.clone())}- fn memory_roots(&self) -> Vec<std::path::PathBuf> {- vec![self.root.join("memory")]- }}+/// 来源 id = 文件所在目录(与 MemoryStub::memory_sources 报的 `<root>/memory` 一致)fn mem_doc(path: &str, title: &str) -> MemoryDoc {+ let source = std::path::Path::new(path)+ .parent()+ .map(|p| p.to_string_lossy().to_string())+ .unwrap_or_default();MemoryDoc {key: format!("claude-code:{path}"),agent: AgentId::ClaudeCode,@@ -712,6 +726,7 @@ fn mem_doc(path: &str, title: &str) -> MemoryDoc {title: title.to_string(),updated_at: 1,size_bytes: 4,+ source,body: "body".to_string(),}}@@ -782,6 +797,131 @@ fn memories_of_a_failing_instance_stay_frozen_while_the_others_reconcile() {assert_eq!(titles(&store), ["a2"]);}+/// Settings → Memory locations 的两种偏离:停用一个默认来源(它的行随下一轮出库),+/// 添加一个自定义目录(它的 *.md 以 agent 记的、用户级列进来);Restore defaults 后+/// 两边都回来 / 走掉+#[test]+fn memory_source_overrides_drive_what_gets_indexed() {+ let dir = tempfile::tempdir().unwrap();+ let store = temp_store(dir.path());+ let home = tempfile::tempdir().unwrap();+ let claude_home = home.path().join(".claude");+ let memory = claude_home.join("projects/-Users-tester-Github-wakefx/memory");+ std::fs::create_dir_all(&memory).unwrap();+ std::fs::write(memory.join("MEMORY.md"), "- notes\n").unwrap();+ std::fs::write(claude_home.join("CLAUDE.md"), "# global\n").unwrap();+ let notes = home.path().join("notes");+ std::fs::create_dir_all(¬es).unwrap();+ std::fs::write(notes.join("team.md"), "# team conventions\n").unwrap();+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![+ CodexAdapter::new().with_custom_root(home.path().join(".nope")),+ wake_core::adapters::claude::ClaudeAdapter::new().with_custom_root(claude_home.clone()),+ ];+ let titles = |store: &Store| -> Vec<String> {+ store+ .list_memories(&MemoryFilter::default())+ .unwrap()+ .iter()+ .map(|d| d.title.clone())+ .collect()+ };+ run_scan(&adapters, &store, &Recorder::new(), false).unwrap();+ assert_eq!(titles(&store), ["MEMORY.md", "CLAUDE.md"]);++ // 停用全局 CLAUDE.md 这个来源+ let claude_md = claude_home.join("CLAUDE.md").to_string_lossy().to_string();+ store+ .set_memory_source_enabled("claude-code", &claude_md, false)+ .unwrap();+ run_scan(&adapters, &store, &Recorder::new(), false).unwrap();+ assert_eq!(titles(&store), ["MEMORY.md"]);++ // 加一个自定义目录+ store+ .add_memory_source("claude-code", ¬es.to_string_lossy())+ .unwrap();+ run_scan(&adapters, &store, &Recorder::new(), false).unwrap();+ let docs = store.list_memories(&MemoryFilter::default()).unwrap();+ let custom = docs+ .iter()+ .find(|d| d.title == "team.md")+ .expect("自定义目录的文件");+ assert_eq!(+ (custom.scope, custom.source.as_str()),+ (MemoryScope::User, notes.to_string_lossy().as_ref())+ );+ let counts = store.memory_source_counts().unwrap();+ assert_eq!(+ counts.get(&(+ "claude-code".to_string(),+ notes.to_string_lossy().to_string()+ )),+ Some(&1)+ );++ // Restore defaults:自定义走掉、停用的回来+ store.clear_memory_source_overrides().unwrap();+ run_scan(&adapters, &store, &Recorder::new(), false).unwrap();+ assert_eq!(titles(&store), ["MEMORY.md", "CLAUDE.md"]);+}++/// 会话 location 全停用(roster 里没有这一家的实例)之后,agent 级的记忆来源——用户加的+/// 自定义目录、项目根下的指令文件——照读:它们不在被停用的 location 里,不该随它消失;+/// 停掉的只是从那个根派生的默认来源(记忆树、全局 CLAUDE.md)。原先这一家直接从计划里+/// 消失,scanner 把它整组删光、Settings 里连自定义行都看不见(2026-09-22 review)+#[test]+fn agent_level_memory_sources_outlive_a_disabled_session_location() {+ let dir = tempfile::tempdir().unwrap();+ let store = temp_store(dir.path());+ let home = tempfile::tempdir().unwrap();+ let claude_home = home.path().join(".claude");+ let memory = claude_home.join("projects/-Users-tester-Github-wakefx/memory");+ std::fs::create_dir_all(&memory).unwrap();+ std::fs::write(memory.join("MEMORY.md"), "- notes\n").unwrap();+ std::fs::write(claude_home.join("CLAUDE.md"), "# global\n").unwrap();+ let notes = home.path().join("notes");+ std::fs::create_dir_all(¬es).unwrap();+ std::fs::write(notes.join("team.md"), "# team conventions\n").unwrap();+ store+ .add_memory_source("claude-code", ¬es.to_string_lossy())+ .unwrap();+ let titles = |store: &Store| -> Vec<String> {+ let mut v: Vec<String> = store+ .list_memories(&MemoryFilter::default())+ .unwrap()+ .iter()+ .map(|d| d.title.clone())+ .collect();+ v.sort();+ v+ };+ let with_claude: Vec<Box<dyn AgentAdapter>> = vec![+ CodexAdapter::new().with_custom_root(home.path().join(".nope")),+ wake_core::adapters::claude::ClaudeAdapter::new().with_custom_root(claude_home.clone()),+ ];+ run_scan(&with_claude, &store, &Recorder::new(), false).unwrap();+ assert_eq!(titles(&store), ["CLAUDE.md", "MEMORY.md", "team.md"]);++ // Claude 的会话 location 停用 = roster 里没有它的实例+ let without_claude: Vec<Box<dyn AgentAdapter>> =+ vec![CodexAdapter::new().with_custom_root(home.path().join(".nope"))];+ run_scan(&without_claude, &store, &Recorder::new(), false).unwrap();+ assert_eq!(+ titles(&store),+ ["team.md"],+ "默认来源随根消失,自定义目录留下"+ );+ let custom = &store.list_memories(&MemoryFilter::default()).unwrap()[0];+ assert_eq!(custom.agent, AgentId::ClaudeCode);++ // 删掉自定义来源才真的走掉+ store+ .remove_memory_source("claude-code", ¬es.to_string_lossy())+ .unwrap();+ run_scan(&without_claude, &store, &Recorder::new(), false).unwrap();+ assert!(titles(&store).is_empty());+}+/// 关系这一刻读不出(state DB 打不开)= None:这一家整段跳过,库里的关系原样保留,/// 而不是拿空快照当"全部解除"整家清空(2026-09-21 review)#[test]diff --git a/crates/wake/assets/icons/user.svg b/crates/wake/assets/icons/user.svgnew file mode 100644index 0000000..6b793a4--- /dev/null+++ b/crates/wake/assets/icons/user.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v0.462.0 - ISC -->+<svg+ class="lucide lucide-user"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" />+ <circle cx="12" cy="7" r="4" />+</svg>diff --git a/crates/wake/locales/zh-Hans.json b/crates/wake/locales/zh-Hans.jsonindex 31b79b3..a87d856 100644--- a/crates/wake/locales/zh-Hans.json+++ b/crates/wake/locales/zh-Hans.json@@ -25,6 +25,7 @@"Add a location": "添加位置","Add host": "添加主机","Add location": "添加位置",+ "Add memory location": "添加记忆位置","Add remote host": "添加远程主机","Add to ~/.codex/config.toml": "加到 ~/.codex/config.toml","Agent": "Agent",@@ -52,7 +53,9 @@"Checking…": "正在检查…","Choose": "选择","Choose a folder": "选择文件夹",+ "Choose a folder or file": "选择文件夹或文件","Choose where Wake looks for local agent sessions.": "选择 Wake 查找本地 agent 会话的位置。",+ "Choose which memory and instruction files Wake indexes.": "选择 Wake 索引哪些记忆与指令文件。","Clean Up Sessions": "清理会话","Cleanup history": "清理记录","Close": "关闭",@@ -83,7 +86,7 @@"Couldn't save appearance: {}": "无法保存外观设置:{}","Couldn't save language: {}": "无法保存语言设置:{}","Couldn't save the image": "无法存储图片",- "Couldn't update location: {}": "无法更新位置:{}",+ "Couldn't update location": "无法更新位置","Couldn't update remote host": "无法更新远程主机","Created {}": "创建于 {}","Customize how Wake looks and reads.": "自定义 Wake 的外观与语言。",@@ -102,6 +105,7 @@"Earlier this week": "本周早些时候","Edit": "编辑","Edit location": "编辑位置",+ "Edit memory location": "编辑记忆位置","Edit…": "编辑…","Enable host": "启用主机","Enable location": "启用位置",@@ -115,6 +119,7 @@"First {} characters": "前 {} 个字符","Folder": "文件夹","Folder not found": "找不到文件夹",+ "Folder or file": "文件夹或文件","Follow the system language, or pick one.": "跟随系统语言,或自行选择。","Follow the system or keep Wake light or dark.": "跟随系统,或固定浅色/深色。","Fri": "周五",@@ -145,7 +150,6 @@"Location enabled": "位置已启用","Location removed": "位置已移除","Location updated": "位置已更新",- "Locations": "位置","Locations restored to defaults": "位置已恢复默认","Longest {} days": "最长 {} 天","Looking for local agent sessions…": "正在查找本地 agent 会话…",@@ -154,6 +158,8 @@"Main Window": "主窗口","Matches natural language and code, like \"useEffect(\".": "自然语言与代码都能匹配,例如 \"useEffect(\"。","Memory": "记忆",+ "Memory locations": "记忆位置",+ "Memory refreshed": "记忆已刷新","Merge into ~/.cursor/mcp.json": "并入 ~/.cursor/mcp.json","Message count": "消息数","Minimize": "最小化",@@ -183,6 +189,7 @@"No tool calls": "无工具调用","No {} adapter is available for this session path.": "此会话路径没有可用的 {} 适配器。","Not detected": "未检测到",+ "Not found": "找不到","Not found next to the Wake app — reinstall Wake": "没在 Wake 应用旁边找到 —— 重装 Wake","Not started": "未开始","Only the local file is removed — Codex's own records stay intact.": "只会删除本地文件 —— Codex 自己的记录不受影响。",@@ -212,6 +219,7 @@"Refresh Sessions": "刷新会话","Refresh failed: {}": "刷新失败:{}","Refresh sessions to see your activity here.": "刷新会话后这里会显示你的活动。",+ "Refreshing memory…": "正在刷新记忆…","Refreshing {}/{}": "正在刷新 {}/{}","Refreshing…": "正在刷新…","Remote host disabled": "远程主机已停用",@@ -280,6 +288,7 @@"The session file will be moved to the Recycle Bin. You can restore it anytime:": "会话文件将被移到回收站,随时可以还原:","Thinking": "思考","This folder is already in Wake's session locations": "该文件夹已在 Wake 的会话位置中",+ "This path is already in Wake's memory locations": "这个路径已经在 Wake 的记忆位置里了","This session and {} nested session will be moved to {}. You can restore them anytime:": "此会话及其 {0} 个子会话将被移到{1},随时可以还原:","This session and {} nested sessions will be moved to {}. You can restore them anytime:": "此会话及其 {0} 个子会话将被移到{1},随时可以还原:","Thu": "周四",@@ -301,7 +310,7 @@"Unstar": "取消收藏","Updated {}": "更新于 {}","Updates": "更新",- "User-level": "用户级",+ "User memory": "用户记忆","Verify in system trash": "请在系统废纸篓中核对","Version {}": "版本 {}","View Update": "查看更新",@@ -328,6 +337,8 @@"{} AM": "上午 {} 点","{} PM": "下午 {} 点","{} failed": "{} 个失败",+ "{} file": "{} 个文件",+ "{} files": "{} 个文件","{} memory file": "{} 份记忆文件","{} memory files": "{} 份记忆文件","{} messages": "{} 条消息",diff --git a/crates/wake/src/assets.rs b/crates/wake/src/assets.rsindex 99a68b1..79a4218 100644--- a/crates/wake/src/assets.rs+++ b/crates/wake/src/assets.rs@@ -110,6 +110,7 @@ icons!("loader","circle-x","file-text",+ "user","more-horizontal","hard-drive","server",diff --git a/crates/wake/src/settings.rs b/crates/wake/src/settings.rsindex fbb0f97..0f50f68 100644--- a/crates/wake/src/settings.rs+++ b/crates/wake/src/settings.rs@@ -14,12 +14,16 @@ use wake_core::models::AgentId;use crate::format::tilde_path;use crate::ui::{action_button, overlay_layers, show_in_fm, BUTTON_SM_H, FONT_BODY, FONT_CAPTION, FONT_DISPLAY,- FONT_HEADING, FONT_LABEL, FONT_TITLE, RADIUS_BUTTON, SPACE_LG, SPACE_MD, SPACE_SM, SPACE_XL,- SPACE_XS, SPACE_XXL,+ FONT_HEADING, FONT_LABEL, FONT_TITLE, ICON_TEXT_GAP, RADIUS_BUTTON, SPACE_LG, SPACE_MD,+ SPACE_SM, SPACE_XL, SPACE_XS, SPACE_XXL,};use crate::update::{self, UpdateStatus};-use crate::workbench::{DataSourceRow, OpenAbout, OpenSettings, OpenUpdates, Workbench};+use crate::workbench::{+ DataSourceRow, LocationSettingsSnapshot, MemoryLocationRow, MemoryLocationSettingsSnapshot,+ OpenAbout, OpenSettings, OpenUpdates, Workbench,+};use crate::{theme, theme::AppearancePreference};+use std::rc::Rc;const SETTINGS_SIDEBAR_W: Pixels = px(180.);const SETTINGS_PAGE_TOP: Pixels = px(38.);@@ -51,6 +55,7 @@ fn format_storage_size(bytes: u64) -> String {pub(crate) enum SettingsPage {General,Locations,+ MemoryLocations,Remotes,Connect,Data,@@ -228,9 +233,64 @@ pub(crate) struct SettingsView {copied: Option<SharedString>,/// 连点时只有最后一次的定时器能清掉 copiedcopied_generation: u64,+ /// Session locations / Memory locations 两页的快照:各是三条 SQL + 每路径一次 stat,+ /// 在 observe Workbench 的回调里取一次(配置变更、扫描进度、记忆同步收尾都会+ /// notify),不在 render 里每帧算——原先 hover 一下就重查一遍库(2026-09-22 /simplify)+ locations: LocationSettingsSnapshot,+ memory_locations: MemoryLocationSettingsSnapshot,_workbench_observer: Option<Subscription>,}+/// location 行菜单里的一个动作(Edit… / Remove):Settings 只转发给 Workbench+type RowAction = Rc<dyn Fn(&mut Window, &mut App)>;++/// 行末的 `…` 菜单(两页共用):Edit…(可编辑的行)、Show in Finder(路径存在时)、分隔线 ++/// Remove(可删的自定义行);每项都是 Option,两页按自己的规则给+fn row_menu(+ ix: usize,+ edit: Option<RowAction>,+ reveal: Option<SharedString>,+ remove: Option<RowAction>,+) -> impl IntoElement {+ Button::new(("settings-location-menu", ix))+ .ghost()+ .small()+ .rounded(RADIUS_BUTTON)+ .icon(icon("icons/more-horizontal.svg").with_size(px(14.)))+ .dropdown_menu(move |menu, _, _| {+ let mut menu = menu.min_w(px(180.));+ if let Some(edit) = edit.clone() {+ menu = menu.item(+ PopupMenuItem::new(t("Edit…")).on_click(move |_, window, cx| edit(window, cx)),+ );+ }+ if let Some(path) = reveal.clone() {+ menu = menu.item(PopupMenuItem::new(show_in_fm()).on_click(move |_, _, _| {+ wake_core::services::terminal::open_in_file_manager(path.as_ref())+ }));+ }+ if let Some(remove) = remove.clone() {+ menu = menu.separator().item(+ PopupMenuItem::new(t("Remove"))+ .on_click(move |_, window, cx| remove(window, cx)),+ );+ }+ menu+ })+}++/// 快照的行按 agent 成组(快照已按 AgentId 声明序排好,相邻同家即一组)+fn group_by_agent<R>(rows: Vec<R>, agent: impl Fn(&R) -> AgentId) -> Vec<(AgentId, Vec<R>)> {+ let mut groups: Vec<(AgentId, Vec<R>)> = Vec::new();+ for row in rows {+ match groups.last_mut() {+ Some((a, rows)) if *a == agent(&row) => rows.push(row),+ _ => groups.push((agent(&row), vec![row])),+ }+ }+ groups+}+impl SettingsView {pub(crate) fn new(workbench: Entity<Workbench>,@@ -242,7 +302,12 @@ impl SettingsView {// 立即 observe 会尝试反读仍被独占借用的 Workbench,触发 double lease。// 下一帧注册时外层 update 已退出。cx.on_next_frame(window, move |this, _, cx| {- this._workbench_observer = Some(cx.observe(&observed, |_, _, cx| cx.notify()));+ this.refresh_snapshots(observed.read(cx));+ this._workbench_observer = Some(cx.observe(&observed, |this, workbench, cx| {+ this.refresh_snapshots(workbench.read(cx));+ cx.notify()+ }));+ cx.notify();});Self {focus_handle: cx.focus_handle(),@@ -253,6 +318,14 @@ impl SettingsView {connect_shown: Default::default(),copied: None,copied_generation: 0,+ locations: LocationSettingsSnapshot {+ rows: Vec::new(),+ diverged: false,+ },+ memory_locations: MemoryLocationSettingsSnapshot {+ rows: Vec::new(),+ diverged: false,+ },_workbench_observer: None,}}@@ -330,11 +403,18 @@ impl SettingsView {)).child(self.render_nav_item("settings-locations-nav",- t("Locations"),+ t("Session locations"),"icons/hard-drive.svg",SettingsPage::Locations,cx,))+ .child(self.render_nav_item(+ "settings-memory-locations-nav",+ t("Memory locations"),+ "icons/brain.svg",+ SettingsPage::MemoryLocations,+ cx,+ )).child(self.render_nav_item("settings-remotes-nav",t("Remote hosts"),@@ -751,7 +831,7 @@ impl SettingsView {.min_h(px(52.)).px(SPACE_LG).py(SPACE_SM)- .gap(SPACE_MD)+ .gap(ICON_TEXT_GAP).items_center().child(img(s.agent.brand_icon(dark)).size(px(17.)).flex_shrink_0()).child(@@ -1172,60 +1252,129 @@ impl SettingsView {.into_any_element()}+ /// 两页 location 面板的快照重读(见字段注释):只刷当前显示的那页——切页走 Workbench+ /// 的 select_settings_page、本身就 notify,目标页在那一次刷到;设置窗开着时主窗的每次+ /// notify(敲一个搜索字)都会到这里,两页都刷是白付两遍 SQL + stat+ fn refresh_snapshots(&mut self, workbench: &Workbench) {+ match workbench.settings_page() {+ SettingsPage::Locations => self.locations = workbench.location_settings_snapshot(),+ SettingsPage::MemoryLocations => {+ self.memory_locations = workbench.memory_location_settings_snapshot()+ }+ _ => {}+ }+ }++ /// Session locations 的一行:Edit… 恒有,Show in Finder 挂存在的路径,Remove 只给自定义行fn render_location_row(&self, row: DataSourceRow, ix: usize, cx: &Context<Self>) -> AnyElement {- let theme = cx.theme();- let enabled = row.enabled;- let exists = row.exists;- let raw = row.raw.clone();+ let workbench = self.workbench.clone();+ let edit: RowAction = {+ let workbench = workbench.clone();+ let row = row.clone();+ Rc::new(move |window, cx| {+ let row = row.clone();+ workbench.update(cx, |this, cx| this.open_edit_location_form(row, window, cx));+ })+ };+ let reveal = row.exists.then(|| row.raw.clone());+ let remove: Option<RowAction> = row.custom.clone().map(|stored| {+ let workbench = workbench.clone();+ let agent = row.agent;+ Rc::new(move |window: &mut Window, cx: &mut App| {+ let stored = stored.clone();+ workbench.update(cx, |this, cx| {+ this.delete_location(agent, stored, window, cx)+ });+ }) as RowAction+ });+ let toggle = {+ let (agent, path) = (row.agent, row.raw.clone());+ move |enabled: &bool, window: &mut Window, cx: &mut App| {+ let path = path.clone();+ workbench.update(cx, |this, cx| {+ this.set_location_enabled(agent, path, *enabled, window, cx)+ });+ }+ };+ self.location_row(+ ix,+ row.display,+ row.tally,+ row.enabled,+ row.exists,+ row_menu(ix, Some(edit), reveal, remove),+ toggle,+ cx,+ )+ }- let edit_workbench = self.workbench.clone();- let edit_row = row.clone();- let reveal_path = row.raw.clone();- let remove_target = row.custom.clone();- let remove_agent = row.agent;- let menu = Button::new(("settings-location-menu", ix))- .ghost()- .small()- .rounded(RADIUS_BUTTON)- .icon(icon("icons/more-horizontal.svg").with_size(px(14.)))- .dropdown_menu(move |menu, _, _| {- let workbench = edit_workbench.clone();- let edit_row = edit_row.clone();- let mut menu = menu- .min_w(px(180.))- .item(- PopupMenuItem::new(t("Edit…")).on_click(move |_, window, cx| {- let row = edit_row.clone();- workbench.update(cx, |this, cx| {- this.open_edit_location_form(row, window, cx)- });- }),- );- if exists {- let path = reveal_path.clone();- menu = menu.item(PopupMenuItem::new(show_in_fm()).on_click(move |_, _, _| {- wake_core::services::terminal::open_in_file_manager(path.as_ref())- }));- }- if let Some(stored) = remove_target.clone() {- let workbench = edit_workbench.clone();- menu = menu- .separator()- .item(- PopupMenuItem::new(t("Remove")).on_click(move |_, window, cx| {- let stored = stored.clone();- workbench.update(cx, |this, cx| {- this.delete_location(remove_agent, stored, window, cx)- });- }),- );- }- menu- });+ /// Memory locations 的一行:默认来源只有开关与 Show in Finder,自定义来源多 Edit /+ /// Remove;项目模式行(`<project>/CLAUDE.md`)没有 Finder+ fn render_memory_location_row(+ &self,+ row: MemoryLocationRow,+ ix: usize,+ cx: &Context<Self>,+ ) -> AnyElement {+ let workbench = self.workbench.clone();+ let edit: Option<RowAction> = row.custom.then(|| {+ let workbench = workbench.clone();+ let row = row.clone();+ Rc::new(move |window: &mut Window, cx: &mut App| {+ let row = row.clone();+ workbench.update(cx, |this, cx| {+ this.open_edit_memory_location_form(row, window, cx)+ });+ }) as RowAction+ });+ let reveal = (!row.pattern && row.exists).then(|| row.raw.clone());+ let remove: Option<RowAction> = row.custom.then(|| {+ let workbench = workbench.clone();+ let (agent, stored) = (row.agent, row.raw.clone());+ Rc::new(move |window: &mut Window, cx: &mut App| {+ let stored = stored.clone();+ workbench.update(cx, |this, cx| {+ this.delete_memory_source(agent, stored, window, cx)+ });+ }) as RowAction+ });+ let toggle = {+ let (agent, id) = (row.agent, row.raw.clone());+ move |enabled: &bool, window: &mut Window, cx: &mut App| {+ let id = id.clone();+ workbench.update(cx, |this, cx| {+ this.set_memory_source_enabled(agent, id, *enabled, window, cx)+ });+ }+ };+ self.location_row(+ ix,+ row.display,+ row.tally,+ row.enabled,+ row.exists,+ row_menu(ix, edit, reveal, remove),+ toggle,+ cx,+ )+ }- let toggle_workbench = self.workbench.clone();- let toggle_path = raw;- let toggle_agent = row.agent;+ /// location 行的壳(Session locations 与 Memory locations 共用):路径 + 计数 / 状态词、+ /// `…` 菜单、开关;停用的行文字降为 muted,路径不在时状态词用 warning 色。两页从不+ /// 同时渲染,元素 id 共用一套+ #[allow(clippy::too_many_arguments)]+ fn location_row(+ &self,+ ix: usize,+ display: SharedString,+ tally: SharedString,+ enabled: bool,+ exists: bool,+ menu: impl IntoElement,+ on_toggle: impl Fn(&bool, &mut Window, &mut App) + 'static,+ cx: &Context<Self>,+ ) -> AnyElement {+ let theme = cx.theme();h_flex().id(("settings-location-row", ix)).min_h(px(60.))@@ -1248,7 +1397,7 @@ impl SettingsView {} else {theme.muted_foreground})- .child(row.display),+ .child(display),).child(div()@@ -1258,7 +1407,7 @@ impl SettingsView {} else {theme.warning})- .child(row.tally),+ .child(tally),),).child(menu)@@ -1271,21 +1420,17 @@ impl SettingsView {} else {t("Enable location")})- .on_click(move |enabled, window, cx| {- let path = toggle_path.clone();- toggle_workbench.update(cx, |this, cx| {- this.set_location_enabled(toggle_agent, path, *enabled, window, cx)- });- }),+ .on_click(on_toggle),).into_any_element()}+ /// 一家的一组行(Session locations 与 Memory locations 共用):品牌图 + 名字的组头,+ /// 下面一张圆角卡,行与行之间一条 hairlinefn render_agent_group(&self,agent: AgentId,- rows: Vec<DataSourceRow>,- row_offset: usize,+ rows: Vec<AnyElement>,cx: &Context<Self>,) -> AnyElement {let theme = cx.theme();@@ -1295,7 +1440,7 @@ impl SettingsView {.child(h_flex().h(px(24.))- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).items_center().child(img(agent.brand_icon(dark)).size(px(17.)).flex_shrink_0()).child(@@ -1318,52 +1463,158 @@ impl SettingsView {div().w_full().when(ix > 0, |this| this.border_t_1().border_color(theme.border))- .child(self.render_location_row(row, row_offset + ix, cx))+ .child(row)})),).into_any_element()}+ /// Settings → Memory locations:Session locations 同形制的页(页壳 `locations_page`)+ fn render_memory_locations(&mut self, cx: &mut Context<Self>) -> impl IntoElement {+ let snapshot = self.memory_locations.clone();+ let mut row_offset = 0usize;+ let list = self.render_agent_groups(+ group_by_agent(snapshot.rows, |row| row.agent),+ &mut row_offset,+ Self::render_memory_location_row,+ cx,+ );+ self.locations_page(+ t("Memory locations"),+ t("Choose which memory and instruction files Wake indexes."),+ snapshot.diverged,+ Workbench::open_add_memory_location_form,+ Workbench::restore_default_memory_locations,+ list,+ cx,+ )+ }+fn render_locations(&mut self, cx: &mut Context<Self>) -> impl IntoElement {let theme = cx.theme();- let snapshot = self.workbench.read(cx).location_settings_snapshot();- let mut groups: Vec<(AgentId, Vec<DataSourceRow>)> = Vec::new();- for row in snapshot.rows {- match groups.last_mut() {- Some((agent, rows)) if *agent == row.agent => rows.push(row),- _ => groups.push((row.agent, vec![row])),- }- }- let (available, unavailable): (Vec<_>, Vec<_>) = groups- .into_iter()- .partition(|(_, rows)| rows.iter().any(|row| row.exists || row.custom.is_some()));+ let snapshot = self.locations.clone();+ let (available, unavailable): (Vec<_>, Vec<_>) =+ group_by_agent(snapshot.rows, |row| row.agent)+ .into_iter()+ .partition(|(_, rows)| rows.iter().any(|row| row.exists || row.custom.is_some()));let unavailable_count = unavailable.len();- let add_workbench = self.workbench.clone();- let restore_workbench = self.workbench.clone();- let diverged = snapshot.diverged;-let mut row_offset = 0usize;- let available_elements: Vec<AnyElement> = available+ let mut list =+ self.render_agent_groups(available, &mut row_offset, Self::render_location_row, cx);+ if unavailable_count > 0 {+ let unavailable_elements = if self.show_unavailable {+ self.render_agent_groups(+ unavailable,+ &mut row_offset,+ Self::render_location_row,+ cx,+ )+ } else {+ Vec::new()+ };+ list.push(+ v_flex()+ .gap(SPACE_LG)+ .child(+ h_flex()+ .id("settings-unavailable-locations")+ .h(px(36.))+ .w_full()+ .pr(SPACE_SM)+ .gap(SPACE_SM)+ .items_center()+ .rounded(theme.radius)+ .cursor_pointer()+ .text_color(theme.muted_foreground)+ .hover(|style| style.bg(theme.secondary_hover))+ .on_click(cx.listener(|this, _, _, cx| {+ this.show_unavailable = !this.show_unavailable;+ cx.notify();+ }))+ .child(+ div()+ .w(px(17.))+ .flex_shrink_0()+ .flex()+ .items_center()+ .justify_center()+ .child(+ icon(if self.show_unavailable {+ "icons/chevron-down.svg"+ } else {+ "icons/chevron-right.svg"+ })+ .with_size(px(13.)),+ ),+ )+ .child(+ div()+ .flex_1()+ .text_size(FONT_CAPTION)+ .font_medium()+ .child(t("Not detected")),+ )+ .child(+ div()+ .text_size(FONT_LABEL)+ .child(unavailable_count.to_string()),+ ),+ )+ .children(unavailable_elements)+ .into_any_element(),+ );+ }+ self.locations_page(+ t("Session locations"),+ t("Choose where Wake looks for local agent sessions."),+ snapshot.diverged,+ Workbench::open_add_location_form,+ Workbench::restore_default_locations,+ list,+ cx,+ )+ }++ /// 按 agent 成组渲染(两页共用):行号在整页内连续,各组的元素 id 不重叠+ fn render_agent_groups<R>(+ &self,+ groups: Vec<(AgentId, Vec<R>)>,+ row_offset: &mut usize,+ render_row: impl Fn(&Self, R, usize, &Context<Self>) -> AnyElement,+ cx: &Context<Self>,+ ) -> Vec<AnyElement> {+ groups.into_iter().map(|(agent, rows)| {- let start = row_offset;- row_offset += rows.len();- self.render_agent_group(agent, rows, start, cx)+ let start = *row_offset;+ *row_offset += rows.len();+ let rendered = rows+ .into_iter()+ .enumerate()+ .map(|(ix, row)| render_row(self, row, start + ix, cx))+ .collect();+ self.render_agent_group(agent, rendered, cx)})- .collect();- let unavailable_elements: Vec<AnyElement> = if self.show_unavailable {- unavailable- .into_iter()- .map(|(agent, rows)| {- let start = row_offset;- row_offset += rows.len();- self.render_agent_group(agent, rows, start, cx)- })- .collect()- } else {- Vec::new()- };+ .collect()+ }+ /// location 页的壳(Session locations 与 Memory locations 共用):页头 = 标题 + 一句+ /// 说明 + Add location + `…` 里的 Restore defaults(没有偏离时禁用),下面是可滚动的+ /// 分组列表。两页从不同时渲染,元素 id 共用一套+ #[allow(clippy::too_many_arguments)]+ fn locations_page(+ &self,+ title: &'static str,+ caption: &'static str,+ diverged: bool,+ on_add: fn(&mut Workbench, &mut Window, &mut Context<Workbench>),+ on_restore: fn(&mut Workbench, &mut Window, &mut Context<Workbench>),+ list: Vec<AnyElement>,+ cx: &Context<Self>,+ ) -> impl IntoElement {+ let theme = cx.theme();+ let add_workbench = self.workbench.clone();+ let restore_workbench = self.workbench.clone();v_flex().flex_1().min_w_0()@@ -1387,13 +1638,13 @@ impl SettingsView {.text_size(FONT_TITLE).font_semibold().text_color(theme.foreground)- .child(t("Session locations")),+ .child(title),).child(div().text_size(FONT_CAPTION).text_color(theme.muted_foreground)- .child(t("Choose where Wake looks for local agent sessions.")),+ .child(caption),),).child(@@ -1404,8 +1655,7 @@ impl SettingsView {cx,).on_click(move |_, window, cx| {- add_workbench- .update(cx, |this, cx| this.open_add_location_form(window, cx));+ add_workbench.update(cx, |this, cx| on_add(this, window, cx));}),).child(@@ -1421,7 +1671,7 @@ impl SettingsView {.disabled(!diverged).on_click(move |_, window, cx| {workbench.update(cx, |this, cx| {- this.restore_default_locations(window, cx)+ on_restore(this, window, cx)});}),)@@ -1437,59 +1687,7 @@ impl SettingsView {.px(SPACE_XXL).pb(px(40.)).gap(SPACE_XL)- .children(available_elements)- .when(unavailable_count > 0, |this| {- this.child(- v_flex()- .gap(SPACE_LG)- .child(- h_flex()- .id("settings-unavailable-locations")- .h(px(36.))- .w_full()- .pr(SPACE_SM)- .gap(SPACE_SM)- .items_center()- .rounded(theme.radius)- .cursor_pointer()- .text_color(theme.muted_foreground)- .hover(|style| style.bg(theme.secondary_hover))- .on_click(cx.listener(|this, _, _, cx| {- this.show_unavailable = !this.show_unavailable;- cx.notify();- }))- .child(- div()- .w(px(17.))- .flex_shrink_0()- .flex()- .items_center()- .justify_center()- .child(- icon(if self.show_unavailable {- "icons/chevron-down.svg"- } else {- "icons/chevron-right.svg"- })- .with_size(px(13.)),- ),- )- .child(- div()- .flex_1()- .text_size(FONT_CAPTION)- .font_medium()- .child(t("Not detected")),- )- .child(- div()- .text_size(FONT_LABEL)- .child(unavailable_count.to_string()),- ),- )- .children(unavailable_elements),- )- }),+ .children(list),)}@@ -1729,6 +1927,7 @@ impl Render for SettingsView {let content = match selected_page {SettingsPage::General => self.render_general(cx),SettingsPage::Locations => self.render_locations(cx).into_any_element(),+ SettingsPage::MemoryLocations => self.render_memory_locations(cx).into_any_element(),SettingsPage::Remotes => self.render_remotes(cx),SettingsPage::Connect => self.render_connect(cx),SettingsPage::Data => self.render_data(cx),diff --git a/crates/wake/src/ui.rs b/crates/wake/src/ui.rsindex 7e43d00..6536b9e 100644--- a/crates/wake/src/ui.rs+++ b/crates/wake/src/ui.rs@@ -143,31 +143,36 @@ pub const SPACE_LG: Pixels = px(16.);pub const SPACE_XL: Pixels = px(20.);pub const SPACE_XXL: Pixels = px(24.);+/// 图标 / 品牌图与紧随其后的文字之间的间距——全应用只此一个值(侧栏行与组头、列表+/// 元信息行、详情与阅读面头部及元信息行、⌘K 结果、Insights 榜单、Open In 菜单、状态行、+/// 设置页与清理页的行)。用户 2026-09-22 定统一:原先 4 / 6 / 7 / 8 / 12 各处不一。+/// 不在 4px 网格上是有意的——品牌 PNG 没有留白,8px 显得空、4px 又贴;lucide 线条图标+/// 自带约 1.5px 留白,6px 几何间距视觉上约 7.5px。卡片级的 24px 头像不在此列+pub const ICON_TEXT_GAP: Pixels = px(6.);+/// 侧栏容器水平内边距(行的 hover/选中胶囊左右各留这么多)。pub const SIDEBAR_EDGE: Pixels = px(10.);// ---- 侧栏中轴:LEAD_AXIS = 26.75 ----// traffic light 实测左缘 20、直径 13.5,中心即 26.75。侧栏每一行的行首元素-// (导航图标、品牌图、文件夹图标、组头首字母)的**中心**都压在这条竖线上。+// (导航图标、品牌图、文件夹图标、组头的折叠 chevron)的**中心**都压在这条竖线上。// 注意:中心对齐与左缘对齐是同一个自由度,只能满足一个——选了中心,// 图标左缘就会落在 17.75,比红灯左缘还靠左 2.25,这是预期而非错位。-// 三个内边距是同一条轴推出来的,改任何一个都必须重算另外两个。+// 两个内边距(LEAD_INSET / TITLE_INSET)是同一条轴推出来的,改一个必须重算另一个。/// 行首槽位:取最大前导元素(品牌图 18px)的尺寸;槽位内**居中**,/// 于是 14/15px 的小图标中心也落在轴上。pub const LEAD_BOX: Pixels = px(18.);+/// 侧栏导航行的线条图标边长(品牌图占满 18px 槽位,线条图标比实心品牌图视觉轻,小一档+/// 才平衡);组头的折叠 chevron 同一档,描边粗细才一致+pub const NAV_ICON: Pixels = px(15.);/// 行左内边距 = 26.75(轴) − 9(槽位半宽) − 10(SIDEBAR_EDGE,容器那一半)pub const LEAD_INSET: Pixels = px(7.75);/// 分组项(agent/项目)相对轴的右缩进,表达从属。/// 压轴的只有主导航行与组头;分组项一律偏这么多。pub const SUB_INDENT: Pixels = px(12.);-/// 组头左内边距:让首字母字形中心落在轴上。组头用 FONT_BODY 常规字重,-/// 实测 A 宽 8.25、P 宽 7.25,两者字形中心恰好重合,一个值同时命中两个组头。-/// **字号或字重一变这个数就失效**——它是从字形宽度反推的,不是间距刻度-/// (semibold 时实测需 12.0/12.25,两个组头还对不上同一个值)。-/// 12.125 实测落位 −0.125;调到 12.25 反而变成 +0.375——2x 屏光栅化步长是-/// 0.5px,两者落进不同物理像素,别再往小数点后调了。-pub const GROUP_HEAD_INSET: Pixels = px(12.125);+// 组头(Agents / Projects)没有自己的内边距常量:NAV_ICON 的 chevron 按自己的框居中压轴+//(见 workbench.rs group_header);靠首字母字形宽度反推的 GROUP_HEAD_INSET 已删(2026-09-22)。/// 侧栏标题 "Wake" 的左内边距:同样让首字母 W 的字形中心落在轴上。/// 实测 16px semibold 的 W 宽 14.25、左承距 0.5,文字左缘需 19.65;/// 减去容器的 SIDEBAR_EDGE 得 9.15,取 9.0(2x 屏下 0.5px 以下的差会被光栅化吃掉)。diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rsindex 31e8535..8bcb52a 100644--- a/crates/wake/src/workbench.rs+++ b/crates/wake/src/workbench.rs@@ -37,6 +37,7 @@ use gpui_component::input::{Input, InputEvent, InputState};use gpui_component::list::{List, ListDelegate, ListEvent, ListItem, ListState};use gpui_component::menu::{DropdownMenu as _, PopupMenuItem};use gpui_component::notification::Notification;+use gpui_component::progress::Progress;use gpui_component::scroll::{AutoScroll, ScrollableElement as _};use gpui_component::spinner::Spinner;use gpui_component::text::{TextView, TextViewStyle};@@ -813,7 +814,7 @@ impl ListDelegate for SessionsDelegate {).child(h_flex()- .gap(px(6.))+ .gap(ICON_TEXT_GAP).text_size(FONT_LABEL).text_color(theme.muted_foreground).child(@@ -1394,7 +1395,7 @@ impl ListDelegate for SearchDelegate {.gap(px(6.)).child(h_flex()- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).text_size(FONT_CAPTION).child(img(h.session.agent.brand_icon(theme.mode.is_dark()))@@ -2330,6 +2331,31 @@ pub(crate) struct LocationSettingsSnapshot {pub(crate) diverged: bool,}+/// Settings/Memory locations 的一行(= 一个记忆来源:各家默认的目录 / 文件 / 库 /+/// 项目模式,或用户加的自定义目录 / 文件)+#[derive(Clone)]+pub(crate) struct MemoryLocationRow {+ pub(crate) agent: AgentId,+ /// `~/…` 展示形态;项目模式原样(`<project>/CLAUDE.md`)+ pub(crate) display: SharedString,+ /// 来源 id(`MemorySource::id`):停用开关、自定义行的落库路径都是它+ pub(crate) raw: SharedString,+ /// 文件数,或路径不存在时的状态词+ pub(crate) tally: SharedString,+ /// 具体路径当前存在(项目模式恒 true,但没有 Show in Finder)+ pub(crate) exists: bool,+ pub(crate) pattern: bool,+ /// 用户加的(可编辑、可删);默认来源只能开关+ pub(crate) custom: bool,+ pub(crate) enabled: bool,+}++#[derive(Clone)]+pub(crate) struct MemoryLocationSettingsSnapshot {+ pub(crate) rows: Vec<MemoryLocationRow>,+ pub(crate) diverged: bool,+}+#[derive(Clone)]pub(crate) struct DataSettingsSnapshot {pub(crate) display_path: SharedString,@@ -2367,6 +2393,28 @@ enum FormTarget {},}+/// 路径表单的一份规格:Session locations 与 Memory locations 共用同一个表单(agent+/// 下拉 + 路径输入 + 选择钮,Cancel/Save 只在有改动时出现;编辑态动作行左 Remove、+/// 右 Show in Finder),两页的差别全在这里+struct PathFormSpec {+ title: &'static str,+ ok_label: &'static str,+ /// 路径字段的标签("Folder" / "Folder or file")+ field_label: &'static str,+ init_agent: AgentId,+ init_path: SharedString,+ /// 选择器是否也收文件(记忆来源可以是单个文件)+ pick_files: bool,+ /// 编辑态动作行 Show in Finder 挂的路径:Some = 这条路径当下存在(添加态、路径不在+ /// 都是 None)+ reveal: Option<SharedString>,+ /// 编辑态 Remove(只有真正可删的自定义行才有)+ remove: Option<Rc<dyn Fn(&mut Workbench, &mut Window, &mut Context<Workbench>)>>,+ /// 提交;返回 false = 表单留着(校验没过,或已手工收场)+ commit:+ Rc<dyn Fn(&mut Workbench, AgentId, String, &mut Window, &mut Context<Workbench>) -> bool>,+}+impl Workbench {pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {let db_path = wake_core::db::default_db_path();@@ -3163,17 +3211,84 @@ impl Workbench {window: &mut Window,cx: &mut Context<Self>,) {- let (title, ok_label, init_agent, init_path): (- &'static str,- &'static str,- AgentId,- SharedString,- ) = match &target {- FormTarget::Add => (t("Add location"), t("Add"), AgentId::ClaudeCode, "".into()),- FormTarget::Edit { agent, path, .. } => {- (t("Edit location"), t("Save"), *agent, path.clone())+ // 编辑态动作行:Show in Finder 只挂真实存在的路径——目录或 SQLite 库文件都算+ // (open_in_finder 对文件走 reveal 选中;用 is_dir 会把三家库文件行的 Finder 恒+ // 隐藏,2026-08-24 Codex review),fs 探测一次、不进每帧 builder;Remove 只属于+ // 真正可删除的自定义 location,内置 location 由行内开关停用、不删除+ let (title, ok_label, init_agent, init_path, reveal, remove) = match &target {+ FormTarget::Add => (+ t("Add location"),+ t("Add"),+ AgentId::ClaudeCode,+ SharedString::from(""),+ None,+ None,+ ),+ FormTarget::Edit {+ agent,+ path,+ custom,+ ..+ } => {+ let reveal = std::path::Path::new(path.as_ref())+ .exists()+ .then(|| path.clone());+ let remove: Option<+ Rc<dyn Fn(&mut Workbench, &mut Window, &mut Context<Workbench>)>,+ > = if *custom {+ let (agent, stored) = (*agent, path.clone());+ Some(Rc::new(move |this: &mut Workbench, window, cx| {+ this.delete_location(agent, stored.clone(), window, cx)+ }))+ } else {+ None+ };+ (+ t("Edit location"),+ t("Save"),+ *agent,+ path.clone(),+ reveal,+ remove,+ )}};+ let commit_target = target;+ self.open_path_form(+ PathFormSpec {+ title,+ ok_label,+ field_label: t("Folder"),+ init_agent,+ init_path,+ pick_files: false,+ reveal,+ remove,+ commit: Rc::new(move |this, agent, text, window, cx| {+ this.commit_location_form(commit_target.clone(), agent, text, window, cx)+ }),+ },+ window,+ cx,+ );+ }++ /// 路径表单本体(添加/编辑共用一套 UI,2026-08-24 定稿):agent 下拉 + 路径输入框+ /// (可手输,~ 展开)+ 选择按钮;Cancel/Save 只在有改动时出现。表单作为 Settings+ /// 窗口的模态层,esc/取消回到来源页。Session locations 与 Memory locations 的差别+ /// 全在 `PathFormSpec` 里+ fn open_path_form(&mut self, spec: PathFormSpec, window: &mut Window, cx: &mut Context<Self>) {+ let PathFormSpec {+ title,+ ok_label,+ field_label,+ init_agent,+ init_path,+ pick_files,+ reveal,+ remove,+ commit,+ } = spec;// 占位符须与校验规则(Path::is_absolute)同形:Windows 上没有盘符// 的 `/absolute/...` 并不算绝对路径,照着占位符敲会被拒let placeholder = if cfg!(target_os = "windows") {@@ -3186,13 +3301,6 @@ impl Workbench {let v = init_path.clone();path_input.update(cx, |st, cx| st.set_value(v, window, cx));}- // 编辑态动作行的 Finder 只挂真实存在的路径——目录或 SQLite 库文件都算- // (open_in_finder 对文件走 reveal 选中;用 is_dir 会把三家库文件行的- // Finder 恒隐藏,2026-08-24 Codex review)。fs 探测一次,不进每帧 builder- let edit_exists = match &target {- FormTarget::Add => None,- FormTarget::Edit { path, .. } => Some(std::path::Path::new(path.as_ref()).exists()),- };// 表单状态放 Rc<Cell>/entity 而非宿主字段:builder 每帧重跑,闭包内// read 宿主 entity 必 double-lease panic(与 refresh 进度弹窗同一约束)let selected: Rc<Cell<AgentId>> = Rc::new(Cell::new(init_agent));@@ -3223,8 +3331,9 @@ impl Workbench {let ok_entity = entity.clone();let ok_input = path_input.clone();let ok_sel = selected.clone();- let ok_target = target.clone();- let action_target = target.clone();+ let ok_commit = commit.clone();+ let remove = remove.clone();+ let reveal = reveal.clone();let dialog = dialog.title(div()@@ -3262,7 +3371,7 @@ impl Workbench {.rounded(RADIUS_BUTTON).child(h_flex()- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).items_center().child(img(sel.brand_icon(dark))@@ -3289,7 +3398,7 @@ impl Workbench {menu = menu.item(PopupMenuItem::element(move |_, _| {h_flex()- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).items_center().child(img(a.brand_icon(dark))@@ -3320,7 +3429,7 @@ impl Workbench {.flex_shrink_0().text_size(FONT_CAPTION).text_color(theme.muted_foreground)- .child(t("Folder")),+ .child(field_label),).child(div().flex_1().min_w_0().child(Input::new(&browse_input))).child(@@ -3328,118 +3437,103 @@ impl Workbench {.outline().rounded(RADIUS_BUTTON).icon(icon("icons/folder.svg").with_size(px(13.)))- .tooltip(t("Choose a folder"))+ .tooltip(if pick_files {+ t("Choose a folder or file")+ } else {+ t("Choose a folder")+ }).on_click({let entity = browse_entity.clone();let input = browse_input.clone();move |_, window, cx| {let input = input.clone();entity.update(cx, |this, cx| {- this.browse_for_location(input, window, cx)+ this.browse_for_location(+ input, pick_files, window, cx,+ )});}}),),)- .when_some(edit_exists, |el, exists| {- let FormTarget::Edit {- agent,- path,- root: _,- custom,- individual_default: _,- } = action_target.clone()- else {- unreachable!("edit_exists 仅在 Edit 目标下为 Some")- };- let remove_entity = entity.clone();- el.when(custom || exists, |el| {- el.child(- // 动作行遵循破坏性靠左惯例:Remove 靠左、Show in- // Finder 靠右。Remove 只属于真正可删除的自定义- // location;内置 location 由行内开关停用,不删除。- // 两钮手排:内边距 = 轴缩进,Remove- // 左侧再减 1.5 补 lucide 字形内白(24 视框留 3- // 单位),字形左缘正落标签轴;右钮文字右缘正落- // 浏览钮右缘。全正值内边距,胶囊完整在内容盒里- h_flex()- .pt(SPACE_XS)- .items_center()- .justify_between()- .when(custom, |el| {- el.child(- h_flex()- .id("loc-remove")- .h(BUTTON_SM_H)- .pl(BUTTON_SM_PX - px(1.5))- .pr(BUTTON_SM_PX)- .rounded(RADIUS_BUTTON)- .items_center()- .gap(px(6.))- .cursor_pointer()- .text_size(FONT_BODY)- .text_color(theme.danger)- .hover(|s| s.bg(theme.danger.opacity(0.1)))- .active(|s| s.bg(theme.danger.opacity(0.16)))- .on_click({- let remove_entity = remove_entity.clone();- let stored = path.clone();- move |_, window, cx| {- // 整栈收场(表单+过期面板);- // delete 内会重开新快照面板- window.close_all_dialogs(cx);- let stored = stored.clone();- remove_entity.update(cx, |this, cx| {- this.delete_location(- agent, stored, window, cx,- )- });- }- })- .child(- icon("icons/trash-2.svg")- .with_size(px(13.))- .flex_shrink_0(),- )- .child(t("Remove")),- )- })- .when(exists, |el| {- el.child(- h_flex()- .id("loc-reveal")- .h(BUTTON_SM_H)- .px(BUTTON_SM_PX)- .rounded(RADIUS_BUTTON)- .items_center()- .gap(px(6.))- .cursor_pointer()- .text_size(FONT_BODY)- .text_color(theme.foreground)- .hover(|s| s.bg(theme.secondary_hover))- .active(|s| s.bg(theme.secondary_active))- .on_click(move |_, _, _| {- terminal::open_in_file_manager(&path)- })- .child(- icon("icons/folder.svg")- .with_size(px(13.))- .flex_shrink_0()- .text_color(theme.muted_foreground),- )- .child(show_in_fm()),- )- }),- )- })+ .when(remove.is_some() || reveal.is_some(), |el| {+ el.child(+ // 动作行遵循破坏性靠左惯例:Remove 靠左、Show in+ // Finder 靠右。两钮手排:内边距 = 轴缩进,Remove+ // 左侧再减 1.5 补 lucide 字形内白(24 视框留 3+ // 单位),字形左缘正落标签轴;右钮文字右缘正落+ // 浏览钮右缘。全正值内边距,胶囊完整在内容盒里+ h_flex()+ .pt(SPACE_XS)+ .items_center()+ .justify_between()+ .when_some(remove.clone(), |el, remove| {+ let remove_entity = entity.clone();+ el.child(+ h_flex()+ .id("loc-remove")+ .h(BUTTON_SM_H)+ .pl(BUTTON_SM_PX - px(1.5))+ .pr(BUTTON_SM_PX)+ .rounded(RADIUS_BUTTON)+ .items_center()+ .gap(ICON_TEXT_GAP)+ .cursor_pointer()+ .text_size(FONT_BODY)+ .text_color(theme.danger)+ .hover(|s| s.bg(theme.danger.opacity(0.1)))+ .active(|s| s.bg(theme.danger.opacity(0.16)))+ .on_click(move |_, window, cx| {+ // 整栈收场(表单+过期面板);+ // 删除内会让面板重读快照+ window.close_all_dialogs(cx);+ let remove = remove.clone();+ remove_entity.update(cx, |this, cx| {+ remove(this, window, cx)+ });+ })+ .child(+ icon("icons/trash-2.svg")+ .with_size(px(13.))+ .flex_shrink_0(),+ )+ .child(t("Remove")),+ )+ })+ .when_some(reveal.clone(), |el, path| {+ el.child(+ h_flex()+ .id("loc-reveal")+ .h(BUTTON_SM_H)+ .px(BUTTON_SM_PX)+ .rounded(RADIUS_BUTTON)+ .items_center()+ .gap(ICON_TEXT_GAP)+ .cursor_pointer()+ .text_size(FONT_BODY)+ .text_color(theme.foreground)+ .hover(|s| s.bg(theme.secondary_hover))+ .active(|s| s.bg(theme.secondary_active))+ .on_click(move |_, _, _| {+ terminal::open_in_file_manager(&path)+ })+ .child(+ icon("icons/folder.svg")+ .with_size(px(13.))+ .flex_shrink_0()+ .text_color(theme.muted_foreground),+ )+ .child(show_in_fm()),+ )+ }),+ )}),).on_ok(move |_, window, cx| {let path_text = ok_input.read(cx).text().to_string();let agent = ok_sel.get();- ok_entity.update(cx, |this, cx| {- this.commit_location_form(ok_target.clone(), agent, path_text, window, cx)- })+ let commit = ok_commit.clone();+ ok_entity.update(cx, |this, cx| commit(this, agent, path_text, window, cx))});if dirty {dialog.footer(@@ -3464,15 +3558,17 @@ impl Workbench {});}- /// 表单的目录选择按钮:系统选择器,选中即回填输入框(取消无事发生)+ /// 表单的选择按钮:系统选择器,选中即回填输入框(取消无事发生);记忆来源的+ /// 表单也收文件fn browse_for_location(&mut self,input: Entity<InputState>,+ files: bool,window: &mut Window,cx: &mut Context<Self>,) {let rx = cx.prompt_for_paths(PathPromptOptions {- files: false,+ files,directories: true,multiple: false,prompt: Some(t("Choose").into()),@@ -3491,45 +3587,54 @@ impl Workbench {.detach();}- /// 表单落库。返回值交给 on_ok:false = 表单留着(校验没过,或已手工收场)。- /// 纯路径管理:不校验目录内容(2026-08-24 用户定稿),只拒空/相对路径与- /// 同家重叠;预设行的编辑落库为"压默认 + 记自定义"- fn commit_location_form(- &mut self,- target: FormTarget,- agent_new: AgentId,- raw_text: String,+ /// 表单里手输/选中的路径整形(两个路径表单共用):`~` 展开;Windows 上把手输的+ /// '/' 折成 '\'(`~/.claude` 展开后是 `C:\Users\me/.claude` 这种混分隔符形态,而+ /// path_owns 的重叠判定是字节精确比较、explorer 只认反斜杠——不在入口归一,同一+ /// 目录就会以两种拼写各注册一份;POSIX 不动:'\' 在那边是合法文件名字符);绝对性+ /// 先判、只判一次(is_absolute 三端同判据,空串它也判 false;**必须判在剪尾之前**:+ /// `//` 剪完是空串,拿剪后的去判会退回未剪形态放行,2026-08-25 review);尾分隔符+ /// 剪掉(展示与重叠判定都吃这份),裸根("/"、"C:\")剪完会失去绝对性、原样保留。+ /// 不是绝对路径就弹提示、给 None+ fn absolute_form_path(+ &self,+ raw: &str,window: &mut Window,cx: &mut Context<Self>,- ) -> bool {- let expanded = expand_tilde(raw_text.trim());- // Windows 上把手输的 '/' 折成 '\':`~/.claude` 展开后是- // `C:\Users\me/.claude` 这种混分隔符形态,而 path_owns 的重叠判定是- // 字节精确比较、explorer 只认反斜杠——不在入口归一,同一目录就会以- // 两种拼写各注册一份(POSIX 不动:'\' 在那边是合法文件名字符)+ ) -> Option<String> {+ let expanded = expand_tilde(raw.trim());let expanded = if cfg!(target_os = "windows") {expanded.replace('/', "\\")} else {expanded};- // 绝对性先判、只判一次:is_absolute 三端同判据(starts_with('/') 会把- // 所有 Windows 盘符路径误拒),空串它也判 false,无需另设 is_empty 关。- // **必须判在剪尾之前**:`//` 剪完是空串,若拿剪后的结果去判就会退回- // 未剪形态放行,而旧版是拒的(2026-08-25 review)if !std::path::Path::new(&expanded).is_absolute() {window.push_notification(Notification::warning(t("Enter an absolute folder path")),cx,);- return false;+ return None;}- // 尾分隔符归一(展示与重叠判定都吃这份);裸根("/"、"C:\")剪完会- // 失去绝对性,原样保留let trimmed = expanded.trim_end_matches(std::path::is_separator);- let path = if std::path::Path::new(trimmed).is_absolute() {+ Some(if std::path::Path::new(trimmed).is_absolute() {trimmed.to_string()} else {- expanded.clone()+ expanded+ })+ }++ /// 表单落库。返回值交给 on_ok:false = 表单留着(校验没过,或已手工收场)。+ /// 纯路径管理:不校验目录内容(2026-08-24 用户定稿),只拒空/相对路径与+ /// 同家重叠;预设行的编辑落库为"压默认 + 记自定义"+ fn commit_location_form(+ &mut self,+ target: FormTarget,+ agent_new: AgentId,+ raw_text: String,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> bool {+ let Some(path) = self.absolute_form_path(&raw_text, window, cx) else {+ return false;};// 各家归一化(codex:直选 sessions 树/平铺 archived 上提到家层,侧档// 找回)。静态分派,不依赖该家实例是否还在 roster(默认被移除时也要@@ -3684,34 +3789,46 @@ impl Workbench {window: &mut Window,cx: &mut Context<Self>,) {- match self+ let res = self.store- .set_location_enabled(agent.as_str(), path.as_ref(), enabled)- {- Err(e) => window.push_notification(- Notification::error(crate::tf!("Couldn't update location: {}", e)),- cx,- ),+ .set_location_enabled(agent.as_str(), path.as_ref(), enabled);+ self.apply_roster_change(+ res,+ t("Couldn't update location"),+ Notification::info(if enabled {+ t("Location enabled")+ } else {+ t("Location disabled")+ }),+ window,+ cx,+ );+ }++ /// 配置写库后的统一收尾:失败弹错;成功先跑 `on_ok`(location:roster 换代 + 补扫;+ /// 记忆来源:只同步一次记忆)再提示——location 增删改与开关、记忆来源增删改与开关+ /// 同一条时序,别各自手写。Settings 页观察 Workbench 的 notify 并重读快照,不需要+ /// 关闭 / 重开管理面板+ fn apply_config_change(+ &mut self,+ res: anyhow::Result<()>,+ err_prefix: &'static str,+ ok_note: Notification,+ on_ok: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ match res {+ Err(e) => window+ .push_notification(Notification::error(crate::tf!("{}: {}", err_prefix, e)), cx),Ok(()) => {- self.rebuild_roster(cx);- self.kick_incremental_scan(cx);- window.push_notification(- Notification::info(if enabled {- t("Location enabled")- } else {- t("Location disabled")- }),- cx,- );- window.refresh();+ on_ok(self, window, cx);+ window.push_notification(ok_note, cx);}}}- /// location 变更的统一收尾(删/恢复/表单提交成功共用)。Settings 页- /// 观察 Workbench 的 notify 并重读快照,不需要关闭/重开管理面板。- /// 配置写库后的统一收尾:失败弹错,成功走"roster 换代 + 补扫 + 提示"- /// ——location 增删改、开关与远程 host 开关同一条时序,别各自手写+ /// location 变更(删 / 恢复 / 开关 / 表单提交成功)的收尾:roster 换代 + 补扫fn apply_roster_change(&mut self,res: anyhow::Result<()>,@@ -3720,19 +3837,270 @@ impl Workbench {window: &mut Window,cx: &mut Context<Self>,) {- match res {- Err(e) => {- window.push_notification(- Notification::error(crate::tf!("{}: {}", err_prefix, e)),- cx,- );+ self.apply_config_change(+ res,+ err_prefix,+ ok_note,+ |this, _, cx| {+ this.rebuild_roster(cx);+ this.kick_incremental_scan(cx);+ },+ window,+ cx,+ );+ }++ // ---------- 记忆来源(Settings → Memory locations) ----------++ /// Memory locations 面板的快照:`memory_source_plan` 给的每个本地实例的来源(默认 ++ /// 项目模式 + 自定义,与 scanner 同一份),按 AgentId 声明序分组;计数按来源 id 从+ /// memories 表聚合(停用的来源行已出库,计数自然是 0)。三条 SQL + 每来源一次 stat:+ /// Settings 在 observe 回调里取一次,不在 render 里每帧算+ pub(crate) fn memory_location_settings_snapshot(&self) -> MemoryLocationSettingsSnapshot {+ let counts = self.store.memory_source_counts().unwrap_or_default();+ // 只是显示,读不出就按"没配置"画(scanner 那边读不出会整轮不动,别混为一谈)+ let (customs, disabled) = self.store.memory_source_overrides().unwrap_or_default();+ let diverged = !customs.is_empty() || !disabled.is_empty();+ let plan = wake_core::adapters::memory_source_plan(&self.adapters, &customs, &disabled);+ let mut by_agent: std::collections::BTreeMap<AgentId, Vec<MemoryLocationRow>> =+ std::collections::BTreeMap::new();+ for planned in plan {+ if !planned.host.is_empty() {+ continue;}- Ok(()) => {- self.rebuild_roster(cx);- self.kick_incremental_scan(cx);- window.push_notification(ok_note, cx);+ for p in planned.sources {+ let agent = p.source.agent;+ let id = p.source.id();+ let pattern = p.source.is_pattern();+ let exists = pattern || p.source.path.exists();+ let count = counts+ .get(&(agent.as_str().to_string(), id.clone()))+ .copied()+ .unwrap_or(0);+ by_agent.entry(agent).or_default().push(MemoryLocationRow {+ agent,+ display: if pattern {+ id.clone().into()+ } else {+ tilde_path(&id).into()+ },+ tally: if exists {+ file_tally(count).into()+ } else {+ t("Not found").into()+ },+ enabled: p.enabled,+ raw: id.into(),+ exists,+ pattern,+ custom: p.custom,+ });}}+ MemoryLocationSettingsSnapshot {+ rows: by_agent.into_values().flatten().collect(),+ diverged,+ }+ }++ pub(crate) fn open_add_memory_location_form(+ &mut self,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ self.open_path_form(+ PathFormSpec {+ title: t("Add memory location"),+ ok_label: t("Add"),+ field_label: t("Folder or file"),+ init_agent: AgentId::ClaudeCode,+ init_path: "".into(),+ pick_files: true,+ reveal: None,+ remove: None,+ commit: Rc::new(|this, agent, text, window, cx| {+ this.commit_memory_location_form(None, agent, text, window, cx)+ }),+ },+ window,+ cx,+ );+ }++ /// 只有自定义行可编辑(面板只对它们挂 Edit);默认来源由行内开关停用+ pub(crate) fn open_edit_memory_location_form(+ &mut self,+ row: MemoryLocationRow,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let old = (row.agent, row.raw.clone());+ let remove_old = old.clone();+ self.open_path_form(+ PathFormSpec {+ title: t("Edit memory location"),+ ok_label: t("Save"),+ field_label: t("Folder or file"),+ init_agent: row.agent,+ init_path: row.raw.clone(),+ pick_files: true,+ reveal: row.exists.then(|| row.raw.clone()),+ remove: Some(Rc::new(move |this, window, cx| {+ this.delete_memory_source(remove_old.0, remove_old.1.clone(), window, cx)+ })),+ commit: Rc::new(move |this, agent, text, window, cx| {+ this.commit_memory_location_form(Some(old.clone()), agent, text, window, cx)+ }),+ },+ window,+ cx,+ );+ }++ /// 记忆来源表单落库。纯路径管理:目录或文件都收、不校验内容,只拒相对路径与同家+ /// 重复(默认来源里已有、或自定义里已有);编辑走 replace_memory_source 单事务+ fn commit_memory_location_form(+ &mut self,+ old: Option<(AgentId, SharedString)>,+ agent_new: AgentId,+ raw_text: String,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> bool {+ let Some(path) = self.absolute_form_path(&raw_text, window, cx) else {+ return false;+ };+ if old+ .as_ref()+ .is_some_and(|(agent, p)| *agent == agent_new && p.as_ref() == path)+ {+ return true;+ }+ // 与面板同一份来源清单查重:该家的默认具体路径(项目模式不算)与已有的自定义+ let (customs, disabled) = self.store.memory_source_overrides().unwrap_or_default();+ let duplicate =+ wake_core::adapters::memory_source_plan(&self.adapters, &customs, &disabled)+ .into_iter()+ .flat_map(|p| p.sources)+ .any(|p| {+ p.source.agent == agent_new+ && !p.source.is_pattern()+ && p.source.path.to_string_lossy() == path+ });+ if duplicate {+ window.push_notification(+ Notification::info(t("This path is already in Wake's memory locations")),+ cx,+ );+ return false;+ }+ let res = match &old {+ None => self.store.add_memory_source(agent_new.as_str(), &path),+ Some((agent, p)) => self.store.replace_memory_source(+ agent.as_str(),+ p.as_ref(),+ agent_new.as_str(),+ &path,+ ),+ };+ if let Err(e) = res {+ window.push_notification(Notification::error(crate::tf!("Save failed: {}", e)), cx);+ return false;+ }+ window.close_all_dialogs(cx);+ let note = if old.is_none() {+ t("Location added")+ } else {+ t("Location updated")+ };+ self.memory_change_applied(window, cx);+ window.push_notification(Notification::success(note), cx);+ false+ }++ pub(crate) fn delete_memory_source(+ &mut self,+ agent: AgentId,+ stored: SharedString,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let res = self+ .store+ .remove_memory_source(agent.as_str(), stored.as_ref());+ self.apply_memory_change(+ res,+ t("Remove failed"),+ Notification::info(t("Location removed")),+ window,+ cx,+ );+ }++ pub(crate) fn restore_default_memory_locations(+ &mut self,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let res = self.store.clear_memory_source_overrides();+ self.apply_memory_change(+ res,+ t("Restore failed"),+ Notification::info(t("Locations restored to defaults")),+ window,+ cx,+ );+ }++ /// Memory locations 行内开关+ pub(crate) fn set_memory_source_enabled(+ &mut self,+ agent: AgentId,+ id: SharedString,+ enabled: bool,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let res = self+ .store+ .set_memory_source_enabled(agent.as_str(), id.as_ref(), enabled);+ self.apply_memory_change(+ res,+ t("Couldn't update location"),+ Notification::info(if enabled {+ t("Location enabled")+ } else {+ t("Location disabled")+ }),+ window,+ cx,+ );+ }++ /// 记忆来源变更的收尾:只同步一次记忆(`sync_memories_quietly` 按新配置重读,不重扫+ /// 会话、不换 roster;扫描进行中就交给它的收尾)+ fn apply_memory_change(+ &mut self,+ res: anyhow::Result<()>,+ err_prefix: &'static str,+ ok_note: Notification,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ self.apply_config_change(+ res,+ err_prefix,+ ok_note,+ Self::memory_change_applied,+ window,+ cx,+ );+ }++ /// 记忆来源配置已落库之后该做的事(表单提交成功也走这里)+ fn memory_change_applied(&mut self, _window: &mut Window, cx: &mut Context<Self>) {+ self.sync_memories_quietly(cx);+ cx.notify();}// ---------- 远程 host(Settings → Remote hosts) ----------@@ -3954,9 +4322,11 @@ impl Workbench {self.pending_rescan = false;self.kick_incremental_scan(cx);}- // 扫描期间整页目的地的重载被按住(见 reload_insights 注释),终态补最后一次+ // 扫描期间整页目的地的重载被按住(见 reload_insights 注释),终态补最后一次;+ // 扫描期间排队的记忆同步也在这里补if !self.scan.scanning {self.reload_page(cx);+ self.drain_pending_memory_sync(cx);}cx.notify();note@@ -4993,11 +5363,16 @@ impl Workbench {&& !self.cleanup.open;// 常态沉默,仅刷新中/监听失效时出现;None 时状态栏整行不渲染。// 文案在此按 scan 现算,不另存字段——存下来就会有第二个写入点要维护+ // 进行中的活动(会话扫描 / 记忆同步 / 远程同步):行首转圈——与页头 Refresh 按钮+ // loading 态同一个 Spinner;出错的那句行首是静态图标+ let busy = self.scan.scanning || self.memory.syncing || !self.syncing_hosts.is_empty();let note = if self.scan.scanning {Some(match self.scan.total {0 => t("Refreshing…").to_string(),total => crate::tf!("Refreshing {}/{}", self.scan.done, total),})+ } else if self.memory.syncing {+ Some(t("Refreshing memory…").to_string())} else if let [only] = self.syncing_hosts.as_slice() {// rsync 与扫描并行;扫描先收工时这里接着展示同步状态Some(crate::tf!("Syncing {}…", only))@@ -5012,17 +5387,41 @@ impl Workbench {.as_ref().map(|e| crate::tf!("Refresh failed: {}", e))};+ // 文字下方一条进度条(用户 2026-09-22 要的):会话扫描按 done/total 定值;总数+ // 未知、记忆同步与远程同步报不出进度,走不定值滑动+ let progress = busy.then(|| {+ let bar = Progress::new("refresh-progress")+ .with_size(px(3.))+ .color(theme.primary);+ let bar = if self.scan.scanning && self.scan.total > 0 {+ bar.value(self.scan.done as f32 / self.scan.total as f32 * 100.)+ } else {+ bar.loading(true)+ };+ bar.into_any_element()+ });let status: Option<AnyElement> = if let Some(note) = note {+ let lead = if busy {+ div()+ .flex_shrink_0()+ .child(+ Spinner::new()+ .with_size(px(12.))+ .color(theme.muted_foreground),+ )+ .into_any_element()+ } else {+ icon("icons/refresh-cw.svg")+ .with_size(px(12.))+ .flex_shrink_0()+ .into_any_element()+ };Some(h_flex().w_full()- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).text_color(theme.muted_foreground)- .child(- icon("icons/refresh-cw.svg")- .with_size(px(12.))- .flex_shrink_0(),- )+ .child(lead).child(div().min_w_0().truncate().child(note)).into_any_element(),)@@ -5030,7 +5429,7 @@ impl Workbench {Some(h_flex().w_full()- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).text_color(theme.muted_foreground).child(div()@@ -5104,18 +5503,20 @@ impl Workbench {.border_color(theme.sidebar_border).when_some(status, |this, status| {this.child(- h_flex()+ v_flex().px(SPACE_XL).pt(SPACE_MD)+ .gap(SPACE_SM).text_size(FONT_LABEL)- .child(status),+ .child(status)+ .children(progress),)})// 两端分置的图标条(Zed 状态栏 / Xcode 导航条那种,不带盒子):左端// 页切换 Sessions / Memory / Insights,当前页那颗用侧栏选中色做底;- // 右端只有 Settings。Refresh 不在这里——它住在各页页头右端(全库重扫,- // 三页同一条路;用户 2026-09-21 三轮反馈:六个一样的图标挤一排不行、- // 刷新不该放这里、带边框的分段盒子也不行)+ // 右端只有 Settings。Refresh 不在这里——它住在各页页头右端(会话页整库+ // 重扫、Memory 页只同步记忆;用户 2026-09-21 三轮反馈:六个一样的图标挤+ // 一排不行、刷新不该放这里、带边框的分段盒子也不行).child(h_flex().h(SIDEBAR_FOOTER_ROW_HEIGHT)@@ -5365,17 +5766,23 @@ impl Workbench {.into_any_element()}- /// 各页页头右端的 Refresh(⌘R 同一条路,全库重扫、不分页——Memory 与 Insights 的- /// 数据都是扫描收尾派生的):扫描进行中显示转圈并禁用- fn refresh_button(&self, cx: &Context<Self>) -> AnyElement {+ /// 页头右端的 Refresh(三页同一外形,各刷各的——用户 2026-09-22 定):会话页与+ /// Insights 走整库重扫(`refresh_sessions`,Insights 的数字全是会话派生的),Memory+ /// 页只同步记忆来源(`refresh_memories`)。进行中 `loading` + 禁用+ fn refresh_button(+ &self,+ busy: bool,+ on_click: impl Fn(&mut Self, &mut Window, &mut Context<Self>) + 'static,+ cx: &Context<Self>,+ ) -> AnyElement {Button::new("refresh").ghost().rounded(RADIUS_BUTTON).icon(icon("icons/refresh-cw.svg").with_size(px(16.)))- .loading(self.scan.scanning)- .disabled(self.scan.scanning)+ .loading(busy)+ .disabled(busy).tooltip(t("Refresh"))- .on_click(cx.listener(|this, _, window, cx| this.refresh_sessions(window, cx)))+ .on_click(cx.listener(move |this, _, window, cx| on_click(this, window, cx))).into_any_element()}@@ -5472,7 +5879,7 @@ impl Workbench {Some(h_flex().gap(SPACE_XS)- .child(self.refresh_button(cx))+ .child(self.refresh_button(self.scan.scanning, Self::refresh_sessions, cx)).child(sort_menu).into_any_element(),),@@ -6077,7 +6484,7 @@ impl Workbench {t("Insights"),subtitle,SPACE_XXL,- Some(self.refresh_button(cx)),+ Some(self.refresh_button(self.scan.scanning, Self::refresh_sessions, cx)),cx,)).child(body)@@ -6536,7 +6943,7 @@ impl Workbench {lead.push(h_flex().min_w_0()- .gap(SPACE_XS)+ .gap(ICON_TEXT_GAP).child(icon("icons/git-branch.svg").with_size(px(11.))@@ -6667,7 +7074,7 @@ impl Workbench {menu = menu.item(PopupMenuItem::element(move |_, _| {h_flex()- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).items_center().child(open_in_icon(Some(term),@@ -6759,7 +7166,7 @@ impl Workbench {.into_any_element(),h_flex().min_w_0()- .gap(px(6.))+ .gap(ICON_TEXT_GAP).child(icon("icons/folder.svg").with_size(px(12.)).flex_shrink_0()).child(div().min_w_0().truncate().child(detail_path)).into_any_element(),@@ -6772,7 +7179,7 @@ impl Workbench {h_flex().w_full().min_w_0()- .gap(px(6.))+ .gap(ICON_TEXT_GAP).items_center().child(icon("icons/calendar.svg")@@ -6835,7 +7242,7 @@ impl Workbench {.bg(theme.popover).items_center().justify_center()- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).text_color(theme.muted_foreground).child(Spinner::new().small()).child(div().text_size(FONT_BODY).child(t("Loading session…")))@@ -6913,7 +7320,10 @@ impl Workbench {}}-/// 可折叠分组头:chevron + 文字,点击切换+/// 侧栏组头(Agents / Projects):行首是 15px 折叠 chevron(收起指右、展开指下;与导航行+/// 图标同一档,描边粗细才一致),中心压 26.75 轴(用户 2026-09-22 定"箭头放到开头,对准+/// 上面菜单的 icon 和红绿灯的红灯";原先 chevron 跟在文字后,靠首字母字形宽度反推的+/// GROUP_HEAD_INSET 压轴,字号 / 字重 / 语言一变就失效)fn group_header(id: &'static str,text: &'static str,@@ -6925,7 +7335,10 @@ fn group_header(div().id(id).flex_shrink_0()- .pl(GROUP_HEAD_INSET)+ // chevron 不占 18px 槽位、只按自己的框居中压轴:槽位居中再接统一间距,墨迹到+ // 文字会比导航行空出一截(chevron 墨迹只有约 5px 宽,用户 2026-09-22 "间隔太大");+ // 按框压轴后文字起点比导航行标签左 1.5px,墨迹到文字视觉约 10.9px、与导航行相当+ .pl(LEAD_INSET + (LEAD_BOX - NAV_ICON) / 2.).pr(SIDEBAR_EDGE).pt(SPACE_MD).pb(SPACE_XS)@@ -6934,20 +7347,21 @@ fn group_header(.on_click(on_click).child(h_flex()- .gap(SPACE_XS)- // 与主导航行同字号同字重(FONT_BODY / 常规),仅靠 muted 色- // 与"无行首图标"区分——加粗会让组头压过它统辖的行+ .gap(ICON_TEXT_GAP)+ // 与主导航行同字号同字重(FONT_BODY / 常规),仅靠 muted 色区分——+ // 加粗会让组头压过它统辖的行.text_size(FONT_BODY).text_color(theme.muted_foreground).hover(|s| s.text_colored(theme.foreground, FONT_BODY))- .child(text).child(icon("icons/chevron-right.svg")- .with_size(px(13.))+ .with_size(NAV_ICON)+ .flex_shrink_0().when(!collapsed, |ic| {ic.rotate(gpui::Radians(std::f32::consts::FRAC_PI_2))}),- ),+ )+ .child(text),)}@@ -7069,7 +7483,7 @@ fn usage_bar_row(let frac = (count as f32 / max.max(1) as f32).clamp(0., 1.);h_flex().h(SPACE_XXL)- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).items_center().when_some(lead, |row, lead| {row.child(@@ -8274,7 +8688,7 @@ fn thinking_panel(.w_full().min_w_0().items_center()- .gap(px(7.))+ .gap(ICON_TEXT_GAP).px(SPACE_MD).py(SPACE_SM).cursor_pointer()@@ -8389,7 +8803,7 @@ fn tool_cluster(.w_full().min_w_0().items_center()- .gap(px(7.))+ .gap(ICON_TEXT_GAP).px(SPACE_MD).py(SPACE_SM).cursor_pointer()@@ -8633,6 +9047,11 @@ pub(crate) fn session_tally(n: i64) -> String {crate::tp!("{} session", "{} sessions", n)}+/// "N files"(Memory locations 的行)+pub(crate) fn file_tally(n: i64) -> String {+ crate::tp!("{} file", "{} files", n)+}+/// 远程会话的 @host 徽章:填充胶囊但用 primary 淡底 + primary 字,与紧邻的 muted/// 项目胶囊拉开(描边版、muted 填充版都试过,用户否决 2026-09-03)。列表行与 ⌘K/// 结果行共用;详情页的描边版是有意的第三种@@ -8740,7 +9159,7 @@ fn detail_header_frame(h_flex().flex_1().min_w_0()- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).items_center().text_size(FONT_LABEL).text_color(theme.muted_foreground)@@ -8868,7 +9287,7 @@ fn sidebar_row(.child(h_flex().w_full()- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).child(// 定宽槽位保证文字起点统一;内部居中,使小图标的中心也落在// LEAD_AXIS 上(左对齐会让 14/15px 图标的中心偏离轴 1.5~2pt)@@ -8881,7 +9300,7 @@ fn sidebar_row(.child(match lead {// 线条图标比实心品牌图视觉轻,给它小一档才平衡RowLead::Icon(ic) => ic- .with_size(if sub { px(14.) } else { px(15.) })+ .with_size(if sub { px(14.) } else { NAV_ICON }).text_color(if active {theme.sidebar_accent_foreground} else {diff --git a/crates/wake/src/workbench/cleanup/filter.rs b/crates/wake/src/workbench/cleanup/filter.rsindex deb41b7..cc111c4 100644--- a/crates/wake/src/workbench/cleanup/filter.rs+++ b/crates/wake/src/workbench/cleanup/filter.rs@@ -171,16 +171,20 @@ fn agent_label(selected: bool,cx: &App,) -> Button {- option_label(button, label, selected, cx).pl(px(26.)).child(- // The button's content excludes its padding; return the brand icon- // to the reserved leading slot without shifting text on selection.- div()- .absolute()- .left(px(6. - 26.))- .top(px(6.5))- .size(px(15.))- .child(leading),- )+ // 行首 6px 处放 15px 品牌图,文字从 6 + 15 + ICON_TEXT_GAP 起(与别处图标-文字同距)+ let text_start = px(6.) + px(15.) + ICON_TEXT_GAP;+ option_label(button, label, selected, cx)+ .pl(text_start)+ .child(+ // The button's content excludes its padding; return the brand icon+ // to the reserved leading slot without shifting text on selection.+ div()+ .absolute()+ .left(px(6.) - text_start)+ .top(px(6.5))+ .size(px(15.))+ .child(leading),+ )}fn section(title: &'static str, selected: usize, options: Vec<Button>) -> AnyElement {diff --git a/crates/wake/src/workbench/cleanup/history.rs b/crates/wake/src/workbench/cleanup/history.rsindex 7401ddd..a21eeeb 100644--- a/crates/wake/src/workbench/cleanup/history.rs+++ b/crates/wake/src/workbench/cleanup/history.rs@@ -699,7 +699,7 @@ impl Workbench {.aria_label(format!("{} · {}", candidate.root.title, file_label)).h(px(40.)).px(SPACE_LG)- .gap(SPACE_SM)+ .gap(ICON_TEXT_GAP).border_t_1().border_color(theme.border).text_size(FONT_CAPTION)diff --git a/crates/wake/src/workbench/cleanup/rows.rs b/crates/wake/src/workbench/cleanup/rows.rsindex 36ebaac..1504499 100644--- a/crates/wake/src/workbench/cleanup/rows.rs+++ b/crates/wake/src/workbench/cleanup/rows.rs@@ -147,7 +147,7 @@ impl Workbench {.child(h_flex().min_w_0()- .gap(SPACE_XS)+ .gap(ICON_TEXT_GAP).items_center().text_size(FONT_LABEL).text_color(theme.muted_foreground)diff --git a/crates/wake/src/workbench/memory.rs b/crates/wake/src/workbench/memory.rsindex d30574c..1ec3e01 100644--- a/crates/wake/src/workbench/memory.rs+++ b/crates/wake/src/workbench/memory.rs@@ -7,9 +7,11 @@use super::*;use wake_core::adapters::memory_body;-use wake_core::models::{MemoryCounts, MemoryDoc, MemoryFilter, MemoryGroup, MemoryScope};+use wake_core::models::{+ MemoryCounts, MemoryDoc, MemoryFilter, MemoryGroup, MemoryScope, UserMemories,+};-/// 左列的一行:分组头(带该组第一份文档的下标,标签从它算)或一份文档+/// 左列的一行:时间分组头(带该组第一份文档的下标,标签从它的时间算)或一份文档#[derive(Clone, Copy)]enum MemoryRow {Group(usize),@@ -24,9 +26,20 @@ struct LoadedMemory {source_path: String,}+/// 侧栏导航的筛选(单选互斥,与会话侧栏同一模型:再点当前项回到 All)+#[derive(Debug, Clone, PartialEq, Eq)]+enum MemoryNav {+ All,+ /// All Memory 下的 User memory 行(会话侧栏 Starred 的同位):只列用户记忆+ User,+ Agent(AgentId),+ /// 空串是没归属的一组(侧栏的 Unknown project 行)+ Project(String),+}+pub(super) struct MemoryState {- /// store 已排好序:项目路径分组、组内新到旧、用户级最后;行里**不带正文**(列表列- /// 给的是空串),选中时按 key 另取+ /// 按更新时间倒序(GUI 自己排;store 给 MCP 的序是按项目、用户级最后);行里**不带+ /// 正文**(列表列给的是空串),选中时按 key 另取docs: Vec<MemoryDoc>,/// 组头 + 文档扁平成行,交 gpui::list 虚拟化——只画看得见的几行,行文案在画/// 的时候现算(译文与相对时间都不缓存,换语言不会留旧串)@@ -36,17 +49,21 @@ pub(super) struct MemoryState {selected: Option<String>,/// 选中后后台读,读到前是 None(转圈)loaded: Option<LoadedMemory>,- /// 侧栏导航的计数(All Memory / Agents / Projects),与 docs 同一次查询刷新+ /// 侧栏导航的计数(All Memory / User memory / Agents / Projects),与 docs 同一次+ /// 查询刷新counts: MemoryCounts,- /// 侧栏筛选(单选,与会话侧栏同一模型):agent 或项目,`Some("")` 是没归属的一组- agent: Option<AgentId>,- project: Option<String>,+ nav: MemoryNav,/// 筛选刚换过(进页归零、点了导航行):下一次重载必须查(扫描进行中也不按住)并把/// 列表拉回顶部、不恢复旧滚动位置scope_changed: bool,/// 进行中的列表/正文任务;新任务覆盖旧值即取消load_task: Option<Task<()>>,body_task: Option<Task<()>>,+ /// 页头 Refresh 起的记忆同步(只同步记忆,不重扫会话)进行中;期间再来的请求+ /// (Settings 改了 Memory locations)记 `sync_pending`,跑完补一次。任务本身 detach:+ /// 有 `syncing` 守着就不会重叠,不必再攥着句柄+ pub(super) syncing: bool,+ sync_pending: bool,}impl Default for MemoryState {@@ -59,34 +76,100 @@ impl Default for MemoryState {selected: None,loaded: None,counts: MemoryCounts::default(),- agent: None,- project: None,+ nav: MemoryNav::All,scope_changed: false,load_task: None,body_task: None,+ syncing: false,+ sync_pending: false,}}}impl Workbench {+ /// 用户记忆要不要置顶单列一组:侧栏选了 User memory 行时整页都是它,组头没意义、照时间分+ fn memory_pins_user(&self) -> bool {+ self.memory.nav != MemoryNav::User+ }+/// 进 Memory 页时从"全部"开始pub(super) fn reset_memory_scope(&mut self) {- self.memory.agent = None;- self.memory.project = None;+ self.memory.nav = MemoryNav::All;+ self.memory.scope_changed = true;+ }++ /// 侧栏导航行的唯一写入点(与会话侧栏的 set_scope 同形)+ fn set_memory_scope(&mut self, nav: MemoryNav, cx: &mut Context<Self>) {+ self.memory.nav = nav;self.memory.scope_changed = true;+ self.reload_memories(cx);+ }++ /// Memory 页页头的 Refresh:只同步记忆来源——读设置里当下的 Memory locations,不重扫+ /// 会话、不碰远程、不弹进度框;会话页的 Refresh 是整库重扫(用户 2026-09-22 定各刷+ /// 各的)。进行中侧栏状态行转圈 + 不定值进度条,跑完弹 "Memory refreshed"(会话那边是+ /// "Sessions refreshed")——同步只要几十毫秒,没有这两样就是"点了没反应"+ pub(super) fn refresh_memories(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ self.start_memory_sync(+ Some((+ window.window_handle(),+ Notification::success(t("Memory refreshed")),+ )),+ cx,+ );+ }++ /// Settings → Memory locations 变更的收尾:同一条同步,不另弹通知(变更本身已提示)+ pub(super) fn sync_memories_quietly(&mut self, cx: &mut Context<Self>) {+ self.start_memory_sync(None, cx);}- /// 侧栏导航行的唯一写入点(agent 与项目互斥,与会话侧栏的 set_scope 同形)- fn set_memory_scope(+ /// 扫描终态:扫描期间排队的记忆同步补上(`on_bg_event` 的终态分支调)+ pub(super) fn drain_pending_memory_sync(&mut self, cx: &mut Context<Self>) {+ if !self.memory.syncing && std::mem::take(&mut self.memory.sync_pending) {+ self.sync_memories_quietly(cx);+ }+ }++ /// 同步或扫描进行中都排队(`sync_pending`),跑完 / 扫描终态再补一次:扫描收尾的+ /// sync_memories 跑完到 UI 收到终态事件之间有空档,那时落库的 Memory locations 变更+ /// 会被漏掉(2026-09-22 review);按钮那时是禁用的,能撞上的只有 Settings 变更。+ /// 跑完重载列表并 notify,Settings 的 Memory locations 页据此重读计数;`done` 的通知+ /// 经窗口句柄投递——同步本身不依赖窗口,终态补跑那条路手里没有窗口+ fn start_memory_sync(&mut self,- agent: Option<AgentId>,- project: Option<String>,+ done: Option<(gpui::AnyWindowHandle, Notification)>,cx: &mut Context<Self>,) {- self.memory.agent = agent;- self.memory.project = project;- self.memory.scope_changed = true;- self.reload_memories(cx);+ if self.memory.syncing || self.scan.scanning {+ self.memory.sync_pending = true;+ return;+ }+ self.memory.syncing = true;+ 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) },+ );+ cx.spawn(async move |this, cx| {+ task.await;+ this.update(cx, |this, cx| {+ this.memory.syncing = false;+ if std::mem::take(&mut this.memory.sync_pending) {+ this.sync_memories_quietly(cx);+ }+ this.reload_memories(cx);+ cx.notify();+ })+ .ok();+ if let Some((window, note)) = done {+ cx.update_window(window, |_, window, cx| window.push_notification(note, cx))+ .ok();+ }+ })+ .detach();}/// refresh 顺带重载(与 reload_insights 同规矩):扫描进行中且已有数据就按住,@@ -102,18 +185,29 @@ impl Workbench {}self.memory.loading = self.memory.docs.is_empty();let store = self.store.clone();- // 侧栏的 "Unknown project" 行是 `Some("")`:筛的是没归属的一组,不是路径为空串的项目- let filter = MemoryFilter {- agents: self.memory.agent.into_iter().collect(),- project_paths: self- .memory- .project- .iter()- .filter(|p| !p.is_empty())- .cloned()- .collect(),- unattributed: self.memory.project.as_deref() == Some(""),- limit: 0,+ // 侧栏的 "Unknown project" 行是 `Project("")`:筛的是没归属的一组,不是路径为空串+ // 的项目。项目行只列项目记忆——用户记忆有自己的 User memory 行(用户 2026-09-22+ // 定);MCP 问一个项目仍连用户记忆一起给(`UserMemories` 的默认值 Alongside)+ let filter = match &self.memory.nav {+ MemoryNav::All => MemoryFilter::default(),+ MemoryNav::User => MemoryFilter {+ user: UserMemories::Only,+ ..Default::default()+ },+ MemoryNav::Agent(agent) => MemoryFilter {+ agents: vec![*agent],+ ..Default::default()+ },+ MemoryNav::Project(path) => MemoryFilter {+ project_paths: if path.is_empty() {+ Vec::new()+ } else {+ vec![path.clone()]+ },+ unattributed: path.is_empty(),+ user: UserMemories::Excluded,+ ..Default::default()+ },};let task = cx.background_spawn(async move {let docs = store.list_memories(&filter)?;@@ -123,9 +217,18 @@ impl Workbench {self.memory.load_task = Some(cx.spawn(async move |this, cx| {let loaded = task.await;this.update(cx, |this, cx| {- if let Ok((docs, counts)) = loaded {+ if let Ok((mut docs, counts)) = loaded {this.memory.counts = counts;- let rows = memory_rows(&docs);+ // 用户记忆对每个项目都成立、没有"发生时间"的意义,像会话列表的 Pinned+ // 那样单独一组置顶;其余按更新时间倒序进时间桶+ docs.sort_by(|a, b| {+ (a.scope != MemoryScope::User)+ .cmp(&(b.scope != MemoryScope::User))+ .then_with(|| b.updated_at.cmp(&a.updated_at))+ .then_with(|| a.key.cmp(&b.key))+ });+ let pin_user = this.memory_pins_user();+ let rows = memory_rows(&docs, Local::now().date_naive(), pin_user);// 重载来自每轮扫描,滚动位置要留住:splice 整段会把落在段内的// 滚动锚点归零(gpui 的 splice 只保段外的锚点),所以先记下再恢复;// 筛选刚换过则回到顶部@@ -279,7 +382,11 @@ impl Workbench {self.memory_context_title(),subtitle,SPACE_LG,- Some(self.refresh_button(cx)),+ Some(self.refresh_button(+ self.scan.scanning || self.memory.syncing,+ Self::refresh_memories,+ cx,+ )),cx,)).child(column),@@ -290,23 +397,20 @@ impl Workbench {/// 左列页头的标题 = 当前侧栏筛选(与会话页 context_title 同规矩)fn memory_context_title(&self) -> String {- if let Some(agent) = self.memory.agent {- return agent.display_name().to_string();- }- if let Some(path) = &self.memory.project {- if path.is_empty() {- return t("Unknown project").to_string();- }- return self+ match &self.memory.nav {+ MemoryNav::All => t("All Memory").to_string(),+ MemoryNav::User => t("User memory").to_string(),+ MemoryNav::Agent(agent) => agent.display_name().to_string(),+ MemoryNav::Project(path) if path.is_empty() => t("Unknown project").to_string(),+ MemoryNav::Project(path) => self.memory.counts.projects.iter().find(|p| &p.path == path).map(|p| p.name.clone())- .unwrap_or_else(|| t("Projects").to_string());+ .unwrap_or_else(|| t("Projects").to_string()),}- t("All Memory").to_string()}/// 记忆流:gpui::list 虚拟化(行高不等:分组头与两行的文档行)@@ -339,12 +443,14 @@ impl Workbench {};match row {MemoryRow::Group(first) => {- // 组头 = 会话流的时间分割线(用户 2026-09-21 定)+ // 组头 = 置顶的 User memory,或会话流同一套时间分割线(Today / Yesterday / …);+ // 文案画的时候现算+ let pin_user = self.memory_pins_user();let label = self.memory.docs.get(first)- .map(memory_group_label)+ .map(|d| memory_section_label(d, Local::now().date_naive(), pin_user)).unwrap_or_default();section_header_row(label, &theme).into_any_element()}@@ -400,15 +506,22 @@ impl Workbench {).child(h_flex()- .gap(px(6.))+ .gap(ICON_TEXT_GAP).text_size(FONT_LABEL).text_color(theme.muted_foreground)- // 项目名由组头说明,行里不重复挂项目徽章.child(img(d.agent.brand_icon(theme.mode.is_dark())).size(px(15.)).flex_shrink_0(),)+ // 项目徽章与会话行同款(muted 胶囊;用户级 / 没归属的+ // 也用组头同一套文案),用户 2026-09-21 定:组头说明了+ // 也要挂,和会话列表看起来一致+ .child(badge(+ memory_group_label(d),+ theme.muted,+ theme.muted_foreground,+ )).children(memory_badges(d, &theme)).child(div().flex_1()).child(@@ -499,7 +612,7 @@ impl Workbench {let meta_rows: Vec<AnyElement> = vec![h_flex().min_w_0()- .gap(px(6.))+ .gap(ICON_TEXT_GAP).child(icon("icons/file-text.svg").with_size(px(12.))@@ -509,7 +622,7 @@ impl Workbench {.into_any_element(),h_flex().min_w_0()- .gap(px(6.))+ .gap(ICON_TEXT_GAP).items_center().child(icon("icons/calendar.svg")@@ -586,11 +699,11 @@ impl Workbench {}/// Memory 页的侧栏导航,替换会话导航(搜索框、All Sessions / Starred、Agents /- /// Projects):All Memory 一行,再接 Agents / Projects 两组(`sidebar_groups`,与会话- /// 侧栏同一套组件、同一个单选模型)按记忆文件计数+ /// Projects):All Memory / User memory 两行,再接 Agents / Projects 两组+ /// (`sidebar_groups`,与会话侧栏同一套组件、同一个单选模型)按记忆文件计数pub(super) fn render_memory_nav(&self, cx: &Context<Self>) -> AnyElement {let counts = &self.memory.counts;- let all_active = self.memory.agent.is_none() && self.memory.project.is_none();+ let nav = &self.memory.nav;v_flex().flex_1().min_h_0()@@ -607,60 +720,97 @@ impl Workbench {RowLead::Icon(icon("icons/file-text.svg")),t("All Memory"),Some(counts.total),- all_active,+ *nav == MemoryNav::All,RowLevel::Primary,cx.listener(|this, _, _window, cx| {- this.set_memory_scope(None, None, cx);+ this.set_memory_scope(MemoryNav::All, cx);+ }),+ cx,+ ))+ // 会话侧栏 Starred 的同位(用户 2026-09-22 定):只列用户记忆,项目行+ // 里不再混它;再点一次回到全部,计数为零不挂徽章+ .child(sidebar_row(+ "memory-user",+ RowLead::Icon(icon("icons/user.svg")),+ t("User memory"),+ (counts.user > 0).then_some(counts.user),+ *nav == MemoryNav::User,+ RowLevel::Primary,+ cx.listener(|this, _, _window, cx| {+ let next = if this.memory.nav == MemoryNav::User {+ MemoryNav::All+ } else {+ MemoryNav::User+ };+ this.set_memory_scope(next, cx);}),cx,)),)- .child(- self.sidebar_groups(- "memory-sidebar-scroll",- counts- .agents- .iter()- .map(|(agent, count)| (*agent, *count, self.memory.agent == Some(*agent))),- counts.projects.iter().map(|p| {- let label: SharedString = if p.path.is_empty() {- t("Unknown project").into()- } else {- p.name.clone().into()- };- (- p.path.clone(),- label,- p.count,- self.memory.project.as_deref() == Some(p.path.as_str()),- )- }),- |this, next, cx| this.set_memory_scope(next, None, cx),- |this, next, cx| this.set_memory_scope(None, next, cx),- cx,- ),- )+ .child(self.sidebar_groups(+ "memory-sidebar-scroll",+ counts.agents.iter().map(|(agent, count)| {+ (+ *agent,+ *count,+ matches!(nav, MemoryNav::Agent(sel) if sel == agent),+ )+ }),+ counts.projects.iter().map(|p| {+ let label: SharedString = if p.path.is_empty() {+ t("Unknown project").into()+ } else {+ p.name.clone().into()+ };+ (+ p.path.clone(),+ label,+ p.count,+ matches!(nav, MemoryNav::Project(sel) if *sel == p.path),+ )+ }),+ |this, next, cx| {+ this.set_memory_scope(next.map_or(MemoryNav::All, MemoryNav::Agent), cx)+ },+ |this, next, cx| {+ this.set_memory_scope(next.map_or(MemoryNav::All, MemoryNav::Project), cx)+ },+ cx,+ )).into_any_element()}}-/// 组头 + 文档扁平成行;分组判据是 `MemoryDoc::group`(与 store 的排序一致:项目按-/// 路径、没归属的一组在项目之后、用户级最后)。不折叠、不缩进(树的形制试过,用户-/// 2026-09-21 定没必要)-fn memory_rows(docs: &[MemoryDoc]) -> Vec<MemoryRow> {+/// 组头 + 文档扁平成行:`docs` 已排成"用户记忆在前,其余按更新时间倒序",用户记忆+/// 自成一组置顶(会话列表的 Pinned 同位),其余按会话列表同一套时间桶+/// (`session_group_label`)切组。按项目分组的形制(树、平铺组头)都试过,行上有了+/// 项目徽章之后用户 2026-09-21 定与会话列表完全一致;用户记忆混进时间线"有点奇怪",+/// 同日再定置顶单列;侧栏选了 User memory 行时整页都是它(`pin_user` 为假),那个+/// 组头就没意义,照时间分+fn memory_rows(docs: &[MemoryDoc], today: NaiveDate, pin_user: bool) -> Vec<MemoryRow> {let mut rows = Vec::with_capacity(docs.len() + 8);- let mut current: Option<MemoryGroup> = None;+ let mut current: Option<SharedString> = None;for (ix, d) in docs.iter().enumerate() {- let group = d.group();- if current != Some(group) {+ let label = memory_section_label(d, today, pin_user);+ if current.as_ref() != Some(&label) {rows.push(MemoryRow::Group(ix));- current = Some(group);+ current = Some(label);}rows.push(MemoryRow::Doc(ix));}rows}+/// 一份文档落在哪个组头下:用户记忆 = "User memory"(`pin_user`),其余按更新时间进+/// 会话列表的时间桶+fn memory_section_label(d: &MemoryDoc, today: NaiveDate, pin_user: bool) -> SharedString {+ if pin_user && d.scope == MemoryScope::User {+ t("User memory").into()+ } else {+ session_group_label(d.updated_at, today)+ }+}+/// 读到 LoadedMemory 之前阅读面要显示的来源路径:线程记忆(Codex 的逐会话摘要)的/// 虚拟路径 `<db>#<id>` 只剥后缀、不 stat(render 每帧调);文件型就是它自己fn memory_display_path(d: &MemoryDoc) -> String {@@ -676,14 +826,15 @@ fn memory_display_path(d: &MemoryDoc) -> String {/// 组头 / 归属徽章的文案:项目名;用户级记忆一组、没有项目的一组fn memory_group_label(d: &MemoryDoc) -> SharedString {match d.group() {- MemoryGroup::User => t("User-level").into(),+ MemoryGroup::User => t("User memory").into(),MemoryGroup::Unknown => t("Unknown project").into(),MemoryGroup::Project { name, .. } => name.to_string().into(),}}/// 文档行与阅读面头部共用的两枚徽章(有则画):Codex 逐会话记忆的 "session memory",-/// 远程记忆的 @host+/// 远程记忆的 @host。指令文件不另挂徽章——文件名(CLAUDE.md、AGENTS.md)已说明身份,+/// 用户 2026-09-21 定不分fn memory_badges(d: &MemoryDoc, theme: &gpui_component::Theme) -> Vec<AnyElement> {let mut out = Vec::with_capacity(2);if d.scope == MemoryScope::Thread {diff --git a/docs/cli.md b/docs/cli.mdindex 320c039..a408bb9 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -102,14 +102,14 @@ Working directories that have session history, most recently active first, with### `memories`-The memory files agents keep for themselves — Claude Code's per-project auto-memory (`~/.claude/projects/<project>/memory/`), Codex's memories (`~/.codex/memories/`, plus its per-session summaries), ZCode's per-project memory (`~/.zcode/cli/memories/projects/<project>/memory/`) — read-only, grouped by project with user-level files last. User-level files are listed under any `--project` because they apply everywhere, even one that matches no indexed project. Each entry ends with a `wake://memory/…` reference; pass it to `show` to read the file, which is read live from disk. Options: `--project`, `--agent`, `--limit` (default 50, max 100; it caps the project-level files — user-level ones are always included).+The memory files agents keep for themselves — Claude Code's per-project auto-memory (`~/.claude/projects/<project>/memory/`), Codex's memories (`~/.codex/memories/`, plus its per-session summaries), ZCode's per-project memory (`~/.zcode/cli/memories/projects/<project>/memory/`) — read-only, grouped by project with *user memory* (the notes that apply to every project) last. User memory is listed under any `--project` because it applies everywhere, even one that matches no indexed project. Each entry ends with a `wake://memory/…` reference; pass it to `show` to read the file, which is read live from disk. Instruction files (CLAUDE.md, AGENTS.md, GEMINI.md, `.cursor/rules`, `.kiro/steering`, `copilot-instructions.md`, from the agents' homes and from every indexed project root) are listed alongside; Settings → Memory locations decides which sources are read. Options: `--project`, `--agent`, `--limit` (default 50, max 100; it caps the project memory — user memory is always included).```bashwake-cli memories --project "$PWD"wake-cli show 'wake://memory/claude-code:/Users/me/.claude/projects/-Users-me-app/memory/MEMORY.md'```-`search` appends up to five memory files that mention the query, with the same references.+`search` appends up to five memory files that mention the query, with the same references; `--project`, `--agent` and `--since` apply to them too.### `setup`diff --git a/docs/mcp.md b/docs/mcp.mdindex 88ed20e..e5d6455 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -211,14 +211,14 @@ Projects (working directories) that have indexed sessions, most recently active### `wake_list_memories`-The memory files coding agents keep for themselves on this machine, read-only: Claude Code's per-project auto-memory (`~/.claude/projects/<project>/memory/`: `MEMORY.md` plus one file per topic) Codex's memories (`~/.codex/memories/*.md`, user-level, and the per-session summaries in `memories_1.sqlite`) and ZCode's per-project memory (`~/.zcode/cli/memories/projects/<project>/memory/`, the same `MEMORY.md` + topic-file layout; its project is recovered from the workspace hash in the directory name). Grouped by project, user-level entries last; user-level entries are listed under any `project` filter because they apply everywhere (a `project` that matches no indexed project still lists them, with a note), and `limit` only caps the project-level entries — user-level ones are always appended. A memory file's project is the one its sessions belong to, so a Claude Code memory whose sessions have all expired shows under *Unknown project*. Each entry ends with a `wake://memory/<key>` reference — pass it to `wake_get_session` to read the file (the file is read live from disk, so an agent's latest edit shows). Wake never writes, edits or syncs these files.+The memory files coding agents keep for themselves on this machine, read-only: Claude Code's per-project auto-memory (`~/.claude/projects/<project>/memory/`: `MEMORY.md` plus one file per topic) Codex's memories (`~/.codex/memories/*.md`, user memory, and the per-session summaries in `memories_1.sqlite`) and ZCode's per-project memory (`~/.zcode/cli/memories/projects/<project>/memory/`, the same `MEMORY.md` + topic-file layout; its project is recovered from the workspace hash in the directory name). Grouped by project, *user memory* (the notes that apply to every project, e.g. `~/.codex/memories/*.md`) last; user memory is listed under any `project` filter because it applies everywhere (a `project` that matches no indexed project still lists it, with a note), and `limit` only caps the project memory — user memory is always appended. A memory file's project is the one its sessions belong to, so a Claude Code memory whose sessions have all expired shows under *Unknown project*. Each entry ends with a `wake://memory/<key>` reference — pass it to `wake_get_session` to read the file (the file is read live from disk, so an agent's latest edit shows). The instruction files you keep for agents are listed alongside: the global `~/.claude/CLAUDE.md`, `~/.codex/AGENTS.md` and `~/.codex/rules/*.rules`, `~/.gemini/GEMINI.md`, and — in every project Wake has sessions for — `CLAUDE.md`, `CLAUDE.local.md`, `AGENTS.md`, `GEMINI.md`, `.cursor/rules/*.mdc`, `.cursorrules`, `.kiro/steering/*.md` and `.github/copilot-instructions.md`. Which sources are read is configured in Settings → Memory locations. Wake never writes, edits or syncs these files.| Parameter | Type | Default | Notes ||---|---|---|---|| `project`, `agents` | | | see above || `limit` | integer 1–100 | 50 | |-`wake_search` also appends up to five memory files that mention the query, under *Memory files that mention …*, with the same references.+`wake_search` also appends up to five memory files that mention the query, under *Memory files that mention …*, with the same references; `project`, `agents` and `since` apply to them too.## Session keys and referencesdiff --git a/skills/wake/SKILL.md b/skills/wake/SKILL.mdindex af5d86e..5076e5f 100644--- a/skills/wake/SKILL.md+++ b/skills/wake/SKILL.md@@ -80,9 +80,11 @@ wake-cli memories --project "$PWD"```The memory files agents keep for themselves — Claude Code's auto-memory, Codex's-memories, ZCode's project memory — read-only, grouped by project, user-level ones last.-Each entry ends with a `wake://memory/…` reference; pass it to `show` to read the file.-Reach for it before re-deriving a project's conventions or decisions from scratch.+memories, ZCode's project memory — plus the instruction files kept for them (CLAUDE.md,+AGENTS.md, GEMINI.md, `.cursor/rules` …), read-only, grouped by project, user memory+(notes that apply to every project) last. Each entry ends with a `wake://memory/…`+reference; pass it to `show` to read the file. Reach for it before re-deriving a+project's conventions or decisions from scratch.## Keys, references and paging