@restregular/dsh-memory 0.13.2 → 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,14 @@
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
+
5
13
  ## 0.13.2 — 修复检索分数全部相同
6
14
 
7
15
  - **根因**:`search()` 组装最终分数时写成了 `c.id`,而候选对象只有 `c.record`,于是所有候选都落到
package/README.md CHANGED
@@ -365,10 +365,23 @@ GET /memory/api/audit
365
365
 
366
366
  GET /memory/api/audit/stats
367
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>
368
370
  ```
369
371
 
370
372
  响应为 `{ ok: true, value: { entries, total, nextCursor?, stats, query } }`。旧调用 `GET /audit?session=<id>` 仍兼容;不带 `session` 时查询全部会话,`query.scope` 会标记为 `all`。
371
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
+
372
385
  审计数据默认**只在内存**:容量 2000 条、每会话 200 条,超出时优先保留 digest / rules / delivery / error 等关键通道;`stats` 暴露 `entries / capacity / dropped / writeErrors / persistence`。重启后记录丢失,面板会明确提示。
373
386
 
374
387
  写入前所有自由文本都经过统一 sanitizer:先限制扫描长度(4000 字符),再做凭据模式脱敏,最后截到 200 字;只保存 ID、计数、枚举原因、字符数和短 hash,不保存记忆正文、原始工具参数、异常堆栈。模式脱敏是保守匹配,不承诺覆盖所有秘密形状。
package/lib/client.js CHANGED
@@ -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('')
@@ -2060,6 +2080,230 @@ window.__ModuleLoader__.load({
2060
2080
  )
2061
2081
  }
2062
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
+
2063
2307
  // ===== 审计标签页 =====
2064
2308
  const AUDIT_CHANNEL_META = {
2065
2309
  digest: '摘要', recall: '召回', rules: '规则', rules_delta: '规则增量',
@@ -2121,6 +2365,7 @@ window.__ModuleLoader__.load({
2121
2365
  return `${meta.label}${meta.detail}${entry.delivery && entry.delivery.textChars ? ` · ${entry.delivery.textChars} 字符` : ''}`
2122
2366
  }
2123
2367
  if (entry.kind === 'signal') {
2368
+ if (entry.stage === 'tool_call') return `记忆工具调用${entry.signal && entry.signal.tool ? ` · ${entry.signal.tool}` : ''}`
2124
2369
  const stage = entry.stage === 'signal_consumed' ? '信号已消费' : entry.stage === 'signal_dropped' ? '信号被丢弃' : '信号已排队'
2125
2370
  return `${stage}${entry.signal && entry.signal.reason ? ` · ${entry.signal.reason}` : ''}`
2126
2371
  }
@@ -2165,7 +2410,16 @@ window.__ModuleLoader__.load({
2165
2410
  tag_mismatch: '标签不匹配', dedup: '去重', excluded: '被排除', skipped: '跳过',
2166
2411
  }
2167
2412
 
2168
- 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
+ }) {
2169
2423
  const [entries, setEntries] = React.useState([])
2170
2424
  const [stats, setStats] = React.useState(null)
2171
2425
  const [total, setTotal] = React.useState(0)
@@ -2176,10 +2430,12 @@ window.__ModuleLoader__.load({
2176
2430
  const [error, setError] = React.useState('')
2177
2431
  const [copyNotice, setCopyNotice] = React.useState('')
2178
2432
  const [exportNotice, setExportNotice] = React.useState('')
2433
+ const [focusNotice, setFocusNotice] = React.useState('')
2434
+ const [focusBusy, setFocusBusy] = React.useState(false)
2179
2435
  const [autoRefresh, setAutoRefresh] = React.useState(true)
2180
2436
  const [refreshMs, setRefreshMs] = React.useState(500)
2181
2437
  const loadingRef = React.useRef(false)
2182
- const [session, setSession] = React.useState(readAuditSession())
2438
+ const [session, setSession] = React.useState(lockSession || readAuditSession())
2183
2439
  const [channel, setChannel] = React.useState('')
2184
2440
  const [outcome, setOutcome] = React.useState('')
2185
2441
  const [trigger, setTrigger] = React.useState('')
@@ -2194,10 +2450,11 @@ window.__ModuleLoader__.load({
2194
2450
  const [recordCache, setRecordCache] = React.useState({})
2195
2451
  const tipTimer = React.useRef(null)
2196
2452
  const hideTimer = React.useRef(null)
2453
+ const effectiveSession = lockSession || session
2197
2454
 
2198
2455
  function queryParams(cursorValue) {
2199
2456
  const params = new URLSearchParams()
2200
- if (session) params.set('session', session)
2457
+ if (effectiveSession) params.set('session', effectiveSession)
2201
2458
  if (channel) params.set('channel', channel)
2202
2459
  if (outcome) params.set('outcome', outcome)
2203
2460
  if (trigger.trim()) params.set('trigger', trigger.trim())
@@ -2245,6 +2502,38 @@ window.__ModuleLoader__.load({
2245
2502
 
2246
2503
  React.useEffect(() => { load('', []) }, [reloadTick])
2247
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
+
2248
2537
  // 自动刷新:默认 500ms,可关;页面隐藏时跳过,避免后台无意义轮询。
2249
2538
  React.useEffect(() => {
2250
2539
  if (!autoRefresh) return undefined
@@ -2253,7 +2542,7 @@ window.__ModuleLoader__.load({
2253
2542
  load(cursor, cursorStack, { silent: true })
2254
2543
  }, refreshMs)
2255
2544
  return () => clearInterval(timer)
2256
- }, [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])
2257
2546
 
2258
2547
  const resetAndReload = () => { setCursor(''); setCursorStack([]); setReloadTick((n) => n + 1) }
2259
2548
  const selected = selectedId === null ? null : entries.find((entry) => entry.id === selectedId) || null
@@ -2358,8 +2647,8 @@ window.__ModuleLoader__.load({
2358
2647
  value: scope.scope.slice(8),
2359
2648
  label: scope.label || `会话 ${scope.scope.slice(8, 16)}`,
2360
2649
  })))
2361
- if (session && !sessionOptions.some((item) => item.value === session)) {
2362
- 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)}` })
2363
2652
  }
2364
2653
  const channelOptions = [{ value: '', label: '全部通道' }].concat(Object.keys(AUDIT_CHANNEL_META).map((key) => ({ value: key, label: AUDIT_CHANNEL_META[key] })))
2365
2654
  const outcomeOptions = [{ value: '', label: '全部结果' }].concat(Object.keys(AUDIT_OUTCOME_META).map((key) => ({ value: key, label: AUDIT_OUTCOME_META[key].label })))
@@ -2396,13 +2685,15 @@ window.__ModuleLoader__.load({
2396
2685
  banner.push(h('div', { className: 'audit-banner bad', key: 'err' }, `审计写入失败 ${writeErrors} 次;面板数据可能不完整。`))
2397
2686
  }
2398
2687
 
2399
- const filterActive = Boolean(session || channel || outcome || trigger || search || problem || range)
2688
+ const filterActive = Boolean(effectiveSession || channel || outcome || trigger || search || problem || range)
2400
2689
  const toolbar = h('div', { className: 'audit-toolbar' },
2401
2690
  h('div', { className: 'audit-filter-row' },
2402
- h(Dropdown, {
2403
- items: sessionOptions, value: session, disabled: loading,
2404
- onChange: (next) => { setSession(next); writeAuditSession(next); resetAndReload() },
2405
- }),
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
+ }),
2406
2697
  h(Dropdown, {
2407
2698
  items: channelOptions, value: channel, disabled: loading,
2408
2699
  onChange: (next) => { setChannel(next); resetAndReload() },
@@ -2462,7 +2753,7 @@ window.__ModuleLoader__.load({
2462
2753
  : null,
2463
2754
  filterActive
2464
2755
  ? h('button', { className: 'linkbtn', onClick: () => {
2465
- 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()
2466
2757
  } }, '清空筛选')
2467
2758
  : null,
2468
2759
  h('span', { className: 'spacer' }),
@@ -2544,15 +2835,48 @@ window.__ModuleLoader__.load({
2544
2835
  onClick: () => openSessionId(selected.sessionId),
2545
2836
  }, selected.sessionId))]
2546
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
+ }
2547
2862
  const json = JSON.stringify(selected, null, 2)
2548
2863
  return h('div', { className: 'audit-detail' },
2549
2864
  h('div', { className: 'audit-detail-head' },
2550
2865
  h('b', null, auditSummaryLine(selected)),
2551
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,
2552
2875
  h('button', { className: 'linkbtn', onClick: () => copyAuditText(selected.id, setCopyNotice) }, '复制 ID'),
2553
2876
  copyNotice ? h('span', { className: 'audit-inline-note' }, copyNotice) : null,
2554
2877
  h('button', { className: 'audit-close', title: '关闭', onClick: () => { setSelectedId(null); setCopyNotice('') } }, '×'),
2555
2878
  ),
2879
+ focusNotice ? h('div', { className: 'audit-jump-note' }, focusNotice) : null,
2556
2880
  h('div', { className: 'audit-kv' },
2557
2881
  kv('事件', selected.id),
2558
2882
  kv('序号', selected.seq),
@@ -2560,6 +2884,7 @@ window.__ModuleLoader__.load({
2560
2884
  kv('schema', selected.schemaVersion || '旧版'),
2561
2885
  sessionNode,
2562
2886
  kv('step', selected.step),
2887
+ kv('轨迹锚点', jumpTarget),
2563
2888
  kv('通道', `${auditChannelLabel(selected.channel)} / ${selected.kind}`),
2564
2889
  kv('阶段', selected.stage),
2565
2890
  kv('触发', selected.trigger),
@@ -2745,7 +3070,7 @@ window.__ModuleLoader__.load({
2745
3070
  /** 待嵌入自动刷新:最多 300 次 × 1.5s(后端挂着时不无限轮询)。 */
2746
3071
  const PENDING_POLL_LIMIT = 300
2747
3072
 
2748
- function MemoryPanel({ openSession, sessionInfo } = {}) {
3073
+ function MemoryPanel({ openSession, sessionInfo, openTrajectory, audience = 'panel', lockSession } = {}) {
2749
3074
  const [records, setRecords] = React.useState([])
2750
3075
  const [scopes, setScopes] = React.useState([])
2751
3076
  const [embedServer, setEmbedServer] = React.useState(null)
@@ -2766,6 +3091,21 @@ window.__ModuleLoader__.load({
2766
3091
  const [pendingTick, setPendingTick] = React.useState(0)
2767
3092
  const [creating, setCreating] = React.useState(false)
2768
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
+
2769
3109
  const load = async (query, scopeF, semanticF) => {
2770
3110
  setLoading(true); setError('')
2771
3111
  try {
@@ -3210,18 +3550,176 @@ window.__ModuleLoader__.load({
3210
3550
  : tab === 'tree'
3211
3551
  ? treeBody
3212
3552
  : tab === 'audit'
3213
- ? 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
+ })
3214
3563
  : overviewBody,
3215
3564
  )
3216
3565
  }
3217
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
+
3218
3716
  const inject = ['slots']
3219
3717
 
3220
3718
  /** 侧栏入口打开的主界面页面(整块可滚动,内容就是面板本体)。 */
3221
- function MemoryPage({ openSession, sessionInfo } = {}) {
3719
+ function MemoryPage({ openSession, sessionInfo, openTrajectory } = {}) {
3222
3720
  return h('div', { className: 'mem-page' },
3223
3721
  h('div', { className: 'mem-page-head' }, h('h2', null, '记忆系统')),
3224
- h(MemoryPanel, { openSession, sessionInfo }),
3722
+ h(MemoryPanel, { openSession, sessionInfo, openTrajectory, audience: 'panel' }),
3225
3723
  )
3226
3724
  }
3227
3725
 
@@ -3264,6 +3762,7 @@ window.__ModuleLoader__.load({
3264
3762
 
3265
3763
  const slots = ctx.get('slots')
3266
3764
  if (slots === undefined) return
3765
+ clientCtx = ctx
3267
3766
 
3268
3767
  /** 宿主 uiWorkspace 服务:打开会话 / 读取会话摘要(旧宿主缺失时静默降级)。 */
3269
3768
  const workspaceService = () => {
@@ -3297,7 +3796,12 @@ window.__ModuleLoader__.load({
3297
3796
 
3298
3797
  slots.inject('settings.section', () => slots.register(
3299
3798
  { name: 'settings.section', id: 'memory', order: 24, label: NAV_LABEL },
3300
- () => React.createElement(MemoryPanel, { openSession, sessionInfo }),
3799
+ () => React.createElement(MemoryPanel, {
3800
+ openSession,
3801
+ sessionInfo,
3802
+ audience: 'panel',
3803
+ openTrajectory: jumpAuditEntryToTrajectory,
3804
+ }),
3301
3805
  ))
3302
3806
 
3303
3807
  // 侧栏入口(可选):开启后在左侧栏「插件」下方多一个「记忆系统」,点击在主界面打开面板。
@@ -3316,7 +3820,11 @@ window.__ModuleLoader__.load({
3316
3820
  }
3317
3821
  try {
3318
3822
  sidebarDisposers = [
3319
- 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
+ }))),
3320
3828
  slots.inject('sidebar.panellist', () => slots.register(
3321
3829
  { name: 'sidebar.panellist', id: 'memory', order: 20, label: () => NAV_LABEL },
3322
3830
  () => React.createElement(NavLineIcon),
@@ -3333,6 +3841,41 @@ window.__ModuleLoader__.load({
3333
3841
  window.addEventListener('dsh-memory:settings', syncSidebar)
3334
3842
  ctx.effect(() => () => window.removeEventListener('dsh-memory:settings', syncSidebar), 'dsh-memory: sidebar entry')
3335
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
+ }
3336
3879
  } catch (error) {
3337
3880
  console.error('[dsh-memory] client apply 失败(已吞掉):', error?.message)
3338
3881
  }
@@ -3458,6 +4001,17 @@ window.__ModuleLoader__.load({
3458
4001
  NavLineIcon: NavLineIcon,
3459
4002
  NAV_DOM: NAV_DOM,
3460
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 },
3461
4015
  }
3462
4016
  return module.exports
3463
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'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.13.2",
3
+ "version": "0.14.0",
4
4
  "description": "DeepSeek Harness 记忆系统(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 五个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",