dsh-sixlayer-memory 2.0.4 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # 变更记录 · dsh-sixlayer-memory(六层记忆底座)
2
2
 
3
+ ## 2.1.0 — 2026-12-02
4
+
5
+ 主题:**记忆会老、会说错、会改口**。补上时间、冲突、并发三处缺口。
6
+
7
+ ### 新增
8
+
9
+ - **时间衰减**(`inject.js`):注入排序从「α 高分优先」改成「α × 时间衰减」。
10
+ 半衰期默认 120 天,下限 0.15 —— 老记忆不会消失,但会排到新鲜记忆后面;
11
+ 被召回一次 α +0.02,自然会浮回来。`inject.decayHalfLifeDays: 0` 可关闭。
12
+ - **用户口径「以最新为准」**(`store.write`):用户亲手写的新结论与旧记忆矛盾时,
13
+ 不再把新的丢进待审,而是**新记录直接生效、旧记录降级为 `superseded`**
14
+ (保留原行、`conflict_of` 指向新的,可追溯)。自动采集/未验证来源仍然先审后入,
15
+ 不会自动推翻你的记忆。传 `supersede: false` 可强制走旧行为。
16
+ - **`mem_conflicts` 工具**(第 33 个):看被推翻的旧口径(superseded)和仍活着但
17
+ 被标记相似的记录,用来确认某条旧规则是不是该退役。
18
+
19
+ ### 修复
20
+
21
+ - **审计哈希链在多进程下断链**(`recorder.js`):写入前先拿跨进程短锁
22
+ (`audit/.lock`,O_EXCL,最多等 2 秒;陈旧锁 >5 秒可抢占),拿到后重读
23
+ `.state.json` 对齐 seq/hash 再编号。之前两个进程同时写会出现**两条记录共用同一个
24
+ seq 和 prev**,链从此断开。回归 `p29` 用 3 个进程并发写 120 条验证。
25
+
26
+ ### 回归
27
+
28
+ - 新增 `p29`(9 项,并发审计)、`p30`(24 项,衰减 + 取代)
29
+ - `validate-tools` 与 `write-chain` 按新语义改写:用户口径矛盾 → 新的生效、旧的退役;
30
+ 自动通道矛盾 → 仍然待审
31
+ - 全量 **33 个套件全绿**,工具 33 个
32
+
33
+ ### 已知问题(不修,保留证据)
34
+
35
+ - `dsh-memory-data/audit/audit-202611.jsonl` 有 **3 处历史断链**(2026-11-01 seq=47、
36
+ 2026-11-04 seq=100 / seq=116),是 2.1.0 之前多进程并发写留下的。
37
+ **没有重写这条链** —— 哈希链的价值就是「断过就是断过」,重写等于销毁证据。
38
+ 要修得走一次显式修复(保留原始 hash 字段),需要单独确认。
39
+
40
+ ---
41
+
3
42
  ## 2.0.4 — 2026-11-22
4
43
 
5
44
  主题:**按社区索引 PR #121 的 review 修三处**(维护者 zhu1090093659)。
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  dsh plugin --profile desktop add dsh-sixlayer-memory
12
12
  ```
13
13
 
14
- **当前版本**:2.0.4 · **32 个工具** · schema v9 · 零外部依赖 · 回归 31 个套件全绿
14
+ **当前版本**:2.1.0 · **33 个工具** · schema v9 · 零外部依赖 · 回归 33 个套件全绿
15
15
 
16
16
  📦 [npm](https://www.npmjs.com/package/dsh-sixlayer-memory) · 🎬 [40 秒介绍视频](media/intro-40s.mp4) · 📝 [变更记录](CHANGELOG.md)
17
17
 
package/lib/index.js CHANGED
@@ -187,6 +187,7 @@ export function apply(ctx, config = {}) {
187
187
  ? new Injector({
188
188
  store,
189
189
  affect: config.affect?.hint === false ? null : { hours: Number(config.affect?.hours ?? 3), threshold: Number(config.affect?.threshold ?? 2) },
190
+ decayHalfLifeDays: Number(config.inject?.decayHalfLifeDays ?? 120),
190
191
  })
191
192
  : null
192
193
  diag('injector ' + (injector ? 'ok' : 'skipped'))
@@ -23,6 +23,21 @@ export const DEFAULT_LIMITS = {
23
23
  maxChars: 500,
24
24
  maxPerGroup: 1,
25
25
  repeatWindowMs: 5 * 60 * 1000,
26
+ // 时间衰减:同一条记忆放半年没人召回,就该往后排;被召回会 +α,自然浮回来。
27
+ // 0 = 关闭衰减。
28
+ decayHalfLifeDays: 120,
29
+ }
30
+
31
+ /**
32
+ * 时间衰减系数:0.5^(ageDays/halfLife),下限 0.15 —— 老记忆不会彻底消失,
33
+ * 只是排在新鲜记忆后面,`mem_audit` 里仍然查得到。
34
+ */
35
+ export function decayFactor(createdAt, { halfLifeDays = 120, now = Date.now(), floor = 0.15 } = {}) {
36
+ if (!halfLifeDays || halfLifeDays <= 0) return 1
37
+ const t = Date.parse(String(createdAt ?? ''))
38
+ if (!Number.isFinite(t)) return 1
39
+ const days = Math.max(0, (now - t) / 86400_000)
40
+ return Math.max(floor, Math.pow(0.5, days / halfLifeDays))
26
41
  }
27
42
 
28
43
  /** 把注入块从任意文本里剥掉(供压缩/摘要前使用)。 */
@@ -37,10 +52,10 @@ export function stripFence(text) {
37
52
  * 注意:这里不按 valid_to 过滤——v3/v4 表结构里没有该列(旧实现引用它导致查询恒失败)。
38
53
  * @returns {Array<{record_id,layer,sad_level,trust_level,alpha,summary,created_at,content_hash,batch_id,source_channel}>}
39
54
  */
40
- export function selectSnapshot(store, { maxRecords = DEFAULT_LIMITS.maxRecords } = {}) {
55
+ export function selectSnapshot(store, { maxRecords = DEFAULT_LIMITS.maxRecords, decayHalfLifeDays = DEFAULT_LIMITS.decayHalfLifeDays, now = Date.now() } = {}) {
41
56
  const n = Math.min(Math.max(Number(maxRecords) || 3, 1), 20)
42
57
  const pool = Math.min(n * 4, 80)
43
- return store.db
58
+ const rows = store.db
44
59
  .prepare(
45
60
  `SELECT record_id, layer, sad_level, trust_level, alpha, summary, created_at, content_hash,
46
61
  batch_id, source_channel, affect_label, affect_arousal,
@@ -56,6 +71,14 @@ export function selectSnapshot(store, { maxRecords = DEFAULT_LIMITS.maxRecords }
56
71
  LIMIT ?`,
57
72
  )
58
73
  .all(pool)
74
+
75
+ // 在 JS 里叠一层时间衰减:SQL 里排序只是粗排,衰减后要重排。
76
+ return rows
77
+ .map((row) => {
78
+ const decay = decayFactor(row.created_at, { halfLifeDays: decayHalfLifeDays, now })
79
+ return { ...row, decay, rank_score: row.rank_score * decay }
80
+ })
81
+ .sort((a, b) => b.rank_score - a.rank_score || String(b.created_at).localeCompare(String(a.created_at)))
59
82
  }
60
83
 
61
84
  /**
@@ -129,6 +152,7 @@ export class Injector {
129
152
  maxChars: options.maxChars ?? DEFAULT_LIMITS.maxChars,
130
153
  maxPerGroup: options.maxPerGroup ?? DEFAULT_LIMITS.maxPerGroup,
131
154
  repeatWindowMs: options.repeatWindowMs ?? DEFAULT_LIMITS.repeatWindowMs,
155
+ decayHalfLifeDays: options.decayHalfLifeDays ?? DEFAULT_LIMITS.decayHalfLifeDays,
132
156
  affect: options.affect ?? null,
133
157
  }
134
158
  this.lastHash = null
@@ -153,7 +177,10 @@ export class Injector {
153
177
  text(now = Date.now()) {
154
178
  let rows = []
155
179
  try {
156
- rows = selectSnapshot(this.store, { maxRecords: this.limits.maxRecords * 4 })
180
+ rows = selectSnapshot(this.store, {
181
+ maxRecords: this.limits.maxRecords * 4,
182
+ decayHalfLifeDays: this.limits.decayHalfLifeDays,
183
+ })
157
184
  } catch {
158
185
  return '' // 库暂时不可读时不注入,也不报错
159
186
  }
@@ -61,10 +61,76 @@ export class Recorder {
61
61
 
62
62
  /**
63
63
  * 追加一条。返回 {seq, hash, trace_id}。
64
+ *
65
+ * 并发安全:多个进程(比如两个 DSH 实例、或"宿主 + 命令行工具")同时往同一个
66
+ * audit 目录追加时,各自内存里的 seq/hash 会同时基于同一份旧状态算,
67
+ * 结果就是两条记录共用同一个 seq 和 prev —— 链从此断开(2026-11-01/11-04 实际发生过)。
68
+ *
69
+ * 处理:写之前拿一个跨进程的短锁,拿到后重读 .state.json 对齐到最新状态再编号;
70
+ * 锁超过 5 秒视为陈旧(进程崩了),抢占。拿不到锁就抛错,由调用方按"审计写失败
71
+ * 不影响主流程"处理 —— 宁可少一条,不写半条坏链。
72
+ *
64
73
  * @param {{op: string, trace_id?: string, [k: string]: any}} fields
65
74
  */
66
75
  record(fields) {
67
76
  if (!this.ready) this.open()
77
+ const release = this.lock()
78
+ try {
79
+ this.refreshState()
80
+ return this._append(fields)
81
+ } finally {
82
+ release()
83
+ }
84
+ }
85
+
86
+ /** 跨进程短锁(O_EXCL 建锁文件);最多等 ~2 秒。 */
87
+ lock({ timeoutMs = 2000, staleMs = 5000 } = {}) {
88
+ ensureDir(this.dir)
89
+ const lockFile = path.join(this.dir, '.lock')
90
+ const deadline = Date.now() + timeoutMs
91
+ const sleeper = new Int32Array(new SharedArrayBuffer(4))
92
+ for (;;) {
93
+ try {
94
+ const fd = fs.openSync(lockFile, 'wx')
95
+ fs.writeSync(fd, String(process.pid))
96
+ fs.closeSync(fd)
97
+ return () => {
98
+ try {
99
+ fs.unlinkSync(lockFile)
100
+ } catch {
101
+ /* 已经被别人清掉 */
102
+ }
103
+ }
104
+ } catch (error) {
105
+ if (error?.code !== 'EEXIST') throw error
106
+ // 陈旧锁:持锁进程崩了
107
+ try {
108
+ const age = Date.now() - fs.statSync(lockFile).mtimeMs
109
+ if (age > staleMs) {
110
+ fs.unlinkSync(lockFile)
111
+ continue
112
+ }
113
+ } catch {
114
+ /* 锁刚好消失,直接重试 */
115
+ }
116
+ if (Date.now() > deadline) throw new Error('audit 锁超时:另一个进程正在写审计')
117
+ Atomics.wait(sleeper, 0, 0, 10)
118
+ }
119
+ }
120
+ }
121
+
122
+ /** 把内存状态对齐到磁盘上最新的 .state.json(别的进程可能已经写过)。 */
123
+ refreshState() {
124
+ const saved = readJson(this.stateFile, null)
125
+ if (!saved || !Number.isFinite(saved.seq)) return false
126
+ if (saved.seq > this.state.seq) {
127
+ this.state = { seq: saved.seq, hash: saved.hash || GENESIS, at: saved.at }
128
+ return true
129
+ }
130
+ return false
131
+ }
132
+
133
+ _append(fields) {
68
134
  const seq = this.state.seq + 1
69
135
  const traceId = fields.trace_id ?? `tr-${seq}-${Date.now().toString(36)}`
70
136
 
@@ -306,11 +306,15 @@ export class MemoryStore {
306
306
 
307
307
  let conflictOf = null
308
308
  let contradiction = false
309
+ const contradicting = []
309
310
  for (const row of candidates) {
310
311
  const sim = similarity(content, row.content)
311
312
  if (sim >= SIMILARITY_THRESHOLD) {
312
313
  if (conflictOf === null) conflictOf = row.record_id
313
- if (contradictionSuspect(content, row.content)) contradiction = true
314
+ if (contradictionSuspect(content, row.content)) {
315
+ contradiction = true
316
+ contradicting.push(row.record_id)
317
+ }
314
318
  }
315
319
  if (conflictOf !== null && contradiction) break
316
320
  }
@@ -329,7 +333,11 @@ export class MemoryStore {
329
333
  pendingReview = 1
330
334
  reviewReason = 'unverified-source'
331
335
  }
332
- if (contradiction && !tainted) {
336
+ // 矛盾的处理分两种(2.1):
337
+ // - 用户亲手说的新口径 → **以最新为准**:新记录 active,旧的降级为 superseded;
338
+ // - 自动采集/未验证来源 → 仍然先审后入,不自动推翻已有记忆。
339
+ const userAuthoritative = trustLevel === 'trusted' && sourceChannel === 'user' && input.supersede !== false
340
+ if (contradiction && !tainted && !userAuthoritative) {
333
341
  status = 'pending'
334
342
  pendingReview = 1
335
343
  if (reviewReason !== 'unverified-source') reviewReason = 'contradiction-suspect'
@@ -393,6 +401,25 @@ export class MemoryStore {
393
401
  .run(recordId, reviewReason, now)
394
402
  }
395
403
 
404
+ // 以最新为准:用户亲口推翻的旧口径降级为 superseded(保留原行,可追溯)
405
+ const superseded = []
406
+ if (userAuthoritative && contradiction && contradicting.length > 0) {
407
+ const stmt = this.db.prepare(
408
+ "UPDATE records SET status = 'superseded', conflict_of = ?, updated_at = ? WHERE record_id = ? AND status = 'active'",
409
+ )
410
+ for (const oldId of contradicting) {
411
+ try {
412
+ const info = stmt.run(recordId, now, oldId)
413
+ if (info.changes > 0) superseded.push(oldId)
414
+ } catch {
415
+ /* 单条失败不影响新记录 */
416
+ }
417
+ }
418
+ if (superseded.length > 0) {
419
+ this._trace({ op: 'supersede', record_id: recordId, superseded, layer })
420
+ }
421
+ }
422
+
396
423
  return {
397
424
  record_id: recordId,
398
425
  dedup: false,
@@ -405,6 +432,7 @@ export class MemoryStore {
405
432
  conflict: conflictOf !== null,
406
433
  conflict_of: conflictOf,
407
434
  contradiction,
435
+ superseded,
408
436
  scanned: scanned.flags,
409
437
  }
410
438
  }
@@ -1073,6 +1101,39 @@ export class MemoryStore {
1073
1101
  .all(Math.min(Math.max(Number(limit) || 20, 1), 100))
1074
1102
  }
1075
1103
 
1104
+ /**
1105
+ * 冲突视图(2.1):被推翻的旧口径 + 还活着但被标记矛盾的记录。
1106
+ * 只读,不改任何状态。
1107
+ */
1108
+ conflicts(limit = 20) {
1109
+ const n = Math.min(Math.max(Number(limit) || 20, 1), 100)
1110
+ const superseded = this.db
1111
+ .prepare(
1112
+ `SELECT r.record_id, r.layer, r.sad_level, r.summary, r.created_at, r.conflict_of,
1113
+ s.summary AS successor_summary
1114
+ FROM records r LEFT JOIN records s ON s.record_id = r.conflict_of
1115
+ WHERE r.status = 'superseded'
1116
+ ORDER BY r.updated_at DESC LIMIT ?`,
1117
+ )
1118
+ .all(n)
1119
+ const suspects = this.db
1120
+ .prepare(
1121
+ `SELECT r.record_id, r.layer, r.sad_level, r.summary, r.created_at, r.conflict_of,
1122
+ s.summary AS other_summary
1123
+ FROM records r LEFT JOIN records s ON s.record_id = r.conflict_of
1124
+ WHERE r.status = 'active' AND r.conflict_of IS NOT NULL
1125
+ ORDER BY r.created_at DESC LIMIT ?`,
1126
+ )
1127
+ .all(n)
1128
+ const total = (status) =>
1129
+ this.db.prepare('SELECT COUNT(*) AS n FROM records WHERE status = ?').get(status).n
1130
+ return {
1131
+ superseded,
1132
+ suspects,
1133
+ counts: { superseded: total('superseded'), suspects: suspects.length },
1134
+ }
1135
+ }
1136
+
1076
1137
  /**
1077
1138
  * 运行时不变量检查(方案 §60):索引与主表逐行一致,内容哈希与正文一致。
1078
1139
  */
@@ -196,6 +196,7 @@ export function buildRegistry(store, host) {
196
196
  conflict: { type: 'boolean' },
197
197
  conflict_of: { type: 'string' },
198
198
  contradiction: { type: 'boolean' },
199
+ superseded: { type: 'array', items: { type: 'string' } },
199
200
  scanned: { type: 'array', items: { type: 'string' } },
200
201
  }),
201
202
  render: renderText,
@@ -229,7 +230,8 @@ export function buildRegistry(store, host) {
229
230
  lines.push(`层 ${r.layer} / 分级 ${r.sad_level} / 信任 ${r.trust_level} / 状态 ${r.status}`)
230
231
  lines.push(r.scanned?.length ? `扫描命中:${r.scanned.join(', ')}` : '扫描无命中')
231
232
  if (r.conflict) lines.push(`与既有记录主题重叠:${r.conflict_of}(已并存,未覆盖)`)
232
- if (r.contradiction) lines.push('疑似与既有记录结论相反:已进待审区,需 mem_review 审核后才参与召回')
233
+ if (r.superseded?.length) lines.push(`以最新为准:旧记录已退役 → ${r.superseded.join(', ')}(可用 mem_conflicts 查看)`)
234
+ else if (r.contradiction) lines.push('疑似与既有记录结论相反:已进待审区,需 mem_review 审核后才参与召回')
233
235
 
234
236
  return {
235
237
  text: lines.join('\n'),
@@ -244,6 +246,7 @@ export function buildRegistry(store, host) {
244
246
  conflict: r.conflict,
245
247
  conflict_of: r.conflict_of ?? '',
246
248
  contradiction: r.contradiction,
249
+ superseded: r.superseded ?? [],
247
250
  scanned: r.scanned ?? [],
248
251
  }
249
252
  },
@@ -704,6 +707,48 @@ export function buildRegistry(store, host) {
704
707
  { label: '待审清单', argsHint: 'mem_pending({ limit? })', needsOpen: true },
705
708
  )
706
709
 
710
+ add(
711
+ {
712
+ name: 'mem_conflicts',
713
+ description:
714
+ '看"口径被推翻"的记录:superseded 是已被新说法取代的旧记忆(保留可追溯),' +
715
+ 'suspects 是还活着但被标记"与别的记录相似/矛盾"的。用来确认某条旧规则是不是该退役。',
716
+ parameters: {
717
+ type: 'object',
718
+ additionalProperties: false,
719
+ properties: {
720
+ limit: { type: 'integer', description: '每类最多返回条数,默认 20' },
721
+ },
722
+ },
723
+ output: {
724
+ schema: textOut({
725
+ superseded: { type: 'array', items: { type: 'object', additionalProperties: true } },
726
+ suspects: { type: 'array', items: { type: 'object', additionalProperties: true } },
727
+ counts: { type: 'object', additionalProperties: true },
728
+ }),
729
+ render: renderText,
730
+ },
731
+ isConcurrencySafe: () => true,
732
+ execute: async (args) => {
733
+ const data = store.conflicts(args?.limit)
734
+ const lines = []
735
+ if (data.counts.superseded === 0 && data.counts.suspects === 0) {
736
+ lines.push('没有冲突记录。')
737
+ } else {
738
+ lines.push(`已退役(superseded):${data.counts.superseded} 条 · 疑似冲突(active):${data.counts.suspects} 条`, '')
739
+ for (const r of data.superseded.slice(0, 10)) {
740
+ lines.push(`- ${r.record_id} 被 ${r.conflict_of ?? '(未知)'} 取代:${r.summary ?? ''}`)
741
+ }
742
+ for (const r of data.suspects.slice(0, 10)) {
743
+ lines.push(`- ${r.record_id} 与 ${r.conflict_of ?? '(未知)'} 相似:${r.summary ?? ''}`)
744
+ }
745
+ }
746
+ return { text: lines.join('\n'), ...data }
747
+ },
748
+ },
749
+ { label: '冲突记录', argsHint: 'mem_conflicts({ limit? })', needsOpen: true },
750
+ )
751
+
707
752
  // ---------- 交接与体检(迁移自 luanyujia-workbench 记忆机制) ----------
708
753
 
709
754
  const SECTION_LABELS = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sixlayer-memory",
3
- "version": "2.0.4",
3
+ "version": "2.1.0",
4
4
  "private": false,
5
5
  "description": "DSH 工作台:六层记忆底座(每轮自动召回 + 候选沉淀 + 闸门审计)+ 零件化,支持 QQ 随身使用。",
6
6
  "type": "module",
@@ -62,6 +62,7 @@
62
62
  "mem_judge",
63
63
  "mem_review",
64
64
  "mem_pending",
65
+ "mem_conflicts",
65
66
  "mem_resume",
66
67
  "mem_handoff",
67
68
  "mem_check",
@@ -0,0 +1,189 @@
1
+ /**
2
+ * monitor.mjs —— 插件上线后的持续监测(下载量 / star / issue / 市场条目)。
3
+ *
4
+ * 用法:node tools/monitor.mjs # 默认把状态写到 monitor/state.json
5
+ * node tools/monitor.mjs --reset # 重置基线
6
+ *
7
+ * 设计:
8
+ * - 只读公开接口,不需要任何 token;
9
+ * - 每个数据源单独 try/catch,一个挂了不影响其它;
10
+ * - 和上一次的 state.json 做 diff,只说变化,不重复念数字。
11
+ */
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+
15
+ const ROOT = path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'))
16
+ const DIR = path.join(ROOT, '..', 'monitor')
17
+ const STATE = path.join(DIR, 'state.json')
18
+ const HISTORY = path.join(DIR, 'history.jsonl')
19
+
20
+ const PKG = 'dsh-sixlayer-memory'
21
+ const OWNER = 'z9134'
22
+ const REPO = 'dsh-sixlayer-memory'
23
+ const INDEX_URL = 'https://dsh-market.com/manifest/plugin-market-index.json'
24
+
25
+ const got = async (url, ms = 15000) => {
26
+ const c = new AbortController()
27
+ const t = setTimeout(() => c.abort(), ms)
28
+ try {
29
+ const r = await fetch(url, { signal: c.signal, headers: { 'user-agent': 'dsh-sixlayer-monitor' } })
30
+ if (!r.ok) throw new Error('HTTP ' + r.status)
31
+ return await r.json()
32
+ } finally {
33
+ clearTimeout(t)
34
+ }
35
+ }
36
+
37
+ function loadState() {
38
+ try {
39
+ return JSON.parse(fs.readFileSync(STATE, 'utf8'))
40
+ } catch {
41
+ return null
42
+ }
43
+ }
44
+
45
+ async function snapshot() {
46
+ const snap = { ts: new Date().toISOString(), npm: null, github: null, market: null, issues: [], pr121: null }
47
+
48
+ try {
49
+ const [day, week, range] = await Promise.all([
50
+ got(`https://api.npmjs.org/downloads/point/last-day/${PKG}`),
51
+ got(`https://api.npmjs.org/downloads/point/last-week/${PKG}`),
52
+ got(`https://api.npmjs.org/downloads/range/last-week/${PKG}`),
53
+ ])
54
+ const pkg = await got(`https://registry.npmjs.org/${PKG}`)
55
+ snap.npm = {
56
+ lastDay: day.downloads ?? 0,
57
+ lastWeek: week.downloads ?? 0,
58
+ latest: pkg['dist-tags']?.latest ?? '',
59
+ daily: (range.downloads ?? []).map((d) => ({ day: d.day, n: d.downloads })),
60
+ }
61
+ } catch (error) {
62
+ snap.npm = { error: error.message }
63
+ }
64
+
65
+ try {
66
+ const repo = await got(`https://api.github.com/repos/${OWNER}/${REPO}`)
67
+ const issues = await got(`https://api.github.com/repos/${OWNER}/${REPO}/issues?state=open&per_page=20`)
68
+ snap.github = {
69
+ stars: repo.stargazers_count ?? 0,
70
+ forks: repo.forks_count ?? 0,
71
+ watchers: repo.subscribers_count ?? 0,
72
+ pushedAt: repo.pushed_at ?? '',
73
+ }
74
+ snap.issues = issues
75
+ .filter((i) => !i.pull_request)
76
+ .map((i) => ({
77
+ number: i.number,
78
+ title: i.title,
79
+ user: i.user?.login ?? '',
80
+ at: i.created_at,
81
+ body: String(i.body ?? '').replace(/\s+/g, ' ').slice(0, 200),
82
+ }))
83
+ } catch (error) {
84
+ snap.github = { error: error.message }
85
+ }
86
+
87
+ // 市场条目的源头 PR(合并后如果有新评论,说明有人对我们这条有话说)
88
+ try {
89
+ const comments = await got('https://api.github.com/repos/zhu1090093659/dsh-community-plugins/issues/121/comments?per_page=50')
90
+ const last = comments[comments.length - 1]
91
+ snap.pr121 = last
92
+ ? { count: comments.length, lastAt: last.created_at, lastBy: last.user?.login ?? '', excerpt: String(last.body ?? '').replace(/\s+/g, ' ').slice(0, 160) }
93
+ : { count: 0 }
94
+ } catch (error) {
95
+ snap.pr121 = { error: error.message }
96
+ }
97
+
98
+ try {
99
+ const index = await got(INDEX_URL, 30000)
100
+ const hit = (index.plugins ?? []).find((p) => p.name === PKG)
101
+ snap.market = {
102
+ inIndex: Boolean(hit),
103
+ indexCount: (index.plugins ?? []).length,
104
+ version: hit?.versions?.[0]?.version ?? '',
105
+ }
106
+ } catch (error) {
107
+ snap.market = { error: error.message }
108
+ }
109
+
110
+ return snap
111
+ }
112
+
113
+ const bar = (n) => '▁▂▃▄▅▆▇█'[Math.min(7, Math.max(0, Math.round(n)))] ?? ''
114
+
115
+ function sparkline(daily) {
116
+ if (!daily?.length) return ''
117
+ const max = Math.max(...daily.map((d) => d.n), 1)
118
+ return daily.map((d) => bar((d.n / max) * 7)).join('')
119
+ }
120
+
121
+ function render(prev, cur) {
122
+ const out = []
123
+ const head = `📊 ${new Date(cur.ts).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`
124
+
125
+ if (cur.npm && !cur.npm.error) {
126
+ const d = prev?.npm && !prev.npm.error ? cur.npm.lastWeek - prev.npm.lastWeek : null
127
+ const trend = d === null ? '' : d > 0 ? `(+${d})` : d < 0 ? `(${d})` : '(持平)'
128
+ out.push(`npm 周下载 ${cur.npm.lastWeek}${trend} · 昨日 ${cur.npm.lastDay} · 版本 ${cur.npm.latest}`)
129
+ const spark = sparkline(cur.npm.daily)
130
+ if (spark) out.push(`近 7 天 ${spark}`)
131
+ } else {
132
+ out.push(`npm 读取失败:${cur.npm?.error ?? '未知'}`)
133
+ }
134
+
135
+ if (cur.github && !cur.github.error) {
136
+ const prevStars = prev?.github?.stars
137
+ const starDelta = typeof prevStars === 'number' ? cur.github.stars - prevStars : null
138
+ const starTxt = starDelta === null ? '' : starDelta > 0 ? `(+${starDelta})` : '(无变化)'
139
+ out.push(`star ${cur.github.stars}${starTxt} · fork ${cur.github.forks} · 打开 issue ${cur.issues.length}`)
140
+ } else {
141
+ out.push(`GitHub 读取失败:${cur.github?.error ?? '未知'}`)
142
+ }
143
+
144
+ const prevIssues = new Set((prev?.issues ?? []).map((i) => i.number))
145
+ const fresh = cur.issues.filter((i) => !prevIssues.has(i.number))
146
+ if (fresh.length) {
147
+ out.push(`新 issue ${fresh.length} 条:`)
148
+ for (const i of fresh.slice(0, 5)) {
149
+ out.push(` #${i.number} ${i.title}(${i.user})`)
150
+ if (i.body) out.push(` ${i.body.slice(0, 120)}`)
151
+ }
152
+ } else if (cur.issues.length) {
153
+ out.push(`issue 无新增(${cur.issues.length} 条待处理)`)
154
+ }
155
+
156
+ // PR 新评论:合并后还有人说话,往往是要我们改东西
157
+ if (cur.pr121 && !cur.pr121.error) {
158
+ const prevAt = prev?.pr121?.lastAt ?? ''
159
+ if (!prev?.pr121) {
160
+ out.push(`市场 PR 评论 ${cur.pr121.count} 条(基线)`)
161
+ } else if (cur.pr121.lastAt && cur.pr121.lastAt !== prevAt) {
162
+ out.push(`市场 PR 有新评论:${cur.pr121.lastBy}「${cur.pr121.excerpt.slice(0, 90)}」`)
163
+ }
164
+ }
165
+
166
+ if (cur.market && !cur.market.error) {
167
+ const changed = prev?.market && !prev.market.error && prev.market.inIndex !== cur.market.inIndex
168
+ const ver = cur.market.version ? ` · 索引版本 ${cur.market.version}` : ''
169
+ out.push(`市场索引 ${cur.market.inIndex ? '在架' : '不在'}${ver}(共 ${cur.market.indexCount} 个插件)${changed ? ' ⚠️ 状态变了' : ''}`)
170
+ } else {
171
+ out.push(`市场索引读取失败:${cur.market?.error ?? '未知'}`)
172
+ }
173
+
174
+ return [head, ...out].join('\n')
175
+ }
176
+
177
+ const args = process.argv.slice(2)
178
+ if (args.includes('--reset')) {
179
+ fs.rmSync(STATE, { force: true })
180
+ console.log('基线已重置')
181
+ }
182
+
183
+ const prev = loadState()
184
+ const cur = await snapshot()
185
+ fs.mkdirSync(DIR, { recursive: true })
186
+ fs.writeFileSync(STATE, JSON.stringify(cur, null, 2), 'utf8')
187
+ fs.appendFileSync(HISTORY, JSON.stringify({ ts: cur.ts, npm: cur.npm?.lastWeek ?? null, stars: cur.github?.stars ?? null, issues: cur.issues.length }) + '\n', 'utf8')
188
+
189
+ console.log(render(prev, cur))
package/tools/p29.mjs ADDED
@@ -0,0 +1,101 @@
1
+ /** p29:多个进程同时写审计,哈希链不能断 */
2
+ import { execFileSync } from 'node:child_process'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { createHash } from 'node:crypto'
7
+ import { Recorder } from '../lib/memory/recorder.js'
8
+
9
+ let pass = 0
10
+ let fail = 0
11
+ function ok(name, cond, extra = '') {
12
+ if (cond) { pass += 1; console.log(' ok ' + name) } else { fail += 1; console.log(' FAIL ' + name + (extra ? ' :: ' + extra : '')) }
13
+ }
14
+
15
+ const sha = (s) => createHash('sha256').update(s, 'utf8').digest('hex')
16
+
17
+ /** 复算整条链,返回第一个断点(没有就 null)。 */
18
+ function firstBreak(dir) {
19
+ const files = fs.readdirSync(dir).filter((f) => /^audit-\d{6}\.jsonl$/.test(f)).sort()
20
+ let prev = 'GENESIS'
21
+ let seq = 1
22
+ for (const f of files) {
23
+ const lines = fs.readFileSync(path.join(dir, f), 'utf8').split('\n').filter((x) => x.trim())
24
+ for (let i = 0; i < lines.length; i += 1) {
25
+ let row
26
+ try { row = JSON.parse(lines[i]) } catch { return { file: f, line: i + 1, why: 'unparsable' } }
27
+ const calc = sha(`${row.prev}|${JSON.stringify(row.payload)}`)
28
+ if (calc !== row.hash) return { file: f, line: i + 1, why: 'hash-mismatch' }
29
+ if (row.payload.seq !== seq) return { file: f, line: i + 1, why: `seq ${row.payload.seq} != ${seq}` }
30
+ if (i > 0 && row.prev !== prev) return { file: f, line: i + 1, why: 'prev-link-mismatch' }
31
+ prev = row.hash
32
+ seq += 1
33
+ }
34
+ }
35
+ return null
36
+ }
37
+
38
+ // ---------- 1. 单进程:正常写,链完整 ----------
39
+ const d1 = fs.mkdtempSync(path.join(os.tmpdir(), 'rec-1p-'))
40
+ const r = new Recorder({ dir: d1 }).open()
41
+ for (let i = 0; i < 20; i += 1) r.record({ op: 'test', i })
42
+ ok('单进程:20 条链完整', firstBreak(d1) === null, JSON.stringify(firstBreak(d1)))
43
+ ok('单进程:seq 连续到 20', r.state.seq === 20, String(r.state.seq))
44
+ ok('单进程:verify 通过', r.verify({ deep: true }).ok === true)
45
+
46
+ // ---------- 2. 两个进程交替写:不能撞 seq ----------
47
+ const d2 = fs.mkdtempSync(path.join(os.tmpdir(), 'rec-2p-'))
48
+ const child = path.join(d2, 'worker.mjs')
49
+ fs.writeFileSync(child, `
50
+ import { Recorder } from ${JSON.stringify(new URL('../lib/memory/recorder.js', import.meta.url).href)}
51
+ const r = new Recorder({ dir: process.argv[2] }).open()
52
+ for (let i = 0; i < 40; i += 1) r.record({ op: 'test', who: process.argv[3], i })
53
+ `, 'utf8')
54
+
55
+ const run = (who) =>
56
+ execFileSync(process.execPath, [child, d2, who], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
57
+
58
+ const procs = ['A', 'B', 'C'].map((who) => spawnWorker(who, run))
59
+ function spawnWorker(who, fn) {
60
+ // 用子进程异步并发:这里用同步 exec 会串行,所以要手动起三个
61
+ return import('node:child_process').then(({ spawn }) => {
62
+ return new Promise((resolve) => {
63
+ const p = spawn(process.execPath, [child, d2, who], { stdio: 'ignore' })
64
+ p.on('exit', (code) => resolve({ who, code }))
65
+ })
66
+ })
67
+ }
68
+
69
+ const results = await Promise.all(procs)
70
+ ok('并发:三个进程都退出 0', results.every((x) => x.code === 0), JSON.stringify(results))
71
+
72
+ const lines = fs.readdirSync(d2).filter((f) => /^audit-\d{6}\.jsonl$/.test(f))
73
+ .flatMap((f) => fs.readFileSync(path.join(d2, f), 'utf8').split('\n').filter((x) => x.trim()))
74
+ ok('并发:120 条一条不少', lines.length === 120, String(lines.length))
75
+
76
+ const brk = firstBreak(d2)
77
+ ok('并发:链完整(无 seq 撞车 / 无断链)', brk === null, JSON.stringify(brk))
78
+
79
+ // ---------- 3. 陈旧锁能被抢占 ----------
80
+ const d3 = fs.mkdtempSync(path.join(os.tmpdir(), 'rec-lock-'))
81
+ const r3 = new Recorder({ dir: d3 }).open()
82
+ const lockFile = path.join(d3, '.lock')
83
+ fs.writeFileSync(lockFile, '99999')
84
+ const old = new Date(Date.now() - 60_000)
85
+ fs.utimesSync(lockFile, old, old)
86
+ r3.record({ op: 'test', after: 'stale-lock' })
87
+ ok('陈旧锁:能抢占继续写', r3.state.seq === 1 && !fs.existsSync(lockFile), String(r3.state.seq))
88
+
89
+ // ---------- 4. 另一进程写过之后,本进程要对齐 seq ----------
90
+ const d4 = fs.mkdtempSync(path.join(os.tmpdir(), 'rec-align-'))
91
+ const mine = new Recorder({ dir: d4 }).open()
92
+ const other = new Recorder({ dir: d4 }).open()
93
+ other.record({ op: 'test', from: 'other' })
94
+ other.record({ op: 'test', from: 'other' })
95
+ mine.record({ op: 'test', from: 'mine' })
96
+ ok('对齐:本进程接着别人的 seq 编号', mine.state.seq === 3, String(mine.state.seq))
97
+ ok('对齐:链仍然完整', firstBreak(d4) === null, JSON.stringify(firstBreak(d4)))
98
+
99
+ for (const d of [d1, d2, d3, d4]) fs.rmSync(d, { recursive: true, force: true })
100
+ console.log(`\nP29 ${fail === 0 ? 'OK' : 'FAIL'} pass=${pass} fail=${fail}`)
101
+ process.exit(fail === 0 ? 0 : 1)
package/tools/p30.mjs ADDED
@@ -0,0 +1,85 @@
1
+ /** p30:2.1 的两件事 —— 时间衰减排序 + 用户口径矛盾「以最新为准」 */
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import MemoryStore from '../lib/memory/store.js'
6
+ import { decayFactor, selectSnapshot } from '../lib/memory/inject.js'
7
+
8
+ let pass = 0
9
+ let fail = 0
10
+ function ok(name, cond, extra = '') {
11
+ if (cond) { pass += 1; console.log(' ok ' + name) } else { fail += 1; console.log(' FAIL ' + name + (extra ? ' :: ' + extra : '')) }
12
+ }
13
+
14
+ const DAY = 86400_000
15
+ const NOW = Date.parse('2026-12-02T12:00:00+08:00')
16
+
17
+ // ---------- 1. 衰减系数 ----------
18
+ ok('衰减:刚写的 = 1', Math.abs(decayFactor(new Date(NOW).toISOString(), { halfLifeDays: 120, now: NOW }) - 1) < 1e-9)
19
+ ok('衰减:半个半衰期 ≈ 0.707', Math.abs(decayFactor(new Date(NOW - 60 * DAY).toISOString(), { halfLifeDays: 120, now: NOW }) - Math.SQRT1_2) < 1e-6)
20
+ ok('衰减:一个半衰期 = 0.5', Math.abs(decayFactor(new Date(NOW - 120 * DAY).toISOString(), { halfLifeDays: 120, now: NOW }) - 0.5) < 1e-9)
21
+ ok('衰减:有下限 0.15', decayFactor(new Date(NOW - 3650 * DAY).toISOString(), { halfLifeDays: 120, now: NOW }) === 0.15)
22
+ ok('衰减:关掉 = 1', decayFactor(new Date(NOW - 3650 * DAY).toISOString(), { halfLifeDays: 0, now: NOW }) === 1)
23
+ ok('衰减:坏时间不炸', decayFactor('not-a-date', { halfLifeDays: 120, now: NOW }) === 1)
24
+
25
+ // ---------- 2. 排序:同样 α,新的排前面 ----------
26
+ const d1 = fs.mkdtempSync(path.join(os.tmpdir(), 'p30-decay-'))
27
+ const s1 = new MemoryStore({ dataDir: d1 }).open()
28
+ const old = s1.write({ content: '老记忆:这是一条很久以前的结论,关于接口超时重试。', layer: 'L2', sourceChannel: 'user' })
29
+ const fresh = s1.write({ content: '新记忆:这是刚写下的结论,关于接口超时重试。', layer: 'L2', sourceChannel: 'user' })
30
+ s1.db.prepare('UPDATE records SET created_at = ? WHERE record_id = ?').run(new Date(NOW - 400 * DAY).toISOString(), old.record_id)
31
+ s1.db.prepare('UPDATE records SET created_at = ? WHERE record_id = ?').run(new Date(NOW).toISOString(), fresh.record_id)
32
+ s1.db.prepare('UPDATE records SET alpha = 0.9 WHERE record_id IN (?, ?)').run(old.record_id, fresh.record_id)
33
+
34
+ const snapOn = selectSnapshot(s1, { maxRecords: 2, decayHalfLifeDays: 120, now: NOW })
35
+ ok('排序:衰减开着时新的在前', snapOn[0]?.record_id === fresh.record_id, snapOn.map((r) => r.record_id).join(','))
36
+ ok('排序:老记录被压到后面', snapOn[1]?.record_id === old.record_id)
37
+ ok('排序:老记录的 rank 被衰减', snapOn[1].rank_score < snapOn[0].rank_score, `${snapOn[1].rank_score.toFixed(3)} vs ${snapOn[0].rank_score.toFixed(3)}`)
38
+
39
+ const snapOff = selectSnapshot(s1, { maxRecords: 2, decayHalfLifeDays: 0, now: NOW })
40
+ ok('排序:关掉衰减后仍可读到两条', snapOff.length === 2)
41
+ s1.close()
42
+ fs.rmSync(d1, { recursive: true, force: true })
43
+
44
+ // ---------- 3. 用户口径矛盾:以最新为准 ----------
45
+ const d2 = fs.mkdtempSync(path.join(os.tmpdir(), 'p30-sup-'))
46
+ const s2 = new MemoryStore({ dataDir: d2 }).open()
47
+ const a = s2.write({ content: '结论:允许关闭写前日志以提速,因为省事。', layer: 'L2', sourceChannel: 'user' })
48
+ const b = s2.write({ content: '结论:禁止关闭写前日志,因为会丢数据。', layer: 'L2', sourceChannel: 'user' })
49
+ ok('矛盾:检测到相反结论', b.contradiction === true, String(b.contradiction))
50
+ ok('矛盾:新记录直接生效', b.status === 'active', b.status)
51
+ ok('矛盾:旧记录被退役', b.superseded.includes(a.record_id), JSON.stringify(b.superseded))
52
+ ok('矛盾:旧记录状态是 superseded', s2.read(a.record_id).status === 'superseded')
53
+
54
+ const hits = s2.search({ query: '关闭写前日志', topK: 5 })
55
+ ok('检索:退役记录不再出现', hits.every((h) => h.record_id !== a.record_id), JSON.stringify(hits.map((h) => h.record_id)))
56
+
57
+ const snap2 = selectSnapshot(s2, { maxRecords: 5, now: NOW })
58
+ ok('注入:退役记录不进快照', snap2.every((r) => r.record_id !== a.record_id))
59
+
60
+ // ---------- 4. 自动采集的矛盾:仍然先审后入 ----------
61
+ const c = s2.write({ content: '结论:禁止关闭写前日志,抓取到的建议。', layer: 'L2', sourceChannel: 'tool' })
62
+ ok('自动通道:矛盾 → 待审', c.status === 'pending', c.status)
63
+ ok('自动通道:不退役既有记录', c.superseded.length === 0, JSON.stringify(c.superseded))
64
+
65
+ // ---------- 5. 冲突视图 ----------
66
+ const view = s2.conflicts(10)
67
+ ok('冲突视图:统计出 1 条退役', view.counts.superseded === 1, JSON.stringify(view.counts))
68
+ ok('冲突视图:退役条目带上取代者', view.superseded[0].conflict_of === b.record_id, JSON.stringify(view.superseded[0]))
69
+ ok('冲突视图:能说明取代者摘要', typeof view.superseded[0].successor_summary === 'string')
70
+
71
+ // ---------- 6. 显式关闭 supersede:复现「矛盾但要求不退役」 ----------
72
+ const d3 = fs.mkdtempSync(path.join(os.tmpdir(), 'p30-off-'))
73
+ const s3 = new MemoryStore({ dataDir: d3 }).open()
74
+ const keepA = s3.write({ content: '结论:允许关闭写前日志以提速,因为省事。', layer: 'L2', sourceChannel: 'user' })
75
+ const e = s3.write({ content: '结论:禁止关闭写前日志,因为会丢数据。', layer: 'L2', sourceChannel: 'user', supersede: false })
76
+ ok('supersede:false:矛盾仍被识别', e.contradiction === true, String(e.contradiction))
77
+ ok('supersede:false:不退役旧记录', e.superseded.length === 0 && s3.read(keepA.record_id).status === 'active', JSON.stringify(e.superseded))
78
+ ok('supersede:false:新记录回到待审', e.status === 'pending', e.status)
79
+ s3.close()
80
+ fs.rmSync(d3, { recursive: true, force: true })
81
+
82
+ s2.close()
83
+ fs.rmSync(d2, { recursive: true, force: true })
84
+ console.log(`\nP30 ${fail === 0 ? 'OK' : 'FAIL'} pass=${pass} fail=${fail}`)
85
+ process.exit(fail === 0 ? 0 : 1)
@@ -127,12 +127,30 @@ try {
127
127
 
128
128
  await registry.get('mem_write').definition.execute({ content: '结论:允许关闭写前日志以提速,因为省事。', layer: 'L2', project_id: 'p9', source_channel: 'user' })
129
129
  const contra = expectValue('mem_write', await registry.get('mem_write').definition.execute({ content: '结论:禁止关闭写前日志,因为会丢数据。', layer: 'L2', project_id: 'p9', source_channel: 'user' }))
130
- lines.push(contra.contradiction === true && contra.status === 'pending' ? ' PASS 疑似矛盾 → 待审' : (fail += 1, ` FAIL 矛盾检测没触发(${JSON.stringify(contra)})`))
130
+ // 2.1 起:用户亲手说的新口径「以最新为准」——新记录 active,旧记录 superseded
131
+ lines.push(
132
+ contra.contradiction === true && contra.status === 'active' && contra.superseded.length === 1
133
+ ? ' PASS 用户口径矛盾 → 新的生效、旧的退役'
134
+ : (fail += 1, ` FAIL 矛盾处理不对(${JSON.stringify(contra)})`),
135
+ )
136
+
137
+ const conflictList = expectValue('mem_conflicts', await registry.get('mem_conflicts').definition.execute({ limit: 5 }))
138
+ lines.push(
139
+ conflictList.counts.superseded === 1 && conflictList.superseded[0].record_id === contra.superseded[0]
140
+ ? ' PASS mem_conflicts 列出被取代的旧记录'
141
+ : (fail += 1, ` FAIL mem_conflicts 不对(${JSON.stringify(conflictList.counts)})`),
142
+ )
143
+
144
+ // 自动采集(非用户直输)遇到矛盾仍然先审后入
145
+ const autoContra = expectValue('mem_write', await registry.get('mem_write').definition.execute({ content: '结论:禁止关闭写前日志,自动化建议。', layer: 'L2', project_id: 'p9', source_channel: 'tool' }))
146
+ lines.push(
147
+ autoContra.status === 'pending' ? ' PASS 自动采集的矛盾仍然待审' : (fail += 1, ` FAIL 自动通道没过闸(${autoContra.status})`),
148
+ )
131
149
 
132
150
  const pend = expectValue('mem_pending', await registry.get('mem_pending').definition.execute({}))
133
- lines.push(pend.items.some((r) => r.record_id === contra.record_id) ? ' PASS mem_pending 列出待审' : (fail += 1, ' FAIL 待审清单没列出'))
151
+ lines.push(pend.items.some((r) => r.record_id === autoContra.record_id) ? ' PASS mem_pending 列出待审' : (fail += 1, ' FAIL 待审清单没列出'))
134
152
 
135
- const rv = expectValue('mem_review', await registry.get('mem_review').definition.execute({ record_id: contra.record_id, decision: 'approve', note: '验证用' }))
153
+ const rv = expectValue('mem_review', await registry.get('mem_review').definition.execute({ record_id: autoContra.record_id, decision: 'approve', note: '验证用' }))
136
154
  lines.push(rv.status === 'active' ? ' PASS mem_review 审核后回到 active' : (fail += 1, ` FAIL 审核没生效(${JSON.stringify(rv)})`))
137
155
 
138
156
  const stub = expectValue('mem_archive', await registry.get('mem_archive').definition.execute({}))
@@ -47,23 +47,33 @@ try {
47
47
  const s4 = store.write({ content: '决定:W2 的写入链先做两级分级(S/A),D 级诱饵库推迟到二期。', layer: 'L1', sourceChannel: 'user' })
48
48
  check('样本 4 同内容 → dedup 同一 record_id', s4.dedup === true && s4.record_id === s1.record_id, JSON.stringify(s4))
49
49
 
50
- // -------- 样本 5:结论相反 → 冲突标记 + 待审 --------
51
- store.write({ content: '结论:允许开启自动更新,因为省事。', layer: 'L2', projectId: 'p1', sourceChannel: 'user' })
50
+ // -------- 样本 5:用户口径相反 → 以最新为准(旧的退役) --------
51
+ const s5old = store.write({ content: '结论:允许开启自动更新,因为省事。', layer: 'L2', projectId: 'p1', sourceChannel: 'user' })
52
52
  const s5 = store.write({ content: '结论:禁止开启自动更新,因为会出事。', layer: 'L2', projectId: 'p1', sourceChannel: 'user' })
53
- check('样本 5 疑似矛盾 → pending + 冲突对象', s5.contradiction === true && s5.status === 'pending' && Boolean(s5.conflict_of), JSON.stringify(s5))
53
+ check(
54
+ '样本 5 用户口径矛盾 → 新的 active、旧的 superseded',
55
+ s5.contradiction === true && s5.status === 'active' && s5.superseded.includes(s5old.record_id),
56
+ JSON.stringify(s5),
57
+ )
58
+ const afterSupersede = store.search({ query: '开启 自动更新', topK: 5 })
59
+ check('退役记录不再进召回', afterSupersede.every((h) => h.record_id !== s5old.record_id), `hits=${afterSupersede.length}`)
60
+
61
+ // -------- 自动采集的矛盾仍然先审后入 --------
62
+ const s5auto = store.write({ content: '结论:禁止开启自动更新,因为会出大事。', layer: 'L2', projectId: 'p1', sourceChannel: 'tool' })
63
+ check('自动通道矛盾 → pending + 冲突对象', s5auto.contradiction === true && s5auto.status === 'pending' && Boolean(s5auto.conflict_of), JSON.stringify(s5auto))
54
64
 
55
65
  // -------- 待审不参与召回,审核后参与 --------
56
66
  const beforeReview = store.search({ query: '禁止 自动更新', topK: 5 })
57
- check('待审记录不进召回', beforeReview.every((h) => h.record_id !== s5.record_id), `hits=${beforeReview.length}`)
67
+ check('待审记录不进召回', beforeReview.every((h) => h.record_id !== s5auto.record_id), `hits=${beforeReview.length}`)
58
68
 
59
69
  const pendingList = store.pendingReview()
60
- check('待审清单能列出这条', pendingList.some((r) => r.record_id === s5.record_id), JSON.stringify(pendingList.map((r) => r.record_id)))
70
+ check('待审清单能列出这条', pendingList.some((r) => r.record_id === s5auto.record_id), JSON.stringify(pendingList.map((r) => r.record_id)))
61
71
 
62
- const reviewed = store.review(s5.record_id, 'approve', '人工确认:这是新决策,覆盖旧结论')
72
+ const reviewed = store.review(s5auto.record_id, 'approve', '人工确认:这是新决策,覆盖旧结论')
63
73
  check('审核 approve → active', reviewed.status === 'active', JSON.stringify(reviewed))
64
74
 
65
75
  const afterReview = store.search({ query: '禁止 自动更新', topK: 5 })
66
- check('审核后进入召回', afterReview.some((h) => h.record_id === s5.record_id), `hits=${afterReview.length}`)
76
+ check('审核后进入召回', afterReview.some((h) => h.record_id === s5auto.record_id), `hits=${afterReview.length}`)
67
77
 
68
78
  // -------- 隔离区出口 --------
69
79
  const released = store.review(s3.record_id, 'release', '测试用:确认是样本不是真攻击')