dsh-wiki-notes 1.4.2 → 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.
Files changed (27) hide show
  1. package/README.md +43 -0
  2. package/docs/README.md +1 -1
  3. package/docs/superpowers/plans/2026-11-05-wiki-call-audit.md +553 -0
  4. package/docs/superpowers/specs/2026-11-05-wiki-call-audit-design.md +164 -0
  5. package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.657.md +657 -0
  6. package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.661.md +661 -0
  7. package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.final.md +661 -0
  8. package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.md +661 -0
  9. package/docs//345/245/221/347/272/246-stage0/samples/_verify_probe.json +1 -1
  10. package/docs//345/245/221/347/272/246-stage0/samples/{context.cq-shenlun.json → context.sample-cache.json} +80 -80
  11. package/docs//345/245/221/347/272/246-stage0/samples/verify.fabricated-quote.json +3 -3
  12. package/docs//345/245/221/347/272/246-stage0/samples/verify.scope-mismatch.json +3 -3
  13. package/docs//345/245/221/347/272/246-stage0/samples/verify.wrong-five.json +9 -9
  14. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2650-/345/256/241/350/256/241/344/270/216/345/245/221/347/272/246.md +10 -10
  15. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2651-/346/225/260/345/200/274/345/210/244/346/215/256/344/270/216/345/274/225/346/223/216/347/212/266/346/200/201.md +9 -9
  16. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2652-/345/277/253/347/205/247/344/270/216TTL.md +3 -3
  17. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2653-/346/224/257/346/214/201/345/216/237/345/233/240.md +3 -3
  18. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2654-/346/217/222/344/273/266/346/216/245/345/205/245.md +1 -1
  19. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2655-/350/247/202/345/257/237/351/227/255/347/216/257/344/270/216/345/256/236/346/210/230/351/252/214/346/224/266.md +10 -10
  20. package/lib/bridge.js +10 -0
  21. package/lib/calls.js +167 -0
  22. package/lib/client.js +463 -11
  23. package/lib/config.js +33 -0
  24. package/lib/governance.js +849 -0
  25. package/lib/index.js +298 -14
  26. package/lib/jsonl-store.js +137 -0
  27. package/package.json +7 -5
@@ -0,0 +1,849 @@
1
+ /**
2
+ * governance.js —— 插件侧的证据约束账本。
3
+ *
4
+ * 为什么单独一个文件:它既要从 Context 派生「本次回答必须核验」清单,
5
+ * 又要记住「哪份 Context 被核过、哪份只是超时没等到后续」。
6
+ * 两件事共用同一批最小化字段,放一起才不会各说各话。
7
+ *
8
+ * 三条硬纪律(来自已复审的设计稿,不许改):
9
+ * 1. 生命周期状态与样本处置状态是两个维度。重启后没有持久化中断标记,
10
+ * 只能 excluded / unobserved,不能补造 interrupted / completed / 漏查。
11
+ * 2. 字段只在白名单里:ID、时间、状态、违规类型、父子关联、计数。
12
+ * 回答原文、引文、页面路径、具体数值一律不进账本。
13
+ * 3. Python Gateway v1 冻结。这里只读插件自己拿到的 Context / Verify
14
+ * 返回体,不改管线、不改 schema、不读 Python 快照内部。
15
+ */
16
+ import { createHash } from 'node:crypto'
17
+ import { createJsonlStore } from './jsonl-store.js'
18
+
19
+ /** 事件账本只认这 18 个字段。 */
20
+ export const GOVERNANCE_FIELDS = [
21
+ 'ts', 'boot_ref', 'session_ref', 'event_id', 'kind', 'context_id',
22
+ 'parent_observe_id', 'lifecycle', 'disposition', 'exclude_reason',
23
+ 'support', 'required_check_count', 'verify_unusable_reason', 'status',
24
+ 'reason', 'violation_types', 'attempt_seq', 'ttl_seconds',
25
+ ]
26
+
27
+ /** 冻结契约里 violation.type 的 11 个枚举;本模块的规则族只能取子集。 */
28
+ export const RULE_FAMILIES = [
29
+ 'conditional_limit_missing',
30
+ 'answered_unfilled_slot',
31
+ 'gap_not_disclosed',
32
+ 'unresolved_disclosure_missing',
33
+ 'unresolved_arbitrated',
34
+ 'review_flag_missing',
35
+ 'duplicate_as_independent',
36
+ 'fabricated_quote',
37
+ 'conclusion_without_evidence',
38
+ 'unsupported_numeric_claim',
39
+ 'numeric_check_failed',
40
+ ]
41
+
42
+ /** 当前冻结契约下可产生的 Verify 不可用原因。 */
43
+ const VERIFY_UNUSABLE_REASONS = ['context_missing', 'context_expired', 'context_corrupt', 'exec_failed']
44
+ /** no_assertion 是兼容性保留值:当前不可产生、不计数、不展示。 */
45
+ const EFFECTIVE_STATUSES = new Set(['ok', 'violations_found'])
46
+ const RISK_SUPPORTS = new Set(['partial', 'insufficient'])
47
+
48
+ export const DEFAULT_TTL_SECONDS = 1800
49
+ export const PENDING_MAX = 512
50
+
51
+ function pad(value) {
52
+ return String(value).padStart(2, '0')
53
+ }
54
+
55
+ /** 本地时间戳,和调用账本同一套时区。 */
56
+ function stamp(ms) {
57
+ const date = new Date(ms)
58
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
59
+ + `T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
60
+ }
61
+
62
+ function shortHash(text) {
63
+ return createHash('sha256').update(String(text)).digest('hex').slice(0, 12)
64
+ }
65
+
66
+ function randomBootRef() {
67
+ return `boot_${shortHash(`${Date.now()}|${Math.random()}`)}`
68
+ }
69
+
70
+ function clampDays(days) {
71
+ const value = Number(days)
72
+ return Number.isFinite(value) && value > 0
73
+ ? Math.min(3650, Math.max(1, Math.trunc(value)))
74
+ : 7
75
+ }
76
+
77
+ function clampTtl(seconds) {
78
+ const value = Number(seconds)
79
+ return Number.isFinite(value) && value > 0
80
+ ? Math.max(1, Math.trunc(value))
81
+ : DEFAULT_TTL_SECONDS
82
+ }
83
+
84
+ function clampPendingMax(value) {
85
+ const parsed = Number(value)
86
+ return Number.isFinite(parsed) && parsed >= 1 ? Math.trunc(parsed) : PENDING_MAX
87
+ }
88
+
89
+ function asArray(value) {
90
+ return Array.isArray(value) ? value : []
91
+ }
92
+
93
+ function unique(values) {
94
+ return [...new Set(values.filter((value) => typeof value === 'string' && value !== ''))]
95
+ }
96
+
97
+ function hasNumericValues(values) {
98
+ if (Array.isArray(values)) {
99
+ return values.some((value) => typeof value === 'number' || (typeof value === 'string' && /\d/.test(value)))
100
+ }
101
+ if (values !== null && typeof values === 'object') {
102
+ return Object.values(values).some((value) => typeof value === 'number' || (typeof value === 'string' && /\d/.test(value)))
103
+ }
104
+ return false
105
+ }
106
+
107
+ function idsText(ids) {
108
+ const clean = ids.filter((value) => typeof value === 'string' && value !== '')
109
+ if (clean.length === 0) return '未提供编号'
110
+ const shown = clean.slice(0, 4).join('、')
111
+ return clean.length > 4 ? `${shown} 等` : shown
112
+ }
113
+
114
+ function pickEvent(event) {
115
+ const out = {}
116
+ for (const key of GOVERNANCE_FIELDS) {
117
+ if (event[key] !== undefined) out[key] = event[key]
118
+ }
119
+ return out
120
+ }
121
+
122
+ /**
123
+ * 从一份 Context 返回体派生「本次回答必须核验」清单。
124
+ *
125
+ * 只从 evidence / evidence_items / missing / unresolved / conflicts /
126
+ * status / answer.constraints 读;不重新推断事实,不制造新证据。
127
+ * 新增清单段只列槽位 id、evidence_id、计数、规则族,不含数值、引文、
128
+ * 页面路径、页面标题。
129
+ */
130
+ export function buildRequiredChecks(value) {
131
+ const title = '本次回答必须核验'
132
+ const empty = { count: 0, support: '', lines: [title], families: [] }
133
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return empty
134
+ if (value.kind === 'error' || value.kind !== 'context') return empty
135
+
136
+ const status = value.status && typeof value.status === 'object' ? value.status : {}
137
+ const support = typeof status.support === 'string' ? status.support : ''
138
+ const evidence = asArray(value.evidence)
139
+ const evidenceItems = asArray(value.evidence_items)
140
+ const supports = evidence.flatMap((page) => asArray(page.supports))
141
+ const missing = asArray(value.missing)
142
+ const unresolved = asArray(value.unresolved)
143
+ const conflicts = asArray(value.conflicts)
144
+ const constraints = value.answer && typeof value.answer === 'object' && value.answer.constraints
145
+ && typeof value.answer.constraints === 'object' ? value.answer.constraints : {}
146
+
147
+ const items = []
148
+ const families = []
149
+ function add(ruleFamilies, line) {
150
+ items.push(line)
151
+ families.push(...ruleFamilies)
152
+ }
153
+
154
+ // 1. 数值类:numeric 槽,或 supports[].values 里带数值。
155
+ const numericItems = evidenceItems.filter((item) => item.slot === 'numeric' || hasNumericValues(item.values))
156
+ const numericSupports = supports.filter((item) => item.slot === 'numeric' || hasNumericValues(item.values))
157
+ if (numericItems.length > 0 || numericSupports.length > 0) {
158
+ const count = numericItems.length || numericSupports.length
159
+ const ids = idsText(numericItems.map((item) => item.evidence_id))
160
+ add(
161
+ ['unsupported_numeric_claim', 'numeric_check_failed'],
162
+ `- 数值类证据单元:${count} 项(${ids})· 槽位:numeric · 规则族:unsupported_numeric_claim / numeric_check_failed`,
163
+ )
164
+ }
165
+
166
+ // 2. 条件限定:quote_support === 'conditional'。
167
+ const conditionalCount = supports.filter((item) => item.quote_support === 'conditional').length
168
+ if (conditionalCount > 0) {
169
+ add(['conditional_limit_missing'], `- 条件限定支撑:${conditionalCount} 项 · 规则族:conditional_limit_missing`)
170
+ }
171
+
172
+ // 3. 引文型:evidence_items[].quote 非空。
173
+ const quoted = evidenceItems.filter((item) => typeof item.quote === 'string' && item.quote.trim() !== '')
174
+ if (quoted.length > 0) {
175
+ add(['fabricated_quote'], `- 引文型证据单元:${quoted.length} 项 · 规则族:fabricated_quote`)
176
+ }
177
+
178
+ // 4. 缺口与未填槽位:missing 非空,或支持度 partial / insufficient。
179
+ if (missing.length > 0 || RISK_SUPPORTS.has(support)) {
180
+ add(
181
+ ['gap_not_disclosed', 'answered_unfilled_slot'],
182
+ `- 缺口披露:支持度 ${support || '未标注'}、明确缺口 ${missing.length} 项 · 规则族:gap_not_disclosed / answered_unfilled_slot`,
183
+ )
184
+ }
185
+
186
+ // 5. 单页多引擎:仅限 page_count === 1 && engine_count >= 2。
187
+ const duplicate = evidenceItems.filter((item) => Number(item.page_count) === 1 && Number(item.engine_count) >= 2)
188
+ if (duplicate.length > 0) {
189
+ add(['duplicate_as_independent'], `- 单页多引擎来源:${duplicate.length} 项 · 规则族:duplicate_as_independent`)
190
+ }
191
+
192
+ // 6. 复核标记:某个槽位的支撑全部 needs_review。
193
+ const bySlot = new Map()
194
+ for (const item of supports) {
195
+ const slot = typeof item.slot === 'string' ? item.slot : ''
196
+ if (!bySlot.has(slot)) bySlot.set(slot, [])
197
+ bySlot.get(slot).push(item)
198
+ }
199
+ const reviewSlots = [...bySlot.entries()]
200
+ .filter(([, list]) => list.length > 0 && list.every((item) => item.needs_review === true))
201
+ .map(([slot]) => slot)
202
+ if (reviewSlots.length > 0) {
203
+ add(['review_flag_missing'], `- 复核标记:槽位 ${reviewSlots.join('、')} 的支撑需复核 · 规则族:review_flag_missing`)
204
+ }
205
+
206
+ // 7. 未裁决与冲突。
207
+ if (unresolved.length > 0 || conflicts.length > 0) {
208
+ add(
209
+ ['unresolved_disclosure_missing', 'unresolved_arbitrated'],
210
+ `- 未裁决与冲突:${unresolved.length + conflicts.length} 项 · 规则族:unresolved_disclosure_missing / unresolved_arbitrated`,
211
+ )
212
+ }
213
+
214
+ // 8. 零证据结论。
215
+ if (support === 'insufficient' && evidenceItems.length === 0) {
216
+ add(['conclusion_without_evidence'], '- 零证据结论:不得在无证据单元时下结论 · 规则族:conclusion_without_evidence')
217
+ }
218
+
219
+ // 9. 回答约束本身也是必核项,但不引入新事实。
220
+ const constraintFlags = []
221
+ if (constraints.must_disclose_gaps === true) constraintFlags.push('必须披露缺口')
222
+ if (constraints.must_preserve_sources === true) constraintFlags.push('保留来源')
223
+ if (constraints.allow_inference === false) constraintFlags.push('不得推断')
224
+ if (constraintFlags.length > 0) {
225
+ add(['gap_not_disclosed'], `- 回答约束:${constraintFlags.join('、')} · 规则族:gap_not_disclosed`)
226
+ }
227
+
228
+ return {
229
+ count: items.length,
230
+ support,
231
+ lines: [title, ...items],
232
+ families: unique(families),
233
+ }
234
+ }
235
+
236
+ function blankMetric() {
237
+ return {
238
+ numerator: null,
239
+ denominator: null,
240
+ value: null,
241
+ effective_samples: null,
242
+ excluded_count: null,
243
+ exclude_reasons: [],
244
+ }
245
+ }
246
+
247
+ function metric(numerator, denominator, excludedCount, excludeReasons) {
248
+ return {
249
+ numerator,
250
+ denominator,
251
+ value: denominator > 0 ? numerator / denominator : null,
252
+ effective_samples: denominator,
253
+ excluded_count: excludedCount,
254
+ exclude_reasons: unique(excludeReasons),
255
+ }
256
+ }
257
+
258
+ function disabledStats(days) {
259
+ const trigger = blankMetric()
260
+ trigger.groups = { partial_insufficient: blankMetric() }
261
+ return {
262
+ state: 'disabled',
263
+ observe_enabled: false,
264
+ window: { days: clampDays(days), since: null },
265
+ message: '观察未启用,因此没有数据',
266
+ metrics: {
267
+ required_check_verification_trigger_rate: trigger,
268
+ effective_verify_violation_discovery_rate: blankMetric(),
269
+ observation_coverage: blankMetric(),
270
+ },
271
+ assertion_measurement: { state: 'unavailable', assertion_count: null, reason: 'contract_unavailable' },
272
+ convergence: {
273
+ metric: '观察到的核验链收敛率',
274
+ converged: null,
275
+ unresolved: null,
276
+ not_rechecked: null,
277
+ },
278
+ excluded: {
279
+ context_samples: { restart_not_observed: null, capacity: null },
280
+ verify_calls: { context_missing: null, context_expired: null, context_corrupt: null, exec_failed: null },
281
+ late_verify: null,
282
+ },
283
+ }
284
+ }
285
+
286
+ function computeConvergence(effectiveRows) {
287
+ const groups = new Map()
288
+ for (const row of effectiveRows) {
289
+ const id = typeof row.context_id === 'string' ? row.context_id : ''
290
+ if (id === '') continue
291
+ if (!groups.has(id)) groups.set(id, [])
292
+ groups.get(id).push(row)
293
+ }
294
+ let converged = 0
295
+ let unresolved = 0
296
+ let notRechecked = 0
297
+ for (const rows of groups.values()) {
298
+ rows.sort((a, b) => {
299
+ const seqDiff = (Number(a.attempt_seq) || 0) - (Number(b.attempt_seq) || 0)
300
+ if (seqDiff !== 0) return seqDiff
301
+ const tsDiff = String(a.ts ?? '').localeCompare(String(b.ts ?? ''))
302
+ if (tsDiff !== 0) return tsDiff
303
+ return String(a.event_id ?? '').localeCompare(String(b.event_id ?? ''))
304
+ })
305
+ const firstViolation = rows.findIndex((row) => row.status === 'violations_found')
306
+ if (firstViolation < 0) continue
307
+ const after = rows.slice(firstViolation + 1)
308
+ if (after.length === 0) {
309
+ notRechecked += 1
310
+ continue
311
+ }
312
+ const last = after[after.length - 1]
313
+ if (last.status === 'ok') converged += 1
314
+ else if (last.status === 'violations_found') unresolved += 1
315
+ else notRechecked += 1
316
+ }
317
+ return {
318
+ metric: '观察到的核验链收敛率',
319
+ converged,
320
+ unresolved,
321
+ not_rechecked: notRechecked,
322
+ }
323
+ }
324
+
325
+ /**
326
+ * 建一份治理观察账本。
327
+ *
328
+ * `cycle()` 给调用方在发起异步工具调用前取周期号;`clear()` 或重新开启
329
+ * 之后,旧周期号传回来会被丢弃 —— 关闭完成后旧观察周期不再落盘。
330
+ */
331
+ export function createGovernance({
332
+ file,
333
+ enabled = true,
334
+ bootRef,
335
+ sessionScope,
336
+ ttlSeconds = DEFAULT_TTL_SECONDS,
337
+ pendingMax = PENDING_MAX,
338
+ now = () => Date.now(),
339
+ } = {}) {
340
+ const store = createJsonlStore({ file })
341
+ const currentBootRef = typeof bootRef === 'string' && bootRef !== '' ? bootRef : randomBootRef()
342
+ const sessionRef = shortHash(sessionScope ?? 'unscoped')
343
+ const ttl = clampTtl(ttlSeconds)
344
+ const maxPending = clampPendingMax(pendingMax)
345
+
346
+ let on = enabled !== false
347
+ let warned = false
348
+ let cycleRef = 1
349
+
350
+ const pending = new Map()
351
+ const seqByContext = new Map()
352
+ const contextIds = new Set()
353
+ const observeById = new Map()
354
+ const expiredContexts = new Set()
355
+ const capacityContexts = new Set()
356
+
357
+ function nowMs() {
358
+ const value = Number(now())
359
+ return Number.isFinite(value) ? value : Date.now()
360
+ }
361
+
362
+ function warnOnce(error) {
363
+ if (warned) return
364
+ warned = true
365
+ console.warn('[wiki-notes] 治理观察账本写不进文件,只保留在内存里:', error?.message ?? error)
366
+ }
367
+
368
+ function scanRows(rows) {
369
+ const seen = new Set()
370
+ const deduped = []
371
+ for (const row of rows) {
372
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) continue
373
+ const id = typeof row.event_id === 'string' && row.event_id !== ''
374
+ ? row.event_id
375
+ : `${row.ts ?? ''}|${row.context_id ?? ''}|${row.kind ?? ''}|${row.attempt_seq ?? ''}`
376
+ if (seen.has(id)) continue
377
+ seen.add(id)
378
+ deduped.push(row)
379
+ }
380
+
381
+ const contexts = new Map()
382
+ const observeIds = new Map()
383
+ const capacityRows = new Set()
384
+ const expired = new Set()
385
+ const completed = new Set()
386
+ const effectiveVerifyRows = []
387
+ const unusableRows = []
388
+ const lateRows = []
389
+ const seqs = new Map()
390
+
391
+ function contextInfoFromRow(row) {
392
+ const id = typeof row.context_id === 'string' ? row.context_id : ''
393
+ if (id === '') return null
394
+ return {
395
+ contextId: id,
396
+ ts: typeof row.ts === 'string' ? row.ts : stamp(nowMs()),
397
+ bootRef: typeof row.boot_ref === 'string' && row.boot_ref !== '' ? row.boot_ref : currentBootRef,
398
+ support: typeof row.support === 'string' ? row.support : '',
399
+ requiredCheckCount: Number(row.required_check_count) > 0 ? Math.trunc(Number(row.required_check_count)) : 0,
400
+ observeId: typeof row.parent_observe_id === 'string' ? row.parent_observe_id : null,
401
+ disposition: row.disposition === 'unobserved' ? 'unobserved' : 'included',
402
+ lifecycle: row.lifecycle === 'expired' || row.lifecycle === 'completed' ? row.lifecycle : 'pending',
403
+ }
404
+ }
405
+
406
+ // 先放 Context 创建事件,再补只有结算/淘汰事件、没有创建行的极端情况。
407
+ for (const row of deduped) {
408
+ if (row.kind !== 'context') continue
409
+ const info = contextInfoFromRow(row)
410
+ if (info === null || contexts.has(info.contextId)) continue
411
+ contexts.set(info.contextId, info)
412
+ observeIds.set(info.contextId, info.observeId)
413
+ }
414
+ for (const row of deduped) {
415
+ if (row.kind !== 'expired' && row.kind !== 'capacity') continue
416
+ const info = contextInfoFromRow(row)
417
+ if (info === null || contexts.has(info.contextId)) continue
418
+ contexts.set(info.contextId, info)
419
+ observeIds.set(info.contextId, info.observeId)
420
+ }
421
+
422
+ for (const row of deduped) {
423
+ const id = typeof row.context_id === 'string' ? row.context_id : ''
424
+ if (id === '') continue
425
+ const seq = Number(row.attempt_seq)
426
+ if (Number.isFinite(seq)) seqs.set(id, Math.max(seqs.get(id) ?? 0, Math.trunc(seq)))
427
+
428
+ if (row.kind === 'capacity' || row.exclude_reason === 'capacity') capacityRows.add(id)
429
+ if (row.kind === 'expired' || row.lifecycle === 'expired') expired.add(id)
430
+
431
+ if (row.kind !== 'verify') continue
432
+ if (row.reason === 'late_verify') {
433
+ lateRows.push(row)
434
+ continue
435
+ }
436
+ if (row.verify_unusable_reason) {
437
+ const reason = VERIFY_UNUSABLE_REASONS.includes(row.verify_unusable_reason)
438
+ ? row.verify_unusable_reason
439
+ : 'exec_failed'
440
+ unusableRows.push({ ...row, verify_unusable_reason: reason })
441
+ continue
442
+ }
443
+ if (row.reason === 'unobserved_context' || row.reason === 'unlinked') continue
444
+ if (EFFECTIVE_STATUSES.has(row.status)) {
445
+ effectiveVerifyRows.push(row)
446
+ completed.add(id)
447
+ }
448
+ }
449
+
450
+ const terminal = new Set([...completed, ...expired])
451
+ for (const id of capacityRows) terminal.delete(id)
452
+ const unobserved = new Map()
453
+ for (const id of capacityRows) unobserved.set(id, 'capacity')
454
+ for (const [id, info] of contexts) {
455
+ if (unobserved.has(id)) continue
456
+ if (info.bootRef !== currentBootRef && !terminal.has(id)) {
457
+ unobserved.set(id, 'restart_not_observed')
458
+ }
459
+ }
460
+
461
+ return {
462
+ contexts,
463
+ observeById: observeIds,
464
+ capacityRows,
465
+ expired,
466
+ completed,
467
+ terminal,
468
+ unobserved,
469
+ effectiveVerifyRows,
470
+ unusableRows,
471
+ lateRows,
472
+ seqByContext: seqs,
473
+ }
474
+ }
475
+
476
+ function makeEvent({
477
+ kind,
478
+ contextId,
479
+ attemptSeq = 0,
480
+ lifecycle = 'pending',
481
+ disposition = 'included',
482
+ excludeReason = null,
483
+ support = null,
484
+ requiredCheckCount = null,
485
+ verifyUnusableReason = null,
486
+ status = null,
487
+ reason = null,
488
+ violationTypes = [],
489
+ parentObserveId = null,
490
+ eventTtlSeconds = ttl,
491
+ }) {
492
+ const ts = stamp(nowMs())
493
+ const eventId = `evt_${shortHash(`${contextId}|${kind}|${attemptSeq}|${ts}`)}`
494
+ return pickEvent({
495
+ ts,
496
+ boot_ref: currentBootRef,
497
+ session_ref: sessionRef,
498
+ event_id: eventId,
499
+ kind,
500
+ context_id: contextId,
501
+ parent_observe_id: parentObserveId,
502
+ lifecycle,
503
+ disposition,
504
+ exclude_reason: excludeReason,
505
+ support,
506
+ required_check_count: requiredCheckCount,
507
+ verify_unusable_reason: verifyUnusableReason,
508
+ status,
509
+ reason,
510
+ violation_types: violationTypes,
511
+ attempt_seq: attemptSeq,
512
+ ttl_seconds: eventTtlSeconds,
513
+ })
514
+ }
515
+
516
+ function appendEvent(event) {
517
+ try {
518
+ store.append(event)
519
+ warned = false
520
+ } catch (error) {
521
+ // 账本是旁路。写不进去就留在内存 pending 里,绝不影响工具返回值。
522
+ warnOnce(error)
523
+ store.invalidate()
524
+ }
525
+ return event
526
+ }
527
+
528
+ function settleExpired() {
529
+ const current = nowMs()
530
+ for (const [contextId, info] of [...pending.entries()]) {
531
+ if (current - info.createdAt < info.ttlSeconds * 1000) continue
532
+ pending.delete(contextId)
533
+ expiredContexts.add(contextId)
534
+ appendEvent(makeEvent({
535
+ kind: 'expired',
536
+ contextId,
537
+ attemptSeq: info.attemptSeq,
538
+ lifecycle: 'expired',
539
+ disposition: 'included',
540
+ reason: 'ttl',
541
+ support: info.support,
542
+ requiredCheckCount: info.requiredCheckCount,
543
+ parentObserveId: info.observeId,
544
+ eventTtlSeconds: info.ttlSeconds,
545
+ }))
546
+ }
547
+ }
548
+
549
+ function evictCapacity() {
550
+ while (pending.size > maxPending) {
551
+ const oldest = pending.keys().next()
552
+ if (oldest.done) break
553
+ const contextId = oldest.value
554
+ const info = pending.get(contextId)
555
+ pending.delete(contextId)
556
+ capacityContexts.add(contextId)
557
+ appendEvent(makeEvent({
558
+ kind: 'capacity',
559
+ contextId,
560
+ attemptSeq: info.attemptSeq,
561
+ lifecycle: 'pending',
562
+ disposition: 'unobserved',
563
+ excludeReason: 'capacity',
564
+ reason: 'capacity',
565
+ support: info.support,
566
+ requiredCheckCount: info.requiredCheckCount,
567
+ parentObserveId: info.observeId,
568
+ eventTtlSeconds: info.ttlSeconds,
569
+ }))
570
+ }
571
+ }
572
+
573
+ function recordContext(value, cycle = cycleRef) {
574
+ if (!on || cycle !== cycleRef) return null
575
+ settleExpired()
576
+ if (value === null || typeof value !== 'object' || value.kind !== 'context') return null
577
+ const contextId = typeof value.context_id === 'string' ? value.context_id : ''
578
+ if (contextId === '') return null
579
+
580
+ const checks = buildRequiredChecks(value)
581
+ const observeId = typeof value.observe_id === 'string' ? value.observe_id : null
582
+ const attemptSeq = Math.max(0, (seqByContext.get(contextId) ?? -1) + 1)
583
+ seqByContext.set(contextId, attemptSeq)
584
+ contextIds.add(contextId)
585
+ observeById.set(contextId, observeId)
586
+
587
+ const event = appendEvent(makeEvent({
588
+ kind: 'context',
589
+ contextId,
590
+ attemptSeq,
591
+ lifecycle: 'pending',
592
+ disposition: 'included',
593
+ support: checks.support,
594
+ requiredCheckCount: checks.count,
595
+ parentObserveId: observeId,
596
+ eventTtlSeconds: ttl,
597
+ }))
598
+
599
+ pending.set(contextId, {
600
+ createdAt: nowMs(),
601
+ ttlSeconds: ttl,
602
+ attemptSeq,
603
+ support: checks.support,
604
+ requiredCheckCount: checks.count,
605
+ observeId,
606
+ })
607
+ evictCapacity()
608
+ return event
609
+ }
610
+
611
+ function recordVerify(contextId, value, cycle = cycleRef) {
612
+ if (!on || cycle !== cycleRef) return null
613
+ if (typeof contextId !== 'string' || contextId === '') return null
614
+ settleExpired()
615
+
616
+ const scan = scanRows(store.readAllRows())
617
+ const status = typeof value?.status === 'string' ? value.status : ''
618
+ const effective = EFFECTIVE_STATUSES.has(status)
619
+ const unusableReason = effective
620
+ ? null
621
+ : (VERIFY_UNUSABLE_REASONS.includes(status) ? status : 'exec_failed')
622
+ const eventStatus = effective ? status : unusableReason
623
+ const violationTypes = asArray(value?.violations)
624
+ .map((item) => (item && typeof item === 'object' ? item.type ?? item.rule : null))
625
+ .filter((type) => typeof type === 'string' && RULE_FAMILIES.includes(type))
626
+
627
+ const seqBase = Math.max(seqByContext.get(contextId) ?? 0, scan.seqByContext.get(contextId) ?? 0)
628
+ const attemptSeq = seqBase + 1
629
+ seqByContext.set(contextId, attemptSeq)
630
+
631
+ const hasContext = scan.contexts.has(contextId) || contextIds.has(contextId)
632
+ const isExpired = scan.expired.has(contextId) || expiredContexts.has(contextId)
633
+ const isUnobserved = scan.unobserved.has(contextId)
634
+ const observeId = scan.observeById.get(contextId)
635
+ ?? observeById.get(contextId)
636
+ ?? pending.get(contextId)?.observeId
637
+ ?? null
638
+ const support = scan.contexts.get(contextId)?.support ?? pending.get(contextId)?.support ?? null
639
+ const requiredCheckCount = scan.contexts.get(contextId)?.requiredCheckCount
640
+ ?? pending.get(contextId)?.requiredCheckCount
641
+ ?? 0
642
+ const eventTtlSeconds = pending.get(contextId)?.ttlSeconds ?? ttl
643
+
644
+ let reason = null
645
+ if (isExpired && effective) reason = 'late_verify'
646
+ else if (!effective) reason = 'verify_unusable'
647
+ else if (isUnobserved) reason = 'unobserved_context'
648
+ else if (!hasContext) reason = 'unlinked'
649
+
650
+ const lifecycle = isExpired
651
+ ? 'expired'
652
+ : effective
653
+ ? 'completed'
654
+ : scan.terminal.has(contextId)
655
+ ? (scan.expired.has(contextId) ? 'expired' : 'completed')
656
+ : 'pending'
657
+ const disposition = isUnobserved ? 'unobserved' : 'included'
658
+ const excludeReason = isUnobserved ? scan.unobserved.get(contextId) ?? null : null
659
+
660
+ const event = appendEvent(makeEvent({
661
+ kind: 'verify',
662
+ contextId,
663
+ attemptSeq,
664
+ lifecycle,
665
+ disposition,
666
+ excludeReason,
667
+ support,
668
+ requiredCheckCount,
669
+ verifyUnusableReason: unusableReason,
670
+ status: eventStatus,
671
+ reason,
672
+ violationTypes,
673
+ parentObserveId: observeId,
674
+ eventTtlSeconds,
675
+ }))
676
+
677
+ if (effective && !isExpired && !isUnobserved && hasContext && pending.has(contextId)) {
678
+ pending.delete(contextId)
679
+ }
680
+ return event
681
+ }
682
+
683
+ function stats({ days = 7 } = {}) {
684
+ if (!on) return disabledStats(days)
685
+ settleExpired()
686
+ const daysNum = clampDays(days)
687
+ const cutoff = nowMs() - daysNum * 86400000
688
+ const scan = scanRows(store.readAllRows())
689
+
690
+ // 文件写失败时,当前进程仍要看得见内存里的 pending。
691
+ for (const [contextId, info] of pending.entries()) {
692
+ if (scan.contexts.has(contextId)) continue
693
+ scan.contexts.set(contextId, {
694
+ contextId,
695
+ ts: stamp(info.createdAt),
696
+ bootRef: currentBootRef,
697
+ support: info.support,
698
+ requiredCheckCount: info.requiredCheckCount,
699
+ observeId: info.observeId,
700
+ disposition: 'included',
701
+ lifecycle: 'pending',
702
+ })
703
+ scan.observeById.set(contextId, info.observeId)
704
+ }
705
+
706
+ function inWindow(row) {
707
+ const parsed = Date.parse(String(row?.ts ?? ''))
708
+ return Number.isFinite(parsed) ? parsed >= cutoff : true
709
+ }
710
+
711
+ const contextEntries = [...scan.contexts.values()].filter(inWindow)
712
+ const unobservedInWindow = contextEntries.filter((info) => scan.unobserved.has(info.contextId))
713
+ const includedContexts = contextEntries.filter((info) => !scan.unobserved.has(info.contextId))
714
+ const requiredContexts = includedContexts.filter((info) => info.requiredCheckCount > 0)
715
+ const groupContexts = requiredContexts.filter((info) => RISK_SUPPORTS.has(info.support))
716
+ const effectiveRows = scan.effectiveVerifyRows.filter(inWindow)
717
+ const effectiveByContext = new Set(effectiveRows.map((row) => row.context_id).filter(Boolean))
718
+ const unusableRows = scan.unusableRows.filter(inWindow)
719
+ const lateRows = scan.lateRows.filter(inWindow)
720
+
721
+ const triggerNumerator = requiredContexts.filter((info) => effectiveByContext.has(info.contextId)).length
722
+ const groupNumerator = groupContexts.filter((info) => effectiveByContext.has(info.contextId)).length
723
+ const discoveryNumerator = effectiveRows.filter((row) => row.status === 'violations_found').length
724
+ const coverageNumerator = includedContexts.filter((info) => scan.terminal.has(info.contextId)).length
725
+
726
+ const excludedContextSamples = { restart_not_observed: 0, capacity: 0 }
727
+ for (const info of unobservedInWindow) {
728
+ const reason = scan.unobserved.get(info.contextId)
729
+ if (reason === 'restart_not_observed') excludedContextSamples.restart_not_observed += 1
730
+ else if (reason === 'capacity') excludedContextSamples.capacity += 1
731
+ }
732
+ const excludedVerifyCalls = { context_missing: 0, context_expired: 0, context_corrupt: 0, exec_failed: 0 }
733
+ for (const row of unusableRows) {
734
+ const reason = row.verify_unusable_reason
735
+ if (Object.prototype.hasOwnProperty.call(excludedVerifyCalls, reason)) {
736
+ excludedVerifyCalls[reason] += 1
737
+ }
738
+ }
739
+
740
+ const triggerExcludedContexts = unobservedInWindow.filter((info) => info.requiredCheckCount > 0)
741
+ const groupExcludedContexts = triggerExcludedContexts.filter((info) => RISK_SUPPORTS.has(info.support))
742
+ const triggerReasons = triggerExcludedContexts.map((info) => scan.unobserved.get(info.contextId))
743
+ const coverageReasons = unobservedInWindow.map((info) => scan.unobserved.get(info.contextId))
744
+ const discoveryReasons = unusableRows
745
+ .map((row) => row.verify_unusable_reason)
746
+ .concat(lateRows.length > 0 ? ['late_verify'] : [])
747
+
748
+ const triggerMetric = metric(
749
+ triggerNumerator,
750
+ requiredContexts.length,
751
+ triggerExcludedContexts.length,
752
+ triggerReasons,
753
+ )
754
+ triggerMetric.groups = {
755
+ partial_insufficient: metric(
756
+ groupNumerator,
757
+ groupContexts.length,
758
+ groupExcludedContexts.length,
759
+ groupExcludedContexts.map((info) => scan.unobserved.get(info.contextId)),
760
+ ),
761
+ }
762
+
763
+ return {
764
+ state: 'ok',
765
+ observe_enabled: true,
766
+ window: { days: daysNum, since: stamp(cutoff) },
767
+ message: '',
768
+ metrics: {
769
+ required_check_verification_trigger_rate: triggerMetric,
770
+ effective_verify_violation_discovery_rate: metric(
771
+ discoveryNumerator,
772
+ effectiveRows.length,
773
+ unusableRows.length + lateRows.length,
774
+ discoveryReasons,
775
+ ),
776
+ observation_coverage: metric(
777
+ coverageNumerator,
778
+ contextEntries.length,
779
+ unobservedInWindow.length,
780
+ coverageReasons,
781
+ ),
782
+ },
783
+ assertion_measurement: {
784
+ state: 'unavailable',
785
+ assertion_count: null,
786
+ reason: 'contract_unavailable',
787
+ note: '冻结契约无法可靠计数;不写 0、不写推断值、不展示百分比',
788
+ },
789
+ convergence: computeConvergence(effectiveRows),
790
+ excluded: {
791
+ context_samples: excludedContextSamples,
792
+ verify_calls: excludedVerifyCalls,
793
+ late_verify: lateRows.length,
794
+ },
795
+ }
796
+ }
797
+
798
+ function clear() {
799
+ cycleRef += 1
800
+ pending.clear()
801
+ seqByContext.clear()
802
+ contextIds.clear()
803
+ observeById.clear()
804
+ expiredContexts.clear()
805
+ capacityContexts.clear()
806
+ try {
807
+ store.clear()
808
+ warned = false
809
+ } catch (error) {
810
+ warnOnce(error)
811
+ store.invalidate()
812
+ }
813
+ }
814
+
815
+ function setEnabled(next) {
816
+ const was = on
817
+ on = next !== false
818
+ if (was === false && on === true) {
819
+ // 重新开启 = 新观察周期。旧周期里还没落盘的异步事件一律作废。
820
+ cycleRef += 1
821
+ pending.clear()
822
+ seqByContext.clear()
823
+ contextIds.clear()
824
+ observeById.clear()
825
+ expiredContexts.clear()
826
+ capacityContexts.clear()
827
+ }
828
+ }
829
+
830
+ const initial = scanRows(store.readAllRows())
831
+ for (const [id, seq] of initial.seqByContext) seqByContext.set(id, seq)
832
+ for (const id of initial.contexts.keys()) contextIds.add(id)
833
+ for (const [id, value] of initial.observeById) observeById.set(id, value)
834
+ for (const id of initial.expired) expiredContexts.add(id)
835
+ for (const id of initial.capacityRows) capacityContexts.add(id)
836
+
837
+ return {
838
+ recordContext,
839
+ recordVerify,
840
+ stats,
841
+ governanceStats: stats,
842
+ setEnabled,
843
+ enabled: () => on,
844
+ clear,
845
+ pendingSize: () => pending.size,
846
+ cycle: () => cycleRef,
847
+ bootRef: () => currentBootRef,
848
+ }
849
+ }