dsh-cortex-memory 0.4.22 → 0.4.146

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 (165) hide show
  1. package/CHANGELOG.md +2216 -7
  2. package/README.md +9 -9
  3. package/bench/migration-bench.mjs +1 -1
  4. package/bench/semantic-cn.js +7 -7
  5. package/bench/synthetic.js +2 -2
  6. package/bin/copy-db.mjs +47 -0
  7. package/bin/repair.mjs +328 -0
  8. package/bin/verify.mjs +202 -0
  9. package/cordis.patch.yml +1 -1
  10. package/docs/install-windows.md +2 -2
  11. package/docs/models.md +1 -1
  12. package/docs/quota-compaction-design.md +175 -0
  13. package/index.js +27 -3
  14. package/package.json +3 -3
  15. package/src/adapters/shiori.js +1 -1
  16. package/src/api/routes.js +1 -1
  17. package/src/core/feature-overrides.js +2 -2
  18. package/src/engines/compression.js +172 -3
  19. package/src/engines/consolidate.js +397 -26
  20. package/src/engines/encode.js +16 -3
  21. package/src/engines/extract.js +72 -8
  22. package/src/engines/fact-guard.js +51 -0
  23. package/src/engines/health.js +263 -3
  24. package/src/engines/inhibition.js +39 -0
  25. package/src/engines/life.js +12 -1
  26. package/src/engines/llm-facts.js +12 -9
  27. package/src/engines/narrative.js +150 -13
  28. package/src/engines/reflect.js +172 -14
  29. package/src/engines/retrieve.js +44 -5
  30. package/src/engines/summary-coverage.js +62 -0
  31. package/src/engines/summary-dedupe.js +77 -0
  32. package/src/engines/summon-rank.js +132 -0
  33. package/src/host/runtime.js +64 -4
  34. package/src/host/scheduler.js +224 -3
  35. package/src/llm/adapter.js +29 -8
  36. package/src/memory/query.js +1 -1
  37. package/src/memory/spacing.js +15 -0
  38. package/src/memory/tokenizer.js +1 -1
  39. package/src/prompt/tiers.js +88 -12
  40. package/src/self/alias.js +25 -0
  41. package/src/self/emotion.js +3 -1
  42. package/src/self/relationship.js +44 -13
  43. package/src/self/state.js +20 -2
  44. package/src/self/working.js +34 -3
  45. package/src/service/cortex.js +493 -53
  46. package/src/store/repositories/facts.js +34 -1
  47. package/src/store/repositories/summaries.js +8 -1
  48. package/src/store/repositories/traces.js +22 -2
  49. package/src/tools/definitions.js +118 -4
  50. package/src/vector/index.js +96 -7
  51. package/test/integration/acceptance.test.js +47 -47
  52. package/test/integration/api-contract.test.js +17 -17
  53. package/test/integration/backup-privacy.test.js +10 -10
  54. package/test/integration/consolidate.test.js +6 -2
  55. package/test/integration/edge-cases.test.js +16 -15
  56. package/test/integration/exchange.test.js +26 -26
  57. package/test/integration/life-loop.test.js +7 -6
  58. package/test/integration/load.test.js +4 -4
  59. package/test/integration/policy-query-api.test.js +4 -4
  60. package/test/integration/resilience-writes.test.js +7 -7
  61. package/test/integration/tools-contract.test.js +57 -57
  62. package/test/unit/alias.test.js +87 -0
  63. package/test/unit/api-client.test.js +3 -3
  64. package/test/unit/api-validate.test.js +3 -3
  65. package/test/unit/api.test.js +3 -3
  66. package/test/unit/auto-reflect.test.js +141 -0
  67. package/test/unit/capture-filter.test.js +296 -0
  68. package/test/unit/compaction-preview.test.js +91 -0
  69. package/test/unit/compression.test.js +4 -4
  70. package/test/unit/consolidate-dedupe.test.js +174 -0
  71. package/test/unit/consolidate-errors.test.js +63 -0
  72. package/test/unit/consolidate-gate.test.js +26 -0
  73. package/test/unit/consolidate-preview.test.js +168 -0
  74. package/test/unit/consolidate-protection.test.js +156 -0
  75. package/test/unit/consolidate-reason.test.js +206 -0
  76. package/test/unit/consolidate-retry.test.js +91 -0
  77. package/test/unit/consolidate-selection.test.js +103 -0
  78. package/test/unit/core.test.js +11 -11
  79. package/test/unit/coverage-rewrite.test.js +38 -0
  80. package/test/unit/dedupe-episodes.test.js +34 -0
  81. package/test/unit/dedupe-threshold.test.js +14 -0
  82. package/test/unit/develop.test.js +4 -4
  83. package/test/unit/edges-candidates.test.js +2 -2
  84. package/test/unit/emotion.test.js +2 -1
  85. package/test/unit/encode.test.js +6 -6
  86. package/test/unit/evolution.test.js +5 -5
  87. package/test/unit/extract-question.test.js +41 -0
  88. package/test/unit/fact-guard.test.js +51 -0
  89. package/test/unit/fact-noise-llm.test.js +44 -0
  90. package/test/unit/facts-belief.test.js +4 -4
  91. package/test/unit/facts-compat.test.js +62 -0
  92. package/test/unit/facts.test.js +5 -5
  93. package/test/unit/fts-migration.test.js +6 -6
  94. package/test/unit/growth-reflect.test.js +4 -3
  95. package/test/unit/guardian.test.js +1 -1
  96. package/test/unit/health-consolidation.test.js +52 -0
  97. package/test/unit/health-fts-scope.test.js +33 -0
  98. package/test/unit/health-privacy.test.js +6 -6
  99. package/test/unit/health-summaries.test.js +24 -0
  100. package/test/unit/health-text-maintain.test.js +33 -0
  101. package/test/unit/health-today.test.js +45 -0
  102. package/test/unit/host-runtime.test.js +8 -8
  103. package/test/unit/host.test.js +1 -1
  104. package/test/unit/induct-evaluate.test.js +3 -3
  105. package/test/unit/ingest-extracted.test.js +3 -3
  106. package/test/unit/inhibition.test.js +90 -0
  107. package/test/unit/jobs.test.js +4 -4
  108. package/test/unit/json-snapshot.test.js +1 -1
  109. package/test/unit/label-entities-skip.test.js +18 -0
  110. package/test/unit/llm-facts-integration.test.js +2 -2
  111. package/test/unit/llm-facts.test.js +3 -3
  112. package/test/unit/llm.test.js +5 -5
  113. package/test/unit/locomo.test.js +2 -2
  114. package/test/unit/longmemeval.test.js +2 -2
  115. package/test/unit/maintain-dispute.test.js +62 -0
  116. package/test/unit/maintain-duration.test.js +194 -0
  117. package/test/unit/markdown-import.test.js +5 -5
  118. package/test/unit/markdown.test.js +2 -2
  119. package/test/unit/memory-edit.test.js +5 -5
  120. package/test/unit/migration.test.js +1 -1
  121. package/test/unit/mood-saturation.test.js +33 -0
  122. package/test/unit/narrative-weave.test.js +271 -0
  123. package/test/unit/privacy-scope.test.js +1 -1
  124. package/test/unit/prompt.test.js +1 -1
  125. package/test/unit/providers.test.js +2 -2
  126. package/test/unit/qa.test.js +9 -9
  127. package/test/unit/query.test.js +10 -10
  128. package/test/unit/reflect-backfill.test.js +158 -0
  129. package/test/unit/reflect-coverage.test.js +35 -0
  130. package/test/unit/reflect-overview.test.js +22 -0
  131. package/test/unit/reflect-phrasing.test.js +75 -0
  132. package/test/unit/reflect-sampling.test.js +80 -0
  133. package/test/unit/reflect-source-budget.test.js +24 -0
  134. package/test/unit/relationship-dynamics.test.js +29 -0
  135. package/test/unit/retrieve.test.js +9 -9
  136. package/test/unit/revive-on-read.test.js +84 -0
  137. package/test/unit/scanner.test.js +2 -2
  138. package/test/unit/scenario.test.js +2 -2
  139. package/test/unit/scheduler-autoconsolidate.test.js +95 -0
  140. package/test/unit/scheduler-autodedupe.test.js +52 -0
  141. package/test/unit/scheduler-autosleep.test.js +50 -0
  142. package/test/unit/scheduler-cadence.test.js +33 -0
  143. package/test/unit/scheduler-deep.test.js +62 -0
  144. package/test/unit/scheduler-tick-gate.test.js +38 -0
  145. package/test/unit/scheduler.test.js +2 -1
  146. package/test/unit/service.test.js +5 -5
  147. package/test/unit/shiori-import.test.js +4 -4
  148. package/test/unit/spacing.test.js +14 -0
  149. package/test/unit/store.test.js +13 -13
  150. package/test/unit/summon-left-slot.test.js +51 -0
  151. package/test/unit/summon-rank.test.js +51 -0
  152. package/test/unit/tiers-gist.test.js +140 -0
  153. package/test/unit/tiers.test.js +1 -1
  154. package/test/unit/tokenizer-fts.test.js +6 -6
  155. package/test/unit/tools.test.js +5 -5
  156. package/test/unit/upgrade-0412.test.js +10 -10
  157. package/test/unit/upgrade-0413.test.js +5 -5
  158. package/test/unit/upgrade-0414.test.js +5 -5
  159. package/test/unit/vector-ann.test.js +3 -3
  160. package/test/unit/vector-async.test.js +7 -7
  161. package/test/unit/vector-coverage.test.js +34 -0
  162. package/test/unit/vector-override.test.js +37 -0
  163. package/test/unit/vector-typed-array.test.js +47 -0
  164. package/test/unit/vector.test.js +8 -8
  165. package/test/unit/working.test.js +19 -0
package/README.md CHANGED
@@ -7,11 +7,11 @@
7
7
  ## 当前版本
8
8
 
9
9
  ```text
10
- 主包:dsh-cortex-memory@0.4.22
10
+ 主包:dsh-cortex-memory@0.4.146
11
11
  提取器:dsh-cortex-extractors@0.3.5
12
- DSH:>=0.2.1-rc.2 <0.4.0
12
+ DSH:>=0.2.1-rc.2 <0.5.0
13
13
  Node:>=24
14
- 测试:440/440
14
+ 测试:520/520
15
15
  ```
16
16
 
17
17
  ## 现在能做什么
@@ -34,7 +34,7 @@ Node:>=24
34
34
  先关闭 DSH,再安装并重启:
35
35
 
36
36
  ```powershell
37
- dsh plugin --profile desktop add dsh-cortex-memory@0.4.22
37
+ dsh plugin --profile desktop add dsh-cortex-memory@0.4.146
38
38
  dsh plugin --profile desktop add dsh-cortex-extractors@0.3.5
39
39
  ```
40
40
 
@@ -45,7 +45,7 @@ dsh plugin --profile desktop add dsh-cortex-extractors@0.3.5
45
45
  GitHub Release 提供:
46
46
 
47
47
  ```text
48
- cortex-memory-oneclick-0.4.21.zip
48
+ cortex-memory-oneclick-0.4.146.zip
49
49
  ```
50
50
 
51
51
  解压后双击 `install.cmd`。安装器会做 profile 检查、备份、SHA256 校验和可选路径迁移。
@@ -87,7 +87,7 @@ CLI 默认读取 `~/.dsh/cortex-memory`;需要指定其他库时显式传 `--d
87
87
  已做:
88
88
 
89
89
  ```text
90
- 主包测试:440/440
90
+ 主包测试:520/520
91
91
  受控中文语义探针:recall@3 1.000 / MRR@3 0.917 / nDCG@3 0.938
92
92
  受控探针延迟:p50 1.31ms / p95 4.07ms
93
93
  真实图片 OCR:已跑通
@@ -125,9 +125,9 @@ Cortex 的定位是“本地可解释、可回滚、能长期长”的记忆系
125
125
 
126
126
  ## 下载
127
127
 
128
- - npm 主包:`dsh-cortex-memory@0.4.22`
128
+ - npm 主包:`dsh-cortex-memory@0.4.146`
129
129
  - npm 提取器:`dsh-cortex-extractors@0.3.5`
130
- - GitHub Release:`v0.4.21`
131
- - Windows 一键包:`cortex-memory-oneclick-0.4.21.zip`
130
+ - GitHub Release:`v0.4.146`
131
+ - Windows 一键包:`cortex-memory-oneclick-0.4.146.zip`
132
132
 
133
133
  安装后重启 DSH,左侧出现「Cortex 记忆」入口。
@@ -18,7 +18,7 @@ try {
18
18
  const texts = [];
19
19
  for (let i = 0; i < count; i += 1) {
20
20
  texts.push({
21
- text: i === 0 ? '白饭:升级后仍然应该能通过“米饭”的 soft 查询找到。' : `老库迁移样本 ${i}:普通记忆内容。`,
21
+ text: i === 0 ? '米饭:升级后仍然应该能通过“饭”的 soft 查询找到。' : `老库迁移样本 ${i}:普通记忆内容。`,
22
22
  title: `迁移样本 #${i}`,
23
23
  explicit: true,
24
24
  operationId: `migrate:${count}:${i}`,
@@ -22,13 +22,13 @@ const cortex = createCortex({
22
22
  });
23
23
 
24
24
  const data = [
25
- ['便宜订阅', '涵儿喜欢便宜的音乐订阅,不买贵的套餐。'],
26
- ['白饭承诺', '涵儿答应下班带白饭,汐儿记得这个承诺。'],
27
- ['颈椎', '久坐后颈椎会疼,汐儿提醒涵儿起身。'],
25
+ ['便宜订阅', '用户喜欢便宜的音乐订阅,不买贵的套餐。'],
26
+ ['米饭承诺', '用户答应下班带米饭,助手记得这个承诺。'],
27
+ ['颈椎', '久坐后颈椎会疼,助手提醒用户起身。'],
28
28
  ['猫粮', '家里的猫只吃鸡肉味猫粮。'],
29
- ['雨天', '下雨天要带伞,涵儿常忘记。'],
29
+ ['雨天', '下雨天要带伞,用户常忘记。'],
30
30
  ['周末', '周末计划去河边散步。'],
31
- ['白饭', '白饭要热的,不要隔夜。'],
31
+ ['米饭', '米饭要热的,不要隔夜。'],
32
32
  ['订阅', '订阅续费前先看价格。'],
33
33
  ['颈椎', '颈椎疼时不要继续低头。'],
34
34
  ['猫', '猫晚上会在门口等。'],
@@ -41,13 +41,13 @@ for (const [title, text] of data) {
41
41
  written.set(title, row.trace.id);
42
42
  }
43
43
  const queries = [
44
- ['白饭', '白饭承诺'],
44
+ ['米饭', '米饭承诺'],
45
45
  ['便宜 订阅', '便宜订阅'],
46
46
  ['颈椎 疼', '颈椎'],
47
47
  ['猫 吃 什么', '猫粮'],
48
48
  ['下雨 带伞', '雨天'],
49
49
  ['周末 散步', '周末'],
50
- ['白饭 热', '白饭'],
50
+ ['米饭 热', '米饭'],
51
51
  ['订阅 价格', '订阅'],
52
52
  ['低头 颈椎', '颈椎'],
53
53
  ['猫 晚上', '猫'],
@@ -15,11 +15,11 @@ function mulberry32(seed) {
15
15
  };
16
16
  }
17
17
 
18
- const PLACES = ['米饭', '插件', '记忆引擎', '鲸鱼', '主人', '同伴', '直播', '语音', '项目', '代码', '测试', 'legacy-data', 'QQ', 'B站', '声音', '梦', '日记'];
18
+ const PLACES = ['米饭', '插件', '记忆引擎', '鲸鱼', '用户', '同伴', '直播', '语音', '项目', '代码', '测试', 'legacy-data', 'QQ', 'B站', '声音', '梦', '日记'];
19
19
  const VERBS = ['修好了', '想起来了', '决定继续', '记录一下', '有点担心', '很开心', '测试了', '重新整理了', '发现了', '计划明天'];
20
20
  const TOPICS = ['图检索', '向量检索', '遗忘曲线', '工作卡', '火花卡', '身份版本', '关系模型', '反思', '巩固', '守护', '备份', '权限'];
21
21
  const PARAPHRASES = new Map([
22
- ['白饭', '米饭'],
22
+ ['米饭', '饭'],
23
23
  ['插件', '扩展程序'],
24
24
  ['记忆引擎', '记忆系统'],
25
25
  ['鲸鱼', '鲸'],
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Make a consistent copy of a cortex database (VACUUM INTO), for rehearsals,
4
+ * drills and offline inspection. Never writes to the source.
5
+ *
6
+ * node bin/copy-db.mjs --source <db> --target <copy>
7
+ * node bin/copy-db.mjs # default live store -> temp file
8
+ */
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import os from 'node:os';
12
+ import { DatabaseSync } from 'node:sqlite';
13
+
14
+ const args = process.argv.slice(2);
15
+ const value = (name, fallback = null) => {
16
+ const index = args.indexOf(name);
17
+ return index >= 0 && args[index + 1] ? args[index + 1] : fallback;
18
+ };
19
+
20
+ const home = process.env.USERPROFILE || os.homedir();
21
+ const source = value('--source', path.join(home, '.dsh', 'cortex-memory', 'cortex.sqlite'));
22
+ const target = value('--target', path.join(os.tmpdir(), `cortex-copy-${Date.now()}.sqlite`));
23
+
24
+ if (!fs.existsSync(source)) {
25
+ console.error(JSON.stringify({ ok: false, error: `source not found: ${source}` }));
26
+ process.exit(2);
27
+ }
28
+
29
+ fs.mkdirSync(path.dirname(target), { recursive: true });
30
+ if (fs.existsSync(target)) fs.unlinkSync(target);
31
+
32
+ const db = new DatabaseSync(source);
33
+ try {
34
+ db.exec(`VACUUM INTO '${target.replace(/'/g, "''")}'`);
35
+ } finally {
36
+ db.close();
37
+ }
38
+
39
+ const copy = new DatabaseSync(target, { readOnly: true });
40
+ let active = 0;
41
+ try {
42
+ active = Number(copy.prepare("SELECT COUNT(*) AS c FROM traces WHERE state = 'active'").get()?.c ?? 0);
43
+ } finally {
44
+ copy.close();
45
+ }
46
+
47
+ console.log(JSON.stringify({ ok: true, source, target, active, bytes: fs.statSync(target).size }));
package/bin/repair.mjs ADDED
@@ -0,0 +1,328 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Offline repair for a dsh-cortex store.
4
+ *
5
+ * It is the "clean up what the old code wrote" step that should run once after
6
+ * upgrading, and it is safe to run again (every step is idempotent).
7
+ *
8
+ * node bin/repair.mjs # dry run: report only
9
+ * node bin/repair.mjs --apply # back up (VACUUM INTO) then write
10
+ * node bin/repair.mjs --apply --user-address 用户 --alias 小名
11
+ *
12
+ * Also covers the identity-boundary rewrite that the 0.4.23 migration needed.
13
+ */
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import os from 'node:os';
17
+ import { DatabaseSync } from 'node:sqlite';
18
+ import { recomputeEpisodeCoverage } from '../src/engines/summary-coverage.js';
19
+ import { findDuplicateEpisodes } from '../src/engines/summary-dedupe.js';
20
+ import { summaryId } from '../src/core/ids.js';
21
+
22
+ const args = process.argv.slice(2);
23
+ const apply = args.includes('--apply');
24
+ // Opt-in only: rewriting summaries is a data change, so it never happens as part
25
+ // of a plain repair run and always reports its diff before touching rows.
26
+ const rewriteCoverage = args.includes('--rewrite-coverage');
27
+ const dedupeEpisodes = args.includes('--dedupe-episodes');
28
+ // Opt-in: archive facts that are sentence fragments, not assertions.
29
+ const dropNoiseFacts = args.includes('--drop-noise-facts');
30
+ const argValue = (name, fallback = null) => {
31
+ const index = args.indexOf(name);
32
+ return index >= 0 && args[index + 1] ? args[index + 1] : fallback;
33
+ };
34
+ const home = process.env.USERPROFILE || os.homedir();
35
+ const profile = argValue('--profile');
36
+ const dbPath = argValue('--db')
37
+ || (profile
38
+ ? path.join(home, '.dsh', 'cortex-memory', 'profiles', profile, 'cortex.sqlite')
39
+ : path.join(home, '.dsh', 'cortex-memory', 'cortex.sqlite'));
40
+ const scopeId = argValue('--scope', 'global');
41
+ const userAddress = argValue('--user-address');
42
+ const aliases = ['用户', '你', '您'];
43
+ for (let i = 0; i < args.length; i += 1) {
44
+ if (args[i] === '--alias' && args[i + 1]) aliases.push(args[i + 1]);
45
+ }
46
+
47
+ if (!fs.existsSync(dbPath)) {
48
+ console.error(`database not found: ${dbPath}`);
49
+ process.exit(2);
50
+ }
51
+
52
+ const now = new Date().toISOString();
53
+ const report = {
54
+ at: now,
55
+ db: dbPath,
56
+ scope: scopeId,
57
+ mode: apply ? 'apply' : 'dry-run',
58
+ backup: null,
59
+ goalRounds: 0,
60
+ injectedTraces: 0,
61
+ duplicateSummaries: 0,
62
+ staleIntentions: 0,
63
+ fragmentRules: 0,
64
+ zombieDisputes: 0,
65
+ aliasRows: 0,
66
+ titles: 0,
67
+ titleFixes: 0,
68
+ coverageRewrite: null,
69
+ noiseFacts: null,
70
+ dedupeEpisodes: null,
71
+ };
72
+
73
+ const db = new DatabaseSync(dbPath);
74
+ db.exec('PRAGMA busy_timeout = 8000');
75
+
76
+ function backup() {
77
+ const dir = path.join(path.dirname(dbPath), 'backups');
78
+ fs.mkdirSync(dir, { recursive: true });
79
+ const file = path.join(dir, `cortex-repair-${now.replace(/[:.]/g, '-')}.sqlite`);
80
+ db.exec(`VACUUM INTO '${file.replace(/'/g, "''")}'`);
81
+ return file;
82
+ }
83
+
84
+ function count(sql, ...params) {
85
+ return Number(db.prepare(sql).get(...params)?.c ?? 0);
86
+ }
87
+
88
+ function run(sql, ...params) {
89
+ return Number(db.prepare(sql).run(...params).changes ?? 0);
90
+ }
91
+
92
+ function deriveTitle(content) {
93
+ const text = String(content ?? '').replace(/^(用户|助手|User|Assistant)\s*[::]\s*/, '').trim();
94
+ // Assistant-side captures start with the persona name ("<name>:…"); strip that
95
+ // short label too so the derived title is not just the name.
96
+ const withoutName = text.replace(/^([^\s::]{1,6})\s*[::]\s*/, '');
97
+ const candidate = withoutName.length >= 8 ? withoutName : text;
98
+ const line = candidate.split(/\r?\n/).map((s) => s.trim()).find((s) => s.length > 0) ?? '';
99
+ const clean = line.replace(/\s+/g, ' ').replace(/^#+\s*/, '').slice(0, 60).trim();
100
+ return clean.length >= 8 ? clean : null;
101
+ }
102
+
103
+ const INJECTED = [
104
+ "content GLOB '用户:Time sampled*'",
105
+ "content GLOB 'Time sampled*'",
106
+ "content GLOB '用户:Elapsed since the preceding*'",
107
+ "content GLOB 'Elapsed since the preceding*'",
108
+ "content GLOB '用户:Current runtime context*'",
109
+ "content GLOB 'Current runtime context*'",
110
+ "content GLOB '用户:<system-reminder>*'",
111
+ "content GLOB '<system-reminder>*'",
112
+ "content GLOB '用户:This is an automatically generated checkpoint*'",
113
+ "content GLOB '用户:Background subagent*'",
114
+ // GLOB treats '[' as a character-class opener, so the reminder prefix needs
115
+ // LIKE instead — otherwise '用户:[SCHEDULE REMINDER*' silently never matches.
116
+ "content LIKE '用户:[SCHEDULE REMINDER%'",
117
+ "content LIKE '[SCHEDULE REMINDER%'",
118
+ "content LIKE '用户:This is a scheduled message from the user%'",
119
+ "content LIKE '用户:<goal_complete>%'",
120
+ "content LIKE '<goal_complete>%'",
121
+ ].join(' OR ');
122
+
123
+ const GOAL_ROUND = `(content LIKE '用户:<goal_round>%' OR content LIKE '<goal_round>%'
124
+ OR (content LIKE '%Objective: "%' AND content LIKE '%Round: %'))`;
125
+
126
+ try {
127
+ if (apply) report.backup = backup();
128
+
129
+ const archiveGoal = `UPDATE traces SET state = 'archived', updated_at = ?
130
+ WHERE scope_id = ? AND state = 'active' AND ${GOAL_ROUND}`;
131
+ report.goalRounds = apply
132
+ ? run(archiveGoal, now, scopeId)
133
+ : count(`SELECT COUNT(*) AS c FROM traces WHERE scope_id = ? AND state = 'active' AND ${GOAL_ROUND}`, scopeId);
134
+
135
+ const archiveInjected = `UPDATE traces SET state = 'archived', updated_at = ?
136
+ WHERE scope_id = ? AND state = 'active' AND (${INJECTED})`;
137
+ report.injectedTraces = apply
138
+ ? run(archiveInjected, now, scopeId)
139
+ : count(`SELECT COUNT(*) AS c FROM traces WHERE scope_id = ? AND state = 'active' AND (${INJECTED})`, scopeId);
140
+
141
+ const groups = db.prepare(`
142
+ SELECT level, content, GROUP_CONCAT(id) AS ids FROM summaries
143
+ WHERE scope_id = ? GROUP BY level, content HAVING COUNT(*) > 1
144
+ `).all(scopeId);
145
+ for (const group of groups) {
146
+ const ids = String(group.ids ?? '').split(',').filter(Boolean);
147
+ for (const id of ids.slice(1)) {
148
+ report.duplicateSummaries += 1;
149
+ if (apply) run('DELETE FROM summaries WHERE id = ?', id);
150
+ }
151
+ }
152
+
153
+ report.staleIntentions = apply
154
+ ? run("UPDATE intentions SET status = 'expired' WHERE scope_id = ? AND status = 'pending' AND expires_at IS NOT NULL AND expires_at < ?", scopeId, now)
155
+ : count("SELECT COUNT(*) AS c FROM intentions WHERE scope_id = ? AND status = 'pending' AND expires_at IS NOT NULL AND expires_at < ?", scopeId, now);
156
+
157
+ const fragmentWhere = "(title LIKE '|%' OR title LIKE '%|%' OR length(title) > 120 OR length(title) < 8)";
158
+ report.fragmentRules = apply
159
+ ? run(`UPDATE playbook_rules SET status = 'retired', updated_at = ? WHERE scope_id = ? AND status = 'candidate' AND ${fragmentWhere}`, now, scopeId)
160
+ : count(`SELECT COUNT(*) AS c FROM playbook_rules WHERE scope_id = ? AND status = 'candidate' AND ${fragmentWhere}`, scopeId);
161
+
162
+ const zombieWhere = `d.status = 'open' AND fa.status != 'active' AND fb.status != 'active'`;
163
+ const zombieJoin = `FROM disputes d JOIN facts fa ON fa.id = d.fact_a JOIN facts fb ON fb.id = d.fact_b`;
164
+ report.zombieDisputes = apply
165
+ ? run(`UPDATE disputes SET status = 'resolved', resolved_at = ?, resolution = 'auto: both facts invalidated'
166
+ WHERE id IN (SELECT d.id ${zombieJoin} WHERE ${zombieWhere} AND d.scope_id = ?)`, now, scopeId)
167
+ : count(`SELECT COUNT(*) AS c ${zombieJoin} WHERE ${zombieWhere} AND d.scope_id = ?`, scopeId);
168
+
169
+ // Title backfill: early captures kept "会话 N 的对话" or no title at all, which
170
+ // made the recall block unreadable. Derive one from the first real line.
171
+ const LEGACY_TITLE = "(title IS NULL OR title = '' OR title LIKE '会话 %')";
172
+ const titleRows = db.prepare(`SELECT id, content FROM traces WHERE scope_id = ? AND state = 'active' AND ${LEGACY_TITLE}`).all(scopeId);
173
+ report.titles = titleRows.length;
174
+ report.titleFixes = 0;
175
+ if (apply) {
176
+ for (const row of titleRows) {
177
+ const title = deriveTitle(row.content);
178
+ if (title) report.titleFixes += run('UPDATE traces SET title = ?, updated_at = ? WHERE id = ?', title, now, row.id);
179
+ }
180
+ }
181
+
182
+ // Opt-in: bring pre-v2 episode summaries onto the importance-weighted coverage
183
+ // definition. Reports the diff even in dry-run so the change can be reviewed.
184
+ // Opt-in: archive facts that are sentence fragments instead of assertions
185
+ // ("at → 等", "will → 收一收", "tail_fin_still_in → 水里"). Dry-run reports the
186
+ // set; --apply invalidates them through the normal backup gate.
187
+ if (dropNoiseFacts) {
188
+ const STOP = ['等', '等等', '收一收', '水里', '那里', '这里', '一下子', '一点', '一些', '什么', '怎么', '那样', '这样'];
189
+ const placeholders = STOP.map(() => '?').join(',');
190
+ const rows = db.prepare(`
191
+ SELECT id, predicate, object_literal FROM facts
192
+ WHERE scope_id = ? AND status = 'active' AND (
193
+ (predicate IN ('at','will') AND (object_literal IS NULL OR length(object_literal) <= 3))
194
+ OR object_literal IN (${placeholders})
195
+ OR length(predicate) > 28
196
+ )
197
+ ORDER BY recorded_at ASC LIMIT 2000
198
+ `).all(scopeId, ...STOP);
199
+ const plan = { candidates: rows.length, applied: 0, sample: rows.slice(0, 5).map((row) => `${row.predicate}→${row.object_literal ?? '(entity)'}`) };
200
+ if (apply) {
201
+ const stmt = db.prepare("UPDATE facts SET status = 'invalidated', invalidated_by = 'repair:noise-facts', valid_to = ?, updated_at = ? WHERE id = ?");
202
+ for (const row of rows) stmt.run(now, now, row.id);
203
+ plan.applied = rows.length;
204
+ }
205
+ report.noiseFacts = plan;
206
+ }
207
+ if (rewriteCoverage) {
208
+ const result = recomputeEpisodeCoverage({ db, scopeId });
209
+ const plan = { candidates: result.candidates, changed: result.updates.length, applied: 0, sample: result.updates.slice(0, 5) };
210
+ if (apply) {
211
+ const stmt = db.prepare("UPDATE summaries SET coverage = ?, model = 'extractive-v2-recomputed' WHERE id = ?");
212
+ for (const item of result.updates) {
213
+ stmt.run(item.to, item.id);
214
+ plan.applied += 1;
215
+ }
216
+ }
217
+ report.coverageRewrite = plan;
218
+ }
219
+
220
+ // Opt-in: merge near-duplicate episode summaries. Keeps the newest of each
221
+ // cluster and records a level='merge' summary so the deleted source ids stay
222
+ // traceable. Dry runs only report the clusters.
223
+ if (dedupeEpisodes) {
224
+ const result = findDuplicateEpisodes({ db, scopeId });
225
+ const plan = {
226
+ candidates: result.candidates,
227
+ clusters: result.clusters.length,
228
+ removed: 0,
229
+ merged: 0,
230
+ sample: result.clusters.slice(0, 5).map((cluster) => ({
231
+ keep: cluster.keep.id,
232
+ remove: cluster.remove.map((item) => item.id),
233
+ contentSim: cluster.contentSim,
234
+ sources: cluster.unionSources.length,
235
+ })),
236
+ };
237
+ if (apply) {
238
+ const remove = db.prepare('DELETE FROM summaries WHERE id = ?');
239
+ const insertMerge = db.prepare(`
240
+ INSERT INTO summaries(id, scope_id, level, period_start, period_end, content, source_ids_json, coverage, created_at, model)
241
+ VALUES (?, ?, 'merge', ?, ?, ?, ?, ?, ?, 'dedupe-v1')
242
+ `);
243
+ for (const cluster of result.clusters) {
244
+ for (const item of cluster.remove) {
245
+ remove.run(item.id);
246
+ plan.removed += 1;
247
+ }
248
+ insertMerge.run(
249
+ summaryId(),
250
+ scopeId,
251
+ cluster.keep.periodStart ?? null,
252
+ cluster.keep.periodEnd ?? null,
253
+ `合并 ${cluster.remove.length} 条近重复的每日摘要(保留 ${cluster.keep.id})`,
254
+ JSON.stringify(cluster.unionSources),
255
+ Number(cluster.keep.coverage ?? 0),
256
+ now,
257
+ );
258
+ plan.merged += 1;
259
+ }
260
+ }
261
+ report.dedupeEpisodes = plan;
262
+ }
263
+
264
+ if (userAddress) {
265
+ const placeholders = aliases.map(() => '?').join(',');
266
+ const mergeRelationships = apply
267
+ ? db.prepare(`SELECT COUNT(*) AS c FROM relationships WHERE scope_id = ? AND target != ? AND target IN (${placeholders})`).get(scopeId, userAddress, ...aliases).c
268
+ : count(`SELECT COUNT(*) AS c FROM relationships WHERE scope_id = ? AND target != ? AND target IN (${placeholders})`, scopeId, userAddress, ...aliases);
269
+ const mergeAffect = count(`SELECT COUNT(*) AS c FROM affect_targets WHERE scope_id = ? AND target != ? AND target IN (${placeholders})`, scopeId, userAddress, ...aliases);
270
+ report.aliasRows = Number(mergeRelationships) + Number(mergeAffect);
271
+ if (apply && report.aliasRows > 0) {
272
+ const canon = db.prepare('SELECT * FROM relationships WHERE scope_id = ? AND target = ?').get(scopeId, userAddress);
273
+ for (const row of db.prepare(`SELECT * FROM relationships WHERE scope_id = ? AND target != ? AND target IN (${placeholders})`).all(scopeId, userAddress, ...aliases)) {
274
+ if (canon) {
275
+ run(`UPDATE relationships SET trust = MAX(trust, ?), care = MAX(care, ?), familiarity = MAX(familiarity, ?), updated_at = ? WHERE scope_id = ? AND target = ?`,
276
+ Number(row.trust), Number(row.care), Number(row.familiarity), now, scopeId, userAddress);
277
+ run('DELETE FROM relationships WHERE scope_id = ? AND target = ?', scopeId, row.target);
278
+ } else {
279
+ run('UPDATE relationships SET target = ? WHERE scope_id = ? AND target = ?', userAddress, scopeId, row.target);
280
+ }
281
+ }
282
+ const canonAffect = db.prepare('SELECT * FROM affect_targets WHERE scope_id = ? AND target = ?').get(scopeId, userAddress);
283
+ for (const row of db.prepare(`SELECT * FROM affect_targets WHERE scope_id = ? AND target != ? AND target IN (${placeholders})`).all(scopeId, userAddress, ...aliases)) {
284
+ if (canonAffect) {
285
+ run('UPDATE affect_targets SET count = count + ?, updated_at = ? WHERE scope_id = ? AND target = ?', Number(row.count) || 0, now, scopeId, userAddress);
286
+ run('DELETE FROM affect_targets WHERE scope_id = ? AND target = ?', scopeId, row.target);
287
+ } else {
288
+ run('UPDATE affect_targets SET target = ? WHERE scope_id = ? AND target = ?', userAddress, scopeId, row.target);
289
+ }
290
+ }
291
+ }
292
+ }
293
+ } finally {
294
+ db.close();
295
+ }
296
+
297
+ console.log(JSON.stringify(report, null, 2));
298
+
299
+ // A JSON dump answers "what changed" for a script but not for a human: "changed:
300
+ // 4" says nothing about which rows. Keep the JSON stable and append a short
301
+ // readable block for whoever runs this by hand.
302
+ const human = [];
303
+ human.push(`== repair 报告(${apply ? '已写入' : '空跑,未写入'})==`);
304
+ human.push(`库:${dbPath}`);
305
+ human.push(`归档 goal_round 旧轮次:${report.goalRounds}`);
306
+ human.push(`归档注入上下文痕迹:${report.injectedTraces}`);
307
+ if (report.titles) human.push(`标题回填:候选 ${report.titles} / 实修 ${report.titleFixes ?? 0}`);
308
+ if (report.duplicateSummaries) human.push(`删除重复摘要:${report.duplicateSummaries}`);
309
+ if (report.staleIntentions) human.push(`过期意图:${report.staleIntentions}`);
310
+ if (report.fragmentRules) human.push(`退役碎片准则:${report.fragmentRules}`);
311
+ if (report.zombieDisputes) human.push(`清理僵尸争议:${report.zombieDisputes}`);
312
+ if (report.aliasRows && userAddress) human.push(`合并别名(${userAddress}):${report.aliasRows} 行`);
313
+ if (report.coverageRewrite) {
314
+ const c = report.coverageRewrite;
315
+ human.push(`覆盖重算:候选 ${c.candidates} / 需改 ${c.changed} / 已写 ${c.applied}`);
316
+ for (const item of c.sample ?? []) human.push(` - ${item.id}:${item.from} → ${item.to}(覆盖 ${item.sources}/${item.window})`);
317
+ }
318
+ if (report.dedupeEpisodes) {
319
+ const d = report.dedupeEpisodes;
320
+ human.push(`摘要去重:候选 ${d.candidates} / 成簇 ${d.clusters} / 删除 ${d.removed} / 合并记录 ${d.merged}`);
321
+ for (const item of d.sample ?? []) human.push(` - 保留 ${item.keep},合并 ${item.remove.join('、')}(内容相似 ${item.contentSim},来源 ${item.sources} 条)`);
322
+ }
323
+ if (report.backup) human.push(`备份:${report.backup}`);
324
+ // stderr, not stdout: callers pipe stdout into ConvertFrom-Json / JSON.parse.
325
+ // The readable block is for a person watching the console; the machine contract
326
+ // stays "stdout is exactly one JSON document".
327
+ console.error(`\n${human.join('\n')}`);
328
+ if (!apply) console.error('\nDry run only. Re-run with --apply to write (backs up first).');