@restregular/dsh-memory 0.12.6 → 0.13.0

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,41 @@
2
2
 
3
3
  本项目的版本记录。安装 id 与 npm 版本一一对应。
4
4
 
5
+ ## 0.13.0 — 记录页语义检索与测试内存修复
6
+
7
+ - **记录页可以主动做语义检索**:搜索框旁边新增「语义检索」开关。开启后搜索不再做关键词过滤,
8
+ 而是走 `GET /memory/api/search`,用与 `memory_search` 同一套召回排序(向量 + 词法 + 可选重排)
9
+ 返回按相关度排好的结果,卡片上带「相关度」得分;作用域下拉、新建 / 编辑 / 删除照常可用。
10
+ - **如实标注检索出处**:结果说明会写明是「语义排序」还是「关键词回退」,并给出向量覆盖率
11
+ (`已嵌入 / 总记录数`);向量未启用、记录还没嵌入、向量服务无响应、旧 provider 四种情况分别说明原因,
12
+ 不把词法结果冒充成语义结果。嵌入完成后面板会自动重跑并刷成语义结果。
13
+ - **语义检索是只读浏览**:新增 provider 方法 `searchForPanel`,复用 `search()` 的召回与打分,
14
+ 但不写 `accessCount` / `lastAccessedAt`(这两个值是召回排序的输入,面板里看一眼不该把排序带偏),
15
+ 并在结果里报告向量通道是否真的参与。`search()` 新增两个内部开关(`vector` / `touch`),
16
+ 工具与注入的调用路径不受影响。
17
+ - **面板 `/search` 路由**:`q` 为空或 `topK` 非法返回 400;非法 scope 与 `/records` 同口径返回 400;
18
+ 不存在的 scope 返回空结果且不创建任何文件;旧 provider(只有 `search` 或只有 `store`)有明确的降级路径。
19
+ - **修复 client 渲染测试的堆爆炸**:测试脚手架的 `useEffect` 会跨多轮渲染累积,`runEffects()`
20
+ 把历史轮次的 effect 全部重放,效应量级按轮数指数增长(审计页自动刷新后约 100MB/测试,
21
+ 在默认 2GB 堆上直接 OOM)。改为每轮渲染只保留本轮 effect(更贴近 React 的提交语义),
22
+ 用例从 45 秒 / OOM 降到 3 秒内跑完。
23
+ - 测试:新增 provider `searchForPanel`(向量 / 词法 / 无向量 / 嵌入失败)、面板 `/search`
24
+ (校验、作用域、降级、只读、不建文件)、客户端(开关、请求、结果说明、相关度、禁用态与回退文案)
25
+ 与包装层转发用例;全量 337 项 336 通过 1 跳过。
26
+
27
+ ## 0.12.7 — 审计详情滚动与锚定浮窗
28
+
29
+ - **详情底部不再被裁切**:审计页高度收紧到 `100vh - 210px`;详情面板改为 `height:auto` +
30
+ `max-height:calc(100vh - 340px)` + `overflow-y:auto`,并加 20px 底部内边距;「原始结构化事件」
31
+ 等底部内容可以完整滚入视口。
32
+ - **浮窗不再跟随鼠标**:浮窗改为根据 ID 气泡的 `getBoundingClientRect()` 固定定位(下方优先,
33
+ 空间不足自动翻到上方),不再随 mousemove 移动。
34
+ - **hover 延迟 + 可移入浮窗**:进入 ID 气泡后等待 350ms 才显示;显示后鼠标移到浮窗内不会隐藏,
35
+ 离开气泡/浮窗 220ms 后隐藏;不再需要重新 hover 才能看到完整 ID(浮窗标题/内容已含完整 ID)。
36
+ - 浮窗改为 `pointer-events:auto` 且可滚动,长正文可以直接在浮窗内查看/滚动。
37
+ - **点击直接跳转**:点击 ID 气泡或浮窗本身都直接执行跳转(记忆 → 记录页并展开,会话 → 打开会话)。
38
+ - 测试更新:hover 延迟后显示完整 ID、记忆原文/会话标题,点击回调仍正确。
39
+
5
40
  ## 0.12.6 — 审计详情分类、滚动与关联跳转
6
41
 
7
42
  - **详情完整可滚动**:审计页采用固定视口高度 + `grid-template-rows:minmax(0,1fr)`,详情面板 `height:100%` 独立滚动,长内容可以滚到底部;整页不滚动。
package/README.md CHANGED
@@ -12,6 +12,7 @@ JSONL 落盘 · 本机向量检索 · 五个模型工具 · 自动召回 · 硬
12
12
  [![npm downloads](https://img.shields.io/npm/dm/@restregular/dsh-memory.svg)](https://www.npmjs.com/package/@restregular/dsh-memory)
13
13
  [![license](https://img.shields.io/npm/l/@restregular/dsh-memory.svg)](https://github.com/RestRegular/dsh-memory/blob/main/LICENSE)
14
14
  [![Node.js](https://img.shields.io/badge/Node.js-%E2%89%A522.13-5FA04E.svg)](https://nodejs.org/)
15
+ [![Listed on dsh-plugin.org](https://dsh-plugin.org/badges/listed.svg)](https://dsh-plugin.org/plugins/restregular/dsh-memory)
15
16
 
16
17
  [npm 包](https://www.npmjs.com/package/@restregular/dsh-memory) · [问题反馈](https://github.com/RestRegular/dsh-memory/issues) · [更新日志](https://github.com/RestRegular/dsh-memory/blob/main/CHANGELOG.md)
17
18
 
@@ -42,12 +43,23 @@ JSONL 落盘 · 本机向量检索 · 五个模型工具 · 自动召回 · 硬
42
43
  | **自动召回** | 每轮按用户问题召回;新会话第一步注入项目 / global 摘要;发布、部署、工具失败等行为按标签触发定向召回 |
43
44
  | **印象形态** | 每轮只给每条记忆的短摘要;模型判断相关但需要细节时再 `memory_get` 取全文,省 token 也不丢信息 |
44
45
  | **硬性规则** | `kind: rule` 进系统提示常驻段;旧会话会收到新增 / 编辑提醒;超预算有明确警告,不静默丢弃 |
45
- | **可视化管理** | 记录浏览 / 搜索 / 新建 / 编辑 / 删除;记忆树展示作用域、类型与修正链;设置改完即存;导入导出 |
46
+ | **可视化管理** | 记录浏览 / 搜索 / 新建 / 编辑 / 删除;**记录页可主动做语义检索**(与 `memory_search` 同一套排序);记忆树展示作用域、类型与修正链;设置改完即存;导入导出 |
46
47
  | **一键向量后端** | 面板里下载 llama.cpp 运行时与内置模型,按 CPU / 内存 / 显卡推荐;换模型自动重建向量 |
47
48
  | **跨进程安全** | 每个作用域一把写锁,锁内重新读盘再合并;多个 DSH 实例或 MCP server 共用一个 store 不丢数据 |
48
49
 
49
50
  ## 界面
50
51
 
52
+ ### 记录页的语义检索
53
+
54
+ 记录页搜索框旁边有「语义检索」开关。开启后,搜索不再按关键词过滤,而是把这句话交给和
55
+ `memory_search` **同一套**的召回排序(向量 + 词法,必要时再重排),结果按相关度返回并标出得分。
56
+
57
+ - 开关只在向量后端已配置时可用;没装后端时保持禁用并说明原因。
58
+ - 语义检索是**只读浏览**:不增加访问计数,不会把 `memory_search` 后续的排序带偏。
59
+ - 结果说明会如实写出这次是「语义排序」还是「关键词回退」:例如记录还没嵌入向量、或向量服务
60
+ 没有响应时,不会把词法结果冒充成语义结果。嵌入完成后列表会自动刷新成语义结果。
61
+ - 作用域下拉与新建 / 编辑 / 删除仍然照常工作;从审计页点记忆 ID 跳过来时会自动回到普通列表并展开该条。
62
+
51
63
  ### 记忆树
52
64
 
53
65
  按 **作用域 → 类型 → 记录** 三层展开,根节点显示总数。`supersedes` 是关系而不是层级,
@@ -71,6 +83,14 @@ JSONL 落盘 · 本机向量检索 · 五个模型工具 · 自动召回 · 硬
71
83
 
72
84
  ## 安装
73
85
 
86
+ 一条命令装进 Web profile:
87
+
88
+ ```bash
89
+ dsh plugin --profile web add @restregular/dsh-memory
90
+ ```
91
+
92
+ 也可以手动加进 profile 的依赖(桌面端 `~/.dsh/profiles/desktop`,Web 端 `~/.dsh/profiles/web`):
93
+
74
94
  ```bash
75
95
  pnpm add @restregular/dsh-memory
76
96
  # 或
@@ -116,7 +136,8 @@ try/catch——任何一半失败都只记一行日志,绝不让 DSH 启动失
116
136
  ### 1. 打开面板
117
137
 
118
138
  设置页 →「记忆系统」;也可以在「设置 → 侧栏入口」打开左侧栏的「记忆系统」按钮。
119
- 面板分四个标签:**服务 / 记录 / 记忆树 / 设置**。
139
+ 面板分四个标签:**服务 / 记录 / 记忆树 / 设置**。记录页的搜索框旁有「语义检索」开关,
140
+ 开启后可以直接用一句话主动搜索(需要先配置向量后端)。
120
141
 
121
142
  ### 2. 存一条记忆
122
143
 
@@ -199,6 +220,8 @@ name / description / 参数,以及工具失败描述;**不读取隐藏思维
199
220
  - **向量通道**:调用 `llama-server` 的 OpenAI 兼容 `/v1/embeddings`;可用面板一键安装,也可接自己的端点。
200
221
  - **可选 LLM 重排**:`retrieval.llm.enabled`,默认关。
201
222
  - **自动降级**:端点没配、进程没起、向量身份不匹配时,只走词法,不报错、不阻塞。
223
+ - **面板主动语义检索**:记录页的「语义检索」开关走 `GET /memory/api/search`,用同一套召回排序
224
+ (只读、不写访问计数),并在结果说明里标明向量通道是否真的参与;旧 provider 会退回关键词过滤并在界面注明。
202
225
 
203
226
  向量边车 `.vec` 的首行是身份头 `#<model>\t<dims>\t<pooling>`。任一对不上就整份丢弃并重新嵌入;
204
227
  重建期间检索暂时只用词法。老边车只有 `model` + `dims` 两段,按兼容接受,下一次写向量时自动升级。
@@ -415,6 +438,7 @@ npm run verify # 构建到 .verify/,不落 packages/
415
438
 
416
439
  ## 更新日志
417
440
 
441
+ - **0.12.7** —— 审计详情可完整滚到底;ID 浮窗改为按气泡位置固定显示,延迟 hover 显示、可移入浮窗,点击气泡或浮窗都直接跳转。
418
442
  - **0.12.6** —— 审计详情分类展示选中/新增/标签/省略/去重 ID;记忆与会话 ID 支持 hover 浮窗和点击跳转;详情独立滚动可到底。
419
443
  - **0.12.5** —— 审计表头移入滚动容器并 sticky,与行严格对齐;重分配列宽,行内预算改紧凑条。
420
444
  - **0.12.4** —— 审计页默认每 0.5 秒自动刷新(可关/可调间隔);移除顶部标题与气泡,整页固定在窗口内,仅列表滚动;新增表头并优化列宽;复制/导出提示就地显示。
package/lib/client.js CHANGED
@@ -104,6 +104,13 @@ window.__ModuleLoader__.load({
104
104
  '.memp .editrow input[type=number]{width:64px;padding:4px 8px}',
105
105
  '.memp .err{color:var(--dsw-alias-label-danger, #e05555);font-size:12px}',
106
106
  '.memp .empty{color:var(--dsw-alias-label-secondary);font-size:12.5px;padding:16px 2px;text-align:center}',
107
+ // 语义检索:搜索框旁的开关 + 结果说明行 + 结果卡上的相关度
108
+ '.memp .toolbar .semantic{flex:none}',
109
+ '.memp .toolbar .semantic.on{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary);background:color-mix(in srgb,var(--dsw-alias-brand-primary) 10%,transparent)}',
110
+ '.memp .search-note{display:flex;flex-wrap:wrap;align-items:center;gap:4px 10px;font-size:11.5px;line-height:1.55;color:var(--dsw-alias-label-secondary)}',
111
+ '.memp .search-note b{font-weight:600;color:var(--dsw-alias-label-primary)}',
112
+ '.memp .search-note .muted{font-size:11.5px}',
113
+ '.memp .badge.score{color:var(--dsw-alias-brand-primary);border-color:color-mix(in srgb,var(--dsw-alias-brand-primary) 45%,transparent)}',
107
114
  // 维护区(卸载向量服务 / 清空记忆数据)
108
115
  '.memp .maint{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:10px 12px;display:flex;flex-direction:column;gap:8px}',
109
116
  '.memp .maint-row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;font-size:12.5px}',
@@ -335,7 +342,7 @@ window.__ModuleLoader__.load({
335
342
  '.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}',
336
343
  '@media (max-width:620px){.memp .tree-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.memp .tree-toolbar input[type=text]{max-width:none}}',
337
344
  // ===== 审计 =====
338
- '.memp .audit{display:flex;flex-direction:column;gap:10px;min-height:0;height:calc(100vh - 160px);max-height:calc(100vh - 160px);overflow:hidden}',
345
+ '.memp .audit{display:flex;flex-direction:column;gap:10px;min-height:0;height:calc(100vh - 210px);max-height:calc(100vh - 210px);overflow:hidden}',
339
346
  '.memp .audit-head{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap}',
340
347
  '.memp .audit-title{font-size:16px;font-weight:650;line-height:1.35}',
341
348
  '.memp .audit-sub{font-size:11.5px;color:var(--dsw-alias-label-secondary);line-height:1.55;margin-top:2px}',
@@ -385,7 +392,7 @@ window.__ModuleLoader__.load({
385
392
  '.memp .audit-pill.bad{color:var(--dsw-alias-label-danger, #e05555);border-color:color-mix(in srgb,var(--dsw-alias-label-danger, #e05555) 42%,var(--dsw-alias-border-l1))}',
386
393
  '.memp .audit-pill.mute{color:var(--dsw-alias-label-secondary)}',
387
394
  '.memp .audit-empty{border:1px dashed var(--dsw-alias-border-l1);border-radius:10px;padding:26px 16px;text-align:center;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.65}',
388
- '.memp .audit-detail{border:1px solid var(--dsw-alias-border-l1);border-radius:11px;background:var(--dsw-alias-bg-layer-1);padding:10px 11px;display:flex;flex-direction:column;gap:9px;height:100%;max-height:100%;min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:thin}',
395
+ '.memp .audit-detail{border:1px solid var(--dsw-alias-border-l1);border-radius:11px;background:var(--dsw-alias-bg-layer-1);padding:10px 11px 20px;box-sizing:border-box;display:flex;flex-direction:column;gap:9px;height:auto;max-height:calc(100vh - 340px);min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:thin}',
389
396
  '.memp .audit-detail-head{display:flex;gap:7px;align-items:center}',
390
397
  '.memp .audit-detail-head b{font-size:12.5px}',
391
398
  '.memp .audit-detail-head .spacer{flex:1}',
@@ -416,15 +423,15 @@ window.__ModuleLoader__.load({
416
423
  '.memp .audit-id-group-title{display:flex;align-items:center;gap:6px;font-size:10.5px;color:var(--dsw-alias-label-secondary);letter-spacing:.02em}',
417
424
  '.memp .audit-id-group-title b{font-weight:600;color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}',
418
425
  '.memp .audit-id-sub{font-size:9.5px;color:var(--dsw-alias-label-secondary);opacity:.85}',
419
- '.memp .audit-tip{position:fixed;z-index:120;max-width:min(380px,calc(100vw - 24px));max-height:min(300px,60vh);overflow:hidden;padding:9px 10px;border:1px solid var(--dsw-alias-border-l2,var(--dsw-alias-border-l1));border-radius:10px;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1) 97%,black 3%);box-shadow:0 14px 36px rgba(0,0,0,.28);pointer-events:none;color:var(--dsw-alias-label-primary)}',
426
+ '.memp .audit-tip{position:fixed;z-index:120;max-width:min(380px,calc(100vw - 24px));max-height:min(300px,60vh);overflow:auto;padding:9px 10px;border:1px solid var(--dsw-alias-border-l2,var(--dsw-alias-border-l1));border-radius:10px;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1) 97%,black 3%);box-shadow:0 14px 36px rgba(0,0,0,.28);pointer-events:auto;cursor:pointer;color:var(--dsw-alias-label-primary)}',
420
427
  '.memp .audit-tip-head{display:flex;align-items:center;gap:6px;margin-bottom:5px;font-size:11px;color:var(--dsw-alias-label-secondary)}',
421
428
  '.memp .audit-tip-title{font-weight:600;color:var(--dsw-alias-label-primary);font-size:11.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}',
422
429
  '.memp .audit-tip-meta{display:flex;flex-wrap:wrap;gap:4px;margin-bottom:5px}',
423
- '.memp .audit-tip-content{font-size:11px;line-height:1.55;white-space:pre-wrap;word-break:break-word;color:var(--dsw-alias-label-primary);max-height:170px;overflow:hidden}',
430
+ '.memp .audit-tip-content{font-size:11px;line-height:1.55;white-space:pre-wrap;word-break:break-word;color:var(--dsw-alias-label-primary);max-height:none;overflow:visible}',
424
431
  '.memp .audit-tip-foot{margin-top:6px;font-size:9.5px;color:var(--dsw-alias-label-secondary)}',
425
432
  '.memp .rec.focus{border-color:var(--dsw-alias-brand-primary);box-shadow:0 0 0 1px color-mix(in srgb,var(--dsw-alias-brand-primary) 25%,transparent)}',
426
433
  '@media (max-width:900px){.memp .audit-split.has-detail{grid-template-columns:minmax(0,1fr)}.memp .audit-row{grid-template-columns:54px 120px 120px minmax(100px,1fr) 96px 100px 80px}.memp .audit-table-head{grid-template-columns:54px 120px 120px minmax(100px,1fr) 96px 100px 80px}}',
427
- '@media (max-width:620px){.memp .audit-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.memp .audit-table-head{display:none}.memp .audit-row{display:flex;flex-wrap:wrap;gap:4px 8px}.memp .audit-row .col-trigger,.memp .audit-row .col-budget{display:none}.memp .audit-row .col-nums{margin-left:auto}.memp .audit-row .col-time{order:1}.memp .audit-row .col-channel{order:2}.memp .audit-row .col-delivery{order:3}.memp .audit-row .col-outcome{order:4;margin-left:auto}.memp .audit-filter-row input[type=text],.memp .audit-filter-row input[type=search]{max-width:none;flex:1}.memp .audit{height:calc(100vh - 120px);max-height:calc(100vh - 120px)}}',
434
+ '@media (max-width:620px){.memp .audit-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.memp .audit-table-head{display:none}.memp .audit-row{display:flex;flex-wrap:wrap;gap:4px 8px}.memp .audit-row .col-trigger,.memp .audit-row .col-budget{display:none}.memp .audit-row .col-nums{margin-left:auto}.memp .audit-row .col-time{order:1}.memp .audit-row .col-channel{order:2}.memp .audit-row .col-delivery{order:3}.memp .audit-row .col-outcome{order:4;margin-left:auto}.memp .audit-filter-row input[type=text],.memp .audit-filter-row input[type=search]{max-width:none;flex:1}.memp .audit{height:calc(100vh - 150px);max-height:calc(100vh - 150px)}.memp .audit-detail{max-height:calc(100vh - 280px)}}',
428
435
  ].join('')
429
436
 
430
437
  async function api(method, body) {
@@ -725,7 +732,7 @@ window.__ModuleLoader__.load({
725
732
  })
726
733
  }
727
734
 
728
- function RecordCard({ rec, vectorOn, labels, onSaved, onDeleted, focus = false }) {
735
+ function RecordCard({ rec, vectorOn, labels, onSaved, onDeleted, focus = false, score = null }) {
729
736
  // collapsed by default: the list stays scannable, full text on demand
730
737
  const [expanded, setExpanded] = React.useState(false)
731
738
  const [editing, setEditing] = React.useState(false)
@@ -794,6 +801,12 @@ window.__ModuleLoader__.load({
794
801
  h('span', { className: open ? 'chev open' : 'chev' }, '▶'),
795
802
  h('span', { className: 'badge scope', title: rec.scope }, scopeLabel(rec.scope, labels)),
796
803
  h('span', { className: 'badge' }, rec.kind),
804
+ score !== null && score !== undefined && Number.isFinite(Number(score))
805
+ ? h('span', {
806
+ className: 'badge score',
807
+ title: '检索得分:向量相似度 / 词法命中,再按时效与重要度加权后的排序分',
808
+ }, `相关度 ${Number(score).toFixed(2)}`)
809
+ : null,
797
810
  rec.supersedes
798
811
  ? h('span', {
799
812
  className: 'badge corrected',
@@ -2173,6 +2186,8 @@ window.__ModuleLoader__.load({
2173
2186
  const [reloadTick, setReloadTick] = React.useState(0)
2174
2187
  const [tip, setTip] = React.useState(null)
2175
2188
  const [recordCache, setRecordCache] = React.useState({})
2189
+ const tipTimer = React.useRef(null)
2190
+ const hideTimer = React.useRef(null)
2176
2191
 
2177
2192
  function queryParams(cursorValue) {
2178
2193
  const params = new URLSearchParams()
@@ -2257,32 +2272,55 @@ window.__ModuleLoader__.load({
2257
2272
  return undefined
2258
2273
  }
2259
2274
  }
2260
- const tipPosition = (event) => {
2275
+ const clearTipTimers = () => {
2276
+ if (tipTimer.current !== null) { clearTimeout(tipTimer.current); tipTimer.current = null }
2277
+ if (hideTimer.current !== null) { clearTimeout(hideTimer.current); hideTimer.current = null }
2278
+ }
2279
+ React.useEffect(() => () => clearTipTimers(), [])
2280
+ const positionForAnchor = (element) => {
2261
2281
  const width = typeof window !== 'undefined' ? window.innerWidth : 1200
2262
2282
  const height = typeof window !== 'undefined' ? window.innerHeight : 800
2263
- return {
2264
- x: Math.max(8, Math.min(event.clientX + 14, width - 390)),
2265
- y: Math.max(8, Math.min(event.clientY + 14, height - 320)),
2266
- }
2283
+ const rect = element && typeof element.getBoundingClientRect === 'function' ? element.getBoundingClientRect() : null
2284
+ if (rect === null) return { x: 12, y: 12 }
2285
+ const tipWidth = Math.min(380, width - 24)
2286
+ const tipHeight = 240
2287
+ const x = Math.max(12, Math.min(rect.left, width - tipWidth - 12))
2288
+ let y = rect.bottom + 8
2289
+ if (y + tipHeight > height - 12) y = Math.max(12, rect.top - tipHeight - 8)
2290
+ return { x, y }
2267
2291
  }
2268
- const moveTip = (event) => {
2269
- if (!event || typeof event.clientX !== 'number') return
2270
- setTip((prev) => prev === null ? prev : { ...prev, ...tipPosition(event) })
2292
+ const scheduleTip = (build, element) => {
2293
+ clearTipTimers()
2294
+ if (tip !== null && tip.id !== build().id) setTip(null)
2295
+ tipTimer.current = setTimeout(() => {
2296
+ tipTimer.current = null
2297
+ setTip({ ...build(), ...positionForAnchor(element) })
2298
+ }, 350)
2271
2299
  }
2272
- const hideTip = () => setTip(null)
2273
- const showMemoryTip = (id, event) => {
2274
- const pos = tipPosition(event)
2300
+ const cancelHideTip = () => {
2301
+ if (hideTimer.current !== null) { clearTimeout(hideTimer.current); hideTimer.current = null }
2302
+ }
2303
+ const scheduleHideTip = () => {
2304
+ if (tipTimer.current !== null) { clearTimeout(tipTimer.current); tipTimer.current = null }
2305
+ cancelHideTip()
2306
+ hideTimer.current = setTimeout(() => { hideTimer.current = null; setTip(null) }, 220)
2307
+ }
2308
+ const hideTip = () => { clearTipTimers(); setTip(null) }
2309
+ const showMemoryTip = (id, element) => {
2275
2310
  const known = findRecord(id)
2276
- setTip({ type: 'memory', id, record: known, loading: known === undefined, ...pos })
2311
+ const box = { record: known }
2312
+ scheduleTip(() => ({ type: 'memory', id, record: box.record, loading: box.record === undefined }), element)
2277
2313
  if (known === undefined) {
2278
2314
  fetchRecord(id).then((record) => {
2279
- if (record !== undefined) setTip((prev) => prev !== null && prev.id === id ? { ...prev, record, loading: false } : prev)
2315
+ if (record === undefined) return
2316
+ box.record = record
2317
+ setTip((prev) => prev !== null && prev.id === id ? { ...prev, record, loading: false } : prev)
2280
2318
  })
2281
2319
  }
2282
2320
  }
2283
- const showSessionTip = (id, event) => {
2321
+ const showSessionTip = (id, element) => {
2284
2322
  const summary = typeof sessionInfo === 'function' ? (() => { try { return sessionInfo(id) } catch { return undefined } })() : undefined
2285
- setTip({ type: 'session', id, summary, ...tipPosition(event) })
2323
+ scheduleTip(() => ({ type: 'session', id, summary }), element)
2286
2324
  }
2287
2325
  const openMemoryId = async (id) => {
2288
2326
  const record = findRecord(id) || await fetchRecord(id)
@@ -2296,10 +2334,9 @@ window.__ModuleLoader__.load({
2296
2334
  const idChip = (id, tone = '', title = undefined) => h('button', {
2297
2335
  key: `${tone}:${id}`,
2298
2336
  className: 'audit-id' + (tone ? ` ${tone}` : ''),
2299
- title: title || id,
2300
- onMouseEnter: (event) => showMemoryTip(id, event),
2301
- onMouseMove: moveTip,
2302
- onMouseLeave: hideTip,
2337
+ 'aria-label': title || id,
2338
+ onMouseEnter: (event) => showMemoryTip(id, event.currentTarget),
2339
+ onMouseLeave: scheduleHideTip,
2303
2340
  onClick: () => openMemoryId(id),
2304
2341
  }, id.length > 12 ? `${id.slice(0, 8)}…${id.slice(-4)}` : id)
2305
2342
 
@@ -2495,10 +2532,9 @@ window.__ModuleLoader__.load({
2495
2532
  ? [h('span', { className: 'k', key: 'k-session' }, '会话'),
2496
2533
  h('span', { className: 'v', key: 'v-session' }, h('button', {
2497
2534
  className: 'audit-id',
2498
- title: selected.sessionId,
2499
- onMouseEnter: (event) => showSessionTip(selected.sessionId, event),
2500
- onMouseMove: moveTip,
2501
- onMouseLeave: hideTip,
2535
+ 'aria-label': selected.sessionId,
2536
+ onMouseEnter: (event) => showSessionTip(selected.sessionId, event.currentTarget),
2537
+ onMouseLeave: scheduleHideTip,
2502
2538
  onClick: () => openSessionId(selected.sessionId),
2503
2539
  }, selected.sessionId))]
2504
2540
  : null
@@ -2633,7 +2669,7 @@ window.__ModuleLoader__.load({
2633
2669
  if (tip.type === 'session') {
2634
2670
  const summary = tip.summary || {}
2635
2671
  const title = summary.title || summary.name || `会话 ${String(tip.id).slice(0, 8)}`
2636
- return h('div', { className: 'audit-tip', style: { left: tip.x, top: tip.y } },
2672
+ return h('div', { className: 'audit-tip', style: { left: tip.x, top: tip.y }, onMouseEnter: cancelHideTip, onMouseLeave: hideTip, onClick: () => openSessionId(tip.id) },
2637
2673
  h('div', { className: 'audit-tip-head' }, h('span', null, '会话'), h('span', { className: 'audit-tip-title' }, title)),
2638
2674
  h('div', { className: 'audit-tip-meta' },
2639
2675
  auditPill(String(tip.id).slice(0, 8) + '…', 'mute'),
@@ -2641,12 +2677,13 @@ window.__ModuleLoader__.load({
2641
2677
  summary.archived === true ? auditPill('已归档', 'warn') : null,
2642
2678
  ),
2643
2679
  summary.cwd ? h('div', { className: 'audit-tip-content' }, summary.cwd) : null,
2680
+ h('div', { className: 'audit-tip-content' }, `ID ${tip.id}`),
2644
2681
  summary.updatedAt ? h('div', { className: 'audit-tip-foot' }, `更新于 ${fmtTime(summary.updatedAt)}`) : null,
2645
2682
  h('div', { className: 'audit-tip-foot' }, '点击打开会话'),
2646
2683
  )
2647
2684
  }
2648
2685
  const record = tip.record
2649
- return h('div', { className: 'audit-tip', style: { left: tip.x, top: tip.y } },
2686
+ return h('div', { className: 'audit-tip', style: { left: tip.x, top: tip.y }, onMouseEnter: cancelHideTip, onMouseLeave: hideTip, onClick: () => openMemoryId(tip.id) },
2650
2687
  h('div', { className: 'audit-tip-head' }, h('span', null, '记忆'), h('span', { className: 'audit-tip-title' }, record ? record.id : tip.id)),
2651
2688
  record
2652
2689
  ? h('div', null,
@@ -2658,7 +2695,7 @@ window.__ModuleLoader__.load({
2658
2695
  record.tags && record.tags.length > 0
2659
2696
  ? h('div', { className: 'audit-flat' }, record.tags.map((tag) => h('span', { className: 'tag', key: tag }, tag)))
2660
2697
  : null,
2661
- h('div', { className: 'audit-tip-content' }, `${String(record.content || '').slice(0, 700)}${String(record.content || '').length > 700 ? '…' : ''}`),
2698
+ h('div', { className: 'audit-tip-content' }, String(record.content || '')),
2662
2699
  )
2663
2700
  : h('div', { className: 'audit-tip-content' }, tip.loading ? '加载记录…' : '记录未找到(可能已删除或不在已加载作用域)'),
2664
2701
  h('div', { className: 'audit-tip-foot' }, '点击跳转到「记录」页并展开'),
@@ -2712,6 +2749,10 @@ window.__ModuleLoader__.load({
2712
2749
  const [dangerAsk, setDangerAsk] = React.useState('')
2713
2750
  const [scopeFilter, setScopeFilter] = React.useState('')
2714
2751
  const [q, setQ] = React.useState('')
2752
+ // 语义检索:默认关(记录页原本是"关键词过滤");开启后搜索走 /search,
2753
+ // 由 provider 用向量 + 词法同一套排序,列表按相关度排。
2754
+ const [semantic, setSemantic] = React.useState(false)
2755
+ const [searchInfo, setSearchInfo] = React.useState(null)
2715
2756
  const [focusRecord, setFocusRecord] = React.useState(null)
2716
2757
  const [loading, setLoading] = React.useState(true)
2717
2758
  const [error, setError] = React.useState('')
@@ -2719,17 +2760,32 @@ window.__ModuleLoader__.load({
2719
2760
  const [pendingTick, setPendingTick] = React.useState(0)
2720
2761
  const [creating, setCreating] = React.useState(false)
2721
2762
 
2722
- const load = async (query, scopeF) => {
2763
+ const load = async (query, scopeF, semanticF) => {
2723
2764
  setLoading(true); setError('')
2724
2765
  try {
2725
2766
  const params = new URLSearchParams()
2726
2767
  const qq = query !== undefined ? query : q
2727
2768
  const ss = scopeF !== undefined ? scopeF : scopeFilter
2769
+ const sem = semanticF !== undefined ? semanticF : semantic
2770
+ // 空查询在语义模式下没有意义(embedding 空串),直接列全部记录。
2771
+ const semanticSearch = sem && qq.trim() !== ''
2728
2772
  if (ss) params.set('scope', ss)
2729
2773
  if (qq.trim()) params.set('q', qq.trim())
2730
2774
  const suffix = params.toString() ? `?${params}` : ''
2731
- const [recVal, status] = await Promise.all([api(`records${suffix}`), api('status')])
2732
- setRecords(recVal.records)
2775
+ const [listVal, status] = await Promise.all([
2776
+ api(`${semanticSearch ? 'search' : 'records'}${suffix}`),
2777
+ api('status'),
2778
+ ])
2779
+ setRecords(semanticSearch ? listVal.hits : listVal.records)
2780
+ setSearchInfo(semanticSearch
2781
+ ? {
2782
+ mode: listVal.mode === 'vector' ? 'vector' : 'lexical',
2783
+ reason: listVal.reason,
2784
+ embedded: Number(listVal.embedded) || 0,
2785
+ total: Number(listVal.total) || 0,
2786
+ query: qq.trim(),
2787
+ }
2788
+ : null)
2733
2789
  setScopes(status.scopes)
2734
2790
  setEmbedServer(status.embedServer ?? null)
2735
2791
  } catch (e) {
@@ -2744,9 +2800,12 @@ window.__ModuleLoader__.load({
2744
2800
  setFocusRecord(id)
2745
2801
  setTab('data')
2746
2802
  setQ('')
2803
+ // 语义模式是按查询排名的:跳转要看到那条记录,必须回到普通列表。
2804
+ setSemantic(false)
2805
+ setSearchInfo(null)
2747
2806
  const nextScope = scope || ''
2748
2807
  setScopeFilter(nextScope)
2749
- load('', nextScope)
2808
+ load('', nextScope, false)
2750
2809
  }
2751
2810
  // 导入完成后从设置页切换回记录页时,列表要能看到新数据(事件由设置页发出)。
2752
2811
  React.useEffect(() => {
@@ -3013,10 +3072,27 @@ window.__ModuleLoader__.load({
3013
3072
 
3014
3073
  const toolbar = h('div', { className: 'row toolbar' },
3015
3074
  h('input', {
3016
- type: 'text', placeholder: '搜索内容、类型或标签', value: q,
3075
+ type: 'text',
3076
+ placeholder: semantic ? '描述你要找的记忆,回车语义检索' : '搜索内容、类型或标签',
3077
+ value: q,
3017
3078
  onChange: (e) => setQ(e.target.value),
3018
3079
  onKeyDown: (e) => { if (e.key === 'Enter') load(q, scopeFilter) },
3019
3080
  }),
3081
+ // 语义检索开关:向量没启用时保持可读但不许点(点开只会给出词法结果,容易误解)。
3082
+ h('button', {
3083
+ className: 'semantic' + (semantic ? ' on' : ''),
3084
+ 'aria-pressed': semantic,
3085
+ disabled: !(configured && vectorEnabled),
3086
+ title: configured && vectorEnabled
3087
+ ? (semantic ? '语义检索已开启:按语义相似度排序,点击切回关键词过滤' : '按语义相似度检索(向量 + 词法;未命中时结果会标注已回退)')
3088
+ : '需要先在「服务」页配置并启用向量检索',
3089
+ onClick: () => {
3090
+ const next = !semantic
3091
+ setSemantic(next)
3092
+ // 已经有查询词时立刻按新模式重跑一次,不用再敲回车。
3093
+ if (q.trim() !== '') load(q, scopeFilter, next)
3094
+ },
3095
+ }, '语义检索'),
3020
3096
  // 作用域也用同一个自绘下拉(与模型/运行时统一);标签优先用服务端给的 label
3021
3097
  h(Dropdown, {
3022
3098
  items: [
@@ -3029,19 +3105,51 @@ window.__ModuleLoader__.load({
3029
3105
  }),
3030
3106
  h('button', { onClick: () => setCreating((v) => !v), disabled: loading }, creating ? '收起' : '新建'),
3031
3107
  h('button', { onClick: () => load(q, scopeFilter), disabled: loading }, loading ? '刷新中…' : '刷新'),
3032
- filtering ? h('button', { className: 'linkbtn', onClick: () => { setQ(''); setScopeFilter(''); load('', '') } }, '清空筛选') : null,
3108
+ filtering ? h('button', { className: 'linkbtn', onClick: () => { setQ(''); setScopeFilter(''); setSearchInfo(null); load('', '', semantic) } }, '清空筛选') : null,
3033
3109
  )
3110
+ // 语义检索结果的出处:真跑了向量,还是因为服务/向量缺失退回了词法 —— 明说,
3111
+ // 不把词法结果冒充成"语义找到的"。
3112
+ const fallbackReason = {
3113
+ 'vector-disabled': '向量检索未启用',
3114
+ 'no-vectors': '记录尚未嵌入向量',
3115
+ 'no-records': '没有可检索的记录',
3116
+ 'embed-failed': '向量服务没有响应',
3117
+ 'provider-lexical': '当前 provider 不支持语义检索',
3118
+ }
3119
+ const searchNoteNode = searchInfo
3120
+ ? h('div', { className: 'search-note' },
3121
+ h('span', { className: 'pill' }, searchInfo.mode === 'vector' ? '语义排序' : '关键词回退'),
3122
+ h('b', null, `「${excerpt(searchInfo.query, 28)}」`),
3123
+ h('span', null, `命中 ${records.length} 条`),
3124
+ searchInfo.mode === 'vector'
3125
+ ? h('span', { className: 'muted' }, `向量覆盖 ${searchInfo.embedded}/${searchInfo.total} 条`)
3126
+ : h('span', { className: 'muted' }, searchInfo.reason === 'no-records'
3127
+ ? '该作用域没有记录'
3128
+ : `${fallbackReason[searchInfo.reason] || '向量不可用'},本次按关键词排序`),
3129
+ )
3130
+ : semantic
3131
+ ? h('div', { className: 'search-note' },
3132
+ h('span', { className: 'muted' }, '输入一句话描述你要找的记忆,按回车开始语义检索。'))
3133
+ : null
3034
3134
  const createForm = creating
3035
3135
  ? h(CreateForm, {
3036
3136
  scopes,
3037
3137
  onCancel: () => setCreating(false),
3038
- onCreated: () => { setCreating(false); setPendingTick(0); load('', '') },
3138
+ // 新建完成后回到普通列表:新记录不一定命中当前语义查询,留在搜索结果里会让人以为没保存。
3139
+ onCreated: () => {
3140
+ setCreating(false); setPendingTick(0)
3141
+ setQ(''); setSemantic(false); setSearchInfo(null)
3142
+ load('', '', false)
3143
+ },
3039
3144
  })
3040
3145
  : null
3146
+ const emptyText = searchInfo ? '没有语义相关的记忆' : filtering ? '没有匹配的记忆' : '还没有记忆'
3041
3147
  const listBody = !loading && !error && records.length === 0
3042
- ? h('div', { className: 'empty' }, filtering ? '没有匹配的记忆' : '还没有记忆')
3148
+ ? h('div', { className: 'empty' },
3149
+ emptyText,
3150
+ searchInfo ? h('div', { className: 'muted' }, '换个说法试试;刚写入的记录可能还没嵌入向量。') : null)
3043
3151
  : h('div', { className: 'list' },
3044
- records.map((rec) => h(RecordCard, { key: rec.id, rec, focus: focusRecord === rec.id, vectorOn: configured && vectorEnabled, labels: labels, onSaved: () => { setPendingTick(0); load() }, onDeleted: () => { setPendingTick(0); load() } })))
3152
+ records.map((rec) => h(RecordCard, { key: rec.id, rec, score: rec.score, focus: focusRecord === rec.id, vectorOn: configured && vectorEnabled, labels: labels, onSaved: () => { setPendingTick(0); load() }, onDeleted: () => { setPendingTick(0); load() } })))
3045
3153
 
3046
3154
  // 服务页底部:一句号召 + 两个外链(Star / issue)。放在内容最后,不打扰上面的状态卡。
3047
3155
  const footer = h('div', { className: 'footer' },
@@ -3055,6 +3163,7 @@ window.__ModuleLoader__.load({
3055
3163
  const dataBody = h('div', { className: 'memp-body' },
3056
3164
  statsCard,
3057
3165
  toolbar,
3166
+ searchNoteNode,
3058
3167
  createForm,
3059
3168
  error ? h('div', { className: 'err' }, error) : null,
3060
3169
  h('div', { className: 'scroll' + (records.length > 0 || loading ? '' : ' is-empty') }, listBody),
package/lib/panel.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * 提供管理员 API(前缀路由 /memory/api):
11
11
  * GET /status 各 scope 记录数 + 待嵌入数 + 展示标签
12
12
  * GET /records ?scope=&q= 枚举/过滤记录
13
+ * GET /search ?scope=&q=&topK= 语义检索(向量 + 词法,provider 排序)
13
14
  * POST /update {id, content?, kind?, importance?, tags?, supersededBy?}
14
15
  * POST /delete {id}
15
16
  * scope 惰性加载是同步的(store.peek(),**读路径不创建**),无需 ready 门。内容编辑会作废旧
@@ -39,6 +40,7 @@ function writeJson(res, body, status = 200) {
39
40
  const CLIENT_ERROR_CODES = new Set([
40
41
  'SCOPE_INVALID', 'SCOPE_DISABLED', 'CONTENT_EMPTY', 'CONTENT_TOO_LONG',
41
42
  'SECRET_DETECTED', 'IMPORT_INVALID', 'IMPORT_TOO_LARGE', 'KIND_INVALID',
43
+ 'QUERY_EMPTY', 'QUERY_INVALID',
42
44
  ])
43
45
 
44
46
  function writeError(res, error) {
@@ -393,6 +395,34 @@ function collectAuditEntries(memory, query) {
393
395
  return out
394
396
  }
395
397
 
398
+ /** scope 选择 → 实际存在的 ScopeStore(读路径只用 peek,绝不通过 store.scope() 创建)。 */
399
+ function selectedStores(store, selection) {
400
+ if (selection === null) return store.allScopes()
401
+ return (Array.isArray(selection) ? selection : [selection])
402
+ .map((s) => store.peek(s))
403
+ .filter((s) => s !== undefined)
404
+ }
405
+
406
+ /**
407
+ * 面板的 scope 参数 → 要看的 scope 集合。
408
+ * null = 全部作用域
409
+ * string[] = 规范化后的 scope 键(current-session / current-project 由 provider 解析)
410
+ * 非法输入抛 400,合法但不存在的 scope 由 selectedStores 自然过滤成空集合。
411
+ */
412
+ function resolveScopeSelection(memory, rawScope) {
413
+ if (rawScope === null || rawScope === undefined || rawScope.trim() === '') return null
414
+ const normalized = normalizeScopeInput(rawScope)
415
+ if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
416
+ if (normalized.kind === 'all') return null
417
+ if (normalized.kind === 'current-session' || normalized.kind === 'current-project') {
418
+ // 面板不在某个 agent 里:按 provider 的读取集合解析('project' → 当前项目键);
419
+ // 解析不出会话时就退化为全部,而不是报错。
420
+ const refs = typeof memory.resolveReadScopes === 'function' ? memory.resolveReadScopes(undefined) : []
421
+ return refs.length > 0 ? refs : null
422
+ }
423
+ return normalized.scope ?? null
424
+ }
425
+
396
426
  async function handle(ctx, routePath, req, res) {
397
427
  const url = new URL(req.url ?? '/', 'http://dsh.local')
398
428
  const path = url.pathname.slice(routePath.length) || '/'
@@ -595,28 +625,7 @@ async function handle(ctx, routePath, req, res) {
595
625
  const idQuery = (url.searchParams.get('id') ?? '').trim()
596
626
  // scope 先过同一套规范化:非法 → 400(而不是当成一个陌生 scope 去建文件);
597
627
  // 合法但不存在的 scope → 空列表。`peek`/`peekScope`,**绝不通过 store.scope() 创建**。
598
- let scope = null
599
- if (rawScope !== null && rawScope.trim() !== '') {
600
- const normalized = normalizeScopeInput(rawScope)
601
- if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
602
- if (normalized.kind === 'all') {
603
- scope = null // 全部
604
- } else if (normalized.kind === 'current-session' || normalized.kind === 'current-project') {
605
- // 面板不在某个 agent 里:按 provider 的读取集合解析('project' → 当前项目键);
606
- // 解析不出会话时就退化为全部,而不是报错。
607
- const refs = typeof memory.resolveReadScopes === 'function' ? memory.resolveReadScopes(undefined) : []
608
- scope = refs.length > 0 ? refs : null
609
- } else {
610
- scope = normalized.scope ?? null
611
- }
612
- } else {
613
- scope = null
614
- }
615
- const stores = scope === null
616
- ? store.allScopes()
617
- : (Array.isArray(scope) ? scope : [scope])
618
- .map((s) => store.peek(s))
619
- .filter((s) => s !== undefined)
628
+ const stores = selectedStores(store, resolveScopeSelection(memory, rawScope))
620
629
  let records = []
621
630
  for (const s of stores) records.push(...collectScope(s))
622
631
  if (query) {
@@ -631,6 +640,84 @@ async function handle(ctx, routePath, req, res) {
631
640
  writeJson(res, { ok: true, value: { records } })
632
641
  return
633
642
  }
643
+ // 记录页的「语义检索」:和 memory_search 同一套召回排序(向量 + 词法 + 可选重排),
644
+ // 由 provider 的 searchForPanel 执行 —— 只读、不写访问计数,并报告向量通道是否
645
+ // 真的参与,面板据此如实标注「语义排序」还是「退回关键词」。
646
+ if (method === 'GET' && path === '/search') {
647
+ const text = (url.searchParams.get('q') ?? '').trim()
648
+ if (text === '') throw new ApiError(400, 'QUERY_EMPTY', '搜索内容不能为空')
649
+ let topK = 20
650
+ const rawTopK = (url.searchParams.get('topK') ?? '').trim()
651
+ if (rawTopK !== '') {
652
+ if (!/^\d+$/.test(rawTopK)) throw new ApiError(400, 'QUERY_INVALID', 'topK 必须是 1..50 的整数')
653
+ topK = Number(rawTopK)
654
+ if (topK < 1 || topK > 50) throw new ApiError(400, 'QUERY_INVALID', 'topK 必须在 1..50 之间')
655
+ }
656
+ const scopes = selectedStores(store, resolveScopeSelection(memory, url.searchParams.get('scope')))
657
+ const keys = scopes.map((s) => s.scope)
658
+ // 空集合不能交给旧 provider 的 search():它会退回"默认项目 + global",
659
+ // 等于点了一个不存在的 scope 却搜出别的 scope 的记录。
660
+ if (keys.length === 0) {
661
+ writeJson(res, { ok: true, value: { hits: [], mode: 'lexical', reason: 'no-records', embedded: 0, total: 0 } })
662
+ return
663
+ }
664
+ const totalRecords = scopes.reduce((n, s) => n + s.records.size, 0)
665
+ const wireHit = (hit) => {
666
+ const scopeStore = store.peek(hit.record.scope)
667
+ let supersededBy = null
668
+ if (scopeStore !== undefined) {
669
+ for (const other of scopeStore.records.values()) {
670
+ if (other.supersedes === hit.record.id) { supersededBy = other.id; break }
671
+ }
672
+ }
673
+ const record = wireRecord(
674
+ hit.record,
675
+ scopeStore ?? { embedPending: new Map(), vectors: new Map() },
676
+ supersededBy,
677
+ )
678
+ return typeof hit.score === 'number' ? { ...record, score: hit.score } : record
679
+ }
680
+ let result
681
+ if (typeof memory.searchForPanel === 'function') {
682
+ result = await memory.searchForPanel({ text, scopes: keys, topK })
683
+ } else if (typeof memory.search === 'function') {
684
+ // 旧 provider 没有面板专用入口:退回通用检索(会写访问计数),向量是否参与
685
+ // 只能按"有没有向量"来推断。
686
+ let embedded = 0
687
+ for (const s of scopes) embedded += s.vectors.size
688
+ const hits = await memory.search({ text, scopes: keys, topK })
689
+ result = {
690
+ hits,
691
+ mode: embedded > 0 ? 'vector' : 'lexical',
692
+ ...(embedded > 0 ? {} : { reason: 'no-vectors' }),
693
+ embedded,
694
+ total: totalRecords,
695
+ }
696
+ } else {
697
+ // 连检索接口都没有:退回 /records?q= 同口径的关键词过滤,面板不至于空转。
698
+ const lowercase = text.toLowerCase()
699
+ const hits = []
700
+ for (const s of scopes) {
701
+ for (const r of collectScope(s)) {
702
+ if (r.content.toLowerCase().includes(lowercase)
703
+ || r.kind.toLowerCase().includes(lowercase)
704
+ || r.tags.some((t) => t.toLowerCase().includes(lowercase))) hits.push({ record: r })
705
+ }
706
+ }
707
+ result = { hits: hits.slice(0, topK), mode: 'lexical', reason: 'provider-lexical', embedded: 0, total: totalRecords }
708
+ }
709
+ writeJson(res, {
710
+ ok: true,
711
+ value: {
712
+ hits: result.hits.slice(0, topK).map(wireHit),
713
+ mode: result.mode,
714
+ ...(result.reason !== undefined ? { reason: result.reason } : {}),
715
+ embedded: result.embedded ?? 0,
716
+ total: result.total ?? totalRecords,
717
+ },
718
+ })
719
+ return
720
+ }
634
721
  if (method === 'POST' && path === '/update') {
635
722
  const body = await readJsonBody(req)
636
723
  const id = String(body.id ?? '')
@@ -119,6 +119,11 @@ export class CordisMemoryService extends Service {
119
119
  return this.impl.search(query)
120
120
  }
121
121
 
122
+ /** 面板「语义检索」:同一套召回排序,只读且带向量通道状态。 */
123
+ searchForPanel(input ) {
124
+ return this.impl.searchForPanel(input)
125
+ }
126
+
122
127
  forget(input ) {
123
128
  return this.impl.forget(input)
124
129
  }
@@ -478,6 +478,23 @@ export function resolveConfig(config = {}) {
478
478
  }
479
479
  }
480
480
 
481
+ /** 面板语义检索的一次结果:排序规则与 memory_search 相同,但不写访问计数。 */
482
+
483
+
484
+
485
+
486
+
487
+
488
+
489
+                             
490
+
491
+              
492
+
493
+                       
494
+
495
+
496
+
497
+
481
498
  export class LocalMemoryService {
482
499
  cfg
483
500
  store
@@ -1455,6 +1472,11 @@ export class LocalMemoryService {
1455
1472
  const recallN = query.recallN ?? this.cfg.recallN
1456
1473
  const now = Date.now()
1457
1474
  const queryTokens = [...new Set(tokenize(query.text))]
1475
+ // 面板的语义检索复用这条流水线,但它是"看一眼"的浏览:不写访问计数,也不在
1476
+ // 没有任何向量时白跑一次嵌入请求。这两个开关只给面板的 searchForPanel 用,
1477
+ // 工具 / 注入调用不会传。
1478
+ const internal = query
1479
+ const allowVector = internal.vector !== false && this.cfg.vector.enabled && this.cfg.vector.configured
1458
1480
 
1459
1481
  // 候选 scope:显式 pin(单值)优先;否则用调用方给的合并集合(query.scopes,
1460
1482
  // 工具 / 注入传"会话 + 项目 + global");两者都没有才退回旧的 project + global。
@@ -1504,7 +1526,7 @@ export class LocalMemoryService {
1504
1526
  // --- channel 2: vector recall over embedded records ---
1505
1527
  // Skipped entirely when no backend is configured (lexical recall above
1506
1528
  // already produced the candidates; a request here would just fail).
1507
- const qvec = this.cfg.vector.enabled && this.cfg.vector.configured
1529
+ const qvec = allowVector
1508
1530
  ? await this.embed.embed([`${this.cfg.vector.queryPrefix ?? ''}${query.text}`], query.signal).catch(() => null)
1509
1531
  : null
1510
1532
  if (qvec?.[0]) {
@@ -1575,12 +1597,73 @@ export class LocalMemoryService {
1575
1597
  }
1576
1598
  }
1577
1599
 
1578
- const hits = ranked.map((c) => ({ record: touch(c.record), score: round4(finalScores.get(c.id) ) }))
1600
+ const hits = ranked.map((c) => ({
1601
+ record: internal.touch === false ? c.record : touch(c.record),
1602
+ score: round4(finalScores.get(c.id) ),
1603
+ }))
1579
1604
 
1580
1605
  this.store.scheduleFlush()
1581
1606
  return hits.slice(0, topK)
1582
1607
  }
1583
1608
 
1609
+ /**
1610
+ * 面板「语义检索」:和 memory_search 走**同一套**双通道召回与打分(向量 + 词法 +
1611
+ * 可选重排),区别只有两点:
1612
+ * 1. 只读浏览器:不 `touch` 记录(访问计数/最近访问时间是检索排序的输入,
1613
+ * 面板里浏览一次不该把排序带偏);
1614
+ * 2. 报告这一次向量通道到底有没有参与 —— 面板得如实写「语义排序」还是
1615
+ * 「向量没跑起来,按关键词排」,而不是把词法结果冒充语义结果。
1616
+ *
1617
+ * `scopes` 由面板显式给出(全部作用域或下拉选中的那个),不做"默认项目"回退。
1618
+ */
1619
+ async searchForPanel(input ) {
1620
+ const scopes = []
1621
+ const seen = new Set ()
1622
+ let total = 0
1623
+ let embedded = 0
1624
+ for (const raw of input.scopes) {
1625
+ const scope = this.canonicalScope(raw)
1626
+ if (seen.has(scope)) continue
1627
+ seen.add(scope)
1628
+ const store = this.store.peek(scope) // 只读:不创建 scope
1629
+ if (!store) continue
1630
+ scopes.push(scope)
1631
+ total += store.records.size
1632
+ embedded += store.vectors.size
1633
+ }
1634
+ const configured = this.cfg.vector.enabled && this.cfg.vector.configured
1635
+ // 空集合不能交给 search():它在 scopes 为空时会退回"默认项目 + global",
1636
+ // 那等于用户点了一个不存在的 scope 却搜出别的 scope 的记录。
1637
+ if (scopes.length === 0) {
1638
+ return {
1639
+ hits: [],
1640
+ mode: 'lexical',
1641
+ reason: 'no-records',
1642
+ embedded: 0,
1643
+ total: 0,
1644
+ }
1645
+ }
1646
+ // 没有向量 / 嵌入服务已被熔断时不要白打一次请求:直接走词法通道。
1647
+ const vector = configured && embedded > 0 && this.embed.isHealthy
1648
+ const hits = await this.search({
1649
+ text: input.text,
1650
+ scopes,
1651
+ topK: input.topK ?? 20,
1652
+ vector,
1653
+ touch: false,
1654
+ } )
1655
+ // 嵌入请求失败会被 EmbedClient 熔断(markDown),所以"跑完还健康"就等于向量通道
1656
+ // 真的产出了分数;否则这次只能算词法排序。
1657
+ const vectorRan = vector && this.embed.isHealthy
1658
+ return {
1659
+ hits,
1660
+ mode: vectorRan ? 'vector' : 'lexical',
1661
+ ...(vectorRan ? {} : { reason: !configured ? 'vector-disabled' : total === 0 ? 'no-records' : embedded === 0 ? 'no-vectors' : 'embed-failed' }),
1662
+ embedded,
1663
+ total,
1664
+ }
1665
+ }
1666
+
1584
1667
  findById(id ) {
1585
1668
  for (const s of this.store.allScopes()) {
1586
1669
  const r = s.records.get(id)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.12.6",
3
+ "version": "0.13.0",
4
4
  "description": "DeepSeek Harness 记忆系统(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 五个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",