@restregular/dsh-memory 0.13.1 → 0.14.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,28 @@
2
2
 
3
3
  本项目的版本记录。安装 id 与 npm 版本一一对应。
4
4
 
5
+ ## 0.14.0 — 记忆审计与会话轨迹互相精准跳转
6
+
7
+ - **审计可定位到轨迹**:审计详情新增「在轨迹中定位」。条目上的 `operationId`(记忆工具调用、触发召回的工具调用)直接作为 Trajectory 的 callId 深链;没有 `operationId` 的按轮/步事件请求新增的 `GET /memory/api/anchor`,由 Host 在会话事件窗口里找该 turn/step 的第一个 `tool/call`。找不到时只切到轨迹页,不伪造锚点。
8
+ - **轨迹行可回到审计**:新增 `shell.overlay` 徽标,只读观察 Trajectory 选中行的 `data-trajectory-row-key`,按 callId 查出相关审计并在行右侧显示「记忆 N」;点击打开记忆面板「审计」页并按 `op:<callId>` 过滤。会话标题行同时提供固定入口「记忆审计」。
9
+ - **会话内新增「记忆」视图**:与 Chat / 轨迹同一个 view ring,按当前会话展示审计;使用宿主传给每个 view 的 `openView` 完成跳转,属于官方扩展路径。主面板不在 view ring 内,通过 `conversation.session` 的 per-session store 调同一个 action(拿不到时退化为只打开会话/轨迹页)。
10
+ - **记忆工具调用入审计**:`memory_save/search/list/get/forget` 的每次调用都会记一条 `stage: tool_call` 的锚点(`operationId` = callId,带 turn/step),即使自动召回关闭也保留;信号事件同步写入 `operationId`、`turn`、`step` 与 `signal.callId`,便于把审计和轨迹对上。
11
+ - 新增 Host 纯函数 `findTrajectoryAnchor` 与回归测试;客户端新增锚点解析、焦点总线、主面板 store 桥、审计详情跳转的渲染测试。
12
+
13
+ ## 0.13.2 — 修复检索分数全部相同
14
+
15
+ - **根因**:`search()` 组装最终分数时写成了 `c.id`,而候选对象只有 `c.record`,于是所有候选都落到
16
+ `finalScores` 的同一个 `undefined` 键上 —— 每条命中拿到的都是**最后一个候选**的分数。召回顺序
17
+ 一直是对的(排序用的是 `shape`),所以只有分数是错的:工具返回的 `score`、记录页语义检索的
18
+ 「得分」全都一样。
19
+ - 同一处 `c.id` 还让传给 LLM 重排的候选 id 全变成 `undefined`,重排永远匹配不上;另外重排成功后
20
+ 只改了分数、没有重排数组,即使匹配上也不会改变结果顺序。现在两处都修好:候选用
21
+ `c.record.id`,重排成功后按混合分数重新排序(无重排时该排序与原顺序完全一致)。
22
+ - 记录页结果卡的「相关度」改名为「得分」:这是排序分(向量/词法命中 × 重要度 × 时效 × 访问次数),
23
+ 不是 0~1 的概率,访问次数多时可能大于 1;结果顺序与它一致。
24
+ - 回归测试(`search-scores.test.ts`):只有重要度不同的两条记录必须拿到不同分数(≈0.95 / ≈0.60);
25
+ 重排 prompt 必须包含真实 record id,且重排能把结果顺序翻转(混合分 ≈0.84)。
26
+
5
27
  ## 0.13.1 — 语义检索改成 toggle 开关
6
28
 
7
29
  - 记录页的「语义检索」从普通文字按钮改成真正的 **toggle 开关**:轨道 + 圆点 + 可见的
package/README.md CHANGED
@@ -56,6 +56,8 @@ JSONL 落盘 · 本机向量检索 · 五个模型工具 · 自动召回 · 硬
56
56
 
57
57
  - 开关只在向量后端已配置时可用;没装后端时保持禁用并说明原因。
58
58
  - 语义检索是**只读浏览**:不增加访问计数,不会把 `memory_search` 后续的排序带偏。
59
+ - 结果卡上的「得分」是**排序分**(向量/词法命中 × 重要度 × 时效 × 访问次数),不是概率,
60
+ 访问次数多时可能大于 1;结果顺序与这个分数一致。
59
61
  - 结果说明会如实写出这次是「语义排序」还是「关键词回退」:例如记录还没嵌入向量、或向量服务
60
62
  没有响应时,不会把词法结果冒充成语义结果。嵌入完成后列表会自动刷新成语义结果。
61
63
  - 作用域下拉与新建 / 编辑 / 删除仍然照常工作;从审计页点记忆 ID 跳过来时会自动回到普通列表并展开该条。
@@ -363,10 +365,23 @@ GET /memory/api/audit
363
365
 
364
366
  GET /memory/api/audit/stats
365
367
  GET /memory/api/audit/export?format=json|jsonl&<same filters>
368
+
369
+ GET /memory/api/anchor?session=<id>&turn=<n>&step=<n>&callId=<optional>
366
370
  ```
367
371
 
368
372
  响应为 `{ ok: true, value: { entries, total, nextCursor?, stats, query } }`。旧调用 `GET /audit?session=<id>` 仍兼容;不带 `session` 时查询全部会话,`query.scope` 会标记为 `all`。
369
373
 
374
+ ### 和会话轨迹互相跳转
375
+
376
+ DSH 自带的 Trajectory 面板是一个**纯投影**:它只声明 `conversation.trajectory.images` 一个子槽,没有行/列扩展点,选中状态也只存在组件内部。因此插件不能直接往轨迹表格里插审计行。当前采用的是一条不碰轨迹 React 树的组合:
377
+
378
+ - **轨迹 → 记忆审计**:Trajectory 的选中行带有稳定的 `data-trajectory-row-key`(工具行是 `kind\0call\0<callId>`)。一个 `shell.overlay` 徽标只读观察选中行,按 callId 查审计,在行右侧浮出「记忆 N」。点击后打开记忆面板的「审计」页,并按 `op:<callId>` 过滤。会话标题行还固定提供一个「记忆审计」入口。
379
+ - **记忆审计 → 轨迹**:审计详情里的「在轨迹中定位」把条目上的 `operationId`(记忆工具调用、触发召回的工具调用)交给 Trajectory 的 `openView('trajectory', callId)`。没有 `operationId` 的按轮/步事件先请求 `/anchor`,由 Host 从会话事件窗口里找该 turn/step 的第一个 `tool/call`;找不到就只切到轨迹页,不伪造定位。
380
+ - **会话内的「记忆」视图**:与 Chat / 轨迹同一个 view ring,按当前会话展示审计;它直接使用宿主传给每个 view 的 `openView`,因此跳转是官方支持路径。主面板不在 view ring 内,通过 `conversation.session` 注册的 per-session store 调同一个 action;拿不到时退化为打开会话/轨迹页。
381
+ - 记忆工具调用(`memory_save/search/list/get/forget`)本身会额外留一条 `stage: tool_call` 的审计锚点:即使自动召回关闭,也能从这条记录精确跳回轨迹里的那次调用。
382
+
383
+ `/anchor` 只返回 `{ callId, tool?, turn?, step?, reason }`,不返回工具参数、消息正文或记忆内容;找不到会话/工具时 `callId` 为 `null` 并给出稳定 `reason`。
384
+
370
385
  审计数据默认**只在内存**:容量 2000 条、每会话 200 条,超出时优先保留 digest / rules / delivery / error 等关键通道;`stats` 暴露 `entries / capacity / dropped / writeErrors / persistence`。重启后记录丢失,面板会明确提示。
371
386
 
372
387
  写入前所有自由文本都经过统一 sanitizer:先限制扫描长度(4000 字符),再做凭据模式脱敏,最后截到 200 字;只保存 ID、计数、枚举原因、字符数和短 hash,不保存记忆正文、原始工具参数、异常堆栈。模式脱敏是保守匹配,不承诺覆盖所有秘密形状。
package/lib/client.js CHANGED
@@ -106,7 +106,7 @@ window.__ModuleLoader__.load({
106
106
  '.memp .empty{color:var(--dsw-alias-label-secondary);font-size:12.5px;padding:16px 2px;text-align:center}',
107
107
  // 语义检索:搜索框旁的 toggle(轨道 + 圆点,沿用 .toggle 的宿主 token 配色,
108
108
  // 深浅色都由 --dsw-alias-switch-thumb / brand-primary / label-primary-foreground
109
- // 决定,不再写死颜色)+ 结果说明行 + 结果卡上的相关度
109
+ // 决定,不再写死颜色)+ 结果说明行 + 结果卡上的排序得分
110
110
  '.memp .toolbar .semantic{flex:none;padding:4px 10px 4px 5px}',
111
111
  '.memp .toolbar .semantic-label{font-size:12px;line-height:1.6}',
112
112
  '.memp .toolbar .semantic-state{font-size:11px;color:var(--dsw-alias-label-secondary)}',
@@ -434,6 +434,26 @@ window.__ModuleLoader__.load({
434
434
  '.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}',
435
435
  '.memp .audit-tip-foot{margin-top:6px;font-size:9.5px;color:var(--dsw-alias-label-secondary)}',
436
436
  '.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)}',
437
+ // 审计 → 轨迹的精准跳转按钮:只在有锚点时出现,不抢详情头部的主操作。
438
+ '.memp .audit-jump{display:inline-flex;align-items:center;gap:4px;border:1px solid var(--dsw-alias-border-l1);border-radius:7px;padding:2px 7px;font-size:10.5px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary);cursor:pointer}',
439
+ '.memp .audit-jump:hover{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}',
440
+ '.memp .audit-jump[disabled]{opacity:.55;cursor:default}',
441
+ '.memp .audit-jump-note{font-size:10px;color:var(--dsw-alias-label-secondary)}',
442
+ // 会话视图里的「记忆审计」页:壳层已经有自己的滚动区,这里只负责头部。
443
+ '.mem-view{display:flex;flex-direction:column;gap:10px;padding:12px 14px 6px;min-height:0;height:100%;box-sizing:border-box;overflow:hidden;color:var(--dsw-alias-label-primary)}',
444
+ '.mem-view-head{display:flex;align-items:center;gap:9px;flex-wrap:wrap;flex:none}',
445
+ '.mem-view-head b{font-size:14px}',
446
+ '.mem-view-head .muted{font-size:11.5px;color:var(--dsw-alias-label-secondary)}',
447
+ '.mem-view-head .spacer{flex:1}',
448
+ '.mem-view-body{min-height:0;flex:1;display:flex;flex-direction:column;overflow:hidden}',
449
+ '.mem-view .audit{height:auto;max-height:none;flex:1}',
450
+ // 会话标题行里的入口:和宿主 header 的紧凑按钮同高,只借边框/文字色。
451
+ '.mem-head-btn{border:1px solid transparent;border-radius:6px;background:none;color:var(--dsw-alias-label-secondary);font-size:11.5px;line-height:20px;padding:0 7px;cursor:pointer;white-space:nowrap}',
452
+ '.mem-head-btn:hover{border-color:var(--dsw-alias-border-l1);background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}',
453
+ // 轨迹行上的记忆徽标:fixed 定位在选中行右侧,不改轨迹表格结构。
454
+ '.mem-traj-chip{position:fixed;z-index:70;display:inline-flex;align-items:center;gap:4px;height:20px;padding:0 7px;border:1px solid color-mix(in srgb,var(--dsw-alias-brand-primary) 42%,var(--dsw-alias-border-l1));border-radius:999px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-brand-primary);font-size:10px;line-height:1;cursor:pointer;box-shadow:0 2px 8px rgba(0,0,0,.18);white-space:nowrap}',
455
+ '.mem-traj-chip:hover{background:color-mix(in srgb,var(--dsw-alias-brand-primary) 10%,var(--dsw-alias-bg-layer-1))}',
456
+ '.mem-traj-chip .dot{width:5px;height:5px;border-radius:50%;background:currentColor}',
437
457
  '@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}}',
438
458
  '@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)}}',
439
459
  ].join('')
@@ -808,8 +828,10 @@ window.__ModuleLoader__.load({
808
828
  score !== null && score !== undefined && Number.isFinite(Number(score))
809
829
  ? h('span', {
810
830
  className: 'badge score',
811
- title: '检索得分:向量相似度 / 词法命中,再按时效与重要度加权后的排序分',
812
- }, `相关度 ${Number(score).toFixed(2)}`)
831
+ // 这是**排序分**,不是概率:向量/词法命中 × 重要度 × 时效 × 访问次数加权,
832
+ // 访问次数多时可能大于 1。叫「相关度」会让人误以为一定在 0~1 之间。
833
+ title: '检索得分 = 向量/词法命中 × 重要度 × 时效 × 访问次数;只用于结果排序,可能大于 1',
834
+ }, `得分 ${Number(score).toFixed(2)}`)
813
835
  : null,
814
836
  rec.supersedes
815
837
  ? h('span', {
@@ -2058,6 +2080,230 @@ window.__ModuleLoader__.load({
2058
2080
  )
2059
2081
  }
2060
2082
 
2083
+ // ===== 记忆审计 ↔ 会话轨迹 的桥接 =====
2084
+ //
2085
+ // DSH 的 Trajectory 面板是一个纯投影:它只声明 `conversation.trajectory.images`
2086
+ // 一个子槽,没有行/列的扩展点,选中状态也是组件私有的。但它**支持按 callId
2087
+ // 深链聚焦**(`toolCallFocus` 就是同一性映射),而每个 `conversation.view`
2088
+ // 的渲染产物都会收到 `openView(view, focus)`。所以:
2089
+ // - 会话内的「记忆审计」视图直接用 openView('trajectory', callId);
2090
+ // - 主面板(不在会话视图树里)通过 `conversation.session` 条目挂的 per-session
2091
+ // store 调同一个 action。这里是宿主 slot 服务的内部字段(`_stores`),
2092
+ // 全部做了存在性判断;拿不到就退化成“只打开会话/只切轨迹页”,绝不 throw。
2093
+ let clientCtx = null
2094
+ const AUDIT_FOCUS_EVENT = 'dsh-memory:audit-focus'
2095
+ let pendingAuditFocus = null
2096
+
2097
+ function safeSlots() {
2098
+ try { return clientCtx?.get?.('slots') } catch { return undefined }
2099
+ }
2100
+
2101
+ function uiWorkspace() {
2102
+ try { return clientCtx?.get?.('uiWorkspace') } catch { return undefined }
2103
+ }
2104
+
2105
+ function openSessionById(id) {
2106
+ if (typeof id !== 'string' || id === '') return
2107
+ try {
2108
+ const workspace = uiWorkspace()
2109
+ if (workspace && typeof workspace.openSession === 'function') {
2110
+ workspace.openSession(id)
2111
+ return
2112
+ }
2113
+ if (typeof window !== 'undefined') window.location.hash = `#/s/${encodeURIComponent(id)}`
2114
+ } catch { /* 旧宿主没有 uiWorkspace:保持原状 */ }
2115
+ }
2116
+
2117
+ /** 当前主视图保留的会话(Host 用 retainedBy.mainView 标出)。 */
2118
+ function currentSessionId() {
2119
+ try {
2120
+ const snapshot = uiWorkspace()?.sessions?.list?.getSnapshot?.()
2121
+ const rows = snapshot && snapshot.byId ? Object.values(snapshot.byId) : []
2122
+ const current = rows.find((row) => row && row.retainedBy && (row.retainedBy.mainView ?? 0) > 0)
2123
+ return current && typeof current.id === 'string' ? current.id : undefined
2124
+ } catch {
2125
+ return undefined
2126
+ }
2127
+ }
2128
+
2129
+ /** 审计条目的轨迹锚:优先 operationId(记忆工具调用/工具信号),其次 signal.callId。 */
2130
+ function auditEntryCallId(entry) {
2131
+ if (!entry || typeof entry !== 'object') return undefined
2132
+ if (typeof entry.operationId === 'string' && entry.operationId !== '') return entry.operationId
2133
+ const signalCall = entry.signal && typeof entry.signal.callId === 'string' ? entry.signal.callId : ''
2134
+ return signalCall !== '' ? signalCall : undefined
2135
+ }
2136
+
2137
+ /** Trajectory 的行 key 形如 `tool\0call\0<callId>`;解析失败返回 undefined。 */
2138
+ function trajectoryRowCallId(row) {
2139
+ try {
2140
+ const key = row && typeof row.getAttribute === 'function' ? row.getAttribute('data-trajectory-row-key') : ''
2141
+ if (typeof key !== 'string') return undefined
2142
+ const sep = '\u0000call\u0000'
2143
+ const at = key.indexOf(sep)
2144
+ return at >= 0 ? key.slice(at + sep.length) : undefined
2145
+ } catch {
2146
+ return undefined
2147
+ }
2148
+ }
2149
+
2150
+ function selectedTrajectoryCallId() {
2151
+ try {
2152
+ const row = typeof document !== 'undefined'
2153
+ ? document.querySelector('tr[data-selected="true"][data-trajectory-row-key]')
2154
+ : null
2155
+ return row === null ? undefined : trajectoryRowCallId(row)
2156
+ } catch {
2157
+ return undefined
2158
+ }
2159
+ }
2160
+
2161
+ /**
2162
+ * `conversation.session` 注册时把 per-session store 交给 slot 服务;服务把实例
2163
+ * 放在 `_stores` 的 handle 记录里,按 session id 解析。这是主面板唯一能拿到
2164
+ * `openView` 的路径(slot 只把 actions 交给注册者自己)。
2165
+ */
2166
+ function conversationStoreFor(sessionId) {
2167
+ if (typeof sessionId !== 'string' || sessionId === '') return undefined
2168
+ try {
2169
+ const slots = safeSlots()
2170
+ const entries = slots?.entries?.('conversation.session') ?? []
2171
+ const handle = entries.map((entry) => entry?.store).find((value) => value !== undefined)
2172
+ if (handle === undefined) return undefined
2173
+ const record = slots?._stores?.get?.(handle)
2174
+ const instances = record && record.instances
2175
+ if (!(instances instanceof Map)) return undefined
2176
+ const direct = instances.get(sessionId)
2177
+ if (direct !== undefined) return direct
2178
+ for (const [key, store] of instances) {
2179
+ if (String(key) === sessionId || String(key).endsWith(sessionId)) return store
2180
+ }
2181
+ if (instances.size === 1) return [...instances.values()][0]
2182
+ return undefined
2183
+ } catch {
2184
+ return undefined
2185
+ }
2186
+ }
2187
+
2188
+ function setConversationView(sessionId, view, focus) {
2189
+ const store = conversationStoreFor(sessionId)
2190
+ const actions = store && store.actions
2191
+ if (!actions) return false
2192
+ try {
2193
+ if (typeof actions.openView === 'function') {
2194
+ actions.openView(view, focus)
2195
+ return true
2196
+ }
2197
+ if (typeof actions.setView === 'function') {
2198
+ actions.setView(view)
2199
+ return true
2200
+ }
2201
+ } catch { /* action 失败:调用方退化成打开会话 */ }
2202
+ return false
2203
+ }
2204
+
2205
+ /** 打开会话并把 Trajectory 切到指定 callId;拿不到 store 时轮询等待会话挂载。 */
2206
+ async function jumpToTrajectory(sessionId, focus) {
2207
+ if (typeof sessionId !== 'string' || sessionId === '') return { opened: false, focused: false }
2208
+ openSessionById(sessionId)
2209
+ for (let attempt = 0; attempt < 40; attempt += 1) {
2210
+ const store = conversationStoreFor(sessionId)
2211
+ const actions = store && store.actions
2212
+ if (actions) {
2213
+ try {
2214
+ if (focus !== undefined && typeof actions.openView === 'function') {
2215
+ actions.openView('trajectory', focus)
2216
+ return { opened: true, focused: true }
2217
+ }
2218
+ if (typeof actions.setView === 'function') {
2219
+ actions.setView('trajectory')
2220
+ return { opened: true, focused: false }
2221
+ }
2222
+ } catch { /* 继续重试 */ }
2223
+ }
2224
+ await new Promise((resolve) => setTimeout(resolve, 75))
2225
+ }
2226
+ return { opened: false, focused: false }
2227
+ }
2228
+
2229
+ /** 无 operationId 时,用 turn/step 去 Host 的会话事件里找该步的工具调用。 */
2230
+ async function resolveAuditFocus(entry) {
2231
+ const direct = auditEntryCallId(entry)
2232
+ if (direct !== undefined) return direct
2233
+ if (!entry || typeof entry.sessionId !== 'string' || entry.sessionId === '') return undefined
2234
+ if (typeof entry.turn !== 'number' && typeof entry.step !== 'number') return undefined
2235
+ try {
2236
+ const params = new URLSearchParams({ session: entry.sessionId })
2237
+ if (typeof entry.turn === 'number') params.set('turn', String(entry.turn))
2238
+ if (typeof entry.step === 'number') params.set('step', String(entry.step))
2239
+ const value = await api(`anchor?${params.toString()}`)
2240
+ return value && typeof value.callId === 'string' && value.callId !== '' ? value.callId : undefined
2241
+ } catch {
2242
+ return undefined
2243
+ }
2244
+ }
2245
+
2246
+ async function jumpAuditEntryToTrajectory(entry) {
2247
+ if (!entry || typeof entry.sessionId !== 'string' || entry.sessionId === '') {
2248
+ return { opened: false, focused: false, reason: 'no_session' }
2249
+ }
2250
+ const focus = await resolveAuditFocus(entry)
2251
+ const result = await jumpToTrajectory(entry.sessionId, focus)
2252
+ return { ...result, reason: focus === undefined ? 'no_anchor' : 'focused' }
2253
+ }
2254
+
2255
+ function requestAuditFocus(target) {
2256
+ pendingAuditFocus = target && typeof target === 'object' ? { ...target, at: Date.now() } : null
2257
+ try {
2258
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof CustomEvent === 'function') {
2259
+ window.dispatchEvent(new CustomEvent(AUDIT_FOCUS_EVENT, { detail: pendingAuditFocus }))
2260
+ }
2261
+ } catch { /* 没有 CustomEvent 时靠挂载时取一次 */ }
2262
+ }
2263
+
2264
+ function takeAuditFocus(audience) {
2265
+ const target = pendingAuditFocus
2266
+ if (!target) return null
2267
+ if (audience && target.audience && target.audience !== audience) return null
2268
+ pendingAuditFocus = null
2269
+ return target
2270
+ }
2271
+
2272
+ /** 只读探测:面板挂载时据此先切到「审计」标签,再让 AuditTab 自己消费。 */
2273
+ function peekAuditFocus(audience) {
2274
+ const target = pendingAuditFocus
2275
+ if (!target) return null
2276
+ if (audience && target.audience && target.audience !== audience) return null
2277
+ return target
2278
+ }
2279
+
2280
+ /**
2281
+ * 从轨迹/头部入口打开记忆审计:优先主面板;没有侧栏入口时切到会话内的
2282
+ * 「记忆」视图;两者都不可用时至少打开设置页(面板挂载后会消费 pending)。
2283
+ */
2284
+ function openMemoryAuditPanel(target) {
2285
+ const sessionId = target && typeof target.sessionId === 'string' ? target.sessionId : undefined
2286
+ try {
2287
+ const main = safeSlots()?.entries?.('main') ?? []
2288
+ if (main.some((entry) => entry?.options?.key === 'memory')) {
2289
+ requestAuditFocus({ ...target, audience: 'panel' })
2290
+ try { clientCtx?.get?.('layout')?.selectPanel?.('memory') } catch { /* 交给挂载消费 */ }
2291
+ return 'panel'
2292
+ }
2293
+ } catch { /* fallthrough */ }
2294
+ try {
2295
+ const views = safeSlots()?.entries?.('conversation.view') ?? []
2296
+ const hasView = views.some((entry) => entry?.options?.id === 'memory')
2297
+ if (hasView && sessionId !== undefined && conversationStoreFor(sessionId) !== undefined) {
2298
+ requestAuditFocus({ ...target, audience: 'view' })
2299
+ if (setConversationView(sessionId, 'memory')) return 'view'
2300
+ }
2301
+ } catch { /* fallthrough */ }
2302
+ requestAuditFocus({ ...target, audience: 'panel' })
2303
+ try { clientCtx?.get?.('layout')?.selectPanel?.('settings') } catch { /* 无布局服务 */ }
2304
+ return 'settings'
2305
+ }
2306
+
2061
2307
  // ===== 审计标签页 =====
2062
2308
  const AUDIT_CHANNEL_META = {
2063
2309
  digest: '摘要', recall: '召回', rules: '规则', rules_delta: '规则增量',
@@ -2119,6 +2365,7 @@ window.__ModuleLoader__.load({
2119
2365
  return `${meta.label}${meta.detail}${entry.delivery && entry.delivery.textChars ? ` · ${entry.delivery.textChars} 字符` : ''}`
2120
2366
  }
2121
2367
  if (entry.kind === 'signal') {
2368
+ if (entry.stage === 'tool_call') return `记忆工具调用${entry.signal && entry.signal.tool ? ` · ${entry.signal.tool}` : ''}`
2122
2369
  const stage = entry.stage === 'signal_consumed' ? '信号已消费' : entry.stage === 'signal_dropped' ? '信号被丢弃' : '信号已排队'
2123
2370
  return `${stage}${entry.signal && entry.signal.reason ? ` · ${entry.signal.reason}` : ''}`
2124
2371
  }
@@ -2163,7 +2410,16 @@ window.__ModuleLoader__.load({
2163
2410
  tag_mismatch: '标签不匹配', dedup: '去重', excluded: '被排除', skipped: '跳过',
2164
2411
  }
2165
2412
 
2166
- function AuditTab({ scopes, records = [], openRecord, openSession, sessionInfo }) {
2413
+ function AuditTab({
2414
+ scopes,
2415
+ records = [],
2416
+ openRecord,
2417
+ openSession,
2418
+ sessionInfo,
2419
+ audience = 'panel',
2420
+ lockSession,
2421
+ openTrajectory,
2422
+ }) {
2167
2423
  const [entries, setEntries] = React.useState([])
2168
2424
  const [stats, setStats] = React.useState(null)
2169
2425
  const [total, setTotal] = React.useState(0)
@@ -2174,10 +2430,12 @@ window.__ModuleLoader__.load({
2174
2430
  const [error, setError] = React.useState('')
2175
2431
  const [copyNotice, setCopyNotice] = React.useState('')
2176
2432
  const [exportNotice, setExportNotice] = React.useState('')
2433
+ const [focusNotice, setFocusNotice] = React.useState('')
2434
+ const [focusBusy, setFocusBusy] = React.useState(false)
2177
2435
  const [autoRefresh, setAutoRefresh] = React.useState(true)
2178
2436
  const [refreshMs, setRefreshMs] = React.useState(500)
2179
2437
  const loadingRef = React.useRef(false)
2180
- const [session, setSession] = React.useState(readAuditSession())
2438
+ const [session, setSession] = React.useState(lockSession || readAuditSession())
2181
2439
  const [channel, setChannel] = React.useState('')
2182
2440
  const [outcome, setOutcome] = React.useState('')
2183
2441
  const [trigger, setTrigger] = React.useState('')
@@ -2192,10 +2450,11 @@ window.__ModuleLoader__.load({
2192
2450
  const [recordCache, setRecordCache] = React.useState({})
2193
2451
  const tipTimer = React.useRef(null)
2194
2452
  const hideTimer = React.useRef(null)
2453
+ const effectiveSession = lockSession || session
2195
2454
 
2196
2455
  function queryParams(cursorValue) {
2197
2456
  const params = new URLSearchParams()
2198
- if (session) params.set('session', session)
2457
+ if (effectiveSession) params.set('session', effectiveSession)
2199
2458
  if (channel) params.set('channel', channel)
2200
2459
  if (outcome) params.set('outcome', outcome)
2201
2460
  if (trigger.trim()) params.set('trigger', trigger.trim())
@@ -2243,6 +2502,38 @@ window.__ModuleLoader__.load({
2243
2502
 
2244
2503
  React.useEffect(() => { load('', []) }, [reloadTick])
2245
2504
 
2505
+ // 从轨迹行/会话头部跳到审计时,可能带着 session + callId + 具体事件 id。
2506
+ // 面板挂载时先取一次 pending,之后靠同一个 window 事件接收(面板已经在
2507
+ // 屏幕上时不必重挂)。只消费与自己 audience 匹配的目标。
2508
+ React.useEffect(() => {
2509
+ const applyFocus = () => {
2510
+ const target = takeAuditFocus(audience)
2511
+ if (!target) return
2512
+ if (!lockSession && typeof target.sessionId === 'string' && target.sessionId !== '') {
2513
+ setSession(target.sessionId)
2514
+ writeAuditSession(target.sessionId)
2515
+ }
2516
+ if (typeof target.callId === 'string' && target.callId !== '') {
2517
+ setSearch(`op:${target.callId}`)
2518
+ setFocusNotice(`已定位到轨迹调用 ${target.callId.slice(0, 12)}`)
2519
+ } else if (!lockSession) {
2520
+ setSearch('')
2521
+ }
2522
+ if (typeof target.entryId === 'string' && target.entryId !== '') setSelectedId(target.entryId)
2523
+ setReloadTick((n) => n + 1)
2524
+ }
2525
+ applyFocus()
2526
+ const onFocus = () => applyFocus()
2527
+ try {
2528
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') window.addEventListener(AUDIT_FOCUS_EVENT, onFocus)
2529
+ } catch { /* 没有 window 事件也能靠挂载时消费 */ }
2530
+ return () => {
2531
+ try {
2532
+ if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') window.removeEventListener(AUDIT_FOCUS_EVENT, onFocus)
2533
+ } catch { /* cleanup 失败不影响面板 */ }
2534
+ }
2535
+ }, [audience, lockSession])
2536
+
2246
2537
  // 自动刷新:默认 500ms,可关;页面隐藏时跳过,避免后台无意义轮询。
2247
2538
  React.useEffect(() => {
2248
2539
  if (!autoRefresh) return undefined
@@ -2251,7 +2542,7 @@ window.__ModuleLoader__.load({
2251
2542
  load(cursor, cursorStack, { silent: true })
2252
2543
  }, refreshMs)
2253
2544
  return () => clearInterval(timer)
2254
- }, [autoRefresh, refreshMs, cursor, cursorStack, session, channel, outcome, trigger, search, problem, range, since, until])
2545
+ }, [autoRefresh, refreshMs, cursor, cursorStack, effectiveSession, channel, outcome, trigger, search, problem, range, since, until])
2255
2546
 
2256
2547
  const resetAndReload = () => { setCursor(''); setCursorStack([]); setReloadTick((n) => n + 1) }
2257
2548
  const selected = selectedId === null ? null : entries.find((entry) => entry.id === selectedId) || null
@@ -2356,8 +2647,8 @@ window.__ModuleLoader__.load({
2356
2647
  value: scope.scope.slice(8),
2357
2648
  label: scope.label || `会话 ${scope.scope.slice(8, 16)}`,
2358
2649
  })))
2359
- if (session && !sessionOptions.some((item) => item.value === session)) {
2360
- sessionOptions.push({ value: session, label: `会话 ${session.slice(0, 8)}` })
2650
+ if (effectiveSession && !sessionOptions.some((item) => item.value === effectiveSession)) {
2651
+ sessionOptions.push({ value: effectiveSession, label: `会话 ${effectiveSession.slice(0, 8)}` })
2361
2652
  }
2362
2653
  const channelOptions = [{ value: '', label: '全部通道' }].concat(Object.keys(AUDIT_CHANNEL_META).map((key) => ({ value: key, label: AUDIT_CHANNEL_META[key] })))
2363
2654
  const outcomeOptions = [{ value: '', label: '全部结果' }].concat(Object.keys(AUDIT_OUTCOME_META).map((key) => ({ value: key, label: AUDIT_OUTCOME_META[key].label })))
@@ -2394,13 +2685,15 @@ window.__ModuleLoader__.load({
2394
2685
  banner.push(h('div', { className: 'audit-banner bad', key: 'err' }, `审计写入失败 ${writeErrors} 次;面板数据可能不完整。`))
2395
2686
  }
2396
2687
 
2397
- const filterActive = Boolean(session || channel || outcome || trigger || search || problem || range)
2688
+ const filterActive = Boolean(effectiveSession || channel || outcome || trigger || search || problem || range)
2398
2689
  const toolbar = h('div', { className: 'audit-toolbar' },
2399
2690
  h('div', { className: 'audit-filter-row' },
2400
- h(Dropdown, {
2401
- items: sessionOptions, value: session, disabled: loading,
2402
- onChange: (next) => { setSession(next); writeAuditSession(next); resetAndReload() },
2403
- }),
2691
+ lockSession
2692
+ ? h('span', { className: 'audit-pill mute', title: lockSession }, `会话 ${String(lockSession).slice(0, 10)}`)
2693
+ : h(Dropdown, {
2694
+ items: sessionOptions, value: session, disabled: loading,
2695
+ onChange: (next) => { setSession(next); writeAuditSession(next); resetAndReload() },
2696
+ }),
2404
2697
  h(Dropdown, {
2405
2698
  items: channelOptions, value: channel, disabled: loading,
2406
2699
  onChange: (next) => { setChannel(next); resetAndReload() },
@@ -2460,7 +2753,7 @@ window.__ModuleLoader__.load({
2460
2753
  : null,
2461
2754
  filterActive
2462
2755
  ? h('button', { className: 'linkbtn', onClick: () => {
2463
- setSession(''); writeAuditSession(''); setChannel(''); setOutcome(''); setTrigger(''); setSearch(''); setProblem(false); setRange(''); setSince(''); setUntil(''); resetAndReload()
2756
+ setSession(lockSession || ''); if (!lockSession) writeAuditSession(''); setChannel(''); setOutcome(''); setTrigger(''); setSearch(''); setProblem(false); setRange(''); setSince(''); setUntil(''); resetAndReload()
2464
2757
  } }, '清空筛选')
2465
2758
  : null,
2466
2759
  h('span', { className: 'spacer' }),
@@ -2542,15 +2835,48 @@ window.__ModuleLoader__.load({
2542
2835
  onClick: () => openSessionId(selected.sessionId),
2543
2836
  }, selected.sessionId))]
2544
2837
  : null
2838
+ const directCall = auditEntryCallId(selected)
2839
+ const hasStep = typeof selected.turn === 'number' || typeof selected.step === 'number'
2840
+ const jumpTarget = directCall !== undefined
2841
+ ? `callId ${directCall}`
2842
+ : hasStep ? `第 ${selected.turn ?? '?'} 轮 / 第 ${selected.step ?? '?'} 步(按步查找)` : undefined
2843
+ const onJump = async () => {
2844
+ if (!selected.sessionId) return
2845
+ setFocusBusy(true)
2846
+ setFocusNotice('')
2847
+ try {
2848
+ const focus = await resolveAuditFocus(selected)
2849
+ if (typeof openTrajectory === 'function') {
2850
+ openTrajectory(focus)
2851
+ setFocusNotice(focus === undefined ? '已切到轨迹页(这条没有精确锚点)' : '已定位到轨迹')
2852
+ return
2853
+ }
2854
+ const result = await jumpAuditEntryToTrajectory(selected)
2855
+ setFocusNotice(result.focused ? '已定位到轨迹' : result.opened ? '已切到轨迹页(未找到精确锚点)' : '打开轨迹失败')
2856
+ } catch {
2857
+ setFocusNotice('定位失败')
2858
+ } finally {
2859
+ setFocusBusy(false)
2860
+ }
2861
+ }
2545
2862
  const json = JSON.stringify(selected, null, 2)
2546
2863
  return h('div', { className: 'audit-detail' },
2547
2864
  h('div', { className: 'audit-detail-head' },
2548
2865
  h('b', null, auditSummaryLine(selected)),
2549
2866
  h('span', { className: 'spacer' }),
2867
+ selected.sessionId
2868
+ ? h('button', {
2869
+ className: 'audit-jump',
2870
+ disabled: focusBusy,
2871
+ title: jumpTarget === undefined ? '切到该会话的轨迹页(本条没有 callId/turn/step 锚点)' : `在轨迹中定位:${jumpTarget}`,
2872
+ onClick: onJump,
2873
+ }, focusBusy ? '定位中…' : '在轨迹中定位')
2874
+ : null,
2550
2875
  h('button', { className: 'linkbtn', onClick: () => copyAuditText(selected.id, setCopyNotice) }, '复制 ID'),
2551
2876
  copyNotice ? h('span', { className: 'audit-inline-note' }, copyNotice) : null,
2552
2877
  h('button', { className: 'audit-close', title: '关闭', onClick: () => { setSelectedId(null); setCopyNotice('') } }, '×'),
2553
2878
  ),
2879
+ focusNotice ? h('div', { className: 'audit-jump-note' }, focusNotice) : null,
2554
2880
  h('div', { className: 'audit-kv' },
2555
2881
  kv('事件', selected.id),
2556
2882
  kv('序号', selected.seq),
@@ -2558,6 +2884,7 @@ window.__ModuleLoader__.load({
2558
2884
  kv('schema', selected.schemaVersion || '旧版'),
2559
2885
  sessionNode,
2560
2886
  kv('step', selected.step),
2887
+ kv('轨迹锚点', jumpTarget),
2561
2888
  kv('通道', `${auditChannelLabel(selected.channel)} / ${selected.kind}`),
2562
2889
  kv('阶段', selected.stage),
2563
2890
  kv('触发', selected.trigger),
@@ -2743,7 +3070,7 @@ window.__ModuleLoader__.load({
2743
3070
  /** 待嵌入自动刷新:最多 300 次 × 1.5s(后端挂着时不无限轮询)。 */
2744
3071
  const PENDING_POLL_LIMIT = 300
2745
3072
 
2746
- function MemoryPanel({ openSession, sessionInfo } = {}) {
3073
+ function MemoryPanel({ openSession, sessionInfo, openTrajectory, audience = 'panel', lockSession } = {}) {
2747
3074
  const [records, setRecords] = React.useState([])
2748
3075
  const [scopes, setScopes] = React.useState([])
2749
3076
  const [embedServer, setEmbedServer] = React.useState(null)
@@ -2764,6 +3091,21 @@ window.__ModuleLoader__.load({
2764
3091
  const [pendingTick, setPendingTick] = React.useState(0)
2765
3092
  const [creating, setCreating] = React.useState(false)
2766
3093
 
3094
+ // 从轨迹/会话头部带进来的焦点:面板可能正停在「记录」页,先切到「审计」,
3095
+ // 具体的 session/entry 过滤由 AuditTab 挂载时消费。
3096
+ React.useEffect(() => {
3097
+ const sync = () => { if (peekAuditFocus(audience) !== null) setTab('audit') }
3098
+ sync()
3099
+ try {
3100
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') window.addEventListener(AUDIT_FOCUS_EVENT, sync)
3101
+ } catch { /* 无事件环境 */ }
3102
+ return () => {
3103
+ try {
3104
+ if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') window.removeEventListener(AUDIT_FOCUS_EVENT, sync)
3105
+ } catch { /* cleanup 失败不影响面板 */ }
3106
+ }
3107
+ }, [audience])
3108
+
2767
3109
  const load = async (query, scopeF, semanticF) => {
2768
3110
  setLoading(true); setError('')
2769
3111
  try {
@@ -3208,18 +3550,176 @@ window.__ModuleLoader__.load({
3208
3550
  : tab === 'tree'
3209
3551
  ? treeBody
3210
3552
  : tab === 'audit'
3211
- ? h(AuditTab, { scopes, records, openRecord, openSession, sessionInfo })
3553
+ ? h(AuditTab, {
3554
+ scopes,
3555
+ records,
3556
+ openRecord,
3557
+ openSession,
3558
+ sessionInfo,
3559
+ audience,
3560
+ lockSession,
3561
+ openTrajectory,
3562
+ })
3212
3563
  : overviewBody,
3213
3564
  )
3214
3565
  }
3215
3566
 
3567
+ /**
3568
+ * 会话内的「记忆审计」视图:和 Chat/Trajectory 同一个 view ring。
3569
+ *
3570
+ * 它拿到 owner 传下来的 `openView(view, focus)`,所以从这里跳轨迹是宿主
3571
+ * 官方支持的深链路径,不依赖任何内部字段。主面板(侧栏/设置)不在 view
3572
+ * ring 里,走 `conversationStoreFor` 的 bridge。
3573
+ */
3574
+ function MemoryAuditView({ sessionId, openView, sessionInfo }) {
3575
+ const openTrajectory = (focus) => {
3576
+ try {
3577
+ if (typeof openView === 'function') openView('trajectory', focus)
3578
+ } catch { /* 视图不可用时保持在本页 */ }
3579
+ }
3580
+ return h('div', { className: 'memp mem-view' },
3581
+ h('div', { className: 'mem-view-head' },
3582
+ h('b', null, '记忆审计'),
3583
+ h('span', { className: 'muted' }, '本会话的注入评估、投递与记忆工具调用;选中一条可在轨迹里精确定位。'),
3584
+ h('span', { className: 'spacer' }),
3585
+ h('button', {
3586
+ className: 'linkbtn',
3587
+ onClick: () => openMemoryAuditPanel({ sessionId }),
3588
+ }, '打开完整面板'),
3589
+ ),
3590
+ h('div', { className: 'mem-view-body' },
3591
+ h(AuditTab, {
3592
+ scopes: [],
3593
+ records: [],
3594
+ sessionInfo,
3595
+ lockSession: sessionId,
3596
+ audience: 'view',
3597
+ openTrajectory,
3598
+ }),
3599
+ ),
3600
+ )
3601
+ }
3602
+
3603
+ /** 会话头部的入口:有选中轨迹行时自动带上 callId,直接落到那组审计。 */
3604
+ function MemoryHeaderAction({ sessionId }) {
3605
+ return h('button', {
3606
+ className: 'mem-head-btn',
3607
+ title: '查看本会话的记忆审计(若轨迹里选中了工具行,会定位到该调用)',
3608
+ onClick: () => {
3609
+ const callId = selectedTrajectoryCallId()
3610
+ openMemoryAuditPanel({
3611
+ sessionId,
3612
+ ...(callId !== undefined ? { callId } : {}),
3613
+ })
3614
+ },
3615
+ }, '记忆审计')
3616
+ }
3617
+
3618
+ /**
3619
+ * Trajectory 行上的记忆徽标。
3620
+ *
3621
+ * Trajectory 不提供行级 slot,选中状态也只存在于组件内部。这里用宿主已经
3622
+ * 渲染到 DOM 上的稳定属性(`data-selected` / `data-trajectory-row-key`:
3623
+ * `kind\0call\0<callId>`)做只读观察,再把一个 fixed 徽标浮在选中行右侧。
3624
+ * 它不插入表格、不改轨迹结构;选择器失配时什么都不显示。
3625
+ */
3626
+ function TrajectoryMemoryBadge() {
3627
+ const [badge, setBadge] = React.useState(null)
3628
+ const cache = React.useRef(new Map())
3629
+ React.useEffect(() => {
3630
+ let disposed = false
3631
+ let raf = 0
3632
+ const rafFn = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : ((fn) => setTimeout(fn, 16))
3633
+ const cancelFn = typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : ((id) => clearTimeout(id))
3634
+ const schedule = () => {
3635
+ if (disposed || raf !== 0) return
3636
+ raf = rafFn(() => { raf = 0; tick() })
3637
+ }
3638
+ const tick = () => {
3639
+ try {
3640
+ if (typeof document === 'undefined' || typeof window === 'undefined') return
3641
+ const row = document.querySelector('tr[data-selected="true"][data-trajectory-row-key]')
3642
+ const callId = trajectoryRowCallId(row)
3643
+ const sessionId = currentSessionId()
3644
+ if (!row || callId === undefined || sessionId === undefined) {
3645
+ setBadge(null)
3646
+ return
3647
+ }
3648
+ const rect = row.getBoundingClientRect()
3649
+ const position = {
3650
+ top: Math.max(4, rect.top + 4),
3651
+ left: Math.max(8, Math.min(window.innerWidth - 132, rect.right - 122)),
3652
+ }
3653
+ const key = `${sessionId}|${callId}`
3654
+ const cached = cache.current.get(key)
3655
+ const now = Date.now()
3656
+ if (cached && cached.pending === true) return
3657
+ if (cached && now - cached.at < 4000) {
3658
+ setBadge(cached.entries.length === 0 ? null : { ...position, sessionId, callId, entries: cached.entries })
3659
+ return
3660
+ }
3661
+ cache.current.set(key, { at: now, pending: true, entries: [] })
3662
+ api(`audit?session=${encodeURIComponent(sessionId)}&operation=${encodeURIComponent(callId)}&limit=20`)
3663
+ .then((value) => {
3664
+ const entries = value && Array.isArray(value.entries) ? value.entries : []
3665
+ cache.current.set(key, { at: Date.now(), pending: false, entries })
3666
+ if (!disposed) schedule()
3667
+ })
3668
+ .catch(() => {
3669
+ cache.current.set(key, { at: Date.now(), pending: false, entries: [] })
3670
+ })
3671
+ } catch { /* 观察失败:保持无徽标 */ }
3672
+ }
3673
+ let observer = null
3674
+ try {
3675
+ observer = new MutationObserver(schedule)
3676
+ observer.observe(document.body, {
3677
+ childList: true,
3678
+ subtree: true,
3679
+ attributes: true,
3680
+ attributeFilter: ['data-selected'],
3681
+ })
3682
+ } catch { observer = null }
3683
+ const onScroll = () => schedule()
3684
+ let onResize = onScroll
3685
+ try {
3686
+ window.addEventListener('scroll', onScroll, true)
3687
+ window.addEventListener('resize', onResize)
3688
+ } catch { /* 非浏览器环境 */ }
3689
+ schedule()
3690
+ return () => {
3691
+ disposed = true
3692
+ if (raf !== 0) cancelFn(raf)
3693
+ try { observer?.disconnect() } catch { /* 已断开 */ }
3694
+ try {
3695
+ window.removeEventListener('scroll', onScroll, true)
3696
+ window.removeEventListener('resize', onResize)
3697
+ } catch { /* 非浏览器环境 */ }
3698
+ }
3699
+ }, [])
3700
+ if (badge === null) return null
3701
+ return h('button', {
3702
+ className: 'mem-traj-chip',
3703
+ style: { top: badge.top, left: badge.left },
3704
+ title: '这次工具调用有记忆审计记录;点击在记忆面板里查看',
3705
+ onClick: () => {
3706
+ openMemoryAuditPanel({
3707
+ sessionId: badge.sessionId,
3708
+ callId: badge.callId,
3709
+ ...(badge.entries[0]?.id ? { entryId: badge.entries[0].id } : {}),
3710
+ })
3711
+ setBadge(null)
3712
+ },
3713
+ }, h('span', { className: 'dot' }), `记忆 ${badge.entries.length}`)
3714
+ }
3715
+
3216
3716
  const inject = ['slots']
3217
3717
 
3218
3718
  /** 侧栏入口打开的主界面页面(整块可滚动,内容就是面板本体)。 */
3219
- function MemoryPage({ openSession, sessionInfo } = {}) {
3719
+ function MemoryPage({ openSession, sessionInfo, openTrajectory } = {}) {
3220
3720
  return h('div', { className: 'mem-page' },
3221
3721
  h('div', { className: 'mem-page-head' }, h('h2', null, '记忆系统')),
3222
- h(MemoryPanel, { openSession, sessionInfo }),
3722
+ h(MemoryPanel, { openSession, sessionInfo, openTrajectory, audience: 'panel' }),
3223
3723
  )
3224
3724
  }
3225
3725
 
@@ -3262,6 +3762,7 @@ window.__ModuleLoader__.load({
3262
3762
 
3263
3763
  const slots = ctx.get('slots')
3264
3764
  if (slots === undefined) return
3765
+ clientCtx = ctx
3265
3766
 
3266
3767
  /** 宿主 uiWorkspace 服务:打开会话 / 读取会话摘要(旧宿主缺失时静默降级)。 */
3267
3768
  const workspaceService = () => {
@@ -3295,7 +3796,12 @@ window.__ModuleLoader__.load({
3295
3796
 
3296
3797
  slots.inject('settings.section', () => slots.register(
3297
3798
  { name: 'settings.section', id: 'memory', order: 24, label: NAV_LABEL },
3298
- () => React.createElement(MemoryPanel, { openSession, sessionInfo }),
3799
+ () => React.createElement(MemoryPanel, {
3800
+ openSession,
3801
+ sessionInfo,
3802
+ audience: 'panel',
3803
+ openTrajectory: jumpAuditEntryToTrajectory,
3804
+ }),
3299
3805
  ))
3300
3806
 
3301
3807
  // 侧栏入口(可选):开启后在左侧栏「插件」下方多一个「记忆系统」,点击在主界面打开面板。
@@ -3314,7 +3820,11 @@ window.__ModuleLoader__.load({
3314
3820
  }
3315
3821
  try {
3316
3822
  sidebarDisposers = [
3317
- slots.inject('main', () => slots.register({ name: 'main', key: 'memory' }, () => React.createElement(MemoryPage, { openSession, sessionInfo }))),
3823
+ slots.inject('main', () => slots.register({ name: 'main', key: 'memory' }, () => React.createElement(MemoryPage, {
3824
+ openSession,
3825
+ sessionInfo,
3826
+ openTrajectory: jumpAuditEntryToTrajectory,
3827
+ }))),
3318
3828
  slots.inject('sidebar.panellist', () => slots.register(
3319
3829
  { name: 'sidebar.panellist', id: 'memory', order: 20, label: () => NAV_LABEL },
3320
3830
  () => React.createElement(NavLineIcon),
@@ -3331,6 +3841,41 @@ window.__ModuleLoader__.load({
3331
3841
  window.addEventListener('dsh-memory:settings', syncSidebar)
3332
3842
  ctx.effect(() => () => window.removeEventListener('dsh-memory:settings', syncSidebar), 'dsh-memory: sidebar entry')
3333
3843
  }
3844
+
3845
+ // ===== 会话轨迹 / 视图环 / 浮层集成 =====
3846
+ // 每一条都单独兜底:宿主没有这个槽(旧版本/精简组合)时只是少一个入口,
3847
+ // 绝不能让整个 client apply 失败。
3848
+ try {
3849
+ slots.inject('conversation.view', () => slots.register({
3850
+ name: 'conversation.view',
3851
+ id: 'memory',
3852
+ order: 20,
3853
+ label: () => '记忆',
3854
+ inject: (sessionId) => ({ sessionId, sessionInfo }),
3855
+ }, MemoryAuditView))
3856
+ } catch (error) {
3857
+ console.warn('[dsh-memory] 记忆审计视图注册失败:', error?.message)
3858
+ }
3859
+ try {
3860
+ slots.inject('conversation.session.header.actions', () => slots.register({
3861
+ name: 'conversation.session.header.actions',
3862
+ id: 'memory-audit',
3863
+ order: 20,
3864
+ label: () => '记忆审计',
3865
+ inject: (sessionId) => ({ sessionId }),
3866
+ }, MemoryHeaderAction))
3867
+ } catch (error) {
3868
+ console.warn('[dsh-memory] 会话头部记忆入口注册失败:', error?.message)
3869
+ }
3870
+ try {
3871
+ slots.inject('shell.overlay', () => slots.register({
3872
+ name: 'shell.overlay',
3873
+ id: 'memory-audit-badge',
3874
+ order: 60,
3875
+ }, () => React.createElement(TrajectoryMemoryBadge)))
3876
+ } catch (error) {
3877
+ console.warn('[dsh-memory] 轨迹记忆徽标注册失败:', error?.message)
3878
+ }
3334
3879
  } catch (error) {
3335
3880
  console.error('[dsh-memory] client apply 失败(已吞掉):', error?.message)
3336
3881
  }
@@ -3456,6 +4001,17 @@ window.__ModuleLoader__.load({
3456
4001
  NavLineIcon: NavLineIcon,
3457
4002
  NAV_DOM: NAV_DOM,
3458
4003
  paintNavIcon: paintNavIcon,
4004
+ // 审计 ↔ 轨迹桥(测试只覆盖纯解析/焦点总线,不碰宿主 slot 实例)
4005
+ MemoryAuditView: MemoryAuditView,
4006
+ MemoryHeaderAction: MemoryHeaderAction,
4007
+ TrajectoryMemoryBadge: TrajectoryMemoryBadge,
4008
+ auditEntryCallId: auditEntryCallId,
4009
+ trajectoryRowCallId: trajectoryRowCallId,
4010
+ requestAuditFocus: requestAuditFocus,
4011
+ takeAuditFocus: takeAuditFocus,
4012
+ conversationStoreFor: conversationStoreFor,
4013
+ setConversationView: setConversationView,
4014
+ setClientCtx: (value) => { clientCtx = value },
3459
4015
  }
3460
4016
  return module.exports
3461
4017
  },
@@ -276,7 +276,11 @@ export function apply(ctx , config = {}) {
276
276
  return limited
277
277
  }
278
278
 
279
- const observeSignal = (sessionId , signal ) => {
279
+ const observeSignal = (
280
+ sessionId ,
281
+ signal ,
282
+ context = {},
283
+ ) => {
280
284
  if (!signal || !signals.note(sessionId, signal)) return
281
285
  const query = sanitizeAuditText(signal.query)
282
286
  recordAudit({
@@ -288,6 +292,9 @@ export function apply(ctx , config = {}) {
288
292
  sessionId,
289
293
  trigger: signal.reason,
290
294
  phase: signal.phase,
295
+ ...(context.turn !== undefined ? { turn: context.turn } : {}),
296
+ ...(context.step !== undefined ? { step: context.step } : {}),
297
+ ...(signal.callId !== undefined ? { operationId: signal.callId } : {}),
291
298
  ...(query !== undefined ? { query } : {}),
292
299
  signal: {
293
300
  key: signal.key,
@@ -296,10 +303,37 @@ export function apply(ctx , config = {}) {
296
303
  ...(signal.tool ? { tool: signal.tool } : {}),
297
304
  ...(signal.tag ? { tag: signal.tag } : {}),
298
305
  ...(signal.source ? { source: signal.source } : {}),
306
+ ...(signal.callId !== undefined ? { callId: signal.callId } : {}),
299
307
  },
300
308
  })
301
309
  }
302
310
 
311
+ /** 记忆工具自身的调用:不属于注入评估,但它是审计里最有用的轨迹锚点。 */
312
+ const MEMORY_TOOL_NAMES = new Set(['memory_save', 'memory_search', 'memory_forget', 'memory_list', 'memory_get'])
313
+ const rememberMemoryToolCall = (
314
+ sessionId ,
315
+ data ,
316
+ ) => {
317
+ const callId = typeof data.callId === 'string' ? data.callId : undefined
318
+ const tool = typeof data.name === 'string' ? data.name : undefined
319
+ if (callId === undefined || tool === undefined || !MEMORY_TOOL_NAMES.has(tool)) return
320
+ const turn = typeof data.turn === 'number' ? data.turn : undefined
321
+ const step = typeof data.step === 'number' ? data.step : undefined
322
+ recordAudit({
323
+ kind: 'signal',
324
+ channel: 'signal',
325
+ stage: 'tool_call',
326
+ outcome: 'success',
327
+ reasonCode: 'memory_tool',
328
+ trigger: 'memory_tool',
329
+ sessionId,
330
+ operationId: callId,
331
+ ...(turn !== undefined ? { turn } : {}),
332
+ ...(step !== undefined ? { step } : {}),
333
+ signal: { key: callId, reason: 'memory_tool', tool, source: 'tool', callId },
334
+ })
335
+ }
336
+
303
337
  const injector = new MemoryInjector(
304
338
  async (query, signal, scopes) => {
305
339
  const memory = ctx.get('memory')
@@ -343,6 +377,10 @@ export function apply(ctx , config = {}) {
343
377
  const memory = ctx.get('memory')
344
378
  if (memory) attachAudit(memory)
345
379
 
380
+ // 记忆工具调用先落一条锚点审计:即使自动召回关闭、或该工具没有命中
381
+ // 任何触发标签,用户也能从审计面板/记忆视图精确跳回轨迹里的那一次调用。
382
+ if (type === 'tool/call') rememberMemoryToolCall(sessionId, data)
383
+
346
384
  if (type === 'compaction/start' || type === 'compaction/end') {
347
385
  // 上下文重建:旧去重状态不再可信,允许摘要/正文重新进入。
348
386
  // 审计也要留下分界,否则压缩前后的记录会被误读成同一段上下文。
@@ -371,17 +409,24 @@ export function apply(ctx , config = {}) {
371
409
 
372
410
  if (type === 'tool/call') {
373
411
  const tool = typeof data.name === 'string' ? data.name : 'tool'
412
+ const callId = typeof data.callId === 'string' ? data.callId : undefined
374
413
  const args = typeof data.arguments === 'string'
375
414
  ? data.arguments
376
415
  : (() => { try { return JSON.stringify(data.arguments ?? '') } catch { return '' } })()
377
416
  const description = auto.useToolDescription ? toolCallDescription(data.arguments) : undefined
378
417
  rememberCallMeta(data.callId, tool, description)
418
+ const turn = typeof data.turn === 'number' ? data.turn : undefined
419
+ const step = typeof data.step === 'number' ? data.step : undefined
379
420
  observeSignal(sessionId, highRiskSignal(tool, args, {
380
421
  tags,
381
422
  ...(description !== undefined ? { description } : {}),
423
+ ...(callId !== undefined ? { callId } : {}),
382
424
  useToolDescription: auto.useToolDescription,
383
425
  maxQueryChars: auto.maxQueryChars,
384
- }))
426
+ }), {
427
+ ...(turn !== undefined ? { turn } : {}),
428
+ ...(step !== undefined ? { step } : {}),
429
+ })
385
430
  return
386
431
  }
387
432
  if (type === 'tool/result') {
@@ -391,10 +436,16 @@ export function apply(ctx , config = {}) {
391
436
  const callId = message?.source?.callId
392
437
  const meta = typeof callId === 'string' ? callMeta.get(callId) : undefined
393
438
  const description = auto.useToolDescription ? meta?.description : undefined
439
+ const turn = typeof data.turn === 'number' ? data.turn : undefined
440
+ const step = typeof data.step === 'number' ? data.step : undefined
394
441
  observeSignal(sessionId, failureSignal(meta?.name, failure.code, failure.message, {
395
442
  ...(description !== undefined ? { description } : {}),
443
+ ...(typeof callId === 'string' ? { callId } : {}),
396
444
  maxQueryChars: auto.maxQueryChars,
397
- }))
445
+ }), {
446
+ ...(turn !== undefined ? { turn } : {}),
447
+ ...(step !== undefined ? { step } : {}),
448
+ })
398
449
  return
399
450
  }
400
451
  // 可见 assistant 输出 / 任务清单 / 命令 / goal:命中记忆标签就排队一次召回。
@@ -528,14 +579,30 @@ export function apply(ctx , config = {}) {
528
579
  recordAudit(auditBase('signal', {
529
580
  kind: 'signal', stage: 'signal_dropped', outcome: 'skipped', reasonCode: 'auto_scope_unavailable',
530
581
  trigger: signal.reason, phase: signal.phase,
531
- signal: { key: signal.key, reason: signal.reason, ...(signal.tag ? { tag: signal.tag } : {}), ...(signal.tool ? { tool: signal.tool } : {}) },
582
+ ...(signal.callId !== undefined ? { operationId: signal.callId } : {}),
583
+ signal: {
584
+ key: signal.key,
585
+ reason: signal.reason,
586
+ ...(signal.tag ? { tag: signal.tag } : {}),
587
+ ...(signal.tool ? { tool: signal.tool } : {}),
588
+ ...(signal.callId !== undefined ? { callId: signal.callId } : {}),
589
+ },
532
590
  }))
533
591
  }
534
592
  if (usableSignal !== undefined) {
535
593
  recordAudit(auditBase('signal', {
536
594
  kind: 'signal', stage: 'signal_consumed', outcome: 'success', reasonCode: 'consumed',
537
595
  trigger: usableSignal.reason, phase: usableSignal.phase,
538
- signal: { key: usableSignal.key, reason: usableSignal.reason, ...(usableSignal.tag ? { tag: usableSignal.tag } : {}), ...(usableSignal.tool ? { tool: usableSignal.tool } : {}), ...(usableSignal.errorClass ? { errorClass: usableSignal.errorClass } : {}), ...(usableSignal.source ? { source: usableSignal.source } : {}) },
596
+ ...(usableSignal.callId !== undefined ? { operationId: usableSignal.callId } : {}),
597
+ signal: {
598
+ key: usableSignal.key,
599
+ reason: usableSignal.reason,
600
+ ...(usableSignal.tag ? { tag: usableSignal.tag } : {}),
601
+ ...(usableSignal.tool ? { tool: usableSignal.tool } : {}),
602
+ ...(usableSignal.errorClass ? { errorClass: usableSignal.errorClass } : {}),
603
+ ...(usableSignal.source ? { source: usableSignal.source } : {}),
604
+ ...(usableSignal.callId !== undefined ? { callId: usableSignal.callId } : {}),
605
+ },
539
606
  }))
540
607
  }
541
608
 
@@ -755,6 +822,7 @@ export function apply(ctx , config = {}) {
755
822
  kind: 'evaluation', stage: 'searched', outcome, reasonCode,
756
823
  trigger: usableSignal?.reason ?? 'turn_start',
757
824
  ...(usableSignal !== undefined ? { phase: usableSignal.phase } : {}),
825
+ ...(usableSignal?.callId !== undefined ? { operationId: usableSignal.callId } : {}),
758
826
  ...(queryField !== undefined ? { query: queryField } : {}),
759
827
  candidates: recall.candidates,
760
828
  filter: {
@@ -785,7 +853,7 @@ export function apply(ctx , config = {}) {
785
853
  ...(recallScopes !== undefined ? { scopes: [...recallScopes] } : {}),
786
854
  limits: { topK: settings.recall.topK, maxQueryChars: settings.autoRecall.maxQueryChars },
787
855
  ...(usableSignal !== undefined
788
- ? { signal: { key: usableSignal.key, reason: usableSignal.reason, ...(usableSignal.errorClass ? { errorClass: usableSignal.errorClass } : {}), ...(usableSignal.tool ? { tool: usableSignal.tool } : {}), ...(usableSignal.tag ? { tag: usableSignal.tag } : {}), ...(usableSignal.source ? { source: usableSignal.source } : {}) } }
856
+ ? { signal: { key: usableSignal.key, reason: usableSignal.reason, ...(usableSignal.errorClass ? { errorClass: usableSignal.errorClass } : {}), ...(usableSignal.tool ? { tool: usableSignal.tool } : {}), ...(usableSignal.tag ? { tag: usableSignal.tag } : {}), ...(usableSignal.source ? { source: usableSignal.source } : {}), ...(usableSignal.callId ? { callId: usableSignal.callId } : {}) } }
789
857
  : {}),
790
858
  }))
791
859
  }
@@ -154,6 +154,12 @@
154
154
 
155
155
 
156
156
 
157
+
158
+
159
+                     
160
+                           
161
+                     
162
+
157
163
 
158
164
 
159
165
 
@@ -32,6 +32,8 @@
32
32
 
33
33
        
34
34
 
35
+                            
36
+
35
37
 
36
38
 
37
39
 
@@ -40,11 +42,15 @@
40
42
 
41
43
 
42
44
 
45
+          
46
+
43
47
 
44
48
 
45
49
 
46
50
 
47
51
 
52
+          
53
+
48
54
 
49
55
 
50
56
  const DEFAULT_MAX_QUERY = 240
@@ -196,6 +202,7 @@ export function highRiskSignal(tool , argumentsText , options
196
202
  tool,
197
203
  tag,
198
204
  source: 'tool',
205
+ ...(options.callId !== undefined ? { callId: options.callId } : {}),
199
206
  }
200
207
  }
201
208
  return undefined
@@ -334,6 +341,7 @@ export function failureSignal(
334
341
  ...(tool !== undefined ? { tool } : {}),
335
342
  errorClass,
336
343
  source: 'failure',
344
+ ...(options.callId !== undefined ? { callId: options.callId } : {}),
337
345
  }
338
346
  }
339
347
 
package/lib/panel.js CHANGED
@@ -355,8 +355,52 @@ function legacyAuditPage(memory, query) {
355
355
  }
356
356
  }
357
357
 
358
- function auditPage(memory, query) {
359
- if (memory === undefined || memory === null) {
358
+ /**
359
+ * 把一个审计条目的 turn/step 锚点解析成轨迹可直接聚焦的 tool call id。
360
+ *
361
+ * Trajectory 的深链只接受 callId(它的 `toolCallFocus` 就是同一性映射),所以
362
+ * 没有 operationId 的审计事件(摘要/规则等按步注入)需要回到会话事件里找该步
363
+ * 的第一个 `tool/call`。找不到工具调用时不伪造:返回 null,由客户端退化成
364
+ * “只切到轨迹页”。
365
+ *
366
+ * @param ctx - Host 插件上下文。
367
+ * @param query - `{ sessionId, turn?, step?, callId? }`。
368
+ * @returns 锚点结果(永不抛错)。
369
+ */
370
+ export function findTrajectoryAnchor(ctx, query) {
371
+ const sessionId = typeof query?.sessionId === 'string' ? query.sessionId.trim() : ''
372
+ if (sessionId === '') return { callId: null, reason: 'session_required' }
373
+ let session
374
+ try { session = ctx?.get?.('sessions')?.get?.(sessionId) } catch { session = undefined }
375
+ if (session === undefined || typeof session?.ownEvents !== 'function') {
376
+ return { callId: null, reason: 'session_unavailable' }
377
+ }
378
+ const turn = typeof query.turn === 'number' ? query.turn : undefined
379
+ const step = typeof query.step === 'number' ? query.step : undefined
380
+ // 已有 callId 时校验它确实属于这个会话,避免把跨会话/伪造 id 送进轨迹。
381
+ const wanted = typeof query.callId === 'string' && query.callId !== '' ? query.callId : undefined
382
+ try {
383
+ for (const event of session.ownEvents()) {
384
+ if (event?.type !== 'tool/call') continue
385
+ const data = event.data ?? {}
386
+ if (turn !== undefined && data.turn !== turn) continue
387
+ if (step !== undefined && data.step !== step) continue
388
+ const callId = typeof data.callId === 'string' ? data.callId : undefined
389
+ if (callId === undefined) continue
390
+ if (wanted !== undefined && callId !== wanted) continue
391
+ return {
392
+ callId,
393
+ tool: typeof data.name === 'string' ? data.name : undefined,
394
+ turn: typeof data.turn === 'number' ? data.turn : undefined,
395
+ step: typeof data.step === 'number' ? data.step : undefined,
396
+ reason: wanted !== undefined ? 'operation' : 'step_tool',
397
+ }
398
+ }
399
+ } catch { /* 事件窗口读取失败:按找不到处理 */ }
400
+ return { callId: null, reason: wanted !== undefined ? 'operation_not_found' : 'no_tool_in_step' }
401
+ }
402
+
403
+ function auditPage(memory, query) { if (memory === undefined || memory === null) {
360
404
  throw new ApiError(503, 'AUDIT_UNAVAILABLE', 'memory provider 未加载')
361
405
  }
362
406
  try {
@@ -446,6 +490,22 @@ async function handle(ctx, routePath, req, res) {
446
490
  writeJson(res, { ok: true, value: auditStats(memory) })
447
491
  return
448
492
  }
493
+ if (method === 'GET' && path === '/anchor') {
494
+ const numeric = (name) => {
495
+ const raw = url.searchParams.get(name)
496
+ if (raw === null || raw.trim() === '') return undefined
497
+ if (!/^-?\d+$/.test(raw.trim())) throw new ApiError(400, 'ANCHOR_QUERY_INVALID', `${name} 必须是整数`)
498
+ return Number(raw)
499
+ }
500
+ const query = {
501
+ sessionId: url.searchParams.get('session') ?? '',
502
+ turn: numeric('turn'),
503
+ step: numeric('step'),
504
+ callId: url.searchParams.get('callId') ?? undefined,
505
+ }
506
+ writeJson(res, { ok: true, value: findTrajectoryAnchor(ctx, query) })
507
+ return
508
+ }
449
509
  if (method === 'GET' && path === '/audit/export') {
450
510
  const query = parseAuditQuery(url)
451
511
  const format = url.searchParams.get('format') === 'jsonl' ? 'jsonl' : 'json'
@@ -1574,10 +1574,13 @@ export class LocalMemoryService {
1574
1574
  .slice(0, recallN)
1575
1575
 
1576
1576
  // --- channel 3: LLM rerank (optional; any skip/failure keeps recall order) ---
1577
- const finalScores = new Map (ranked.map((c) => [c.id, shape(c)]))
1577
+ // 键必须是 **record.id**。这里曾经写成 `c.id`(Cand 上没有 id 字段),所有候选都落到
1578
+ // 同一个 `undefined` 键上:排序数组本身是对的,但每条命中拿到的都是最后一个候选的
1579
+ // 分数(面板上表现为「每条相关度都一样」),重排的候选 id 也全成了 undefined。
1580
+ const finalScores = new Map (ranked.map((c) => [c.record.id, shape(c)]))
1578
1581
  if (this.cfg.llm.enabled && this.llmInvoke && ranked.length >= 2) {
1579
- const asCands = ranked.map((c) => ({ id: c.id, content: c.record.content, recallScore: finalScores.get(c.id) }))
1580
- const cacheKey = RerankCache.key(query.text, ranked.map((c) => c.id), this.cfg.llm.model)
1582
+ const asCands = ranked.map((c) => ({ id: c.record.id, content: c.record.content, recallScore: finalScores.get(c.record.id) }))
1583
+ const cacheKey = RerankCache.key(query.text, ranked.map((c) => c.record.id), this.cfg.llm.model)
1581
1584
  let outcome = this.rerankCache.get(cacheKey)
1582
1585
  if (!outcome) {
1583
1586
  outcome = await rerank({
@@ -1595,11 +1598,16 @@ export class LocalMemoryService {
1595
1598
  finalScores.set(id, score)
1596
1599
  }
1597
1600
  }
1601
+ // 重排必须能改变顺序,否则它只改了显示分数、召回序列原样输出。没有重排时
1602
+ // finalScores 就等于 shape(),这个二次排序与原顺序完全一致(同一套 tie-break)。
1603
+ ranked.sort((a, b) => finalScores.get(b.record.id) - finalScores.get(a.record.id)
1604
+ || scopeTier(a.record.scope) - scopeTier(b.record.scope)
1605
+ || a.record.id.localeCompare(b.record.id))
1598
1606
  }
1599
1607
 
1600
1608
  const hits = ranked.map((c) => ({
1601
1609
  record: internal.touch === false ? c.record : touch(c.record),
1602
- score: round4(finalScores.get(c.id) ),
1610
+ score: round4(finalScores.get(c.record.id) ),
1603
1611
  }))
1604
1612
 
1605
1613
  this.store.scheduleFlush()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.13.1",
3
+ "version": "0.14.0",
4
4
  "description": "DeepSeek Harness 记忆系统(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 五个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",