dsh-sixlayer-memory 0.0.0-stage → 2.0.3

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 (92) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/README.md +292 -3
  3. package/catalog/.index.json +111704 -0
  4. package/catalog/parts.json +8808 -0
  5. package/cordis.patch.yml +8 -0
  6. package/docs/DETAIL.md +1 -0
  7. package/docs/DETAIL.zh.md +1 -0
  8. package/docs/preview.svg +51 -0
  9. package/docs//347/224/237/345/221/275/345/221/250/346/234/237-/350/207/252/345/212/250/345/217/254/345/233/236/344/270/216/345/200/231/351/200/211.md +103 -0
  10. package/icon.svg +8 -0
  11. package/lib/client.js +1209 -0
  12. package/lib/index.js +741 -0
  13. package/lib/memory/affect-alert.js +60 -0
  14. package/lib/memory/affect-events.js +201 -0
  15. package/lib/memory/affect-report.js +61 -0
  16. package/lib/memory/api.js +194 -0
  17. package/lib/memory/crypto.js +68 -0
  18. package/lib/memory/detail.js +43 -0
  19. package/lib/memory/embed.js +394 -0
  20. package/lib/memory/emotion.js +99 -0
  21. package/lib/memory/explain.js +207 -0
  22. package/lib/memory/importer.js +215 -0
  23. package/lib/memory/inject.js +193 -0
  24. package/lib/memory/ledger.js +101 -0
  25. package/lib/memory/lifecycle.js +491 -0
  26. package/lib/memory/notify.js +164 -0
  27. package/lib/memory/policy.js +182 -0
  28. package/lib/memory/qq-official.js +196 -0
  29. package/lib/memory/qq.js +326 -0
  30. package/lib/memory/recorder.js +241 -0
  31. package/lib/memory/redact.js +120 -0
  32. package/lib/memory/scanners.js +142 -0
  33. package/lib/memory/schema.js +205 -0
  34. package/lib/memory/service-plugin.js +69 -0
  35. package/lib/memory/service.js +123 -0
  36. package/lib/memory/shadow.js +133 -0
  37. package/lib/memory/store.js +1138 -0
  38. package/lib/memory/timeline.js +74 -0
  39. package/lib/memory/tokenize.js +66 -0
  40. package/lib/memory/tools.js +1371 -0
  41. package/lib/memory/util.js +129 -0
  42. package/lib/parts/index.js +154 -0
  43. package/lib/parts/installer.js +294 -0
  44. package/lib/parts/jobs.js +91 -0
  45. package/lib/parts/library.js +91 -0
  46. package/lib/probe-plugin.js +38 -0
  47. package/lib/voice/board-asr.js +31 -0
  48. package/locale/en.json +7 -0
  49. package/locale/zh.json +7 -0
  50. package/package.json +114 -3
  51. package/tools/backfill-affect.mjs +82 -0
  52. package/tools/eval.mjs +88 -0
  53. package/tools/p1.mjs +108 -0
  54. package/tools/p10.mjs +36 -0
  55. package/tools/p11.mjs +51 -0
  56. package/tools/p12.mjs +53 -0
  57. package/tools/p13.mjs +65 -0
  58. package/tools/p14.mjs +66 -0
  59. package/tools/p15.mjs +43 -0
  60. package/tools/p16.mjs +42 -0
  61. package/tools/p17.mjs +29 -0
  62. package/tools/p18.mjs +48 -0
  63. package/tools/p19.mjs +50 -0
  64. package/tools/p2.mjs +59 -0
  65. package/tools/p20.mjs +54 -0
  66. package/tools/p21.mjs +42 -0
  67. package/tools/p22.mjs +32 -0
  68. package/tools/p23.mjs +43 -0
  69. package/tools/p24.mjs +40 -0
  70. package/tools/p25.mjs +151 -0
  71. package/tools/p26.mjs +113 -0
  72. package/tools/p27.mjs +89 -0
  73. package/tools/p28.mjs +60 -0
  74. package/tools/p3.mjs +54 -0
  75. package/tools/p4.mjs +73 -0
  76. package/tools/p5.mjs +117 -0
  77. package/tools/p6.mjs +122 -0
  78. package/tools/p8.mjs +50 -0
  79. package/tools/p9.mjs +35 -0
  80. package/tools/phase2.mjs +159 -0
  81. package/tools/preflight.mjs +320 -0
  82. package/tools/push-via-api.mjs +187 -0
  83. package/tools/quarterly.mjs +129 -0
  84. package/tools/refresh-catalog.mjs +60 -0
  85. package/tools/register-bundle.mjs +38 -0
  86. package/tools/review.mjs +156 -0
  87. package/tools/selfcheck.mjs +80 -0
  88. package/tools/smoke.mjs +112 -0
  89. package/tools/testset-v1.json +70 -0
  90. package/tools/validate-tools.mjs +150 -0
  91. package/tools/verify-all.mjs +39 -0
  92. package/tools/write-chain.mjs +139 -0
@@ -0,0 +1,1138 @@
1
+ /**
2
+ * store.js — 六层记忆库:打开/迁移/写入链/检索/评分/审核/不变量/快照。
3
+ *
4
+ * 设计约束(来自方案):
5
+ * - 只增不删:本文件不提供物理删除;archive 只是改 layer/depth(二期)。
6
+ * - 失败即显式:低价值不落库要说出原因,降级要说清理由,不伪造数据。
7
+ * - 写入不静默覆盖:重复内容返回既有 record_id(dedup),疑似冲突标记后交调用方。
8
+ * - S 级不进自动召回;tainted 进隔离区;pending 需人工审核后才参与召回。
9
+ */
10
+ import fs from 'node:fs'
11
+ import path from 'node:path'
12
+ import { DatabaseSync } from 'node:sqlite'
13
+ import { DDL, SCHEMA_VERSION, MIGRATIONS } from './schema.js'
14
+ import { cryptoStatus as cryptoInfo, ensureKey, loadKey, isEncrypted, encryptText, decryptText } from './crypto.js'
15
+ import { normalizeContent, sha256, nowIso, nowUtc, ulid, ensureDir } from './util.js'
16
+ import { toIndexedText, toMatchQuery } from './tokenize.js'
17
+ import {
18
+ resolveTrust,
19
+ weakerTrust,
20
+ scan,
21
+ lowValueReason,
22
+ classifySAD,
23
+ similarity,
24
+ contradictionSuspect,
25
+ usageCaveat,
26
+ } from './policy.js'
27
+ import { Recorder } from './recorder.js'
28
+ import { LegacyImporter } from './importer.js'
29
+ import { LegacyIndex, shadowCompare } from './shadow.js'
30
+ import { analyzeAffect, initialImportance } from './emotion.js'
31
+
32
+ export const LAYERS = ['L0', 'L1', 'L2', 'L3', 'L4', 'L5']
33
+ export const SAD = ['S', 'A', 'D']
34
+ export const TRUST = ['trusted', 'unverified', 'tainted']
35
+ export const AUTHORITY = ['legacy', 'shadow', 'new']
36
+ export const REVIEW_DECISIONS = ['approve', 'reject', 'release']
37
+
38
+ /**
39
+ * 判定"说的是同一件事"的相似度阈值。
40
+ * 实测标定(lib/policy.js 的 bigram Jaccard):
41
+ * 结论相反的同话题句 0.438 · 同话题不同细节 0.636 · 同话题无关内容 0.190
42
+ * 取 0.35:把 0.438 这类"结论相反"捞出来,0.19 这类噪音挡在外面。
43
+ * 阈值偏低时只会多出"待审",不会误删——代价可控。
44
+ */
45
+ const SIMILARITY_THRESHOLD = 0.35
46
+
47
+ export class MemoryStore {
48
+ /**
49
+ * @param {{dataDir: string, authority?: string, snapshotIntervalMs?: number}} options
50
+ */
51
+ constructor(options) {
52
+ if (!options || !options.dataDir) throw new Error('MemoryStore: dataDir 必填')
53
+ this.dataDir = options.dataDir
54
+ this.dbDir = path.join(this.dataDir, 'db')
55
+ this.backupDir = path.join(this.dataDir, 'backup')
56
+ this.dbFile = path.join(this.dbDir, 'memory.db')
57
+ this.auditDir = path.join(this.dataDir, 'audit')
58
+ this.recorder = null
59
+ this.auditHealth = { ok: null, lines: 0, brokenAt: null }
60
+ this.authority = AUTHORITY.includes(options.authority) ? options.authority : 'shadow'
61
+ this.snapshotIntervalMs = options.snapshotIntervalMs ?? 24 * 60 * 60 * 1000
62
+ this.db = null
63
+ this.openedAt = null
64
+ }
65
+
66
+ // ---------- 生命周期 ----------
67
+
68
+ open() {
69
+ if (this.db) return this
70
+ ensureDir(this.dbDir)
71
+ ensureDir(this.backupDir)
72
+ ensureDir(path.join(this.dataDir, 'audit'))
73
+ ensureDir(path.join(this.dataDir, 'meta'))
74
+
75
+ this.db = new DatabaseSync(this.dbFile)
76
+ this.db.exec('PRAGMA journal_mode = WAL')
77
+ this.db.exec('PRAGMA synchronous = FULL')
78
+ this.db.exec('PRAGMA foreign_keys = ON')
79
+ this.db.exec(DDL)
80
+
81
+ const raw = this.getMeta('schema_version')
82
+ if (raw === null) {
83
+ this.setMeta('schema_version', String(SCHEMA_VERSION))
84
+ this.setMeta('created_at', nowIso())
85
+ } else {
86
+ const version = Number(raw)
87
+ if (!Number.isFinite(version)) throw new Error(`MemoryStore: schema_version 不是数字(${raw})`)
88
+ if (version > SCHEMA_VERSION) {
89
+ throw new Error(`MemoryStore: 库版本 v${version} 高于代码 v${SCHEMA_VERSION},请升级插件再打开(不做降级迁移)`)
90
+ }
91
+ if (version < SCHEMA_VERSION) this.migrate(version)
92
+ }
93
+ // batch_id 索引放在迁移之后建:旧库先 ALTER 加列,再建索引;新库直接建。
94
+ try {
95
+ this.db.exec('CREATE INDEX IF NOT EXISTS idx_records_batch ON records(batch_id)')
96
+ } catch {
97
+ /* 索引失败不阻断打开 */
98
+ }
99
+ if (this.getMeta('authority') === null) this.setMeta('authority', this.authority)
100
+
101
+ // 记录仪:JSONL 是 append-only 真源,traces 表是索引
102
+ this.recorder = new Recorder({
103
+ dir: this.auditDir,
104
+ onRecord: (payload, prev, hash) => {
105
+ try {
106
+ this.db
107
+ .prepare(
108
+ `INSERT OR REPLACE INTO traces (
109
+ trace_id, seq, at, op, principal_id, query_hash, query_preview, hits, injected,
110
+ tokens_in, tokens_out, duration_ms, prev_hash, hash
111
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
112
+ )
113
+ .run(
114
+ payload.trace_id,
115
+ payload.seq,
116
+ payload.at,
117
+ payload.op ?? 'unknown',
118
+ payload.principal_id ?? null,
119
+ payload.query_hash ?? null,
120
+ payload.query_preview ?? null,
121
+ JSON.stringify(payload.hits ?? []),
122
+ JSON.stringify(payload.injected ?? []),
123
+ payload.tokens_in ?? null,
124
+ payload.tokens_out ?? null,
125
+ payload.duration_ms ?? null,
126
+ prev,
127
+ hash,
128
+ )
129
+ } catch {
130
+ /* 索引写失败不影响审计 */
131
+ }
132
+ },
133
+ }).open()
134
+
135
+ // 启动体检:只校验最后一行与状态是否一致(全量校验走 mem_audit --deep)
136
+ this.auditHealth = this.recorder.verify({ deep: false })
137
+
138
+ this.openedAt = nowUtc()
139
+ this.maybeSnapshot()
140
+ return this
141
+ }
142
+
143
+ /** 逐版本升级;ADD COLUMN 不幂等,所以先查 pragma 再执行。 */
144
+ migrate(from) {
145
+ for (let v = from + 1; v <= SCHEMA_VERSION; v += 1) {
146
+ const steps = MIGRATIONS[v]
147
+ if (!steps) throw new Error(`MemoryStore: 缺少 v${v} 的迁移脚本`)
148
+ for (const step of steps) {
149
+ const cols = this.db.prepare(`PRAGMA table_info(${step.table})`).all().map((c) => c.name)
150
+ if (!cols.includes(step.column)) this.db.exec(step.sql)
151
+ }
152
+ this.setMeta('schema_version', String(v))
153
+ this.setMeta(`migrated_to_v${v}_at`, nowIso())
154
+ }
155
+ }
156
+
157
+ close() {
158
+ if (!this.db) return
159
+ try {
160
+ this.db.exec('PRAGMA wal_checkpoint(TRUNCATE)')
161
+ } catch {
162
+ /* 忽略:关闭阶段不允许抛 */
163
+ }
164
+ this.db.close()
165
+ this.db = null
166
+ }
167
+
168
+ // ---------- meta ----------
169
+
170
+ getMeta(key) {
171
+ const row = this.db.prepare('SELECT value FROM meta WHERE key = ?').get(key)
172
+ return row ? row.value : null
173
+ }
174
+
175
+ setMeta(key, value) {
176
+ this.db.prepare('INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, String(value))
177
+ }
178
+
179
+ // ---------- 权限/权威开关 ----------
180
+
181
+ getAuthority() {
182
+ return this.getMeta('authority') ?? this.authority
183
+ }
184
+
185
+ setAuthority(value) {
186
+ if (!AUTHORITY.includes(value)) throw new Error(`authority 只能是 ${AUTHORITY.join(' / ')}`)
187
+ this.setMeta('authority', value)
188
+ this.setMeta('authority_changed_at', nowIso())
189
+ return value
190
+ }
191
+
192
+ // ---------- 写入 ----------
193
+
194
+ /**
195
+ * 写入一条记忆(方案 §14 的 a–h)。
196
+ *
197
+ * 顺序:信任判定 → 投毒扫描 → 沉淀前决策 → 分级 → 去重 → 冲突/矛盾 → 落库(含待审标记)。
198
+ * 不抛"业务拒绝",用返回值说清楚:skipped / dedup / conflict / contradiction。
199
+ */
200
+ write(input) {
201
+ const t0 = Date.now()
202
+ const result = this._writeInternal(input)
203
+ this._trace({
204
+ op: result.dedup ? 'write.dedup' : result.skipped ? 'write.skipped' : 'write',
205
+ record_id: result.record_id ?? '',
206
+ layer: result.layer,
207
+ sad_level: result.sad_level,
208
+ trust_level: result.trust_level,
209
+ status: result.status,
210
+ dedup: result.dedup,
211
+ skipped: result.skipped,
212
+ scanned: result.scanned ?? [],
213
+ principal_id: input?.identityId ?? input?.principalId ?? null,
214
+ duration_ms: Date.now() - t0,
215
+ })
216
+ return result
217
+ }
218
+
219
+ _trace(fields) {
220
+ try {
221
+ return this.recorder?.record(fields) ?? null
222
+ } catch {
223
+ return null
224
+ }
225
+ }
226
+
227
+ /**
228
+ * 公开记录入口:给注入器等外部模块写审计用(P2 修)。
229
+ * 之前 inject.js 调的是 store.record(),但本类没有这个方法 —— 注入审计一直在静默丢失。
230
+ */
231
+ record(fields) {
232
+ return this._trace(fields ?? {})
233
+ }
234
+
235
+ _writeInternal(input) {
236
+ const content = normalizeContent(input.content ?? '')
237
+ if (!content) throw new Error('write: content 不能为空')
238
+ if (content.length > 200_000) throw new Error('write: content 超过 200k 字符,请先摘要')
239
+
240
+ const layer = LAYERS.includes(input.layer) ? input.layer : 'L2'
241
+ const sourceChannel = input.sourceChannel ?? input.source_channel ?? 'unknown'
242
+ const identityId = input.identityId ?? input.identity_id ?? (input.principalId ? 'owner' : 'agent')
243
+ const hash = sha256(content)
244
+
245
+ // a. 信任判定:通道 × 身份;显式传入优先(但不会高于 trusted)
246
+ let trustLevel = TRUST.includes(input.trustLevel)
247
+ ? input.trustLevel
248
+ : resolveTrust({ channel: sourceChannel, principalId: identityId })
249
+
250
+ // b. 投毒扫描
251
+ const scanned = scan(content)
252
+ if (scanned.injection.length > 0) trustLevel = weakerTrust(trustLevel, 'tainted')
253
+
254
+ // c. 沉淀前决策:低价值不落库(用户显式写入永远保留;显式调用也保留)
255
+ const skipReason = input.explicit === true ? null : lowValueReason(content, sourceChannel)
256
+ if (skipReason) {
257
+ return {
258
+ record_id: null,
259
+ dedup: false,
260
+ skipped: true,
261
+ reason: skipReason,
262
+ layer,
263
+ sad_level: 'A',
264
+ trust_level: trustLevel,
265
+ status: 'skipped',
266
+ conflict: false,
267
+ conflict_of: null,
268
+ contradiction: false,
269
+ scanned: scanned.flags,
270
+ }
271
+ }
272
+
273
+ // e. 去重:内容寻址
274
+ const existing = this.db
275
+ .prepare("SELECT * FROM records WHERE content_hash = ? AND status != 'quarantined' LIMIT 1")
276
+ .get(hash)
277
+ if (existing) {
278
+ return {
279
+ record_id: existing.record_id,
280
+ dedup: true,
281
+ skipped: false,
282
+ reason: '',
283
+ layer: existing.layer,
284
+ sad_level: existing.sad_level,
285
+ trust_level: existing.trust_level,
286
+ status: existing.status,
287
+ conflict: Boolean(existing.conflict_of),
288
+ conflict_of: existing.conflict_of ?? null,
289
+ contradiction: false,
290
+ scanned: scanned.flags,
291
+ }
292
+ }
293
+
294
+ // f. 分级
295
+ const sadLevel = classifySAD({ flags: scanned.flags, explicit: input.sadLevel })
296
+
297
+ // g. 冲突与矛盾:同项目同层里"说的是同一件事"的既有记录
298
+ const candidates = this.db
299
+ .prepare(
300
+ `SELECT record_id, content FROM records
301
+ WHERE layer = ? AND status IN ('active','pending')
302
+ AND (project_id IS ? OR project_id = ?)
303
+ ORDER BY created_at DESC LIMIT 50`,
304
+ )
305
+ .all(layer, input.projectId ?? null, input.projectId ?? null)
306
+
307
+ let conflictOf = null
308
+ let contradiction = false
309
+ for (const row of candidates) {
310
+ const sim = similarity(content, row.content)
311
+ if (sim >= SIMILARITY_THRESHOLD) {
312
+ if (conflictOf === null) conflictOf = row.record_id
313
+ if (contradictionSuspect(content, row.content)) contradiction = true
314
+ }
315
+ if (conflictOf !== null && contradiction) break
316
+ }
317
+
318
+ // h. 状态:投毒→隔离;未验证来源→过闸门待审;疑似矛盾→待审;其余→active
319
+ const origin = input.origin ?? 'manual'
320
+ const batchId = input.batchId ?? input.batch_id ?? input.sessionId ?? null
321
+ const tainted = trustLevel === 'tainted'
322
+ let status = tainted ? 'quarantined' : 'active'
323
+ let pendingReview = 0
324
+ let reviewReason = 'contradiction-suspect'
325
+ // 闸门公理(P1):只有用户亲手输入、或已在闸门确认过的才可信。
326
+ // 旧记忆导入是用户自己的数据,不重复过闸;其余非用户直输一律先审后入。
327
+ if (!tainted && trustLevel !== 'trusted' && sourceChannel !== 'user' && origin !== 'legacy_import') {
328
+ status = 'pending'
329
+ pendingReview = 1
330
+ reviewReason = 'unverified-source'
331
+ }
332
+ if (contradiction && !tainted) {
333
+ status = 'pending'
334
+ pendingReview = 1
335
+ if (reviewReason !== 'unverified-source') reviewReason = 'contradiction-suspect'
336
+ }
337
+
338
+ const recordId = ulid()
339
+ const now = nowIso()
340
+ const summary = input.summary ?? content.slice(0, 120).replace(/\s+/g, ' ')
341
+ // 认知层:写入时算一次情绪;重要性用情绪 + 层级给初值,后续 beta 继续修正
342
+ const affect = analyzeAffect(content)
343
+ const importance = initialImportance(affect, layer)
344
+
345
+ this.db
346
+ .prepare(
347
+ `INSERT INTO records (
348
+ record_id, layer, depth, content, summary, content_hash, sad_level, trust_level,
349
+ source_channel, origin, principal_id, identity_id, project_id, session_id,
350
+ alpha, beta, scored, status, pending_review, conflict_of, scan_result,
351
+ legacy_ref, legacy_source, batch_id, affect_label, affect_valence, affect_arousal,
352
+ importance, created_at, updated_at
353
+ ) VALUES (?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
354
+ )
355
+ .run(
356
+ recordId,
357
+ layer,
358
+ content,
359
+ summary,
360
+ hash,
361
+ sadLevel,
362
+ trustLevel,
363
+ sourceChannel,
364
+ origin,
365
+ input.principalId ?? null,
366
+ identityId,
367
+ input.projectId ?? null,
368
+ input.sessionId ?? null,
369
+ status,
370
+ pendingReview,
371
+ conflictOf,
372
+ JSON.stringify(scanned),
373
+ input.legacyRef ?? null,
374
+ input.legacySource ?? null,
375
+ batchId,
376
+ affect.label,
377
+ affect.valence,
378
+ affect.arousal,
379
+ importance,
380
+ now,
381
+ now,
382
+ )
383
+
384
+ this.db.prepare('INSERT INTO records_fts(record_id, body) VALUES(?, ?)').run(recordId, toIndexedText(`${summary}\n${content}`))
385
+
386
+ for (const tag of Array.isArray(input.tags) ? input.tags : []) {
387
+ this.db.prepare('INSERT OR IGNORE INTO tags(record_id, tag) VALUES(?, ?)').run(recordId, String(tag))
388
+ }
389
+
390
+ if (pendingReview === 1) {
391
+ this.db
392
+ .prepare('INSERT OR REPLACE INTO review_queue(record_id, reason, created_at) VALUES(?, ?, ?)')
393
+ .run(recordId, reviewReason, now)
394
+ }
395
+
396
+ return {
397
+ record_id: recordId,
398
+ dedup: false,
399
+ skipped: false,
400
+ reason: '',
401
+ layer,
402
+ sad_level: sadLevel,
403
+ trust_level: trustLevel,
404
+ status,
405
+ conflict: conflictOf !== null,
406
+ conflict_of: conflictOf,
407
+ contradiction,
408
+ scanned: scanned.flags,
409
+ }
410
+ }
411
+
412
+ // ---------- 评分(非阻塞) ----------
413
+
414
+ /**
415
+ * 补评 α(0.01–1)与 β(0–1)。未评分的记录可以召回,但注入时带"未评分"标记(方案 §15)。
416
+ */
417
+ judge(recordId, { alpha, beta } = {}) {
418
+ const row = this.db.prepare('SELECT record_id, alpha, beta FROM records WHERE record_id = ?').get(recordId)
419
+ if (!row) throw new Error(`judge: 没有记录 ${recordId}`)
420
+ const a = alpha === undefined || alpha === null ? row.alpha : Number(alpha)
421
+ const b = beta === undefined || beta === null ? row.beta : Number(beta)
422
+ if (a !== null && (!Number.isFinite(a) || a < 0.01 || a > 1)) throw new Error('judge: alpha 必须在 0.01–1 之间')
423
+ if (b !== null && (!Number.isFinite(b) || b < 0 || b > 1)) throw new Error('judge: beta 必须在 0–1 之间')
424
+ if (a === null && b === null) throw new Error('judge: alpha / beta 至少要给一个')
425
+
426
+ this.db
427
+ .prepare('UPDATE records SET alpha = ?, beta = ?, scored = 1, updated_at = ? WHERE record_id = ?')
428
+ .run(a, b, nowIso(), recordId)
429
+ return { record_id: recordId, alpha: a, beta: b, scored: true }
430
+ }
431
+
432
+ // ---------- 审核(隔离区/待审区的出口) ----------
433
+
434
+ /**
435
+ * 审核并给出决定。没有出口的隔离区会变成垃圾场(方案自评里点过这条)。
436
+ * approve / release → active;reject → rejected(保留正文,不物理删除)。
437
+ */
438
+ review(recordId, decision, note = null) {
439
+ if (!REVIEW_DECISIONS.includes(decision)) throw new Error(`review: decision 只能是 ${REVIEW_DECISIONS.join(' / ')}`)
440
+ const row = this.db.prepare('SELECT record_id, status FROM records WHERE record_id = ?').get(recordId)
441
+ if (!row) throw new Error(`review: 没有记录 ${recordId}`)
442
+ const status = decision === 'reject' ? 'rejected' : 'active'
443
+ const now = nowIso()
444
+ // 闸门裁决即确认(P1 公理 2):approve / release 把来源信任升为 trusted,
445
+ // reject 保持原信任等级但状态转 rejected(保留正文,不物理删除)。
446
+ if (decision === 'reject') {
447
+ this.db
448
+ .prepare('UPDATE records SET status = ?, pending_review = 0, updated_at = ? WHERE record_id = ?')
449
+ .run(status, now, recordId)
450
+ } else {
451
+ this.db
452
+ .prepare("UPDATE records SET status = ?, pending_review = 0, trust_level = 'trusted', updated_at = ? WHERE record_id = ?")
453
+ .run(status, now, recordId)
454
+ }
455
+ this.db
456
+ .prepare(
457
+ `INSERT INTO review_queue(record_id, reason, created_at, decided_at, decision, note)
458
+ VALUES(?, ?, ?, ?, ?, ?)
459
+ ON CONFLICT(record_id) DO UPDATE SET decided_at = excluded.decided_at,
460
+ decision = excluded.decision, note = excluded.note`,
461
+ )
462
+ .run(recordId, 'manual-review', now, now, decision, note)
463
+ return { record_id: recordId, status, decision }
464
+ }
465
+
466
+ // ---------- 场景交接(源自 luanyujia-workbench 的记忆机制) ----------
467
+
468
+ /**
469
+ * 覆盖写一个场景的「§〇 交接」。
470
+ * 规则(与 workbench 一致):
471
+ * - 只留最新一份,覆盖不追加;
472
+ * - ≤ 4 KB,超了说明在写过程而不是写结论;
473
+ * - 五小节固定键:last / projects / changes / next / blockers。
474
+ */
475
+ handoffWrite({ scene, title = null, sections, updatedBy = null } = {}) {
476
+ const key = String(scene ?? '').trim()
477
+ if (!key) throw new Error('handoffWrite: scene 不能为空')
478
+ const allow = ['last', 'projects', 'changes', 'next', 'blockers']
479
+ const clean = {}
480
+ for (const k of allow) {
481
+ const v = sections?.[k]
482
+ if (v !== undefined && v !== null && String(v).trim() !== '') clean[k] = String(v)
483
+ }
484
+ if (Object.keys(clean).length === 0) throw new Error('handoffWrite: 至少写一个小节')
485
+ const json = JSON.stringify(clean)
486
+ const bytes = Buffer.byteLength(json, 'utf8')
487
+ if (bytes > 4096) {
488
+ throw new Error(`handoffWrite: 交接 ${bytes} 字节,超过 4096 上限(只留结论与指针,历史搬归档)`)
489
+ }
490
+ const now = nowIso()
491
+ this.db
492
+ .prepare(
493
+ `INSERT INTO handoffs (scene, title, sections, bytes, updated_at, updated_by)
494
+ VALUES (?, ?, ?, ?, ?, ?)
495
+ ON CONFLICT(scene) DO UPDATE SET
496
+ title = excluded.title, sections = excluded.sections, bytes = excluded.bytes,
497
+ updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
498
+ )
499
+ .run(key, title, json, bytes, now, updatedBy)
500
+ this._trace({ op: 'handoff', scene: key, bytes })
501
+ return { scene: key, bytes, updated_at: now, sections: clean }
502
+ }
503
+
504
+ handoffRead(scene) {
505
+ const row = this.db.prepare('SELECT * FROM handoffs WHERE scene = ?').get(String(scene ?? ''))
506
+ if (!row) return null
507
+ return { ...row, sections: JSON.parse(row.sections) }
508
+ }
509
+
510
+ handoffList() {
511
+ return this.db
512
+ .prepare('SELECT scene, title, bytes, updated_at, updated_by FROM handoffs ORDER BY updated_at DESC')
513
+ .all()
514
+ }
515
+
516
+ /**
517
+ * 体量体检:把 workbench 的红线落到库上。
518
+ * 交接 ≤4 KB;场景记忆(该项目下记录正文总和)≤25 KB;待审 ≤20;审计链一致。
519
+ */
520
+ checkBudgets(scene = null) {
521
+ const items = []
522
+ const handoffs = scene
523
+ ? this.db.prepare('SELECT scene, bytes FROM handoffs WHERE scene = ?').all(String(scene))
524
+ : this.db.prepare('SELECT scene, bytes FROM handoffs').all()
525
+ for (const h of handoffs) {
526
+ items.push({ name: '交接 ' + h.scene, value: h.bytes, limit: 4096, ok: h.bytes <= 4096 })
527
+ }
528
+ if (scene) {
529
+ const size = this.db
530
+ .prepare('SELECT COALESCE(SUM(length(content)), 0) n FROM records WHERE project_id = ?')
531
+ .get(String(scene)).n
532
+ items.push({ name: '场景记忆 ' + scene, value: size, limit: 25600, ok: size <= 25600 })
533
+ }
534
+ const pending = this.db.prepare('SELECT COUNT(*) n FROM review_queue WHERE decision IS NULL').get().n
535
+ items.push({ name: '待审积压', value: pending, limit: 20, ok: pending <= 20 })
536
+ const chainOk = this.auditHealth?.ok !== false
537
+ items.push({ name: '审计链', value: chainOk ? 1 : 0, limit: 1, ok: chainOk })
538
+ return { ok: items.every((i) => i.ok), items }
539
+ }
540
+
541
+ // ---------- 派单台账(协作/派单机制) ----------
542
+
543
+ /**
544
+ * 建一条派单或公告。
545
+ * - dispatch:要对方动手,四件套(现象/照哪做/怎么验/回一句)缺一不可;
546
+ * - notice:只落盘知悉,不要求四件套。
547
+ */
548
+ dispatchCreate({ kind = 'dispatch', from, to, title, phenomenon, howTo, howVerify, needReply = true, deadlineMinutes = 1440 } = {}) {
549
+ const k = kind === 'notice' ? 'notice' : 'dispatch'
550
+ const f = String(from ?? '').trim()
551
+ const t = String(to ?? '').trim()
552
+ const ti = String(title ?? '').trim()
553
+ if (!f || !t) throw new Error('dispatchCreate: from / to 都不能为空')
554
+ if (!ti) throw new Error('dispatchCreate: title 不能为空')
555
+ if (k === 'dispatch') {
556
+ const missing = []
557
+ if (!String(phenomenon ?? '').trim()) missing.push('现象')
558
+ if (!String(howTo ?? '').trim()) missing.push('照哪做')
559
+ if (!String(howVerify ?? '').trim()) missing.push('怎么验')
560
+ if (missing.length) throw new Error(`dispatchCreate: 派单四件套缺 ${missing.join(' / ')}(缺一件对方就得追问)`)
561
+ }
562
+ const now = nowIso()
563
+ const id = ulid()
564
+ const mins = k === 'dispatch' ? Math.max(1, Number(deadlineMinutes) || 1440) : null
565
+ const deadline = k === 'dispatch' ? new Date(Date.now() + mins * 60000).toISOString() : null
566
+ this.db
567
+ .prepare(
568
+ `INSERT INTO tasks (task_id, kind, from_scene, to_scene, title, phenomenon, how_to, how_verify,
569
+ need_reply, status, messages, created_at, updated_at, deadline_at, ack_json)
570
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'sent', 1, ?, ?, ?, NULL)`,
571
+ )
572
+ .run(id, k, f, t, ti, phenomenon ?? null, howTo ?? null, howVerify ?? null, needReply ? 1 : 0, now, now, deadline)
573
+ this._trace({ op: k === 'dispatch' ? 'dispatch' : 'notice', task_id: id, from: f, to: t })
574
+ return this.taskGet(id)
575
+ }
576
+
577
+ /**
578
+ * 回执:接单方干完 / 卡住 / 干不了都要回,且必须带证据。
579
+ * 同一件事 ≤3 条消息(派单 + 回执 + 收尾知悉)。
580
+ */
581
+ taskReceipt({ taskId, conclusion, evidence, path, remaining } = {}) {
582
+ const row = this.db.prepare('SELECT * FROM tasks WHERE task_id = ?').get(String(taskId ?? ''))
583
+ if (!row) throw new Error('taskReceipt: 没有这条任务 ' + String(taskId))
584
+ if (row.messages >= 3) throw new Error('taskReceipt: 同一件事已 3 条消息(派单+回执+知悉),到上限了')
585
+ if (!String(conclusion ?? '').trim()) throw new Error('taskReceipt: 回执必须写结论')
586
+ if (!String(evidence ?? '').trim()) throw new Error('taskReceipt: 回执必须带证据(跑了什么 / 几条通过),只说"好了"等于没说')
587
+ const ack = {
588
+ conclusion: String(conclusion),
589
+ evidence: String(evidence),
590
+ path: path ? String(path) : null,
591
+ remaining: remaining ? String(remaining) : null,
592
+ }
593
+ const now = nowIso()
594
+ this.db
595
+ .prepare("UPDATE tasks SET status = 'acked', messages = messages + 1, ack_json = ?, updated_at = ? WHERE task_id = ?")
596
+ .run(JSON.stringify(ack), now, row.task_id)
597
+ this._trace({ op: 'receipt', task_id: row.task_id, to: row.from_scene })
598
+ return this.taskGet(row.task_id)
599
+ }
600
+
601
+ /** 状态推进:delivered / done / failed / closed。 */
602
+ taskMark({ taskId, status, actor = null } = {}) {
603
+ const allow = ['delivered', 'done', 'failed', 'closed']
604
+ if (!allow.includes(status)) throw new Error('taskMark: status 只能是 ' + allow.join(' / '))
605
+ const row = this.db.prepare('SELECT * FROM tasks WHERE task_id = ?').get(String(taskId ?? ''))
606
+ if (!row) throw new Error('taskMark: 没有这条任务 ' + String(taskId))
607
+ if (status === 'delivered' && row.status !== 'sent') throw new Error('taskMark: 只有 sent 可以标记为 delivered')
608
+ if (status === 'done' && row.status !== 'acked') throw new Error('taskMark: 只有 acked 可以销账为 done')
609
+ this.db
610
+ .prepare('UPDATE tasks SET status = ?, updated_at = ? WHERE task_id = ?')
611
+ .run(status, nowIso(), row.task_id)
612
+ this._trace({ op: 'task.' + status, task_id: row.task_id, actor })
613
+ return this.taskGet(row.task_id)
614
+ }
615
+
616
+ taskGet(taskId) {
617
+ const row = this.db.prepare('SELECT * FROM tasks WHERE task_id = ?').get(String(taskId ?? ''))
618
+ if (!row) return null
619
+ return { ...row, ack: row.ack_json ? JSON.parse(row.ack_json) : null }
620
+ }
621
+
622
+ /**
623
+ * 台账查询。scope:
624
+ * - outbound:我发出、还没回的(催对方)
625
+ * - inbound:别人发给我、我还没回的(我欠别人)
626
+ * - open:全部未办结
627
+ */
628
+ taskList({ scene = null, scope = 'open' } = {}) {
629
+ const now = Date.now()
630
+ let rows = []
631
+ if (scope === 'outbound') {
632
+ rows = this.db.prepare("SELECT * FROM tasks WHERE from_scene = ? AND status IN ('sent','delivered','overdue')").all(String(scene))
633
+ } else if (scope === 'inbound') {
634
+ rows = this.db.prepare("SELECT * FROM tasks WHERE to_scene = ? AND status IN ('sent','delivered','overdue')").all(String(scene))
635
+ } else if (scope === 'all') {
636
+ rows = this.db.prepare('SELECT * FROM tasks ORDER BY created_at DESC LIMIT 200').all()
637
+ } else {
638
+ rows = this.db.prepare("SELECT * FROM tasks WHERE status NOT IN ('done','closed','failed') ORDER BY created_at DESC LIMIT 200").all()
639
+ }
640
+ return rows.map((r) => {
641
+ const overdue = (r.status === 'sent' || r.status === 'delivered') && r.deadline_at && Date.parse(r.deadline_at) < now
642
+ return { ...r, ack: r.ack_json ? JSON.parse(r.ack_json) : null, overdue, effective_status: overdue ? 'overdue' : r.status }
643
+ })
644
+ }
645
+
646
+ taskOverdueCount(scene = null) {
647
+ return this.taskList({ scene, scope: scene ? 'outbound' : 'all' }).filter((t) => t.overdue).length
648
+ }
649
+
650
+ // ---------- 检索 ----------
651
+
652
+ /**
653
+ * 检索。默认只返回 active 且非 S 级;S 级需显式 includeSensitive。
654
+ * 每条结果带信任级、评分状态与使用约束(方案 §18/§19)。
655
+ */
656
+ search(input) {
657
+ const t0 = Date.now()
658
+ const hits = this._searchInternal(input)
659
+ this._trace({
660
+ op: 'search',
661
+ query: input?.query ?? '',
662
+ hits: hits.map((h) => h.record_id),
663
+ tokens_in: Math.ceil(String(input?.query ?? '').length / 3),
664
+ tokens_out: Math.ceil(hits.reduce((sum, h) => sum + String(h.snippet ?? '').length, 0) / 3),
665
+ duration_ms: Date.now() - t0,
666
+ principal_id: input?.principalId ?? null,
667
+ })
668
+ return hits
669
+ }
670
+
671
+ /**
672
+ * 联想:从一条记忆或一句话出发,找标签、语义、情绪上相近的记忆。
673
+ * 认知层的第二块——不是“搜索”,是“由 A 想到 B”。
674
+ */
675
+ buildEdges({ limit = 5000 } = {}) {
676
+ const now = nowIso()
677
+ this.db.exec('BEGIN')
678
+ try {
679
+ this.db.exec('DELETE FROM edges')
680
+ this.db
681
+ .prepare(
682
+ `INSERT OR IGNORE INTO edges(from_id, to_id, kind, weight, created_at)
683
+ SELECT a.record_id, b.record_id, 'tag', 1, ?
684
+ FROM tags a JOIN tags b ON a.tag = b.tag AND a.record_id < b.record_id
685
+ WHERE (SELECT status FROM records r WHERE r.record_id = a.record_id) = 'active'
686
+ AND (SELECT status FROM records r WHERE r.record_id = b.record_id) = 'active'
687
+ LIMIT ?`,
688
+ )
689
+ .run(now, limit)
690
+ this.db
691
+ .prepare(
692
+ `INSERT OR IGNORE INTO edges(from_id, to_id, kind, weight, created_at)
693
+ SELECT a.record_id, b.record_id, 'batch', 1, ?
694
+ FROM records a JOIN records b
695
+ ON a.batch_id = b.batch_id AND a.batch_id IS NOT NULL AND a.record_id < b.record_id
696
+ WHERE a.status = 'active' AND b.status = 'active'
697
+ LIMIT ?`,
698
+ )
699
+ .run(now, limit)
700
+ this.db.exec('COMMIT')
701
+ } catch (error) {
702
+ this.db.exec('ROLLBACK')
703
+ throw error
704
+ }
705
+ return this.db.prepare('SELECT COUNT(*) AS n FROM edges').get().n
706
+ }
707
+
708
+ graphNeighbors(recordId, { hops = 1, edgeTypes = null } = {}) {
709
+ const maxHops = Math.min(Math.max(Number(hops) || 1, 1), 3)
710
+ const kinds = Array.isArray(edgeTypes) && edgeTypes.length > 0 ? edgeTypes.map(String) : null
711
+ const nodes = new Map()
712
+ const edges = []
713
+ const root = String(recordId)
714
+ let frontier = [root]
715
+ nodes.set(root, 0)
716
+ for (let h = 0; h < maxHops; h += 1) {
717
+ const next = []
718
+ for (const id of frontier) {
719
+ const rows = this.db.prepare('SELECT from_id AS a, to_id AS b, kind, weight FROM edges WHERE from_id = ? OR to_id = ?').all(id, id)
720
+ for (const row of rows) {
721
+ if (kinds && !kinds.includes(row.kind)) continue
722
+ const other = row.a === id ? row.b : row.a
723
+ edges.push({ from: row.a, to: row.b, kind: row.kind, weight: row.weight })
724
+ if (!nodes.has(other)) {
725
+ nodes.set(other, h + 1)
726
+ next.push(other)
727
+ }
728
+ }
729
+ }
730
+ frontier = next
731
+ if (frontier.length === 0) break
732
+ }
733
+ const ids = [...nodes.keys()]
734
+ const detail = ids.length
735
+ ? this.db
736
+ .prepare(`SELECT record_id, layer, sad_level, summary FROM records WHERE record_id IN (${ids.map(() => '?').join(',')})`)
737
+ .all(...ids)
738
+ : []
739
+ const byId = new Map(detail.map((r) => [r.record_id, r]))
740
+ return {
741
+ root,
742
+ nodes: ids.map((id) => ({ record_id: id, depth: nodes.get(id), ...(byId.get(id) ?? {}) })),
743
+ edges,
744
+ }
745
+ }
746
+
747
+ graphTraverse(seedIds, { hops = 2, edgeTypes = null } = {}) {
748
+ const seeds = (Array.isArray(seedIds) ? seedIds : [seedIds]).filter(Boolean).map(String)
749
+ const nodes = new Map()
750
+ const edges = []
751
+ for (const seed of seeds) {
752
+ const result = this.graphNeighbors(seed, { hops, edgeTypes })
753
+ for (const node of result.nodes) if (!nodes.has(node.record_id)) nodes.set(node.record_id, node)
754
+ edges.push(...result.edges)
755
+ }
756
+ const seen = new Set()
757
+ const unique = edges.filter((e) => {
758
+ const key = e.from + '|' + e.to + '|' + e.kind
759
+ if (seen.has(key)) return false
760
+ seen.add(key)
761
+ return true
762
+ })
763
+ return { seeds, nodes: [...nodes.values()], edges: unique }
764
+ }
765
+
766
+ associate(input = {}) {
767
+ const limit = Math.min(Math.max(Number(input.topK ?? 5), 1), 20)
768
+ const seed = input.recordId
769
+ ? this.db
770
+ .prepare(
771
+ 'SELECT record_id, summary, content, layer, affect_label, affect_valence, affect_arousal, importance FROM records WHERE record_id = ?',
772
+ )
773
+ .get(String(input.recordId))
774
+ : null
775
+ const found = new Map()
776
+ const addHit = (row, reason, weight) => {
777
+ if (!row?.record_id) return
778
+ const current = found.get(row.record_id)
779
+ if (current) {
780
+ current.weight += weight
781
+ if (!current.reasons.includes(reason)) current.reasons.push(reason)
782
+ return
783
+ }
784
+ found.set(row.record_id, {
785
+ record_id: row.record_id,
786
+ summary: row.summary ?? '',
787
+ layer: row.layer ?? '',
788
+ affect_label: row.affect_label ?? null,
789
+ importance: row.importance ?? null,
790
+ weight,
791
+ reasons: [reason],
792
+ })
793
+ }
794
+
795
+ if (seed) {
796
+ const tags = this.db.prepare('SELECT tag FROM tags WHERE record_id = ?').all(seed.record_id).map((r) => r.tag)
797
+ for (const tag of tags) {
798
+ const rows = this.db
799
+ .prepare(
800
+ `SELECT r.record_id, r.summary, r.layer, r.affect_label, r.importance
801
+ FROM records r JOIN tags t ON t.record_id = r.record_id
802
+ WHERE t.tag = ? AND r.record_id <> ? AND r.status = 'active' AND r.sad_level != 'S'
803
+ ORDER BY r.importance DESC LIMIT ?`,
804
+ )
805
+ .all(tag, seed.record_id, limit)
806
+ for (const row of rows) addHit(row, `标签:${tag}`, 1)
807
+ }
808
+ if (seed.affect_label && seed.affect_label !== 'neutral') {
809
+ const rows = this.db
810
+ .prepare(
811
+ `SELECT record_id, summary, layer, affect_label, importance FROM records
812
+ WHERE affect_label = ? AND record_id <> ? AND status = 'active' AND sad_level != 'S'
813
+ ORDER BY importance DESC LIMIT ?`,
814
+ )
815
+ .all(seed.affect_label, seed.record_id, limit)
816
+ for (const row of rows) addHit(row, `同情绪:${seed.affect_label}`, 0.4)
817
+ }
818
+ }
819
+
820
+ const text = String(input.query ?? seed?.summary ?? '').trim()
821
+ if (text) {
822
+ let hits = []
823
+ try {
824
+ hits = this._searchInternal({ query: text, topK: limit, includeSensitive: input.includeSensitive === true })
825
+ } catch {
826
+ hits = []
827
+ }
828
+ for (const row of hits) {
829
+ if (seed && row.record_id === seed.record_id) continue
830
+ addHit(row, '语义', 0.8)
831
+ }
832
+ }
833
+
834
+ const items = [...found.values()]
835
+ .sort((a, b) => b.weight - a.weight || (b.importance ?? 0) - (a.importance ?? 0))
836
+ .slice(0, limit)
837
+ .map((item) => ({ ...item, weight: Math.round(item.weight * 10) / 10 }))
838
+
839
+ return {
840
+ seed: seed
841
+ ? {
842
+ record_id: seed.record_id,
843
+ summary: seed.summary,
844
+ layer: seed.layer,
845
+ affect_label: seed.affect_label,
846
+ }
847
+ : null,
848
+ items,
849
+ }
850
+ }
851
+
852
+ _searchInternal(input) {
853
+ const query = String(input.query ?? '').trim()
854
+ const topK = Math.min(Math.max(Number(input.topK ?? 10), 1), 50)
855
+ if (!query) return []
856
+ const match = toMatchQuery(query)
857
+ if (!match) return []
858
+
859
+ const where = ['records_fts MATCH ?', "r.status = 'active'"]
860
+ const params = [match]
861
+ if (LAYERS.includes(input.layer)) {
862
+ where.push('r.layer = ?')
863
+ params.push(input.layer)
864
+ }
865
+ if (!input.includeSensitive) where.push("r.sad_level != 'S'")
866
+ params.push(topK)
867
+
868
+ const rows = this.db
869
+ .prepare(
870
+ `SELECT r.record_id, r.layer, r.summary, r.sad_level, r.trust_level, r.source_channel,
871
+ r.project_id, r.created_at, r.content_hash, r.alpha, r.beta, r.scored,
872
+ bm25(records_fts) AS score
873
+ FROM records_fts
874
+ JOIN records r ON r.record_id = records_fts.record_id
875
+ WHERE ${where.join(' AND ')}
876
+ ORDER BY score ASC
877
+ LIMIT ?`,
878
+ )
879
+ .all(...params)
880
+
881
+ return rows.map((row) => {
882
+ const caveat = usageCaveat({ trustLevel: row.trust_level, beta: row.beta, scored: row.scored })
883
+ return {
884
+ record_id: row.record_id,
885
+ layer: row.layer,
886
+ snippet: row.summary,
887
+ score: row.score,
888
+ content_hash: row.content_hash,
889
+ source_channel: row.source_channel,
890
+ trust_level: row.trust_level,
891
+ sad_level: row.sad_level,
892
+ project_id: row.project_id,
893
+ created_at: row.created_at,
894
+ alpha: row.alpha,
895
+ beta: row.beta,
896
+ scored: row.scored === 1,
897
+ caveat,
898
+ }
899
+ })
900
+ }
901
+
902
+ /** 读全文。S 级需要 includeSensitive 才给正文(一期先这么收紧,二期接权限判定)。 */
903
+ read(recordId, options = {}) {
904
+ const row = this.db.prepare('SELECT * FROM records WHERE record_id = ?').get(recordId)
905
+ this._trace({
906
+ op: 'read',
907
+ record_id: String(recordId ?? ''),
908
+ denied: Boolean(row && row.sad_level === 'S' && !options.includeSensitive),
909
+ sad_level: row?.sad_level ?? null,
910
+ layer: row?.layer ?? null,
911
+ principal_id: options.principalId ?? null,
912
+ })
913
+ if (!row) return null
914
+ if (isEncrypted(row.content)) {
915
+ try {
916
+ row.content = decryptText(row.content, loadKey(this.dataDir))
917
+ } catch (error) {
918
+ return { ...row, content: '', denied: true, reason: '已加密但无法解密:' + (error?.message ?? String(error)) }
919
+ }
920
+ }
921
+ if (row.sad_level === 'S' && !options.includeSensitive) {
922
+ // 注意:不能把 content 置成 undefined —— 宿主要求返回值是 lossless JSON,
923
+ // 含 undefined 的键会直接报 "value is not lossless JSON",所以整个键都不出现。
924
+ const { content: _withheld, ...meta } = row
925
+ return { ...meta, denied: true, reason: 'S 级记录需要显式授权(include_sensitive=true)' }
926
+ }
927
+ return row
928
+ }
929
+
930
+ // ---------- 四期:加密 ----------
931
+
932
+ cryptoStatus() {
933
+ return cryptoInfo(this.dataDir)
934
+ }
935
+
936
+ enableCrypto() {
937
+ const { created } = ensureKey(this.dataDir)
938
+ this._trace({ op: 'crypto.enable' })
939
+ return { created, ...cryptoInfo(this.dataDir) }
940
+ }
941
+
942
+ encryptRecord(recordId) {
943
+ const key = loadKey(this.dataDir)
944
+ if (!key) throw new Error('尚未启用加密:先执行 enable')
945
+ const row = this.db.prepare('SELECT content FROM records WHERE record_id = ?').get(String(recordId))
946
+ if (!row) throw new Error('记录不存在')
947
+ const next = encryptText(row.content, key)
948
+ this.db.prepare('UPDATE records SET content = ? WHERE record_id = ?').run(next, String(recordId))
949
+ this._trace({ op: 'crypto.encrypt', record_id: String(recordId) })
950
+ return { record_id: String(recordId), encrypted: true }
951
+ }
952
+
953
+ decryptRecord(recordId) {
954
+ const row = this.db.prepare('SELECT content FROM records WHERE record_id = ?').get(String(recordId))
955
+ if (!row) throw new Error('记录不存在')
956
+ if (!isEncrypted(row.content)) return { record_id: String(recordId), encrypted: false }
957
+ const plain = decryptText(row.content, loadKey(this.dataDir))
958
+ this.db.prepare('UPDATE records SET content = ? WHERE record_id = ?').run(plain, String(recordId))
959
+ this._trace({ op: 'crypto.decrypt', record_id: String(recordId) })
960
+ return { record_id: String(recordId), encrypted: false }
961
+ }
962
+
963
+ // ---------- 二期:导入 / 影子读 / 回放 ----------
964
+
965
+ /**
966
+ * 导入旧记忆(只读 + 脱敏 + 幂等)。
967
+ * @param {{dryRun?: boolean, home?: string}} [options]
968
+ */
969
+ importLegacy(options = {}) {
970
+ if (this.getAuthority() === 'legacy') {
971
+ // legacy 模式下新库只写不读,导入仍然允许(它只是补数据)
972
+ }
973
+ const importer = new LegacyImporter({ store: this, home: options.home })
974
+ const report = importer.run({ dryRun: options.dryRun === true })
975
+ this._trace({
976
+ op: 'import',
977
+ imported: report.imported,
978
+ skipped: report.skipped,
979
+ redacted: report.redacted,
980
+ errors: report.errors.length,
981
+ dry_run: report.dry_run,
982
+ principal_id: 'owner',
983
+ })
984
+ return report
985
+ }
986
+
987
+ /** 影子读:新旧两路并排。 */
988
+ shadow({ query, topK = 5, home } = {}) {
989
+ const index = new LegacyIndex({ home })
990
+ const result = shadowCompare({ store: this, index, query, topK })
991
+ this._trace({
992
+ op: 'shadow',
993
+ query: query ?? '',
994
+ hits: result.mine.map((h) => h.record_id),
995
+ only_legacy: result.diff.only_legacy.length,
996
+ only_new: result.diff.only_new.length,
997
+ consistent: result.consistent,
998
+ })
999
+ return result
1000
+ }
1001
+
1002
+ /** 按 trace_id 回放(先查索引表,再回落到 JSONL)。 */
1003
+ traceLookup(traceId) {
1004
+ const row = this.db.prepare('SELECT * FROM traces WHERE trace_id = ?').get(String(traceId ?? ''))
1005
+ const fromJsonl = this.recorder?.trace(traceId) ?? null
1006
+ if (!row && !fromJsonl) return null
1007
+ return {
1008
+ trace_id: row?.trace_id ?? fromJsonl.trace_id,
1009
+ seq: row?.seq ?? fromJsonl.seq,
1010
+ at: row?.at ?? fromJsonl.at,
1011
+ op: row?.op ?? fromJsonl.op,
1012
+ query_preview: row?.query_preview ?? fromJsonl.query_preview ?? null,
1013
+ query_hash: row?.query_hash ?? fromJsonl.query_hash ?? null,
1014
+ hits: row ? JSON.parse(row.hits || '[]') : (fromJsonl.hits ?? []),
1015
+ injected: row ? JSON.parse(row.injected || '[]') : (fromJsonl.injected ?? []),
1016
+ tokens_in: row?.tokens_in ?? fromJsonl.tokens_in ?? null,
1017
+ tokens_out: row?.tokens_out ?? fromJsonl.tokens_out ?? null,
1018
+ duration_ms: row?.duration_ms ?? fromJsonl.duration_ms ?? null,
1019
+ prev_hash: row?.prev_hash ?? fromJsonl.prev ?? null,
1020
+ hash: row?.hash ?? fromJsonl.hash ?? null,
1021
+ file: fromJsonl?.file ?? null,
1022
+ }
1023
+ }
1024
+
1025
+ /** 审计体检:deep=true 时逐行重算整条链。 */
1026
+ audit({ deep = false } = {}) {
1027
+ const verify = this.recorder?.verify({ deep }) ?? { ok: null, lines: 0, files: 0, brokenAt: null }
1028
+ const stats = this.recorder?.stats() ?? { files: 0, bytes: 0, lastSeq: 0 }
1029
+ this.auditHealth = verify
1030
+ const recent = this.db.prepare('SELECT trace_id, at, op, hits FROM traces ORDER BY seq DESC LIMIT 5').all()
1031
+ return { ...verify, ...stats, recent, schema_version: this.getMeta('schema_version') }
1032
+ }
1033
+
1034
+ // ---------- 统计 / 不变量 ----------
1035
+
1036
+ stats() {
1037
+ const one = (sql) => this.db.prepare(sql).get()
1038
+ return {
1039
+ records: one('SELECT COUNT(*) AS n FROM records').n,
1040
+ fts: one('SELECT COUNT(*) AS n FROM records_fts').n,
1041
+ active: one("SELECT COUNT(*) AS n FROM records WHERE status = 'active'").n,
1042
+ pending: one("SELECT COUNT(*) AS n FROM records WHERE status = 'pending'").n,
1043
+ quarantined: one("SELECT COUNT(*) AS n FROM records WHERE status = 'quarantined'").n,
1044
+ rejected: one("SELECT COUNT(*) AS n FROM records WHERE status = 'rejected'").n,
1045
+ scored: one('SELECT COUNT(*) AS n FROM records WHERE scored = 1').n,
1046
+ sLevel: one("SELECT COUNT(*) AS n FROM records WHERE sad_level = 'S'").n,
1047
+ legacy: one("SELECT COUNT(*) AS n FROM records WHERE origin = 'legacy_import'").n,
1048
+ traces: one('SELECT COUNT(*) AS n FROM traces').n,
1049
+ audit: {
1050
+ ok: this.auditHealth?.ok ?? null,
1051
+ lines: this.auditHealth?.lines ?? 0,
1052
+ files: this.recorder?.stats?.().files ?? 0,
1053
+ bytes: this.recorder?.stats?.().bytes ?? 0,
1054
+ broken_at: this.auditHealth?.brokenAt ?? null,
1055
+ },
1056
+ byLayer: this.db.prepare('SELECT layer, COUNT(*) AS n FROM records GROUP BY layer ORDER BY layer').all(),
1057
+ authority: this.getAuthority(),
1058
+ dataDir: this.dataDir,
1059
+ schemaVersion: this.getMeta('schema_version'),
1060
+ }
1061
+ }
1062
+
1063
+ /** 待审/隔离清单(review 的输入)。 */
1064
+ pendingReview(limit = 20) {
1065
+ return this.db
1066
+ .prepare(
1067
+ `SELECT r.record_id, r.layer, r.sad_level, r.trust_level, r.status, r.summary,
1068
+ r.conflict_of, r.created_at, q.reason
1069
+ FROM records r LEFT JOIN review_queue q ON q.record_id = r.record_id
1070
+ WHERE r.status IN ('pending','quarantined')
1071
+ ORDER BY r.created_at DESC LIMIT ?`,
1072
+ )
1073
+ .all(Math.min(Math.max(Number(limit) || 20, 1), 100))
1074
+ }
1075
+
1076
+ /**
1077
+ * 运行时不变量检查(方案 §60):索引与主表逐行一致,内容哈希与正文一致。
1078
+ */
1079
+ checkInvariants() {
1080
+ const records = this.db.prepare('SELECT record_id, content, content_hash FROM records').all()
1081
+ const ftsRows = this.db.prepare('SELECT record_id FROM records_fts').all()
1082
+ const ftsSet = new Set(ftsRows.map((r) => r.record_id))
1083
+ const recSet = new Set(records.map((r) => r.record_id))
1084
+ const missingFts = []
1085
+ const hashMismatch = []
1086
+ for (const row of records) {
1087
+ if (!ftsSet.has(row.record_id)) missingFts.push(row.record_id)
1088
+ if (sha256(row.content) !== row.content_hash) hashMismatch.push(row.record_id)
1089
+ }
1090
+ const orphanFts = [...ftsSet].filter((id) => !recSet.has(id))
1091
+ return {
1092
+ ok: missingFts.length === 0 && hashMismatch.length === 0 && orphanFts.length === 0,
1093
+ records: records.length,
1094
+ fts: ftsRows.length,
1095
+ missingFts,
1096
+ hashMismatch,
1097
+ orphanFts,
1098
+ }
1099
+ }
1100
+
1101
+ // ---------- 快照(只读复制,不动原库) ----------
1102
+
1103
+ maybeSnapshot(force = false) {
1104
+ const last = this.getMeta('last_snapshot_at')
1105
+ if (!force && last) {
1106
+ const ago = Date.now() - Date.parse(last)
1107
+ if (Number.isFinite(ago) && ago < this.snapshotIntervalMs) return null
1108
+ }
1109
+ return this.snapshot()
1110
+ }
1111
+
1112
+ snapshot() {
1113
+ const stamp = new Date()
1114
+ .toLocaleString('sv-SE', { hour12: false })
1115
+ .replace(/[-: ]/g, '')
1116
+ .slice(0, 13)
1117
+ const dir = path.join(this.backupDir, `snap-${stamp}`)
1118
+ ensureDir(dir)
1119
+ try {
1120
+ this.db.exec('PRAGMA wal_checkpoint(TRUNCATE)')
1121
+ } catch {
1122
+ /* 快照失败不阻断主流程 */
1123
+ }
1124
+ fs.copyFileSync(this.dbFile, path.join(dir, 'memory.db'))
1125
+ const manifest = []
1126
+ for (const name of fs.readdirSync(dir)) {
1127
+ const file = path.join(dir, name)
1128
+ if (fs.statSync(file).isFile()) {
1129
+ manifest.push({ file: name, bytes: fs.statSync(file).size, sha256: sha256(fs.readFileSync(file)) })
1130
+ }
1131
+ }
1132
+ fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify({ created_at: nowIso(), files: manifest }, null, 2))
1133
+ this.setMeta('last_snapshot_at', nowUtc())
1134
+ return { dir, files: manifest }
1135
+ }
1136
+ }
1137
+
1138
+ export default MemoryStore