@restregular/dsh-memory 0.9.4 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +14 -3
  2. package/lib/client.js +906 -1
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -9,10 +9,14 @@ English: Local, durable memory for DeepSeek Harness — one npm package, one loa
9
9
 
10
10
  ## 预览 / Preview
11
11
 
12
- 设置页 →「记忆」:顶部统计(记忆数 / 作用域数 / 待嵌入向量)、向量服务(运行状态、本机配置、当前模型)、维护(卸载向量服务 / 清空记忆数据)、记录列表(搜索 + 作用域筛选 + 按 scope / 类型 / 时间展开)。
12
+ 设置页 →「记忆」:顶部统计(记忆数 / 作用域数 / 待嵌入向量)、向量服务(运行状态、本机配置、当前模型)、维护(卸载向量服务 / 清空记忆数据)、记录列表(搜索 + 作用域筛选 + 按 scope / 类型 / 时间展开),以及按**作用域 → 类型 → 记录**分层展示、带修正关系连线的**记忆树**。
13
13
 
14
14
  ![设置页「记忆」面板](./preview/memory-panel.png)
15
15
 
16
+ 「记忆树」标签页:金色虚线表示 `supersedes`(新记录修正旧记录),点节点看详情,悬停或选中时整条修正链一起点亮。
17
+
18
+ ![记忆树](./preview/memory-tree.png)
19
+
16
20
  模型在对话里查记忆 —— `memory_search` 的入参与召回结果:
17
21
 
18
22
  ![memory_search 工具调用](./preview/memory-search.png)
@@ -30,7 +34,7 @@ English: Local, durable memory for DeepSeek Harness — one npm package, one loa
30
34
  | **记忆使用策略** | 系统提示常驻段:什么时候该查记忆、查到怎么复用、查不到时低风险推断 / 高风险先问用户 |
31
35
  | **硬性规则** | `kind: rule` 的记忆进系统提示常驻段(限量、可关);**新增/改过的规则会在旧会话的下一轮补一条提醒**(同一条只提醒一次)。能机械校验的规则应该做成钩子,提示词只做解释 |
32
36
  | **五个工具** | `memory_save` / `memory_search` / `memory_list` / `memory_get` / `memory_forget`(摘要带 8 位 id,`memory_get` 直接取全文) |
33
- | **管理面板** | 设置页「记忆」:记录(浏览 / 搜索 / 新建 / 编辑 / 删除)+ 设置(召回、摘要、印象、策略、规则、轮末提醒逐项开关、导入导出)、向量服务启停、模型与硬件、维护(卸载 / 清空) |
37
+ | **管理面板** | 设置页「记忆」:记录(浏览 / 搜索 / 新建 / 编辑 / 删除)+ **记忆树**(作用域 / 类型 / 修正关系可视化、折叠、筛选、缩放与详情)+ 设置(召回、摘要、印象、策略、规则、轮末提醒逐项开关、导入导出)、向量服务启停、模型与硬件、维护(卸载 / 清空) |
34
38
  | **向量后端一键装** | 面板里选模型 → 下 llama.cpp 运行时 + 模型 → 托管 `llama-server` 进程;内置 8 个模型 + 硬件推荐 + 自定义 GGUF |
35
39
 
36
40
  ## 安装 / Install
@@ -102,10 +106,11 @@ memory_save({
102
106
  **3. 按 id 取全文**:召回 / 摘要每行开头是 8 位 id 前缀,`memory_get({ ids: ["3f2a9c1d"] })` 直接拿原文,不用再检索。
103
107
  **4. 列出 / 忘记**:`memory_list({ limit: 20 })`(默认只列当前会话,末尾附作用域清单 + 记录数)、`memory_forget({ id })` 或 `memory_forget({ query, scope })`(按内容删默认**只作用于当前会话**,防止跨作用域误删)。
104
108
 
105
- **5. 打开面板**:设置页 →「记忆」;也可以在「设置 → 侧栏入口」打开左侧栏的「记忆」按钮,点击在主界面打开面板。面板分三个标签:
109
+ **5. 打开面板**:设置页 →「记忆」;也可以在「设置 → 侧栏入口」打开左侧栏的「记忆」按钮,点击在主界面打开面板。面板分四个标签:
106
110
 
107
111
  - **服务**:「向量服务」:状态、地址、启停开关、**模型与硬件**(见下)、维护(卸载向量服务 / 清空记忆数据,两步确认)
108
112
  - **记录**(默认打开):顶部统计(记忆数 / 作用域数 / 待嵌入向量数)、搜索、按作用域筛选、**新建**(任意作用域 + 类型,类型里含 `rule`)、展开编辑 / 删除;列表放在独立的滚动容器里(记忆再多也不把面板撑长),滚动条是自定义的细圆头样式,从侧栏入口打开时容器还会跟着窗口长高;作用域下拉**动态枚举实际存在的作用域**(`global` 显示「全局」、project 显示 cwd、会话 scope 显示会话标题、自定义 scope 显示原名)
113
+ - **记忆树**:所有作用域的记忆按 **作用域 → 类型 → 记录** 三层展开,根节点显示总数;记录卡按类型着色,`supersedes` / `supersededBy` 用金色虚线把「修正版」和「被修正的旧版」连起来。支持搜索(命中高亮、其余淡出)、按类型逐个开关、按作用域筛选、折叠作用域 / 类型、缩放与「适应」、以及点击记录打开的详情抽屉(全文、标签、重要度、时间、id 与双向修正链)。修正是**关系**而不是层级,所以不改变树结构,只叠在右侧;悬停或选中一条记录时,整条修正链一起点亮
109
114
  - **设置**:注入链路逐项开关 —— 每轮召回(topK / 预算)、印象形态(每条字数)、会话摘要(条数 / 预算)、记忆使用策略段、硬性规则段(条数 / 预算 / 变更提醒,并显示当前规则条数)、轮末提醒、侧栏入口;底部「数据」:导出全部 / 导入文件。改完**即保存**,不需要点按钮
110
115
 
111
116
  > **导入 / 导出**:导出的是纯文本 —— 作用域、类型、内容、标签、重要度、时间戳,**没有向量**。导入时逐条走保存路径,按**当前模型重新嵌入**,并按「作用域 + 内容」去重(重复的计入「跳过」)。一次最多 5000 条。
@@ -326,6 +331,12 @@ tools/build-single-package.mjs 构建(产物契约检查 + 可选加载验证)
326
331
 
327
332
  ## 版本
328
333
 
334
+ - **0.9.5** —— 新增「记忆树」标签页:
335
+ - 所有作用域的记忆按 **作用域 → 类型 → 记录** 分层展示,根节点是总数;记录卡按类型着色(事实 / 决策 / 偏好 / 流程 / 笔记 / 规则),修正/被修正各有徽标。
336
+ - `supersedes` 是点对点关系、不是层级,所以不改树结构:金色虚线从修正版弯到旧版的右缘,悬停或选中任意一端时,两端与整条修正链一起点亮;关闭「修正连线」可只看结构。
337
+ - 交互:搜索(命中高亮、其余淡出)、按类型逐个开关(带计数)、作用域筛选、折叠作用域 / 类型、全部展开 / 只看作用域、缩放 / 适应;点记录打开详情抽屉(全文、标签、重要度、时间、id、双向修正链,关系项可直接跳到另一端)。
338
+ - 布局用固定三层列 + 父节点在子树高度里居中,首次进入按画布宽度自动缩放并把根节点滚到视口中央;记录多时纵向滚动,不把面板撑长。
339
+ - 测试:布局纯函数(分组、折叠、类型筛选、修正边只连两端都可见的记录)+ 面板标签切换冒烟;README 增加预览图。
329
340
  - **0.9.4** —— 侧栏图标改回单色线稿:
330
341
  - 0.9.3 把彩色年轮瓦片放进了左侧栏入口和设置侧栏,和那一列 16px 单色线稿图标不一致。现在两处都画成**年轮线稿**:圆角瓦片轮廓 + 1.75 圈螺旋,16 网格、`fill:none`、`stroke:currentColor`、1.3 描边,深浅主题自动跟随文字色。
331
342
  - 插件列表的彩色 `icon.svg` 不变 —— 那是插件的品牌美术,只服务 30/36px 的插件卡片/行,不参与侧栏。
package/lib/client.js CHANGED
@@ -186,6 +186,115 @@ window.__ModuleLoader__.load({
186
186
  '.mem-page .memp .scroll{max-height:calc(100vh - 340px)}',
187
187
  '.mem-page-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}',
188
188
  '.mem-page-head h2{font-size:15px;font-weight:600;margin:0}',
189
+ // ===== 记忆树 =====
190
+ // 结构:统计 → 工具条/类型图例 → 画布(HTML 节点 + SVG 连线) → 右侧详情抽屉。
191
+ // 节点用 HTML 而不是 SVG <text>:内容换行、省略号、悬停过渡都由浏览器排版,
192
+ // SVG 只负责画连接线,缩放时整体 transform。
193
+ '.memp .tree-tab{display:flex;flex-direction:column;gap:12px}',
194
+ '.memp .tree-stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}',
195
+ '.memp .tree-stats .stat{position:relative;overflow:hidden;padding:8px 12px 7px;border-radius:11px;background:linear-gradient(160deg,color-mix(in srgb,var(--dsw-alias-brand-primary) 8%,var(--dsw-alias-bg-layer-1)),var(--dsw-alias-bg-layer-1) 72%)}',
196
+ '.memp .tree-stats .stat::after{content:"";position:absolute;right:-14px;top:-20px;width:56px;height:56px;border-radius:50%;background:color-mix(in srgb,var(--dsw-alias-brand-primary) 9%,transparent);pointer-events:none}',
197
+ '.memp .tree-stats .stat b{font-size:18px}',
198
+ '.memp .tree-toolbar{display:flex;gap:8px;align-items:center;flex-wrap:wrap}',
199
+ '.memp .tree-toolbar input[type=text]{flex:1 1 190px;min-width:150px;max-width:300px}',
200
+ '.memp .tree-toolbar .spacer{flex:1}',
201
+ '.memp .tree-toolbar button{padding:5px 10px;font-size:12px}',
202
+ // 工具条里的类型胶囊沿用 kchip 的圆角与内边距,不被上面的通用 button 规则撑高。
203
+ '.memp .tree-toolbar .kchip{padding:1px 9px 1px 7px;line-height:1.8;border-radius:999px;font-size:11.5px}',
204
+ '.memp .tree-toolbar .linkbtn{padding:2px 4px;border:0;background:none}',
205
+ '.memp .kindbar{display:flex;gap:6px;align-items:center;flex-wrap:wrap;min-width:0}',
206
+ '.memp .kindbar-label{font-size:11.5px;color:var(--dsw-alias-label-secondary);flex:none}',
207
+ '.memp .kchip{display:inline-flex;align-items:center;gap:5px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-secondary);border-radius:999px;padding:1px 9px 1px 7px;font-size:11.5px;line-height:1.8;cursor:pointer;transition:opacity .12s ease,border-color .12s ease,color .12s ease,background .12s ease}',
208
+ '.memp .kchip .tdot{width:7px;height:7px;border-radius:50%;background:var(--k);box-shadow:0 0 0 3px color-mix(in srgb,var(--k) 15%,transparent)}',
209
+ '.memp .kchip b{font-weight:600;color:var(--dsw-alias-label-primary)}',
210
+ '.memp .kchip.off{opacity:.42;background:transparent}',
211
+ '.memp .kchip.on{color:var(--dsw-alias-label-primary);border-color:color-mix(in srgb,#D9A441 45%,var(--dsw-alias-border-l1));background:color-mix(in srgb,#D9A441 8%,var(--dsw-alias-bg-layer-1))}',
212
+ '.memp .kchip:hover{border-color:var(--k);color:var(--dsw-alias-label-primary)}',
213
+ '.memp .kchip .corr-swatch{width:14px;border-top:1.5px dashed #D9A441}',
214
+ '.memp .tree-matchinfo{font-size:11px;color:var(--dsw-alias-label-secondary);flex:none}',
215
+ '.memp .tree-wrap{position:relative;height:min(56vh,560px);min-height:320px;border:1px solid var(--dsw-alias-border-l1);border-radius:14px;overflow:hidden;background:radial-gradient(circle at 16% 8%,color-mix(in srgb,var(--dsw-alias-brand-primary) 9%,transparent),transparent 44%),radial-gradient(circle at 1px 1px,color-mix(in srgb,var(--dsw-alias-label-secondary) 15%,transparent) 1px,transparent 0) 0 0/22px 22px,var(--dsw-alias-bg-layer-1)}',
216
+ '.mem-page .memp .tree-wrap{height:calc(100vh - 360px);min-height:420px}',
217
+ '.memp .tree-scroll{height:100%;overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-color:color-mix(in srgb,var(--dsw-alias-label-secondary) 30%,transparent) transparent}',
218
+ '.memp .tree-scroll::-webkit-scrollbar{width:9px;height:9px}',
219
+ '.memp .tree-scroll::-webkit-scrollbar-track{background:transparent}',
220
+ '.memp .tree-scroll::-webkit-scrollbar-thumb{background:rgba(127,127,127,.28);background:color-mix(in srgb,var(--dsw-alias-label-secondary) 30%,transparent);border-radius:999px;border:2px solid transparent;background-clip:padding-box}',
221
+ '.memp .tree-scroll::-webkit-scrollbar-thumb:hover{background:rgba(127,127,127,.5);background:color-mix(in srgb,var(--dsw-alias-label-secondary) 55%,transparent);border:2px solid transparent;background-clip:padding-box}',
222
+ '.memp .tree-scroll::-webkit-scrollbar-corner{background:transparent}',
223
+ '.memp .tree-zoomspace{position:relative;margin:0 auto}',
224
+ '.memp .tree-canvas{position:relative;transform-origin:0 0;transition:transform .16s ease}',
225
+ '.memp .tree-edges{position:absolute;inset:0;overflow:visible;pointer-events:none}',
226
+ '.memp .edge{fill:none;stroke:color-mix(in srgb,var(--dsw-alias-label-secondary) 40%,transparent);stroke-width:1.2;transition:opacity .15s ease,stroke .15s ease,stroke-width .15s ease}',
227
+ '.memp .edge.active{stroke:var(--dsw-alias-brand-primary);stroke-width:1.8;opacity:.95}',
228
+ '.memp .tree-canvas.focused .edge:not(.active){opacity:.28}',
229
+ '.memp .corr-edge{fill:none;stroke:#D9A441;stroke-width:1.25;stroke-dasharray:4 3;opacity:.5;transition:opacity .15s ease,stroke-width .15s ease}',
230
+ '.memp .corr-edge.active{opacity:1;stroke-width:2;stroke-dasharray:none}',
231
+ '.memp .tree-canvas.focused .corr-edge:not(.active){opacity:.14}',
232
+ '.memp .corr-dot{fill:#D9A441;opacity:.6;transition:opacity .15s ease}',
233
+ '.memp .corr-dot.active{opacity:1}',
234
+ '.memp .tree-node{position:absolute;box-sizing:border-box;border:1px solid var(--dsw-alias-border-l1);border-radius:11px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);cursor:pointer;user-select:none;transition:border-color .14s ease,box-shadow .14s ease,opacity .14s ease,background .14s ease;animation:memNodeIn .2s ease both}',
235
+ '@keyframes memNodeIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}',
236
+ '.memp .tree-node.root{display:flex;align-items:center;gap:7px;padding:0 10px;border-color:color-mix(in srgb,var(--dsw-alias-brand-primary) 55%,var(--dsw-alias-border-l1));background:linear-gradient(145deg,color-mix(in srgb,var(--dsw-alias-brand-primary) 16%,var(--dsw-alias-bg-layer-1)),var(--dsw-alias-bg-layer-1) 72%);box-shadow:0 6px 18px color-mix(in srgb,var(--dsw-alias-brand-primary) 13%,transparent);cursor:default}',
237
+ '.memp .tree-node.root .root-icon{display:inline-flex;color:var(--dsw-alias-brand-primary);flex:none}',
238
+ '.memp .tree-node.root b{display:block;font-size:13px;line-height:1.2}',
239
+ '.memp .tree-node.root span{display:block;font-size:10.5px;color:var(--dsw-alias-label-secondary);white-space:nowrap}',
240
+ '.memp .tree-node.scope{display:flex;align-items:center;gap:7px;padding:0 10px;background:linear-gradient(120deg,var(--dsw-alias-bg-layer-1),color-mix(in srgb,var(--dsw-alias-brand-primary) 5%,var(--dsw-alias-bg-layer-1)))}',
241
+ '.memp .tree-node.scope:hover,.memp .tree-node.kind:hover{border-color:color-mix(in srgb,var(--dsw-alias-brand-primary) 60%,var(--dsw-alias-border-l1))}',
242
+ '.memp .tn-ico{flex:none;width:20px;height:20px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;font-size:10.5px;font-weight:600;background:color-mix(in srgb,var(--dsw-alias-brand-primary) 14%,var(--dsw-alias-bg-layer-2));color:var(--dsw-alias-brand-primary)}',
243
+ '.memp .tn-scope{flex:1;min-width:0;font-size:12px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
244
+ '.memp .tn-count{flex:none;font-size:10.5px;color:var(--dsw-alias-label-secondary);border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:0 6px;line-height:1.6;background:var(--dsw-alias-bg-layer-2)}',
245
+ '.memp .tn-caret{flex:none;font-size:9px;color:var(--dsw-alias-label-secondary);opacity:.8}',
246
+ '.memp .tree-node.collapsed{border-style:dashed}',
247
+ '.memp .tree-node.kind{display:flex;align-items:center;gap:6px;padding:0 9px;border-radius:9px;border-left:3px solid var(--k)}',
248
+ '.memp .tree-node.kind .tn-name{flex:1;min-width:0;font-size:11.5px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
249
+ '.memp .tree-node.kind .tdot{width:6px;height:6px;border-radius:50%;background:var(--k);flex:none}',
250
+ '.memp .tree-node.record{padding:6px 9px 6px 12px;display:flex;flex-direction:column;gap:4px;box-shadow:0 1px 2px rgba(0,0,0,.04)}',
251
+ '.memp .tree-node.record::before{content:"";position:absolute;left:0;top:8px;bottom:8px;width:3px;border-radius:999px;background:var(--k);opacity:.85}',
252
+ '.memp .tree-node.record:hover{border-color:var(--k);box-shadow:0 6px 16px color-mix(in srgb,var(--k) 16%,transparent)}',
253
+ '.memp .tree-node.record.selected{border-color:var(--dsw-alias-brand-primary);box-shadow:0 0 0 2px color-mix(in srgb,var(--dsw-alias-brand-primary) 22%,transparent),0 8px 20px rgba(0,0,0,.10)}',
254
+ '.memp .tree-node.record.related{border-color:color-mix(in srgb,var(--k) 70%,var(--dsw-alias-border-l1))}',
255
+ '.memp .tree-node.record.miss{opacity:.28}',
256
+ '.memp .tree-node.record.match{border-color:var(--dsw-alias-brand-primary);box-shadow:0 0 0 1px color-mix(in srgb,var(--dsw-alias-brand-primary) 32%,transparent)}',
257
+ '.memp .tree-canvas.focused .tree-node.record:not(.related){opacity:.55}',
258
+ '.memp .tn-head{display:flex;align-items:center;gap:5px;min-width:0;font-size:10.5px;color:var(--dsw-alias-label-secondary)}',
259
+ '.memp .tn-head .tdot{width:6px;height:6px;border-radius:50%;background:var(--k);flex:none}',
260
+ '.memp .tn-kind{font-weight:600;color:var(--dsw-alias-label-primary);letter-spacing:.02em;flex:none}',
261
+ '.memp .tn-badge{border-radius:999px;padding:0 5px;line-height:1.55;font-size:9.5px;border:1px solid transparent;flex:none}',
262
+ '.memp .tn-badge.corr{color:color-mix(in srgb,#D9A441 62%,var(--dsw-alias-label-primary));background:color-mix(in srgb,#D9A441 14%,transparent);border-color:color-mix(in srgb,#D9A441 35%,transparent)}',
263
+ '.memp .tn-badge.old{color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-border-l1)}',
264
+ '.memp .tn-time{margin-left:auto;flex:none;font-size:9.5px;opacity:.75}',
265
+ '.memp .tn-content{font-size:11.5px;line-height:1.45;color:var(--dsw-alias-label-secondary);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;word-break:break-word}',
266
+ '.memp .tree-empty{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:8px;color:var(--dsw-alias-label-secondary);font-size:12.5px;line-height:1.6;text-align:center;padding:24px;z-index:1}',
267
+ '.memp .tree-empty .big{font-size:22px;opacity:.65}',
268
+ '.memp .tree-empty button{padding:4px 12px;font-size:12px}',
269
+ '.memp .tree-zoom{position:absolute;right:10px;bottom:10px;display:flex;align-items:center;gap:1px;padding:3px;border:1px solid var(--dsw-alias-border-l1);border-radius:9px;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1) 88%,transparent);backdrop-filter:blur(6px);box-shadow:0 4px 14px rgba(0,0,0,.12);z-index:3}',
270
+ '.memp .tree-zoom button{background:none;border:0;padding:2px 8px;border-radius:6px;font-size:12px;color:var(--dsw-alias-label-secondary)}',
271
+ '.memp .tree-zoom button:hover{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-brand-primary)}',
272
+ '.memp .tree-zoom .zoomval{font-size:10.5px;min-width:38px;text-align:center;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}',
273
+ '.memp .tree-legend{position:absolute;left:10px;bottom:10px;display:flex;gap:10px;align-items:center;font-size:10.5px;color:var(--dsw-alias-label-secondary);padding:3px 9px;border-radius:999px;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1) 88%,transparent);border:1px solid var(--dsw-alias-border-l1);backdrop-filter:blur(6px);z-index:2;pointer-events:none}',
274
+ '.memp .tree-legend .line{display:inline-block;width:18px;height:0;border-top:1.5px dashed #D9A441;margin-right:4px;vertical-align:middle}',
275
+ '.memp .tree-detail{position:absolute;z-index:4;top:10px;left:10px;bottom:10px;width:min(322px,calc(100% - 20px));display:flex;flex-direction:column;gap:10px;padding:12px;border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1) 96%,transparent);backdrop-filter:blur(10px);box-shadow:0 16px 42px rgba(0,0,0,.22);overflow:auto;font-size:11.5px;scrollbar-width:thin;scrollbar-color:color-mix(in srgb,var(--dsw-alias-label-secondary) 30%,transparent) transparent}',
276
+ '.memp .tree-detail::-webkit-scrollbar{width:8px}',
277
+ '.memp .tree-detail::-webkit-scrollbar-thumb{background:color-mix(in srgb,var(--dsw-alias-label-secondary) 30%,transparent);border-radius:999px;border:2px solid transparent;background-clip:padding-box}',
278
+ '.memp .td-head{display:flex;align-items:center;gap:6px}',
279
+ '.memp .td-head .td-title{font-weight:600;font-size:12px}',
280
+ '.memp .td-close{margin-left:auto;background:none;border:0;font-size:15px;line-height:1;padding:2px 4px;color:var(--dsw-alias-label-secondary)}',
281
+ '.memp .td-close:hover{color:var(--dsw-alias-brand-primary)}',
282
+ '.memp .td-scope{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--dsw-alias-label-secondary);padding-bottom:8px;border-bottom:1px solid var(--dsw-alias-border-l1);min-width:0}',
283
+ '.memp .td-scope .tn-scope{font-size:11px;font-weight:500}',
284
+ '.memp .td-content{font-size:12.5px;line-height:1.62;white-space:pre-wrap;word-break:break-word;color:var(--dsw-alias-label-primary)}',
285
+ '.memp .td-tags{display:flex;flex-wrap:wrap;gap:4px}',
286
+ '.memp .td-meta{display:flex;flex-direction:column;gap:5px;font-size:10.5px;color:var(--dsw-alias-label-secondary);padding-top:8px;border-top:1px solid var(--dsw-alias-border-l1)}',
287
+ '.memp .td-meta .rowline{display:flex;align-items:center;gap:6px;min-width:0}',
288
+ '.memp .td-meta .rowline b{font-weight:500;color:var(--dsw-alias-label-primary);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
289
+ '.memp .td-impbar{flex:1;height:4px;border-radius:999px;background:var(--dsw-alias-bg-layer-2);overflow:hidden}',
290
+ '.memp .td-impbar i{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,color-mix(in srgb,var(--dsw-alias-brand-primary) 45%,transparent),var(--dsw-alias-brand-primary))}',
291
+ '.memp .td-id{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:9.5px;padding:1px 5px;border-radius:5px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-2);cursor:pointer;user-select:all;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
292
+ '.memp .td-rel{display:flex;flex-direction:column;gap:5px;padding-top:8px;border-top:1px solid var(--dsw-alias-border-l1)}',
293
+ '.memp .td-rel-label{font-size:10px;color:var(--dsw-alias-label-secondary);letter-spacing:.04em}',
294
+ '.memp .td-rel-btn{display:flex;align-items:flex-start;gap:6px;text-align:left;padding:6px 8px;border-radius:8px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);font-size:10.5px;line-height:1.45}',
295
+ '.memp .td-rel-dir{flex:none;color:color-mix(in srgb,#D9A441 62%,var(--dsw-alias-label-primary));font-weight:600}',
296
+ '.memp .td-rel-text{color:var(--dsw-alias-label-secondary);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;word-break:break-word}',
297
+ '@media (max-width:620px){.memp .tree-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.memp .tree-toolbar input[type=text]{max-width:none}}',
189
298
  ].join('')
190
299
 
191
300
  async function api(method, body) {
@@ -220,6 +329,272 @@ window.__ModuleLoader__.load({
220
329
  return scope
221
330
  }
222
331
 
332
+ /** 记忆类型 → 中文名 + 树里的强调色(与宿主主题无关的固定色相,底色用 color-mix 自适应)。 */
333
+ const KIND_ORDER = ['fact', 'decision', 'preference', 'procedure', 'note', 'rule']
334
+ const KIND_META = {
335
+ fact: { label: '事实', color: '#5B8DEF' },
336
+ decision: { label: '决策', color: '#D99A2B' },
337
+ preference: { label: '偏好', color: '#D868A8' },
338
+ procedure: { label: '流程', color: '#3FAE7A' },
339
+ note: { label: '笔记', color: '#7C8AA0' },
340
+ rule: { label: '规则', color: '#9B6BE0' },
341
+ }
342
+
343
+ function kindMeta(kind) {
344
+ return KIND_META[kind] || { label: String(kind), color: '#8B93A7' }
345
+ }
346
+
347
+ function kindRank(kind) {
348
+ const index = KIND_ORDER.indexOf(kind)
349
+ return index < 0 ? KIND_ORDER.length : index
350
+ }
351
+
352
+ function scopeRank(scope) {
353
+ if (scope === 'global') return 0
354
+ if (scope.startsWith('project:')) return 1
355
+ if (scope.startsWith('session:')) return 2
356
+ return 3
357
+ }
358
+
359
+ /** 作用域类型的一字记号(全 / 项 / 会 / 自),比抽象图标更好认。 */
360
+ function scopeGlyph(scope) {
361
+ if (scope === 'global') return '全'
362
+ if (scope.startsWith('project:')) return '项'
363
+ if (scope.startsWith('session:')) return '会'
364
+ return '自'
365
+ }
366
+
367
+ /** 紧凑时间:今天只给时分,其它日期给月/日。 */
368
+ function shortTime(ts) {
369
+ if (!ts) return ''
370
+ const date = new Date(ts)
371
+ const pad = (n) => String(n).padStart(2, '0')
372
+ const now = new Date()
373
+ if (date.toDateString() === now.toDateString()) return `${pad(date.getHours())}:${pad(date.getMinutes())}`
374
+ return `${date.getMonth() + 1}/${date.getDate()}`
375
+ }
376
+
377
+ function excerpt(text, limit = 64) {
378
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim()
379
+ return flat.length > limit ? `${flat.slice(0, limit)}…` : flat
380
+ }
381
+
382
+ /**
383
+ * 记忆树的**纯布局**:输入记录,输出节点的绝对坐标、层级连线与修正连线。
384
+ *
385
+ * 层级固定为 root → scope → kind → record,列间平推、叶子纵向堆叠;父节点在自己
386
+ * 子树的高度里居中。折叠一个 scope/kind 只是不展开它下面的节点,布局仍然成立。
387
+ * 修正关系不改变层级(一条记录只会修正同一个作用域里的旧记录),所以单独作为
388
+ * 曲线叠在右侧,避免把树本身拧成图。
389
+ *
390
+ * 这个函数不碰 DOM,测试可以直接断言节点与连线。
391
+ */
392
+ const TREE_METRICS = {
393
+ rootW: 100, rootH: 48,
394
+ scopeW: 202, scopeH: 42,
395
+ kindW: 128, kindH: 30,
396
+ recordW: 236, recordH: 56,
397
+ padX: 26, padY: 24,
398
+ colGap: 54, leafGap: 8, groupGap: 16,
399
+ arcRoom: 104,
400
+ }
401
+
402
+ function buildMemoryTree(records, options = {}) {
403
+ const M = TREE_METRICS
404
+ const labels = options.labels || {}
405
+ const collapsed = options.collapsed instanceof Set ? options.collapsed : new Set(options.collapsed || [])
406
+ const activeKinds = options.activeKinds instanceof Set ? options.activeKinds : new Set(KIND_ORDER)
407
+ const scopeFilter = typeof options.scopeFilter === 'string' ? options.scopeFilter : ''
408
+ const query = String(options.query ?? '').trim().toLowerCase()
409
+
410
+ const byScope = new Map()
411
+ for (const rec of records) {
412
+ if (!activeKinds.has(rec.kind)) continue
413
+ if (scopeFilter !== '' && rec.scope !== scopeFilter) continue
414
+ let kinds = byScope.get(rec.scope)
415
+ if (kinds === undefined) { kinds = new Map(); byScope.set(rec.scope, kinds) }
416
+ let list = kinds.get(rec.kind)
417
+ if (list === undefined) { list = []; kinds.set(rec.kind, list) }
418
+ list.push(rec)
419
+ }
420
+
421
+ const scopeGroups = []
422
+ for (const [scope, kindMap] of byScope) {
423
+ const kinds = []
424
+ for (const [kind, list] of kindMap) {
425
+ kinds.push({ kind, records: list.slice().sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0)) })
426
+ }
427
+ kinds.sort((a, b) => kindRank(a.kind) - kindRank(b.kind) || String(a.kind).localeCompare(String(b.kind)))
428
+ let count = 0
429
+ for (const entry of kinds) count += entry.records.length
430
+ scopeGroups.push({ scope, label: scopeLabel(scope, labels), kinds, count })
431
+ }
432
+ scopeGroups.sort((a, b) => scopeRank(a.scope) - scopeRank(b.scope) || a.label.localeCompare(b.label, 'zh'))
433
+
434
+ const scopeKey = (scope) => `scope:${scope}`
435
+ const kindKey = (scope, kind) => `kind:${scope}|${kind}`
436
+ const recordKey = (id) => `record:${id}`
437
+
438
+ const scopeBlocks = scopeGroups.map((group) => {
439
+ const collapsedScope = collapsed.has(scopeKey(group.scope))
440
+ const kindBlocks = collapsedScope ? [] : group.kinds.map((entry) => {
441
+ const collapsedKind = collapsed.has(kindKey(group.scope, entry.kind))
442
+ const recordsHeight = entry.records.length * M.recordH
443
+ + Math.max(0, entry.records.length - 1) * M.leafGap
444
+ return {
445
+ ...entry,
446
+ collapsed: collapsedKind,
447
+ height: collapsedKind ? M.kindH : Math.max(M.kindH, recordsHeight),
448
+ }
449
+ })
450
+ let body = 0
451
+ for (const entry of kindBlocks) body += entry.height
452
+ const height = collapsedScope
453
+ ? M.scopeH
454
+ : Math.max(M.scopeH, body + Math.max(0, kindBlocks.length - 1) * M.groupGap)
455
+ return { ...group, collapsed: collapsedScope, kindBlocks, height }
456
+ })
457
+
458
+ let scopesHeight = 0
459
+ for (const block of scopeBlocks) scopesHeight += block.height
460
+ if (scopeBlocks.length > 1) scopesHeight += (scopeBlocks.length - 1) * M.groupGap
461
+ const contentHeight = Math.max(M.rootH, scopesHeight)
462
+
463
+ const nodes = []
464
+ const nodeByKey = new Map()
465
+ const recordNode = new Map()
466
+ const edges = []
467
+ const corrections = []
468
+ const addNode = (node) => { nodes.push(node); nodeByKey.set(node.key, node) }
469
+
470
+ const rootX = M.padX
471
+ const rootY = M.padY + (contentHeight - M.rootH) / 2
472
+ const scopeX = rootX + M.rootW + M.colGap
473
+ const kindX = scopeX + M.scopeW + M.colGap
474
+ const recordX = kindX + M.kindW + M.colGap
475
+ let visibleRecords = 0
476
+
477
+ addNode({
478
+ key: 'root', type: 'root',
479
+ x: rootX, y: rootY, w: M.rootW, h: M.rootH,
480
+ count: scopeGroups.reduce((sum, group) => sum + group.count, 0),
481
+ })
482
+
483
+ let top = M.padY
484
+ for (const scope of scopeBlocks) {
485
+ const sKey = scopeKey(scope.scope)
486
+ addNode({
487
+ key: sKey, type: 'scope',
488
+ x: scopeX, y: top + (scope.height - M.scopeH) / 2, w: M.scopeW, h: M.scopeH,
489
+ scope: scope.scope, label: scope.label, count: scope.count, collapsed: scope.collapsed,
490
+ })
491
+ edges.push({ key: `root>${sKey}`, type: 'tree', fromKey: 'root', toKey: sKey, toType: 'scope', toId: scope.scope })
492
+
493
+ let kindTop = top
494
+ for (const entry of scope.kindBlocks) {
495
+ const kKey = kindKey(scope.scope, entry.kind)
496
+ addNode({
497
+ key: kKey, type: 'kind',
498
+ x: kindX, y: kindTop + (entry.height - M.kindH) / 2, w: M.kindW, h: M.kindH,
499
+ scope: scope.scope, kind: entry.kind, count: entry.records.length, collapsed: entry.collapsed,
500
+ })
501
+ edges.push({
502
+ key: `${sKey}>${kKey}`, type: 'tree',
503
+ fromKey: sKey, toKey: kKey, toType: 'kind', toId: `${scope.scope}|${entry.kind}`,
504
+ })
505
+ if (!entry.collapsed) {
506
+ const recordsHeight = entry.records.length * M.recordH
507
+ + Math.max(0, entry.records.length - 1) * M.leafGap
508
+ const recordTop = kindTop + (entry.height - recordsHeight) / 2
509
+ entry.records.forEach((rec, index) => {
510
+ const rKey = recordKey(rec.id)
511
+ const y = recordTop + index * (M.recordH + M.leafGap)
512
+ addNode({
513
+ key: rKey, type: 'record',
514
+ x: recordX, y, w: M.recordW, h: M.recordH,
515
+ scope: rec.scope, kind: rec.kind, rec,
516
+ })
517
+ recordNode.set(rec.id, rKey)
518
+ edges.push({ key: `${kKey}>${rKey}`, type: 'tree', fromKey: kKey, toKey: rKey, toType: 'record', toId: rec.id })
519
+ visibleRecords += 1
520
+ })
521
+ }
522
+ kindTop += entry.height + M.groupGap
523
+ }
524
+ top += scope.height + M.groupGap
525
+ }
526
+
527
+ // 修正连线要等**所有**节点都落位后再算:新记录排在旧记录前面(按 updatedAt 倒序),
528
+ // 单遍循环时还看不到被修正的旧记录。
529
+ for (const node of nodes) {
530
+ if (node.type !== 'record') continue
531
+ const rec = node.rec
532
+ const oldKey = rec.supersedes ? recordNode.get(rec.supersedes) : undefined
533
+ if (oldKey === undefined) continue
534
+ corrections.push({
535
+ key: `corr:${rec.id}>${rec.supersedes}`,
536
+ fromKey: node.key, toKey: oldKey, fromId: rec.id, toId: rec.supersedes,
537
+ })
538
+ }
539
+
540
+ const matches = new Set()
541
+ if (query !== '') {
542
+ for (const node of nodes) {
543
+ if (node.type !== 'record') continue
544
+ const rec = node.rec
545
+ const haystack = [
546
+ rec.content, rec.kind, kindMeta(rec.kind).label,
547
+ (rec.tags || []).join(' '), node.scope, scopeLabel(node.scope, labels),
548
+ ].join(' ').toLowerCase()
549
+ if (haystack.includes(query)) matches.add(rec.id)
550
+ }
551
+ }
552
+
553
+ const visibleKinds = new Set()
554
+ for (const group of scopeGroups) for (const entry of group.kinds) visibleKinds.add(entry.kind)
555
+ const width = recordX + M.recordW + M.padX + M.arcRoom
556
+ const height = M.padY * 2 + contentHeight
557
+
558
+ return {
559
+ nodes, edges, corrections, nodeByKey, recordNode, matches,
560
+ width, height,
561
+ counts: {
562
+ records: visibleRecords,
563
+ scopes: scopeGroups.length,
564
+ kinds: visibleKinds.size,
565
+ corrections: corrections.length,
566
+ },
567
+ }
568
+ }
569
+
570
+ /** 层级连线:从父节点右缘到子节点左缘,水平方向用三次贝塞尔。 */
571
+ function treeEdgePath(from, to) {
572
+ const x1 = from.x + from.w
573
+ const y1 = from.y + from.h / 2
574
+ const x2 = to.x
575
+ const y2 = to.y + to.h / 2
576
+ const bend = Math.max(18, Math.abs(x2 - x1) * 0.48)
577
+ return `M${x1},${y1} C${x1 + bend},${y1} ${x2 - bend},${y2} ${x2},${y2}`
578
+ }
579
+
580
+ /** 修正连线:两端都从卡片右缘出,向右侧鼓出一条弧,不穿过叶子文本。 */
581
+ function treeCorrectionPath(from, to) {
582
+ const x1 = from.x + from.w
583
+ const y1 = from.y + from.h / 2
584
+ const x2 = to.x + to.w
585
+ const y2 = to.y + to.h / 2
586
+ const bend = 34 + Math.min(66, Math.abs(y2 - y1) * 0.09)
587
+ return `M${x1},${y1} C${x1 + bend},${y1} ${x2 + bend},${y2} ${x2},${y2}`
588
+ }
589
+
590
+ function KindDot({ kind }) {
591
+ return h('span', {
592
+ className: 'tdot',
593
+ style: { '--k': kindMeta(kind).color },
594
+ 'aria-hidden': 'true',
595
+ })
596
+ }
597
+
223
598
  function RecordCard({ rec, vectorOn, labels, onSaved, onDeleted }) {
224
599
  // collapsed by default: the list stays scannable, full text on demand
225
600
  const [expanded, setExpanded] = React.useState(false)
@@ -348,6 +723,514 @@ window.__ModuleLoader__.load({
348
723
  )
349
724
  }
350
725
 
726
+ /** 树上的一条记忆:内容两行封顶,类型/修正/时间放在头行。 */
727
+ function TreeRecordNode({ node, selected, related, miss, match, onSelect, onHover }) {
728
+ const rec = node.rec
729
+ const meta = kindMeta(rec.kind)
730
+ const classes = ['tree-node', 'record']
731
+ if (selected) classes.push('selected')
732
+ if (related) classes.push('related')
733
+ if (miss) classes.push('miss')
734
+ if (match) classes.push('match')
735
+ const pick = () => onSelect(rec.id)
736
+ return h('div', {
737
+ className: classes.join(' '),
738
+ style: { left: node.x, top: node.y, width: node.w, height: node.h, '--k': meta.color },
739
+ title: rec.content,
740
+ role: 'button',
741
+ tabIndex: 0,
742
+ 'aria-pressed': Boolean(selected),
743
+ onClick: pick,
744
+ onKeyDown: (event) => {
745
+ if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); pick() }
746
+ },
747
+ onMouseEnter: () => onHover(rec.id),
748
+ onMouseLeave: () => onHover(null),
749
+ onFocus: () => onHover(rec.id),
750
+ onBlur: () => onHover(null),
751
+ },
752
+ h('div', { className: 'tn-head' },
753
+ h(KindDot, { kind: rec.kind }),
754
+ h('span', { className: 'tn-kind' }, meta.label),
755
+ rec.supersedes
756
+ ? h('span', { className: 'tn-badge corr', title: `这条记录修正了旧记录 #${rec.supersedes}` }, '修正版')
757
+ : null,
758
+ rec.supersededBy
759
+ ? h('span', { className: 'tn-badge old', title: `已被 #${rec.supersededBy} 修正` }, '已修正')
760
+ : null,
761
+ h('span', { className: 'tn-time' }, shortTime(rec.updatedAt)),
762
+ ),
763
+ h('div', { className: 'tn-content' }, rec.content),
764
+ )
765
+ }
766
+
767
+ /** 树上的一个作用域:点击折叠/展开。 */
768
+ function TreeScopeNode({ node, onToggle }) {
769
+ return h('div', {
770
+ className: 'tree-node scope' + (node.collapsed ? ' collapsed' : ''),
771
+ style: { left: node.x, top: node.y, width: node.w, height: node.h },
772
+ role: 'button',
773
+ tabIndex: 0,
774
+ 'aria-expanded': !node.collapsed,
775
+ title: `${node.scope} · 点击${node.collapsed ? '展开' : '折叠'}`,
776
+ onClick: () => onToggle(node.scope),
777
+ onKeyDown: (event) => {
778
+ if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); onToggle(node.scope) }
779
+ },
780
+ },
781
+ h('span', { className: 'tn-ico' }, scopeGlyph(node.scope)),
782
+ h('span', { className: 'tn-scope' }, node.label),
783
+ h('span', { className: 'tn-count' }, String(node.count)),
784
+ h('span', { className: 'tn-caret' }, node.collapsed ? '▸' : '▾'),
785
+ )
786
+ }
787
+
788
+ /** 树上的一个类型分组:点击折叠/展开。 */
789
+ function TreeKindNode({ node, onToggle }) {
790
+ const meta = kindMeta(node.kind)
791
+ return h('div', {
792
+ className: 'tree-node kind' + (node.collapsed ? ' collapsed' : ''),
793
+ style: { left: node.x, top: node.y, width: node.w, height: node.h, '--k': meta.color },
794
+ role: 'button',
795
+ tabIndex: 0,
796
+ 'aria-expanded': !node.collapsed,
797
+ title: `${node.kind} · ${meta.label} · 点击${node.collapsed ? '展开' : '折叠'}`,
798
+ onClick: () => onToggle(node.scope, node.kind),
799
+ onKeyDown: (event) => {
800
+ if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); onToggle(node.scope, node.kind) }
801
+ },
802
+ },
803
+ h('span', { className: 'tdot' }),
804
+ h('span', { className: 'tn-name' }, meta.label),
805
+ h('span', { className: 'tn-count' }, String(node.count)),
806
+ h('span', { className: 'tn-caret' }, node.collapsed ? '▸' : '▾'),
807
+ )
808
+ }
809
+
810
+ function TreeRootNode({ node }) {
811
+ return h('div', {
812
+ className: 'tree-node root',
813
+ style: { left: node.x, top: node.y, width: node.w, height: node.h },
814
+ title: '所有作用域的记忆',
815
+ },
816
+ h('span', { className: 'root-icon' }, h(NavLineIcon, { size: 19 })),
817
+ h('span', null,
818
+ h('b', null, '记忆'),
819
+ h('span', null, `${node.count} 条`),
820
+ ),
821
+ )
822
+ }
823
+
824
+ /** 右侧详情抽屉:全文、标签、重要度、id,以及修正关系的双向入口。 */
825
+ function TreeDetail({ rec, labels, byId, onClose, onJump }) {
826
+ const [copied, setCopied] = React.useState(false)
827
+ const meta = kindMeta(rec.kind)
828
+ const older = rec.supersedes ? byId.get(rec.supersedes) : undefined
829
+ const newer = rec.supersededBy ? byId.get(rec.supersededBy) : undefined
830
+ const copyId = () => {
831
+ try {
832
+ if (navigator?.clipboard?.writeText) void navigator.clipboard.writeText(rec.id)
833
+ setCopied(true)
834
+ setTimeout(() => setCopied(false), 1200)
835
+ } catch { /* 剪贴板不可用时忽略 */ }
836
+ }
837
+ return h('aside', { className: 'tree-detail', 'aria-label': '记忆详情' },
838
+ h('div', { className: 'td-head' },
839
+ h(KindDot, { kind: rec.kind }),
840
+ h('span', { className: 'td-title' }, meta.label),
841
+ h('span', { className: 'tn-count' }, rec.kind),
842
+ h('button', { className: 'td-close', title: '关闭详情', onClick: onClose }, '×'),
843
+ ),
844
+ h('div', { className: 'td-scope' },
845
+ h('span', { className: 'tn-ico' }, scopeGlyph(rec.scope)),
846
+ h('span', { className: 'tn-scope' }, scopeLabel(rec.scope, labels)),
847
+ ),
848
+ h('div', { className: 'td-content' }, rec.content),
849
+ rec.tags && rec.tags.length > 0
850
+ ? h('div', { className: 'td-tags' }, rec.tags.map((tag) => h('span', { className: 'tag', key: tag }, tag)))
851
+ : null,
852
+ h('div', { className: 'td-meta' },
853
+ h('div', { className: 'rowline' },
854
+ h('span', null, '重要度'),
855
+ h('span', { className: 'td-impbar' }, h('i', { style: { width: `${Math.round((Number(rec.importance) || 0) * 100)}%` } })),
856
+ h('span', null, `${Math.round((Number(rec.importance) || 0) * 100)}%`),
857
+ ),
858
+ h('div', { className: 'rowline' }, h('span', null, '创建'), h('b', null, fmtTime(rec.createdAt))),
859
+ h('div', { className: 'rowline' }, h('span', null, '更新'), h('b', null, fmtTime(rec.updatedAt))),
860
+ h('div', { className: 'rowline' },
861
+ h('span', null, 'id'),
862
+ h('code', { className: 'td-id', title: '点击复制完整 id', onClick: copyId }, rec.id),
863
+ copied ? h('span', { className: 'meta-done' }, '已复制') : null,
864
+ ),
865
+ ),
866
+ h('div', { className: 'td-rel' },
867
+ h('span', { className: 'td-rel-label' }, '修正关系'),
868
+ older
869
+ ? h('button', { className: 'td-rel-btn', title: `跳转到被修正的旧记录 #${older.id}`, onClick: () => onJump(older.id) },
870
+ h('span', { className: 'td-rel-dir' }, '修正自'),
871
+ h('span', { className: 'td-rel-text' }, excerpt(older.content)),
872
+ )
873
+ : null,
874
+ newer
875
+ ? h('button', { className: 'td-rel-btn', title: `跳转到修正它的新记录 #${newer.id}`, onClick: () => onJump(newer.id) },
876
+ h('span', { className: 'td-rel-dir' }, '已被修正为'),
877
+ h('span', { className: 'td-rel-text' }, excerpt(newer.content)),
878
+ )
879
+ : null,
880
+ !older && !newer ? h('span', { className: 'muted' }, '这条记忆没有修正关系。') : null,
881
+ older && newer
882
+ ? h('span', { className: 'muted' }, '这条记录处在一条修正链的中间。')
883
+ : null,
884
+ ),
885
+ )
886
+ }
887
+
888
+ /**
889
+ * 「记忆树」标签页。
890
+ *
891
+ * 层级:记忆 → 作用域 → 类型 → 记录。三个维度正好对应记忆的归属(scope)、
892
+ * 语义(kind)与内容;修正关系是跨记录的点对点关系,用金色虚线单独画在树的右侧,
893
+ * 悬停/选中任意一端时两端与整条链一起点亮。
894
+ */
895
+ function MemoryTreeTab({ records, scopes, loading, error, onRefresh }) {
896
+ const [query, setQuery] = React.useState('')
897
+ const [scopeFilter, setScopeFilter] = React.useState('')
898
+ const [kindFilter, setKindFilter] = React.useState(null)
899
+ const [collapsed, setCollapsed] = React.useState(new Set())
900
+ const [selectedId, setSelectedId] = React.useState(null)
901
+ const [hoverId, setHoverId] = React.useState(null)
902
+ const [showCorrections, setShowCorrections] = React.useState(true)
903
+ const [zoom, setZoom] = React.useState(1)
904
+ const [autoFitDone, setAutoFitDone] = React.useState(false)
905
+ const wrapRef = React.useRef(null)
906
+
907
+ const labels = {}
908
+ for (const entry of scopes) {
909
+ if (entry && typeof entry.scope === 'string' && typeof entry.label === 'string') labels[entry.scope] = entry.label
910
+ }
911
+ const recordById = new Map()
912
+ const kindCounts = new Map()
913
+ const presentKinds = []
914
+ const presentScopes = []
915
+ for (const rec of records) {
916
+ recordById.set(rec.id, rec)
917
+ kindCounts.set(rec.kind, (kindCounts.get(rec.kind) || 0) + 1)
918
+ if (!presentKinds.includes(rec.kind)) presentKinds.push(rec.kind)
919
+ if (!presentScopes.includes(rec.scope)) presentScopes.push(rec.scope)
920
+ }
921
+ presentKinds.sort((a, b) => kindRank(a) - kindRank(b) || String(a).localeCompare(String(b)))
922
+ presentScopes.sort((a, b) => scopeRank(a) - scopeRank(b) || scopeLabel(a, labels).localeCompare(scopeLabel(b, labels), 'zh'))
923
+
924
+ const allKinds = new Set(presentKinds)
925
+ const activeKinds = kindFilter === null
926
+ ? allKinds
927
+ : new Set(presentKinds.filter((kind) => kindFilter.has(kind)))
928
+
929
+ const layout = buildMemoryTree(records, {
930
+ labels, collapsed, activeKinds, scopeFilter, query,
931
+ })
932
+
933
+ // 第一次拿到记录时把宽度缩到画布内:右侧的记录列默认不该被横向截断。
934
+ // 高度方向仍可滚动 —— 记忆很多时把整棵树压到一屏里会小到看不清。
935
+ React.useEffect(() => {
936
+ if (autoFitDone || layout.counts.records === 0) return
937
+ const wrap = wrapRef.current
938
+ const scroll = wrap && typeof wrap.querySelector === 'function' ? wrap.querySelector('.tree-scroll') : null
939
+ if (!scroll || scroll.clientWidth <= 0 || layout.width <= 0) return
940
+ const widthFit = (scroll.clientWidth - 28) / layout.width
941
+ if (widthFit < 0.99) setZoom(Math.max(0.62, Math.round(widthFit * 100) / 100))
942
+ setAutoFitDone(true)
943
+ }, [autoFitDone, layout.counts.records, layout.width])
944
+
945
+ // 根节点在整棵树的高度里居中;树比视口高时,首屏应该正好看到它,
946
+ // 而不是从最上面的作用域往下翻。
947
+ React.useEffect(() => {
948
+ if (!autoFitDone) return
949
+ const wrap = wrapRef.current
950
+ const scroll = wrap && typeof wrap.querySelector === 'function' ? wrap.querySelector('.tree-scroll') : null
951
+ const root = layout.nodeByKey.get('root')
952
+ if (!scroll || !root) return
953
+ const max = Math.max(0, scroll.scrollHeight - scroll.clientHeight)
954
+ const target = (root.y + root.h / 2) * zoom - scroll.clientHeight / 2
955
+ scroll.scrollTop = Math.max(0, Math.min(target, max))
956
+ }, [autoFitDone, zoom])
957
+
958
+ // 选中一条记忆时把它滚进视口:右侧详情是从「修正关系」里跳过来的,
959
+ // 目标可能在当前滚动范围之外。
960
+ React.useEffect(() => {
961
+ if (selectedId === null) return
962
+ const wrap = wrapRef.current
963
+ const scroll = wrap && typeof wrap.querySelector === 'function' ? wrap.querySelector('.tree-scroll') : null
964
+ const node = scroll ? scroll.querySelector('.tree-node.record.selected') : null
965
+ if (!scroll || !node) return
966
+ const top = node.offsetTop * zoom
967
+ const bottom = top + node.offsetHeight * zoom
968
+ const viewTop = scroll.scrollTop
969
+ const viewBottom = viewTop + scroll.clientHeight
970
+ if (top < viewTop + 12) scroll.scrollTop = Math.max(0, top - 12)
971
+ else if (bottom > viewBottom - 12) scroll.scrollTop = bottom - scroll.clientHeight + 12
972
+ }, [selectedId])
973
+
974
+ const focusId = hoverId || selectedId
975
+ const related = new Set()
976
+ if (focusId) {
977
+ related.add(focusId)
978
+ for (const correction of layout.corrections) {
979
+ if (correction.fromId === focusId) related.add(correction.toId)
980
+ if (correction.toId === focusId) related.add(correction.fromId)
981
+ }
982
+ }
983
+ const pathKeys = new Set()
984
+ for (const id of related) {
985
+ const rec = recordById.get(id)
986
+ if (rec) {
987
+ pathKeys.add(`scope:${rec.scope}`)
988
+ pathKeys.add(`kind:${rec.scope}|${rec.kind}`)
989
+ }
990
+ }
991
+ const edgeActive = (edge) => {
992
+ if (focusId === null) return false
993
+ if (edge.type === 'correction') return related.has(edge.fromId) || related.has(edge.toId)
994
+ if (edge.toType === 'record') return related.has(edge.toId)
995
+ if (edge.toType === 'kind' || edge.toType === 'scope') return pathKeys.has(edge.toKey)
996
+ return false
997
+ }
998
+
999
+ const toggleScope = (scope) => {
1000
+ const key = `scope:${scope}`
1001
+ setCollapsed((previous) => {
1002
+ const next = new Set(previous)
1003
+ if (next.has(key)) next.delete(key); else next.add(key)
1004
+ return next
1005
+ })
1006
+ }
1007
+ const toggleKind = (scope, kind) => {
1008
+ const key = `kind:${scope}|${kind}`
1009
+ setCollapsed((previous) => {
1010
+ const next = new Set(previous)
1011
+ if (next.has(key)) next.delete(key); else next.add(key)
1012
+ return next
1013
+ })
1014
+ }
1015
+ const toggleKindFilter = (kind) => {
1016
+ setKindFilter((previous) => {
1017
+ const next = previous === null ? new Set(presentKinds) : new Set(previous)
1018
+ if (next.has(kind)) next.delete(kind); else next.add(kind)
1019
+ return next
1020
+ })
1021
+ }
1022
+ const resetFilters = () => {
1023
+ setQuery('')
1024
+ setScopeFilter('')
1025
+ setKindFilter(null)
1026
+ setCollapsed(new Set())
1027
+ }
1028
+ const jumpTo = (id) => {
1029
+ // 从详情里跳修正链:清掉筛选并展开全部,否则目标可能正好被折叠/筛掉。
1030
+ setKindFilter(null)
1031
+ setScopeFilter('')
1032
+ setQuery('')
1033
+ setCollapsed(new Set())
1034
+ setSelectedId(id)
1035
+ setHoverId(null)
1036
+ setShowCorrections(true)
1037
+ }
1038
+ const stepZoom = (delta) => {
1039
+ setZoom((value) => Math.max(0.45, Math.min(1.6, Math.round((value + delta) * 100) / 100)))
1040
+ }
1041
+ const fitView = () => {
1042
+ try {
1043
+ const wrap = wrapRef.current
1044
+ const scroll = wrap && typeof wrap.querySelector === 'function' ? wrap.querySelector('.tree-scroll') : null
1045
+ if (!scroll || layout.width <= 0 || layout.height <= 0) { setZoom(1); return }
1046
+ const next = Math.min(
1047
+ (scroll.clientWidth - 28) / layout.width,
1048
+ Math.max((scroll.clientHeight - 28) / layout.height, 0.72),
1049
+ 1.15,
1050
+ )
1051
+ setZoom(Math.max(0.5, Math.min(1.6, Math.round(next * 100) / 100)))
1052
+ } catch { setZoom(1) }
1053
+ }
1054
+
1055
+ const selected = selectedId === null ? undefined : recordById.get(selectedId)
1056
+ const scopeItems = [{ value: '', label: '全部作用域' }]
1057
+ for (const scope of presentScopes) scopeItems.push({ value: scope, label: scopeLabel(scope, labels) })
1058
+ const correctionsTotal = records.reduce((sum, rec) => sum + (rec.supersedes ? 1 : 0), 0)
1059
+ const scopeTotal = new Set(records.map((rec) => rec.scope)).size
1060
+ const emptyText = records.length === 0
1061
+ ? (loading ? '正在加载记忆…' : '还没有记忆。去「记录」里新建一条,或让 Agent 用 memory_save 写一条。')
1062
+ : layout.counts.records === 0
1063
+ ? '当前筛选下没有记忆。'
1064
+ : ''
1065
+ const showEmpty = emptyText !== '' || (Boolean(error) && records.length === 0)
1066
+
1067
+ const stats = h('div', { className: 'tree-stats' },
1068
+ h('div', { className: 'stat' }, h('b', null, String(records.length)), h('span', null, '条记忆')),
1069
+ h('div', { className: 'stat' }, h('b', null, String(scopeTotal)), h('span', null, '个作用域')),
1070
+ h('div', { className: 'stat' }, h('b', null, String(presentKinds.length)), h('span', null, '种类型')),
1071
+ h('div', { className: 'stat' }, h('b', null, String(correctionsTotal)), h('span', null, '处修正')),
1072
+ )
1073
+
1074
+ const toolbar = h('div', { className: 'tree-toolbar' },
1075
+ h('input', {
1076
+ type: 'text',
1077
+ placeholder: '搜索内容、类型、标签或作用域',
1078
+ value: query,
1079
+ onChange: (event) => setQuery(event.target.value),
1080
+ }),
1081
+ h(Dropdown, {
1082
+ items: scopeItems,
1083
+ value: scopeFilter,
1084
+ disabled: loading,
1085
+ onChange: setScopeFilter,
1086
+ }),
1087
+ h('button', {
1088
+ className: 'kchip' + (showCorrections ? ' on' : ' off'),
1089
+ title: '显示 / 隐藏修正关系连线',
1090
+ onClick: () => setShowCorrections((value) => !value),
1091
+ }, h('span', { className: 'corr-swatch' }), '修正连线'),
1092
+ query.trim() !== ''
1093
+ ? h('span', { className: 'tree-matchinfo' }, `匹配 ${layout.matches.size} 条`)
1094
+ : null,
1095
+ h('span', { className: 'spacer' }),
1096
+ h('button', { onClick: () => setCollapsed(new Set()) }, '全部展开'),
1097
+ h('button', { onClick: () => setCollapsed(new Set(presentScopes.map((scope) => `scope:${scope}`))) }, '只看作用域'),
1098
+ h('button', { disabled: loading, onClick: onRefresh }, loading ? '刷新中…' : '刷新'),
1099
+ )
1100
+
1101
+ const kindbar = h('div', { className: 'kindbar' },
1102
+ h('span', { className: 'kindbar-label' }, '类型'),
1103
+ presentKinds.map((kind) => h('button', {
1104
+ key: kind,
1105
+ className: 'kchip' + (activeKinds.has(kind) ? '' : ' off'),
1106
+ style: { '--k': kindMeta(kind).color },
1107
+ title: `${kind} · ${kindMeta(kind).label}`,
1108
+ onClick: () => toggleKindFilter(kind),
1109
+ },
1110
+ h('span', { className: 'tdot' }),
1111
+ kindMeta(kind).label,
1112
+ h('b', null, String(kindCounts.get(kind) || 0)),
1113
+ )),
1114
+ presentKinds.length > 0 && presentKinds.every((kind) => activeKinds.has(kind))
1115
+ ? null
1116
+ : h('button', { className: 'linkbtn', onClick: () => setKindFilter(null) }, '恢复全部类型'),
1117
+ )
1118
+
1119
+ const nodes = []
1120
+ const add = (child) => { if (child !== null) nodes.push(child) }
1121
+ for (const node of layout.nodes) {
1122
+ if (node.type === 'root') {
1123
+ add(h(TreeRootNode, { key: node.key, node }))
1124
+ } else if (node.type === 'scope') {
1125
+ add(h(TreeScopeNode, { key: node.key, node, onToggle: toggleScope }))
1126
+ } else if (node.type === 'kind') {
1127
+ add(h(TreeKindNode, { key: node.key, node, onToggle: toggleKind }))
1128
+ } else {
1129
+ const rec = node.rec
1130
+ add(h(TreeRecordNode, {
1131
+ key: node.key,
1132
+ node,
1133
+ selected: rec.id === selectedId,
1134
+ related: related.has(rec.id),
1135
+ miss: query.trim() !== '' && !layout.matches.has(rec.id),
1136
+ match: query.trim() !== '' && layout.matches.has(rec.id),
1137
+ onSelect: (id) => setSelectedId((current) => current === id ? null : id),
1138
+ onHover: setHoverId,
1139
+ }))
1140
+ }
1141
+ }
1142
+
1143
+ const edgePaths = []
1144
+ for (const edge of layout.edges) {
1145
+ const from = layout.nodeByKey.get(edge.fromKey)
1146
+ const to = layout.nodeByKey.get(edge.toKey)
1147
+ if (!from || !to) continue
1148
+ edgePaths.push(h('path', {
1149
+ key: edge.key,
1150
+ className: 'edge' + (edgeActive(edge) ? ' active' : ''),
1151
+ d: treeEdgePath(from, to),
1152
+ }))
1153
+ }
1154
+ if (showCorrections) {
1155
+ for (const edge of layout.corrections) {
1156
+ const from = layout.nodeByKey.get(edge.fromKey)
1157
+ const to = layout.nodeByKey.get(edge.toKey)
1158
+ if (!from || !to) continue
1159
+ const active = edgeActive(edge)
1160
+ edgePaths.push(h('path', {
1161
+ key: edge.key,
1162
+ className: 'corr-edge' + (active ? ' active' : ''),
1163
+ d: treeCorrectionPath(from, to),
1164
+ }))
1165
+ edgePaths.push(h('circle', {
1166
+ key: `${edge.key}:dot`,
1167
+ className: 'corr-dot' + (active ? ' active' : ''),
1168
+ cx: to.x + to.w,
1169
+ cy: to.y + to.h / 2,
1170
+ r: 2.6,
1171
+ }))
1172
+ }
1173
+ }
1174
+
1175
+ const canvas = h('div', {
1176
+ className: 'tree-canvas' + (focusId !== null ? ' focused' : ''),
1177
+ style: { width: layout.width, height: layout.height, transform: `scale(${zoom})` },
1178
+ },
1179
+ h('svg', {
1180
+ className: 'tree-edges',
1181
+ width: layout.width,
1182
+ height: layout.height,
1183
+ viewBox: `0 0 ${layout.width} ${layout.height}`,
1184
+ 'aria-hidden': 'true',
1185
+ }, edgePaths),
1186
+ nodes,
1187
+ )
1188
+
1189
+ const treeWrap = h('div', { className: 'tree-wrap', ref: wrapRef },
1190
+ h('div', { className: 'tree-scroll' },
1191
+ h('div', {
1192
+ className: 'tree-zoomspace',
1193
+ style: { width: Math.ceil(layout.width * zoom), height: Math.ceil(layout.height * zoom) },
1194
+ }, canvas),
1195
+ ),
1196
+ showEmpty
1197
+ ? h('div', { className: 'tree-empty' },
1198
+ h('span', { className: 'big' }, '🌳'),
1199
+ h('span', null, emptyText || String(error)),
1200
+ emptyText === '当前筛选下没有记忆。'
1201
+ ? h('button', { onClick: resetFilters }, '清空筛选')
1202
+ : null,
1203
+ )
1204
+ : null,
1205
+ showEmpty ? null : h('div', { className: 'tree-zoom' },
1206
+ h('button', { title: '缩小', onClick: () => stepZoom(-0.1) }, '−'),
1207
+ h('span', { className: 'zoomval' }, `${Math.round(zoom * 100)}%`),
1208
+ h('button', { title: '放大', onClick: () => stepZoom(0.1) }, '+'),
1209
+ h('button', { title: '适应画布', onClick: fitView }, '适应'),
1210
+ ),
1211
+ showCorrections && layout.corrections.length > 0 && !showEmpty
1212
+ ? h('div', { className: 'tree-legend' }, h('span', null, h('i', { className: 'line' }), '修正关系'))
1213
+ : null,
1214
+ selected
1215
+ ? h(TreeDetail, {
1216
+ rec: selected,
1217
+ labels,
1218
+ byId: recordById,
1219
+ onClose: () => setSelectedId(null),
1220
+ onJump: jumpTo,
1221
+ })
1222
+ : null,
1223
+ )
1224
+
1225
+ return h('div', { className: 'tree-tab' },
1226
+ stats,
1227
+ toolbar,
1228
+ kindbar,
1229
+ error && records.length > 0 ? h('div', { className: 'err' }, error) : null,
1230
+ treeWrap,
1231
+ )
1232
+ }
1233
+
351
1234
  /** 磁盘文案:MB 就是 MB,不足 1GB 时别显示成 "0GB"(曾经多除了一次 1024)。 */
352
1235
  function diskText(freeDiskMb) {
353
1236
  return freeDiskMb >= 1024 ? `${(freeDiskMb / 1024).toFixed(0)}GB` : `${freeDiskMb.toFixed(0)}MB`
@@ -1248,14 +2131,33 @@ window.__ModuleLoader__.load({
1248
2131
  error ? h('div', { className: 'err' }, error) : null,
1249
2132
  h('div', { className: 'scroll' + (records.length > 0 || loading ? '' : ' is-empty') }, listBody),
1250
2133
  )
2134
+ // 记忆树是自己的过滤维度(客户端即时筛选),进来时先拉一份不带服务端筛选的全量记录,
2135
+ // 否则从「记录」页带着搜索词切过来会只剩一部分树。
2136
+ const treeBody = h(MemoryTreeTab, {
2137
+ records,
2138
+ scopes,
2139
+ loading,
2140
+ error,
2141
+ onRefresh: () => { setPendingTick(0); load('', '') },
2142
+ })
1251
2143
 
1252
2144
  return h('div', { className: 'memp' },
1253
2145
  h('div', { className: 'tabs' },
1254
2146
  h('button', { className: 'tab' + (tab === 'records' ? ' on' : ''), onClick: () => setTab('records') }, '服务'),
1255
2147
  h('button', { className: 'tab' + (tab === 'data' ? ' on' : ''), onClick: () => { if (tab !== 'data') load(); setTab('data') } }, '记录'),
2148
+ h('button', {
2149
+ className: 'tab' + (tab === 'tree' ? ' on' : ''),
2150
+ onClick: () => { if (tab !== 'tree') load('', ''); setTab('tree') },
2151
+ }, '记忆树'),
1256
2152
  h('button', { className: 'tab' + (tab === 'settings' ? ' on' : ''), onClick: () => setTab('settings') }, '设置'),
1257
2153
  ),
1258
- tab === 'settings' ? h(SettingsTab, {}) : tab === 'data' ? dataBody : overviewBody,
2154
+ tab === 'settings'
2155
+ ? h(SettingsTab, {})
2156
+ : tab === 'data'
2157
+ ? dataBody
2158
+ : tab === 'tree'
2159
+ ? treeBody
2160
+ : overviewBody,
1259
2161
  )
1260
2162
  }
1261
2163
 
@@ -1460,6 +2362,9 @@ window.__ModuleLoader__.load({
1460
2362
  exports.__test = {
1461
2363
  RecordCard: RecordCard,
1462
2364
  MemoryPanel: MemoryPanel,
2365
+ MemoryTreeTab: MemoryTreeTab,
2366
+ buildMemoryTree: buildMemoryTree,
2367
+ KIND_META: KIND_META,
1463
2368
  CSS: CSS,
1464
2369
  shouldPollInstall: shouldPollInstall,
1465
2370
  // 图标一致性护栏:测试会核对两条渲染路径都是同一份 16px 单色线稿
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.9.4",
3
+ "version": "0.9.5",
4
4
  "description": "DeepSeek Harness 本地长期记忆(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 五个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",