dsh-wiki-notes 1.4.3 → 1.5.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/bridge.js CHANGED
@@ -33,6 +33,16 @@ export function errorEnvelope(code, message, stage = 'bridge', detail = null, re
33
33
  }
34
34
  }
35
35
 
36
+ /**
37
+ * 冻结契约里 observe 命令的「成功统计返回」只有一种形状:kind === 'observe_stats'。
38
+ * 'observe' 是 observe_log.jsonl 里单条日志事件的 kind,不是命令返回;
39
+ * 'error' 是通路坏了的错误信封,绝不能往上挂治理指标。
40
+ * 判定放在 bridge 层(这里只管调用形状),让插件接线和 CI 复用同一份语义。
41
+ */
42
+ export function isObserveResult(value) {
43
+ return value !== null && typeof value === 'object' && value.kind === 'observe_stats'
44
+ }
45
+
36
46
  function tail(text, n = 600) {
37
47
  const s = String(text ?? '')
38
48
  return s.length <= n ? s : `…${s.slice(-n)}`
package/lib/calls.js CHANGED
@@ -11,8 +11,10 @@
11
11
  * 3. 读的时候只认尾部 —— 账本会长到几千行,没人需要为了看一眼今天的调用
12
12
  * 把整个文件解析一遍。
13
13
  */
14
+ import { createJsonlStore } from './jsonl-store.js'
14
15
 
15
- import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, statSync, writeFileSync } from 'node:fs'
16
+ export { MAX_LINES, KEEP_LINES, TAIL_BYTES, lineCountOf } from './jsonl-store.js'
17
+ import { MAX_LINES, KEEP_LINES } from './jsonl-store.js'
16
18
 
17
19
  /** 账本只认这 8 个字段。顺序就是表头顺序。 */
18
20
  export const CALL_FIELDS = ['ts', 'source', 'tool', 'mode', 'query', 'hits', 'ms', 'ok']
@@ -21,12 +23,6 @@ export const CALL_FIELDS = ['ts', 'source', 'tool', 'mode', 'query', 'hits', 'ms
21
23
  export const QUERY_MAX = 120
22
24
  /** 内存里留最近多少条 —— 文件读不出来时的兜底。 */
23
25
  export const BUFFER_MAX = 500
24
- /** 超过这么多行就轮转。 */
25
- export const MAX_LINES = 5000
26
- /** 轮转后留最后这么多行。 */
27
- export const KEEP_LINES = 2500
28
- /** 读取时只从文件尾部读这么多字节。 */
29
- export const TAIL_BYTES = 262144
30
26
  const DEFAULT_LIMIT = 200
31
27
  const LIMIT_MAX = 500
32
28
  /** totals 最多扫这么多行 —— 再老的不值得为「今日」统计去解析。 */
@@ -73,72 +69,14 @@ export function normalizeEntry(raw) {
73
69
  }
74
70
  }
75
71
 
76
- /** 读文件尾部;文件不存在或读不了就返回空串,由调用方退回内存缓冲。 */
77
- function readTail(file, bytes = TAIL_BYTES) {
78
- let size = 0
79
- try {
80
- size = statSync(file).size
81
- } catch {
82
- return ''
83
- }
84
- if (size === 0) return ''
85
- if (size <= bytes) {
86
- try {
87
- return readFileSync(file, 'utf8')
88
- } catch {
89
- return ''
90
- }
91
- }
92
- let fd = null
93
- try {
94
- fd = openSync(file, 'r')
95
- const length = Math.min(bytes, fstatSync(fd).size)
96
- const buffer = Buffer.alloc(length)
97
- readSync(fd, buffer, 0, length, size - length)
98
- return buffer.toString('utf8')
99
- } catch {
100
- return ''
101
- } finally {
102
- if (fd !== null) {
103
- try {
104
- closeSync(fd)
105
- } catch {
106
- /* 关不掉也只是句柄,不影响读到的内容 */
107
- }
108
- }
109
- }
110
- }
111
-
112
- function parseLines(text) {
113
- const rows = []
114
- for (const line of text.split('\n')) {
115
- const trimmed = line.trim()
116
- if (trimmed === '') continue
117
- try {
118
- rows.push(JSON.parse(trimmed))
119
- } catch {
120
- // 进程写到一半被杀会留下半行。跳过它,不要因此让整页白掉。
121
- }
122
- }
123
- return rows
124
- }
125
-
126
- function countLines(file) {
127
- try {
128
- return parseLines(readFileSync(file, 'utf8')).length
129
- } catch {
130
- return 0
131
- }
132
- }
133
-
134
72
  /**
135
73
  * 建一个账本。同一个文件可以有多个实例(宿主一个、测试一个),
136
74
  * 它们各记各的内存缓冲,文件是共享的。
137
75
  */
138
76
  export function createCallLog({ file, enabled = true, maxLines = MAX_LINES, keepLines = KEEP_LINES } = {}) {
139
77
  const buffer = []
78
+ const store = createJsonlStore({ file, maxLines, keepLines })
140
79
  let on = enabled !== false
141
- let lineCount = null
142
80
  let warned = false
143
81
 
144
82
  function warnOnce(error) {
@@ -147,49 +85,33 @@ export function createCallLog({ file, enabled = true, maxLines = MAX_LINES, keep
147
85
  console.warn('[wiki-notes] 调用记录写不进文件,只保留在内存里:', error?.message ?? error)
148
86
  }
149
87
 
150
- function rotateIfNeeded() {
151
- if (lineCount === null) lineCount = countLines(file)
152
- if (lineCount <= maxLines) return
153
- let kept = []
154
- try {
155
- kept = parseLines(readFileSync(file, 'utf8')).slice(-keepLines)
156
- } catch {
157
- kept = []
158
- }
159
- try {
160
- writeFileSync(file, kept.map((row) => JSON.stringify(row) + '\n').join(''))
161
- lineCount = kept.length
162
- } catch (error) {
163
- warnOnce(error)
164
- }
165
- }
166
-
167
88
  function append(entry) {
168
89
  if (file === undefined || file === null || file === '') return
169
90
  try {
170
- rotateIfNeeded()
171
- appendFileSync(file, JSON.stringify(entry) + '\n')
172
- lineCount = (lineCount ?? 0) + 1
91
+ store.append(entry)
173
92
  warned = false
174
93
  } catch (error) {
175
94
  // 目录被删、只读、被别的进程占住 —— 都只影响账本,不影响检索。
176
95
  // 下次还会再试:用户可能只是临时删掉了文件。
177
96
  warnOnce(error)
178
- lineCount = null
97
+ store.invalidate()
179
98
  }
180
99
  }
181
100
 
182
101
  function record(raw) {
102
+ // 关闭观察就是明确放弃这段历史:先阻断新事件进入,连内存缓冲也不收。
103
+ // 否则关闭后旧周期仍会有一行「没落盘但留在内存里」的残留,重新打开时又浮出来。
104
+ if (!on) return null
183
105
  const entry = normalizeEntry(raw)
184
106
  if (entry === null) return null
185
107
  buffer.push(entry)
186
108
  while (buffer.length > BUFFER_MAX) buffer.shift()
187
- if (on) append(entry)
109
+ append(entry)
188
110
  return entry
189
111
  }
190
112
 
191
113
  function read({ limit = DEFAULT_LIMIT, source = 'all', only = 'all' } = {}) {
192
- const fileRows = parseLines(readTail(file))
114
+ const fileRows = store.readRows()
193
115
  // 文件里可能只有历史的一部分(刚被删过、或写失败过),把内存里文件没覆盖的补回来。
194
116
  // 键带上 hits / ms:同一秒里两次相同的查询是不同的两件事,不该被去重吃掉。
195
117
  const seen = new Set(fileRows.map((row) => `${row.ts}|${row.tool}|${row.query}|${row.hits}|${row.ms}`))
@@ -227,13 +149,13 @@ export function createCallLog({ file, enabled = true, maxLines = MAX_LINES, keep
227
149
 
228
150
  function clear() {
229
151
  buffer.length = 0
230
- lineCount = 0
231
152
  if (file === undefined || file === null || file === '') return
232
153
  try {
233
- writeFileSync(file, '')
154
+ store.clear()
234
155
  warned = false
235
156
  } catch (error) {
236
157
  warnOnce(error)
158
+ store.invalidate()
237
159
  }
238
160
  }
239
161
 
@@ -243,8 +165,3 @@ export function createCallLog({ file, enabled = true, maxLines = MAX_LINES, keep
243
165
 
244
166
  return { record, read, clear, setEnabled, enabled: () => on, buffer: () => buffer.slice() }
245
167
  }
246
-
247
- /** 给测试与排查用:账本文件现在有多少行。 */
248
- export function lineCountOf(file) {
249
- return existsSync(file) ? countLines(file) : 0
250
- }
package/lib/client.js CHANGED
@@ -1396,6 +1396,104 @@ window.__ModuleLoader__.load({
1396
1396
  return next
1397
1397
  }
1398
1398
 
1399
+ /** 指标为 null 时不许伪装成 0%;「没有数据」和「0 次违规」必须是两种状态。 */
1400
+ function governancePercent(metric) {
1401
+ if (!metric || typeof metric.value !== 'number' || !Number.isFinite(metric.value)) return '没有数据'
1402
+ return (metric.value * 100).toFixed(1) + '%'
1403
+ }
1404
+
1405
+ /** 每项指标都带分子分母、有效样本数、排除数与排除原因,不许只报一个百分比。 */
1406
+ function governanceDetail(metric) {
1407
+ if (!metric) return ''
1408
+ function shown(value) {
1409
+ return value === null || value === undefined ? '—' : String(value)
1410
+ }
1411
+ var parts = [
1412
+ '分子/分母:' + shown(metric.numerator) + '/' + shown(metric.denominator),
1413
+ '有效样本:' + shown(metric.effective_samples),
1414
+ '排除:' + shown(metric.excluded_count),
1415
+ ]
1416
+ var reasons = Array.isArray(metric.exclude_reasons) ? metric.exclude_reasons : []
1417
+ if (reasons.length > 0) parts.push('排除原因:' + reasons.join('、'))
1418
+ return parts.join(' · ')
1419
+ }
1420
+
1421
+ function governanceMetricRow(label, metric, extraClassName) {
1422
+ var text = governancePercent(metric)
1423
+ if (label === '有效 Verify 违规发现率' && metric && metric.numerator === 0
1424
+ && typeof metric.denominator === 'number' && metric.denominator > 0) {
1425
+ text = '0 次违规(0.0%)'
1426
+ }
1427
+ return h(
1428
+ 'div',
1429
+ { className: 'wn-gov-row' + (extraClassName ? ' ' + extraClassName : '') },
1430
+ h('div', { className: 'wn-gov-row-head' }, h('span', null, label), h('b', null, text)),
1431
+ h('div', { className: 'wn-gov-detail' }, governanceDetail(metric)),
1432
+ )
1433
+ }
1434
+
1435
+ /** 治理指标面板只挂在「知识库 → 调用记录」页签内,不另开页签或一级入口。 */
1436
+ function WikiGovernancePanel(props) {
1437
+ var g = props && props.governance
1438
+ var head = h('div', { className: 'wn-gov-head' }, '治理观察(插件侧账本,与 Python 观察日志分开)')
1439
+ var on = !!(g && g.observe_enabled === true && g.state !== 'disabled' && g.state !== 'unavailable')
1440
+ if (!on) {
1441
+ return h(
1442
+ 'div',
1443
+ { className: 'wn-gov' },
1444
+ head,
1445
+ h('div', { className: 'wn-gov-off' }, (g && g.message) || '没有启用观察,因此没有数据'),
1446
+ h('div', { className: 'wn-gov-note' }, '观察是否启用:未启用 · 窗口 ' + String((g && g.window && g.window.days) || 7) + ' 天'),
1447
+ h('div', { className: 'wn-gov-note' }, '断言数量:数据不可用'),
1448
+ h('div', { className: 'wn-gov-note' }, '观察到的核验链收敛率:没有启用观察,因此没有数据'),
1449
+ )
1450
+ }
1451
+
1452
+ var metrics = g.metrics || {}
1453
+ var trigger = metrics.required_check_verification_trigger_rate
1454
+ var discovery = metrics.effective_verify_violation_discovery_rate
1455
+ var coverage = metrics.observation_coverage
1456
+ var rows = [
1457
+ governanceMetricRow('必核项 Context 核验触发率', trigger),
1458
+ governanceMetricRow('有效 Verify 违规发现率', discovery),
1459
+ governanceMetricRow('观察覆盖率', coverage),
1460
+ ]
1461
+ var group = trigger && trigger.groups && trigger.groups.partial_insufficient
1462
+ if (group) {
1463
+ rows.push(governanceMetricRow('其中 partial / insufficient 分组', group, 'wn-gov-sub'))
1464
+ }
1465
+
1466
+ var conv = g.convergence || {}
1467
+ var convParts = []
1468
+ if (typeof conv.converged === 'number') convParts.push('已收敛 ' + conv.converged)
1469
+ if (typeof conv.unresolved === 'number') convParts.push('仍未收敛 ' + conv.unresolved)
1470
+ if (typeof conv.not_rechecked === 'number') convParts.push('未复核 ' + conv.not_rechecked)
1471
+
1472
+ var ex = g.excluded || {}
1473
+ var cs = ex.context_samples || {}
1474
+ var vc = ex.verify_calls || {}
1475
+ var exParts = []
1476
+ ;['restart_not_observed', 'capacity'].forEach(function (key) {
1477
+ if (typeof cs[key] === 'number' && cs[key] > 0) exParts.push('样本 ' + key + ' ' + cs[key])
1478
+ })
1479
+ ;['context_missing', 'context_expired', 'context_corrupt', 'exec_failed'].forEach(function (key) {
1480
+ if (typeof vc[key] === 'number' && vc[key] > 0) exParts.push('Verify ' + key + ' ' + vc[key])
1481
+ })
1482
+ if (typeof ex.late_verify === 'number' && ex.late_verify > 0) exParts.push('迟到 Verify ' + ex.late_verify)
1483
+
1484
+ return h(
1485
+ 'div',
1486
+ { className: 'wn-gov' },
1487
+ head,
1488
+ h('div', { className: 'wn-gov-note' }, '观察是否启用:已启用 · 窗口 ' + String((g.window && g.window.days) || 7) + ' 天'),
1489
+ h('div', { className: 'wn-gov-rows' }, rows),
1490
+ h('div', { className: 'wn-gov-note' }, '断言数量:数据不可用'),
1491
+ h('div', { className: 'wn-gov-note' }, '观察到的核验链收敛率:' + (convParts.length > 0 ? convParts.join(' / ') : '没有数据')),
1492
+ h('div', { className: 'wn-gov-note' }, exParts.length > 0 ? '排除:' + exParts.join(' · ') : '排除:无'),
1493
+ h('div', { className: 'wn-gov-note' }, '收敛只表示观察到的核验链,不等于最终回答已证明可靠。'),
1494
+ )
1495
+ }
1496
+
1399
1497
  /**
1400
1498
  * 「知识库 · 调用」。
1401
1499
  *
@@ -1403,7 +1501,7 @@ window.__ModuleLoader__.load({
1403
1501
  * 所以「模型到底查没查库」这件事,之前只能去翻会话转录。这个页面就是那本账。
1404
1502
  */
1405
1503
  function WikiCallsSection(props) {
1406
- var stateTuple = useState({ rows: [], totals: null, enabled: true, window: 0, error: '', loading: true })
1504
+ var stateTuple = useState({ rows: [], totals: null, enabled: true, window: 0, governance: null, error: '', loading: true })
1407
1505
  var state = stateTuple[0]
1408
1506
  var setState = stateTuple[1]
1409
1507
 
@@ -1440,6 +1538,7 @@ window.__ModuleLoader__.load({
1440
1538
  totals: (data && data.totals) || null,
1441
1539
  enabled: !(data && data.enabled === false),
1442
1540
  window: data && typeof data.window === 'number' ? data.window : 0,
1541
+ governance: data && data.governance && typeof data.governance === 'object' ? data.governance : null,
1443
1542
  error: '',
1444
1543
  loading: false,
1445
1544
  })
@@ -1609,6 +1708,7 @@ window.__ModuleLoader__.load({
1609
1708
  { className: 'wn-calls-note' },
1610
1709
  '统计基于最近 ' + String(state.window === undefined ? 0 : state.window) + ' 条记录;命中率分母不含 verify / observe。',
1611
1710
  ),
1711
+ h(WikiGovernancePanel, { governance: state.governance }),
1612
1712
  h(
1613
1713
  'div',
1614
1714
  { className: 'wn-calls-bar' },
@@ -1635,6 +1735,7 @@ window.__ModuleLoader__.load({
1635
1735
  }),
1636
1736
  '记录开关',
1637
1737
  ),
1738
+ h('span', { className: 'wn-calls-warn' }, '关闭会清空现有记录与待核验状态,期间指标不可用'),
1638
1739
  h(
1639
1740
  'button',
1640
1741
  { type: 'button', className: confirmClear === true ? 'wn-btn wn-btn-danger' : 'wn-btn', onClick: clearCalls },
@@ -1835,6 +1936,16 @@ window.__ModuleLoader__.load({
1835
1936
  '.wn-calls-ms{text-align:right;font-variant-numeric:tabular-nums;color:var(--wn-muted);}',
1836
1937
  '.wn-calls-ms.wn-slow{color:#b4552d;}',
1837
1938
  '.wn-calls-empty{padding:18px 12px;text-align:center;color:var(--wn-muted);font-size:12.5px;background:var(--wn-card);border:1px dashed var(--wn-line);border-radius:10px;}',
1939
+ '.wn-calls-warn{font-size:11.5px;color:var(--wn-warn);}',
1940
+ '.wn-gov{display:flex;flex-direction:column;gap:7px;padding:12px;background:var(--wn-card);border:1px solid var(--wn-line-soft);border-radius:10px;}',
1941
+ '.wn-gov-head{font-size:12.5px;font-weight:600;color:var(--wn-fg);}',
1942
+ '.wn-gov-off{padding:8px 10px;background:var(--wn-bar);border-radius:8px;font-size:12px;color:var(--wn-muted);}',
1943
+ '.wn-gov-rows{display:flex;flex-direction:column;gap:6px;}',
1944
+ '.wn-gov-row{display:flex;flex-direction:column;gap:2px;padding:8px 10px;background:var(--wn-field);border:1px solid var(--wn-line-soft);border-radius:8px;}',
1945
+ '.wn-gov-row.wn-gov-sub{margin-left:16px;}',
1946
+ '.wn-gov-row-head{display:flex;justify-content:space-between;gap:10px;font-size:12.5px;}',
1947
+ '.wn-gov-row-head b{font-variant-numeric:tabular-nums;}',
1948
+ '.wn-gov-detail,.wn-gov-note{font-size:11.5px;color:var(--wn-muted);line-height:1.5;}',
1838
1949
  '}',
1839
1950
  ].join('')
1840
1951
 
@@ -1962,6 +2073,8 @@ window.__ModuleLoader__.load({
1962
2073
  shortTime: shortTime,
1963
2074
  WikiSearchPanel: WikiSearchPanel,
1964
2075
  WikiSearchSidebarTab: WikiSearchSidebarTab,
2076
+ WikiCallsSection: WikiCallsSection,
2077
+ WikiGovernancePanel: WikiGovernancePanel,
1965
2078
  },
1966
2079
  }
1967
2080
  return module.exports