@restregular/dsh-memory 0.17.0 → 0.18.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,31 @@
2
2
 
3
3
  本项目的版本记录。安装 id 与 npm 版本一一对应。
4
4
 
5
+ ## 0.18.0 — 会话级「记忆可见范围」+ 规则注入带 ID / 摘要说明
6
+
7
+ - **输入框新增「记忆范围」按钮**:挂在宿主 `conversation.input.right` 槽(会话输入框工具行右侧),点开按当前会话列出可选作用域(当前会话 / 当前项目 / global / 自定义),勾选后立即生效。有覆盖时按钮显示「记忆 N」并高亮。
8
+ - **可见范围是会话级白名单**:本会话的 Agent 及其子 Agent 只检索、只注入、只 `memory_get` 勾选范围内的记忆。
9
+ - `memory_search` / `memory_list` 的默认集合与 `scope:'all'` 都收窄到白名单;显式询问范围外的 scope 返回 `SCOPE_NOT_VISIBLE`。
10
+ - `memory_get` 按 id 取正文时也会过滤:范围外记录的正文不会被取出(`missing` 里照常报告)。
11
+ - 召回 / 摘要 / 规则 / 流程索引 / 行为召回都走同一份 `resolveReadScopes`,不需要分别改。
12
+ - 显式可见范围设置后,`inject.extraScopes` 与 fork 父会话都不再撑大读取集合;空数组保持为空。
13
+ - **子 Agent 继承**:子 Agent 的 session scope 继续映射到父会话;可见范围沿真实会话 id + `parentSession` 链向上查找,根会话设置一次即可覆盖整棵子 Agent 树。子 Agent 自己再设置只影响它自己。
14
+ - **持久化**:覆盖按会话写到 `<storeDir>/visibility/<session>.json`(临时文件 + rename),与记忆数据同目录;没有文件 = 使用默认三路集合。「恢复默认」删除文件。
15
+ - **面板 API**:新增 `GET /memory/api/visibility?session=<id>` 与 `POST /memory/api/visibility { session, scopes: string[] | null }`,返回自己的覆盖 / 实际生效集合 / 是否继承 / 可勾选目录;`scopes` 必须是具体作用域键,空数组与 `all` / 裸 `project` / 裸 `session` 会被拒绝。
16
+ - **硬性规则带 ID 并标注摘要**:系统提示「硬性规则」段与新规则增量块每行改为 ``- `<8位id>` <正文摘要>``;段头明确说明注入的是摘要,需要完整规则时用 `memory_get` 按 ID 取全文。规则去重仍按整行比对,格式变更会在旧会话触发一次全量提醒(带上了 ID,属于预期的一次性迁移)。
17
+ - 测试:provider 覆盖解析 / 子 Agent 链式继承 / scope 开关过滤 / 落盘重读、工具层白名单(search / list / get / all / 显式 scope)、面板 GET/POST /visibility、输入框按钮渲染与保存请求、规则行格式与段头文案、注入范围不被 extraScopes 撑大。
18
+
19
+ ## 0.17.1 — memory_save 成功即把这条记忆记为「正文已注入」
20
+
21
+ - **现象**:在同一个会话里 `memory_save` 成功后,下一轮(或同一轮后续步骤)的召回会把刚保存的那条记忆再注入一遍,然后再被会话级去重标记。实况样本:某会话 turn 1 末尾保存一条发布记录,turn 2 第一步的召回又把它作为「相关记忆」塞回上下文,之后同一条再也不出现。
22
+ - **根因**:0.16.1 只把 `memory_get` 取正文记成 `content_injected`;`memory_save` 的正文其实也进了上下文 —— 写入语句就是模型产出的 `tool/call` 参数 —— 但保存路径没有写会话注入状态,于是下一次召回把它当成「还没注入过的新记忆」。
23
+ - **修复**:`session/event` 里跟踪 `memory_save` 的 `callId`;`tool/result` 成功、且能从结果里解析出记录 id 时(`getByIds` 再校验存在性),把该记录按 `updatedAt` 记为 `content_injected`。
24
+ - 只按 UUID 形态解析记录 id,不依赖结果文案,本地化 / 措辞改动不会让去重失效。
25
+ - 保存失败 / 被拒绝不标记;记录之后被更新(`updatedAt` 变化)仍会重新评估并重新注入。
26
+ - 去重标记独立于 `autoRecall` 开关,和 `memory_get` 的口径一致;compaction 时随会话状态一起清空。
27
+ - **审计**:保存成功时写一条 `kind=lifecycle / stage=content_pinned / reasonCode=saved_in_context` 事件(带 `operationId` = 这次 save 的 callId、`selected.contentIds`),面板按记忆 id 能查到「它为什么后面被去重跳过」。
28
+ - 回归测试:结果解析(保存 / 去重命中 / 非中文文案 / 无 id)、成功后下一次召回被去重且审计可见、保存失败不标记、版本变化重新注入、去重命中同样标记。
29
+
5
30
  ## 0.17.0 — 会话去重状态持久化到工作区 `.dsh/dsh-memory`
6
31
 
7
32
  - **状态现在可以跨插件重载 / 宿主重启恢复**:`InjectionState` 可按会话挂一个持久化 store,首次接触会话时读一次盘,之后写入由 store 合并。
package/README.md CHANGED
@@ -44,7 +44,8 @@ JSONL 落盘 · 本机向量检索 · 五个模型工具 · 自动召回 · 硬
44
44
  | **双通道检索** | 词法(IDF + 中文 bigram)**+** 向量(本机 llama-server 的 OpenAI 兼容 `/v1/embeddings`)。向量缺席自动降级,不报错、不阻塞 |
45
45
  | **自动召回** | 每轮按用户问题召回;新会话第一步注入项目 / global 摘要;发布、部署、工具失败等行为按标签触发定向召回 |
46
46
  | **印象形态** | 每轮只给每条记忆的短摘要;模型判断相关但需要细节时再 `memory_get` 取全文,省 token 也不丢信息 |
47
- | **硬性规则** | `kind: rule` 进系统提示常驻段;旧会话会收到新增 / 编辑提醒;超预算有明确警告,不静默丢弃 |
47
+ | **硬性规则** | `kind: rule` 进系统提示常驻段;行首带 8 位 id,注入的是摘要,需要全文时用 `memory_get`;旧会话会收到新增 / 编辑提醒;超预算有明确警告,不静默丢弃 |
48
+ | **会话可见范围** | 输入框旁的「记忆范围」按钮设置本会话可读的作用域;Agent 及其子 Agent 都按这个白名单检索、注入与 `memory_get` |
48
49
  | **状态记忆** | `kind: state` 默认 7 天 TTL;注入带「状态,使用前验证」;过期后默认不进检索 / 摘要 / 召回,但 `memory_get` 与面板仍可取 |
49
50
  | **流程索引** | `kind: procedure` 的目录进系统提示:按当前工作区 + 触发词(工具名 / 关键词)列 `id · 触发词 → 标题`,需要时再用 `memory_get` 取全文 |
50
51
  | **可视化管理** | 记录浏览 / 搜索 / 新建 / 编辑 / 删除;**记录页可主动做语义检索**(与 `memory_search` 同一套排序);记忆树展示作用域、类型与修正链;设置改完即存;导入导出 |
@@ -80,6 +81,16 @@ JSONL 落盘 · 本机向量检索 · 五个模型工具 · 自动召回 · 硬
80
81
 
81
82
  ![记忆设置](https://raw.githubusercontent.com/RestRegular/dsh-memory/main/preview/memory-settings.png)
82
83
 
84
+ ### 输入框的记忆可见范围
85
+
86
+ 输入框工具行右侧有「记忆范围」按钮(有覆盖时显示「记忆 N」并高亮)。点开后按当前会话列出可选作用域:当前会话 / 当前项目 / global / 已有自定义作用域,勾选后保存。
87
+
88
+ - 这是**会话级**白名单:本会话的 Agent 及其子 Agent 只检索、只注入、只 `memory_get` 勾选范围内的记忆;未勾选的范围不会被 `memory_search` / `memory_list` 看到,`memory_get` 也取不到正文。
89
+ - 子 Agent 自动继承父会话 / 根会话的设置;在子 Agent 自己的会话里再设置,只影响那一个会话。
90
+ - 「恢复默认」清除覆盖,回到「会话 + 项目 + global」的默认读取集合。
91
+ - 覆盖按会话落盘在 `<storeDir>/visibility/<session>.json`,浏览器刷新 / 插件重载后仍在。
92
+ - 只影响**读取**:`memory_save` 的落点仍由 `scope` 参数与默认写口径决定;面板管理页不受可见范围限制。
93
+
83
94
  ### 向量服务
84
95
 
85
96
  在本机托管 `llama-server`,下载运行时与模型;内置清单为每个模型配好 `dims` 与 `pooling`,
@@ -212,7 +223,7 @@ memory_forget({ "id": "3f2a9c1d" }) // 按内容删:memory_forget({ q
212
223
  | `recall` | 每轮 `agent/pre-step` | 按本轮用户问题检索,按 topK / token 预算注入;默认只给每条 120 字摘要 + `memory_get` 指引 |
213
224
  | `digest` | 会话第一步 | 注入项目 + global 概览:按重要度 × 新鲜度挑选;`kind=rule` 不进摘要(已常驻系统提示);正文超预算时附可检索的标签索引 |
214
225
  | `policy` | 系统提示常驻 | 什么时候查记忆、查到怎么复用、查不到时低风险推断 / 高风险先问用户 |
215
- | `rules` | 系统提示常驻 | `kind: rule` 的硬性规则,限量与预算;`mandatory` / `pinned` 排在最前 |
226
+ | `rules` | 系统提示常驻 | `kind: rule` 的硬性规则摘要;每行 `id · 正文`,需要全文时 `memory_get`;限量与预算;`mandatory` / `pinned` 排在最前 |
216
227
  | `procedures` | 系统提示常驻 | `kind: procedure` 的目录:当前工作区 + 触发词命中的流程,每行 `id · 触发词 → 标题`;正文按需 `memory_get` |
217
228
  | `turnEnd` | 每轮结束(默认关) | 下一轮开头提醒「有可复用结论先落盘」 |
218
229
  | 行为召回 | 可见文本 / 任务 / 命令 / 工具失败 | 命中标签后,在**下一个** `agent/pre-step` 定向检索;工具失败优先用该工具自己的 description |
@@ -227,6 +238,8 @@ memory_forget({ "id": "3f2a9c1d" }) // 按内容删:memory_forget({ q
227
238
  的规则快照」与当前规则:新增、以及编辑过(同一 id 的行变了)的规则都补一条提醒,没变化不重复;
228
239
  宿主重启用历史里的规则行做种子,不会整批重提醒。关掉它只停提醒,常驻段与检索照旧。
229
240
 
241
+ 规则段注入的是**摘要**:每行是 ``- `<8位id>` <正文前240字>``。段头会明确说明这一点,模型需要完整规则或细节时用 `memory_get` 按 ID 取;因此规则再长也不会把整段正文常驻在系统提示里。
242
+
230
243
  ### 流程索引(procedure)
231
244
 
232
245
  流程通常很长,全部常驻会挤爆系统提示;而注入发生在 `agent/pre-step`,模型决定调用工具之前拿不到工具名。
@@ -239,6 +252,7 @@ memory_forget({ "id": "3f2a9c1d" }) // 按内容删:memory_forget({ q
239
252
 
240
253
  - 召回按 **sessionId + 记忆 id / 版本** 去重;只给过标签的记录,任务命中后可补正文;内容更新会重新评估。
241
254
  - `memory_get` 取到正文后,这条记忆会记成「正文已注入」;同一会话后续的普通召回 / 摘要 / 自动召回都不会再把同一段正文塞一遍。只取 `summary` / `tags` / 元数据不算正文,仍可被召回。
255
+ - `memory_save` **保存成功**同样算「正文已在上下文里」:写入语句(`content`)就是模型自己产出的 tool/call 参数,因此这条记录会立刻记成「正文已注入」,本会话后续的召回 / 摘要不会把刚保存的记忆原样再注入一次(去重命中既有记录时也一样)。保存失败不标记;记录之后被更新(`updatedAt` 变化)仍会重新评估。审计里会留一条 `content_pinned / saved_in_context` 的 lifecycle 事件,说明后面的「去重跳过」从哪来。
242
256
  - **去重状态持久化**:状态写到会话工作区的插件目录
243
257
  `<cwd>/.dsh/dsh-memory/sessions/<session>.jsonl`,插件重载 / 宿主重启后自动恢复;只有首次接触该会话时读一次盘。
244
258
  - 只存记录 id、状态、版本(`updatedAt`)和时间戳,**不存正文,也不存查询**。
@@ -348,6 +362,7 @@ retrieval:
348
362
  | `<storeDir>/projects/<sha1(scope)>.vec` | 向量边车;首行 `#<model>\t<dims>\t<pooling>`,后面每行 `id\t<base64 向量>` |
349
363
  | `<storeDir>/settings.json` | 面板设置(覆盖配置文件里的默认值) |
350
364
  | `<storeDir>/scopes.json` | 项目作用域别名(显示名 → `project:<路径>`) |
365
+ | `<storeDir>/visibility/<session>.json` | 会话「记忆可见范围」覆盖;没有文件 = 使用默认三路集合 |
351
366
  | `<storeDir>/*.lock` | 跨进程写锁;陈旧锁(持有者已死或 10s 未动)会被接管 |
352
367
  | `<installRoot>/llamacpp/` | llama-server 运行时、依赖 dll、`llama-server.log` |
353
368
  | `<installRoot>/models/` | 下载的 GGUF 模型 |
@@ -403,10 +418,15 @@ GET /memory/api/audit/stats
403
418
  GET /memory/api/audit/export?format=json|jsonl&<same filters>
404
419
 
405
420
  GET /memory/api/anchor?session=<id>&turn=<n>&step=<n>&callId=<optional>
421
+
422
+ GET /memory/api/visibility?session=<id>
423
+ POST /memory/api/visibility { session: "<id>", scopes: ["session:<id>", "project:<cwd>", "global"] | null }
406
424
  ```
407
425
 
408
426
  响应为 `{ ok: true, value: { entries, total, nextCursor?, stats, query } }`。旧调用 `GET /audit?session=<id>` 仍兼容;不带 `session` 时查询全部会话,`query.scope` 会标记为 `all`。
409
427
 
428
+ `/visibility` 返回 `{ sessionId, override, effective, inherited, scopes }`:`override` 是该会话自己的覆盖(`null` = 使用默认集合),`effective` 是当前实际生效的读取范围,`inherited` 表示是否继承自父会话,`scopes` 是可勾选的作用域目录(含 `label` 与记录数)。保存 `scopes: null` 即恢复默认;空数组会被拒绝(至少保留一个范围)。
429
+
410
430
  ### 和会话轨迹互相跳转
411
431
 
412
432
  DSH 自带的 Trajectory 面板是一个**纯投影**:它只声明 `conversation.trajectory.images` 一个子槽,没有行/列扩展点,选中状态也只存在组件内部。因此插件不能直接往轨迹表格里插审计行。当前采用的是一条不碰轨迹 React 树的组合:
package/lib/client.js CHANGED
@@ -485,6 +485,24 @@ window.__ModuleLoader__.load({
485
485
  '.mem-traj-mark:focus-visible{outline:1px solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:1px}',
486
486
  '@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}}',
487
487
  '@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)}}',
488
+ '.mem-scope-btn{display:inline-flex;align-items:center;gap:5px;height:28px;padding:0 8px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1;cursor:pointer;flex:none}',
489
+ '.mem-scope-btn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}',
490
+ '.mem-scope-btn.on{color:var(--dsw-alias-brand-primary);border-color:color-mix(in srgb,var(--dsw-alias-brand-primary) 45%,var(--dsw-alias-border-l1))}',
491
+ '.mem-scope-btn svg{flex:none}',
492
+ '.mem-scope-pop{position:fixed;z-index:80;width:300px;max-height:min(460px,62vh);display:flex;flex-direction:column;gap:10px;padding:12px;border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:var(--dsw-specific-menu,var(--dsw-alias-bg-layer-1));box-shadow:var(--dsw-elevation-panel,0 10px 30px rgba(0,0,0,.22));color:var(--dsw-alias-label-primary);font-size:13px}',
493
+ '.mem-scope-pop h4{margin:0;font-size:13px;font-weight:600;line-height:1.4}',
494
+ '.mem-scope-pop .hint{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.55}',
495
+ '.mem-scope-list{display:flex;flex-direction:column;gap:2px;overflow:auto;min-height:0;padding:2px 0}',
496
+ '.mem-scope-item{display:flex;align-items:center;gap:8px;padding:6px;border-radius:7px;cursor:pointer}',
497
+ '.mem-scope-item:hover{background:var(--dsw-alias-interactive-bg-hover)}',
498
+ '.mem-scope-item input{margin:0;flex:none}',
499
+ '.mem-scope-item .lab{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
500
+ '.mem-scope-item .cnt{flex:none;color:var(--dsw-alias-label-secondary);font-size:11px}',
501
+ '.mem-scope-foot{display:flex;align-items:center;gap:8px;justify-content:flex-end}',
502
+ '.mem-scope-foot .spacer{flex:1}',
503
+ '.mem-scope-foot button{padding:5px 12px;font-size:12px}',
504
+ '.mem-scope-foot button.primary{background:var(--dsw-alias-brand-primary);border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-label-on-brand,#fff)}',
505
+ '.mem-scope-err{color:var(--dsw-alias-state-error-primary,#d33);font-size:12px;line-height:1.5}',
488
506
  ].join('')
489
507
 
490
508
  async function api(method, body) {
@@ -4311,6 +4329,169 @@ window.__ModuleLoader__.load({
4311
4329
  )
4312
4330
  }
4313
4331
 
4332
+ /**
4333
+ * 输入框里的「记忆可见范围」按钮。
4334
+ *
4335
+ * 宿主 `conversation.input.right` 是 session 作用域的 list 槽,owner 会把
4336
+ * `sessionId` 作为标准 prop 传进来,所以这里不需要 register 的 inject。
4337
+ *
4338
+ * 读写走 /memory/api/visibility:
4339
+ * GET ?session=<id> → { override, effective, inherited, scopes }
4340
+ * POST { session, scopes: string[] | null } → 同上
4341
+ * `override === null` = 使用默认三路集合;子 Agent 会话会继承父会话的 override。
4342
+ *
4343
+ * 弹层用 fixed 定位(按按钮 rect 往上开),避免被 composer 的 overflow 裁掉。
4344
+ */
4345
+ function MemoryVisibilityButton({ sessionId } = {}) {
4346
+ const [open, setOpen] = React.useState(false)
4347
+ const [loading, setLoading] = React.useState(false)
4348
+ const [busy, setBusy] = React.useState(false)
4349
+ const [error, setError] = React.useState('')
4350
+ const [data, setData] = React.useState(null)
4351
+ const [selected, setSelected] = React.useState([])
4352
+ const [anchor, setAnchor] = React.useState(null)
4353
+ const wrapRef = React.useRef(null)
4354
+
4355
+ React.useEffect(() => {
4356
+ if (!open) return undefined
4357
+ if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return undefined
4358
+ const onDown = (event) => {
4359
+ try {
4360
+ const node = wrapRef.current
4361
+ if (node && typeof node.contains === 'function' && !node.contains(event.target)) setOpen(false)
4362
+ } catch { /* 关闭失败不影响页面 */ }
4363
+ }
4364
+ const onKey = (event) => { if (event && event.key === 'Escape') setOpen(false) }
4365
+ document.addEventListener('mousedown', onDown)
4366
+ document.addEventListener('keydown', onKey)
4367
+ return () => {
4368
+ try {
4369
+ document.removeEventListener('mousedown', onDown)
4370
+ document.removeEventListener('keydown', onKey)
4371
+ } catch { /* 宿主卸载时 document 可能已不可用 */ }
4372
+ }
4373
+ }, [open])
4374
+
4375
+ if (typeof sessionId !== 'string' || sessionId === '') return null
4376
+
4377
+ const applyPayload = (value) => {
4378
+ if (!value || typeof value !== 'object') return
4379
+ setData(value)
4380
+ const next = Array.isArray(value.override)
4381
+ ? value.override
4382
+ : Array.isArray(value.effective) ? value.effective : []
4383
+ setSelected([...next])
4384
+ }
4385
+
4386
+ const load = () => {
4387
+ setLoading(true)
4388
+ setError('')
4389
+ api(`visibility?session=${encodeURIComponent(sessionId)}`)
4390
+ .then(applyPayload)
4391
+ .catch((e) => setError(String((e && e.message) || e)))
4392
+ .finally(() => setLoading(false))
4393
+ }
4394
+
4395
+ const toggle = (event) => {
4396
+ if (open) { setOpen(false); return }
4397
+ let nextAnchor = null
4398
+ try {
4399
+ const rect = event && event.currentTarget && event.currentTarget.getBoundingClientRect
4400
+ ? event.currentTarget.getBoundingClientRect()
4401
+ : null
4402
+ if (rect) nextAnchor = { left: rect.left, top: rect.top }
4403
+ } catch { nextAnchor = null }
4404
+ setAnchor(nextAnchor)
4405
+ setOpen(true)
4406
+ load()
4407
+ }
4408
+
4409
+ const toggleScope = (scope) => {
4410
+ setSelected((prev) => prev.includes(scope) ? prev.filter((item) => item !== scope) : [...prev, scope])
4411
+ }
4412
+
4413
+ const save = (scopes) => {
4414
+ setBusy(true)
4415
+ setError('')
4416
+ api('visibility', { session: sessionId, scopes })
4417
+ .then((value) => {
4418
+ applyPayload(value)
4419
+ setOpen(false)
4420
+ })
4421
+ .catch((e) => setError(String((e && e.message) || e)))
4422
+ .finally(() => setBusy(false))
4423
+ }
4424
+
4425
+ const scopes = data && Array.isArray(data.scopes) ? data.scopes : []
4426
+ const hasOverride = Boolean(data && Array.isArray(data.override))
4427
+ const count = selected.length
4428
+ let popStyle = {}
4429
+ if (anchor) {
4430
+ const width = 300
4431
+ const margin = 8
4432
+ const viewportW = (typeof window !== 'undefined' && Number(window.innerWidth)) || 1024
4433
+ const viewportH = (typeof window !== 'undefined' && Number(window.innerHeight)) || 768
4434
+ popStyle = {
4435
+ left: Math.min(Math.max(margin, anchor.left), Math.max(margin, viewportW - width - margin)),
4436
+ bottom: Math.max(margin, viewportH - anchor.top + 8),
4437
+ }
4438
+ }
4439
+
4440
+ return h('span', { className: 'mem-scope-wrap', ref: wrapRef },
4441
+ h('button', {
4442
+ type: 'button',
4443
+ className: `mem-scope-btn${hasOverride ? ' on' : ''}`,
4444
+ title: '记忆可见范围(本会话及子 Agent)',
4445
+ 'aria-label': '记忆可见范围',
4446
+ 'aria-expanded': open,
4447
+ onMouseDown: (event) => { try { event.preventDefault() } catch { /* keepFocus */ } },
4448
+ onClick: toggle,
4449
+ },
4450
+ h(NavLineIcon, { size: 14 }),
4451
+ h('span', null, count > 0 ? `记忆 ${count}` : '记忆范围'),
4452
+ ),
4453
+ open ? h('div', { className: 'mem-scope-pop', style: popStyle, role: 'dialog', 'aria-label': '记忆可见范围' },
4454
+ h('h4', null, '记忆可见范围'),
4455
+ h('div', { className: 'hint' },
4456
+ '本会话的 Agent 及其子 Agent 只能检索和读取勾选的范围;未勾选的范围不会被注入。'),
4457
+ data && data.inherited
4458
+ ? h('div', { className: 'hint' }, '当前继承自父会话;保存后在本会话独立生效。')
4459
+ : null,
4460
+ loading
4461
+ ? h('div', { className: 'hint' }, '读取中…')
4462
+ : h('div', { className: 'mem-scope-list' },
4463
+ scopes.length === 0
4464
+ ? h('div', { className: 'hint' }, '还没有可选的范围。')
4465
+ : scopes.map((item) => h('label', { className: 'mem-scope-item', key: item.scope },
4466
+ h('input', {
4467
+ type: 'checkbox',
4468
+ checked: selected.includes(item.scope),
4469
+ onChange: () => toggleScope(item.scope),
4470
+ }),
4471
+ h('span', { className: 'lab', title: item.scope }, item.label || item.scope),
4472
+ h('span', { className: 'cnt' }, `${item.records ?? 0}`),
4473
+ )),
4474
+ ),
4475
+ error ? h('div', { className: 'mem-scope-err' }, error) : null,
4476
+ h('div', { className: 'mem-scope-foot' },
4477
+ h('button', {
4478
+ type: 'button',
4479
+ className: 'linkbtn',
4480
+ disabled: busy || !data || data.override === null,
4481
+ onClick: () => save(null),
4482
+ }, '恢复默认'),
4483
+ h('span', { className: 'spacer' }),
4484
+ h('button', {
4485
+ type: 'button',
4486
+ className: 'primary',
4487
+ disabled: busy || selected.length === 0,
4488
+ onClick: () => save(selected),
4489
+ }, busy ? '保存中…' : '保存'),
4490
+ ),
4491
+ ) : null,
4492
+ )
4493
+ }
4494
+
4314
4495
  function apply(ctx) {
4315
4496
  try {
4316
4497
  const styleEl = document.createElement('style')
@@ -4414,6 +4595,18 @@ window.__ModuleLoader__.load({
4414
4595
  } catch (error) {
4415
4596
  console.warn('[dsh-memory] 记忆审计视图注册失败:', error?.message)
4416
4597
  }
4598
+ // 输入框工具行右侧:本会话「记忆可见范围」按钮。session 作用域的 list 槽,
4599
+ // owner 会把 sessionId 作为标准 prop 传进来;旧宿主没有这个槽时只少一个入口。
4600
+ try {
4601
+ slots.inject('conversation.input.right', () => slots.register({
4602
+ name: 'conversation.input.right',
4603
+ id: 'memory-visibility',
4604
+ order: 30,
4605
+ label: () => '记忆范围',
4606
+ }, MemoryVisibilityButton))
4607
+ } catch (error) {
4608
+ console.warn('[dsh-memory] 记忆可见范围按钮注册失败:', error?.message)
4609
+ }
4417
4610
  try {
4418
4611
  slots.inject('shell.overlay', () => slots.register({
4419
4612
  name: 'shell.overlay',
@@ -4558,6 +4751,7 @@ window.__ModuleLoader__.load({
4558
4751
  MemoryTreeTab: MemoryTreeTab,
4559
4752
  SettingsTab: SettingsTab,
4560
4753
  AuditTab: AuditTab,
4754
+ MemoryVisibilityButton: MemoryVisibilityButton,
4561
4755
  buildMemoryTree: buildMemoryTree,
4562
4756
  KIND_META: KIND_META,
4563
4757
  CSS: CSS,
@@ -67,6 +67,7 @@ import {
67
67
  highRiskSignal,
68
68
  memoryGetRequestsContent,
69
69
  memoryGetResultIds,
70
+ memorySaveResultIds,
70
71
  textTagSignal,
71
72
  todoText,
72
73
  toolCallDescription,
@@ -149,6 +150,8 @@ export function apply(ctx , config = {}) {
149
150
  const callMeta = new Map ()
150
151
  /** memory_get 调用 → 这次是否取正文;tool/result 到达后用来写 content_injected。 */
151
152
  const memoryGetCalls = new Map ()
153
+ /** memory_save 调用中还没等到结果的 callId;成功后把被保存的记录记为 content_injected。 */
154
+ const memorySaveCalls = new Set ()
152
155
  const sessionScopes = new Map ()
153
156
  const sessionAutoScopes = new Map ()
154
157
  /** 本轮已经发生过的 signal 驱动召回:每轮最多一次,同 tag/query 也跳过。 */
@@ -235,6 +238,11 @@ export function apply(ctx , config = {}) {
235
238
 
236
239
  /** 系统提示 rules 段实际使用的 scope(与 section 回调保持同一口径)。 */
237
240
  const promptScopesFor = (memory , agent ) => {
241
+ try {
242
+ // 显式可见范围是白名单,空数组也照用(表示本会话看不到任何规则)。
243
+ const explicit = memory.visibleScopes?.(agent)
244
+ if (Array.isArray(explicit)) return explicit
245
+ } catch { /* fallthrough */ }
238
246
  try {
239
247
  const resolved = memory.resolveReadScopes?.(agent)
240
248
  if (Array.isArray(resolved) && resolved.length > 0) return resolved
@@ -290,6 +298,54 @@ export function apply(ctx , config = {}) {
290
298
  } catch { /* 去重状态是尽力而为,不能影响工具结果 */ }
291
299
  }
292
300
 
301
+ /** 记住这次 memory_save 的 callId;结果成功到达后才知道记录 id。 */
302
+ const rememberMemorySaveCall = (callId ) => {
303
+ if (typeof callId !== 'string' || callId === '') return
304
+ memorySaveCalls.add(callId)
305
+ if (memorySaveCalls.size > 500) {
306
+ const oldest = memorySaveCalls.values().next()
307
+ if (!oldest.done) memorySaveCalls.delete(oldest.value)
308
+ }
309
+ }
310
+
311
+ /**
312
+ * memory_save 成功 → 这条记忆的正文**已经由模型自己写进上下文**(写入语句就在
313
+ * tool/call 的参数里),和 memory_get 取正文同一口径记为 content_injected:
314
+ * 本会话后续的摘要 / 召回不再把刚写进去的内容原样塞回来(0.17.0 之前的实况是
315
+ * 下一轮 recall 会把保存的记忆再注入一遍,然后才被去重)。
316
+ *
317
+ * 只在保存成功时标记:失败 / 被拒绝的保存没有可信的记录 id,也没有"正文已在
318
+ * 上下文里"这一事实。与 memory_get 一样,去重标记独立于 autoRecall 开关。
319
+ */
320
+ const markMemorySaveContent = (
321
+ sessionId ,
322
+ memory ,
323
+ event ,
324
+ context = {},
325
+ ) => {
326
+ try {
327
+ const ids = memorySaveResultIds(event)
328
+ if (ids.length === 0 || typeof memory.getByIds !== 'function') return
329
+ const found = memory.getByIds(ids)
330
+ if (found.length === 0) return
331
+ injectionState.markContent(sessionId, found.map((record) => ({ id: record.id, updatedAt: record.updatedAt })))
332
+ // 这条状态变化要能从审计里查到,否则后续 recall 的 dedup 列表会显得没来由。
333
+ recordAudit({
334
+ kind: 'lifecycle',
335
+ channel: 'lifecycle',
336
+ stage: 'content_pinned',
337
+ outcome: 'success',
338
+ reasonCode: 'saved_in_context',
339
+ trigger: 'memory_save',
340
+ sessionId,
341
+ ...(context.callId !== undefined ? { operationId: context.callId } : {}),
342
+ ...(context.turn !== undefined ? { turn: context.turn } : {}),
343
+ ...(context.step !== undefined ? { step: context.step } : {}),
344
+ selected: { contentIds: found.map((record) => record.id), hintIds: [], count: found.length },
345
+ })
346
+ } catch { /* 去重状态是尽力而为,不能影响工具结果 */ }
347
+ }
348
+
293
349
  /** 记录本会话最近用过的工具名,给流程索引做触发词匹配。 */
294
350
  const rememberProcedureTool = (sessionId , tool ) => {
295
351
  const recent = procedureTools.get(sessionId) ?? []
@@ -511,6 +567,7 @@ export function apply(ctx , config = {}) {
511
567
  for (const key of tagCache.keys()) if (key.startsWith(`${sessionId}|`)) tagCache.delete(key)
512
568
  callMeta.clear()
513
569
  memoryGetCalls.clear()
570
+ memorySaveCalls.clear()
514
571
  return
515
572
  }
516
573
 
@@ -518,13 +575,24 @@ export function apply(ctx , config = {}) {
518
575
  // 普通每轮召回 / 摘要仍会注入同一段正文。这里在 autoRecall 闸门前记录。
519
576
  if (type === 'tool/call' && data.name === 'memory_get') {
520
577
  rememberMemoryGetCall(data.callId, memoryGetRequestsContent(data.arguments))
578
+ } else if (type === 'tool/call' && data.name === 'memory_save') {
579
+ rememberMemorySaveCall(data.callId)
521
580
  } else if (type === 'tool/result') {
522
581
  const callId = (data.message )?.source?.callId
523
582
  if (typeof callId === 'string') {
524
583
  const takesContent = memoryGetCalls.get(callId)
525
584
  memoryGetCalls.delete(callId)
526
- if (takesContent === true && memory !== undefined && !toolResultFailure(event).isError) {
585
+ const isError = toolResultFailure(event).isError
586
+ if (takesContent === true && memory !== undefined && !isError) {
527
587
  markMemoryGetContent(sessionId, memory, event)
588
+ } else if (memorySaveCalls.delete(callId) && memory !== undefined && !isError) {
589
+ const turn = typeof data.turn === 'number' ? data.turn : undefined
590
+ const step = typeof data.step === 'number' ? data.step : undefined
591
+ markMemorySaveContent(sessionId, memory, event, {
592
+ callId,
593
+ ...(turn !== undefined ? { turn } : {}),
594
+ ...(step !== undefined ? { step } : {}),
595
+ })
528
596
  }
529
597
  }
530
598
  }
@@ -35,6 +35,11 @@ export const defaultInjectConfig = {
35
35
 
36
36
 
37
37
 
38
+
39
+                              
40
+              
41
+
42
+
38
43
                             
39
44
 
40
45
                            
@@ -88,6 +93,15 @@ export function resolveInjectScopes(
88
93
  extraScopes ,
89
94
  sessions ,
90
95
  ) {
96
+ // 会话设置了显式可见范围时,它就是白名单:extraScopes / 父会话都不能把它撑大。
97
+ // 空数组也要原样返回(表示什么都不允许读),不能当成"没设置"。
98
+ let explicit
99
+ try {
100
+ const visible = memory.visibleScopes?.(agent)
101
+ if (Array.isArray(visible)) explicit = [...visible]
102
+ } catch { /* 拿不到覆盖就按默认集合 */ }
103
+ if (explicit !== undefined) return explicit
104
+
91
105
  const scopes = []
92
106
  try {
93
107
  for (const scope of memory.resolveReadScopes?.(agent) ?? []) {
@@ -22,10 +22,12 @@ import { estimateTokens } from '../provider/rerank.js'
22
22
  import { supersededIds } from './digest.js'
23
23
 
24
24
  export const RULES_HEADER =
25
- '以下是必须遵守的硬性规则(来自 kind=rule 的记忆;除非用户明确要求破例,否则按它做):'
25
+ '以下是必须遵守的硬性规则(来自 kind=rule 的记忆,只注入摘要;每条开头的短 ID 可用于取全文,' +
26
+ '需要原文或细节时用 memory_get 按 ID 获取。除非用户明确要求破例,否则按它做):'
26
27
 
27
28
  export const RULES_DELTA_HEADER =
28
- '以下是新增或变更的硬性规则(来自 kind=rule 的记忆;从现在起按它做):'
29
+ '以下是新增或变更的硬性规则(来自 kind=rule 的记忆,只注入摘要;' +
30
+ '需要原文或细节时用 memory_get 按 ID 获取;从现在起按它做):'
29
31
 
30
32
  /** mandatory/pinned 是显式的标签约定,不把全部 kind=rule 自动升级。 */
31
33
  const MANDATORY_TAGS = new Set(['mandatory', 'pinned', '必含', '强制'])
@@ -40,9 +42,12 @@ export function isMandatoryRule(record ) {
40
42
  /**
41
43
  * 一条规则的渲染行。常驻段与增量块共用同一个格式 —— 增量靠"逐行比对"判断
42
44
  * 会话是否已经见过某条规则,两边只要有一个字符不同就会重复提醒。
45
+ *
46
+ * 0.18.0 起行首带 8 位短 ID(与摘要/召回索引同一口径):注入的是摘要,正文可能被
47
+ * 截断,模型需要完整规则时用 memory_get(前缀) 取。
43
48
  */
44
49
  export function ruleLine(record ) {
45
- return `- ${record.content.replace(/\s+/g, ' ').slice(0, 240)}`
50
+ return `- \`${record.id.slice(0, 8)}\` ${record.content.replace(/\s+/g, ' ').slice(0, 240)}`
46
51
  }
47
52
 
48
53
  /** 规则排序:mandatory 优先,其次重要度、新的在前,最后按内容稳定排序。 */
@@ -420,6 +420,36 @@ export function memoryGetResultIds(event ) {
420
420
  return ids.slice(0, 50)
421
421
  }
422
422
 
423
+ /** 记录 id 的形态:`newId()` 生成 randomUUID,这里只认完整 UUID。 */
424
+ const RECORD_ID_PATTERN = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi
425
+
426
+ /**
427
+ * 从 `memory_save` 的 tool/result 里取这次写入 / 去重命中的记录 id。
428
+ *
429
+ * 工具结果的渲染只有两种形态:「已保存记忆 <id> @ <scope>」与
430
+ * 「已更新既有记忆(内容相同,去重):<id> @ <scope>」,id 是 randomUUID。
431
+ * 这里**不按文案匹配**(本地化/措辞改动不该让去重失效),只按 UUID 形态取候选;
432
+ * 调用方还会用 `getByIds` 校验一次存在性,所以 scope 名字里的偶然片段不会误伤。
433
+ */
434
+ export function memorySaveResultIds(event ) {
435
+ const data = (event )?.data
436
+ const message = data?.message
437
+ const text = Array.isArray(message?.content)
438
+ ? message.content.filter((block) => block?.type === 'text' && typeof block.text === 'string').map((block) => block.text ).join('\n')
439
+ : ''
440
+ if (text === '') return []
441
+ const seen = new Set ()
442
+ const ids = []
443
+ for (const match of text.matchAll(RECORD_ID_PATTERN)) {
444
+ const id = match[0]
445
+ if (seen.has(id)) continue
446
+ seen.add(id)
447
+ ids.push(id)
448
+ if (ids.length >= 10) break
449
+ }
450
+ return ids
451
+ }
452
+
423
453
  /**
424
454
  * 每个会话只保留**最新一条未消费**的信号;相同 key 不重复排队。
425
455
  * `take()` 消费后保留 lastKey,同一失败不会因为重复事件反复搜索。
package/lib/panel.js CHANGED
@@ -26,7 +26,7 @@
26
26
  // scope 规范化与 provider 共用同一份实现。路径按**源码树位置**写:构建脚本的改写表
27
27
  // 会把它落成产物里的 `../provider/scope.js`(`lib/panel.js` → `lib/provider/scope.js`),
28
28
  // 在源码树里同一路径直接命中 source/memory-local/src —— 测试与真实加载都能解析。
29
- import { normalizeScopeInput } from './provider/scope.js'
29
+ import { normalizeScopeInput, resolveCurrentScopes } from './provider/scope.js'
30
30
 
31
31
 
32
32
  function writeJson(res, body, status = 200) {
@@ -40,7 +40,7 @@ function writeJson(res, body, status = 200) {
40
40
  const CLIENT_ERROR_CODES = new Set([
41
41
  'SCOPE_INVALID', 'SCOPE_DISABLED', 'CONTENT_EMPTY', 'CONTENT_TOO_LONG',
42
42
  'SECRET_DETECTED', 'IMPORT_INVALID', 'IMPORT_TOO_LARGE', 'KIND_INVALID',
43
- 'QUERY_EMPTY', 'QUERY_INVALID',
43
+ 'QUERY_EMPTY', 'QUERY_INVALID', 'SESSION_REQUIRED', 'SCOPE_EMPTY', 'SCOPE_NOT_VISIBLE',
44
44
  ])
45
45
 
46
46
  function writeError(res, error) {
@@ -470,6 +470,62 @@ function resolveScopeSelection(memory, rawScope) {
470
470
  return normalized.scope ?? null
471
471
  }
472
472
 
473
+ /**
474
+ * 会话「记忆可见范围」的完整快照:自己的覆盖 + 实际生效集合 + 可选范围目录。
475
+ *
476
+ * 自己的覆盖(null = 没设置)用于面板上的"恢复默认";effective 用于预选(子 Agent
477
+ * 会话会继承父会话的覆盖);scopes 是本次会话可以勾选的全部具体作用域键。
478
+ */
479
+ function visibilityPayload(ctx, memory, sessionId) {
480
+ let session
481
+ try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
482
+ const agentLike = { session: session !== undefined ? session : { id: sessionId } }
483
+ const own = typeof memory.sessionVisibility === 'function' ? memory.sessionVisibility(sessionId) : null
484
+ let effective = null
485
+ let inherited = false
486
+ try {
487
+ if (typeof memory.visibleScopes === 'function') {
488
+ const resolved = memory.visibleScopes(agentLike)
489
+ if (Array.isArray(resolved)) {
490
+ effective = resolved
491
+ inherited = own === null
492
+ }
493
+ }
494
+ if (effective === null) {
495
+ const resolved = memory.resolveReadScopes?.(session !== undefined ? { session } : undefined)
496
+ if (Array.isArray(resolved)) effective = resolved
497
+ }
498
+ } catch { /* 可见范围是增强;拿不到就只返回自己的覆盖 */ }
499
+
500
+ let refs
501
+ try { if (session !== undefined) refs = resolveCurrentScopes({ session }) } catch { refs = undefined }
502
+ const stats = typeof memory.scopeStats === 'function' ? memory.scopeStats() : []
503
+ const byScope = new Map()
504
+ for (const item of Array.isArray(stats) ? stats : []) {
505
+ if (item && typeof item.scope === 'string') byScope.set(item.scope, item)
506
+ }
507
+ // 即使还没有任何记录,也要能把"当前会话 / 当前项目 / global"勾进可见范围。
508
+ const ensure = (scope) => {
509
+ if (typeof scope === 'string' && scope !== '' && !byScope.has(scope)) {
510
+ byScope.set(scope, { scope, records: 0, pendingEmbeds: 0 })
511
+ }
512
+ }
513
+ ensure(refs?.session)
514
+ ensure(refs?.project)
515
+ ensure('global')
516
+ const rank = (scope) => scope === refs?.session ? 0 : scope === refs?.project ? 1 : scope === 'global' ? 2 : 3
517
+ const scopes = [...byScope.values()]
518
+ .sort((a, b) => rank(a.scope) - rank(b.scope) || String(a.scope).localeCompare(String(b.scope)))
519
+ .map((item) => ({ ...item, label: item.name ?? scopeLabel(ctx, item.scope) }))
520
+ return {
521
+ sessionId,
522
+ override: own,
523
+ effective: Array.isArray(effective) ? effective : null,
524
+ inherited,
525
+ scopes,
526
+ }
527
+ }
528
+
473
529
  async function handle(ctx, routePath, req, res) {
474
530
  const url = new URL(req.url ?? '/', 'http://dsh.local')
475
531
  const path = url.pathname.slice(routePath.length) || '/'
@@ -539,6 +595,43 @@ async function handle(ctx, routePath, req, res) {
539
595
  // memories from earlier sessions included) — best-effort discovery, cached.
540
596
  discoverScopes(memory, store)
541
597
 
598
+ // 会话级「记忆可见范围」:输入框旁的按钮读写这一对接口。
599
+ if (method === 'GET' && path === '/visibility') {
600
+ if (typeof memory.sessionVisibility !== 'function') {
601
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话可见范围接口(请升级 @restregular/dsh-memory)')
602
+ }
603
+ const sessionId = (url.searchParams.get('session') ?? '').trim()
604
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 参数不能为空')
605
+ writeJson(res, { ok: true, value: visibilityPayload(ctx, memory, sessionId) })
606
+ return
607
+ }
608
+ if (method === 'POST' && path === '/visibility') {
609
+ if (typeof memory.setSessionVisibility !== 'function') {
610
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话可见范围接口(请升级 @restregular/dsh-memory)')
611
+ }
612
+ const body = await readJsonBody(req)
613
+ const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
614
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
615
+ let next = null
616
+ if (body?.scopes !== null && body?.scopes !== undefined) {
617
+ if (!Array.isArray(body.scopes)) throw new ApiError(400, 'SCOPE_INVALID', 'scopes 必须是数组或 null')
618
+ if (body.scopes.length === 0) throw new ApiError(400, 'SCOPE_EMPTY', '至少选择一个可见范围')
619
+ next = []
620
+ for (const raw of body.scopes) {
621
+ if (typeof raw !== 'string') throw new ApiError(400, 'SCOPE_INVALID', 'scope 必须是字符串')
622
+ const normalized = normalizeScopeInput(raw)
623
+ if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
624
+ if (normalized.kind === 'all' || normalized.kind === 'current-project' || normalized.kind === 'current-session') {
625
+ throw new ApiError(400, 'SCOPE_INVALID', `可见范围必须是具体作用域键: ${JSON.stringify(raw)}`)
626
+ }
627
+ if (normalized.scope !== undefined && !next.includes(normalized.scope)) next.push(normalized.scope)
628
+ }
629
+ }
630
+ memory.setSessionVisibility(sessionId, next)
631
+ writeJson(res, { ok: true, value: visibilityPayload(ctx, memory, sessionId) })
632
+ return
633
+ }
634
+
542
635
  if (method === 'GET' && path === '/status') {
543
636
  const stats = typeof memory.scopeStats === 'function'
544
637
  ? memory.scopeStats()
@@ -27,6 +27,15 @@ export class CordisMemoryService extends Service {
27
27
  constructor(ctx , config = {}) {
28
28
  super(ctx, 'memory')
29
29
  this.impl = new LocalMemoryService(config)
30
+ // 会话可见范围的继承要沿 parentSession 链走;这里只放一个惰性查询,
31
+ // sessions 服务晚于本插件就绪也能在真正解析时拿到。
32
+ this.impl.setSessionLookup((id) => {
33
+ try {
34
+ return (ctx.get('sessions') )?.get?.(id)
35
+ } catch {
36
+ return undefined
37
+ }
38
+ })
30
39
  // 0.11.1:同一个目录因为 `D:/x` 与 `D:\x` 写法不同而分叉成两个 scope 的历史数据,
31
40
  // 在装配期合并一次(每进程一次;失败只影响合并,不影响读写)。
32
41
  try {
@@ -229,6 +238,21 @@ export class CordisMemoryService extends Service {
229
238
  return this.impl.resolveReadScopes(agent)
230
239
  }
231
240
 
241
+ /** 显式「可见范围」覆盖(undefined = 未设置);工具用它判断是否限制 memory_get。 */
242
+ visibleScopes(agent ) {
243
+ return this.impl.visibleScopes(agent)
244
+ }
245
+
246
+ /** 面板:读取某会话自己的可见范围(null = 未设置)。 */
247
+ sessionVisibility(sessionId ) {
248
+ return this.impl.sessionVisibility(sessionId)
249
+ }
250
+
251
+ /** 面板:设置/清除某会话的可见范围(null = 恢复默认)。 */
252
+ setSessionVisibility(sessionId , scopes ) {
253
+ return this.impl.setSessionVisibility(sessionId, scopes)
254
+ }
255
+
232
256
  /** 写路径默认 scope(省略 scope 时落到哪)。 */
233
257
  resolveWriteScope(agent , requested ) {
234
258
  return this.impl.resolveWriteScope(agent, requested)
@@ -27,6 +27,7 @@ import {
27
27
 
28
28
  } from './scope.js'
29
29
  import { ScopeNames } from './scope-names.js'
30
+ import { SessionVisibilityStore } from './session-visibility.js'
30
31
  import { mergeInjectSettings, normalizeInjectSettings, } from './inject-settings.js'
31
32
  import { buildStats, lexicalScore, recordScore, tokenize, cosine, normalizeInPlace, hasStrongHit } from './scoring.js'
32
33
  import { EmbedClient } from './embed.js'
@@ -515,6 +516,13 @@ export class LocalMemoryService {
515
516
  names
516
517
  /** 注入设置(面板「设置」标签页可改;落盘在 <storeDir>/settings.json)。 */
517
518
  inject
519
+ /** 会话级「记忆可见范围」覆盖;没有覆盖时沿用默认三路集合。 */
520
+ visibility
521
+ /**
522
+ * 会话 id → live session 的只读查询(用于沿 parentSession 链继承可见范围)。
523
+ * 宿主侧 apply.ts 注入;旧宿主 / 测试里没有时退化为只看当前会话。
524
+ */
525
+ sessionLookup
518
526
  /** 注入半边的审计收集器(可选;没有注入半边时保持 null)。 */
519
527
  injectAuditSink
520
528
 
@@ -528,6 +536,7 @@ export class LocalMemoryService {
528
536
  this.cfg = resolveConfig(config)
529
537
  this.inject = this.loadInjectSettings((config ).inject)
530
538
  this.names = new ScopeNames(join(this.cfg.storeDir, 'scopes.json'))
539
+ this.visibility = new SessionVisibilityStore({ root: this.cfg.storeDir })
531
540
  this.rerankBudget = new DailyBudget(this.cfg.llm.dailyBudgetTokens)
532
541
  this.store = new MemoryStore(this.cfg.storeDir, { onWarn: (m) => console.warn(`[dsh-memory-local] ${m}`) })
533
542
  // Identity BEFORE the eager load (issue #1): ScopeStore skips its sidecar
@@ -1298,11 +1307,112 @@ export class LocalMemoryService {
1298
1307
  return this.scopeRefs(agent).project
1299
1308
  }
1300
1309
 
1310
+ /** 宿主注入 live session 查询(用于沿 parentSession 链继承可见范围)。 */
1311
+ setSessionLookup(lookup ) {
1312
+ this.sessionLookup = lookup
1313
+ }
1314
+
1315
+ /** 只保留当前配置允许的 scope(覆盖集合里若含被禁用的 scope,静默剔除)。 */
1316
+ filterEnabledScopes(scopes ) {
1317
+ const out = []
1318
+ for (const raw of scopes) {
1319
+ const scope = this.canonicalScope(raw)
1320
+ if (out.includes(scope)) continue
1321
+ switch (scopeKind(scope)) {
1322
+ case 'global': if (!this.cfg.globalEnabled) continue; break
1323
+ case 'project': if (!this.cfg.projectEnabled) continue; break
1324
+ case 'session': if (!this.cfg.sessionEnabled) continue; break
1325
+ default: if (!this.cfg.customEnabled) continue; break
1326
+ }
1327
+ out.push(scope)
1328
+ }
1329
+ return out
1330
+ }
1331
+
1332
+ /**
1333
+ * 从会话 id 沿 parentSession 链找最近的显式可见范围。
1334
+ *
1335
+ * 起点用**当前会话自己的 id**(不是 resolveCurrentScopes 映射后的父会话):
1336
+ * 子 Agent 自己也可以有一份覆盖;没有时才沿链继承父会话 / 根会话。
1337
+ */
1338
+ visibilityForSession(sessionId ) {
1339
+ let id = sessionId ?? ''
1340
+ const seen = new Set ()
1341
+ while (id !== '' && !seen.has(id)) {
1342
+ seen.add(id)
1343
+ const found = this.visibility.get(id)
1344
+ if (found !== undefined) return found
1345
+ let parent
1346
+ try {
1347
+ const session = this.sessionLookup?.(id)
1348
+ parent = typeof session?.header?.parentSession === 'string' && session.header.parentSession !== ''
1349
+ ? session.header.parentSession
1350
+ : undefined
1351
+ } catch { parent = undefined }
1352
+ id = parent ?? ''
1353
+ }
1354
+ return undefined
1355
+ }
1356
+
1357
+ /** agent 上真实的会话 id(不映射到父会话);用于可见范围自己的文件。 */
1358
+ rawSessionIdOf(agent ) {
1359
+ try {
1360
+ const session = (agent )?.session
1361
+ const id = session?.header?.id ?? session?.id
1362
+ return typeof id === 'string' && id !== '' ? id : undefined
1363
+ } catch {
1364
+ return undefined
1365
+ }
1366
+ }
1367
+
1368
+ /**
1369
+ * 显式「记忆可见范围」:解析当前 agent(含子 Agent 的 parentSession 链)的覆盖。
1370
+ * undefined = 没有覆盖(调用方沿用默认三路集合 / 不限制 memory_get);
1371
+ * [] = 显式设置了范围但全部被 scope 开关禁用,调用方必须按空处理。
1372
+ */
1373
+ visibleScopes(agent ) {
1374
+ const explicit = this.visibilityForSession(this.rawSessionIdOf(agent))
1375
+ return explicit === undefined ? undefined : this.filterEnabledScopes(explicit)
1376
+ }
1377
+
1378
+ /** 面板:读取某会话自己的覆盖(null = 没有覆盖,继续用默认集合)。 */
1379
+ sessionVisibility(sessionId ) {
1380
+ if (typeof sessionId !== 'string' || sessionId.trim() === '') return null
1381
+ const scopes = this.visibility.get(sessionId.trim())
1382
+ return scopes === undefined ? null : [...scopes]
1383
+ }
1384
+
1385
+ /** 面板:写入/清除某会话的覆盖。null = 恢复默认。 */
1386
+ setSessionVisibility(sessionId , scopes ) {
1387
+ if (typeof sessionId !== 'string' || sessionId.trim() === '') return null
1388
+ const cleaned = scopes === null ? null : this.normalizeVisibilityScopes(scopes)
1389
+ if (cleaned !== null && cleaned.length === 0) {
1390
+ throw memoryError('SCOPE_EMPTY', '至少选择一个可见的记忆范围')
1391
+ }
1392
+ return this.visibility.set(sessionId.trim(), cleaned)
1393
+ }
1394
+
1395
+ /** 校验并规范化面板提交的 scope 键(必须是具体键;不接受 all/current-*)。 */
1396
+ normalizeVisibilityScopes(scopes ) {
1397
+ const out = []
1398
+ for (const raw of scopes) {
1399
+ const normalized = normalizeScopeInput(raw)
1400
+ if (!normalized.ok) throw memoryError(normalized.code, normalized.message)
1401
+ if (normalized.kind === 'all' || normalized.kind === 'current-session' || normalized.kind === 'current-project') {
1402
+ throw memoryError('SCOPE_INVALID', `可见范围必须是具体作用域键: ${JSON.stringify(raw)}`)
1403
+ }
1404
+ if (normalized.scope !== undefined && !out.includes(normalized.scope)) out.push(normalized.scope)
1405
+ }
1406
+ return out
1407
+ }
1408
+
1301
1409
  /**
1302
1410
  * 无显式 scope 时的**读取**合并集合:当前会话 + 当前项目 + global(各自开关生效、按 key 去重)。
1303
- * 工具 / 注入都用它,保证"写进会话的东西,默认读得回来"。
1411
+ * 工具 / 注入都用它。会话设置了「可见范围」时以覆盖为准(不再并入默认集合)。
1304
1412
  */
1305
1413
  resolveReadScopes(agent ) {
1414
+ const explicit = this.visibleScopes(agent)
1415
+ if (explicit !== undefined) return explicit
1306
1416
  const refs = this.scopeRefs(agent)
1307
1417
  const out = []
1308
1418
  const push = (scope , enabled ) => {
@@ -1485,6 +1595,9 @@ export class LocalMemoryService {
1485
1595
  // 多 scope 合并由调用方显式给出(工具层传"会话 + 项目 + global");宿主类型里的
1486
1596
  // MemoryQuery 只有单值 scope,所以这里按结构化读一次可选数组,保持原语义不变。
1487
1597
  const queryScopes = (query ).scopes
1598
+ // 显式空集合 = 什么都不允许读(会话可见范围把所有勾选项都禁用了)。不能退回
1599
+ // 默认项目 + global,否则"看不见任何范围"反而会搜出默认范围的记录。
1600
+ if (query.scope === undefined && queryScopes !== undefined && queryScopes.length === 0) return []
1488
1601
  const topK = query.topK ?? this.cfg.topK
1489
1602
  const recallN = query.recallN ?? this.cfg.recallN
1490
1603
  const now = Date.now()
@@ -1748,6 +1861,8 @@ export class LocalMemoryService {
1748
1861
  */
1749
1862
  async list(input = {}) {
1750
1863
  const internal = input
1864
+ // 显式空集合 = 无可见范围(见 search 的同口径说明)。
1865
+ if (input.scope === undefined && input.scopes !== undefined && input.scopes.length === 0) return []
1751
1866
  const wanted = (input.scope !== undefined
1752
1867
  ? [input.scope]
1753
1868
  : (input.scopes ?? []).length > 0
@@ -0,0 +1,132 @@
1
+ /**
2
+ * 会话级「记忆可见范围」的持久化。
3
+ *
4
+ * 位置:`<storeDir>/visibility/<session>.json`(与记忆数据同目录,便于一起备份/清理)。
5
+ *
6
+ * 为什么放在 provider 而不是注入半边:
7
+ * resolveReadScopes / memory_search / memory_get 都以 provider 为**唯一口径**;
8
+ * 如果把覆盖范围放在注入半边,工具与注入就会各读一份,模型能看到的范围页面
9
+ * 和工具实际能读到的范围可能不一致。provider 落盘、注入与工具都通过它解析。
10
+ *
11
+ * 为什么一个会话一个文件,而不是一个 JSON map:
12
+ * 同一个 storeDir 可能被多个进程共用(见 store.ts 的 issue #3)。单文件 map 在并发
13
+ * 写入时会互相覆盖;按会话分文件后,一个会话的写入不影响另一个会话。
14
+ *
15
+ * 语义:
16
+ * - 文件存在且 scopes 非空 = 该会话显式指定了可见范围;
17
+ * - 文件不存在 = 没有覆盖,继续用默认的三路集合(会话 + 项目 + global);
18
+ * - scopes 为空数组视为"无覆盖"(面板在保存时也会拒绝空选择),不会把会话锁死。
19
+ *
20
+ * 容错:读写失败都只退化为"没有覆盖",绝不把异常抛回检索/注入链路。
21
+ */
22
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
23
+ import { join } from 'node:path'
24
+ import { createHash } from 'node:crypto'
25
+
26
+ const VERSION = 1
27
+
28
+
29
+                
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+ /** 会话 id 通常已经是 UUID;异常字符换成 `_`,改写过的再加 8 位 hash 防碰撞。 */
41
+ function safeName(sessionId ) {
42
+ const cleaned = sessionId.replace(/[^A-Za-z0-9._-]+/g, '_').slice(0, 80)
43
+ if (cleaned === sessionId && cleaned !== '') return cleaned
44
+ const base = cleaned === '' ? 'session' : cleaned.slice(0, 64)
45
+ return `${base}-${createHash('sha1').update(sessionId).digest('hex').slice(0, 8)}`
46
+ }
47
+
48
+ /** 只保留非空字符串并去重(顺序即用户勾选顺序);空数组返回 undefined。 */
49
+ function cleanScopes(raw ) {
50
+ if (!Array.isArray(raw)) return undefined
51
+ const out = []
52
+ for (const item of raw) {
53
+ if (typeof item !== 'string') continue
54
+ const value = item.trim()
55
+ if (value === '' || out.includes(value)) continue
56
+ out.push(value)
57
+ }
58
+ return out.length > 0 ? out : undefined
59
+ }
60
+
61
+ export class SessionVisibilityStore {
62
+ dir
63
+ warn
64
+ /** sessionId -> 显式范围;null = 已确认没有文件(避免反复 stat)。 */
65
+ cache = new Map ()
66
+
67
+ constructor(options ) {
68
+ this.dir = join(options.root, 'visibility')
69
+ this.warn = options.warn ?? ((message) => console.warn(message))
70
+ }
71
+
72
+ fileOf(sessionId ) {
73
+ return join(this.dir, `${safeName(sessionId)}.json`)
74
+ }
75
+
76
+ /** 显式可见范围;undefined = 没有覆盖(用默认集合)。 */
77
+ get(sessionId ) {
78
+ if (sessionId === '') return undefined
79
+ const cached = this.cache.get(sessionId)
80
+ if (cached !== undefined) return cached ?? undefined
81
+ let scopes
82
+ try {
83
+ const file = this.fileOf(sessionId)
84
+ if (existsSync(file)) {
85
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
86
+ scopes = cleanScopes(parsed?.scopes)
87
+ if (parsed?.version !== undefined && parsed.version !== VERSION) {
88
+ // 未知版本:读得出来就继续用,读不出来就按"无覆盖"处理。
89
+ scopes = scopes ?? undefined
90
+ }
91
+ }
92
+ } catch (error) {
93
+ // 损坏文件不应该让会话失去默认可见范围;只告警一次(缓存 null)。
94
+ this.warn(`[dsh-memory-local] 忽略损坏的会话可见范围 ${this.fileOf(sessionId)}: ${error instanceof Error ? error.message : String(error)}`)
95
+ scopes = undefined
96
+ }
97
+ this.cache.set(sessionId, scopes ?? null)
98
+ return scopes
99
+ }
100
+
101
+ /** 写入/清除显式范围。null 或空数组 = 清除(恢复默认)。返回写入后的值。 */
102
+ set(sessionId , scopes ) {
103
+ if (sessionId === '') return null
104
+ const cleaned = scopes === null ? undefined : cleanScopes(scopes)
105
+ try {
106
+ const file = this.fileOf(sessionId)
107
+ if (cleaned === undefined) {
108
+ rmSync(file, { force: true })
109
+ this.cache.set(sessionId, null)
110
+ return null
111
+ }
112
+ mkdirSync(this.dir, { recursive: true })
113
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
114
+ writeFileSync(tmp, `${JSON.stringify({ version: VERSION, scopes: cleaned, updatedAt: Date.now() }, null, 2)}\n`, 'utf8')
115
+ renameSync(tmp, file)
116
+ this.cache.set(sessionId, cleaned)
117
+ return [...cleaned]
118
+ } catch (error) {
119
+ // 写盘失败:内存里的旧值不清空,但也不能假装成功。调用方会看到旧值。
120
+ this.warn(`[dsh-memory-local] 无法写入会话可见范围 ${this.fileOf(sessionId)}: ${error instanceof Error ? error.message : String(error)}`)
121
+ return this.cache.get(sessionId) ?? null
122
+ }
123
+ }
124
+
125
+ /** 把缓存里这个会话的值清掉(下一次 get 重新读盘);维护/测试用。 */
126
+ invalidate(sessionId ) {
127
+ this.cache.delete(sessionId)
128
+ }
129
+ }
130
+
131
+
132
+ //# sourceURL=source/memory-local/src/session-visibility.ts
@@ -49,6 +49,11 @@ import { canonicalWorkspacePath, normalizeScopeInput, resolveScopeRef } from '..
49
49
 
50
50
                      
51
51
 
52
+
53
+                               
54
+          
55
+
56
+
52
57
                            
53
58
 
54
59
                 
@@ -113,8 +118,34 @@ function projectKey(opts , service , agent
113
118
  return (opts.projectScope ?? `project:${process.cwd()}`)
114
119
  }
115
120
 
121
+ /**
122
+ * 显式「可见范围」白名单;undefined = 没有覆盖(保持旧行为,不限制显式 scope)。
123
+ * provider 方法抛错时按"没有覆盖"处理:可见范围是防越界,不应该让一个 provider
124
+ * 内部错误把所有读取都锁死。
125
+ */
126
+ function visibleScopeList(service , agent ) {
127
+ try {
128
+ const explicit = service.visibleScopes?.(agent)
129
+ if (Array.isArray(explicit)) return [...new Set(explicit)]
130
+ } catch { /* 降级为不限制 */ }
131
+ return undefined
132
+ }
133
+
134
+ /** 显式询问一个不在可见范围内的 scope 时给出明确错误,而不是返回空结果。 */
135
+ function assertScopeVisible(service , agent , scope ) {
136
+ const visible = visibleScopeList(service, agent)
137
+ if (visible === undefined || visible.includes(scope)) return
138
+ throw new MemoryToolError(
139
+ 'SCOPE_NOT_VISIBLE',
140
+ `当前会话的「记忆可见范围」不包含 ${scope};只能读取: ${visible.length > 0 ? visible.join(', ') : '(无)'}`,
141
+ )
142
+ }
143
+
116
144
  /** 该服务/配置下"当前会话 + 当前项目 + global"的合并读取集合(去重)。 */
117
145
  function readScopes(opts , service , agent ) {
146
+ // 显式可见范围优先,空数组也要原样返回(表示什么都不允许读)。
147
+ const explicit = visibleScopeList(service, agent)
148
+ if (explicit !== undefined) return explicit
118
149
  const provided = service.resolveReadScopes?.(agent)
119
150
  if (Array.isArray(provided) && provided.length > 0) return [...new Set(provided)]
120
151
  // 服务没提供(测试 mock / 旧 provider):退回 defaultScope 口径
@@ -328,14 +359,23 @@ export function memorySearchTool(opts )
328
359
  throw new MemoryToolError('QUERY_EMPTY', 'query must be a non-empty string')
329
360
  }
330
361
  const resolved = resolveScope(opts, service, exec, args.scope, 'read')
362
+ const agent = agentOf(exec)
331
363
  let scopes
332
364
  if (resolved.all) {
333
- // 'all' = 所有已发现作用域;scopeStats() 自身会先做 discovery(带限流)。
334
- scopes = (service.scopeStats?.() ?? []).map((s) => s.scope)
335
- service.discoverScopes?.()
365
+ const visible = visibleScopeList(service, agent)
366
+ if (visible !== undefined) {
367
+ // 'all' 在有可见范围限制时只等于"所有可见范围",不是磁盘上的全部 scope。
368
+ scopes = visible
369
+ } else {
370
+ // 'all' = 所有已发现作用域;scopeStats() 自身会先做 discovery(带限流)。
371
+ scopes = (service.scopeStats?.() ?? []).map((s) => s.scope)
372
+ service.discoverScopes?.()
373
+ }
336
374
  } else if (resolved.scope === undefined) {
337
- // 省略 scope:三路合并(会话 + 项目 + global)
338
- scopes = readScopes(opts, service, agentOf(exec))
375
+ // 省略 scope:三路合并(会话 + 项目 + global),或显式可见范围。
376
+ scopes = readScopes(opts, service, agent)
377
+ } else {
378
+ assertScopeVisible(service, agent, resolved.scope)
339
379
  }
340
380
  const chars = resolveSummaryChars(args.summaryChars)
341
381
  try {
@@ -434,13 +474,20 @@ export function memoryListTool(opts )
434
474
  async execute(args , exec ) {
435
475
  const service = svc(opts)
436
476
  const resolved = resolveScope(opts, service, exec, args.scope, 'read')
477
+ const agent = agentOf(exec)
437
478
  let scopes
438
479
  if (resolved.all) {
439
- scopes = (service.scopeStats?.() ?? []).map((s) => s.scope)
440
- service.discoverScopes?.()
480
+ const visible = visibleScopeList(service, agent)
481
+ if (visible !== undefined) scopes = visible
482
+ else {
483
+ scopes = (service.scopeStats?.() ?? []).map((s) => s.scope)
484
+ service.discoverScopes?.()
485
+ }
441
486
  } else if (resolved.scope === undefined) {
442
487
  // 省略 scope:默认**只列当前会话**(按需求;读全部请显式 'all')
443
- scopes = readScopes(opts, service, agentOf(exec)).slice(0, 1)
488
+ scopes = readScopes(opts, service, agent).slice(0, 1)
489
+ } else {
490
+ assertScopeVisible(service, agent, resolved.scope)
444
491
  }
445
492
  let records
446
493
  try {
@@ -460,7 +507,11 @@ export function memoryListTool(opts )
460
507
  } catch (error) {
461
508
  throw toolError(error)
462
509
  }
463
- const stats = service.scopeStats?.()
510
+ const statsAll = service.scopeStats?.()
511
+ const visible = visibleScopeList(service, agent)
512
+ const stats = statsAll !== undefined && visible !== undefined
513
+ ? statsAll.filter((s) => visible.includes(s.scope))
514
+ : statsAll
464
515
  return stats !== undefined ? { records, scopeStats: stats } : { records }
465
516
  },
466
517
  }
@@ -570,7 +621,7 @@ export function memoryGetTool(opts )
570
621
  },
571
622
  summaryChars: { type: 'number', description: `summary 字段的字数上限(默认 ${DEFAULT_SUMMARY_CHARS},20~2000)` },
572
623
  },
573
- async execute(args ) {
624
+ async execute(args , exec ) {
574
625
  const service = svc(opts)
575
626
  const ids = Array.isArray(args.ids)
576
627
  ? [...new Set(args.ids.map(String).filter((id) => id.trim() !== ''))].slice(0, 50)
@@ -582,7 +633,11 @@ export function memoryGetTool(opts )
582
633
  const fields = resolveGetFields(args.fields)
583
634
  const chars = resolveSummaryChars(args.summaryChars)
584
635
  try {
585
- const found = service.getByIds(ids)
636
+ const all = service.getByIds(ids)
637
+ // 显式可见范围是白名单:即使知道 id,也不能读别的范围的正文。未设置时保持
638
+ // 旧行为(记忆 id 本身是随机不可猜的,跨 scope 取全文是既有能力)。
639
+ const visible = visibleScopeList(service, agentOf(exec))
640
+ const found = visible === undefined ? all : all.filter((r) => visible.includes(r.scope))
586
641
  return {
587
642
  records: found.map((r) => pickGetFields(r, fields, chars)),
588
643
  fields,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "description": "DeepSeek Harness 记忆系统(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 五个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",