All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.
Rust
feat: read-only memory layer with a Memory page and wake_list_memories
Corey Chiu6625ac4da7c1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 206fe65..5c80f83 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,10 @@## [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+- 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 fromdiff --git a/DESIGN.md b/DESIGN.mdindex f42b67a..31e92d5 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -125,8 +125,8 @@ macOS 不设置横跨三栏的自定义 header。主窗口透明标题栏高 44p### 资料库侧栏-- 侧栏顶端按红绿灯、`Wake` 标题和搜索框的可见边界做光学对齐:标题容器上留 4px、下留 16px。窗口控制区和品牌行各高 44px,合计 88px。-- 顶部是唯一的全文搜索入口,文案 "Search sessions",右侧显示 `⌘K`;Search/All Sessions/Starred 固定不随滚动。+- 侧栏顶端按红绿灯、`Wake` 标题和搜索框的可见边界做光学对齐:标题容器上留 4px、下留 16px。窗口控制区和品牌行各高 44px,合计 88px。Memory 页把这个标题换成 "Memory"(顶上就说明现在管的是什么,2026-09-21 用户定,不另加模式标题行)。+- 顶部是唯一的全文搜索入口,文案 "Search sessions",右侧显示 `⌘K`;Search/All Sessions/Starred 固定不随滚动。Memory 页不画这个搜索框(它搜的是会话;⌘K 照常可用),导航紧接标题、直接从 All Memory 开始(补同高空白让行位置不跳的做法试过,用户定不要)。- 搜索行必须有防溢出结构:标签文字 `flex_1 + min_w_0 + truncate`,图标与 `⌘K` 徽标显式 `flex_shrink_0`。裸文字子元素的最小宽度被内容锁死,侧栏一窄就会把右侧元素挤出边界裁掉。- 侧栏搜索入口与 Filter 来源搜索共用 `ui::search_field_frame`:32px 高、8px 主题圆角、secondary 填充、10px 水平留白、13px 搜索图标和 Caption 字阶。局部搜索在同一外壳内放无外观的 Input,不叠加默认细边框输入框。- **行分两级**(侧栏纵向层级的来源,不得拉平):主导航 All Sessions/Starred 32px 行高 + Body 14;分组展开项(agent/项目)26px 行高 + Caption 12 + 整行右移 `SUB_INDENT` 12px 表达从属。@@ -134,7 +134,7 @@ macOS 不设置横跨三栏的自定义 header。主窗口透明标题栏高 44p- 线条图标比实心品牌图视觉轻,同档里给小一号:分组项 Lucide 14 / 品牌图 18,主导航 Lucide 15。- 行内容 = 行首元素 + 标题 + 计数;计数一律 Label 档 muted。- 组头 "Agents"/"Projects" 用 Body 档常规字重 + muted 色(与主导航同字号同字重,仅靠颜色和"无行首图标"区分——加粗会让组头压过它统辖的行),带 13px chevron 可折叠。-- 底部工具条常驻,总高 44px(含顶部 1px hairline),按钮靠右排列(次要操作区:透明底、hover 才出色,不与导航行选中态抢注意力)——依次为 chart-column "Insights"、brush-cleaning "Clean Up Sessions"、齿轮 "Settings"、refresh。Insights 或清理页打开时,对应图标以 primary 点亮。Settings 同时进入 Wake 菜单并绑定 `⌘,`(其他平台 `Ctrl+,`),保持单例窗口。+- 底部工具条常驻,总高 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 始终后台运行;进度复用侧栏状态行,完成后发通知,不用模态框阻断浏览、搜索或阅读。@@ -209,7 +209,7 @@ emoji 不再承担界面或正文结构图标职责。### Insights-侧栏底部工具条的 chart-column 按钮进入;它是与全部导航行互斥的**整页目的地**——打开时替换会话流与阅读区,点任意导航行(或再点入口)退出并落回 All Sessions。设置仍是独立场景,Insights 不是。+侧栏底部工具条的 Insights 钮(chart-column)进入;它是与全部导航行互斥的**整页目的地**——打开时替换会话流与阅读区,点任意导航行(或工具条的 Sessions 钮)退出并落回 All Sessions。页头右端有 Refresh。设置仍是独立场景,Insights 不是。- 页面用 `background` 材质整片承载;顶部 88px 标题区与中栏同节奏(Insights 22px semibold + Label 11 副行,副行只说 "Since {首会话月份}"),兼窗口拖拽区。内容限 720px 阅读宽居中,区块之间只用 32px 留白与 Body 14 semibold 组头分隔——**不做卡片墙、零投影**,延续"避免每个区域加边框"的层级原则。- 统计口径与主 UI 一致(archived 不计):"Prompts" 一律指主线用户消息。数据在打开与每次 Refresh 后后台重算,不阻塞浏览。@@ -221,6 +221,16 @@ emoji 不再承担界面或正文结构图标职责。- Agents / Projects / Models 三个榜单同构:24px 条形行 = 行首(品牌图 15px 原色 / folder 图标 / 无)+ 名称列定宽 truncate + 6px 圆头轨道条(`muted` 轨、`primary` 填充,按组内峰值归一)+ 右对齐 Label 计数。三个组头都挂 ‹ › 切换度量,循环序与概览行一致:Sessions / Tokens / Prompts;**当前档位名(首字母大写的裸名词)显示在两键中间**——64px 定宽居中,Caption muted,按钮位置不随文本跳动;榜单组头因此为单行(标题与按钮组居中对齐),分布图组头保留 caption 双行、按钮中间无标签(其标题本身就是档位名)。每个榜单各自记忆档位,行按当前度量降序重排后取 top-N(Agents 全量、Projects/Models 各 6;截断在排序之后,换度量不漏项);Tokens 档只列报过用量的组、值用 K/M 缩写,组内无人报 token 时该档不进循环。- 空态沿用详情空态形制("No activity yet" + "Refresh sessions to see your activity here.");加载用居中 Spinner,已有数据时静默换新不闪烁。+### Memory++侧栏底部工具条的 Memory 钮(brain 图标)进入;与 Insights 同为**整页目的地**——打开时替换会话流与阅读区,工具条的 Sessions 钮落回 All Sessions。页头右端有 Refresh。只读: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`,只对默认根)。+- 阅读面头部是详情头部同款: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" + 一句说明它们从哪来)。+### 本机会话清理- Filter 使用 16px 内边距,标题、日期区、来源区与操作栏共用左缘。标题右侧提供「仅显示可清理」多选选项,默认关闭并随其他条件一起记忆、清除。Clear(悬停提示 Clear filters)与 Done 集中到底栏,均为 32px 高、6px 圆角,复用 Settings 的普通/主要按钮样式;常态实色填充,前者 secondary、后者 primary,Done 最小宽度 80px。@@ -228,7 +238,7 @@ emoji 不再承担界面或正文结构图标职责。- 清理入口 Delete 与最终 Confirm 按钮统一使用现有 danger 样式;取消选择、筛选与排序仍使用各自的普通控件。检查阶段显示已检查数 / 总数并可取消,执行阶段显示已处理数 / 总数并允许完成当前会话后停止。取消检查不产生确认框或清理记录。- 确认框标题用 Delete this session?/Delete N sessions?,顶部仅接一行 Caption/muted 的 Local files · About X 体积摘要,随后直接显示会话列表。两条短说明固定在列表下方、按钮上方,与列表共用左缘:先说明可从废纸篓恢复及释放空间的条件,再说明原工具可能无法继续会话。说明区顶部的分隔线固定,清单内仅在会话之间分隔;说明与按钮间距 16px,不随文件列表滚动。移除重复的长段落和清理页中额外的 Codex 说明;文件名使用 12px muted 等宽文字,过长时省略,悬停可见完整路径。只有一项时使用单数文案。结果区把未开始、已移动、需要处理分开,未开始不标红;没有移动文件时不提示空间待回收。-- 入口在侧栏底部工具条,顺序为 Insights / Clean Up Sessions / Settings / Refresh;清理使用 14px `brush-cleaning` 图标,打开时以 primary 表达激活态。+- 入口在侧栏底部工具条左端,排在 Sessions / Memory / Insights 三颗页切换之后(见「资料库侧栏」);清理使用 14px `brush-cleaning` 图标,打开时用侧栏选中色做圆角底表达激活态。- 清理页保留侧栏,主区与 Insights 共用 `background` 页面底色及 24px 水平留白。标题通过 `library_header` 与 All Sessions、Insights 共用:88px 高、22px 标题、11px 副行、2px 行间距并支持窗口拖拽,Filter、Sort、刷新对齐标题首行右侧;不放装饰图标、独立体积大字或嵌套卡片。- 标题下直接进入列表,不设置内容分类标签或独立工具栏。Filter 内容宽 468px,使用单层弹出面板:两项日期各用一行完整时长选项,沿用 Appearance 的中性分段控件,选中项用 popover 底色与轻阴影;Exclude 以独立标题与下方等宽选项呈现收藏/置顶/无法清理排除,标题右侧不放筛选条件。日期与排除条件固定可见。Agent、项目与 Exclude 统一使用原 Agents 的选项块样式:28px 行高、12px 文字,选中时浅蓝底色与右侧勾号,未选中时使用浅中性底色和细边框,不使用方形复选框。Agent 的 15px 品牌图标位于名称左侧。来源区域以分隔线分组,Sources 标题右侧放 284px 宽搜索框,来源选项单独滚动。输入来源搜索词不改变会话范围,点选后立即生效且面板保持打开。创建时间与更新时间各自提供完整时长快捷项,组合时取交集;副标题同时显示生效条件。旧单日期偏好迁移到对应项,另一项不限。候选无预设大小或对话轮数门槛,旧内容分类偏好加载时忽略。- 收藏与置顶默认不排除,选中的排除条件同步显示在页面副标题;时间门槛完全由时间筛选决定,不另设隐藏的 7 天保护。可清理和无法清理的会话统一显示,参与同一套创建/更新日期、来源、收藏和置顶筛选以及排序。无法清理项禁用勾选,标题与品牌图保持正常显示,来源信息后直接呈现简短原因,完整说明通过悬停查看,保留预览;不再提供额外展开入口或原因弹窗。大小未知显示「—」,按大小升降序均排在最后,统计只累加可清理体积。Filter 可显式开启「仅显示可清理」。所有计数均为当前筛选范围;全选只选择可清理会话。diff --git a/PRODUCT.md b/PRODUCT.mdindex 5c301f2..dd6d439 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-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`;记忆的项目归属按它挂的会话在读时解析,永远跟着索引走。不编辑、不同步、不删除——写别家数据破铁律,要改一个 Reveal 就到;也不做"把会话自动写成记忆")。后续边界(2026-09-07 定):摘要层(需 LLM、opt-in、明示会把会话正文发给用户配置的端点)只在 MCP 接入有真实使用之后再做;Timeline / Profile 一类视图建立在摘要之上;不做 ChatGPT / Claude.ai 导出导入主线、不做实体本体与知识图谱、不做 Chrome 扩展注入。约束:对 agent 数据目录只读;绝不写 Codex 的 SQLite;不读凭证;GPUI 无 SF Symbols(图标用 lucide SVG 自备)。已支持十九家 agent:Claude Code、Codex(0.6.6 起排除可识别的内部线程:guardian auto-review、`/review`、compaction、memory consolidation 与用户会话同树,adapter 文件边界按首行 session_meta 的 source / thread_source 认出即不枚举;老格式或读不出的首行保守放行,`codex exec --thread-source` 打了标签的自动化线程照常收录,issue #30。`spawn_agent` 子代理是其中唯一的例外,issue #42:那是用户自己派出去的活,收录后挂在派它的会话下面、以任务名为标题,fork 进来的父线程历史折成一条不入库的占位,父会话的对话不会被索引两遍)、Qoder CLI(`~/.qoder/projects` JSONL,active-leaf 分支恢复、tool result 回挂、`QODER_CONFIG_DIR`)、Copilot CLI、Cursor(CLI 转录 + 0.6.7 起 IDE Chat/Composer 历史,PR #32:`globalStorage/state.vscdb` 明文 KV 库,composerData 给顺序、bubbleId 行给正文;转录带正文的会话归转录源,库只补转录缺失或只剩 turn_ended 空壳的会话;库里多数老会话没存工作区路径,落 Unknown project)、OpenCode(含 OpenCode 2 next,stable 的 `opencode.db` 与 next 的 `opencode-next.db` 同时扫描;逐会话兼容 `message+part`、真实 `session+session_message` 及早期 `session_v2` schema;preview 会话标 opencode2 徽章)、Kiro、Gemini CLI(2026-08-17 P1 五家落地)+ Pi、Oh My Pi、Grok Build、Kimi Code、Antigravity CLI(2026-08-19 对齐 kooky 内置 roster;Antigravity 正文加密仅元数据卡片)+ DeepSeek Harness(dsh,2026-08-20,zstd 事件日志透明解压;格式由源码推断,当天用户跑出真实会话完成首验)+ Hermes Agent(2026-09-03,多档案 state.db,无 cwd 故 project 留空)、OpenClaw(2026-09-03,两代存储同扫;本机零会话,格式由源码推断未经真机验证)、CodeBuddy(2026-09-14,issue #27:`~/.codebuddy/projects` 的 Responses 形 JSONL,custom / ai / topic 三级标题,`CODEBUDDY_CONFIG_DIR`;本机零会话,格式由官方 CLI 文档与三家第三方实现交叉推断、未经真机验证)、WorkBuddy(同日,CodeBuddy 的孪生实例:同一解析核心,`~/.workbuddy/projects`、`WORKBUDDY_CONFIG_DIR`;桌面 app 无 CLI,不提供 resume;同构只有 cc-switch 一家佐证)、ZCode(2026-09-21:Z.ai 的 GLM-5.3 官方 harness,桌面 app;运行时是 OpenCode 衍生物——`~/.zcode/cli/db/db.sqlite` 的 session/message/part 与 OpenCode v1 同形、part 解码复用,但 session 表没有 model/tokens 列故另起一家;`v2/tasks-index.sqlite` 只借 deleted / migration_source 两个过滤位;按 `task_type` 白名单只列 interactive / fork / selection_side_chat(subagent_child 等运行时会话不列);`semantics.transcriptVisibility == hidden` 与用户消息 `origin != real_user` 归 Meta、compact_summary 折成一条、字段缺席放行;`ZCODE_STORAGE_DIR`;桌面 app 无 CLI、`zcode://` 没有按会话打开的深链,不提供 resume;本机 3.14.0 真会话首验通过,同日开源(Apache-2.0)后语义全部按源码核对)。做不了的:Windsurf/Trae 加密,Amp/Factory(Droid)/Warp 云端无本地数据,Reasonix 本机零会话格式未实测。diff --git a/README.md b/README.mdindex 273ad35..e90f7b1 100644--- a/README.md+++ b/README.md@@ -79,7 +79,7 @@ How it works, and what it doesn't do yet:## Connect your agents (MCP)-Wake ships `wake-mcp`, a small read-only [MCP](https://modelcontextprotocol.io) server over stdio that sits next to the app binary (`Wake.app/Contents/MacOS/wake-mcp` on macOS, beside `wake` on Linux and Windows). Point an MCP client at it and the agent gets four tools:+Wake ships `wake-mcp`, a small read-only [MCP](https://modelcontextprotocol.io) server over stdio that sits next to the app binary (`Wake.app/Contents/MacOS/wake-mcp` on macOS, beside `wake` on Linux and Windows). Point an MCP client at it and the agent gets five tools:| Tool | What it does ||---|---|@@ -87,6 +87,7 @@ Wake ships `wake-mcp`, a small read-only [MCP](https://modelcontextprotocol.io)| `wake_list_sessions` | Most recently updated sessions, scoped by project (pass the agent's working directory), agent, time window or starred || `wake_get_session` | One transcript as compact Markdown — user and assistant messages with `[seq N]` markers, tool calls folded to a line, injected context omitted — paginated by `from_seq` || `wake_list_projects` | Projects with indexed sessions, most recently active first |+| `wake_list_memories` | The memory files agents keep for themselves (Claude Code auto-memory, Codex memories, ZCode project memory), grouped by project; read one with `wake_get_session` and its `wake://memory/…` reference |Setup is a copy-paste from Settings → Connect, or run `wake-mcp setup` in a terminal. For example, Claude Code:@@ -221,8 +222,8 @@ crates/│ ├── scanner.rs # single-pass scan: meta + FTS in one go, mtime incremental│ ├── watcher.rs # notify-based file watching → per-file incremental updates│ ├── db.rs # rusqlite (WAL): sessions / messages / messages_fts / user_data / tombstones (+ location, remote_hosts & schema meta tables)-│ ├── mcp/ # wake-mcp: read-only MCP server over stdio (hand-written JSON-RPC, four tools)-│ ├── cli.rs # wake-cli: argv → the same four tools, same text out as MCP+│ ├── mcp/ # wake-mcp: read-only MCP server over stdio (hand-written JSON-RPC, five tools)+│ ├── cli.rs # wake-cli: argv → the same five tools, same text out as MCP│ └── services/ # terminal resume (per-platform: AppleScript / argv / Win32) / export / trash / agent context helpers└── wake # GPUI app (three-pane workbench + ⌘K / Ctrl+K palette)```diff --git a/crates/wake-core/src/adapters/claude.rs b/crates/wake-core/src/adapters/claude.rsindex 35e2dcf..eca1321 100644--- a/crates/wake-core/src/adapters/claude.rs+++ b/crates/wake-core/src/adapters/claude.rs@@ -27,6 +27,15 @@ const KNOWN_SKIP_TYPES: &[&str] = &[pub struct ClaudeAdapter {root: PathBuf,+ /// 默认根(本机自己的 ~/.claude):项目目录名才能在本机文件系统上反推——目录名+ /// 指的是写下会话的那台机器上的路径,自定义根(别处拷来的、远程镜像)反推不得+ local: bool,+ /// auto-memory 文档,按目录指纹缓存(每轮扫描都会列,指纹没变不重读)+ memories: MtimeCache<Vec<MemoryDoc>>,+ /// 目录名 → 反推出的项目路径,进程内记住(含反推失败):反推要从 `/` 逐层+ /// read_dir + stat,答案又几乎不变,每轮扫描重走一遍是白费;目录后来才出现的+ /// 极少数情况重启即可+ decoded: std::sync::Mutex<HashMap<String, Option<String>>>,}impl ClaudeAdapter {@@ -35,10 +44,69 @@ impl ClaudeAdapter {.unwrap_or_default().join(".claude").join("projects");- Self { root }+ Self {+ root,+ local: true,+ memories: MtimeCache::new(),+ decoded: std::sync::Mutex::new(HashMap::new()),+ }+ }++ /// `decode_project_dir` 的记忆版+ fn project_path_of_dir(&self, name: &str) -> Option<String> {+ let mut cache = self.decoded.lock().unwrap();+ cache+ .entry(name.to_string())+ .or_insert_with(|| decode_project_dir(name))+ .clone()}}+/// projects/<目录名> → 项目路径:Claude 把 cwd 里所有非字母数字字符都替成 `-`+/// (`/Users/x/.claude/worktrees/a-b` → `-Users-x--claude-worktrees-a-b`),反推只能+/// 靠磁盘:从 `/` 起逐层列目录,取编码后与剩余串前缀相符的子目录(同一层多个候选+/// 先试最长的),整串吃完即命中。只在没有会话可当锚点的目录上用(每轮几个目录、+/// 每层一次 read_dir);目录已不在磁盘上就认不出,落 Unknown project+fn decode_project_dir(name: &str) -> Option<String> {+ fn encode(raw: &str) -> String {+ raw.chars()+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })+ .collect()+ }+ fn walk(dir: PathBuf, rest: &str) -> Option<PathBuf> {+ if rest.is_empty() {+ return Some(dir);+ }+ let mut candidates: Vec<(String, PathBuf)> = fs::read_dir(&dir)+ .ok()?+ .flatten()+ .filter(|e| e.path().is_dir())+ .filter_map(|e| {+ let encoded = encode(&e.file_name().to_string_lossy());+ let matches = !encoded.is_empty()+ && rest.starts_with(&encoded)+ && matches!(rest.as_bytes().get(encoded.len()), None | Some(b'-'));+ matches.then(|| (encoded, e.path()))+ })+ .collect();+ candidates.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.cmp(&b.0)));+ for (encoded, path) in candidates {+ let next = &rest[encoded.len()..];+ let next = next.strip_prefix('-').unwrap_or(next);+ if let Some(hit) = walk(path, next) {+ return Some(hit);+ }+ }+ None+ }+ // 只认 POSIX 绝对路径(首字符 `/` → `-`);Windows 的 `C--Users-…` 形态不做+ let rest = name.strip_prefix('-')?;+ if rest.is_empty() {+ return None;+ }+ walk(PathBuf::from("/"), rest).map(|p| p.to_string_lossy().to_string())+}+struct ParseResult {messages: Vec<TranscriptMessage>,title: String,@@ -507,6 +575,24 @@ fn list_sidechains(r: &SessionFileRef) -> Vec<SidechainInfo> {out}+/// projects/<有损编码目录>/ 里最新的一份会话(按 mtime,平局取 id 字典序靠后的)+/// 的 key:目录名反推不了项目路径,而目录里的会话都是同一个 cwd 起的——记忆挂到+/// 这条会话上,项目路径读库时按它从 sessions 表解析(索引已经算过,不再翻文件)。+/// 候选与会话枚举同一个判据(`default_file_ref`:.jsonl、非隐藏、非零字节),否则+/// 锚点会指向一条进不了库的会话、整组记忆落 Unknown project。没有会话给 None+fn newest_session_key(dir: &Path) -> Option<String> {+ fs::read_dir(dir)+ .ok()?+ .flatten()+ .filter_map(|e| default_file_ref(AgentId::ClaudeCode, &e.path()))+ .max_by(|a, b| {+ a.mtime_ms+ .cmp(&b.mtime_ms)+ .then_with(|| a.native_id.cmp(&b.native_id))+ })+ .map(|r| session_key(AgentId::ClaudeCode, "", &r.native_id))+}+impl AgentAdapter for ClaudeAdapter {fn agent(&self) -> AgentId {AgentId::ClaudeCode@@ -616,6 +702,48 @@ 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_roots(&self) -> Vec<PathBuf> {+ vec![self.root.clone()]+ }+fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// 选中 `~/.claude` 形态(含 projects/)或直接选中 projects 目录都认let root = if dir.join("projects").is_dir() {@@ -623,10 +751,47 @@ impl AgentAdapter for ClaudeAdapter {} else {dir};- Box::new(Self { root })+ Box::new(Self {+ root,+ local: false,+ memories: MtimeCache::new(),+ decoded: std::sync::Mutex::new(HashMap::new()),+ })}fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}}++#[cfg(test)]+mod tests {+ use super::*;++ /// 目录名反推项目路径:`.`、`_`、空格都被编成 `-`,同一层多个候选按最长优先,+ /// 磁盘上不存在的认不出+ #[test]+ fn project_dir_name_decodes_against_the_filesystem() {+ let tmp = tempfile::tempdir().unwrap();+ let project = tmp+ .path()+ .join(".claude")+ .join("work trees")+ .join("my-app_v2");+ fs::create_dir_all(&project).unwrap();+ // 干扰项:同一层还有一个前缀相同但更短的目录+ fs::create_dir_all(tmp.path().join(".claude").join("work")).unwrap();+ let encoded: String = project+ .to_string_lossy()+ .chars()+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })+ .collect();+ assert!(encoded.starts_with('-'), "{encoded}");+ assert_eq!(+ decode_project_dir(&encoded).as_deref(),+ Some(project.to_string_lossy().as_ref())+ );+ assert_eq!(decode_project_dir(&format!("{encoded}-nope")), None);+ assert_eq!(decode_project_dir("Users-x"), None, "不是绝对路径形态");+ }+}diff --git a/crates/wake-core/src/adapters/codex.rs b/crates/wake-core/src/adapters/codex.rsindex b6e0f9a..ea2667a 100644--- a/crates/wake-core/src/adapters/codex.rs+++ b/crates/wake-core/src/adapters/codex.rs@@ -1,5 +1,5 @@use super::parse_utils::*;-use super::sqlite_ro::open_sqlite_ro;+use super::sqlite_ro::{open_sqlite_ro, virtual_path};use super::{units_from_messages, AgentAdapter};use crate::models::*;use anyhow::Result;@@ -19,6 +19,13 @@ pub struct CodexAdapter {scan_sessions: bool,scan_archived: bool,links_cache: MtimeCache<Vec<(String, String)>>,+ /// CODEX_HOME(memories/ 与 memories_1.sqlite 的所在);自定义根选的是独立的+ /// sessions 目录或裸 rollout 拷贝时没有 home——侧档绝不越界摸父目录(不变量 8⑨)+ home: Option<PathBuf>,+ /// memories/*.md 按目录指纹缓存、memories_1.sqlite 的线程记忆按库戳缓存+ /// (每轮扫描都会列,没变不重读)+ memories: MtimeCache<Vec<MemoryDoc>>,+ thread_memories: MtimeCache<Vec<MemoryDoc>>,}impl CodexAdapter {@@ -36,6 +43,9 @@ impl CodexAdapter {scan_sessions: true,scan_archived: true,links_cache: MtimeCache::new(),+ home: Some(root),+ memories: MtimeCache::new(),+ thread_memories: MtimeCache::new(),}}}@@ -973,6 +983,103 @@ fn build_meta(r: &SessionFileRef, p: &CodexParse, archived_dir: &Path) -> Sessio}}+/// memories_1.sqlite 的 stage1_outputs:Codex 记忆整合的第一阶段,按线程一行——+/// rollout_summary 是对整段会话的摘要,raw_memory 是从中抽出的记忆条目;挂到+/// `codex:<thread_id>` 会话上,项目读库时按该会话解析。按库 + WAL 的 mtime 戳缓存+/// (别家 SQLite 型 adapter 同款)。**`None` 与 `Some(空)` 是两件事**:库不存在、+/// 表不存在(老版本)= 确定没有;库在但打不开 / 读出错 = 不知道,交回 None 让缓存+/// 不记——把一次瞬时失败缓存成"没有"会让库里的线程记忆整组被删,而戳不动就再也+/// 不读(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 read_thread_memories(db: &Path) -> Option<Vec<MemoryDoc>> {+ if !db.is_file() {+ return Some(Vec::new());+ }+ let ro = open_sqlite_ro(db, "codex-memories")?;+ let has_table: bool = ro+ .conn+ .query_row(+ "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'stage1_outputs')",+ [],+ |r| r.get(0),+ )+ .ok()?;+ if !has_table {+ return Some(Vec::new());+ }+ let mut stmt = ro+ .conn+ .prepare(+ "SELECT thread_id, rollout_slug, rollout_summary, raw_memory, generated_at+ FROM stage1_outputs",+ )+ .ok()?;+ // 列的可空性与类型是推断的(本机零行):正文两列按可空读,generated_at 认数字+ // 与 ISO 文本;某一行的类型对不上只跳过那一行——原先一行坏就让整个函数 None、+ // 连 memories/*.md 一起从索引里消失(2026-09-21 review);读到一半的 I/O 错误+ // 仍是"不知道"+ let rows = stmt+ .query_map([], |r| {+ Ok((+ r.get::<_, String>(0)?,+ r.get::<_, Option<String>>(1)?,+ r.get::<_, Option<String>>(2)?,+ r.get::<_, Option<String>>(3)?,+ r.get::<_, rusqlite::types::Value>(4)?,+ ))+ })+ .ok()?;+ let mut out = Vec::new();+ for row in rows {+ let (thread_id, slug, summary, memory, generated) = match row {+ Ok(row) => row,+ Err(rusqlite::Error::InvalidColumnType(..)) => continue,+ Err(_) => return None,+ };+ let summary = summary.unwrap_or_default();+ let memory = memory.unwrap_or_default();+ let generated = match generated {+ rusqlite::types::Value::Real(f) => f,+ rusqlite::types::Value::Integer(i) => i as f64,+ rusqlite::types::Value::Text(t) => iso_ms(&t) as f64 / 1000.0,+ _ => 0.0,+ };+ if summary.trim().is_empty() && memory.trim().is_empty() {+ continue;+ }+ let path = virtual_path(db, &thread_id);+ let body = format!(+ "## Summary\n\n{}\n\n## Memory\n\n{}\n",+ summary.trim(),+ memory.trim()+ );+ out.push(MemoryDoc {+ key: session_key(AgentId::Codex, "", &path),+ agent: AgentId::Codex,+ host: String::new(),+ scope: MemoryScope::Thread,+ project_path: String::new(),+ project_name: String::new(),+ session_key: session_key(AgentId::Codex, "", &thread_id),+ title: slug+ .filter(|s| !s.trim().is_empty())+ .unwrap_or_else(|| "Session memory".to_string()),+ // 秒还是毫秒未验证,交 epoch_ms 统一裁定+ updated_at: epoch_ms(generated),+ size_bytes: body.len() as i64,+ path,+ body,+ });+ }+ Some(out)+}+impl AgentAdapter for CodexAdapter {fn agent(&self) -> AgentId {AgentId::Codex@@ -1082,24 +1189,21 @@ impl AgentAdapter for CodexAdapter {/// 问的是**所有**管关系的 adapter,别家 watcher 事件也会走到这里。/// 代价:没有 state DB 的根(自定义 location 只选了数据目录的裸 rollout/// 拷贝)认不出父子,子线程以任务名作为顶层会话列出——不是噪音,只是没嵌套- fn parent_links(&self) -> Vec<(String, String)> {+ fn parent_links(&self) -> Option<Vec<(String, String)>> {let stamp = super::sqlite_ro::db_cache_stamp(&self.state_db);- self.links_cache- .get_or_try_build(stamp, || {- // `?` 而不是 unwrap_or_default:读不出来时交回 None,MtimeCache- // 于是不缓存,下次重试——把失败缓存成"没有关系"会让- // sync_parent_links 当成"关系全解除",一句整家清空把所有子会话- // 解挂,而且戳不动就不自愈- let mut links: Vec<(String, String)> = read_spawn_edges(&self.state_db)?- .into_iter()- .filter(|(child, parent)| !parent.is_empty() && child != parent)- .map(|(child, parent)| (format!("codex:{child}"), format!("codex:{parent}")))- .collect();- // HashMap 的迭代序是每进程随机的,别让它漏进返回值- links.sort();- Some(links)- })- .unwrap_or_default()+ // 读不出来时 `?` 交回 None:MtimeCache 不缓存、下次重试,scanner 对这一家整段+ // 跳过——原先这里 unwrap_or_default 成空,一次瞬时失败就让 sync_parent_links+ // 当成"关系全解除",整家清空所有子会话的挂靠(2026-09-21 review)+ self.links_cache.get_or_try_build(stamp, || {+ let mut links: Vec<(String, String)> = read_spawn_edges(&self.state_db)?+ .into_iter()+ .filter(|(child, parent)| !parent.is_empty() && child != parent)+ .map(|(child, parent)| (format!("codex:{child}"), format!("codex:{parent}")))+ .collect();+ // HashMap 的迭代序是每进程随机的,别让它漏进返回值+ links.sort();+ Some(links)+ })}fn merge_quick_meta(&self, mut parsed: SessionMeta, quick: &SessionMeta) -> SessionMeta {@@ -1148,6 +1252,37 @@ 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,那里就没有记忆(不摸父目录)+ let Some(home) = &self.home else {+ return Ok(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)+ }++ 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 with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// dir 视作 CODEX_HOME 形态;归一化未上提的孤立数据目录按**目录名**// 保留角色:空的独立 sessions 目录日后落盘的 rollout 要能被发现,@@ -1156,11 +1291,15 @@ impl AgentAdapter for CodexAdapter {// 侧档一并相对 dir 派生,绝不越界摸父目录——"父目录有 home 证据"的// 场景由 normalize_custom_root 在入库前上提(2026-08-24 Codex review)let name = dir.file_name().and_then(|n| n.to_str());- let (sessions_dir, archived_dir) = match name {- Some("archived_sessions") => (dir.join("sessions"), dir.clone()),- Some("sessions") => (dir.clone(), dir.join("archived_sessions")),- _ if is_rollout_store(&dir) => (dir.clone(), dir.join("archived_sessions")),- _ => (dir.join("sessions"), dir.join("archived_sessions")),+ let (sessions_dir, archived_dir, home) = match name {+ Some("archived_sessions") => (dir.join("sessions"), dir.clone(), None),+ Some("sessions") => (dir.clone(), dir.join("archived_sessions"), None),+ _ if is_rollout_store(&dir) => (dir.clone(), dir.join("archived_sessions"), None),+ _ => (+ dir.join("sessions"),+ dir.join("archived_sessions"),+ Some(dir.clone()),+ ),};Box::new(Self {sessions_dir,@@ -1169,6 +1308,9 @@ impl AgentAdapter for CodexAdapter {scan_sessions: true,scan_archived: true,links_cache: MtimeCache::new(),+ home,+ memories: MtimeCache::new(),+ thread_memories: MtimeCache::new(),})}@@ -1191,6 +1333,9 @@ impl AgentAdapter for CodexAdapter {scan_sessions: self.scan_sessions && !roots.contains(&self.sessions_dir),scan_archived: self.scan_archived && !roots.contains(&self.archived_dir),links_cache: MtimeCache::new(),+ home: self.home.clone(),+ memories: MtimeCache::new(),+ thread_memories: MtimeCache::new(),}))}}diff --git a/crates/wake-core/src/adapters/cursor_ide.rs b/crates/wake-core/src/adapters/cursor_ide.rsindex 3a221a2..6511206 100644--- a/crates/wake-core/src/adapters/cursor_ide.rs+++ b/crates/wake-core/src/adapters/cursor_ide.rs@@ -566,11 +566,11 @@ impl AgentAdapter for CursorIdeAdapter {true}- fn parent_links(&self) -> Vec<(String, String)> {+ fn parent_links(&self) -> Option<Vec<(String, String)>> {+ // 库读不出 = None(scanner 保留库里的关系),不折成空let mtime = super::sqlite_ro::db_cache_stamp(&self.db);self.links_cache.get_or_try_build(mtime, || parent_links_from(&self.db))- .unwrap_or_default()}fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {diff --git a/crates/wake-core/src/adapters/grok.rs b/crates/wake-core/src/adapters/grok.rsindex d4dcbe8..9ce1b4b 100644--- a/crates/wake-core/src/adapters/grok.rs+++ b/crates/wake-core/src/adapters/grok.rs@@ -404,8 +404,8 @@ impl AgentAdapter for GrokAdapter {true}- fn parent_links(&self) -> Vec<(String, String)> {- grok_group::parent_links(&self.group_ctx())+ fn parent_links(&self) -> Option<Vec<(String, String)>> {+ Some(grok_group::parent_links(&self.group_ctx()))}fn is_parent_link_event(&self, path: &Path) -> bool {diff --git a/crates/wake-core/src/adapters/hermes.rs b/crates/wake-core/src/adapters/hermes.rsindex 9d44a60..f48c753 100644--- a/crates/wake-core/src/adapters/hermes.rs+++ b/crates/wake-core/src/adapters/hermes.rs@@ -501,18 +501,20 @@ impl AgentAdapter for HermesAdapter {true}- /// (child, parent) 全量快照:跨档案的父指针不成立(各库独立),只在库内配对- fn parent_links(&self) -> Vec<(String, String)> {+ /// (child, parent) 全量快照:跨档案的父指针不成立(各库独立),只在库内配对。+ /// 某个档案的库读不出就是整家"不知道"(None):跳过它给出的半截快照会让那个档案+ /// 的关系被当成已解除+ fn parent_links(&self) -> Option<Vec<(String, String)>> {let mut links = Vec::new();for db in &self.dbs {- let Some(rows) = Self::rows(db) else { 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| {let parent = r.parent_id.as_deref().filter(|p| ids.contains(p))?;Some((format!("hermes:{}", r.id), format!("hermes:{parent}")))}));}- links+ Some(links)}fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {diff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rsindex 6fc0c2d..3e037a6 100644--- a/crates/wake-core/src/adapters/mod.rs+++ b/crates/wake-core/src/adapters/mod.rs@@ -29,7 +29,7 @@ pub(crate) mod sqlite_ro;pub use sqlite_ro::strip_virtual_path as session_source_path;use crate::models::*;-use anyhow::Result;+use anyhow::{Context as _, Result};use std::path::Path;/// agent 数据源适配器。列表扫描与详情解析共用同一核心解析器,@@ -110,6 +110,23 @@ 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) 整组替换入库,消失的文件随之出库。项目归属不在这里+ /// 算:填 `session_key` 指向所属会话,读库时按它连 sessions 表解析(见 MemoryDoc)。+ /// 远程装饰器必须转发并改写 key / host / session_key+ fn list_memories(&self) -> Result<Vec<MemoryDoc>> {+ Ok(Vec::new())+ }+ /// `list_memories` 读的根(目录,或 SQLite 型的库文件;虚拟路径以库路径开头):+ /// 同 (agent, host) 有多个实例时,某个实例 `list_memories` 报 Err,scanner 只冻结+ /// 它这些根下的行(不删不改),其余实例照常对账——否则一个坏 location 会让默认+ /// 实例的记忆永远停在上次(2026-09-21 review)。实现了 list_memories 就要给+ fn memory_roots(&self) -> Vec<std::path::PathBuf> {+ Vec::new()+ }/// 一轮扫描开始前刷新 adapter 的跨会话快照。默认 adapter 没有这类状态。fn begin_scan(&self) {}/// 此 adapter 是否负责维护会话父子关系。单独的能力位用于区分“当前没有@@ -118,9 +135,12 @@ pub trait AgentAdapter: Send + Sync {false}/// 当前数据根内的 `(child_key, direct_parent_key)` 全量快照。scanner 会在- /// 合并同 agent 的所有 location 后统一扁平到 root。- fn parent_links(&self) -> Vec<(String, String)> {- Vec::new()+ /// 合并同 agent 的所有 location 后统一扁平到 root。**`None` 是"这一刻读不出来"**+ /// (state DB 打不开、读到一半出错),scanner 对这一家整段跳过、库里的关系原样+ /// 保留;`Some(空)` 才是"确定没有关系"——把读失败折成空会让 sync_parent_links+ /// 当成关系全解除,一句整家清空(2026-09-21 review)+ fn parent_links(&self) -> Option<Vec<(String, String)>> {+ Some(Vec::new())}/// watcher 事件是否会改变父子关系快照。关系边车不是会话主文件,不能塞进/// `file_ref`;命中后 watcher 会单独刷新同 agent 的所有关系快照。@@ -485,6 +505,175 @@ 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 {+ pub scope: MemoryScope,+ pub session_key: String,+ /// adapter 自己就知道的项目路径(Claude 目录里没会话时从目录名反推);空 = 交给锚点+ pub project_path: String,+ pub dir: std::path::PathBuf,+}++/// 几个记忆目录的文档,经 `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>>,+ agent: AgentId,+ dirs: &[MemoryDir],+) -> 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) {+ 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())),+ };+ let mut files: Vec<(std::path::PathBuf, i64, i64)> = Vec::new();+ for entry in entries {+ let entry = entry.with_context(|| md.dir.display().to_string())?;+ let path = entry.path();+ if !path.extension().is_some_and(|x| x == "md") {+ continue;+ }+ let meta = entry+ .metadata()+ .with_context(|| path.display().to_string())?;+ if meta.is_file() {+ files.push((path, parse_utils::mtime_ms(&meta), meta.len() as i64));+ }+ }+ if files.is_empty() {+ continue;+ }+ files.sort();+ md.session_key.hash(&mut hasher);+ md.project_path.hash(&mut hasher);+ files.hash(&mut hasher);+ listing.push((md, files));+ }+ let stamp = hasher.finish() as i64;+ cache.get_or_build_result(stamp, || {+ let mut docs = Vec::new();+ for (md, 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)?+ {+ docs.push(doc);+ }+ }+ }+ Ok(docs)+ })+}++/// 记忆标题(frontmatter 的 description)的字符上限:会话标题是 `MAX_TITLE` = 80,+/// description 是完整一句话,给宽一档+pub const MEMORY_TITLE_MAX: usize = 120;++/// 读一份 Markdown 记忆文件成 MemoryDoc:标题取 frontmatter 的 description,其次+/// name,再退文件名;正文原样保留(含 frontmatter,阅读面照渲染)。项目路径不在这里+/// 填(读库时按 session_key 解析)。非 UTF-8 给 Ok(None)(不是记忆),其余读取失败+/// 原样报错+fn memory_doc_from_file(+ agent: AgentId,+ dir: &MemoryDir,+ path: &Path,+ updated_at: i64,+ size_bytes: i64,+) -> Result<Option<MemoryDoc>> {+ let body = match std::fs::read_to_string(path) {+ Ok(body) => body,+ 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()+ .map(|s| s.to_string_lossy().to_string())+ .unwrap_or_default();+ // description 是一句话,本机实测有 565 字符的:折行、按字符封顶,列表与 MCP 一行+ // 一条才放得下(2026-09-21 review)+ 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);+ 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() {+ String::new()+ } else {+ parse_utils::project_name_of(&dir.project_path)+ },+ session_key: dir.session_key.clone(),+ path: path_str,+ title,+ updated_at,+ size_bytes,+ body,+ }))+}++/// 阅读一份记忆的正文:文件型现场读磁盘(agent 刚改过也能看到),读不到退库里那份;+/// SQLite 型(虚拟路径)只有库里那份。MCP 的 wake_get_session 与 GUI 阅读面共用+pub fn memory_body(doc: &MemoryDoc) -> String {+ if session_source_path(&doc.path) != doc.path {+ return doc.body.clone();+ }+ std::fs::read_to_string(&doc.path).unwrap_or_else(|_| doc.body.clone())+}++/// YAML frontmatter(文件开头 `---` 围起的几行)里一个顶层 `key: 值`。不做完整+/// YAML:只认顶格的 `key:`,值去首尾引号;块标量(`key: >` / `|`,值在下面缩进的几行)+/// 把那几行折成一行——否则标题就是一个字面的 ">"。没有 frontmatter 或没这个键给 None+pub(crate) fn frontmatter_field(body: &str, key: &str) -> Option<String> {+ let mut lines = body.lines();+ if lines.next()?.trim() != "---" {+ return None;+ }+ let mut lines = lines.peekable();+ while let Some(line) = lines.next() {+ if line.trim() == "---" {+ break;+ }+ let Some(value) = line+ .strip_prefix(key)+ .and_then(|rest| rest.strip_prefix(':'))+ else {+ continue;+ };+ let value = value.trim();+ let value = if matches!(value, ">" | "|" | ">-" | "|-" | ">+" | "|+") {+ let mut folded = Vec::new();+ while let Some(next) = lines.peek() {+ if !next.starts_with([' ', '\t']) || next.trim() == "---" {+ break;+ }+ folded.push(next.trim());+ lines.next();+ }+ folded.join(" ")+ } else {+ value.trim_matches('"').trim_matches('\'').to_string()+ };+ return (!value.is_empty()).then_some(value);+ }+ None+}+/// 手输路径的 `~` 前缀展开(仅前缀;边界落在分隔符上,Windows 用户手输/// `~\foo` 同样认)。HOME 与 adapter 同源(`home_dir` 的 WAKE_HOME 开关);/// UI 的 `format::expand_tilde` 与 wake-mcp 的 project 参数都走这里diff --git a/crates/wake-core/src/adapters/parse_utils.rs b/crates/wake-core/src/adapters/parse_utils.rsindex 507ae38..307f836 100644--- a/crates/wake-core/src/adapters/parse_utils.rs+++ b/crates/wake-core/src/adapters/parse_utils.rs@@ -697,17 +697,39 @@ impl<T: Clone> MtimeCache<T> {}pub fn get_or_try_build(&self, mtime: i64, build: impl FnOnce() -> Option<T>) -> Option<T> {+ self.get_or_build_result(mtime, || build().ok_or(())).ok()+ }++ /// 同 `get_or_try_build`,但 build 失败时交回**上一次成功的值**(戳不更新,下次照样+ /// 重试)。给"读不出来也得给个答案"的调用方:ZCode 的隐藏名单与行清单这类接口表达+ /// 不了"不知道",而空答案的后果是全部放出 / 全部删掉(2026-09-21 review),旧答案+ /// 至少是上一次的事实。从没成功过才是 None+ pub fn get_or_stale(&self, mtime: i64, build: impl FnOnce() -> Option<T>) -> Option<T> {+ if let Some(v) = self.get_or_try_build(mtime, build) {+ return Some(v);+ }+ self.0.lock().unwrap().as_ref().map(|(_, v)| v.clone())+ }++ /// build 带错误:Ok 才缓存,Err 原样带回、不记——"失败不缓存"是这个缓存本来的+ /// 契约,只是多把原因交出去(记忆目录列不出、读不出时 scanner 要靠 Err 跳过该组,+ /// 不能拿到一个空的 Ok);`get_or_try_build` 是它的 Option 壳+ pub fn get_or_build_result<E>(+ &self,+ mtime: i64,+ build: impl FnOnce() -> Result<T, E>,+ ) -> Result<T, E> {{let cache = self.0.lock().unwrap();if let Some((t, v)) = cache.as_ref() {if *t == mtime {- return Some(v.clone());+ return Ok(v.clone());}}}let v = build()?;*self.0.lock().unwrap() = Some((mtime, v.clone()));- Some(v)+ Ok(v)}}@@ -777,21 +799,23 @@ pub fn sqlite_dt_ms(s: &str) -> i64 {/// ISO8601 字符串或 unix 秒/毫秒 → epoch mspub fn to_epoch_ms(v: &Value) -> i64 {match v {- Value::Number(n) => {- let f = n.as_f64().unwrap_or(0.0);- if f > 1e12 {- f as i64- } else if f > 0.0 {- (f * 1000.0) as i64- } else {- 0- }- }+ Value::Number(n) => epoch_ms(n.as_f64().unwrap_or(0.0)),Value::String(s) => iso_ms(s),_ => 0,}}+/// unix 秒或毫秒(> 1e12 当毫秒)→ epoch ms;非正数给 0。秒/毫秒的唯一裁定点+pub fn epoch_ms(n: f64) -> i64 {+ if n > 1e12 {+ n as i64+ } else if n > 0.0 {+ (n * 1000.0) as i64+ } else {+ 0+ }+}+/// 清洗标题候选:剥 slash-command 壳与 system-reminder 等标签,压单行截断。空串=不可用pub fn clean_title_candidate(raw: &str) -> String {let mut s = strip_tag_block(raw, "system-reminder");diff --git a/crates/wake-core/src/adapters/remote.rs b/crates/wake-core/src/adapters/remote.rsindex be42d17..ed9f15d 100644--- a/crates/wake-core/src/adapters/remote.rs+++ b/crates/wake-core/src/adapters/remote.rs@@ -144,6 +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()?;+ for d in &mut docs {+ d.key = self.rewrite_key(&d.key);+ d.host = self.host.clone();+ if !d.session_key.is_empty() {+ d.session_key = self.rewrite_key(&d.session_key);+ }+ }+ Ok(docs)+ }+fn begin_scan(&self) {self.inner.begin_scan();}@@ -152,12 +165,19 @@ impl AgentAdapter for RemoteAdapter {self.inner.manages_parent_links()}- fn parent_links(&self) -> Vec<(String, String)> {- self.inner- .parent_links()- .into_iter()- .map(|(child, parent)| (self.rewrite_key(&child), self.rewrite_key(&parent)))- .collect()+ fn parent_links(&self) -> Option<Vec<(String, String)>> {+ Some(+ self.inner+ .parent_links()?+ .into_iter()+ .map(|(child, parent)| (self.rewrite_key(&child), self.rewrite_key(&parent)))+ .collect(),+ )+ }++ fn memory_roots(&self) -> Vec<std::path::PathBuf> {+ // inner 是按缓存挂载点构造的实例,它报的根已经是缓存内路径+ self.inner.memory_roots()}fn is_parent_link_event(&self, path: &Path) -> bool {diff --git a/crates/wake-core/src/adapters/zcode.rs b/crates/wake-core/src/adapters/zcode.rsindex 41f575f..6a82724 100644--- a/crates/wake-core/src/adapters/zcode.rs+++ b/crates/wake-core/src/adapters/zcode.rs@@ -38,6 +38,18 @@//! tool / step-start / step-finish 五种 part、中途换模型、429 失败的 turn 全吻合;//! 同日 ZCode 开源(github.com/zai-org/zcode,Apache-2.0),task_type / semantics ///! title_source / migration_source / deleted 的语义全部按源码核过。+//!+//! 记忆(2026-09-21 晚,记忆可见层):`cli/memories/projects/<slug>-<hash>/memory/*.md`,+//! `MEMORY.md` 索引 + 逐条主题文件,frontmatter(name / description / metadata.type)+//! 与 Claude auto-memory 同款——源码 context/sections/memory.ts 那段提示词就是照着+//! Claude 的写的,由它的 memory extraction 子代理在对话后写入,桌面端自己也有一个+//! 只认 `*.md` 的 Project Memory 列表。目录名的 hash 是 sha256(工作区路径) 的前+//! 16 位(memory/project-root.ts;win32 先小写),而库里每条会话都带 directory:+//! 逐条算一遍就精确对上项目,不用会话锚点、不用像 Claude 那样在磁盘上反推;+//! 对不上的落 Unknown project。只从 home 形态取(裸库拷贝没有 home,不摸父目录)。+//! 本机目录还是空的:目录名规则对真机核过(`default-0e81bcb7a4286b1b` 正是库里唯一+//! 工作区 `~/.zcode/workspace/default` 的 hash),文件格式按源码推断、**未经真机验证**+//! (OpenClaw / CodeBuddy 同款),fixture 合成。use super::opencode::{parse_v1_messages, V1Order};use super::parse_utils::*;use super::sqlite_ro::{@@ -48,7 +60,8 @@ use crate::models::*;use anyhow::{anyhow, Result};use rusqlite::Connection;use serde_json::Value;-use std::collections::HashSet;+use sha2::{Digest as _, Sha256};+use std::collections::{HashMap, HashSet};use std::path::{Path, PathBuf};const HOME_DIR_NAME: &str = ".zcode";@@ -56,15 +69,21 @@ const HOME_DIR_NAME: &str = ".zcode";const DB_REL: &str = "cli/db/db.sqlite";/// 桌面层的任务索引,相对 ZCode homeconst TASKS_REL: &str = "v2/tasks-index.sqlite";+/// 按项目的记忆目录,相对 ZCode home:`<slug>-<hash>/memory/*.md`+const MEMORIES_REL: &str = "cli/memories/projects";pub struct ZcodeAdapter {db: PathBuf,/// None = 孤立的库拷贝(自定义 location 直接选了 db.sqlite),没有桌面层,什么都不藏tasks_db: Option<PathBuf>,+ /// ZCode home(记忆目录的所在);孤立的库拷贝没有——侧档绝不越界摸父目录(不变量 8⑨)+ home: Option<PathBuf>,/// 枚举查询带全表相关子查询,按库 mtime 缓存一轮扫描内的重复调用rows_cache: MtimeCache<Vec<ZcRow>>,/// tasks-index 里要藏的会话 id,按它自己的 mtime 缓存hidden_cache: MtimeCache<HashSet<String>>,+ /// 记忆文档按目录指纹缓存(每轮扫描都会列,没变不重读)+ memories: MtimeCache<Vec<MemoryDoc>>,}#[derive(Clone)]@@ -133,15 +152,30 @@ impl ZcodeAdapter {let home = super::env_dir("ZCODE_STORAGE_DIR").filter(|dir| dir.join(DB_REL).is_file()).unwrap_or_else(|| super::home_dir().unwrap_or_default().join(HOME_DIR_NAME));- Self::with_paths(home.join(DB_REL), Some(home.join(TASKS_REL)))+ Self::from_home(home)+ }++ /// home 形态:库、任务索引、记忆目录全相对派生+ fn from_home(home: PathBuf) -> Self {+ Self {+ db: home.join(DB_REL),+ tasks_db: Some(home.join(TASKS_REL)),+ home: Some(home),+ rows_cache: MtimeCache::new(),+ hidden_cache: MtimeCache::new(),+ memories: MtimeCache::new(),+ }}- fn with_paths(db: PathBuf, tasks_db: Option<PathBuf>) -> Self {+ /// 孤立的库拷贝:只有会话,没有桌面层、没有记忆+ fn from_db(db: PathBuf) -> Self {Self {db,- tasks_db,+ tasks_db: None,+ home: None,rows_cache: MtimeCache::new(),hidden_cache: MtimeCache::new(),+ memories: MtimeCache::new(),}}@@ -149,23 +183,29 @@ impl ZcodeAdapter {open_sqlite_ro(&self.db, "zcode")}+ /// 行清单。库这一刻读不出(ZCode 原地 migration、copy 梯度失败)交回**上一次读到+ /// 的**:枚举接口表达不了"不知道",而空清单会让 scanner 把整家会话当"磁盘已删"+ /// 清掉、下一轮再全部重解析回来;从没读成功过才是 None(2026-09-21 review)fn rows(&self) -> Option<Vec<ZcRow>> {let stamp = db_cache_stamp(&self.db);- self.rows_cache.get_or_try_build(stamp, || {+ self.rows_cache.get_or_stale(stamp, || {let ro = self.open()?;query_rows(&ro.conn, ZcSchema::probe(&ro.conn), None).ok()})}- /// 桌面层要藏起来的会话 id。`None`(库在但读不出)不缓存、下次重试;- /// 库不在 = 确定没有要藏的(只同步了 cli 库的远程缓存、没装桌面端)+ /// 桌面层要藏起来的会话 id。库不在 = 确定没有要藏的(只同步了 cli 库的远程缓存、+ /// 没装桌面端);库在但读不出 = 不知道,用上一次读到的名单(`get_or_stale`,戳不+ /// 更新、下次重试)——折成空名单会把用户在桌面端删掉的、向导从 Claude 导入的+ /// 会话整批放进索引(2026-09-21 review);本进程从没读成功过的第一轮仍是空,+ /// 那一轮多列的行在下一轮读成功后随枚举消失fn hidden(&self) -> HashSet<String> {let Some(tasks_db) = &self.tasks_db else {return HashSet::new();};let stamp = db_cache_stamp(tasks_db);self.hidden_cache- .get_or_try_build(stamp, || read_hidden(tasks_db))+ .get_or_stale(stamp, || read_hidden(tasks_db)).unwrap_or_default()}@@ -417,18 +457,89 @@ impl AgentAdapter for ZcodeAdapter {vec![self.db.clone()]}+ fn memory_roots(&self) -> Vec<PathBuf> {+ self.home+ .as_ref()+ .map(|home| vec![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 with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// 只按路径形状整形、不看存不存在:远程缓存首次同步前目录还没落盘,// 判据随目录出现而改判会让先构造的实例指错树(契约测试卡)。认两种:// ZCode home,或直接给到 db.sqlite——后者是孤立的库拷贝,没有桌面层;// 中间层(cli/、cli/db/)由 normalize_custom_root 在入库前上提到 homeif dir.file_name().is_some_and(|n| n == "db.sqlite") {- Box::new(Self::with_paths(dir, None))+ Box::new(Self::from_db(dir))} else {- Box::new(Self::with_paths(- dir.join(DB_REL),- Some(dir.join(TASKS_REL)),- ))+ Box::new(Self::from_home(dir))}}}++/// 记忆目录名 `<slug>-<hash>` 里的 hash:sha256(工作区路径) 的十六进制前 16 位+/// (源码 memory/project-root.ts:路径先 `resolve`——这里只剥收尾分隔符——win32 再+/// 小写)。库里 session.directory 就是那条工作区路径,算一遍就能对上+pub fn memory_dir_hash(workspace: &str) -> String {+ let trimmed = workspace.trim_end_matches(std::path::is_separator);+ let key = if trimmed.is_empty() {+ workspace+ } else {+ trimmed+ };+ let key = if cfg!(windows) {+ key.to_lowercase()+ } else {+ key.to_string()+ };+ Sha256::digest(key.as_bytes())+ .iter()+ .take(8)+ .map(|b| format!("{b:02x}"))+ .collect()+}diff --git a/crates/wake-core/src/cli.rs b/crates/wake-core/src/cli.rsindex be92e79..70c8444 100644--- a/crates/wake-core/src/cli.rs+++ b/crates/wake-core/src/cli.rs@@ -209,6 +209,7 @@ const SHOW_FLAGS: &[FlagSpec] = &[F_SUBAGENT,];const PROJECTS_FLAGS: &[FlagSpec] = &[F_SINCE, F_LIMIT];+const MEMORIES_FLAGS: &[FlagSpec] = &[F_PROJECT, F_AGENT, F_LIMIT];/// 子命令与 MCP 工具一一对应。加一家工具就在这里加一行,否则单测红pub const COMMANDS: &[CommandSpec] = &[@@ -240,6 +241,13 @@ pub const COMMANDS: &[CommandSpec] = &[flags: PROJECTS_FLAGS,summary: "list projects that have session history",},+ CommandSpec {+ name: "memories",+ tool: tools::LIST_MEMORIES,+ positional: None,+ flags: MEMORIES_FLAGS,+ summary: "list the memory files agents keep, grouped by project",+ },];// ---------------------------------------------------------------- 类型@@ -756,11 +764,13 @@ whether an error has been seen before — git history does not hold that.wake-cli sessions --project \"$PWD\" --limit 10wake-cli search \"<terms>\" --project \"$PWD\"wake-cli show <key>+ wake-cli memories --project \"$PWD\"`sessions` and `search` print a key for every session; `search` also prints a-`wake://session/<key>#<seq>` reference that `show` accepts. Always pass---project \"$PWD\" — without it every project on the machine is in scope.-Everything is read-only.";+`wake://session/<key>#<seq>` reference that `show` accepts. `memories` lists the+notes agents keep for themselves about the project, each with a `wake://memory/…`+reference `show` accepts. Always pass --project \"$PWD\" — without it every+project on the machine is in scope. Everything is read-only.";/// 一行装好 skill。`owner/repo` 形式由 vercel-labs 的 skills CLI 认,仓库里/// 有 `skills/` 目录即可被发现。Settings → Connect 的 Skill 卡展示的就是它,@@ -859,6 +869,14 @@ mod tests {/// 在这里写明白为什么不进const NOT_IN_CLI: &[&str] = &[];+ /// 贴进 CLAUDE.md 的那段是 agent 唯一常驻的说明:记忆这一面(子命令与引用形态)+ /// 得点到名,否则只读这段的 agent 不知道有它(2026-09-21 review)+ #[test]+ fn agent_memo_mentions_memories() {+ assert!(AGENT_MEMO.contains("wake-cli memories --project"));+ assert!(AGENT_MEMO.contains("wake://memory/"));+ }+fn p(a: &[&str]) -> Result<Invocation, CliError> {parse(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>())}diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rsindex 3f68fc3..1cd3007 100644--- a/crates/wake-core/src/db.rs+++ b/crates/wake-core/src/db.rs@@ -128,6 +128,33 @@ CREATE VIRTUAL TABLE IF NOT EXISTS titles_fts USING fts5(title,tokenize="trigram case_sensitive 0");++-- agent 自己写下的记忆(Claude Code auto-memory、Codex memories)的只读镜像:+-- 扫描收尾按 (agent, host) 整组替换(2026-09-17)。正文一并入库(小 Markdown),+-- 搜索走 memories_fts(rowid = memories.id,删改按 rowid 定位——FTS 表里+-- UNINDEXED 列的 WHERE 是整表扫描,正文列在里面扫不起);阅读时文件型先读+-- 磁盘、读不到再用这份。project_path 多半为空,读时按 session_key 连 sessions 解析+CREATE TABLE IF NOT EXISTS memories (+ id INTEGER PRIMARY KEY,+ key TEXT NOT NULL UNIQUE,+ agent_id TEXT NOT NULL,+ host TEXT NOT NULL DEFAULT '',+ scope TEXT NOT NULL,+ project_path TEXT NOT NULL DEFAULT '',+ project_name TEXT NOT NULL DEFAULT '',+ session_key TEXT NOT NULL DEFAULT '',+ path TEXT NOT NULL,+ title TEXT NOT NULL DEFAULT '',+ updated_at INTEGER DEFAULT 0,+ size_bytes INTEGER DEFAULT 0,+ body TEXT NOT NULL DEFAULT ''+);+CREATE INDEX IF NOT EXISTS idx_memories_group ON memories(agent_id, host);+CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(+ title,+ body,+ tokenize="trigram case_sensitive 0"+);"#;/// 会话元数据和 FTS 单元的派生规则版本(`adapters::units_from_messages` 及其上游解析)。改了派生@@ -135,7 +162,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS titles_fts USING fts5(/// "1" = 2026-09-14 前(工具段不过滤 Wake 自指),"2" = 过滤自指回声,/// "3" = Pi / omp / OpenClaw 累计每次 assistant 调用的 token,/// "4" = Cursor 项目路径优先读取工作区元数据,并恢复 slug 中的空格。-pub const FTS_FORMAT: &str = "5";+pub const FTS_FORMAT: &str = "7";fn open_conn(path: &Path) -> Result<Connection> {if let Some(dir) = path.parent() {@@ -231,8 +258,9 @@ fn open_conn(path: &Path) -> Result<Connection> {/// 最近一次迁移加的列——`open_read_only` 用它判断库够不够新。**加新迁移时把/// 这里改成新列**,否则只读入口会放行老库、深处查询才报 no such columnconst NEWEST_COLUMN: (&str, &str) = ("sessions", "host");-/// 最近一次迁移加的表,与 NEWEST_COLUMN 同一用途、同一维护规矩-const NEWEST_TABLE: &str = "titles_fts";+/// 最近一次迁移加的、只读读者会查的表(wake_list_memories 读 memories),与+/// NEWEST_COLUMN 同一用途、同一维护规矩+const NEWEST_TABLE: &str = "memories";fn table_exists(conn: &Connection, table: &str) -> Result<bool> {Ok(conn.query_row(@@ -1126,7 +1154,8 @@ impl Store {pub fn rebuild_all(&self) -> Result<()> {let conn = self.write.lock().unwrap();conn.execute_batch(- "DELETE FROM messages; DELETE FROM messages_fts; DELETE FROM titles_fts; DELETE FROM sessions;",+ "DELETE FROM messages; DELETE FROM messages_fts; DELETE FROM titles_fts;+ DELETE FROM memories; DELETE FROM memories_fts; DELETE FROM sessions;",)?;Ok(())}@@ -1394,6 +1423,294 @@ impl Store {)?)}+ // ---------- 记忆(agent 写的 Markdown,只读镜像) ----------++ /// 一组 (agent, host) 的记忆整体对齐到 `docs`:多出的删、变了的换(按 updated_at、+ /// size 与归属锚点 / 项目判,正文不比)、没变的不动;返回有没有改动。同 key+ /// 重复后者胜。这是 memories / memories_fts 的**唯一写点**(rebuild_all 只清空)+ pub fn replace_memories(+ &self,+ agent: AgentId,+ host: &str,+ docs: &[MemoryDoc],+ frozen: &[std::path::PathBuf],+ ) -> 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))> = {+ let mut stmt = tx.prepare_cached(+ "SELECT key, id, updated_at, size_bytes, session_key, project_path+ FROM memories WHERE agent_id = ?1 AND host = ?2",+ )?;+ let rows = stmt.query_map(params![agent.as_str(), host], |r| {+ Ok((+ r.get::<_, String>(0)?,+ (+ r.get::<_, i64>(1)?,+ (+ r.get::<_, i64>(2)?,+ r.get::<_, i64>(3)?,+ r.get::<_, String>(4)?,+ r.get::<_, String>(5)?,+ ),+ ),+ ))+ })?;+ rows.collect::<rusqlite::Result<_>>()?+ };+ // 同 key 重复(同家两个实例的根重叠)后者胜:先按 key 收成一份再写,否则+ // 前一份写了、后一份与库里相同被跳过,就成了前者胜+ let latest: std::collections::BTreeMap<&str, &MemoryDoc> =+ docs.iter().map(|d| (d.key.as_str(), d)).collect();+ 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) {+ continue;+ }+ upsert_memory(&tx, d)?;+ changed = true;+ }+ // `frozen` 是这一轮读失败的实例的根:那些根下的行不删(它们没出现在 docs 里+ // 只是因为读不出,不是文件没了)+ let frozen: Vec<String> = frozen+ .iter()+ .map(|p| p.to_string_lossy().to_string())+ .collect();+ 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)) {+ continue;+ }+ stmt_fts.execute(params![id])?;+ stmt_row.execute(params![key])?;+ changed = true;+ }+ drop(stmt_fts);+ drop(stmt_row);+ tx.commit()?;+ Ok(changed)+ }++ /// 库里现有记忆的 (agent, host) 分组——scanner 拿它对照当前 roster,不再配置的来源+ /// (删掉的远程 host、停用的 agent)整组清掉+ pub fn memory_groups(&self) -> Result<Vec<(AgentId, String)>> {+ let conn = self.read.lock().unwrap();+ let mut stmt = conn.prepare_cached("SELECT DISTINCT agent_id, host FROM memories")?;+ let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;+ let mut out = Vec::new();+ for r in rows {+ let (agent, host) = r?;+ if let Some(agent) = AgentId::from_str(&agent) {+ out.push((agent, host));+ }+ }+ Ok(out)+ }++ /// Memory 页侧栏的计数:agent 按 AgentId 声明序(与会话侧栏同序,计数平局不抖),+ /// 项目按最近更新降序、没归属的一项(path 为空)垫底。项目按读时解析的归属算,+ /// 与 list_memories 同一口径——**用户级记忆对每个项目都成立**,list_memories 在+ /// 任何项目筛选下都列它们,所以每个项目行(含 Unknown project)的计数都把用户级+ /// 加进去,点开看到多少行、徽章就是多少(2026-09-21 review)+ pub fn memory_counts(&self) -> Result<MemoryCounts> {+ let conn = self.read.lock().unwrap();+ let mut stmt = conn.prepare_cached(&format!(+ "SELECT m.agent_id, {MEMORY_PROJECT},+ COALESCE(NULLIF(m.project_name, ''), s.project_name, ''),+ m.scope, COUNT(*), MAX(m.updated_at)+ FROM memories m {MEMORY_SESSION_JOIN}+ GROUP BY 1, 2, 3, 4"+ ))?;+ let rows = stmt.query_map([], |r| {+ Ok((+ r.get::<_, String>(0)?,+ r.get::<_, String>(1)?,+ r.get::<_, String>(2)?,+ r.get::<_, String>(3)?,+ r.get::<_, i64>(4)?,+ r.get::<_, i64>(5)?,+ ))+ })?;+ let mut counts = MemoryCounts::default();+ let mut agents: HashMap<AgentId, i64> = HashMap::new();+ let mut projects: HashMap<String, MemoryProject> = HashMap::new();+ let mut user_level = 0i64;+ for r in rows {+ let (agent, path, name, scope, n, last) = r?;+ let Some(agent) = AgentId::from_str(&agent) else {+ continue;+ };+ counts.total += n;+ *agents.entry(agent).or_default() += n;+ if scope == MemoryScope::User.as_str() {+ user_level += n;+ continue;+ }+ let p = projects+ .entry(path.clone())+ .or_insert_with(|| MemoryProject {+ path,+ name,+ count: 0,+ updated_at: 0,+ });+ p.count += n;+ p.updated_at = p.updated_at.max(last);+ }+ for p in projects.values_mut() {+ p.count += user_level;+ }+ counts.agents = agents.into_iter().collect();+ counts.agents.sort_by_key(|(agent, _)| *agent);+ counts.projects = projects.into_values().collect();+ counts.projects.sort_by(|a, b| {+ a.path+ .is_empty()+ .cmp(&b.path.is_empty())+ .then_with(|| b.updated_at.cmp(&a.updated_at))+ .then_with(|| a.path.cmp(&b.path))+ });+ Ok(counts)+ }++ /// 记忆列表:项目级按项目路径成组、组内新到旧,没归属的一组排在项目之后,+ /// 用户级(对每个项目都成立)最后;项目筛选下用户级照列。**`limit` 只封项目级**:+ /// 用户级排在最后,一刀切的 LIMIT 砍掉的正是筛选特意放进来的那几份(2026-09-21+ /// review),所以项目级带 LIMIT 查、用户级不限量另查再接上。**行里 body 是空串**+ /// (`MEMORY_LIST_COLS`),要正文走 `get_memory`+ pub fn list_memories(&self, f: &MemoryFilter) -> Result<Vec<MemoryDoc>> {+ let (filter_sql, args) = memory_filter(f);+ let user = MemoryScope::User.as_str();+ let conn = self.read.lock().unwrap();+ let order = format!(+ "ORDER BY m.scope = '{user}', {MEMORY_PROJECT} = '', {MEMORY_PROJECT},+ m.updated_at DESC, m.key"+ );+ if f.limit <= 0 {+ let mut stmt = conn.prepare_cached(&format!(+ "SELECT {MEMORY_LIST_COLS} FROM memories m {MEMORY_SESSION_JOIN}+ WHERE 1 = 1{filter_sql} {order}"+ ))?;+ let rows = stmt.query_map(+ rusqlite::params_from_iter(args.iter().map(|b| b.as_ref())),+ row_to_memory,+ )?;+ return Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?);+ }+ let mut out = {+ let mut stmt = conn.prepare_cached(&format!(+ "SELECT {MEMORY_LIST_COLS} FROM memories m {MEMORY_SESSION_JOIN}+ WHERE m.scope != '{user}'{filter_sql} {order} LIMIT ?"+ ))?;+ let limit: Box<dyn rusqlite::ToSql> = Box::new(f.limit);+ let rows = stmt.query_map(+ rusqlite::params_from_iter(+ args.iter()+ .chain(std::iter::once(&limit))+ .map(|b| b.as_ref()),+ ),+ row_to_memory,+ )?;+ rows.collect::<rusqlite::Result<Vec<_>>>()?+ };+ let mut stmt = conn.prepare_cached(&format!(+ "SELECT {MEMORY_LIST_COLS} FROM memories m {MEMORY_SESSION_JOIN}+ WHERE m.scope = '{user}'{filter_sql} {order}"+ ))?;+ let rows = stmt.query_map(+ rusqlite::params_from_iter(args.iter().map(|b| b.as_ref())),+ row_to_memory,+ )?;+ out.extend(rows.collect::<rusqlite::Result<Vec<_>>>()?);+ Ok(out)+ }++ pub fn get_memory(&self, key: &str) -> Result<Option<MemoryDoc>> {+ let conn = self.read.lock().unwrap();+ let mut stmt = conn.prepare_cached(&format!(+ "SELECT {MEMORY_COLS} FROM memories m {MEMORY_SESSION_JOIN} WHERE m.key = ?1"+ ))?;+ Ok(stmt.query_row(params![key], row_to_memory).optional()?)+ }++ /// 记忆全文搜索(标题 + 正文),与会话搜索同一套分词与 <3 码点降级规则;命中按+ /// bm25 排、snippet 取自正文。筛选同 list_memories+ pub fn search_memories(&self, q: &str, f: &MemoryFilter) -> Result<Vec<MemoryHit>> {+ let segs = fts_terms(q);+ if segs.is_empty() {+ return Ok(Vec::new());+ }+ let limit = if f.limit > 0 { f.limit } else { 20 };+ let (filter_sql, filter_args) = memory_filter(f);+ let conn = self.read.lock().unwrap();+ let mut out = Vec::new();+ if !needs_like_fallback(&segs) {+ let mut stmt = conn.prepare_cached(&format!(+ "SELECT {MEMORY_COLS}, snippet(memories_fts, 1, ?, ?, '…', 16)+ FROM memories_fts JOIN memories m ON m.id = memories_fts.rowid+ {MEMORY_SESSION_JOIN}+ WHERE memories_fts MATCH ?{filter_sql}+ ORDER BY bm25(memories_fts) LIMIT ?"+ ))?;+ let mut all_args: Vec<Box<dyn rusqlite::ToSql>> = vec![+ Box::new(HL_OPEN.to_string()),+ Box::new(HL_CLOSE.to_string()),+ Box::new(fts_match_expr(&segs)),+ ];+ all_args.extend(filter_args);+ all_args.push(Box::new(limit));+ let rows = stmt.query_map(+ rusqlite::params_from_iter(all_args.iter().map(|b| b.as_ref())),+ |r| {+ Ok(MemoryHit {+ doc: row_to_memory(r)?,+ snippet: r.get(12)?,+ })+ },+ )?;+ for r in rows {+ out.push(r?);+ }+ } else {+ let like_where = like_where(&["m.title", "m.body"], segs.len());+ let mut stmt = conn.prepare_cached(&format!(+ "SELECT {MEMORY_COLS} FROM memories m {MEMORY_SESSION_JOIN}+ WHERE {like_where}{filter_sql}+ ORDER BY m.updated_at DESC LIMIT ?"+ ))?;+ let mut all_args = like_args(&segs, 2);+ all_args.extend(filter_args);+ all_args.push(Box::new(limit));+ let rows = stmt.query_map(+ rusqlite::params_from_iter(all_args.iter().map(|b| b.as_ref())),+ row_to_memory,+ )?;+ for r in rows {+ let doc = r?;+ let snippet = make_like_snippet(&doc.body, segs[0]);+ out.push(MemoryHit { doc, snippet });+ }+ }+ Ok(out)+ }+pub fn agent_counts(&self) -> Result<HashMap<String, i64>> {let conn = self.read.lock().unwrap();let mut stmt = conn.prepare_cached(@@ -1685,11 +2002,11 @@ impl Store {/// 全文搜索的完整筛选形态(多项目并集 + 时间下界);`search` 是它的便捷壳。/// 命中按 bm25 排序、消息级一行一条;archived 会话不排除(meta.archived 标出)pub fn search_with(&self, q: &str, f: &SearchFilter) -> Result<(Vec<SearchHit>, bool)> {- let segs: Vec<&str> = q.split_whitespace().filter(|s| !s.is_empty()).collect();+ let segs = fts_terms(q);if segs.is_empty() {return Ok((Vec::new(), false));}- let degraded = segs.iter().any(|s| s.chars().count() < 3);+ let degraded = needs_like_fallback(&segs);let limit = if f.limit > 0 { f.limit } else { 60 };// 近因加权:bm25 是负数、越小越相关,乘上 (1 + W / (1 + 距今天数 / H)) 让// 新会话的命中"更负"。W = 1、H = 30 天:今天的会话 ×2、一个月前 ×1.5、@@ -1732,11 +2049,7 @@ impl Store {v};// FTS 的 MATCH 表达式(正文与标题两张表共用)- let match_expr = segs- .iter()- .map(|s| format!("\"{}\"", s.replace('"', "\"\"")))- .collect::<Vec<_>>()- .join(" AND ");+ let match_expr = fts_match_expr(&segs);let conn = self.read.lock().unwrap();let mut raw: Vec<(String, i64, Option<String>, String, Option<i64>, String)> = Vec::new();@@ -1777,11 +2090,7 @@ impl Store {raw.push(r?);}} else {- let like_where = segs- .iter()- .map(|_| "m.text LIKE ? ESCAPE '\\'")- .collect::<Vec<_>>()- .join(" AND ");+ let like_where = like_where(&["m.text"], segs.len());let sql = format!("SELECT m.session_key, m.seq, m.sidechain_id, m.role, m.ts, m.textFROM messages m JOIN sessions s ON s.key = m.session_key@@ -1789,10 +2098,7 @@ impl Store {ORDER BY m.ts DESC LIMIT ?");let mut stmt = conn.prepare_cached(&sql)?;- let mut all_args: Vec<Box<dyn rusqlite::ToSql>> = segs- .iter()- .map(|s| Box::new(format!("%{}%", escape_like(s))) as Box<dyn rusqlite::ToSql>)- .collect();+ let mut all_args = like_args(&segs, 1);all_args.extend(filter_args(f));all_args.push(Box::new(limit));let rows = stmt.query_map(@@ -1849,21 +2155,14 @@ impl Store {title_raw.push(r?);}} else {- let like_where = segs- .iter()- .map(|_| "s.title LIKE ? ESCAPE '\\'")- .collect::<Vec<_>>()- .join(" AND ");+ let like_where = like_where(&["s.title"], segs.len());let sql = format!("SELECT s.key, s.title FROM sessions sWHERE {like_where}{filter_sql}ORDER BY s.updated_at DESC LIMIT ?");let mut stmt = conn.prepare_cached(&sql)?;- let mut all_args: Vec<Box<dyn rusqlite::ToSql>> = segs- .iter()- .map(|s| Box::new(format!("%{}%", escape_like(s))) as Box<dyn rusqlite::ToSql>)- .collect();+ let mut all_args = like_args(&segs, 1);all_args.extend(filter_args(f));all_args.push(Box::new(limit));let rows = stmt.query_map(@@ -2042,6 +2341,135 @@ fn push_session_filters(}}+/// memories 连它的归属会话:项目路径在读时解析——adapter 填了就用 adapter 的,+/// 否则取 `session_key` 指向的会话的(线程级记忆是它所属的会话,Claude 项目级是+/// 同目录最新的会话)。归属随索引走,会话被重新归属、晚于记忆才入库都自动跟上+const MEMORY_SESSION_JOIN: &str = "LEFT JOIN sessions s ON s.key = m.session_key";+const MEMORY_PROJECT: &str = "COALESCE(NULLIF(m.project_path, ''), s.project_path, '')";++/// memories 的列(带 `m.` 前缀:搜索要与 memories_fts 连表,裸 key 会歧义);+/// 必须带上 `MEMORY_SESSION_JOIN` 选,项目两列就是 `MEMORY_PROJECT` 那个表达式。+/// 最后一列是正文的位置,`row_to_memory` 按位读+macro_rules! memory_cols {+ ($body:literal) => {+ concat!(+ "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, ",+ $body+ )+ };+}+const MEMORY_COLS: &str = memory_cols!("m.body");+/// 列表用的同一组列,只是正文给空串:列表谁都不看正文(GUI 阅读时经 get_memory+/// 另取,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)?;+ Ok(MemoryDoc {+ key: r.get(0)?,+ agent: AgentId::from_str(&agent).unwrap_or(AgentId::ClaudeCode),+ host: r.get(2)?,+ scope: MemoryScope::parse(&scope).unwrap_or(MemoryScope::Project),+ project_path: r.get(4)?,+ project_name: r.get(5)?,+ session_key: r.get(6)?,+ path: r.get(7)?,+ title: r.get(8)?,+ updated_at: r.get(9)?,+ size_bytes: r.get(10)?,+ body: r.get(11)?,+ })+}++/// list_memories / search_memories 共用的筛选谓词(表别名 m):agent 并集;项目并集+/// 之外用户级记忆恒放行——它对每个项目都成立+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();+ if !f.agents.is_empty() {+ sql.push_str(&format!(+ " AND m.agent_id IN ({})",+ placeholders(f.agents.len())+ ));+ for a in &f.agents {+ args.push(Box::new(a.as_str().to_string()));+ }+ }+ if f.scopes_projects() {+ // 项目并集 ∪ 没归属的一组(显式的 unattributed,不拿空串当暗号:空串什么都+ // 不匹配)∪ 用户级(对每个项目都成立)+ let mut terms: Vec<String> = Vec::new();+ if !f.project_paths.is_empty() {+ terms.push(format!(+ "({MEMORY_PROJECT} != '' AND {MEMORY_PROJECT} IN ({}))",+ placeholders(f.project_paths.len())+ ));+ for p in &f.project_paths {+ args.push(Box::new(p.clone()));+ }+ }+ if f.unattributed {+ terms.push(format!("{MEMORY_PROJECT} = ''"));+ }+ terms.push(format!("m.scope = '{}'", MemoryScope::User.as_str()));+ sql.push_str(&format!(" AND ({})", terms.join(" OR ")));+ }+ (sql, args)+}++/// 写一份记忆:memories 行按 key 就地更新(id 不变,memories_fts 的 rowid 就是它),+/// FTS 那份先按 rowid 删再插。语句都走 prepare_cached——一次冷建一百多份,逐条+/// 编译 SQL 白费+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)+ 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+ RETURNING id",+ )?+ .query_row(+ params![+ d.key,+ d.agent.as_str(),+ d.host,+ d.scope.as_str(),+ d.project_path,+ d.project_name,+ d.session_key,+ d.path,+ d.title,+ d.updated_at,+ d.size_bytes,+ d.body,+ ],+ |r| r.get::<_, i64>(0),+ )?;+ tx.prepare_cached("DELETE FROM memories_fts WHERE rowid = ?1")?+ .execute(params![id])?;+ tx.prepare_cached("INSERT INTO memories_fts(rowid, title, body) VALUES (?1, ?2, ?3)")?+ .execute(params![id, d.title, d.body])?;+ Ok(())+}+fn row_to_meta(r: &rusqlite::Row<'_>) -> rusqlite::Result<SessionMeta> {let agent_str: String = r.get(1)?;Ok(SessionMeta {@@ -2167,27 +2595,93 @@ fn escape_like(s: &str) -> String {.replace('_', "\\_")}-fn make_like_snippet(text: &str, first_seg: &str) -> String {- let lower = text.to_lowercase();- let seg_lower = first_seg.to_lowercase();- let Some(byte_idx) = lower.find(&seg_lower) else {- return text.chars().take(120).collect();+/// 搜索串按空白切成词项(会话搜索与记忆搜索同一套分词)+fn fts_terms(q: &str) -> Vec<&str> {+ q.split_whitespace().filter(|s| !s.is_empty()).collect()+}++/// 有词项短于 3 码点就走 LIKE 子串扫描——trigram 分词对更短的词无能为力+fn needs_like_fallback(segs: &[&str]) -> bool {+ segs.iter().any(|s| s.chars().count() < 3)+}++/// FTS5 的 MATCH 表达式:每个词项加引号(内部引号翻倍)、AND 连接。三张 FTS 表共用,+/// 转义规则只此一处+fn fts_match_expr(segs: &[&str]) -> String {+ segs.iter()+ .map(|s| format!("\"{}\"", s.replace('"', "\"\"")))+ .collect::<Vec<_>>()+ .join(" AND ")+}++/// LIKE 降级路径的 WHERE:每个词项对每一列各一个 `LIKE ? ESCAPE '\'`(列之间 OR、+/// 词项之间 AND),参数由 `like_args` 按同一顺序给。正文、标题、记忆三条降级路径共用+fn like_where(cols: &[&str], terms: usize) -> String {+ let per_term = cols+ .iter()+ .map(|c| format!("{c} LIKE ? ESCAPE '\\'"))+ .collect::<Vec<_>>()+ .join(" OR ");+ let per_term = if cols.len() > 1 {+ format!("({per_term})")+ } else {+ per_term};- // 定位到字符边界安全的窗口+ std::iter::repeat_n(per_term, terms)+ .collect::<Vec<_>>()+ .join(" AND ")+}++/// `like_where` 的参数:每个词项转义成 `%term%`,每列一份+fn like_args(segs: &[&str], cols: usize) -> Vec<Box<dyn rusqlite::ToSql>> {+ segs.iter()+ .flat_map(|s| {+ let pat = format!("%{}%", escape_like(s));+ std::iter::repeat_n(pat, cols)+ })+ .map(|pat| Box::new(pat) as Box<dyn rusqlite::ToSql>)+ .collect()+}++/// LIKE 降级路径的 snippet:不区分大小写找首个词项,前 40 / 后 80 字符开窗并高亮。+/// 全程按**字符**下标走:逐字符小写并记下每个小写字符来自原文第几个字符——小写+/// 不保长(Ω→ω、İ→i̇、K→k 字节数与字符数都会变),拿小写串里的字节偏移去切原文正是+/// 2026-09-21 review 复现的 panic(⌘K 逐字键入 CJK 查询必经此路,后台线程 panic+/// 直接 abort 整个 app)+fn make_like_snippet(text: &str, first_seg: &str) -> String {let chars: Vec<char> = text.chars().collect();- let char_idx = text[..byte_idx].chars().count();- let seg_len = first_seg.chars().count();+ let needle: Vec<char> = first_seg.to_lowercase().chars().collect();+ let mut lower: Vec<char> = Vec::with_capacity(chars.len());+ let mut origin: Vec<usize> = Vec::with_capacity(chars.len());+ for (i, c) in chars.iter().enumerate() {+ for lc in c.to_lowercase() {+ lower.push(lc);+ origin.push(i);+ }+ }+ let hit = (!needle.is_empty())+ .then(|| {+ lower+ .windows(needle.len())+ .position(|w| w == needle.as_slice())+ })+ .flatten();+ let Some(pos) = hit else {+ return chars.iter().take(120).collect();+ };+ let char_idx = origin[pos];+ let match_end = origin[pos + needle.len() - 1] + 1;let start = char_idx.saturating_sub(40);- let end = (char_idx + seg_len + 80).min(chars.len());+ let end = (match_end + 80).min(chars.len());let mut out = String::new();if start > 0 {out.push('…');}out.extend(&chars[start..char_idx]);out.push(HL_OPEN);- out.extend(&chars[char_idx..(char_idx + seg_len).min(chars.len())]);+ out.extend(&chars[char_idx..match_end]);out.push(HL_CLOSE);- out.extend(&chars[(char_idx + seg_len).min(chars.len())..end]);+ out.extend(&chars[match_end..end]);if end < chars.len() {out.push('…');}diff --git a/crates/wake-core/src/mcp/mod.rs b/crates/wake-core/src/mcp/mod.rsindex 70bea1b..25b9fd7 100644--- a/crates/wake-core/src/mcp/mod.rs+++ b/crates/wake-core/src/mcp/mod.rs@@ -42,7 +42,10 @@ coding agent: what was discussed, decided or tried, why something was done a cerwhere previous work stopped, or whether an error was seen before. Git history and the \working tree do not contain that; Wake does. Start with wake_list_sessions (pass the \current working directory as `project`) or wake_search, then read the relevant transcript \-with wake_get_session. Nothing here can modify a session.";+with wake_get_session; wake_list_projects shows which projects have history. \+wake_list_memories lists the notes agents keep for themselves about a project (Claude \+Code and ZCode auto-memory, Codex memories); read one by passing its wake://memory/… \+reference to wake_get_session. Nothing here can modify a session or a memory file.";const JSONRPC_PARSE_ERROR: i64 = -32700;const JSONRPC_INVALID_REQUEST: i64 = -32600;@@ -293,6 +296,16 @@ pub fn setup_snippets(bin: &Path) -> Vec<SetupSnippet> {mod tests {use super::*;+ /// initialize 回的 instructions 是 agent 唯一常驻的一段说明:每个工具都得点到名,+ /// 否则新工具对只读这段的 agent 就是隐形的(2026-09-21 review:加 wake_list_memories+ /// 时漏了这里)+ #[test]+ fn instructions_mention_every_tool() {+ for name in tools::NAMES {+ assert!(INSTRUCTIONS.contains(name), "INSTRUCTIONS 没提到 {name}");+ }+ }+#[test]fn snippets_quote_paths_for_every_client() {let snippets = setup_snippets(Path::new(diff --git a/crates/wake-core/src/mcp/tools.rs b/crates/wake-core/src/mcp/tools.rsindex 22c09dd..e46bbaa 100644--- a/crates/wake-core/src/mcp/tools.rs+++ b/crates/wake-core/src/mcp/tools.rs@@ -94,12 +94,22 @@ pub const SEARCH: &str = "wake_search";pub const LIST_SESSIONS: &str = "wake_list_sessions";pub const GET_SESSION: &str = "wake_get_session";pub const LIST_PROJECTS: &str = "wake_list_projects";-/// 四个工具名的清单:自指回声过滤(`adapters::is_wake_lookup`)与 definitions 的-/// 稳定性测试都读它,加第五家改这里与 `definitions()` 两处即可-pub const NAMES: [&str; 4] = [SEARCH, LIST_SESSIONS, GET_SESSION, LIST_PROJECTS];+pub const LIST_MEMORIES: &str = "wake_list_memories";+/// 工具名的清单:自指回声过滤(`adapters::is_wake_lookup`)与 definitions 的+/// 稳定性测试都读它,加一家改这里与 `definitions()` 两处即可+pub const NAMES: [&str; 5] = [+ SEARCH,+ LIST_SESSIONS,+ GET_SESSION,+ LIST_PROJECTS,+ LIST_MEMORIES,+];const MAX_SEARCH_SESSIONS: i64 = 30;const MAX_LIST_SESSIONS: i64 = 100;+const MAX_LIST_MEMORIES: i64 = 100;+/// wake_search 末尾附带的记忆命中数+const MEMORY_HITS_IN_SEARCH: i64 = 5;const MAX_LIST_PROJECTS: i64 = 200;const SNIPPETS_PER_SESSION: usize = 3;@@ -173,11 +183,11 @@ pub fn definitions() -> Vec<Value> {json!({"name": GET_SESSION,"title": "Read a session transcript",- "description": "Read one session's transcript, parsed live from the agent's own files, as compact Markdown: user and assistant messages with `[seq N]` markers, tool calls folded to one line each, injected context omitted. Use it after wake_search or wake_list_sessions to see what actually happened — the reasoning, the decisions and the exact steps of an earlier session. Paginated: when the reply ends with a `from_seq` hint, call again with it to continue. Accepts a session key or a `wake://session/<key>#<seq>` reference (the seq becomes the starting point). Subagent transcripts (Claude Code sidechains, Cursor subagents) are listed at the end of the main transcript; pass one's id as `subagent` to read it.",+ "description": "Read one session's transcript, parsed live from the agent's own files, as compact Markdown: user and assistant messages with `[seq N]` markers, tool calls folded to one line each, injected context omitted. Use it after wake_search or wake_list_sessions to see what actually happened — the reasoning, the decisions and the exact steps of an earlier session. Paginated: when the reply ends with a `from_seq` hint, call again with it to continue. Accepts a session key or a `wake://session/<key>#<seq>` reference (the seq becomes the starting point). Subagent transcripts (Claude Code sidechains, Cursor subagents) are listed at the end of the main transcript; pass one's id as `subagent` to read it. Also reads memory files: pass a `wake://memory/<key>` reference from wake_list_memories or wake_search to get that file.","inputSchema": {"type": "object","properties": {- "key": { "type": "string", "description": "Session key such as `claude-code:1b2c…`, or a wake://session/… reference." },+ "key": { "type": "string", "description": "Session key such as `claude-code:1b2c…`, a wake://session/… reference, or a wake://memory/… reference to read a memory file." },"from_seq": { "type": "integer", "minimum": 0, "description": "Start at this message seq (inclusive). Default: the beginning." },"max_messages": { "type": "integer", "minimum": 1, "maximum": 200, "default": 60, "description": "Messages per page." },"max_chars": { "type": "integer", "minimum": 200, "maximum": 100000, "default": 20000, "description": "Character budget per page." },@@ -203,6 +213,20 @@ pub fn definitions() -> Vec<Value> {},"annotations": read_only_annotations(),}),+ 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.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "project": project_param(),+ "agents": agents_param(),+ "limit": { "type": "integer", "minimum": 1, "maximum": MAX_LIST_MEMORIES, "default": 50 },+ },+ },+ "annotations": read_only_annotations(),+ }),]}@@ -212,6 +236,7 @@ fn call(ctx: &ToolContext, name: &str, args: &Value) -> ToolResult {LIST_SESSIONS => list_sessions(ctx, args),GET_SESSION => get_session(ctx, args),LIST_PROJECTS => list_projects(ctx, args),+ LIST_MEMORIES => list_memories(ctx, args),other => Err(ToolError::InvalidParams(format!("Unknown tool: {other}"))),}}@@ -408,7 +433,24 @@ fn project_arg(ctx: &ToolContext, args: &Value) -> Result<ProjectScope, ToolErroOk(ProjectScope::NoMatch(text))}-/// 两个列表工具共用的 project 解包:没匹配上时直接把提示文本当结果返回+/// 记忆面的 project 解包:没匹配上索引里的项目**不早退**——用户级记忆对每个项目都+/// 成立,筛选串按原样传下去(项目级本来就一份都不会匹配、用户级照列),提示文本+/// 另外带回给调用方决定怎么说+fn memory_project_scope(+ ctx: &ToolContext,+ args: &Value,+) -> Result<(Option<Vec<String>>, Option<String>), ToolError> {+ Ok(match project_arg(ctx, args)? {+ ProjectScope::All => (None, None),+ ProjectScope::Paths(p) => (Some(p), None),+ ProjectScope::NoMatch(text) => {+ let arg = text_arg(args, "project")?.unwrap_or_default().to_string();+ (Some(vec![arg]), Some(text))+ }+ })+}++/// 会话列表工具的 project 解包:没匹配上时直接把提示文本当结果返回macro_rules! project_scope {($ctx:expr, $args:expr) => {match project_arg($ctx, $args)? {@@ -524,6 +566,42 @@ fn session_ref(key: &str, seq: i64) -> String {format!("wake://session/{key}#{seq}")}+fn memory_ref(key: &str) -> String {+ format!("wake://memory/{key}")+}++/// `wake_get_session` 的 `key` 参数认的三种形态:裸会话 key、`wake://session/<key>#<seq>`+/// (seq 成为默认起点)、`wake://memory/<key>`(记忆文件,另一条读法)。写引用的+/// `session_ref` / `memory_ref` 与读引用的 `parse` 放在一起,两边一起改。记忆 key+/// 自身可含 `#`(SQLite 型虚拟路径 `<db>#<id>`),所以先认 scheme 再拆 seq+#[derive(Debug, PartialEq, Eq)]+enum WakeRef {+ Session { key: String, seq: Option<i64> },+ Memory { key: String },+}++impl WakeRef {+ fn parse(raw: &str) -> Self {+ let s = raw.trim();+ if let Some(key) = s.strip_prefix("wake://memory/") {+ return Self::Memory {+ key: key.trim().to_string(),+ };+ }+ let s = s.strip_prefix("wake://session/").unwrap_or(s);+ match s.rsplit_once('#') {+ Some((key, seq)) if seq.parse::<i64>().is_ok() => Self::Session {+ key: key.to_string(),+ seq: seq.parse().ok(),+ },+ _ => Self::Session {+ key: s.to_string(),+ seq: None,+ },+ }+ }+}+// ---------------------------------------------------------------- 工具实现fn search(ctx: &ToolContext, args: &Value) -> ToolResult {@@ -532,7 +610,18 @@ fn search(ctx: &ToolContext, args: &Value) -> ToolResult {let agents = agents_arg(args)?;let since = since_arg(ctx, args)?;let limit = int_arg(args, "limit", 10, 1, MAX_SEARCH_SESSIONS)?;- let project = project_scope!(ctx, args);+ let (project, unmatched) = memory_project_scope(ctx, args)?;+ if let Some(text) = unmatched {+ // 会话没有这个项目,但用户级记忆对每个项目都成立——提示之余照样查一遍+ let memory = memory_hits_section(ctx, query, &agents, &project)?;+ let mut out = text;+ if !memory.is_empty() {+ // 提示文本不带收尾换行,记忆段自带前导空行;没命中就一字不加+ out.push('\n');+ out.push_str(memory.trim_end());+ }+ return Ok(out);+ }// 命中是消息级、按 bm25 排;一个会话能占掉前几十行,多取一些再按会话归组let fetch = (limit * 8).clamp(60, 400);let (hits, degraded) = ctx.store.search_with(@@ -556,13 +645,18 @@ 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 mut out = String::new();if order.is_empty() {- out.push_str(&format!("No matches for `{query}`{scope}.\n"));+ out.push_str(&format!("No session matches `{query}`{scope}.\n"));if degraded {out.push_str("Note: terms shorter than 3 characters use a substring scan; try a longer or more specific term.\n");}- out.push_str("Try fewer or different terms, drop the project/agent/since filters, or list sessions with wake_list_sessions.\n\n");+ if memory.is_empty() {+ out.push_str("Try fewer or different terms, drop the project/agent/since filters, or list sessions with wake_list_sessions.\n\n");+ }+ out.push_str(&memory);out.push_str(&index_note(ctx.store));return Ok(out);}@@ -613,10 +707,187 @@ fn search(ctx: &ToolContext, args: &Value) -> ToolResult {out.push_str("Read a session with wake_get_session (pass the key, or a ref to start at that message).\n",);+ out.push_str(&memory);+ out.push_str(&index_note(ctx.store));+ Ok(out)+}++/// wake_search 末尾附带的记忆命中:agent 自己写的记忆里提到这个词的几份,带+/// `wake://memory/…` 引用。整段前后各一个空行,调用方直接拼、不用管分隔;没有就是空串+fn memory_hits_section(+ ctx: &ToolContext,+ query: &str,+ agents: &[AgentId],+ project: &Option<Vec<String>>,+) -> Result<String, ToolError> {+ let hits = ctx.store.search_memories(+ query,+ &MemoryFilter {+ agents: agents.to_vec(),+ project_paths: project.clone().unwrap_or_default(),+ unattributed: false,+ limit: MEMORY_HITS_IN_SEARCH,+ },+ )?;+ if hits.is_empty() {+ return Ok(String::new());+ }+ let mut out = format!("\nMemory files that mention `{query}`:\n");+ for h in &hits {+ out.push_str(&format!(+ "- {}{} · {}: {}\n ref: {}\n",+ memory_label(&h.doc),+ memory_session_note(&h.doc),+ memory_group(&h.doc),+ clean_snippet(&h.snippet),+ memory_ref(&h.doc.key)+ ));+ }+ out.push('\n');+ Ok(out)+}++/// `<标题> · <agent> · <层级>[ · @host]`+fn memory_label(d: &MemoryDoc) -> String {+ // 标题入库时已按 MEMORY_TITLE_MAX 折行封顶;老库里的行要等文件变了才重读,这里再兜一道+ let mut s = format!(+ "{} · {} · {}",+ one_line(&d.title, crate::adapters::MEMORY_TITLE_MAX),+ d.agent.display_name(),+ d.scope.label()+ );+ if !d.host.is_empty() {+ s.push_str(&format!(" · @{}", d.host));+ }+ s+}++/// 记忆归属哪一组(列表的组头、搜索命中的归属都用它);分组判据在 `MemoryDoc::group`+fn memory_group(d: &MemoryDoc) -> String {+ match d.group() {+ MemoryGroup::User => "User-level (applies to every project)".to_string(),+ MemoryGroup::Unknown => "Unknown project".to_string(),+ MemoryGroup::Project { path, name } => format!("{path} — {name}"),+ }+}++/// 线程级记忆才标它所属的会话;项目级的 session_key 只是解析项目用的锚点,不露出+fn memory_session_note(d: &MemoryDoc) -> String {+ if d.scope == MemoryScope::Thread && !d.session_key.is_empty() {+ format!(" · session `{}`", d.session_key)+ } else {+ String::new()+ }+}++fn list_memories(ctx: &ToolContext, args: &Value) -> ToolResult {+ let agents = agents_arg(args)?;+ let limit = int_arg(args, "limit", 50, 1, MAX_LIST_MEMORIES)?;+ let (project, unmatched) = memory_project_scope(ctx, args)?;+ let docs = ctx.store.list_memories(&MemoryFilter {+ agents: agents.clone(),+ project_paths: project.clone().unwrap_or_default(),+ unattributed: false,+ limit,+ })?;+ let scope = scope_note(&project, &agents, None, false);+ let mut out = String::new();+ 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"+ ));+ }+ 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"+ ));+ 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",+ docs.len(),+ plural(docs.len() as i64)+ ));+ // store 已按 (用户级最后, 项目路径, 新到旧) 排好,这里只在组变化时打组头+ let mut current: Option<String> = None;+ for d in &docs {+ let group = memory_group(d);+ if current.as_deref() != Some(group.as_str()) {+ out.push_str(&format!("\n## {group}\n"));+ current = Some(group);+ }+ out.push_str(&format!(+ "- {}{} · updated {}\n ref: {}\n",+ memory_label(d),+ memory_session_note(d),+ fmt_time(Some(d.updated_at)),+ memory_ref(&d.key)+ ));+ }+ out.push_str("\nRead one with wake_get_session using its wake://memory/… reference.\n");out.push_str(&index_note(ctx.store));Ok(out)}+/// `wake_get_session` 收到 `wake://memory/<key>` 引用时的读法:标题行 + 归属 + 来源+/// 路径,然后是正文。文件型现场读磁盘(agent 刚改过也能看到),读不到退库里那份;+/// SQLite 型只有库里那份。同一个 `max_chars` 预算,超了截断并说明+/// `wake_get_session` 读记忆时一页的字符上限(与会话页同数);`int_arg` 静默封顶+const MAX_GET_CHARS: usize = 100_000;++fn get_memory(ctx: &ToolContext, key: &str, args: &Value) -> ToolResult {+ let max_chars = int_arg(args, "max_chars", 20_000, 200, MAX_GET_CHARS as i64)? as usize;+ let Some(doc) = ctx.store.get_memory(key)? else {+ return Err(ToolError::Failed(format!(+ "No memory file with key `{key}`; get a wake://memory/… reference from wake_list_memories or wake_search."+ )));+ };+ let body = crate::adapters::memory_body(&doc);+ let mut out = format!(+ "# {}\nkey: `{}` · {} · {} memory",+ doc.title,+ doc.key,+ doc.agent.display_name(),+ doc.scope.label()+ );+ if !doc.project_path.is_empty() {+ out.push_str(&format!(" · project {}", doc.project_path));+ }+ out.push_str(&memory_session_note(&doc));+ if !doc.host.is_empty() {+ out.push_str(&format!(" · @{}", doc.host));+ }+ out.push_str(&format!(+ " · updated {}\nsource: {}\n\n",+ fmt_time(Some(doc.updated_at)),+ doc.path+ ));+ let (text, truncated) = crate::adapters::parse_utils::clip(&body, max_chars);+ out.push_str(&text);+ if !text.ends_with('\n') {+ out.push('\n');+ }+ if truncated {+ // 说实话:max_chars 静默封顶在 MAX_GET_CHARS,超过它没有翻页可言,只能指向+ // 文件本身——原先一律劝"传更大的 max_chars",顶格的调用方会原地打转+ if max_chars < MAX_GET_CHARS {+ out.push_str(&format!(+ "\n[truncated at {max_chars} of {} characters — pass a larger max_chars (up to {MAX_GET_CHARS}) for the rest]\n",+ body.chars().count()+ ));+ } else {+ out.push_str(&format!(+ "\n[truncated at {max_chars} characters; the file is {} characters and that is the largest page this tool reads — open {} for the rest]\n",+ body.chars().count(),+ doc.path+ ));+ }+ }+ Ok(out)+}+fn list_sessions(ctx: &ToolContext, args: &Value) -> ToolResult {let agents = agents_arg(args)?;let since = since_arg(ctx, args)?;@@ -709,16 +980,6 @@ fn list_projects(ctx: &ToolContext, args: &Value) -> ToolResult {Ok(out)}-/// `key` 也接受 `wake://session/<key>#<seq>` 引用(seq 成为默认起点)-fn parse_key_arg(raw: &str) -> (String, Option<i64>) {- let s = raw.trim();- let s = s.strip_prefix("wake://session/").unwrap_or(s);- match s.rsplit_once('#') {- Some((key, seq)) if seq.parse::<i64>().is_ok() => (key.to_string(), seq.parse().ok()),- _ => (s.to_string(), None),- }-}-fn find_session(store: &Store, key: &str) -> Result<Result<SessionMeta, String>, ToolError> {if let Some(meta) = store.get_session(key)? {return Ok(Ok(meta));@@ -844,7 +1105,11 @@ fn subagent_listing(title: &str, meta: &SessionMeta, sidechains: &[SidechainInfofn get_session(ctx: &ToolContext, args: &Value) -> ToolResult {let raw_key = text_arg(args, "key")?.ok_or_else(|| ToolError::InvalidParams("`key` is required".into()))?;- let (key, ref_seq) = parse_key_arg(raw_key);+ // 记忆引用走另一条读法;不另开工具,agent 拿到什么引用都交给同一个入口+ let (key, ref_seq) = match WakeRef::parse(raw_key) {+ WakeRef::Memory { key } => return get_memory(ctx, &key, args),+ WakeRef::Session { key, seq } => (key, seq),+ };let from_seq = int_arg(args, "from_seq", ref_seq.unwrap_or(0), 0, i64::MAX)?;let opts = CompactOptions {from_seq,@@ -1090,17 +1355,29 @@ mod tests {#[test]fn key_arg_accepts_wake_refs() {+ let session = |key: &str, seq: Option<i64>| WakeRef::Session {+ key: key.to_string(),+ seq,+ };assert_eq!(- parse_key_arg("wake://session/claude-code:abc#12"),- ("claude-code:abc".to_string(), Some(12))+ WakeRef::parse(&session_ref("claude-code:abc", 12)),+ session("claude-code:abc", Some(12)));assert_eq!(- parse_key_arg("codex:devbox:0195-xyz"),- ("codex:devbox:0195-xyz".to_string(), None)+ WakeRef::parse("codex:devbox:0195-xyz"),+ session("codex:devbox:0195-xyz", None));assert_eq!(- parse_key_arg(" claude-code:abc "),- ("claude-code:abc".to_string(), None)+ WakeRef::parse(" claude-code:abc "),+ session("claude-code:abc", None)+ );+ // 记忆 key 自身带 `#`(SQLite 型虚拟路径)也不能被当成 seq 拆掉+ let memory_key = "codex:/home/me/.codex/memories_1.sqlite#t-0001";+ assert_eq!(+ WakeRef::parse(&memory_ref(memory_key)),+ WakeRef::Memory {+ key: memory_key.to_string()+ });}diff --git a/crates/wake-core/src/models.rs b/crates/wake-core/src/models.rsindex e838c86..c111e36 100644--- a/crates/wake-core/src/models.rs+++ b/crates/wake-core/src/models.rs@@ -613,6 +613,149 @@ pub const MAX_IMAGE_BYTES: u64 = 12 * 1024 * 1024;pub const MAX_TOOL_IO: usize = 16 * 1024;pub const MAX_TITLE: usize = 80;+/// agent 自己写下的记忆文档(Claude Code 的 auto-memory、Codex 的 memories)。Wake+/// 只读:列出、搜索、阅读,不编辑、不同步、不删除——写别家数据破铁律,各家格式+/// 与语义也不同。落 memories 表,扫描收尾时由各家 `list_memories` 按 (agent, host)+/// 整组替换+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct MemoryDoc {+ /// `{agent}:{path}`,远程 `{agent}:{host}:{path}`——与会话 key 同一构造点+ /// (`session_key`),远程装饰器插 host 的逻辑因此一份通吃;agent 恒为首段+ pub key: String,+ pub agent: AgentId,+ /// 远程 host 名;空 = 本地+ pub host: String,+ pub scope: MemoryScope,+ /// 归属的项目路径。adapter 一般不填(留空),读库时按 `session_key` 连 sessions+ /// 表解析——项目归属随索引走、永远是新的,不在写入时定格;adapter 自己知道+ /// 项目时可以直接填,填了优先。用户级恒空+ pub project_path: String,+ pub project_name: String,+ /// 归属锚点:线程级记忆是它所属的会话,Claude 项目级记忆是该项目目录里最新的+ /// 一条会话(同目录的会话同一个 cwd);用户级为空。只有线程级才在界面上标成+ /// "session memory",项目级的锚点只用来解析项目+ pub session_key: String,+ /// 文件路径;SQLite 型是 `<db>#<id>` 虚拟路径(sqlite_ro::virtual_path)+ pub path: String,+ pub title: String,+ /// epoch ms+ pub updated_at: i64,+ pub size_bytes: i64,+ /// 正文原样(含 frontmatter);文件型阅读时先读磁盘,这份是索引与兜底+ pub body: String,+}++/// Memory 页侧栏的导航计数:总数、按 agent、按解析出的项目(用户级记忆只计入+/// 总数与 agent,不属于任何项目;没归属的记在 path 为空的那一项)+#[derive(Debug, Clone, Default)]+pub struct MemoryCounts {+ pub total: i64,+ pub agents: Vec<(AgentId, i64)>,+ pub projects: Vec<MemoryProject>,+}++/// 一个项目名下的记忆文件数(path 为空 = 没归属的那一组)+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct MemoryProject {+ pub path: String,+ pub name: String,+ pub count: i64,+ /// 组内最近一次更新,epoch ms+ pub updated_at: i64,+}++/// 记忆文档归哪一组:用户级一组、没归属一组、其余按项目——GUI 的分组/侧栏/页头与+/// MCP 的组头都从这里派生,判据(scope、project_path 空不空)只写一处+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum MemoryGroup<'a> {+ User,+ Unknown,+ Project { path: &'a str, name: &'a str },+}++impl MemoryDoc {+ pub fn group(&self) -> MemoryGroup<'_> {+ if self.scope == MemoryScope::User {+ MemoryGroup::User+ } else if self.project_path.is_empty() {+ MemoryGroup::Unknown+ } else {+ MemoryGroup::Project {+ path: &self.project_path,+ name: &self.project_name,+ }+ }+ }+}++/// 记忆的归属层级+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum MemoryScope {+ /// 跨项目的用户级(Codex 的 memories/*.md)+ User,+ /// 某个项目的(Claude Code 的 projects/<dir>/memory/)+ Project,+ /// 某条会话的(Codex 的 stage1_outputs 逐线程摘要)+ Thread,+}++impl MemoryScope {+ /// 落库/传输用的小写名+ pub fn as_str(self) -> &'static str {+ match self {+ Self::User => "user",+ Self::Project => "project",+ Self::Thread => "thread",+ }+ }++ pub fn parse(s: &str) -> Option<Self> {+ match s {+ "user" => Some(Self::User),+ "project" => Some(Self::Project),+ "thread" => Some(Self::Thread),+ _ => None,+ }+ }++ /// 人读标签(MCP 输出用;UI 另过 t())+ pub fn label(self) -> &'static str {+ match self {+ Self::User => "user-level",+ Self::Project => "project",+ Self::Thread => "session",+ }+ }+}++/// 记忆列表/搜索的筛选面(Memory 页与 wake_list_memories / wake_search 共用)+#[derive(Debug, Clone, Default)]+pub struct MemoryFilter {+ pub agents: Vec<AgentId>,+ /// 项目路径并集;空串不匹配任何东西。用户级记忆对每个项目都成立,任何项目筛选+ /// 下都列出+ pub project_paths: Vec<String>,+ /// 只要没归属(项目解析不出)的那一组——GUI 侧栏的 Unknown project 行;与+ /// `project_paths` 一起时取并集。显式一位,不拿空串当暗号+ pub unattributed: bool,+ /// 0 = 不限+ pub limit: i64,+}++impl MemoryFilter {+ /// 有没有任何项目维度的筛选+ pub fn scopes_projects(&self) -> bool {+ !self.project_paths.is_empty() || self.unattributed+ }+}++/// 记忆搜索的一条命中(snippet 带 HL_OPEN/HL_CLOSE 高亮哨兵,与会话命中同款)+#[derive(Debug, Clone)]+pub struct MemoryHit {+ pub doc: MemoryDoc,+ pub snippet: String,+}+/// 无标题会话的占位标题(quickMeta 守卫与 adapters 共用,防半/全角漂移)pub const UNTITLED: &str = "Untitled";diff --git a/crates/wake-core/src/remote.rs b/crates/wake-core/src/remote.rsindex ae16f6a..71250ef 100644--- a/crates/wake-core/src/remote.rs+++ b/crates/wake-core/src/remote.rs@@ -68,6 +68,10 @@ pub const REMOTE_LAYOUTS: &[RemoteAgentLayout] = &[".codex/archived_sessions",".codex/state_5.sqlite",".codex/state_5.sqlite-wal",+ // 记忆:用户级 Markdown 与逐线程的整合库(list_memories 读)+ ".codex/memories",+ ".codex/memories_1.sqlite",+ ".codex/memories_1.sqlite-wal",],exclude: &[],},@@ -194,15 +198,16 @@ pub const REMOTE_LAYOUTS: &[RemoteAgentLayout] = &[},RemoteAgentLayout {agent: AgentId::Zcode,- // home 形态:cli/db/db.sqlite 与 v2/tasks-index.sqlite 全相对派生。- // 只拉两个库文件——凭证(v2/credentials.json)与网络 CA 私钥(v2/certs/)- // 不在白名单里就不会被碰;exclude 只对目录源起作用,文件源留空+ // home 形态:cli/db/db.sqlite、v2/tasks-index.sqlite 与 cli/memories 全相对+ // 派生。只拉两个库文件 + 记忆目录(里面只有 Markdown)——凭证+ // (v2/credentials.json)与网络 CA 私钥(v2/certs/)不在白名单里就不会被碰mount: ".zcode",sync_paths: &[".zcode/cli/db/db.sqlite",".zcode/cli/db/db.sqlite-wal",".zcode/v2/tasks-index.sqlite",".zcode/v2/tasks-index.sqlite-wal",+ ".zcode/cli/memories",],exclude: &[],},diff --git a/crates/wake-core/src/scanner.rs b/crates/wake-core/src/scanner.rsindex 32ee9cf..c71fa56 100644--- a/crates/wake-core/src/scanner.rs+++ b/crates/wake-core/src/scanner.rs@@ -470,6 +470,9 @@ fn run_scan_inner(if sync_parent_links(adapters, store)? {events.on_sessions_changed();}+ if sync_memories(adapters, store) {+ events.on_sessions_changed();+ }if force_grok_backfill && grok_backfill_succeeded {store.finish_grok_parent_backfill()?;}@@ -480,17 +483,90 @@ fn run_scan_inner(Ok(())}+/// 记忆文档随每轮扫描整组刷新:同 (agent, host) 的各实例(默认根 + 自定义根;远程+/// 镜像按 host 自成组)合并后交给 store 按组替换,消失的文件随之出库。项目归属+/// 不在这里算(读库时按 session_key 连 sessions)。某家读失败只 eprintln 并**跳过+/// 该组**(None,不替换,免得一次瞬时失败把库里那组清空),不截断整轮——与会话+/// 枚举同规矩。库里有、roster 里已经没有的分组(删掉的远程 host、停用的 agent)+/// 整组清掉——否则它们的记忆在会话与缓存都没了之后还能被列出、搜到(Codex review+/// 2026-09-17)+fn sync_memories(adapters: &[Box<dyn AgentAdapter>], store: &Arc<Store>) -> bool {+ /// 一组的收集结果:读成功的实例给文档,读失败的实例给它的根(那些根下的行冻结)+ #[derive(Default)]+ struct Group {+ docs: Vec<MemoryDoc>,+ frozen: Vec<std::path::PathBuf>,+ succeeded: usize,+ failed: usize,+ }+ 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 adapter in adapters {+ let group = groups+ .entry((adapter.agent(), adapter.host().to_string()))+ .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 mut changed = false;+ for ((agent, host), group) in groups {+ // 这一组的实例全失败:整组原样保留(roster 里没有实例的组是 0/0,照常清空)+ if group.succeeded == 0 && group.failed > 0 {+ continue;+ }+ match store.replace_memories(agent, &host, &group.docs, &group.frozen) {+ Ok(c) => changed |= c,+ Err(e) => eprintln!(+ "[scanner] memories write failed for {}: {e}",+ agent.as_str()+ ),+ }+ }+ changed+}+/// 多 location 下关系元数据跟着 parent 会话,而 child 的胜出文件可能在另一根。/// 因此先接受“关系目标 parent 的胜出文件也属于该快照”的直接边,再跨快照把/// 嵌套链扁平到 root。解除/换父前重解析 child,恢复被旧父项目覆盖的自身归属。fn sync_parent_links(adapters: &[Box<dyn AgentAdapter>], store: &Arc<Store>) -> Result<bool> {let mut managed_agents = std::collections::HashSet::new();+ let mut unknown_agents = std::collections::HashSet::new();let mut links_by_adapter: Vec<std::collections::HashMap<String, String>> =Vec::with_capacity(adapters.len());for adapter in adapters {if adapter.manages_parent_links() {managed_agents.insert(adapter.agent());- links_by_adapter.push(adapter.parent_links().into_iter().collect());+ match adapter.parent_links() {+ Some(links) => links_by_adapter.push(links.into_iter().collect()),+ None => {+ // 这一刻读不出关系(state DB 打不开):这一家整段跳过,库里的关系+ // 原样保留——拿空快照对账就是整家清空(2026-09-21 review)+ eprintln!(+ "[scanner] parent links of {} unreadable this round; keeping the indexed ones",+ adapter.agent().as_str()+ );+ unknown_agents.insert(adapter.agent());+ links_by_adapter.push(std::collections::HashMap::new());+ }+ }} else {links_by_adapter.push(std::collections::HashMap::new());}@@ -498,6 +574,9 @@ fn sync_parent_links(adapters: &[Box<dyn AgentAdapter>], store: &Arc<Store>) ->let mut changed = false;for agent in managed_agents {+ if unknown_agents.contains(&agent) {+ continue;+ }// 这一家眼下一条关系都没有、库里也没有:整段对账是纯浪费——// session_sources_for_agent 要把这家全部会话读一遍,replace_parent_links// 还要开写事务与扫描线程抢锁。watcher 只要**任一**受影响 agent 管关系@@ -588,8 +667,13 @@ fn sync_parent_links(adapters: &[Box<dyn AgentAdapter>], store: &Arc<Store>) ->continue;}// 保留不会留下悬空关系:replace_parent_links 的 UPDATE 带- // EXISTS(parent),parent 真没了这条边写不进去- if asserted.contains(&(child.as_str(), old_parent.as_str())) {+ // EXISTS(parent),parent 真没了这条边写不进去。只在这一轮算不出这个+ // child 的父时才保留:算得出(parent 已入库、链已扁平到 root)就以算出的+ // 为准——否则先入库的直接边 child→mid 会一直压住 child→root,两层+ // spawn 链永远钉在中间那层(2026-09-21 review)+ if !desired_map.contains_key(&child)+ && asserted.contains(&(child.as_str(), old_parent.as_str()))+ {desired_map.insert(child, old_parent);continue;}diff --git a/crates/wake-core/tests/adapter_contracts.rs b/crates/wake-core/tests/adapter_contracts.rsindex f221d08..a405f1c 100644--- a/crates/wake-core/tests/adapter_contracts.rs+++ b/crates/wake-core/tests/adapter_contracts.rs@@ -726,7 +726,7 @@ fn codex_spawned_subagent_keeps_only_its_own_turns() {assert_eq!(parsed.units[0].seq, visible[0].seq);assert_eq!(- adapter.parent_links(),+ adapter.parent_links().unwrap(),vec![(format!("codex:{child_id}"), format!("codex:{parent_id}"))]);}@@ -873,7 +873,7 @@ fn codex_spawn_links_need_the_state_db_registry() {let adapter = CodexAdapter::new().with_custom_root(home.path().to_path_buf());let refs = adapter.list_session_files().unwrap();- assert!(adapter.parent_links().is_empty());+ assert!(adapter.parent_links().unwrap().is_empty());let child = refs.iter().find(|r| r.native_id == child_id).unwrap();assert_eq!(adapter.parse_session(child).unwrap().meta.title,@@ -1329,7 +1329,7 @@ fn cursor_ide_parse_contract() {// 子代理归属来自 composerHeaders.subagentInfoassert!(adapter.manages_parent_links());assert_eq!(- adapter.parent_links(),+ adapter.parent_links().unwrap(),vec![("cursor:cide-0004".to_string(),"cursor:cide-0001".to_string()@@ -1785,7 +1785,7 @@ fn grok_parse_contract() {setup();let adapter = GrokAdapter::new().with_custom_root(fixture("grok"));adapter.begin_scan();- assert!(adapter.parent_links().contains(&(+ assert!(adapter.parent_links().unwrap().contains(&("grok:aaaaaaaa-aaaa-bbbb-cccc-0000000000aa".into(),"grok:77777777-aaaa-bbbb-cccc-000000000007".into(),)));@@ -2445,7 +2445,7 @@ fn hermes_parse_contract() {// /branch 分支挂到父会话下(parent_session_id),不当顶层assert!(adapter.manages_parent_links());assert_eq!(- adapter.parent_links(),+ adapter.parent_links().unwrap(),vec![("hermes:hs-0005".to_string(), "hermes:hs-0001".to_string())]);@@ -3680,3 +3680,293 @@ fn workbuddy_is_a_codebuddy_twin() {"没有 CLI 的 agent 不画 Open In");}++// ---------------------------------------------------------------- 记忆(只读镜像)++/// Claude auto-memory:projects/<dir>/memory/*.md,挂到同目录里的一条会话上(项目+/// 路径读库时按它解析,adapter 不填),标题取 frontmatter 的 description、没有就用+/// 文件名,正文原样;指纹没变第二次列出的是缓存的同一份+#[test]+fn claude_lists_project_memories() {+ setup();+ let adapter = ClaudeAdapter::new().with_custom_root(fixture("claude/projects"));+ let docs = adapter.list_memories().unwrap();+ let titles: Vec<&str> = docs.iter().map(|d| d.title.as_str()).collect();+ assert_eq!(titles, ["MEMORY", "Wake testing conventions for this repo"]);+ let session_keys: Vec<String> = adapter+ .list_session_files()+ .unwrap()+ .iter()+ .map(|r| format!("claude-code:{}", r.native_id))+ .collect();+ for d in &docs {+ assert_eq!(d.agent, AgentId::ClaudeCode);+ assert_eq!(d.scope, MemoryScope::Project);+ assert!(+ d.project_path.is_empty() && d.project_name.is_empty(),+ "项目在读库时按锚点解析,adapter 不填"+ );+ assert!(+ session_keys.contains(&d.session_key),+ "锚点是同目录里的一条会话: {} ∉ {session_keys:?}",+ d.session_key+ );+ assert!(+ d.key.starts_with("claude-code:") && d.key.ends_with(".md"),+ "{}",+ d.key+ );+ assert!(d.host.is_empty());+ assert!(d.size_bytes > 0 && d.updated_at > 0);+ }+ assert_eq!(+ docs[1].body.lines().next(),+ Some("---"),+ "正文原样含 frontmatter"+ );+ assert!(docs[1].body.contains("name: wake-testing"));+ assert_eq!(adapter.list_memories().unwrap(), docs, "指纹没变走缓存");+}++/// ZCode:`cli/memories/projects/<slug>-<hash>/memory/*.md`(Claude auto-memory 同款+/// 格式);目录名的 hash 是 sha256(工作区路径) 前 16 位,按库里会话的 directory 精确+/// 对上项目、不用锚点;对不上的落 Unknown project;没有 memory/ 子目录的工作区目录+/// 不算;裸库拷贝(没有 home)一份都不列+#[test]+fn zcode_lists_project_memories() {+ setup();+ let home = tempfile::tempdir().unwrap();+ let root = home.path().join(".zcode");+ let db = root.join("cli/db/db.sqlite");+ fs::create_dir_all(db.parent().unwrap()).unwrap();+ common::build_zcode_db(&db);+ // 3b44ec0d2ccabf78 = sha256("/Users/tester/Github/wakefx")[..16],fixture 会话的+ // directory。写死而不是调 memory_dir_hash 算——算法漂了这里才会红+ let wakefx = root.join("cli/memories/projects/wakefx-3b44ec0d2ccabf78/memory");+ fs::create_dir_all(&wakefx).unwrap();+ fs::write(+ wakefx.join("MEMORY.md"),+ "- [Prefers pnpm](prefers-pnpm.md) — tooling\n",+ )+ .unwrap();+ fs::write(+ wakefx.join("prefers-pnpm.md"),+ "---\nname: prefers-pnpm\ndescription: Prefers pnpm over npm\nmetadata:\n type: feedback\n---\n\nUse pnpm.\n",+ )+ .unwrap();+ // 库里没有会话的工作区:hash 对不上,落 Unknown project+ let orphan = root.join("cli/memories/projects/other-0000000000000000/memory");+ fs::create_dir_all(&orphan).unwrap();+ fs::write(orphan.join("note.md"), "# orphan\n").unwrap();+ 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 summary: Vec<(&str, &str, &str)> = docs+ .iter()+ .map(|d| {+ (+ d.title.as_str(),+ d.project_path.as_str(),+ d.project_name.as_str(),+ )+ })+ .collect();+ assert_eq!(+ summary,+ [+ ("note", "", ""),+ ("MEMORY", "/Users/tester/Github/wakefx", "wakefx"),+ (+ "Prefers pnpm over npm",+ "/Users/tester/Github/wakefx",+ "wakefx"+ ),+ ]+ );+ for d in &docs {+ assert_eq!(d.agent, AgentId::Zcode);+ assert_eq!(d.scope, MemoryScope::Project);+ assert!(d.session_key.is_empty(), "项目由目录名直接对上,不用锚点");+ assert!(+ d.key.starts_with("zcode:") && d.key.ends_with(".md"),+ "{}",+ d.key+ );+ assert!(d.host.is_empty());+ assert!(d.size_bytes > 0 && d.updated_at > 0);+ }+ assert!(+ docs[2].body.contains("name: prefers-pnpm"),+ "正文原样含 frontmatter"+ );+ assert_eq!(adapter.list_memories().unwrap(), docs, "指纹没变走缓存");+ assert_eq!(+ wake_core::adapters::zcode::memory_dir_hash("/Users/tester/Github/wakefx/"),+ "3b44ec0d2ccabf78",+ "收尾分隔符不影响(源码先 resolve 再 hash)"+ );++ // 直接选中 db.sqlite 的裸库拷贝没有 home:不摸父目录,一份都不列+ let bare = ZcodeAdapter::new().with_custom_root(db.clone());+ assert!(bare.list_memories().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());+}++/// 标题来自 frontmatter 的 description:块标量(`description: >` 换行缩进写)折成一行,+/// 不是一个字面的 ">";超长的按字符封顶(本机有 565 字符的,列表与 MCP 一行放不下)+#[test]+fn memory_titles_fold_block_scalars_and_clip() {+ setup();+ let root = tempfile::tempdir().unwrap();+ let project = root.path().join("-Users-tester-Github-wakefx");+ fs::create_dir_all(project.join("memory")).unwrap();+ fs::write(+ project.join("11111111-aaaa-bbbb-cccc-000000000001.jsonl"),+ "{\"type\":\"user\",\"cwd\":\"/Users/tester/Github/wakefx\"}\n",+ )+ .unwrap();+ fs::write(+ project.join("memory").join("folded.md"),+ "---\nname: folded\ndescription: >\n Prefers pnpm over npm,\n and never runs db:push\nmetadata:\n type: feedback\n---\n\nbody\n",+ )+ .unwrap();+ let long = "x".repeat(300);+ fs::write(+ project.join("memory").join("long.md"),+ format!("---\nname: long\ndescription: {long}\n---\n\nbody\n"),+ )+ .unwrap();+ let adapter = ClaudeAdapter::new().with_custom_root(root.path().to_path_buf());+ let docs = adapter.list_memories().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!(+ titles[1].chars().count() <= 121 && titles[1].ends_with('…'),+ "{}",+ titles[1]+ );+}++/// Claude 记忆的锚点是项目目录里最新的**非空**会话:零字节的 jsonl(刚起的会话)+/// 进不了库,拿它当锚点整组记忆就落 Unknown project+#[test]+fn claude_memory_anchor_skips_empty_sessions() {+ setup();+ let root = tempfile::tempdir().unwrap();+ let project = root.path().join("-Users-tester-Github-wakefx");+ fs::create_dir_all(project.join("memory")).unwrap();+ fs::write(project.join("memory").join("MEMORY.md"), "# notes\n").unwrap();+ fs::write(+ project.join("11111111-aaaa-bbbb-cccc-000000000001.jsonl"),+ "{\"type\":\"user\",\"cwd\":\"/Users/tester/Github/wakefx\"}\n",+ )+ .unwrap();+ fs::write(+ project.join("ffffffff-aaaa-bbbb-cccc-00000000000f.jsonl"),+ "",+ )+ .unwrap();+ let adapter = ClaudeAdapter::new().with_custom_root(root.path().to_path_buf());+ let docs = adapter.list_memories().unwrap();+ assert_eq!(docs.len(), 1);+ assert_eq!(+ docs[0].session_key,+ "claude-code:11111111-aaaa-bbbb-cccc-000000000001"+ );+}++/// Codex:memories/*.md 是用户级;memories_1.sqlite 的 stage1_outputs 逐线程一行,+/// 挂到 codex:<thread_id>;空摘要的线程不列;没有 home 的裸目录为空+#[test]+fn codex_lists_user_and_thread_memories() {+ setup();+ let home = tempfile::tempdir().unwrap();+ fs::create_dir_all(home.path().join("sessions")).unwrap();+ fs::create_dir_all(home.path().join("memories")).unwrap();+ fs::write(+ home.path().join("memories").join("user-preferences.md"),+ "# User preferences\n\nConcise replies.\n",+ )+ .unwrap();+ let db = rusqlite::Connection::open(home.path().join("memories_1.sqlite")).unwrap();+ db.execute_batch(+ "CREATE TABLE stage1_outputs (+ thread_id TEXT PRIMARY KEY, source_updated_at INTEGER NOT NULL,+ raw_memory TEXT, rollout_summary TEXT, rollout_slug TEXT,+ generated_at INTEGER NOT NULL, usage_count INTEGER, last_usage INTEGER,+ selected_for_phase2 INTEGER NOT NULL DEFAULT 0,+ selected_for_phase2_source_updated_at INTEGER);+ INSERT INTO stage1_outputs VALUES ('t-0001', 1, 'Prefers rustfmt before commits',+ 'Fixed the scanner finale contract', 'scanner-finale', 1786100000, NULL, NULL, 0, NULL);+ INSERT INTO stage1_outputs VALUES ('t-0002', 1, '', '', NULL, 1786100001, NULL, NULL, 0, NULL);+ INSERT INTO stage1_outputs VALUES ('t-0003', 1, NULL, 'Only a summary, memory column NULL',+ 'nullable-row', '2026-09-21T10:00:00Z', NULL, NULL, 0, NULL);",+ )+ .unwrap();+ drop(db);++ let adapter = CodexAdapter::new().with_custom_root(home.path().to_path_buf());+ let docs = adapter.list_memories().unwrap();+ assert_eq!(docs.len(), 3, "空摘要空记忆的线程不列: {docs:?}");+ // 列的可空性与时间格式是推断的:NULL 正文列与 ISO 文本时间的行照样列,别的行不受影响+ let nullable = &docs[2];+ assert_eq!(+ (nullable.session_key.as_str(), nullable.title.as_str()),+ ("codex:t-0003", "nullable-row")+ );+ assert!(nullable.body.contains("Only a summary") && nullable.updated_at > 1_786_100_000_000);+ let user = &docs[0];+ assert_eq!(+ (user.scope, user.title.as_str()),+ (MemoryScope::User, "user-preferences")+ );+ assert!(user.project_path.is_empty() && user.session_key.is_empty());+ let thread = &docs[1];+ assert_eq!(thread.scope, MemoryScope::Thread);+ assert_eq!(thread.session_key, "codex:t-0001");+ assert_eq!(thread.title, "scanner-finale");+ assert!(+ thread.body.contains("Fixed the scanner finale contract")+ && thread.body.contains("rustfmt")+ );+ assert_eq!(thread.updated_at, 1_786_100_000_000, "秒换算成毫秒");+ // 非 UTF-8 的文件不是记忆:跳过它,别的照列(指纹变了才重读,新文件即新指纹)+ fs::write(+ home.path().join("memories").join("blob.md"),+ [0xff, 0xfe, 0x00],+ )+ .unwrap();+ let docs_again = adapter.list_memories().unwrap();+ assert_eq!(docs_again.len(), 3, "{docs_again:?}");+ // 自定义根只选了 sessions 目录:没有 home,不摸父目录里的 memories+ let sessions_only = CodexAdapter::new().with_custom_root(home.path().join("sessions"));+ assert!(+ sessions_only.list_memories().unwrap().is_empty(),+ "sessions 目录当根时不得越界读父目录的记忆"+ );+ // 库在但读不出(不是 SQLite 文件)= 不知道:整家报 Err、不缓存,scanner 跳过该组;+ // 缓存成"没有"会把库里的线程记忆整组删掉。库换回好的(戳变了)立刻恢复+ let db_path = home.path().join("memories_1.sqlite");+ let good = fs::read(&db_path).unwrap();+ fs::write(&db_path, b"not a sqlite database").unwrap();+ assert!(+ adapter.list_memories().is_err(),+ "memories_1.sqlite 读不出必须报 Err 而不是当成空"+ );+ fs::write(&db_path, good).unwrap();+ assert_eq!(adapter.list_memories().unwrap().len(), 3);+ assert!(+ thread.path.ends_with("memories_1.sqlite#t-0001"),+ "{}",+ thread.path+ );+ assert_eq!(thread.key, format!("codex:{}", thread.path));++ // 没有 home 证据的目录:memories 自然为空,不报错+ let bare = CodexAdapter::new().with_custom_root(home.path().join("elsewhere"));+ assert!(bare.list_memories().unwrap().is_empty());+}diff --git a/crates/wake-core/tests/cli.rs b/crates/wake-core/tests/cli.rsindex 1a2504d..e1b1a1b 100644--- a/crates/wake-core/tests/cli.rs+++ b/crates/wake-core/tests/cli.rs@@ -218,6 +218,19 @@ fn cases() -> Vec<(Vec<String>, &'static str, Value)> {tools::LIST_PROJECTS,json!({"since":ALWAYS,"limit":10}),),+ (+ argv(&[+ "memories",+ "--project",+ CLAUDE_PROJECT,+ "--agent",+ "claude-code",+ "--limit",+ "10",+ ]),+ tools::LIST_MEMORIES,+ json!({"project":CLAUDE_PROJECT,"agents":["claude-code"],"limit":10}),+ ),]}@@ -313,13 +326,17 @@ fn unreadable_session_exits_one() {#[test]fn no_results_is_success() {for (argv, prefix) in [- (vec!["search", "zzqqxx-no-such-term"], "No matches for"),+ (vec!["search", "zzqqxx-no-such-term"], "No session matches"),(vec!["sessions", "--project", "/nope/nope"],"No indexed project matches",),(vec!["sessions", "--since", NEVER], "No sessions"),(vec!["projects", "--since", NEVER], "No projects"),+ (+ vec!["memories", "--project", "/nope/nope"],+ "No indexed project matches",+ ),] {let (stdout, stderr, code) = cli_run(&argv);assert_eq!(code, Some(0), "argv {argv:?}: {stderr}");diff --git a/crates/wake-core/tests/db_roundtrip.rs b/crates/wake-core/tests/db_roundtrip.rsindex 6761c08..0022a45 100644--- a/crates/wake-core/tests/db_roundtrip.rs+++ b/crates/wake-core/tests/db_roundtrip.rs@@ -1209,3 +1209,371 @@ fn search_ranks_recently_active_sessions_higher() {["claude-code:fresh", "claude-code:old"]);}++/// 记忆表:按 (agent, host) 整组替换——没变的不动、变了的换、多出的删;列表项目内+/// 新到旧、用户级最后且不受项目筛选影响;搜索命中带 snippet 并随删除消失;rebuild 清空+/// `limit` 只封项目级:用户级(对每个项目都成立)不限量接在后面——否则默认 50 条+/// 一刀切砍掉的正是它们;侧栏计数与列表同口径:项目行的计数含用户级,点开看到几行+/// 徽章就是几;LIKE 降级的 snippet 遇到小写不保长的字符(Ω)与全角标点不得 panic+/// (2026-09-21 review)+#[test]+fn memory_limit_keeps_user_level_and_counts_and_snippets_agree() {+ let dir = tempfile::tempdir().unwrap();+ let store = Store::open(&dir.path().join("t.db")).unwrap();+ let doc = |key: &str, scope: MemoryScope, project: &str, body: &str, updated: i64| MemoryDoc {+ key: key.to_string(),+ agent: AgentId::ClaudeCode,+ host: String::new(),+ scope,+ project_path: project.to_string(),+ project_name: if project.is_empty() {+ String::new()+ } else {+ "app".to_string()+ },+ session_key: String::new(),+ path: key.trim_start_matches("claude-code:").to_string(),+ title: key.to_string(),+ updated_at: updated,+ size_bytes: body.len() as i64,+ body: body.to_string(),+ };+ let docs = vec![+ doc(+ "claude-code:/m/p1.md",+ MemoryScope::Project,+ "/work/app",+ "Ωmega,二维码在这里",+ 3,+ ),+ doc(+ "claude-code:/m/p2.md",+ MemoryScope::Project,+ "/work/app",+ "second",+ 2,+ ),+ doc(+ "claude-code:/m/p3.md",+ MemoryScope::Project,+ "/work/app",+ "third",+ 1,+ ),+ doc(+ "claude-code:/m/u.md",+ MemoryScope::User,+ "",+ "global prefs",+ 9,+ ),+ ];+ store+ .replace_memories(AgentId::ClaudeCode, "", &docs, &[])+ .unwrap();+ let keys = |v: &[MemoryDoc]| v.iter().map(|d| d.key.clone()).collect::<Vec<_>>();++ let limited = store+ .list_memories(&MemoryFilter {+ project_paths: vec!["/work/app".into()],+ limit: 2,+ ..Default::default()+ })+ .unwrap();+ assert_eq!(+ keys(&limited),+ [+ "claude-code:/m/p1.md",+ "claude-code:/m/p2.md",+ "claude-code:/m/u.md"+ ],+ "项目级封顶 2,用户级照列"+ );+ let limited_all = store+ .list_memories(&MemoryFilter {+ limit: 1,+ ..Default::default()+ })+ .unwrap();+ assert_eq!(+ keys(&limited_all),+ ["claude-code:/m/p1.md", "claude-code:/m/u.md"]+ );++ let counts = store.memory_counts().unwrap();+ assert_eq!(counts.total, 4);+ assert_eq!(+ counts+ .projects+ .iter()+ .map(|p| (p.path.as_str(), p.count))+ .collect::<Vec<_>>(),+ [("/work/app", 4)],+ "项目行的计数含用户级"+ );+ let opened = store+ .list_memories(&MemoryFilter {+ project_paths: vec!["/work/app".into()],+ ..Default::default()+ })+ .unwrap();+ assert_eq!(+ opened.len() as i64,+ counts.projects[0].count,+ "徽章 == 点开的行数"+ );++ // 2 个码点走 LIKE 降级;Ω 小写成 ω 后字节数变了,原先拿小写串的字节偏移切原文会 panic+ let hits = store+ .search_memories("二维", &MemoryFilter::default())+ .unwrap();+ assert_eq!(hits.len(), 1);+ assert!(hits[0].snippet.contains("二维"), "{}", hits[0].snippet);+}++#[test]+fn memories_replace_list_and_search() {+ let (_dir, store) = temp_store();+ let doc =+ |key: &str, scope: MemoryScope, project: &str, title: &str, body: &str, updated: i64| {+ MemoryDoc {+ key: key.to_string(),+ agent: AgentId::ClaudeCode,+ host: String::new(),+ scope,+ project_path: project.to_string(),+ project_name: project.rsplit('/').next().unwrap_or("").to_string(),+ session_key: String::new(),+ path: key.trim_start_matches("claude-code:").to_string(),+ title: title.to_string(),+ updated_at: updated,+ size_bytes: body.len() as i64,+ body: body.to_string(),+ }+ };+ let a = doc(+ "claude-code:/m/a.md",+ MemoryScope::Project,+ "/work/app",+ "Scanner notes",+ "The scanner finale guard must always fire.",+ 100,+ );+ let b = doc(+ "claude-code:/m/b.md",+ MemoryScope::Project,+ "/work/app",+ "Style",+ "Four-space indent, no tabs.",+ 200,+ );+ let u = doc(+ "claude-code:/m/user.md",+ MemoryScope::User,+ "",+ "Preferences",+ "Concise replies.",+ 50,+ );+ let all_three = [a.clone(), b.clone(), u.clone()];+ assert!(store+ .replace_memories(AgentId::ClaudeCode, "", &all_three, &[])+ .unwrap());+ assert!(+ !store+ .replace_memories(AgentId::ClaudeCode, "", &all_three, &[])+ .unwrap(),+ "没变不算改动"+ );++ let keys = |docs: &[MemoryDoc]| docs.iter().map(|d| d.key.clone()).collect::<Vec<_>>();+ assert_eq!(+ keys(&store.list_memories(&MemoryFilter::default()).unwrap()),+ [+ "claude-code:/m/b.md",+ "claude-code:/m/a.md",+ "claude-code:/m/user.md"+ ],+ "项目内新到旧,用户级最后"+ );+ let scoped = store+ .list_memories(&MemoryFilter {+ project_paths: vec!["/other".into()],+ ..Default::default()+ })+ .unwrap();+ assert_eq!(+ keys(&scoped),+ ["claude-code:/m/user.md"],+ "项目筛选下用户级照列"+ );+ assert_eq!(+ store+ .get_memory("claude-code:/m/a.md")+ .unwrap()+ .unwrap()+ .body,+ a.body+ );++ let hits = store+ .search_memories("finale guard", &MemoryFilter::default())+ .unwrap();+ assert_eq!(hits.len(), 1);+ assert_eq!(hits[0].doc.key, a.key);+ assert!(hits[0].snippet.contains("finale"), "{}", hits[0].snippet);+ let degraded = store+ .search_memories("no", &MemoryFilter::default())+ .unwrap();+ assert!(+ degraded.iter().any(|h| h.doc.key == b.key),+ "<3 码点走 LIKE: {degraded:?}"+ );++ // b 变了、u 消失:替换后 b 是新正文,u 从列表与搜索里都不见+ let mut b2 = b.clone();+ b2.body = "Tabs are fine now.".into();+ b2.updated_at = 300;+ b2.size_bytes = b2.body.len() as i64;+ assert!(store+ .replace_memories(AgentId::ClaudeCode, "", &[a.clone(), b2.clone()], &[])+ .unwrap());+ assert_eq!(+ store.list_memories(&MemoryFilter::default()).unwrap().len(),+ 2+ );+ assert_eq!(store.get_memory(&b.key).unwrap().unwrap().body, b2.body);+ assert!(+ store+ .search_memories("Concise", &MemoryFilter::default())+ .unwrap()+ .is_empty(),+ "删掉的记忆不再命中"+ );++ store.rebuild_all().unwrap();+ assert!(store+ .list_memories(&MemoryFilter::default())+ .unwrap()+ .is_empty());+}++/// 项目归属在读库时按 session_key 连 sessions 解析:会话晚于记忆入库、会话换了项目,+/// 记忆都自动跟上;没有锚点也没有项目的落 Unknown,项目筛选捞不到它+#[test]+fn memories_resolve_their_project_through_the_anchor_session() {+ let (_dir, store) = temp_store();+ let anchored = MemoryDoc {+ key: "claude-code:/m/anchored.md".to_string(),+ agent: AgentId::ClaudeCode,+ host: String::new(),+ scope: MemoryScope::Project,+ project_path: String::new(),+ project_name: String::new(),+ session_key: "claude-code:s1".to_string(),+ path: "/m/anchored.md".to_string(),+ title: "Anchored".to_string(),+ updated_at: 10,+ size_bytes: 4,+ body: "body".to_string(),+ };+ let orphan = MemoryDoc {+ key: "claude-code:/m/orphan.md".to_string(),+ session_key: String::new(),+ path: "/m/orphan.md".to_string(),+ title: "Orphan".to_string(),+ ..anchored.clone()+ };+ store+ .replace_memories(AgentId::ClaudeCode, "", &[anchored.clone(), orphan], &[])+ .unwrap();+ let project_of = |key: &str| store.get_memory(key).unwrap().unwrap().project_path;+ assert_eq!(project_of(&anchored.key), "", "会话还没入库:暂时没有项目");++ // 会话入库(晚于记忆)——记忆立刻有了项目,写入时没有定格+ let mut s1 = meta("claude-code:s1", "Session one");+ s1.project_path = "/work/app".into();+ s1.project_name = "app".into();+ store+ .write_session_guarded(&s1, 5, &[], &|_| 0, None)+ .unwrap();+ assert_eq!(project_of(&anchored.key), "/work/app");+ assert_eq!(+ store+ .list_memories(&MemoryFilter::default())+ .unwrap()+ .iter()+ .map(|d| d.key.as_str())+ .collect::<Vec<_>>(),+ [anchored.key.as_str(), "claude-code:/m/orphan.md"],+ "没归属的一组排在项目之后"+ );+ let scoped = store+ .list_memories(&MemoryFilter {+ project_paths: vec!["/work/app".into()],+ ..Default::default()+ })+ .unwrap();+ assert_eq!(+ scoped.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),+ [anchored.key.as_str()],+ "项目筛选按解析出的项目;没归属的不算任何项目"+ );+ assert_eq!(scoped[0].project_name, "app");+ let unknown = store+ .list_memories(&MemoryFilter {+ unattributed: true,+ ..Default::default()+ })+ .unwrap();+ assert_eq!(+ unknown.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),+ ["claude-code:/m/orphan.md"],+ "空串筛的是没归属的那一组(侧栏 Unknown project 行)"+ );+ // 侧栏计数与列表同一口径:总数、按 agent、按解析出的项目(没归属的垫底)+ let counts = store.memory_counts().unwrap();+ assert_eq!(counts.total, 2);+ assert_eq!(counts.agents, vec![(AgentId::ClaudeCode, 2)]);+ assert_eq!(+ counts+ .projects+ .iter()+ .map(|p| (p.path.as_str(), p.name.as_str(), p.count))+ .collect::<Vec<_>>(),+ [("/work/app", "app", 1), ("", "", 1)]+ );++ // 会话换了项目,记忆跟着走+ s1.project_path = "/work/app-renamed".into();+ s1.project_name = "app-renamed".into();+ store+ .write_session_guarded(&s1, 6, &[], &|_| 0, None)+ .unwrap();+ assert_eq!(project_of(&anchored.key), "/work/app-renamed");++ // 锚点换了(目录里来了更新的会话)是改动,同 key 重写;正文与时间没变也要写。+ // 同 key 重复(同家两个实例的根重叠)后者胜——前面那份与库里相同也不算数+ let mut moved = anchored.clone();+ moved.session_key = "claude-code:s2".to_string();+ assert!(store+ .replace_memories(+ AgentId::ClaudeCode,+ "",+ &[anchored.clone(), moved.clone()],+ &[]+ )+ .unwrap());+ assert_eq!(+ store.get_memory(&moved.key).unwrap().unwrap().session_key,+ "claude-code:s2"+ );+ assert!(+ store+ .search_memories("body", &MemoryFilter::default())+ .unwrap()+ .iter()+ .all(|h| h.doc.key == moved.key),+ "重写后 FTS 里只剩这一份、没有旧行残留"+ );+}diff --git a/crates/wake-core/tests/fixtures/claude/projects/-Users-tester-Github-wakefx/memory/MEMORY.md b/crates/wake-core/tests/fixtures/claude/projects/-Users-tester-Github-wakefx/memory/MEMORY.mdnew file mode 100644index 0000000..8045a9e--- /dev/null+++ b/crates/wake-core/tests/fixtures/claude/projects/-Users-tester-Github-wakefx/memory/MEMORY.md@@ -0,0 +1,3 @@+# Memory Index++- [Wake testing conventions](wake-testing.md) — fixtures are synthetic, never real sessionsdiff --git a/crates/wake-core/tests/fixtures/claude/projects/-Users-tester-Github-wakefx/memory/wake-testing.md b/crates/wake-core/tests/fixtures/claude/projects/-Users-tester-Github-wakefx/memory/wake-testing.mdnew file mode 100644index 0000000..781f9c3--- /dev/null+++ b/crates/wake-core/tests/fixtures/claude/projects/-Users-tester-Github-wakefx/memory/wake-testing.md@@ -0,0 +1,9 @@+---+name: wake-testing+description: Wake testing conventions for this repo+metadata:+ type: project+---++Fixtures are synthetic; never commit real session data. Run scripts/test.sh after every+non-trivial change, and the qrcode scanner regression needs a real fixture file.diff --git a/crates/wake-core/tests/fixtures/codex/memories/user-preferences.md b/crates/wake-core/tests/fixtures/codex/memories/user-preferences.mdnew file mode 100644index 0000000..e86b8ff--- /dev/null+++ b/crates/wake-core/tests/fixtures/codex/memories/user-preferences.md@@ -0,0 +1,4 @@+# User preferences++Prefers concise replies. Runs the test suite before every commit and dislikes+unrequested refactors.diff --git a/crates/wake-core/tests/mcp_stdio.rs b/crates/wake-core/tests/mcp_stdio.rsindex 1a0bbde..2f83c47 100644--- a/crates/wake-core/tests/mcp_stdio.rs+++ b/crates/wake-core/tests/mcp_stdio.rs@@ -206,7 +206,8 @@ fn stdio_contract_end_to_end() {"wake_search","wake_list_sessions","wake_get_session",- "wake_list_projects"+ "wake_list_projects",+ "wake_list_memories"]);@@ -384,6 +385,44 @@ fn stdio_contract_end_to_end() {);let (projects, _) = c.call("wake_list_projects", json!({}));assert!(projects.contains(CLAUDE_PROJECT));++ // 5b. 记忆:Claude 的 auto-memory 按项目列出,Codex 的用户级不受项目筛选影响;+ // wake://memory 引用交给 wake_get_session 读;wake_search 末尾附带记忆命中+ let (memories, _) = c.call("wake_list_memories", json!({ "project": CLAUDE_PROJECT }));+ assert!(+ memories.contains("Wake testing conventions for this repo"),+ "{memories}"+ );+ assert!(+ memories.contains("user-preferences"),+ "Codex 的用户级记忆不受项目筛选影响:\n{memories}"+ );+ let mem_ref = memories+ .lines()+ .find_map(|l| l.trim().strip_prefix("ref: "))+ .expect("a wake://memory ref")+ .to_string();+ assert!(mem_ref.starts_with("wake://memory/"), "{mem_ref}");+ let (memory, is_err) = c.call("wake_get_session", json!({ "key": mem_ref }));+ assert!(!is_err, "{memory}");+ assert!(+ memory.starts_with("# ") && memory.contains("source: "),+ "{memory}"+ );+ let (found, _) = c.call("wake_search", json!({ "query": "synthetic" }));+ assert!(found.contains("Memory files that mention"), "{found}");+ // 项目没匹配上:会话一条都没有,但用户级记忆对每个项目都成立,照样查+ let (unmatched, is_err) = c.call(+ "wake_search",+ json!({ "query": "concise", "project": "/nope/nope" }),+ );+ assert!(!is_err);+ assert!(+ unmatched.contains("No indexed project matches")+ && unmatched.contains("Memory files that mention")+ && unmatched.contains("user-preferences"),+ "{unmatched}"+ );// 用不可能到达的绝对日期,不用 "1m":fixture 的 updated_at 有的取自文件 mtime,// Linux 的 fs::copy 不保留 mtime(macOS 走 APFS clone 会保留),staged 的// fixture 在 Linux 上就是"刚刚"——2026-09-08 CI 只红 ubuntu 那路diff --git a/crates/wake-core/tests/scanner_finale.rs b/crates/wake-core/tests/scanner_finale.rsindex 719c485..45eaa63 100644--- a/crates/wake-core/tests/scanner_finale.rs+++ b/crates/wake-core/tests/scanner_finale.rs@@ -152,6 +152,46 @@ fn finale_fires_on_empty_scan() {assert_terminal_event(&rec.0.lock().unwrap(), "空 adapter 列表");}+/// 库里有、roster 里已经没有的记忆分组(删掉的远程 host、停用的 agent)在下一轮+/// 扫描收尾整组清掉——否则会话与缓存都没了之后记忆还能被列出、搜到+#[test]+fn memories_of_sources_gone_from_the_roster_are_pruned() {+ let dir = tempfile::tempdir().unwrap();+ let store = temp_store(dir.path());+ let doc = MemoryDoc {+ key: "codex:devbox:/home/me/.codex/memories/prefs.md".to_string(),+ agent: AgentId::Codex,+ host: "devbox".to_string(),+ scope: MemoryScope::User,+ project_path: String::new(),+ project_name: String::new(),+ session_key: String::new(),+ path: "/home/me/.codex/memories/prefs.md".to_string(),+ title: "prefs".to_string(),+ updated_at: 1,+ size_bytes: 4,+ body: "body".to_string(),+ };+ store+ .replace_memories(AgentId::Codex, "devbox", &[doc], &[])+ .unwrap();+ assert_eq!(+ store.list_memories(&MemoryFilter::default()).unwrap().len(),+ 1+ );++ // roster 里没有 devbox 这台 host(已被删除)+ let adapters: Vec<Box<dyn AgentAdapter>> = Vec::new();+ run_scan(&adapters, &store, &Recorder::new(), false).unwrap();+ assert!(+ store+ .list_memories(&MemoryFilter::default())+ .unwrap()+ .is_empty(),+ "不再配置的来源的记忆必须随扫描出库"+ );+}+#[test]fn finale_fires_when_adapter_fails() {let dir = tempfile::tempdir().unwrap();@@ -548,6 +588,8 @@ struct SeedAdapter {quick_key: Option<String>,manages_links: bool,parent_links: Vec<(String, String)>,+ /// 模拟"这一刻读不出关系"(state DB 打不开):parent_links 交 None+ links_unknown: bool,rank: u8,}@@ -585,8 +627,8 @@ impl AgentAdapter for SeedAdapter {fn manages_parent_links(&self) -> bool {self.manages_links}- fn parent_links(&self) -> Vec<(String, String)> {- self.parent_links.clone()+ fn parent_links(&self) -> Option<Vec<(String, String)>> {+ (!self.links_unknown).then(|| self.parent_links.clone())}fn parse_session(&self, _: &SessionFileRef) -> Result<ParsedSession> {if self.fail_parse {@@ -614,11 +656,233 @@ impl AgentAdapter for SeedAdapter {quick_key: self.quick_key.clone(),manages_links: self.manages_links,parent_links: self.parent_links.clone(),+ links_unknown: self.links_unknown,rank: self.rank,})}}+/// 只提供记忆的 adapter:同 (agent, host) 多实例、一个坏一个好的对账测试用+struct MemoryStub {+ root: std::path::PathBuf,+ docs: Vec<MemoryDoc>,+ fail: bool,+}++impl AgentAdapter for MemoryStub {+ fn agent(&self) -> AgentId {+ AgentId::ClaudeCode+ }+ fn list_session_files(&self) -> Result<Vec<SessionFileRef>> {+ Ok(Vec::new())+ }+ fn parse_session(&self, _: &SessionFileRef) -> Result<ParsedSession> {+ bail!("unreachable")+ }+ fn parse_transcript(&self, _: &SessionFileRef) -> Result<ParsedTranscript> {+ bail!("unreachable")+ }+ fn data_roots(&self) -> Vec<std::path::PathBuf> {+ vec![self.root.clone()]+ }+ fn with_custom_root(&self, _: std::path::PathBuf) -> Box<dyn AgentAdapter> {+ unreachable!("not used in scans")+ }+ fn list_memories(&self) -> 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")]+ }+}++fn mem_doc(path: &str, title: &str) -> MemoryDoc {+ MemoryDoc {+ key: format!("claude-code:{path}"),+ agent: AgentId::ClaudeCode,+ host: String::new(),+ scope: MemoryScope::Project,+ project_path: String::new(),+ project_name: String::new(),+ session_key: String::new(),+ path: path.to_string(),+ title: title.to_string(),+ updated_at: 1,+ size_bytes: 4,+ body: "body".to_string(),+ }+}++fn memory_stub(root: &str, docs: Vec<MemoryDoc>, fail: bool) -> Box<dyn AgentAdapter> {+ Box::new(MemoryStub {+ root: std::path::PathBuf::from(root),+ docs,+ fail,+ })+}++/// 同 (agent, host) 的两个实例,一个读得出、一个读不出:好的那个照常对账(新增入库、+/// 消失出库),坏的那个根下的行原样冻结;全部实例都失败才整组不动——原先一个实例失败+/// 整组不写,默认根的记忆会一直停在上次(2026-09-21 review)+#[test]+fn memories_of_a_failing_instance_stay_frozen_while_the_others_reconcile() {+ let dir = tempfile::tempdir().unwrap();+ let store = temp_store(dir.path());+ let titles = |store: &Store| -> Vec<String> {+ store+ .list_memories(&MemoryFilter::default())+ .unwrap()+ .iter()+ .map(|d| d.title.clone())+ .collect()+ };+ // 上一轮两边都好:a1 与 b1 入库+ let adapters = vec![+ memory_stub(+ "/roots/a",+ vec![mem_doc("/roots/a/memory/a1.md", "a1")],+ false,+ ),+ memory_stub(+ "/roots/b",+ vec![mem_doc("/roots/b/memory/b1.md", "b1")],+ false,+ ),+ ];+ run_scan(&adapters, &store, &Recorder::new(), false).unwrap();+ assert_eq!(titles(&store), ["a1", "b1"]);+ // 这一轮 a 换了文件、b 读不出+ let adapters = vec![+ memory_stub(+ "/roots/a",+ vec![mem_doc("/roots/a/memory/a2.md", "a2")],+ false,+ ),+ memory_stub("/roots/b", Vec::new(), true),+ ];+ run_scan(&adapters, &store, &Recorder::new(), false).unwrap();+ assert_eq!(titles(&store), ["a2", "b1"], "a 对账了,b 冻结");+ // 全部实例都失败:整组不动+ let adapters = vec![memory_stub("/roots/a", Vec::new(), true)];+ run_scan(&adapters, &store, &Recorder::new(), false).unwrap();+ assert_eq!(titles(&store), ["a2", "b1"]);+ // b 恢复后按它现在的内容对账+ let adapters = vec![+ memory_stub(+ "/roots/a",+ vec![mem_doc("/roots/a/memory/a2.md", "a2")],+ false,+ ),+ memory_stub("/roots/b", Vec::new(), false),+ ];+ run_scan(&adapters, &store, &Recorder::new(), false).unwrap();+ assert_eq!(titles(&store), ["a2"]);+}++/// 关系这一刻读不出(state DB 打不开)= None:这一家整段跳过,库里的关系原样保留,+/// 而不是拿空快照当"全部解除"整家清空(2026-09-21 review)+#[test]+fn unreadable_parent_links_keep_the_indexed_relationships() {+ let dir = tempfile::tempdir().unwrap();+ let store = temp_store(dir.path());+ let pair = |unknown: bool| -> Vec<Box<dyn AgentAdapter>> {+ let mut child = seed(+ AgentId::Grok,+ "/tmp/grok-child-location",+ "/tmp/grok-child-location/group/child/updates.jsonl",+ "child",+ 20,+ );+ child.manages_links = true;+ child.links_unknown = unknown;+ let mut parent = seed(+ AgentId::Grok,+ "/tmp/grok-parent-location",+ "/tmp/grok-parent-location/group/parent/updates.jsonl",+ "parent",+ 10,+ );+ parent.manages_links = true;+ parent.parent_links = vec![("grok:child".into(), "grok:parent".into())];+ parent.links_unknown = unknown;+ vec![Box::new(child), Box::new(parent)]+ };+ run_scan(&pair(false), &store, &Recorder::new(), true).unwrap();+ assert_eq!(+ store.parent_key_of("grok:child").unwrap(),+ Some("grok:parent".into())+ );+ run_scan(&pair(true), &store, &Recorder::new(), true).unwrap();+ assert_eq!(+ store.parent_key_of("grok:child").unwrap(),+ Some("grok:parent".into()),+ "读不出不等于解除"+ );+}++/// 两层链:先只有 leaf 与 middle 入库(leaf→middle),root 后来才被索引——这一轮算得出+/// leaf→root 就以它为准;原先 asserted 守卫会把先入库的直接边 leaf→middle 保留回去,+/// 链永远钉在中间层(2026-09-21 review)+#[test]+fn nested_chain_reflattens_once_the_root_is_indexed() {+ let dir = tempfile::tempdir().unwrap();+ let store = temp_store(dir.path());+ let leaf = || {+ let mut leaf = seed(+ AgentId::Grok,+ "/tmp/grok-leaf-location",+ "/tmp/grok-leaf-location/group/leaf/updates.jsonl",+ "leaf",+ 30,+ );+ leaf.manages_links = true;+ leaf+ };+ let middle = || {+ let mut middle = seed(+ AgentId::Grok,+ "/tmp/grok-middle-location",+ "/tmp/grok-middle-location/group/middle/updates.jsonl",+ "middle",+ 20,+ );+ middle.manages_links = true;+ middle.parent_links = vec![("grok:leaf".into(), "grok:middle".into())];+ middle+ };+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![Box::new(leaf()), Box::new(middle())];+ run_scan(&adapters, &store, &Recorder::new(), true).unwrap();+ assert_eq!(+ store.parent_key_of("grok:leaf").unwrap(),+ Some("grok:middle".into())+ );++ let mut root = seed(+ AgentId::Grok,+ "/tmp/grok-root-location",+ "/tmp/grok-root-location/group/root/updates.jsonl",+ "root",+ 10,+ );+ root.manages_links = true;+ root.parent_links = vec![("grok:middle".into(), "grok:root".into())];+ let adapters: Vec<Box<dyn AgentAdapter>> =+ vec![Box::new(leaf()), Box::new(middle()), Box::new(root)];+ run_scan(&adapters, &store, &Recorder::new(), true).unwrap();+ assert_eq!(+ store.parent_key_of("grok:middle").unwrap(),+ Some("grok:root".into())+ );+ assert_eq!(+ store.parent_key_of("grok:leaf").unwrap(),+ Some("grok:root".into()),+ "root 入库后 leaf 要重新扁平到 root,而不是钉在 middle"+ );+}+/// SeedAdapter 三件套:根/路径/mtime 齐配的最小会话fn seed(agent: AgentId, root: &str, path: &str, native_id: &str, mtime: i64) -> SeedAdapter {SeedAdapter {@@ -656,6 +920,7 @@ fn seed(agent: AgentId, root: &str, path: &str, native_id: &str, mtime: i64) ->quick_key: None,manages_links: false,parent_links: Vec::new(),+ links_unknown: false,rank: 0,}}@@ -703,6 +968,7 @@ fn tombstoned_session_does_not_resurrect_on_rescan() {quick_key: None,manages_links: false,parent_links: Vec::new(),+ links_unknown: false,rank: 0,})];let rec = Recorder::new();@@ -1124,7 +1390,7 @@ fn codex_guardian_rescan_prunes_stale_index_and_all_mcp_views() {&json!({ "query": "guardianartifact7429", "agents": ["codex"] }),).unwrap();- assert!(searched.contains("No matches"), "{searched}");+ assert!(searched.contains("No session matches"), "{searched}");let listed = tools::invoke(store.as_ref(),diff --git a/crates/wake/assets/icons/brain.svg b/crates/wake/assets/icons/brain.svgnew file mode 100644index 0000000..ecf9181--- /dev/null+++ b/crates/wake/assets/icons/brain.svg@@ -0,0 +1,21 @@+<!-- @license lucide - ISC -->+<svg+ 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="M12 18V5" />+ <path d="M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4" />+ <path d="M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5" />+ <path d="M17.997 5.125a4 4 0 0 1 2.526 5.77" />+ <path d="M18 18a4 4 0 0 0 2-7.464" />+ <path d="M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517" />+ <path d="M6 18a4 4 0 0 1-2-7.464" />+ <path d="M6.003 5.125a4 4 0 0 0-2.526 5.77" />+</svg>diff --git a/crates/wake/assets/icons/messages-square.svg b/crates/wake/assets/icons/messages-square.svgnew file mode 100644index 0000000..1752edd--- /dev/null+++ b/crates/wake/assets/icons/messages-square.svg@@ -0,0 +1,15 @@+<!-- @license lucide - ISC -->+<svg+ 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="M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />+ <path d="M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1" />+</svg>diff --git a/crates/wake/locales/zh-Hans.json b/crates/wake/locales/zh-Hans.jsonindex 8d646ac..31b79b3 100644--- a/crates/wake/locales/zh-Hans.json+++ b/crates/wake/locales/zh-Hans.json@@ -29,6 +29,8 @@"Add to ~/.codex/config.toml": "加到 ~/.codex/config.toml","Agent": "Agent","Agents": "Agent",+ "Agents write these as they work: Claude Code's auto-memory, Codex's memories, ZCode's project memory. They show up here once they exist.": "agent 工作时会自己记下这些:Claude Code 的 auto-memory、Codex 的 memories、ZCode 的项目记忆。有了就会出现在这里。",+ "All Memory": "全部记忆","All Sessions": "全部会话","All your AI agent sessions, in one place.": "所有 AI agent 会话,集中在一处。","Any time": "不限",@@ -73,6 +75,7 @@"Copy image": "拷贝图片","Copy path": "拷贝路径","Copy the SSH command that resumes this session on its host": "拷贝可在其主机上恢复此会话的 SSH 命令",+ "Could not read this memory file: {}": "读不出这份记忆文件:{}","Couldn't add remote host: {}": "无法添加远程主机:{}","Couldn't check for updates. Check your connection and try again.": "检查更新失败。请检查网络后重试。","Couldn't load this session": "无法载入此会话",@@ -150,6 +153,7 @@"MCP server": "MCP 服务器","Main Window": "主窗口","Matches natural language and code, like \"useEffect(\".": "自然语言与代码都能匹配,例如 \"useEffect(\"。",+ "Memory": "记忆","Merge into ~/.cursor/mcp.json": "并入 ~/.cursor/mcp.json","Message count": "消息数","Minimize": "最小化",@@ -168,6 +172,7 @@"No activity": "没有活动","No activity yet": "还没有活动记录","No matching sessions": "没有匹配的会话",+ "No memory files yet": "还没有记忆文件","No newer release is available (latest: {}).": "没有更新的版本(最新:{})。","No prompts": "没有提问","No remote hosts yet. Add one to mirror its sessions into Wake.": "还没有远程主机。添加一台即可把它的会话镜像进 Wake。",@@ -203,9 +208,9 @@"Quit Wake": "退出 Wake","Recycle Bin": "回收站","Redo": "重做",+ "Refresh": "刷新","Refresh Sessions": "刷新会话","Refresh failed: {}": "刷新失败:{}",- "Refresh sessions": "刷新会话","Refresh sessions to see your activity here.": "刷新会话后这里会显示你的活动。","Refreshing {}/{}": "正在刷新 {}/{}","Refreshing…": "正在刷新…",@@ -296,6 +301,7 @@"Unstar": "取消收藏","Updated {}": "更新于 {}","Updates": "更新",+ "User-level": "用户级","Verify in system trash": "请在系统废纸篓中核对","Version {}": "版本 {}","View Update": "查看更新",@@ -317,10 +323,13 @@"esc close": "esc 关闭","open": "打开","reopen": "重新打开",+ "session memory": "会话记忆","the Recycle Bin": "回收站","{} AM": "上午 {} 点","{} PM": "下午 {} 点","{} failed": "{} 个失败",+ "{} memory file": "{} 份记忆文件",+ "{} memory files": "{} 份记忆文件","{} messages": "{} 条消息","{} min ago": "{} 分钟前","{} nested session": "{0} 个子会话",diff --git a/crates/wake/src/assets.rs b/crates/wake/src/assets.rsindex a0bb8de..99a68b1 100644--- a/crates/wake/src/assets.rs+++ b/crates/wake/src/assets.rs@@ -78,6 +78,10 @@ icons!("window-maximize","window-restore","window-close",+ // 底部工具条的页切换:Sessions 用双气泡(单气泡 message-square 留给消息级用途)+ "messages-square",+ // Memory 页(侧栏模式标题与底部工具条入口)+ "brain","star","pin","download",diff --git a/crates/wake/src/i18n.rs b/crates/wake/src/i18n.rsindex 7f07ac6..4fd847e 100644--- a/crates/wake/src/i18n.rs+++ b/crates/wake/src/i18n.rs@@ -621,6 +621,7 @@ mod tests {include_str!("workbench/cleanup/filter.rs"),include_str!("workbench/cleanup/history.rs"),include_str!("workbench/cleanup/rows.rs"),+ include_str!("workbench/memory.rs"),include_str!("settings.rs"),include_str!("main.rs"),include_str!("markdown_links.rs"),diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rsindex e23dc32..31e8535 100644--- a/crates/wake/src/workbench.rs+++ b/crates/wake/src/workbench.rs@@ -16,6 +16,7 @@// ============================================================================use crate::i18n::t;mod cleanup;+mod memory;use std::cell::Cell;use std::collections::{HashMap, HashSet};use std::ops::Range;@@ -872,22 +873,7 @@ impl ListDelegate for SessionsDelegate {if label.is_empty() {return None;}- let theme = cx.theme();-- Some(- h_flex()- .h(px(32.))- .w_full()- .items_center()- .gap(SPACE_SM)- .px(SPACE_MD)- .pt(SPACE_XS)- .text_size(FONT_LABEL)- .font_medium()- .text_color(theme.muted_foreground)- .child(div().flex_shrink_0().child(label))- .child(div().h(px(1.)).flex_1().bg(theme.border.opacity(0.72))),- )+ Some(section_header_row(label, cx.theme()))}// 还有下一页时返回 true。失败后停住,等待用户刷新重建 delegate,@@ -2092,6 +2078,17 @@ mod detail_selection_tests {// ---------------- Workbench ----------------+/// 主区当前显示的页:会话列表 + 阅读面,或两个整页目的地(侧栏底部入口)。一个+/// 字段承担互斥——三个 bool 各自"关掉别人"漏一处就是两页同时亮(2026-09-17+/// /simplify)。Clean up 是叠在会话视图上的模式(侧栏筛选仍然作用于它),另有+/// `cleanup.open`,进入时把这里落回 Sessions+#[derive(Clone, Copy, PartialEq, Eq)]+enum Page {+ Sessions,+ Insights,+ Memory,+}+pub struct Workbench {focus_handle: FocusHandle,store: Arc<Store>,@@ -2164,10 +2161,13 @@ pub struct Workbench {/// 器也不会误清新状态。image_action_feedback_generation: u64,- /// Insights 页(侧栏底部入口):打开时替换中栏+右栏。与其他导航目的地- /// 互斥(侧栏单选模型);数据在 open/refresh 时后台重算,Rc 免深拷贝- insights_open: bool,+ /// 主区当前的页(侧栏单选模型):Insights / Memory 打开时替换中栏+右栏,+ /// 数据在 open/refresh 时后台重算+ page: Page,cleanup: cleanup::CleanupState,+ /// Memory 页的数据与选中态(agent 自己写的记忆文档)+ memory: memory::MemoryState,+ /// Insights 页数据,Rc 免深拷贝insights: Option<Rc<InsightsData>>,insights_loading: bool,insights_range: InsightsRange,@@ -2495,8 +2495,9 @@ impl Workbench {detail_selection_auto_scroll: AutoScroll::default(),detail: None,image_action_feedback_generation: 0,- insights_open: false,+ page: Page::Sessions,cleanup: cleanup::CleanupState::default(),+ memory: memory::MemoryState::default(),insights: None,insights_loading: false,insights_range: InsightsRange::Hour,@@ -2620,9 +2621,9 @@ impl Workbench {self.agent_counts = counts;self.projects = self.store.list_projects(false).unwrap_or_default();self.starred_count = self.store.starred_count().unwrap_or(0);- // Insights 打开着就顺带重算:扫描增量/收藏变更等一切走 refresh 的+ // Insights / Memory 打开着就顺带重算:扫描增量/收藏变更等一切走 refresh 的// 路径都会让页面数据跟上,不设第二条失效通道- self.reload_insights(cx);+ self.reload_page(cx);cx.notify();}@@ -2668,27 +2669,40 @@ impl Workbench {}}- /// 侧栏底部入口。再点一次(或点任意导航行)退回会话列表- fn toggle_insights(&mut self, cx: &mut Context<Self>) {+ /// 底部工具条的页切换(不是开关:再点当前页不退出)。回会话列表不动筛选;去整页+ /// 目的地时清掉三个会话筛选、Memory 的侧栏筛选也从全部开始——互斥单选,点任意+ /// 导航行都退回会话列表(`set_scope`)+ fn show_page(&mut self, page: Page, cx: &mut Context<Self>) {self.leave_cleanup(cx);- if self.insights_open {- self.insights_open = false;+ if self.page == page {cx.notify();return;}- self.insights_open = true;- // 互斥单选:Insights 是独立目的地,退出时落回 All Sessions- self.selected_agent = None;- self.selected_project = None;- self.favorite_only = false;+ self.page = page;+ if page != Page::Sessions {+ self.selected_agent = None;+ self.selected_project = None;+ self.favorite_only = false;+ self.reset_memory_scope();+ }self.refresh(cx);}+ /// 打开着的整页目的地顺带重载(refresh 与扫描终态都走这里);各页自己按住+ /// "扫描中且已有数据"的情形+ fn reload_page(&mut self, cx: &mut Context<Self>) {+ match self.page {+ Page::Sessions => {}+ Page::Insights => self.reload_insights(cx),+ Page::Memory => self.reload_memories(cx),+ }+ }+/// messages 全表分桶几十毫秒量级,走后台;已有数据时静默换新不闪 loading。/// 扫描进行中 Changed 事件每秒都来,有旧数据就先按住——终态 Progress/// 会补最后一次;新任务覆盖 insights_task 即取消旧查询,不堆积读锁竞争fn reload_insights(&mut self, cx: &mut Context<Self>) {- if !self.insights_open {+ if self.page != Page::Insights {return;}if self.scan.scanning && self.insights.is_some() {@@ -3940,9 +3954,9 @@ impl Workbench {self.pending_rescan = false;self.kick_incremental_scan(cx);}- // 扫描期间 reload_insights 被按住(见其注释),终态补最后一次+ // 扫描期间整页目的地的重载被按住(见 reload_insights 注释),终态补最后一次if !self.scan.scanning {- self.reload_insights(cx);+ self.reload_page(cx);}cx.notify();note@@ -4425,7 +4439,7 @@ impl Workbench {self.selected_agent = agent;self.selected_project = project;self.favorite_only = favorite;- self.insights_open = false;+ self.page = Page::Sessions;self.refresh(cx);}@@ -4448,6 +4462,11 @@ impl Workbench {.flatten().is_some_and(|session| !session.archived){+ // 阅读面只在会话页才画:从 Memory / Insights(或清理模式)里 ⌘K 打开归档命中,+ // 得先落回会话页,否则 detail 设了却什么都不显示(2026-09-21 review)+ self.leave_cleanup(cx);+ self.page = Page::Sessions;+ cx.notify();return;}self.show_all_sessions(window, cx);@@ -4970,7 +4989,7 @@ impl Workbench {let all_active = self.selected_agent.is_none()&& self.selected_project.is_none()&& !self.favorite_only- && !self.insights_open+ && self.page == Page::Sessions&& !self.cleanup.open;// 常态沉默,仅刷新中/监听失效时出现;None 时状态栏整行不渲染。// 文案在此按 scan 现算,不另存字段——存下来就会有第二个写入点要维护@@ -5060,9 +5079,70 @@ impl Workbench {.text_size(FONT_HEADING).font_semibold().text_color(theme.foreground)- .child("Wake"),+ // Memory 页标题换成 Memory:侧栏顶上就说明现在管的是什么,+ // 不另加模式标题行(用户 2026-09-21)+ .child(if self.page == Page::Memory {+ t("Memory")+ } else {+ "Wake"+ }),),)+ // 导航按页切换:Memory 页是记忆的导航(All Memory / Agents / Projects,按记忆+ // 计数),其余是会话的(搜索框 + All Sessions / Starred + Agents / Projects)+ .child(match self.page {+ Page::Memory => self.render_memory_nav(cx),+ _ => self.render_sessions_nav(all_active, cx),+ })+ // 底部工具条:次要操作(数据源、刷新)与扫描状态同处一区,与上方+ // 导航行只用一条 border 分隔。按钮透明底、hover 才出色,不跟导航+ // 行的选中态抢注意力;图标-only 元素改 text_color 不丢字号+ .child(+ v_flex()+ .flex_shrink_0()+ .border_t_1()+ .border_color(theme.sidebar_border)+ .when_some(status, |this, status| {+ this.child(+ h_flex()+ .px(SPACE_XL)+ .pt(SPACE_MD)+ .text_size(FONT_LABEL)+ .child(status),+ )+ })+ // 两端分置的图标条(Zed 状态栏 / Xcode 导航条那种,不带盒子):左端+ // 页切换 Sessions / Memory / Insights,当前页那颗用侧栏选中色做底;+ // 右端只有 Settings。Refresh 不在这里——它住在各页页头右端(全库重扫,+ // 三页同一条路;用户 2026-09-21 三轮反馈:六个一样的图标挤一排不行、+ // 刷新不该放这里、带边框的分段盒子也不行)+ .child(+ h_flex()+ .h(SIDEBAR_FOOTER_ROW_HEIGHT)+ .pl(FOOTER_LEAD_INSET)+ .pr(SIDEBAR_EDGE)+ .items_center()+ .justify_between()+ .child(self.render_page_switch(cx))+ .child(h_flex().gap(px(2.)).child(sidebar_tool_btn(+ "settings",+ t("Settings"),+ false,+ "icons/settings.svg",+ cx.listener(|this, _, _window, cx| this.open_settings(cx)),+ cx,+ ))),+ ),+ )+ }++ /// 会话导航(Insights 页也画它——点任何一行都回会话列表):搜索框(搜的是会话,+ /// ⌘K 同一条路)、All Sessions / Starred 两行,再接 Agents / Projects 两组+ fn render_sessions_nav(&self, all_active: bool, cx: &Context<Self>) -> AnyElement {+ let theme = cx.theme();+ v_flex()+ .flex_1()+ .min_h_0().child(div().flex_shrink_0().px(SIDEBAR_EDGE).pb(SPACE_MD).child(h_flex().gap(SPACE_SM).child(@@ -5079,8 +5159,8 @@ impl Workbench {this.toggle_search(&ToggleSearch, window, cx)})).child(icon("icons/search.svg").with_size(px(13.)).flex_shrink_0())- // flex_1 + min_w_0 + truncate:空间不足时压这里,- // 绝不把右侧刷新按钮挤出侧栏+ // flex_1 + min_w_0 + truncate:空间不足时压文案,右侧的 ⌘K+ // 提示不被挤出侧栏.child(div().flex_1()@@ -5135,169 +5215,168 @@ impl Workbench {cx,)),)- .child(- v_flex()- .id("sidebar-scroll")- .flex_1()- .min_h_0()- .overflow_y_scroll()- .px(SIDEBAR_EDGE)- .pt(SPACE_XS)- .pb(SPACE_LG)- .gap(SPACE_XS)- .child(group_header(- "agents-header",- t("Agents"),- self.agents_collapsed,- cx.listener(|this, _, _window, cx| {- this.agents_collapsed = !this.agents_collapsed;- cx.notify();- }),- cx,- ))- .when(!self.agents_collapsed, |this| {- this.children(self.agent_counts.iter().map(|(agent, count)| {- let agent = *agent;- sidebar_row(- agent.as_str(),- RowLead::Brand(agent.brand_icon(theme.mode.is_dark())),- agent.display_name(),- Some(*count),- self.selected_agent == Some(agent) && !self.cleanup.open,- RowLevel::Sub,- cx.listener(move |this, _, _window, cx| {- let next = if this.selected_agent == Some(agent)- && !this.cleanup.open- {- None- } else {- Some(agent)- };- this.set_scope(next, None, false, cx);- }),- cx,- )- }))- })- .child(group_header(- "projects-header",- t("Projects"),- self.projects_collapsed,- cx.listener(|this, _, _window, cx| {- this.projects_collapsed = !this.projects_collapsed;- cx.notify();+ .child(self.sidebar_groups(+ "sidebar-scroll",+ self.agent_counts.iter().map(|(agent, count)| {+ (+ *agent,+ *count,+ self.selected_agent == Some(*agent) && !self.cleanup.open,+ )+ }),+ self.projects.iter().map(|p| {+ (+ p.path.clone(),+ SharedString::from(p.name.clone()),+ p.session_count,+ self.selected_project.as_deref() == Some(p.path.as_str())+ && !self.cleanup.open,+ )+ }),+ |this, next, cx| this.set_scope(next, None, false, cx),+ |this, next, cx| this.set_scope(None, next, false, cx),+ cx,+ ))+ .into_any_element()+ }++ /// 侧栏的 Agents / Projects 两组(会话导航与 Memory 导航同一套行组件、同一个单选+ /// 模型,折叠状态两页共用)。每行给 (身份, 计数, 是否当前);点击回调收到切换后的+ /// 目标——点当前项就是 None(回全部)+ fn sidebar_groups(+ &self,+ id: &'static str,+ agents: impl IntoIterator<Item = (AgentId, i64, bool)>,+ projects: impl IntoIterator<Item = (String, SharedString, i64, bool)>,+ on_agent: fn(&mut Self, Option<AgentId>, &mut Context<Self>),+ on_project: fn(&mut Self, Option<String>, &mut Context<Self>),+ cx: &Context<Self>,+ ) -> Stateful<Div> {+ let dark = cx.theme().mode.is_dark();+ v_flex()+ .id(id)+ .flex_1()+ .min_h_0()+ .overflow_y_scroll()+ .px(SIDEBAR_EDGE)+ .pt(SPACE_XS)+ .pb(SPACE_LG)+ .gap(SPACE_XS)+ .child(group_header(+ "agents-header",+ t("Agents"),+ self.agents_collapsed,+ cx.listener(|this, _, _window, cx| {+ this.agents_collapsed = !this.agents_collapsed;+ cx.notify();+ }),+ cx,+ ))+ .when(!self.agents_collapsed, |this| {+ this.children(agents.into_iter().map(|(agent, count, active)| {+ sidebar_row(+ agent.as_str(),+ RowLead::Brand(agent.brand_icon(dark)),+ agent.display_name(),+ Some(count),+ active,+ RowLevel::Sub,+ cx.listener(move |this, _, _window, cx| {+ on_agent(this, (!active).then_some(agent), cx)}),cx,- ))- .when(!self.projects_collapsed, |this| {- this.children(self.projects.iter().enumerate().map(|(ix, p)| {- let path = p.path.clone();- sidebar_row(- ("proj", ix),- RowLead::Icon(icon("icons/folder.svg")),- p.name.clone(),- Some(p.session_count),- self.selected_project.as_deref() == Some(p.path.as_str())- && !self.cleanup.open,- RowLevel::Sub,- cx.listener(move |this, _, _window, cx| {- let next = if !this.cleanup.open- && this.selected_project.as_deref() == Some(path.as_str())- {- None- } else {- Some(path.clone())- };- this.set_scope(None, next, false, cx);- }),- cx,- )- }))- }),- )- // 底部工具条:次要操作(数据源、刷新)与扫描状态同处一区,与上方- // 导航行只用一条 border 分隔。按钮透明底、hover 才出色,不跟导航- // 行的选中态抢注意力;图标-only 元素改 text_color 不丢字号- .child(- v_flex()- .flex_shrink_0()- .border_t_1()- .border_color(theme.sidebar_border)- .when_some(status, |this, status| {- this.child(- h_flex()- .px(SPACE_XL)- .pt(SPACE_MD)- .text_size(FONT_LABEL)- .child(status),+ )+ }))+ })+ .child(group_header(+ "projects-header",+ t("Projects"),+ self.projects_collapsed,+ cx.listener(|this, _, _window, cx| {+ this.projects_collapsed = !this.projects_collapsed;+ cx.notify();+ }),+ cx,+ ))+ .when(!self.projects_collapsed, |this| {+ this.children(projects.into_iter().enumerate().map(+ |(ix, (path, label, count, active))| {+ sidebar_row(+ ("proj", ix),+ RowLead::Icon(icon("icons/folder.svg")),+ label,+ Some(count),+ active,+ RowLevel::Sub,+ cx.listener(move |this, _, _window, cx| {+ on_project(this, (!active).then(|| path.clone()), cx)+ }),+ cx,)- })- .child(- h_flex()- .h(SIDEBAR_FOOTER_ROW_HEIGHT)- .px(SIDEBAR_EDGE)- .items_center()- .justify_end()- .gap(SPACE_XS)- .child(sidebar_tool_btn(- "insights",- t("Insights"),- true,- // 页面打开时图标点亮 primary(显式设色后不被- // hover 的容器 text_color 覆盖)- {- let mut ic = icon("icons/chart-column.svg").with_size(px(14.));- if self.insights_open {- ic = ic.text_color(theme.primary);- }- ic.into_any_element()- },- cx.listener(|this, _, _window, cx| this.toggle_insights(cx)),- cx,- ))- .child(sidebar_tool_btn(- "cleanup",- t("Clean Up Sessions"),- true,- icon("icons/brush-cleaning.svg")- .with_size(px(14.))- .text_color(if self.cleanup.open {- theme.primary- } else {- theme.muted_foreground- })- .into_any_element(),- cx.listener(|this, _, window, cx| this.toggle_cleanup(window, cx)),- cx,- ))- .child(sidebar_tool_btn(- "settings",- t("Settings"),- true,- icon("icons/settings.svg")- .with_size(px(14.))- .into_any_element(),- cx.listener(|this, _, _window, cx| this.open_settings(cx)),- cx,- ))- .child(sidebar_tool_btn(- "refresh",- t("Refresh sessions"),- !self.scan.scanning,- if self.scan.scanning {- Spinner::new().small().into_any_element()- } else {- icon("icons/refresh-cw.svg")- .with_size(px(14.))- .into_any_element()- },- cx.listener(|this, _, window, cx| {- this.refresh_sessions(window, cx)- }),- cx,- )),- ),+ },+ ))+ })+ }++ /// 侧栏底部左端的一组:三颗页切换 + Clean up,同尺寸图标钮,当前页那颗 `active`+ /// (侧栏选中色圆角底)。Sessions 也是一颗——否则从 Memory 回来只能"再点一次+ /// Memory"。Clean up 打开时三颗页都不亮、它自己亮(它是叠在会话视图上的模式,+ /// 不是页;用户 2026-09-21 定它也靠左,右端只留 Settings)+ fn render_page_switch(&self, cx: &Context<Self>) -> AnyElement {+ let current = (!self.cleanup.open).then_some(self.page);+ let button = |id: &'static str, tooltip: &'static str, glyph: &'static str, page: Page| {+ sidebar_tool_btn(+ id,+ tooltip,+ current == Some(page),+ glyph,+ cx.listener(move |this, _, _window, cx| this.show_page(page, cx)),+ cx,)+ };+ h_flex()+ .gap(px(2.))+ .child(button(+ "page-sessions",+ t("Sessions"),+ "icons/messages-square.svg",+ Page::Sessions,+ ))+ .child(button(+ "page-memory",+ t("Memory"),+ "icons/brain.svg",+ Page::Memory,+ ))+ .child(button(+ "page-insights",+ t("Insights"),+ "icons/chart-column.svg",+ Page::Insights,+ ))+ .child(sidebar_tool_btn(+ "cleanup",+ t("Clean Up Sessions"),+ self.cleanup.open,+ "icons/brush-cleaning.svg",+ cx.listener(|this, _, window, cx| this.toggle_cleanup(window, cx)),+ cx,+ ))+ .into_any_element()+ }++ /// 各页页头右端的 Refresh(⌘R 同一条路,全库重扫、不分页——Memory 与 Insights 的+ /// 数据都是扫描收尾派生的):扫描进行中显示转圈并禁用+ fn refresh_button(&self, 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)+ .tooltip(t("Refresh"))+ .on_click(cx.listener(|this, _, window, cx| this.refresh_sessions(window, cx)))+ .into_any_element()}fn render_session_list(&self, cx: &Context<Self>) -> impl IntoElement {@@ -5390,7 +5469,13 @@ impl Workbench {self.context_title(),shown_label,SPACE_LG,- Some(sort_menu.into_any_element()),+ Some(+ h_flex()+ .gap(SPACE_XS)+ .child(self.refresh_button(cx))+ .child(sort_menu)+ .into_any_element(),+ ),cx,)).child(if shown == 0 {@@ -5992,7 +6077,7 @@ impl Workbench {t("Insights"),subtitle,SPACE_XXL,- None,+ Some(self.refresh_button(cx)),cx,)).child(body)@@ -6311,7 +6396,6 @@ impl Workbench {}).disabled(detail.source_path.as_deref().is_none_or(str::is_empty)).on_click(cx.listener(|this, _, _, cx| this.copy_session_path(cx)));- let detail_title_tooltip: SharedString = meta.title.clone().into();let session_id = meta.id.clone();let export_entity = cx.entity();let reveal_entity = export_entity.clone();@@ -6410,446 +6494,341 @@ impl Workbench {});let branch: Option<SharedString> =visible_git_branch(meta.git_branch.as_deref()).map(|branch| branch.to_string().into());- let project_badge: AnyElement = {- let badge = badge(- meta.project_name.clone(),- theme.muted,- theme.muted_foreground,- );- if meta.project_path.is_empty() {- div().child(badge).into_any_element()- } else {- let project_path = meta.project_path.clone();- div()- .id("detail-project")- .cursor_pointer()- .tooltip(|window, cx| {- gpui_component::tooltip::Tooltip::new(show_in_fm()).build(window, cx)- })- .on_click(move |_, _, _| terminal::open_in_file_manager(&project_path))- .child(badge)- .into_any_element()- }- };- v_flex()- .flex_1()- .min_w_0()- .h_full()- .bg(theme.background)- .child(- v_flex()- .id("detail-header")- .flex_shrink_0()- .window_control_area(WindowControlArea::Drag)- .px(SPACE_XXL)- .pb(SPACE_SM)- .border_b_1()- .border_color(theme.border)+ let project_badge = project_badge(+ "detail-project",+ &meta.project_path,+ meta.project_name.clone(),+ theme,+ );+ let mut lead: Vec<AnyElement> = Vec::new();+ if self.cleanup.open {+ lead.push(+ Button::new("cleanup-back")+ .ghost()+ .h(px(28.))+ .px(SPACE_SM)+ .text_size(FONT_CAPTION)+ .rounded(RADIUS_BUTTON)+ .icon(icon("icons/chevron-left.svg").with_size(px(15.)))+ .label(t("Back"))+ .tooltip(t("Back to cleanup list"))+ .on_click(cx.listener(|this, _, window, cx| {+ this.close_cleanup_preview(window, cx);+ }))+ .into_any_element(),+ );+ }+ lead.push(+ img(meta.agent.brand_icon(theme.mode.is_dark()))+ .size(px(15.))+ .flex_shrink_0()+ .into_any_element(),+ );+ lead.push(+ div()+ .flex_shrink_0()+ .child(meta.agent.display_name())+ .into_any_element(),+ );+ lead.push(project_badge);+ if let Some(branch) = branch {+ lead.push(+ h_flex()+ .min_w_0()+ .gap(SPACE_XS).child(- h_flex()- .w_full()- .h(WINDOW_TITLEBAR_HEIGHT)- .items_center()- .justify_between()- .gap(SPACE_MD)- .child(- h_flex()- .flex_1()- .min_w_0()- .gap(SPACE_SM)- .items_center()- .text_size(FONT_LABEL)- .text_color(theme.muted_foreground)- .when(self.cleanup.open, |row| row.child(- Button::new("cleanup-back")- .ghost()- .h(px(28.))- .px(SPACE_SM)- .text_size(FONT_CAPTION)- .rounded(RADIUS_BUTTON)- .icon(icon("icons/chevron-left.svg").with_size(px(15.)))- .label(t("Back"))- .tooltip(t("Back to cleanup list"))- .on_click(cx.listener(|this, _, window, cx| {- this.close_cleanup_preview(window, cx);- }))- ))- .child(img(meta.agent.brand_icon(theme.mode.is_dark())).size(px(15.)).flex_shrink_0())- .child(div().flex_shrink_0().child(meta.agent.display_name()))- .child(project_badge)- .when_some(branch, |this, branch| {- this.child(- h_flex()- .min_w_0()- .gap(SPACE_XS)- .child(icon("icons/git-branch.svg").with_size(px(11.)).flex_shrink_0())- .child(div().min_w_0().truncate().child(branch)),- )- }),- )- .child(- h_flex()- .flex_shrink_0()- .gap(SPACE_XS)- .child(if terminal::resume_targets(meta).is_empty() {- // 没有 resume 形制的 agent(OpenClaw 的 TUI 只按 session- // key 开会话):不画 Open In,别给一组点了才报错的死按钮- div().into_any_element()- } else if let [terminal::ResumeTarget::CopySshCommand] =- terminal::resume_targets(meta).as_slice()- {- // 远程会话(阶段 1 只有 Copy SSH command):单段控件用- // 现成 Button,无 chevron 无记忆(split 按钮手搓只因它- // 要双段共壳)。本地会话即便只剩一个终端也走 split- // 按钮,品牌图标与 per-agent 记忆不丢- crate::settings::settings_button(- Button::new("open-in-single"),- cx,- )- .h(px(28.))- .icon(icon("icons/terminal.svg").with_size(px(13.)))- .label(t("Copy SSH command"))- .tooltip(- t("Copy the SSH command that resumes this session on its host"),- )- .on_click(cx.listener(|this, _, window, cx| {+ icon("icons/git-branch.svg")+ .with_size(px(11.))+ .flex_shrink_0(),+ )+ .child(div().min_w_0().truncate().child(branch))+ .into_any_element(),+ );+ }+ let open_in: AnyElement = if terminal::resume_targets(meta).is_empty() {+ // 没有 resume 形制的 agent(OpenClaw 的 TUI 只按 session+ // key 开会话):不画 Open In,别给一组点了才报错的死按钮+ div().into_any_element()+ } else if let [terminal::ResumeTarget::CopySshCommand] =+ terminal::resume_targets(meta).as_slice()+ {+ // 远程会话(阶段 1 只有 Copy SSH command):单段控件用+ // 现成 Button,无 chevron 无记忆(split 按钮手搓只因它+ // 要双段共壳)。本地会话即便只剩一个终端也走 split+ // 按钮,品牌图标与 per-agent 记忆不丢+ crate::settings::settings_button(Button::new("open-in-single"), cx)+ .h(px(28.))+ .icon(icon("icons/terminal.svg").with_size(px(13.)))+ .label(t("Copy SSH command"))+ .tooltip(t(+ "Copy the SSH command that resumes this session on its host",+ ))+ .on_click(cx.listener(|this, _, window, cx| {+ this.do_resume(terminal::ResumeTarget::CopySshCommand, false, window, cx);+ }))+ .into_any_element()+ } else {+ // Open In split 按钮(Codex/kooky 风):左段 = 上次+ // 目标的应用图标,点击直开;右段 chevron 展开列表。+ // 目标列表按 agent 过滤(Kooky 深链不认 dsh);+ // 偏好目标不在列表时(如 dsh 会话 + 偏好 Kooky)回退首项+ let terms: Vec<terminal::TerminalApp> = terminal::resume_targets(meta)+ .into_iter()+ .filter_map(|t| match t {+ terminal::ResumeTarget::App(app) => Some(app),+ _ => None,+ })+ .collect();+ let current = self.open_in_target(meta.agent, &terms);+ let current_icon = current.and_then(|t| self.terminal_icons.get(t.id()).cloned());+ let term_items: Vec<(terminal::TerminalApp, Option<PathBuf>)> = terms+ .iter()+ .map(|t| (*t, self.terminal_icons.get(t.id()).cloned()))+ .collect();+ let menu_entity = cx.entity();+ // 无常显分隔线,hover 分段高亮暗示两段(Codex 同款);+ // 右段 Button 用 custom variant 与左段 hover 完全一致+ h_flex()+ .h(px(28.))+ .rounded(RADIUS_BUTTON)+ .border_1()+ .border_color(theme.border)+ .bg(theme.secondary)+ .overflow_hidden()+ .child(+ div()+ .id("open-in-main")+ .h_full()+ .px(px(7.))+ .flex()+ .items_center()+ .cursor_pointer()+ .hover(|s| s.bg(theme.secondary_hover))+ .active(|s| s.bg(theme.secondary_active))+ .child(open_in_icon(+ current,+ current_icon.as_ref(),+ icon("icons/terminal.svg")+ .with_size(px(13.))+ .text_color(theme.secondary_foreground),+ ))+ .tooltip({+ let label: SharedString = match current {+ Some(t) => {+ crate::tf!("Open this session in {}", t.display_name()).into()+ }+ None => t("Open this session").into(),+ };+ move |window, cx| {+ gpui_component::tooltip::Tooltip::new(label.clone())+ .build(window, cx)+ }+ })+ .on_click(cx.listener(move |this, _, window, cx| {+ if let Some(term) = current {+ this.do_resume(+ terminal::ResumeTarget::App(term),+ false,+ window,+ cx,+ );+ } else {+ // 空列表在 macOS 不可能(Terminal.app 恒在),+ // Windows/Linux 上 PATH 被启动器改写时会发生+ // ——静默无操作是死按钮,至少说一声为什么+ window.push_notification(+ Notification::warning(t(+ "No terminal application found on PATH",+ )),+ cx,+ );+ }+ })),+ )+ .child(div().w(px(1.)).h_full().flex_shrink_0().bg(theme.border))+ .child(+ Button::new("open-in-more")+ .custom(+ ButtonCustomVariant::new(cx)+ .foreground(theme.muted_foreground)+ .hover(theme.secondary_hover)+ .active(theme.secondary_active),+ )+ .rounded(px(0.))+ .h(px(26.))+ .w(px(22.))+ .icon(icon("icons/chevron-down.svg").with_size(px(12.)))+ .tooltip(t("Open this session in…"))+ .dropdown_menu(move |menu, _, _| {+ let mut menu = menu.min_w(px(170.));+ for (term, icon_path) in term_items.clone() {+ let entity = menu_entity.clone();+ menu = menu.item(+ PopupMenuItem::element(move |_, _| {+ h_flex()+ .gap(SPACE_SM)+ .items_center()+ .child(open_in_icon(+ Some(term),+ icon_path.as_ref(),+ icon("icons/terminal.svg").with_size(px(15.)),+ ))+ .child(term.display_name())+ })+ .on_click(+ move |_, window, cx| {+ entity.update(cx, |this, cx| {this.do_resume(- terminal::ResumeTarget::CopySshCommand,- false,+ terminal::ResumeTarget::App(term),+ true,window,cx,);- }))- .into_any_element()- } else {- // Open In split 按钮(Codex/kooky 风):左段 = 上次- // 目标的应用图标,点击直开;右段 chevron 展开列表。- // 目标列表按 agent 过滤(Kooky 深链不认 dsh);- // 偏好目标不在列表时(如 dsh 会话 + 偏好 Kooky)回退首项- let terms: Vec<terminal::TerminalApp> =- terminal::resume_targets(meta)- .into_iter()- .filter_map(|t| match t {- terminal::ResumeTarget::App(app) => Some(app),- _ => None,- })- .collect();- let current = self.open_in_target(meta.agent, &terms);- let current_icon = current- .and_then(|t| self.terminal_icons.get(t.id()).cloned());- let term_items: Vec<(terminal::TerminalApp, Option<PathBuf>)> =- terms- .iter()- .map(|t| {- (*t, self.terminal_icons.get(t.id()).cloned())- })- .collect();- let menu_entity = cx.entity();- // 无常显分隔线,hover 分段高亮暗示两段(Codex 同款);- // 右段 Button 用 custom variant 与左段 hover 完全一致- h_flex()- .h(px(28.))- .rounded(RADIUS_BUTTON)- .border_1()- .border_color(theme.border)- .bg(theme.secondary)- .overflow_hidden()- .child(- div()- .id("open-in-main")- .h_full()- .px(px(7.))- .flex()- .items_center()- .cursor_pointer()- .hover(|s| s.bg(theme.secondary_hover))- .active(|s| s.bg(theme.secondary_active))- .child(open_in_icon(- current,- current_icon.as_ref(),- icon("icons/terminal.svg")- .with_size(px(13.))- .text_color(theme.secondary_foreground),- ))- .tooltip({- let label: SharedString = match current {- Some(t) => crate::tf!("Open this session in {}", t.display_name()).into(),- None => t("Open this session").into(),- };- move |window, cx| {- gpui_component::tooltip::Tooltip::new(label.clone()).build(window, cx)- }- })- .on_click(cx.listener(move |this, _, window, cx| {- if let Some(term) = current {- this.do_resume(- terminal::ResumeTarget::App(term),- false,- window,- cx,- );- } else {- // 空列表在 macOS 不可能(Terminal.app 恒在),- // Windows/Linux 上 PATH 被启动器改写时会发生- // ——静默无操作是死按钮,至少说一声为什么- window.push_notification(- Notification::warning(- t("No terminal application found on PATH"),- ),- cx,- );- }- })),- )- .child(- div()- .w(px(1.))- .h_full()- .flex_shrink_0()- .bg(theme.border),- )- .child(- Button::new("open-in-more")- .custom(- ButtonCustomVariant::new(cx)- .foreground(theme.muted_foreground)- .hover(theme.secondary_hover)- .active(theme.secondary_active),- )- .rounded(px(0.))- .h(px(26.))- .w(px(22.))- .icon(- icon("icons/chevron-down.svg")- .with_size(px(12.)),- )- .tooltip(t("Open this session in…"))- .dropdown_menu(move |menu, _, _| {- let mut menu = menu.min_w(px(170.));- for (term, icon_path) in term_items.clone() {- let entity = menu_entity.clone();- menu = menu.item(- PopupMenuItem::element(move |_, _| {- h_flex()- .gap(SPACE_SM)- .items_center()- .child(open_in_icon(- Some(term),- icon_path.as_ref(),- icon("icons/terminal.svg")- .with_size(px(15.)),- ))- .child(term.display_name())- })- .on_click(move |_, window, cx| {- entity.update(cx, |this, cx| {- this.do_resume(- terminal::ResumeTarget::App(term),- true,- window,- cx,- );- });- }),- );- }- menu- })- .anchor(Anchor::TopRight),- )- .into_any_element()- })- .child(tool_btn(- "fav",- "icons/star.svg",- "icons/star-filled.svg",- rgb(crate::theme::STAR_YELLOW).into(),- if meta.favorite {- t("Unstar")- } else {- t("Star")+ });},- meta.favorite,- cx.listener(|this, _, window, cx| {- this.toggle_favorite(window, cx)- }),- ))- .child(tool_btn(- "pin",- "icons/pin.svg",- "icons/pin-filled.svg",- theme.primary,- if meta.pinned {- t("Unpin")- } else {- t("Pin")- },- meta.pinned,- cx.listener(|this, _, window, cx| {- this.toggle_pinned(window, cx)- }),- ))- .child(copy_path)- .child(more_menu),- ),- )+ ),+ );+ }+ menu+ })+ .anchor(Anchor::TopRight),+ )+ .into_any_element()+ };+ let actions: Vec<AnyElement> = vec![+ open_in,+ tool_btn(+ "fav",+ "icons/star.svg",+ "icons/star-filled.svg",+ rgb(crate::theme::STAR_YELLOW).into(),+ if meta.favorite {+ t("Unstar")+ } else {+ t("Star")+ },+ meta.favorite,+ cx.listener(|this, _, window, cx| this.toggle_favorite(window, cx)),+ )+ .into_any_element(),+ tool_btn(+ "pin",+ "icons/pin.svg",+ "icons/pin-filled.svg",+ theme.primary,+ if meta.pinned { t("Unpin") } else { t("Pin") },+ meta.pinned,+ cx.listener(|this, _, window, cx| this.toggle_pinned(window, cx)),+ )+ .into_any_element(),+ copy_path.into_any_element(),+ more_menu.into_any_element(),+ ];+ let mut meta_rows: Vec<AnyElement> = vec![+ h_flex()+ .w_full()+ .min_w_0()+ .gap(SPACE_MD)+ .items_center()+ .when_some(meta.model.clone(), |this, model| {+ this.child(outline_badge(+ model,+ rgb(crate::theme::MODEL_BADGE_BG).into(),+ ))+ })+ .when_some(+ meta.source.clone().filter(|s| !s.is_empty()),+ |this, source| {+ let color = if source == "opencode2" {+ theme.primary+ } else {+ theme.success+ };+ this.child(outline_badge(source, color))+ },+ )+ .when(!meta.host.is_empty(), |this| {+ // 详情页保持 model/source 同排的描边形态,色相与列表行的 host+ // 胶囊一致(primary);muted 描边用户否决 2026-09-03+ this.child(outline_badge(format!("@{}", meta.host), theme.primary))+ })+ .when(has_detail_facts, |this| {+ this.child(div().flex_1().min_w_0().truncate().child(detail_fact_line))+ })+ .into_any_element(),+ h_flex()+ .min_w_0()+ .gap(px(6.))+ .child(icon("icons/folder.svg").with_size(px(12.)).flex_shrink_0())+ .child(div().min_w_0().truncate().child(detail_path))+ .into_any_element(),+ ];+ if self.cleanup.open {+ meta_rows.push(self.render_cleanup_detail_facts(cx));+ }+ if created_time.is_some() || updated_time.is_some() {+ meta_rows.push(+ h_flex()+ .w_full()+ .min_w_0()+ .gap(px(6.))+ .items_center().child(- div()- .w_full()- .min_h(WINDOW_TITLEBAR_HEIGHT)- .min_w_0()- .py(SPACE_SM)- .flex()- .items_center()- .child(- div()- .id("detail-title")- .w_full()- .min_w_0()- .whitespace_normal()- .text_size(FONT_TITLE)- .line_height(relative(1.15))- .font_semibold()- .child(meta.title.clone())- .tooltip(move |window, cx| {- gpui_component::tooltip::Tooltip::new(- detail_title_tooltip.clone(),- )- .build(window, cx)- }),- ),+ icon("icons/calendar.svg")+ .with_size(px(12.))+ .flex_shrink_0(),).child(- v_flex()- .w_full()+ h_flex().min_w_0()- .pt(SPACE_SM)- .gap(SPACE_SM)- .text_size(FONT_LABEL)- .text_color(theme.muted_foreground)- .child(- h_flex()- .w_full()- .min_w_0()- .gap(SPACE_MD)- .items_center()- .when_some(meta.model.clone(), |this, model| {- this.child(outline_badge(- model,- rgb(crate::theme::MODEL_BADGE_BG).into(),- ))- })- .when_some(- meta.source.clone().filter(|s| !s.is_empty()),- |this, source| {- let color = if source == "opencode2" {- theme.primary- } else {- theme.success- };- this.child(outline_badge(source, color))- },- )- .when(!meta.host.is_empty(), |this| {- // 详情页保持 model/source 同排的描边形态,色相- // 与列表行的 host 胶囊一致(primary);muted 描边- // 用户否决 2026-09-03- this.child(outline_badge(- format!("@{}", meta.host),- theme.primary,- ))- })- .when(has_detail_facts, |this| {- this.child(- div()- .flex_1()- .min_w_0()- .truncate()- .child(detail_fact_line),- )- }),- )- .child(- h_flex()- .min_w_0()- .gap(px(6.))- .child(- icon("icons/folder.svg")- .with_size(px(12.))- .flex_shrink_0(),- )- .child(div().min_w_0().truncate().child(detail_path)),- )- .when(self.cleanup.open, |this| this.child(self.render_cleanup_detail_facts(cx)))- .when(created_time.is_some() || updated_time.is_some(), |this| {- this.child(- h_flex()- .w_full()+ .gap(SPACE_MD)+ .when_some(created_time.clone(), |row, (created, tooltip)| {+ row.child(+ div()+ .id("detail-created-time").min_w_0()- .gap(px(6.))- .items_center()- .child(- icon("icons/calendar.svg")- .with_size(px(12.))- .flex_shrink_0(),- )- .child(- h_flex()- .min_w_0()- .gap(SPACE_MD)- .when_some(- created_time.clone(),- |row, (created, tooltip)| {- row.child(- div()- .id("detail-created-time")- .min_w_0()- .truncate()- .child(created)- .tooltip(move |window, cx| {- gpui_component::tooltip::Tooltip::new(- tooltip.clone(),- )- .build(window, cx)- }),- )- },- )- .when(- created_time.is_some()- && updated_time.is_some(),- |row| {- row.child(- div()- .flex_shrink_0()- .text_color(theme.border)- .child("·"),- )- },- )- .when_some(- updated_time.clone(),- |row, (updated, tooltip)| {- row.child(- div()- .id("detail-updated-time")- .flex_shrink_0()- .child(updated)- .tooltip(move |window, cx| {- gpui_component::tooltip::Tooltip::new(- tooltip.clone(),- )- .build(window, cx)- }),- )- },- ),- ),+ .truncate()+ .child(created)+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(tooltip.clone())+ .build(window, cx)+ }),+ )+ })+ .when(created_time.is_some() && updated_time.is_some(), |row| {+ row.child(div().flex_shrink_0().text_color(theme.border).child("·"))+ })+ .when_some(updated_time.clone(), |row, (updated, tooltip)| {+ row.child(+ div()+ .id("detail-updated-time")+ .flex_shrink_0()+ .child(updated)+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(tooltip.clone())+ .build(window, cx)+ }),)}),- ),- )+ )+ .into_any_element(),+ );+ }++ v_flex()+ .flex_1()+ .min_w_0()+ .h_full()+ .bg(theme.background)+ .child(detail_header_frame(+ "detail-header",+ lead,+ actions,+ meta.title.clone().into(),+ meta_rows,+ theme,+ )).child(if detail.loading {h_flex().flex_1()@@ -8011,7 +7990,8 @@ fn message_content(markdown_body(format!("dmsg-{seq}-part-{part}").into(),segment,- session,+ &session.host,+ &session.project_path,base,paragraph_gap,dark,@@ -8188,10 +8168,13 @@ fn centered_pill(text: impl Into<SharedString>, cx: &App) -> Div {/// 对话正文共用的 Markdown 视图。表格、引用块与分隔线由组件原生解析;/// Wake 覆写样式、代码操作区,并按会话所属主机处理 macOS 正文链接。+/// Markdown 正文(消息与记忆文档共用);`host` / `project_path` 只用来解析正文里的+/// 相对链接(远程会话不开本地文件)fn markdown_body(id: SharedString,- text: &str,- session: &SessionMeta,+ text: impl Into<SharedString>,+ host: &str,+ project_path: &str,base: Pixels,paragraph_gap: gpui::Rems,dark: bool,@@ -8265,7 +8248,7 @@ fn markdown_body()}).selectable(true);- crate::markdown_links::with_session_links(view, &session.host, &session.project_path)+ crate::markdown_links::with_session_links(view, host, project_path)}/// Thinking 折叠面板:收起是一行摘要,展开后显示完整原文。@@ -8687,37 +8670,159 @@ fn outline_badge(name: impl Into<SharedString>, color: Hsla) -> impl IntoElement.child(div().truncate().child(name.into()))}-/// 侧栏底部工具条的图标按钮。透明底、hover 才出色——底部是次要操作区,-/// 不与导航行的选中态抢注意力;图标-only 元素改 text_color 不丢字号。-/// enabled=false(刷新进行中)只留静态内容,连 tooltip 与点击一起摘掉+/// 列表流里的分组头(会话流的时间分割线、记忆流的项目组头共用):Label 11 medium+/// muted 的标签 + 右侧低对比度 hairline,32px 高、px 12+fn section_header_row(label: impl Into<SharedString>, theme: &gpui_component::Theme) -> Div {+ h_flex()+ .h(px(32.))+ .w_full()+ .items_center()+ .gap(SPACE_SM)+ .px(SPACE_MD)+ .pt(SPACE_XS)+ .text_size(FONT_LABEL)+ .font_medium()+ .text_color(theme.muted_foreground)+ .child(div().flex_shrink_0().child(label.into()))+ .child(div().h(px(1.)).flex_1().bg(theme.border.opacity(0.72)))+}++/// 阅读面头部上下文行里的项目胶囊(会话详情与记忆阅读面共用):有路径就可点、在+/// 文件管理器里打开;没有(Unknown project)就是静态胶囊+fn project_badge(+ id: &'static str,+ path: &str,+ label: impl Into<SharedString>,+ theme: &gpui_component::Theme,+) -> AnyElement {+ let badge = badge(label, theme.muted, theme.muted_foreground);+ if path.is_empty() {+ return div().child(badge).into_any_element();+ }+ let path = path.to_string();+ div()+ .id(id)+ .cursor_pointer()+ .tooltip(|window, cx| gpui_component::tooltip::Tooltip::new(show_in_fm()).build(window, cx))+ .on_click(move |_, _, _| terminal::open_in_file_manager(&path))+ .child(badge)+ .into_any_element()+}++/// 阅读面头部的骨架(会话详情与记忆阅读面共用):44px 上下文行(左 `lead`:Label muted+/// 的品牌图 + agent + 归属;右 `actions`)→ 可换行的 22px 标题(整题挂 tooltip)→+/// Label 的元信息行。整块是窗口拖拽区+fn detail_header_frame(+ id: &'static str,+ lead: Vec<AnyElement>,+ actions: Vec<AnyElement>,+ title: SharedString,+ meta_rows: Vec<AnyElement>,+ theme: &gpui_component::Theme,+) -> Stateful<Div> {+ let title_tooltip = title.clone();+ v_flex()+ .id(id)+ .flex_shrink_0()+ .window_control_area(WindowControlArea::Drag)+ .px(SPACE_XXL)+ .pb(SPACE_SM)+ .border_b_1()+ .border_color(theme.border)+ .child(+ h_flex()+ .w_full()+ .h(WINDOW_TITLEBAR_HEIGHT)+ .items_center()+ .justify_between()+ .gap(SPACE_MD)+ .child(+ h_flex()+ .flex_1()+ .min_w_0()+ .gap(SPACE_SM)+ .items_center()+ .text_size(FONT_LABEL)+ .text_color(theme.muted_foreground)+ .children(lead),+ )+ .child(h_flex().flex_shrink_0().gap(SPACE_XS).children(actions)),+ )+ .child(+ div()+ .w_full()+ .min_h(WINDOW_TITLEBAR_HEIGHT)+ .min_w_0()+ .py(SPACE_SM)+ .flex()+ .items_center()+ .child(+ div()+ .id((ElementId::from(id), "title"))+ .w_full()+ .min_w_0()+ .whitespace_normal()+ .text_size(FONT_TITLE)+ .line_height(relative(1.15))+ .font_semibold()+ .child(title)+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(title_tooltip.clone())+ .build(window, cx)+ }),+ ),+ )+ .child(+ v_flex()+ .w_full()+ .min_w_0()+ .pt(SPACE_SM)+ .gap(SPACE_SM)+ .text_size(FONT_LABEL)+ .text_color(theme.muted_foreground)+ .children(meta_rows),+ )+}++/// 底部工具条按钮的边长:比导航行(32)小一档+const FOOTER_BTN: Pixels = px(28.);+/// 工具条左内边距 = 26.75(侧栏中轴,红绿灯红灯中心)− 14(按钮半宽):最左那颗+/// 图标的中心压在与导航行行首同一条轴上(用户 2026-09-21)+const FOOTER_LEAD_INSET: Pixels = px(12.75);++/// 底部工具条的图标按钮(Zed 状态栏 / Xcode 导航条同款图标条,不带盒子):透明底、+/// hover 才出色;`active`(当前页 / 清理模式)用侧栏行的选中色做圆角底 + 选中前景,+/// 与导航行的选中态同一套语言。14px 图标由容器 text_color 着色fn sidebar_tool_btn(id: &'static str,tooltip: &'static str,- enabled: bool,- content: AnyElement,+ active: bool,+ glyph: &'static str,on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,cx: &Context<Workbench>,) -> Stateful<Div> {let theme = cx.theme();div().id(id)- .size(ROW_HEIGHT)+ .size(FOOTER_BTN).flex_shrink_0()- .rounded(theme.radius)+ .rounded(RADIUS_BUTTON).flex().items_center().justify_center()- .text_color(theme.muted_foreground)- .when(enabled, |el| {- el.cursor_pointer()+ .cursor_pointer()+ .when(active, |el| {+ el.bg(theme.sidebar_accent)+ .text_color(theme.sidebar_accent_foreground)+ })+ .when(!active, |el| {+ el.text_color(theme.muted_foreground).hover(|s| s.bg(theme.secondary_hover).text_color(theme.foreground)).active(|s| s.bg(theme.secondary_active))- .tooltip(move |window, cx| {- gpui_component::tooltip::Tooltip::new(tooltip).build(window, cx)- })- .on_click(on_click)})- .child(content)+ .tooltip(move |window, cx| gpui_component::tooltip::Tooltip::new(tooltip).build(window, cx))+ .on_click(on_click)+ .child(icon(glyph).with_size(px(14.)))}/// Things 风源列表行:图标 + 文字 + 计数,6px 圆角选中胶囊@@ -8918,15 +9023,17 @@ impl Render for Workbench {h_flex().size_full().child(self.render_sidebar(window, cx))- // Insights 是整页目的地:替换中栏+右栏,侧栏导航保持在场+ // Insights / Memory 是整页目的地:替换中栏+右栏,侧栏导航保持在场.map(|this| {if self.cleanup.open {- this.child(self.render_cleanup(window, cx))- } else if self.insights_open {- this.child(self.render_insights(cx))- } else {- this.child(self.render_session_list(cx))- .child(self.render_detail(window, cx))+ return this.child(self.render_cleanup(window, cx));+ }+ match self.page {+ Page::Memory => this.child(self.render_memory(cx)),+ Page::Insights => this.child(self.render_insights(cx)),+ Page::Sessions => this+ .child(self.render_session_list(cx))+ .child(self.render_detail(window, cx)),}}),)diff --git a/crates/wake/src/workbench/cleanup.rs b/crates/wake/src/workbench/cleanup.rsindex f8e1e94..ad81e37 100644--- a/crates/wake/src/workbench/cleanup.rs+++ b/crates/wake/src/workbench/cleanup.rs@@ -496,7 +496,8 @@ impl Workbench {self.leave_cleanup(cx);return;}- self.insights_open = false;+ // 叠在会话视图上:整页目的地(Insights / Memory)先落回会话列表+ self.page = Page::Sessions;self.cleanup.saved_detail = self.detail.take();self.cleanup.open = true;self.cleanup.history_open = false;diff --git a/crates/wake/src/workbench/cleanup/rows.rs b/crates/wake/src/workbench/cleanup/rows.rsindex b428263..36ebaac 100644--- a/crates/wake/src/workbench/cleanup/rows.rs+++ b/crates/wake/src/workbench/cleanup/rows.rs@@ -1,6 +1,29 @@//! Both availability states use the same two-line row and column layout.use super::*;+/// 可选中的列表行热区:圆角、SPACE_SM 侧距、SPACE_MD 列距,选中 list_active、未选中+/// 悬停 list_hover。外层由调用方给 SPACE_LG 侧距 + 2px 行距+fn list_row_shell(+ id: impl Into<ElementId>,+ height: Pixels,+ selected: bool,+ theme: &gpui_component::Theme,+) -> Stateful<Div> {+ h_flex()+ .id(id)+ .w_full()+ .min_w_0()+ .h(height)+ .px(SPACE_SM)+ .rounded(theme.radius)+ .gap(SPACE_MD)+ .items_center()+ .when(selected, |row| row.bg(theme.list_active))+ .when(!selected, |row| {+ row.hover(|style| style.bg(theme.list_hover))+ })+}+fn reason_label(reason: &str) -> &str {match reason {"This source does not support independent file cleanup"@@ -57,191 +80,175 @@ impl Workbench {.px(SPACE_LG).py(px(2.)).child(- h_flex()- .id(SharedString::from(format!("cleanup-{key}")))- .w_full()- .min_w_0()- .h(px(60.))- .px(SPACE_SM)- .rounded(theme.radius)- .gap(SPACE_MD)- .items_center()- .when(selected, |row| row.bg(theme.list_active))- .when(!selected, |row| {- row.hover(|style| style.bg(theme.list_hover))- })- .child(- h_flex()- .flex_1()- .min_w_0()- .gap(SPACE_MD)- .items_center()- .child(- Checkbox::new(SharedString::from(format!("select-{key}")))- .checked(selected)- .disabled(- !selectable || self.cleanup.busy || self.cleanup.loading,- )- .when_some(reason, |checkbox, reason| {- checkbox.tooltip(unavailable_reason(reason).to_owned())- })- .on_click(move |checked, _, cx| {- if !selectable {- return;+ list_row_shell(+ SharedString::from(format!("cleanup-{key}")),+ px(60.),+ selected,+ theme,+ )+ .child(+ h_flex()+ .flex_1()+ .min_w_0()+ .gap(SPACE_MD)+ .items_center()+ .child(+ Checkbox::new(SharedString::from(format!("select-{key}")))+ .checked(selected)+ .disabled(!selectable || self.cleanup.busy || self.cleanup.loading)+ .when_some(reason, |checkbox, reason| {+ checkbox.tooltip(unavailable_reason(reason).to_owned())+ })+ .on_click(move |checked, _, cx| {+ if !selectable {+ return;+ }+ entity.update(cx, |this, cx| {+ if *checked {+ this.cleanup.selected.insert(key.clone());+ } else {+ this.cleanup.selected.remove(&key);}- entity.update(cx, |this, cx| {- if *checked {- this.cleanup.selected.insert(key.clone());- } else {- this.cleanup.selected.remove(&key);- }- cx.notify();- });- }),- )- .child(- v_flex()- .id(("cleanup-preview", ix))- .focusable()- .tab_stop(true)- .cursor_pointer()- .hover(|style| style.text_color(theme.primary))- .focus(|style| {- style.bg(theme.list_hover).rounded(RADIUS_BUTTON)- })- .on_key_down(cx.listener(- move |this, event: &KeyDownEvent, window, cx| {- if event.keystroke.key == "enter"- || event.keystroke.key == "space"- {- this.show_cleanup_preview(- &keyboard_key,- window,- cx,- );- cx.stop_propagation();- }- },- ))- .on_click(cx.listener(move |this, _, window, cx| {- this.show_cleanup_preview(&preview_key, window, cx);- }))- .flex_1()- .min_w_0()- .gap(SPACE_XS)- .child(cleanup_session_title(- meta,- members.iter().any(|s| s.favorite),- members.iter().any(|s| s.pinned),- ("cleanup-title", ix),- cx,- ))- .child(- h_flex()- .min_w_0()- .gap(SPACE_XS)- .items_center()- .text_size(FONT_LABEL)- .text_color(theme.muted_foreground)- .child(- img(meta.agent.brand_icon(theme.mode.is_dark()))- .size(px(15.))- .flex_shrink_0(),- )- .child(+ cx.notify();+ });+ }),+ )+ .child(+ v_flex()+ .id(("cleanup-preview", ix))+ .focusable()+ .tab_stop(true)+ .cursor_pointer()+ .hover(|style| style.text_color(theme.primary))+ .focus(|style| style.bg(theme.list_hover).rounded(RADIUS_BUTTON))+ .on_key_down(cx.listener(+ move |this, event: &KeyDownEvent, window, cx| {+ if event.keystroke.key == "enter"+ || event.keystroke.key == "space"+ {+ this.show_cleanup_preview(&keyboard_key, window, cx);+ cx.stop_propagation();+ }+ },+ ))+ .on_click(cx.listener(move |this, _, window, cx| {+ this.show_cleanup_preview(&preview_key, window, cx);+ }))+ .flex_1()+ .min_w_0()+ .gap(SPACE_XS)+ .child(cleanup_session_title(+ meta,+ members.iter().any(|s| s.favorite),+ members.iter().any(|s| s.pinned),+ ("cleanup-title", ix),+ cx,+ ))+ .child(+ h_flex()+ .min_w_0()+ .gap(SPACE_XS)+ .items_center()+ .text_size(FONT_LABEL)+ .text_color(theme.muted_foreground)+ .child(+ img(meta.agent.brand_icon(theme.mode.is_dark()))+ .size(px(15.))+ .flex_shrink_0(),+ )+ .child(+ div()+ .id(("cleanup-source", ix))+ .min_w_0()+ .max_w(px(128.))+ .child(badge(+ meta.project_name.clone(),+ theme.muted,+ theme.muted_foreground,+ ))+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(+ source.clone(),+ )+ .build(window, cx)+ }),+ )+ .when_some(reason, |row, reason| {+ let full_reason = unavailable_reason(reason).to_owned();+ row.child(div().px(SPACE_XS).child("·")).child(div()- .id(("cleanup-source", ix))+ .id(("cleanup-reason", ix))+ .flex_1().min_w_0()- .max_w(px(128.))- .child(badge(- meta.project_name.clone(),- theme.muted,- theme.muted_foreground,- ))+ .truncate()+ .child(reason_label(reason).to_owned()).tooltip(move |window, cx| {gpui_component::tooltip::Tooltip::new(- source.clone(),+ full_reason.clone(),).build(window, cx)}),)- .when_some(reason, |row, reason| {- let full_reason =- unavailable_reason(reason).to_owned();- row.child(div().px(SPACE_XS).child("·")).child(- div()- .id(("cleanup-reason", ix))- .flex_1()- .min_w_0()- .truncate()- .child(reason_label(reason).to_owned())- .tooltip(move |window, cx| {- gpui_component::tooltip::Tooltip::new(- full_reason.clone(),- )- .build(window, cx)- }),- )- })- .when(selectable && members.len() > 1, |row| {- row.child(crate::tp!(- "{} nested session",- "{} nested sessions",- members.len() - 1- ))- }),- ),- ),- )- .child(- div()- .id(("cleanup-date", ix))- .w(CLEANUP_DATE_WIDTH)- .flex_shrink_0()- .text_right()- .text_size(FONT_LABEL)- .text_color(theme.muted_foreground)- .child(if date > 0 {- smart_time(date)- } else {- "—".into()- })- .tooltip({- let dates = format!(- "{} · {}\n{} · {}",- t("Date created"),- abs_date(meta.created_at),- t("Date updated"),- abs_date(item.updated_at())- );- move |window, cx| {- gpui_component::tooltip::Tooltip::new(dates.clone())- .build(window, cx)- }- }),- )- .child(- div()- .id(("cleanup-size", ix))- .w(CLEANUP_SIZE_WIDTH)- .flex_shrink_0()- .text_right()- .text_size(FONT_BODY)- .when(!selectable, |size| {- size.text_color(theme.muted_foreground)- .tooltip(|window, cx| {- gpui_component::tooltip::Tooltip::new(t(- "File size unavailable",- ))- .build(window, cx)- })- })- .child(- candidate- .map(|c| bytes(c.bytes))- .unwrap_or_else(|| "—".into()),- ),- ),+ })+ .when(selectable && members.len() > 1, |row| {+ row.child(crate::tp!(+ "{} nested session",+ "{} nested sessions",+ members.len() - 1+ ))+ }),+ ),+ ),+ )+ .child(+ div()+ .id(("cleanup-date", ix))+ .w(CLEANUP_DATE_WIDTH)+ .flex_shrink_0()+ .text_right()+ .text_size(FONT_LABEL)+ .text_color(theme.muted_foreground)+ .child(if date > 0 {+ smart_time(date)+ } else {+ "—".into()+ })+ .tooltip({+ let dates = format!(+ "{} · {}\n{} · {}",+ t("Date created"),+ abs_date(meta.created_at),+ t("Date updated"),+ abs_date(item.updated_at())+ );+ move |window, cx| {+ gpui_component::tooltip::Tooltip::new(dates.clone())+ .build(window, cx)+ }+ }),+ )+ .child(+ div()+ .id(("cleanup-size", ix))+ .w(CLEANUP_SIZE_WIDTH)+ .flex_shrink_0()+ .text_right()+ .text_size(FONT_BODY)+ .when(!selectable, |size| {+ size.text_color(theme.muted_foreground)+ .tooltip(|window, cx| {+ gpui_component::tooltip::Tooltip::new(t(+ "File size unavailable",+ ))+ .build(window, cx)+ })+ })+ .child(+ candidate+ .map(|c| bytes(c.bytes))+ .unwrap_or_else(|| "—".into()),+ ),+ ),).into_any_element()}diff --git a/crates/wake/src/workbench/memory.rs b/crates/wake/src/workbench/memory.rsnew file mode 100644index 0000000..d30574c--- /dev/null+++ b/crates/wake/src/workbench/memory.rs@@ -0,0 +1,698 @@+//! Memory 页:agent 自己写下的记忆文档(Claude Code 的 auto-memory、Codex 的+//! memories)的只读浏览。侧栏底部入口,整页目的地——与 Insights 同形制:替换中栏与+//! 阅读区、与导航行互斥(`Workbench::page`)。左列按项目分组的文件列表,右侧阅读面+//! 渲染 Markdown。数据来自 memories 表(scanner 每轮扫描收尾刷新),正文阅读时先读+//! 磁盘、读不到用库里那份。只看不改:动作只有 Reveal 与 Copy path——写别家的记忆+//! 是别家的事(用户 2026-09-17 定:整页目的地、只读;MCP 面另有 wake_list_memories)++use super::*;+use wake_core::adapters::memory_body;+use wake_core::models::{MemoryCounts, MemoryDoc, MemoryFilter, MemoryGroup, MemoryScope};++/// 左列的一行:分组头(带该组第一份文档的下标,标签从它算)或一份文档+#[derive(Clone, Copy)]+enum MemoryRow {+ Group(usize),+ Doc(usize),+}++/// 选中文档在后台读好的部分:正文(SharedString——TextView 每帧要一份,Arc 一拨就够),+/// 以及解析过的来源路径(SQLite 型的虚拟路径落到库文件本体——解析要 stat,不能在+/// render 里每帧做)+struct LoadedMemory {+ body: SharedString,+ source_path: String,+}++pub(super) struct MemoryState {+ /// store 已排好序:项目路径分组、组内新到旧、用户级最后;行里**不带正文**(列表列+ /// 给的是空串),选中时按 key 另取+ docs: Vec<MemoryDoc>,+ /// 组头 + 文档扁平成行,交 gpui::list 虚拟化——只画看得见的几行,行文案在画+ /// 的时候现算(译文与相对时间都不缓存,换语言不会留旧串)+ rows: Vec<MemoryRow>,+ list: gpui::ListState,+ loading: bool,+ selected: Option<String>,+ /// 选中后后台读,读到前是 None(转圈)+ loaded: Option<LoadedMemory>,+ /// 侧栏导航的计数(All Memory / Agents / Projects),与 docs 同一次查询刷新+ counts: MemoryCounts,+ /// 侧栏筛选(单选,与会话侧栏同一模型):agent 或项目,`Some("")` 是没归属的一组+ agent: Option<AgentId>,+ project: Option<String>,+ /// 筛选刚换过(进页归零、点了导航行):下一次重载必须查(扫描进行中也不按住)并把+ /// 列表拉回顶部、不恢复旧滚动位置+ scope_changed: bool,+ /// 进行中的列表/正文任务;新任务覆盖旧值即取消+ load_task: Option<Task<()>>,+ body_task: Option<Task<()>>,+}++impl Default for MemoryState {+ fn default() -> Self {+ Self {+ docs: Vec::new(),+ rows: Vec::new(),+ list: gpui::ListState::new(0, gpui::ListAlignment::Top, px(200.)),+ loading: false,+ selected: None,+ loaded: None,+ counts: MemoryCounts::default(),+ agent: None,+ project: None,+ scope_changed: false,+ load_task: None,+ body_task: None,+ }+ }+}++impl Workbench {+ /// 进 Memory 页时从"全部"开始+ pub(super) fn reset_memory_scope(&mut self) {+ self.memory.agent = None;+ self.memory.project = None;+ self.memory.scope_changed = true;+ }++ /// 侧栏导航行的唯一写入点(agent 与项目互斥,与会话侧栏的 set_scope 同形)+ fn set_memory_scope(+ &mut self,+ agent: Option<AgentId>,+ project: Option<String>,+ cx: &mut Context<Self>,+ ) {+ self.memory.agent = agent;+ self.memory.project = project;+ self.memory.scope_changed = true;+ self.reload_memories(cx);+ }++ /// refresh 顺带重载(与 reload_insights 同规矩):扫描进行中且已有数据就按住,+ /// 终态 Progress 补最后一次——**筛选刚换过除外**:这里也是侧栏导航的唯一落点,+ /// 按住就是点了没反应、标题换了列表没换(2026-09-21 review)。选中项还在就保留,+ /// 否则落到第一份+ pub(super) fn reload_memories(&mut self, cx: &mut Context<Self>) {+ if self.page != Page::Memory {+ return;+ }+ if self.scan.scanning && !self.memory.docs.is_empty() && !self.memory.scope_changed {+ return;+ }+ 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,+ };+ let task = cx.background_spawn(async move {+ let docs = store.list_memories(&filter)?;+ let counts = store.memory_counts()?;+ anyhow::Ok((docs, counts))+ });+ 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 {+ this.memory.counts = counts;+ let rows = memory_rows(&docs);+ // 重载来自每轮扫描,滚动位置要留住:splice 整段会把落在段内的+ // 滚动锚点归零(gpui 的 splice 只保段外的锚点),所以先记下再恢复;+ // 筛选刚换过则回到顶部+ let top = if this.memory.scope_changed {+ gpui::ListOffset {+ item_ix: 0,+ offset_in_item: px(0.),+ }+ } else {+ this.memory.list.logical_scroll_top()+ };+ this.memory.scope_changed = false;+ let old = this.memory.rows.len();+ this.memory.list.splice(0..old, rows.len());+ this.memory.list.scroll_to(top);+ // 选中项:还在且没变就不动;正文被 agent 改过(时间或大小变了)+ // 重读,否则新标题配旧正文;没了就落到第一份+ let stamp = |docs: &[MemoryDoc], key: &str| {+ docs.iter()+ .find(|d| d.key == key)+ .map(|d| (d.updated_at, d.size_bytes))+ };+ let selected = this.memory.selected.clone();+ let before = selected+ .as_deref()+ .and_then(|k| stamp(&this.memory.docs, k));+ let after = selected.as_deref().and_then(|k| stamp(&docs, k));+ this.memory.docs = docs;+ this.memory.rows = rows;+ match (selected, after) {+ (Some(key), Some(now)) if before != Some(now) => {+ this.select_memory(key, cx);+ }+ (Some(_), Some(_)) => {}+ _ => {+ this.memory.selected = None;+ this.memory.loaded = None;+ if let Some(first) = this.memory.docs.first().map(|d| d.key.clone()) {+ this.select_memory(first, cx);+ }+ }+ }+ }+ this.memory.loading = false;+ cx.notify();+ })+ .ok();+ }));+ }++ fn select_memory(&mut self, key: String, cx: &mut Context<Self>) {+ let Some(path) = self+ .memory+ .docs+ .iter()+ .find(|d| d.key == key)+ .map(|d| d.path.clone())+ else {+ return;+ };+ self.memory.selected = Some(key.clone());+ self.memory.loaded = None;+ // 列表行不带正文,选中时按 key 另取一行;正文与来源路径都在后台算:两者都要+ // stat(虚拟路径解析、现场读文件),自定义 location 挂在慢盘上时不能卡 UI 线程+ let store = self.store.clone();+ let task = {+ let key = key.clone();+ cx.background_spawn(async move {+ let doc = store+ .get_memory(&key)?+ .ok_or_else(|| anyhow::anyhow!("memory {key} is no longer indexed"))?;+ anyhow::Ok(LoadedMemory {+ source_path: session_source_path(&doc.path).to_string(),+ body: memory_body(&doc).into(),+ })+ })+ };+ self.memory.body_task = Some(cx.spawn(async move |this, cx| {+ let loaded = task.await;+ this.update(cx, |this, cx| {+ // 只写回仍然选中的那份,快速切换时旧任务不覆盖新选择+ if this.memory.selected.as_deref() != Some(key.as_str()) {+ return;+ }+ // 读不出(刚被扫描清掉、库读错)也得收场,不能让阅读面一直转圈;来源路径+ // 同样要解析过(虚拟路径落到库文件),Copy path 才不会给出 `<db>#<id>`+ this.memory.loaded = Some(loaded.unwrap_or_else(|e| LoadedMemory {+ source_path: session_source_path(&path).to_string(),+ body:+ crate::tf!("Could not read this memory file: {}", format!("{e:#}")).into(),+ }));+ cx.notify();+ })+ .ok();+ }));+ cx.notify();+ }++ /// 会话页同一形制(用户 2026-09-21:整页宽的页头压着两栏"看着很奇怪"):左列 =+ /// 列内页头 + 记忆流,右侧 = 阅读面(详情页同款头部 + popover 正文)+ pub(super) fn render_memory(&self, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme().clone();+ let count = self.memory.docs.len();+ let subtitle: SharedString = crate::tp!("{} memory file", "{} memory files", count).into();+ let column: AnyElement = if self.memory.docs.is_empty() {+ div().flex_1().into_any_element()+ } else {+ self.render_memory_list(cx)+ };+ // 列表非空时选中项恒有(reload 落到第一份),阅读面跟着它;空库给空态卡+ let selected = self+ .memory+ .selected+ .as_ref()+ .and_then(|k| self.memory.docs.iter().find(|d| &d.key == k));+ let pane: AnyElement = match selected {+ Some(doc) => self.render_memory_reader(doc, cx),+ None => v_flex()+ .flex_1()+ .h_full()+ .items_center()+ .justify_center()+ .bg(theme.background)+ .child(if self.memory.loading {+ Spinner::new().into_any_element()+ } else {+ empty_state_card(+ "icons/file-text.svg",+ px(58.),+ px(24.),+ t("No memory files yet"),+ t("Agents write these as they work: Claude Code's auto-memory, Codex's memories, ZCode's project memory. They show up here once they exist."),+ cx,+ )+ .into_any_element()+ })+ .into_any_element(),+ };+ h_flex()+ .flex_1()+ .min_w_0()+ .h_full()+ .child(+ v_flex()+ .w(SESSION_STREAM_WIDTH)+ .h_full()+ .flex_shrink_0()+ .bg(theme.colors.list)+ .child(library_header(+ "memory-header",+ self.memory_context_title(),+ subtitle,+ SPACE_LG,+ Some(self.refresh_button(cx)),+ cx,+ ))+ .child(column),+ )+ .child(pane)+ .into_any_element()+ }++ /// 左列页头的标题 = 当前侧栏筛选(与会话页 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+ .memory+ .counts+ .projects+ .iter()+ .find(|p| &p.path == path)+ .map(|p| p.name.clone())+ .unwrap_or_else(|| t("Projects").to_string());+ }+ t("All Memory").to_string()+ }++ /// 记忆流:gpui::list 虚拟化(行高不等:分组头与两行的文档行)+ fn render_memory_list(&self, cx: &Context<Self>) -> AnyElement {+ let entity = cx.entity().downgrade();+ div()+ .flex_1()+ .min_h_0()+ .w_full()+ .relative()+ .child(+ gpui::list(self.memory.list.clone(), move |ix, _window, cx| {+ entity+ .upgrade()+ .map(|e| e.update(cx, |this, cx| this.render_memory_row(ix, cx)))+ .unwrap_or_else(|| div().into_any_element())+ })+ .size_full(),+ )+ .vertical_scrollbar(&self.memory.list)+ .into_any_element()+ }++ /// 一行:分组头(会话流的时间分割线同款),或两行的文档行(会话行同款:Body 14+ /// medium 标题一行;Label 11 的品牌图 + 归属徽章 + 右对齐时间)+ fn render_memory_row(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme().clone();+ let Some(row) = self.memory.rows.get(ix).copied() else {+ return div().into_any_element();+ };+ match row {+ MemoryRow::Group(first) => {+ // 组头 = 会话流的时间分割线(用户 2026-09-21 定)+ let label = self+ .memory+ .docs+ .get(first)+ .map(memory_group_label)+ .unwrap_or_default();+ section_header_row(label, &theme).into_any_element()+ }+ MemoryRow::Doc(di) => {+ let Some(d) = self.memory.docs.get(di) else {+ return div().into_any_element();+ };+ let selected = self.memory.selected.as_deref() == Some(d.key.as_str());+ let key = d.key.clone();+ let title: SharedString = clip_display(&d.title, SESSION_TITLE_MAX_WIDTH).into();+ let title_tooltip: SharedString = d.title.clone().into();+ let shown_time: SharedString = smart_time(d.updated_at).into();+ let shown_tooltip: SharedString = abs_date(d.updated_at).into();+ // 盒模型逐项照会话行:ListItem 自带 px_3 / py_1(12 / 4)再套行内容的+ // SPACE_XS / SPACE_SM(4 / 8),高亮面 mx = SPACE_SM——这里没有 ListItem,+ // 把两层加成一层写死同样的数。不缩进、不画竖线(树的子行形制试过,用户+ // 2026-09-21 定没必要)+ div()+ .w_full()+ .px(SPACE_SM)+ .child(+ v_flex()+ .id(("memory-row", ix))+ .w_full()+ .min_w_0()+ .rounded(theme.radius)+ .px(SPACE_MD + SPACE_XS)+ .py(SPACE_XS + SPACE_SM)+ .gap(SPACE_XS)+ .cursor_pointer()+ .when(selected, |row| row.bg(theme.list_active))+ .when(!selected, |row| {+ row.hover(|style| style.bg(theme.list_hover))+ })+ .on_click(cx.listener(move |this, _, _window, cx| {+ this.select_memory(key.clone(), cx)+ }))+ .child(+ div()+ .id(("memory-title", ix))+ .w_full()+ .min_w_0()+ .overflow_hidden()+ .whitespace_nowrap()+ .text_size(FONT_BODY)+ .font_medium()+ .text_color(theme.foreground)+ .child(title)+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(title_tooltip.clone())+ .build(window, cx)+ }),+ )+ .child(+ h_flex()+ .gap(px(6.))+ .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(),+ )+ .children(memory_badges(d, &theme))+ .child(div().flex_1())+ .child(+ div()+ .id(("memory-time", ix))+ .flex_shrink_0()+ .child(shown_time)+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(+ shown_tooltip.clone(),+ )+ .build(window, cx)+ }),+ ),+ ),+ )+ .into_any_element()+ }+ }+ }++ /// 阅读面,详情页同款头部(`detail_header_frame`):上下文行是品牌图 + agent + 归属+ /// 徽章,右端 Reveal / Copy path;元信息是文件路径与更新时间;正文 popover 底、+ /// 720 阅读宽居中,与消息正文同一套 Markdown 渲染+ fn render_memory_reader(&self, doc: &MemoryDoc, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme().clone();+ let dark = theme.mode.is_dark();+ // SQLite 型的虚拟路径落到库文件本体,Reveal 与 Copy 才有东西可指;解析在+ // select_memory 的后台任务里做好,读到之前按 scope 剥虚拟后缀顶一下(不 stat)+ let source_path = self+ .memory+ .loaded+ .as_ref()+ .map(|l| l.source_path.clone())+ .unwrap_or_else(|| memory_display_path(doc));+ let reveal_path = source_path.clone();+ let copy_path = source_path.clone();+ // 相对链接按记忆文件所在目录解析(MEMORY.md 链接的是同目录的主题文件),+ // 不是项目根;SQLite 型没有目录,退项目路径+ let link_base = if source_path == doc.path {+ std::path::Path::new(&doc.path)+ .parent()+ .map(|p| p.to_string_lossy().to_string())+ .unwrap_or_default()+ } else {+ doc.project_path.clone()+ };+ let updated: SharedString = crate::tf!("Updated {}", smart_time(doc.updated_at)).into();+ let updated_tooltip: SharedString =+ crate::tf!("Updated {}", abs_date(doc.updated_at)).into();+ let mut lead: Vec<AnyElement> = vec![+ img(doc.agent.brand_icon(dark))+ .size(px(15.))+ .flex_shrink_0()+ .into_any_element(),+ div()+ .flex_shrink_0()+ .child(doc.agent.display_name())+ .into_any_element(),+ project_badge(+ "memory-project",+ &doc.project_path,+ memory_group_label(doc),+ &theme,+ ),+ ];+ lead.extend(memory_badges(doc, &theme));+ let actions: Vec<AnyElement> = vec![+ Button::new("memory-reveal")+ .ghost()+ .rounded(RADIUS_BUTTON)+ .icon(icon("icons/folder.svg").with_size(px(16.)))+ .tooltip(reveal_in_fm())+ .on_click(move |_, _, _| {+ terminal::reveal_in_file_manager(&reveal_path);+ })+ .into_any_element(),+ Button::new("memory-copy-path")+ .ghost()+ .rounded(RADIUS_BUTTON)+ .icon(icon("icons/copy.svg").with_size(px(16.)))+ .tooltip(t("Copy path"))+ .on_click(move |_, _, cx| {+ cx.write_to_clipboard(ClipboardItem::new_string(copy_path.clone()));+ })+ .into_any_element(),+ ];+ let meta_rows: Vec<AnyElement> = vec![+ h_flex()+ .min_w_0()+ .gap(px(6.))+ .child(+ icon("icons/file-text.svg")+ .with_size(px(12.))+ .flex_shrink_0(),+ )+ .child(div().min_w_0().truncate().child(tilde_path(&source_path)))+ .into_any_element(),+ h_flex()+ .min_w_0()+ .gap(px(6.))+ .items_center()+ .child(+ icon("icons/calendar.svg")+ .with_size(px(12.))+ .flex_shrink_0(),+ )+ .child(+ div()+ .id("memory-updated")+ .min_w_0()+ .truncate()+ .child(updated)+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(updated_tooltip.clone())+ .build(window, cx)+ }),+ )+ .into_any_element(),+ ];+ let header = detail_header_frame(+ "memory-detail-header",+ lead,+ actions,+ doc.title.clone().into(),+ meta_rows,+ &theme,+ );+ let content: AnyElement = match &self.memory.loaded {+ Some(loaded) => markdown_body(+ format!("memory-{}", doc.key).into(),+ loaded.body.clone(),+ &doc.host,+ &link_base,+ FONT_MSG_BODY,+ gpui::rems(0.5),+ dark,+ cx,+ )+ .into_any_element(),+ None => div()+ .w_full()+ .flex()+ .justify_center()+ .py(SPACE_XXL)+ .child(Spinner::new())+ .into_any_element(),+ };+ v_flex()+ .flex_1()+ .min_w_0()+ .h_full()+ .bg(theme.background)+ .child(header)+ .child(+ div()+ .id("memory-reader")+ .flex_1()+ .min_h_0()+ .overflow_y_scroll()+ .bg(theme.popover)+ // 与详情正文同一组数:24px 阅读轴,首条上留 16、末条下留 24+ .px(SPACE_XXL)+ .pt(SPACE_LG)+ .pb(SPACE_XXL)+ .child(+ div()+ .w_full()+ .flex()+ .justify_center()+ .child(div().w_full().max_w(READER_MAX_WIDTH).child(content)),+ ),+ )+ .into_any_element()+ }++ /// Memory 页的侧栏导航,替换会话导航(搜索框、All Sessions / Starred、Agents /+ /// Projects):All 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();+ v_flex()+ .flex_1()+ .min_h_0()+ .child(+ v_flex()+ .flex_shrink_0()+ .px(SIDEBAR_EDGE)+ .pb(SPACE_XS)+ .gap(SPACE_XS)+ // 不放模式标题:当前页由底部工具条点亮的那颗说明(曾加过一行+ // brain + "Memory",用户 2026-09-21 定没必要)+ .child(sidebar_row(+ "memory-all",+ RowLead::Icon(icon("icons/file-text.svg")),+ t("All Memory"),+ Some(counts.total),+ all_active,+ RowLevel::Primary,+ cx.listener(|this, _, _window, cx| {+ this.set_memory_scope(None, None, 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,+ ),+ )+ .into_any_element()+ }+}++/// 组头 + 文档扁平成行;分组判据是 `MemoryDoc::group`(与 store 的排序一致:项目按+/// 路径、没归属的一组在项目之后、用户级最后)。不折叠、不缩进(树的形制试过,用户+/// 2026-09-21 定没必要)+fn memory_rows(docs: &[MemoryDoc]) -> Vec<MemoryRow> {+ let mut rows = Vec::with_capacity(docs.len() + 8);+ let mut current: Option<MemoryGroup> = None;+ for (ix, d) in docs.iter().enumerate() {+ let group = d.group();+ if current != Some(group) {+ rows.push(MemoryRow::Group(ix));+ current = Some(group);+ }+ rows.push(MemoryRow::Doc(ix));+ }+ rows+}++/// 读到 LoadedMemory 之前阅读面要显示的来源路径:线程记忆(Codex 的逐会话摘要)的+/// 虚拟路径 `<db>#<id>` 只剥后缀、不 stat(render 每帧调);文件型就是它自己+fn memory_display_path(d: &MemoryDoc) -> String {+ if d.scope == MemoryScope::Thread {+ d.path+ .rsplit_once('#')+ .map_or_else(|| d.path.clone(), |(db, _)| db.to_string())+ } else {+ d.path.clone()+ }+}++/// 组头 / 归属徽章的文案:项目名;用户级记忆一组、没有项目的一组+fn memory_group_label(d: &MemoryDoc) -> SharedString {+ match d.group() {+ MemoryGroup::User => t("User-level").into(),+ MemoryGroup::Unknown => t("Unknown project").into(),+ MemoryGroup::Project { name, .. } => name.to_string().into(),+ }+}++/// 文档行与阅读面头部共用的两枚徽章(有则画):Codex 逐会话记忆的 "session memory",+/// 远程记忆的 @host+fn memory_badges(d: &MemoryDoc, theme: &gpui_component::Theme) -> Vec<AnyElement> {+ let mut out = Vec::with_capacity(2);+ if d.scope == MemoryScope::Thread {+ out.push(+ badge(t("session memory"), theme.muted, theme.muted_foreground).into_any_element(),+ );+ }+ if !d.host.is_empty() {+ out.push(host_badge(&d.host, theme).into_any_element());+ }+ out+}diff --git a/docs/cli.md b/docs/cli.mdindex 1cc4192..320c039 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -100,6 +100,17 @@ wake-cli show 'claude-code:1b2c3d4e-…' --subagent '*'Working directories that have session history, most recently active first, with session counts. Use it to find the right `--project` value. Options: `--since`, `--limit` (default 50, max 200).+### `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).++```bash+wake-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.+### `setup`Prints this binary's path, the index path, how to put it on your `PATH`, a paste-able block that tells an agent when and how to use it, and — when `wake-mcp` sits next to it — the one-line MCP setup for Claude Code. It installs nothing and never edits another tool's config files. The one thing it can write is Wake's own: resolving the default index path creates Wake's data directory and migrates an index left by the old `vibex` builds (`--db` skips that).diff --git a/docs/mcp.md b/docs/mcp.mdindex 48f02a4..88ed20e 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -57,7 +57,7 @@ If the index does not exist yet, the server exits with status 2 and a message on### Check that it is connected-- **Claude Code**: `claude mcp list` shows `wake` as connected; inside a session, `/mcp` lists the server and its four tools.+- **Claude Code**: `claude mcp list` shows `wake` as connected; inside a session, `/mcp` lists the server and its five tools.- **Codex**: restart Codex after editing `config.toml`; the `wake_*` tools show up in its tool list.- **Cursor**: Settings → MCP shows `wake` with a green status dot.- **No client at hand**: `wake-mcp call wake_list_projects` in a terminal prints exactly what an agent would see.@@ -121,7 +121,7 @@ so an agent can tell how recent the data is. Two replies carry no freshness line## Tools-All four tools are read-only and return Markdown text (`content[0].text`). Parameters are JSON; every parameter except the ones marked required is optional.+All five tools are read-only and return Markdown text (`content[0].text`). Parameters are JSON; every parameter except the ones marked required is optional.### Shared parameters@@ -209,11 +209,23 @@ Projects (working directories) that have indexed sessions, most recently active| `since` | string | || `limit` | integer 1–200 | 50 |+### `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.++| 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.+## Session keys and references- Local sessions: `<agent>:<native id>`, for example `codex:0195c2a1-…`.- Sessions mirrored from a remote host: `<agent>:<host>:<native id>`.- References: `wake://session/<key>#<seq>` point at one message; `wake_get_session` accepts them as `key` and starts the page there.+- Memory files: `wake://memory/<agent>:<path>` (with a host segment for mirrored hosts); `wake_get_session` accepts them as `key` and returns the file.The native id is the one the agent's own `--resume` flag expects.diff --git a/skills/wake/SKILL.md b/skills/wake/SKILL.mdindex 6a40404..af5d86e 100644--- a/skills/wake/SKILL.md+++ b/skills/wake/SKILL.md@@ -73,6 +73,17 @@ as sessions of their own (Codex `spawn_agent`, Grok) are listed at the end too,wake-cli projects --limit 20```+**What an agent already remembers about this project**++```bash+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.+## Keys, references and paging`sessions` and `search` print a key for every session — `<agent>:<id>`, or