@restregular/dsh-memory 0.11.0 → 0.12.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/lib/client.js CHANGED
@@ -334,6 +334,61 @@ window.__ModuleLoader__.load({
334
334
  '.memp .td-rel-dir{flex:none;color:color-mix(in srgb,#D9A441 62%,var(--dsw-alias-label-primary));font-weight:600}',
335
335
  '.memp .td-rel-text{color:var(--dsw-alias-label-secondary);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;word-break:break-word}',
336
336
  '@media (max-width:620px){.memp .tree-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.memp .tree-toolbar input[type=text]{max-width:none}}',
337
+ // ===== 审计 =====
338
+ '.memp .audit{display:flex;flex-direction:column;gap:12px;min-height:0}',
339
+ '.memp .audit-head{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap}',
340
+ '.memp .audit-title{font-size:16px;font-weight:650;line-height:1.35}',
341
+ '.memp .audit-sub{font-size:11.5px;color:var(--dsw-alias-label-secondary);line-height:1.55;margin-top:2px}',
342
+ '.memp .audit-mode{margin-left:auto;display:flex;gap:6px;align-items:center;flex-wrap:wrap}',
343
+ '.memp .audit-banner{border:1px solid color-mix(in srgb,#D9A441 42%,var(--dsw-alias-border-l1));background:color-mix(in srgb,#D9A441 9%,transparent);border-radius:9px;padding:7px 10px;font-size:11.5px;line-height:1.55;color:var(--dsw-alias-label-secondary)}',
344
+ '.memp .audit-banner.bad{border-color:color-mix(in srgb,var(--dsw-alias-label-danger, #e05555) 45%,var(--dsw-alias-border-l1));background:color-mix(in srgb,var(--dsw-alias-label-danger, #e05555) 8%,transparent)}',
345
+ '.memp .audit-stats{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px}',
346
+ '.memp .audit-stat{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);padding:7px 10px;min-width:0}',
347
+ '.memp .audit-stat b{display:block;font-size:17px;line-height:1.3;font-weight:650;font-variant-numeric:tabular-nums}',
348
+ '.memp .audit-stat span{display:block;font-size:10.5px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
349
+ '.memp .audit-toolbar{display:flex;gap:6px;align-items:center;flex-wrap:wrap;padding:8px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}',
350
+ '.memp .audit-toolbar input[type=text]{min-width:150px;max-width:230px;padding:4px 8px}',
351
+ '.memp .audit-toolbar .dropbtn{padding:4px 9px}',
352
+ '.memp .audit-toolbar label{display:inline-flex;align-items:center;gap:5px;font-size:11.5px;color:var(--dsw-alias-label-secondary);white-space:nowrap}',
353
+ '.memp .audit-toolbar input[type=checkbox]{accent-color:var(--dsw-alias-brand-primary)}',
354
+ '.memp .audit-split{display:grid;grid-template-columns:minmax(0,1fr);gap:10px;min-height:0}',
355
+ '.memp .audit-split.has-detail{grid-template-columns:minmax(0,1fr) minmax(300px,360px)}',
356
+ '.memp .audit-list{display:flex;flex-direction:column;gap:5px;min-width:0}',
357
+ '.memp .audit-row{display:grid;grid-template-columns:64px 116px minmax(90px,1fr) 92px 104px 84px 74px;gap:8px;align-items:center;border:1px solid var(--dsw-alias-border-l1);border-radius:9px;background:var(--dsw-alias-bg-layer-1);padding:6px 9px;font-size:11.5px;cursor:pointer;text-align:left;color:inherit;width:100%}',
358
+ '.memp .audit-row:hover{border-color:var(--dsw-alias-brand-primary)}',
359
+ '.memp .audit-row.on{border-color:var(--dsw-alias-brand-primary);background:color-mix(in srgb,var(--dsw-alias-brand-primary) 6%,var(--dsw-alias-bg-layer-1))}',
360
+ '.memp .audit-row .m{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
361
+ '.memp .audit-row .t{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:10.5px;color:var(--dsw-alias-label-secondary)}',
362
+ '.memp .audit-row .ch{font-weight:600}',
363
+ '.memp .audit-row .trig{color:var(--dsw-alias-label-secondary);font-size:10.5px}',
364
+ '.memp .audit-row .nums{font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary)}',
365
+ '.memp .audit-row .del{font-size:10.5px}',
366
+ '.memp .audit-pill{display:inline-flex;align-items:center;gap:4px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);padding:0 6px;line-height:1.65;font-size:10px;white-space:nowrap;max-width:100%}',
367
+ '.memp .audit-pill.ok{color:color-mix(in srgb,#2E9B68 78%,var(--dsw-alias-label-primary));border-color:color-mix(in srgb,#2E9B68 38%,var(--dsw-alias-border-l1))}',
368
+ '.memp .audit-pill.warn{color:color-mix(in srgb,#D9A441 82%,var(--dsw-alias-label-primary));border-color:color-mix(in srgb,#D9A441 42%,var(--dsw-alias-border-l1))}',
369
+ '.memp .audit-pill.bad{color:var(--dsw-alias-label-danger, #e05555);border-color:color-mix(in srgb,var(--dsw-alias-label-danger, #e05555) 42%,var(--dsw-alias-border-l1))}',
370
+ '.memp .audit-pill.mute{color:var(--dsw-alias-label-secondary)}',
371
+ '.memp .audit-empty{border:1px dashed var(--dsw-alias-border-l1);border-radius:10px;padding:26px 16px;text-align:center;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.65}',
372
+ '.memp .audit-detail{border:1px solid var(--dsw-alias-border-l1);border-radius:11px;background:var(--dsw-alias-bg-layer-1);padding:10px 11px;display:flex;flex-direction:column;gap:9px;max-height:min(560px,68vh);overflow:auto;scrollbar-width:thin}',
373
+ '.memp .audit-detail-head{display:flex;gap:7px;align-items:center}',
374
+ '.memp .audit-detail-head b{font-size:12.5px}',
375
+ '.memp .audit-detail-head .spacer{flex:1}',
376
+ '.memp .audit-close{background:none;border:0;padding:0 4px;font-size:15px;line-height:1;color:var(--dsw-alias-label-secondary)}',
377
+ '.memp .audit-kv{display:grid;grid-template-columns:74px minmax(0,1fr);gap:4px 8px;font-size:11px;line-height:1.5}',
378
+ '.memp .audit-kv .k{color:var(--dsw-alias-label-secondary)}',
379
+ '.memp .audit-kv .v{min-width:0;overflow-wrap:anywhere}',
380
+ '.memp .audit-sec{border-top:1px solid var(--dsw-alias-border-l1);padding-top:8px;display:flex;flex-direction:column;gap:5px}',
381
+ '.memp .audit-sec-title{font-size:10.5px;letter-spacing:.04em;color:var(--dsw-alias-label-secondary)}',
382
+ '.memp .audit-budget{display:grid;grid-template-columns:64px minmax(0,1fr) 92px;gap:7px;align-items:center;font-size:10.5px;color:var(--dsw-alias-label-secondary)}',
383
+ '.memp .audit-budget .bar{height:5px;border-radius:999px;background:var(--dsw-alias-bg-layer-2);overflow:hidden}',
384
+ '.memp .audit-budget .bar i{display:block;height:100%;border-radius:999px;background:var(--dsw-alias-brand-primary)}',
385
+ '.memp .audit-budget .bar i.over{background:var(--dsw-alias-label-danger, #e05555)}',
386
+ '.memp .audit-budget .num{text-align:right;font-variant-numeric:tabular-nums}',
387
+ '.memp .audit-json{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:10px;line-height:1.45;white-space:pre-wrap;word-break:break-word;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:7px;max-height:220px;overflow:auto}',
388
+ '.memp .audit-pager{display:flex;gap:6px;align-items:center;justify-content:flex-end;font-size:11px;color:var(--dsw-alias-label-secondary)}',
389
+ '.memp .audit-flat{display:flex;flex-wrap:wrap;gap:4px}',
390
+ '@media (max-width:900px){.memp .audit-split.has-detail{grid-template-columns:minmax(0,1fr)}.memp .audit-row{grid-template-columns:54px 100px minmax(80px,1fr) 70px 84px}}',
391
+ '@media (max-width:620px){.memp .audit-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.memp .audit-row{grid-template-columns:minmax(0,1fr) auto;gap:4px 8px}.memp .audit-row .sec{display:none}.memp .audit-toolbar input[type=text]{max-width:none;flex:1}}',
337
392
  ].join('')
338
393
 
339
394
  async function api(method, body) {
@@ -1947,6 +2002,427 @@ window.__ModuleLoader__.load({
1947
2002
  )
1948
2003
  }
1949
2004
 
2005
+ // ===== 审计标签页 =====
2006
+ const AUDIT_CHANNEL_META = {
2007
+ digest: '摘要', recall: '召回', rules: '规则', rules_delta: '规则增量',
2008
+ policy: '策略', nudge: '提醒', signal: '信号', lifecycle: '生命周期',
2009
+ }
2010
+ const AUDIT_OUTCOME_META = {
2011
+ success: { label: '成功', tone: 'ok' },
2012
+ failed: { label: '失败', tone: 'bad' },
2013
+ skipped: { label: '跳过', tone: 'mute' },
2014
+ partial: { label: '部分', tone: 'warn' },
2015
+ unknown: { label: '未知', tone: 'mute' },
2016
+ }
2017
+ const AUDIT_DELIVERY_META = {
2018
+ appended: { label: '已投递', tone: 'ok' },
2019
+ suppressed: { label: '被抑制', tone: 'warn' },
2020
+ rejected: { label: '被拒绝', tone: 'bad' },
2021
+ not_attempted: { label: '未尝试', tone: 'mute' },
2022
+ unknown: { label: '未确认', tone: 'mute' },
2023
+ }
2024
+
2025
+ function readAuditSession() {
2026
+ try { return window.localStorage.getItem('dsh-memory:audit-session') || '' } catch { return '' }
2027
+ }
2028
+ function writeAuditSession(value) {
2029
+ try {
2030
+ if (value) window.localStorage.setItem('dsh-memory:audit-session', value)
2031
+ else window.localStorage.removeItem('dsh-memory:audit-session')
2032
+ } catch { /* 隐私模式等 */ }
2033
+ }
2034
+ function auditChannelLabel(channel) {
2035
+ return AUDIT_CHANNEL_META[channel] || String(channel || '未知')
2036
+ }
2037
+ function auditOutcomeMeta(outcome) {
2038
+ return AUDIT_OUTCOME_META[outcome] || { label: String(outcome || '未知'), tone: 'mute' }
2039
+ }
2040
+ function auditDeliveryMeta(entry) {
2041
+ const delivery = entry && entry.delivery
2042
+ if (!delivery || !delivery.status) return { label: '未记录', tone: 'mute', detail: '' }
2043
+ let meta = AUDIT_DELIVERY_META[delivery.status] || { label: String(delivery.status), tone: 'mute' }
2044
+ if (delivery.status === 'unknown' && entry.reasonCode === 'prepared') {
2045
+ meta = { label: '已准备(投递未确认)', tone: 'warn' }
2046
+ }
2047
+ const reason = delivery.suppressedBy ? `(${delivery.suppressedBy})` : ''
2048
+ return { ...meta, detail: reason }
2049
+ }
2050
+ function auditPill(text, tone, title) {
2051
+ return h('span', { className: `audit-pill ${tone || 'mute'}`, ...(title ? { title } : {}) }, text)
2052
+ }
2053
+ function auditBudgetOf(entry) {
2054
+ const budgets = entry && entry.budgets ? entry.budgets : null
2055
+ if (!budgets) return null
2056
+ const name = Object.keys(budgets)[0]
2057
+ return name ? { name, ...budgets[name] } : null
2058
+ }
2059
+ function auditSummaryLine(entry) {
2060
+ if (!entry) return ''
2061
+ if (entry.kind === 'delivery') {
2062
+ const meta = auditDeliveryMeta(entry)
2063
+ return `${meta.label}${meta.detail}${entry.delivery && entry.delivery.textChars ? ` · ${entry.delivery.textChars} 字符` : ''}`
2064
+ }
2065
+ if (entry.kind === 'signal') {
2066
+ const stage = entry.stage === 'signal_consumed' ? '信号已消费' : entry.stage === 'signal_dropped' ? '信号被丢弃' : '信号已排队'
2067
+ return `${stage}${entry.signal && entry.signal.reason ? ` · ${entry.signal.reason}` : ''}`
2068
+ }
2069
+ if (entry.error) return `失败:${entry.error.code}(${entry.error.stage})`
2070
+ if (entry.reasonCode === 'no_candidates') return '没有候选'
2071
+ if (entry.reasonCode === 'all_omitted') return '候选全部被省略'
2072
+ if (entry.reasonCode === 'deduped') return '全部命中已注入去重'
2073
+ if (entry.reasonCode === 'retrieval_failed') return '检索失败'
2074
+ if (entry.selected && entry.selected.count > 0) return `选中 ${entry.selected.count} 条`
2075
+ return entry.reasonCode || '—'
2076
+ }
2077
+ async function copyAuditText(text, setNotice) {
2078
+ try {
2079
+ if (navigator?.clipboard?.writeText) {
2080
+ await navigator.clipboard.writeText(text)
2081
+ setNotice('已复制')
2082
+ return
2083
+ }
2084
+ } catch { /* fallthrough */ }
2085
+ setNotice('复制失败:浏览器不允许访问剪贴板')
2086
+ }
2087
+
2088
+ /**
2089
+ * 独立“审计”标签页:事件流 + 详情 + 健康状态。
2090
+ *
2091
+ * 数据全部来自 /memory/api/audit;没有数据就显示真实空状态,不补造。
2092
+ * 展示口径:evaluation 的“选中”不等于投递;投递看 delivery 事件的 status。
2093
+ */
2094
+ function AuditTab({ scopes }) {
2095
+ const [entries, setEntries] = React.useState([])
2096
+ const [stats, setStats] = React.useState(null)
2097
+ const [total, setTotal] = React.useState(0)
2098
+ const [nextCursor, setNextCursor] = React.useState(null)
2099
+ const [cursorStack, setCursorStack] = React.useState([])
2100
+ const [cursor, setCursor] = React.useState('')
2101
+ const [loading, setLoading] = React.useState(true)
2102
+ const [error, setError] = React.useState('')
2103
+ const [notice, setNotice] = React.useState('')
2104
+ const [session, setSession] = React.useState(readAuditSession())
2105
+ const [channel, setChannel] = React.useState('')
2106
+ const [outcome, setOutcome] = React.useState('')
2107
+ const [trigger, setTrigger] = React.useState('')
2108
+ const [search, setSearch] = React.useState('')
2109
+ const [problem, setProblem] = React.useState(false)
2110
+ const [since, setSince] = React.useState('')
2111
+ const [until, setUntil] = React.useState('')
2112
+ const [selectedId, setSelectedId] = React.useState(null)
2113
+ const [reloadTick, setReloadTick] = React.useState(0)
2114
+
2115
+ function queryParams(cursorValue) {
2116
+ const params = new URLSearchParams()
2117
+ if (session) params.set('session', session)
2118
+ if (channel) params.set('channel', channel)
2119
+ if (outcome) params.set('outcome', outcome)
2120
+ if (trigger.trim()) params.set('trigger', trigger.trim())
2121
+ const needle = search.trim()
2122
+ if (needle) {
2123
+ if (needle.startsWith('trace:')) params.set('trace', needle.slice(6).trim())
2124
+ else if (needle.startsWith('op:')) params.set('operation', needle.slice(3).trim())
2125
+ else params.set('memory', needle)
2126
+ }
2127
+ if (problem) params.set('problem', '1')
2128
+ if (since) params.set('since', String(new Date(`${since}T00:00:00`).getTime()))
2129
+ if (until) params.set('until', String(new Date(`${until}T23:59:59.999`).getTime()))
2130
+ if (cursorValue) params.set('cursor', cursorValue)
2131
+ params.set('limit', '50')
2132
+ return params
2133
+ }
2134
+
2135
+ async function load(cursorValue, stack) {
2136
+ setLoading(true); setError(''); setNotice('')
2137
+ try {
2138
+ const value = await api(`audit?${queryParams(cursorValue)}`)
2139
+ const list = Array.isArray(value.entries) ? value.entries : []
2140
+ setEntries(list)
2141
+ setStats(value.stats || null)
2142
+ setTotal(typeof value.total === 'number' ? value.total : list.length)
2143
+ setNextCursor(typeof value.nextCursor === 'string' ? value.nextCursor : null)
2144
+ setCursor(cursorValue || '')
2145
+ if (stack !== undefined) setCursorStack(stack)
2146
+ if (selectedId !== null && !list.some((entry) => entry.id === selectedId)) setSelectedId(null)
2147
+ } catch (e) {
2148
+ setError(String(e.message || e))
2149
+ setEntries([])
2150
+ }
2151
+ setLoading(false)
2152
+ }
2153
+
2154
+ React.useEffect(() => { load('', []) }, [reloadTick])
2155
+
2156
+ const resetAndReload = () => { setCursor(''); setCursorStack([]); setReloadTick((n) => n + 1) }
2157
+ const selected = selectedId === null ? null : entries.find((entry) => entry.id === selectedId) || null
2158
+ const prepared = entries.filter((entry) => entry.delivery && entry.delivery.status === 'unknown' && entry.reasonCode === 'prepared').length
2159
+ const suppressed = entries.filter((entry) => entry.delivery && (entry.delivery.status === 'suppressed' || entry.delivery.status === 'not_attempted')).length
2160
+ const failed = entries.filter((entry) => entry.outcome === 'failed').length
2161
+ const persistence = stats && stats.persistence ? stats.persistence : 'memory'
2162
+ const capacity = stats && typeof stats.capacity === 'number' ? stats.capacity : null
2163
+ const dropped = stats && typeof stats.dropped === 'number' ? stats.dropped : 0
2164
+ const writeErrors = stats && typeof stats.writeErrors === 'number' ? stats.writeErrors : 0
2165
+ const sessionOptions = [{ value: '', label: '全部会话(显式)' }]
2166
+ .concat((scopes || []).filter((scope) => scope.scope?.startsWith('session:')).map((scope) => ({
2167
+ value: scope.scope.slice(8),
2168
+ label: scope.label || `会话 ${scope.scope.slice(8, 16)}`,
2169
+ })))
2170
+ const channelOptions = [{ value: '', label: '全部通道' }].concat(Object.keys(AUDIT_CHANNEL_META).map((key) => ({ value: key, label: AUDIT_CHANNEL_META[key] })))
2171
+ const outcomeOptions = [{ value: '', label: '全部结果' }].concat(Object.keys(AUDIT_OUTCOME_META).map((key) => ({ value: key, label: AUDIT_OUTCOME_META[key].label })))
2172
+
2173
+ const exportAudit = async (format) => {
2174
+ setNotice('')
2175
+ try {
2176
+ const res = await fetch(`${API}/audit/export?${queryParams('')}&format=${format}`)
2177
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
2178
+ const blob = await res.blob()
2179
+ const url = URL.createObjectURL(blob)
2180
+ const link = document.createElement('a')
2181
+ link.href = url
2182
+ link.download = `dsh-memory-audit.${format}`
2183
+ link.click()
2184
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
2185
+ setNotice(`已导出当前筛选(${format.toUpperCase()})。`)
2186
+ } catch (e) {
2187
+ setNotice(`导出失败:${String(e.message || e)}`)
2188
+ }
2189
+ }
2190
+
2191
+ const banner = []
2192
+ if (persistence === 'memory') {
2193
+ banner.push(h('div', { className: 'audit-banner', key: 'mem' },
2194
+ `内存模式:重启后记录不会保留${capacity === null ? '' : `;当前容量 ${capacity} 条`}${dropped > 0 ? `,已有 ${dropped} 条被容量策略丢弃` : ''}。`))
2195
+ } else if (persistence === 'degraded') {
2196
+ banner.push(h('div', { className: 'audit-banner bad', key: 'deg' }, '审计存储处于降级状态:部分记录可能缺失。'))
2197
+ }
2198
+ if (writeErrors > 0) {
2199
+ banner.push(h('div', { className: 'audit-banner bad', key: 'err' }, `审计写入失败 ${writeErrors} 次;面板数据可能不完整。`))
2200
+ }
2201
+
2202
+ const toolbar = h('div', { className: 'audit-toolbar' },
2203
+ h(Dropdown, {
2204
+ items: sessionOptions, value: session, disabled: loading,
2205
+ onChange: (next) => { setSession(next); writeAuditSession(next); resetAndReload() },
2206
+ }),
2207
+ h(Dropdown, {
2208
+ items: channelOptions, value: channel, disabled: loading,
2209
+ onChange: (next) => { setChannel(next); resetAndReload() },
2210
+ }),
2211
+ h(Dropdown, {
2212
+ items: outcomeOptions, value: outcome, disabled: loading,
2213
+ onChange: (next) => { setOutcome(next); resetAndReload() },
2214
+ }),
2215
+ h('input', {
2216
+ type: 'text', placeholder: '触发源 / memory ID / trace:', value: trigger,
2217
+ onChange: (e) => setTrigger(e.target.value),
2218
+ onKeyDown: (e) => { if (e.key === 'Enter') resetAndReload() },
2219
+ }),
2220
+ h('input', {
2221
+ type: 'text', placeholder: '搜索 memory / trace: / op:', value: search,
2222
+ onChange: (e) => setSearch(e.target.value),
2223
+ onKeyDown: (e) => { if (e.key === 'Enter') resetAndReload() },
2224
+ }),
2225
+ h('label', null,
2226
+ h('input', { type: 'checkbox', checked: problem, onChange: (e) => { setProblem(e.target.checked); resetAndReload() } }),
2227
+ '仅看问题',
2228
+ ),
2229
+ h('input', { type: 'date', value: since, title: '起始日期', onChange: (e) => { setSince(e.target.value); resetAndReload() } }),
2230
+ h('input', { type: 'date', value: until, title: '结束日期', onChange: (e) => { setUntil(e.target.value); resetAndReload() } }),
2231
+ h('button', { disabled: loading, onClick: () => setReloadTick((n) => n + 1) }, loading ? '刷新中…' : '刷新'),
2232
+ h('button', { disabled: loading, onClick: () => exportAudit('jsonl') }, '导出 JSONL'),
2233
+ (session || channel || outcome || trigger || search || problem || since || until)
2234
+ ? h('button', { className: 'linkbtn', onClick: () => {
2235
+ setSession(''); writeAuditSession(''); setChannel(''); setOutcome(''); setTrigger(''); setSearch(''); setProblem(false); setSince(''); setUntil(''); resetAndReload()
2236
+ } }, '清空筛选')
2237
+ : null,
2238
+ )
2239
+
2240
+ const row = (entry) => {
2241
+ const delivery = auditDeliveryMeta(entry)
2242
+ const outcomeMeta = auditOutcomeMeta(entry.outcome)
2243
+ const budget = auditBudgetOf(entry)
2244
+ const picked = entry.selected ? entry.selected.count : 0
2245
+ const omitted = Array.isArray(entry.omitted) ? entry.omitted.length : 0
2246
+ const candidates = typeof entry.candidates === 'number' ? entry.candidates : '—'
2247
+ return h('button', {
2248
+ key: entry.id,
2249
+ className: 'audit-row' + (entry.id === selectedId ? ' on' : ''),
2250
+ onClick: () => setSelectedId(entry.id),
2251
+ },
2252
+ h('span', { className: 'm t', title: fmtTime(entry.at) }, shortTime(entry.at)),
2253
+ h('span', { className: 'm' },
2254
+ h('b', { className: 'ch' }, auditChannelLabel(entry.channel)),
2255
+ h('span', { className: 'trig' }, ` · ${entry.kind || 'event'}`),
2256
+ ),
2257
+ h('span', { className: 'm trig', title: `${entry.trigger || ''} ${entry.phase || ''}` },
2258
+ `${entry.trigger || '—'}${entry.phase ? ` / ${entry.phase}` : ''}`),
2259
+ h('span', { className: 'm nums' }, `${candidates} / ${picked} / ${omitted}`),
2260
+ h('span', { className: 'm' }, budget
2261
+ ? h('span', { className: 'audit-budget' },
2262
+ h('span', { className: 'bar' }, h('i', { className: budget.over ? 'over' : '', style: { width: `${budget.budget > 0 ? Math.min(100, Math.round((budget.used / budget.budget) * 100)) : 100}%` } })),
2263
+ h('span', { className: 'num' }, `${budget.used}/${budget.budget}`),
2264
+ )
2265
+ : h('span', { className: 'muted' }, '—')),
2266
+ h('span', { className: 'm del' }, auditPill(delivery.label + delivery.detail, delivery.tone, delivery.detail || undefined)),
2267
+ h('span', { className: 'm' }, auditPill(outcomeMeta.label, outcomeMeta.tone)),
2268
+ )
2269
+ }
2270
+
2271
+ const detail = selected ? (() => {
2272
+ const delivery = auditDeliveryMeta(selected)
2273
+ const budgetRows = Object.entries(selected.budgets || {}).map(([name, budget]) => {
2274
+ const pct = budget.budget > 0 ? Math.min(100, Math.round((budget.used / budget.budget) * 100)) : 100
2275
+ return h('div', { className: 'audit-budget', key: name },
2276
+ h('span', null, name),
2277
+ h('span', { className: 'bar' }, h('i', { className: budget.over ? 'over' : '', style: { width: `${pct}%` } })),
2278
+ h('span', { className: 'num' }, `${budget.used}/${budget.budget}${budget.over ? ' 超' : ''}`),
2279
+ )
2280
+ })
2281
+ const selectedIds = selected.selected ? selected.selected.contentIds : (selected.contentIds || [])
2282
+ const hintIds = selected.selected ? selected.selected.hintIds : (selected.hintIds || [])
2283
+ const omitted = Array.isArray(selected.omitted) ? selected.omitted : []
2284
+ const kv = (label, value) => (value === undefined || value === null || value === '')
2285
+ ? null
2286
+ : [h('span', { className: 'k', key: 'k' }, label), h('span', { className: 'v', key: 'v' }, String(value))]
2287
+ const json = JSON.stringify(selected, null, 2)
2288
+ return h('div', { className: 'audit-detail' },
2289
+ h('div', { className: 'audit-detail-head' },
2290
+ h('b', null, auditSummaryLine(selected)),
2291
+ h('span', { className: 'spacer' }),
2292
+ h('button', { className: 'linkbtn', onClick: () => copyAuditText(selected.id, setNotice) }, '复制 ID'),
2293
+ h('button', { className: 'audit-close', title: '关闭', onClick: () => setSelectedId(null) }, '×'),
2294
+ ),
2295
+ h('div', { className: 'audit-kv' },
2296
+ kv('事件', selected.id),
2297
+ kv('序号', selected.seq),
2298
+ kv('时间', fmtTime(selected.at)),
2299
+ kv('schema', selected.schemaVersion || '旧版'),
2300
+ kv('会话', selected.sessionId),
2301
+ kv('step', selected.step),
2302
+ kv('通道', `${auditChannelLabel(selected.channel)} / ${selected.kind}`),
2303
+ kv('阶段', selected.stage),
2304
+ kv('触发', selected.trigger),
2305
+ kv('phase', selected.phase),
2306
+ kv('原因', selected.reasonCode),
2307
+ kv('作用域', (selected.scopes || []).join(' → ')),
2308
+ ),
2309
+ selected.query ? h('div', { className: 'audit-sec' },
2310
+ h('div', { className: 'audit-sec-title' }, '查询(已脱敏)'),
2311
+ h('div', null, selected.query.text || '(文本已脱敏/为空)'),
2312
+ h('div', { className: 'muted' }, `${selected.query.chars} 字符${selected.query.redacted ? ' · 命中凭据脱敏' : ''}${selected.query.hash ? ` · ${selected.query.hash}` : ''}`),
2313
+ ) : null,
2314
+ selected.filter ? h('div', { className: 'audit-sec' },
2315
+ h('div', { className: 'audit-sec-title' }, '检索与过滤'),
2316
+ h('div', { className: 'audit-kv' },
2317
+ kv('原始命中', selected.filter.rawHits),
2318
+ kv('标签过滤', selected.filter.tagFiltered),
2319
+ kv('退役排除', selected.filter.supersededExcluded),
2320
+ kv('最终候选', selected.filter.candidates),
2321
+ ),
2322
+ ) : null,
2323
+ h('div', { className: 'audit-sec' },
2324
+ h('div', { className: 'audit-sec-title' }, '选择与省略'),
2325
+ h('div', { className: 'audit-kv' },
2326
+ kv('候选', selected.candidates),
2327
+ kv('选中', selectedIds.length),
2328
+ kv('新增', selected.selected && selected.selected.newlyAddedIds ? selected.selected.newlyAddedIds.length : '—'),
2329
+ kv('hint', hintIds.length),
2330
+ kv('去重跳过', selected.dedup ? selected.dedup.skipped : '—'),
2331
+ ),
2332
+ selectedIds.length > 0 ? h('div', { className: 'audit-flat' }, selectedIds.map((id) => h('span', { className: 'tag', key: id }, id))) : null,
2333
+ omitted.length > 0 ? h('div', { className: 'audit-flat' }, omitted.map((item, i) => h('span', { className: 'tag', key: `${item.id}-${i}`, title: item.tags ? item.tags.join(', ') : '' }, `${item.id.slice(0, 8)} · ${item.reason}`))) : null,
2334
+ ),
2335
+ budgetRows.length > 0 ? h('div', { className: 'audit-sec' },
2336
+ h('div', { className: 'audit-sec-title' }, '预算'),
2337
+ ...budgetRows,
2338
+ ) : null,
2339
+ selected.delivery ? h('div', { className: 'audit-sec' },
2340
+ h('div', { className: 'audit-sec-title' }, '投递'),
2341
+ h('div', { className: 'audit-kv' },
2342
+ kv('状态', delivery.label + delivery.detail),
2343
+ kv('appended', selected.delivery.appended === null ? '未知' : String(selected.delivery.appended)),
2344
+ kv('抑制原因', selected.delivery.suppressedBy),
2345
+ kv('字符数', selected.delivery.textChars),
2346
+ kv('内容 hash', selected.delivery.textHash),
2347
+ ),
2348
+ ) : null,
2349
+ selected.error ? h('div', { className: 'audit-sec' },
2350
+ h('div', { className: 'audit-sec-title' }, '失败'),
2351
+ h('div', null, `${selected.error.stage} / ${selected.error.code}`),
2352
+ h('div', { className: 'muted' }, '审计只保留稳定错误码,不包含堆栈或异常原文。'),
2353
+ ) : null,
2354
+ selected.signal ? h('div', { className: 'audit-sec' },
2355
+ h('div', { className: 'audit-sec-title' }, '信号'),
2356
+ h('div', { className: 'audit-kv' },
2357
+ kv('key', selected.signal.key),
2358
+ kv('reason', selected.signal.reason),
2359
+ kv('tool', selected.signal.tool),
2360
+ kv('tag', selected.signal.tag),
2361
+ kv('errorClass', selected.signal.errorClass),
2362
+ kv('source', selected.signal.source),
2363
+ ),
2364
+ ) : null,
2365
+ h('details', { className: 'audit-sec' },
2366
+ h('summary', { className: 'audit-sec-title' }, '原始结构化事件'),
2367
+ h('pre', { className: 'audit-json' }, json),
2368
+ h('div', { className: 'row' }, h('button', { className: 'linkbtn', onClick: () => copyAuditText(json, setNotice) }, '复制 JSON')),
2369
+ ),
2370
+ )
2371
+ })() : null
2372
+
2373
+ const listBody = loading
2374
+ ? h('div', { className: 'audit-empty' }, '加载审计事件…')
2375
+ : entries.length === 0
2376
+ ? h('div', { className: 'audit-empty' },
2377
+ error ? '加载失败。' : '当前筛选没有审计事件。',
2378
+ error ? null : h('div', { className: 'muted' }, '开始一轮任务后,这里会出现注入评估与投递记录。'),
2379
+ error ? h('div', { className: 'err' }, error) : null,
2380
+ error ? h('div', null, h('button', { onClick: () => setReloadTick((n) => n + 1) }, '重试')) : null,
2381
+ )
2382
+ : h('div', { className: 'audit-list' }, entries.map(row))
2383
+
2384
+ return h('div', { className: 'audit' },
2385
+ h('div', { className: 'audit-head' },
2386
+ h('div', null,
2387
+ h('div', { className: 'audit-title' }, '记忆审计'),
2388
+ h('div', { className: 'audit-sub' }, '追踪记忆注入的触发、筛选、预算、投递与失败原因;评估选中 ≠ 已投递。'),
2389
+ ),
2390
+ h('div', { className: 'audit-mode' },
2391
+ auditPill(persistence === 'memory' ? '内存模式 · 重启后不保留' : persistence === 'jsonl' ? '持久化正常' : '记录不完整', persistence === 'degraded' ? 'bad' : persistence === 'memory' ? 'warn' : 'ok'),
2392
+ notice ? h('span', { className: 'muted' }, notice) : null,
2393
+ ),
2394
+ ),
2395
+ ...banner,
2396
+ h('div', { className: 'audit-stats' },
2397
+ h('div', { className: 'audit-stat' }, h('b', null, String(total)), h('span', null, '筛选内事件')),
2398
+ h('div', { className: 'audit-stat' }, h('b', null, String(prepared)), h('span', null, '本页已准备(投递未确认)')),
2399
+ h('div', { className: 'audit-stat' }, h('b', null, String(suppressed)), h('span', null, '本页被抑制/未尝试')),
2400
+ h('div', { className: 'audit-stat' }, h('b', null, String(failed)), h('span', null, '本页失败')),
2401
+ h('div', { className: 'audit-stat' }, h('b', null, dropped > 0 ? String(dropped) : '0'), h('span', null, capacity === null ? '已丢弃' : `已丢弃 / 容量 ${capacity}`)),
2402
+ ),
2403
+ toolbar,
2404
+ error && entries.length > 0 ? h('div', { className: 'err' }, error) : null,
2405
+ h('div', { className: 'audit-split' + (selected ? ' has-detail' : '') },
2406
+ h('div', null, listBody),
2407
+ detail,
2408
+ ),
2409
+ h('div', { className: 'audit-pager' },
2410
+ h('button', { disabled: loading || cursorStack.length === 0, onClick: () => {
2411
+ const stack = cursorStack.slice()
2412
+ const prev = stack.pop() || ''
2413
+ setCursorStack(stack)
2414
+ load(prev, stack)
2415
+ } }, '上一页'),
2416
+ h('span', null, `${total} 条${nextCursor ? '' : ' · 已到末页'}`),
2417
+ h('button', { disabled: loading || !nextCursor, onClick: () => {
2418
+ const stack = cursorStack.concat(cursor || '')
2419
+ setCursorStack(stack)
2420
+ load(nextCursor, stack)
2421
+ } }, '下一页'),
2422
+ ),
2423
+ )
2424
+ }
2425
+
1950
2426
  /** 待嵌入自动刷新:最多 300 次 × 1.5s(后端挂着时不无限轮询)。 */
1951
2427
  const PENDING_POLL_LIMIT = 300
1952
2428
 
@@ -2315,6 +2791,7 @@ window.__ModuleLoader__.load({
2315
2791
  onClick: () => { if (tab !== 'tree') load('', ''); setTab('tree') },
2316
2792
  }, '记忆树'),
2317
2793
  h('button', { className: 'tab' + (tab === 'settings' ? ' on' : ''), onClick: () => setTab('settings') }, '设置'),
2794
+ h('button', { className: 'tab' + (tab === 'audit' ? ' on' : ''), onClick: () => setTab('audit') }, '审计'),
2318
2795
  ),
2319
2796
  tab === 'settings'
2320
2797
  ? h(SettingsTab, {})
@@ -2322,7 +2799,9 @@ window.__ModuleLoader__.load({
2322
2799
  ? dataBody
2323
2800
  : tab === 'tree'
2324
2801
  ? treeBody
2325
- : overviewBody,
2802
+ : tab === 'audit'
2803
+ ? h(AuditTab, { scopes })
2804
+ : overviewBody,
2326
2805
  )
2327
2806
  }
2328
2807
 
@@ -2529,6 +3008,7 @@ window.__ModuleLoader__.load({
2529
3008
  MemoryPanel: MemoryPanel,
2530
3009
  MemoryTreeTab: MemoryTreeTab,
2531
3010
  SettingsTab: SettingsTab,
3011
+ AuditTab: AuditTab,
2532
3012
  buildMemoryTree: buildMemoryTree,
2533
3013
  KIND_META: KIND_META,
2534
3014
  CSS: CSS,