recallnest 2.2.1 → 2.5.4

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 (227) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +46 -35
  3. package/README_CN.md +41 -26
  4. package/assets/ui/app.js +1031 -0
  5. package/assets/ui/index.html +224 -0
  6. package/assets/ui/styles.css +781 -0
  7. package/config.json.example +4 -1
  8. package/connectors/examples/email-adapter.ts +73 -0
  9. package/connectors/examples/logs-adapter.ts +103 -0
  10. package/connectors/examples/rss-adapter.ts +95 -0
  11. package/docs/api-reference.md +1291 -0
  12. package/docs/architecture.md +168 -0
  13. package/docs/connector-spec.md +126 -0
  14. package/eval/cases-canary.json +58 -0
  15. package/eval/cases-scope-robustness.json +278 -0
  16. package/eval/cases.json +117 -20
  17. package/package.json +22 -1
  18. package/src/__tests__/access-tracker-novelty.test.ts +238 -0
  19. package/src/__tests__/activity-counter.test.ts +125 -0
  20. package/src/__tests__/adaptive-fidelity.test.ts +102 -0
  21. package/src/__tests__/admission-control.test.ts +206 -0
  22. package/src/__tests__/anchor-generator.test.ts +67 -0
  23. package/src/__tests__/auto-consolidation.test.ts +168 -0
  24. package/src/__tests__/auto-recall.test.ts +131 -0
  25. package/src/__tests__/babel-integration.test.ts +144 -0
  26. package/src/__tests__/batch-dedup.test.ts +65 -0
  27. package/src/__tests__/canary-eval.test.ts +114 -0
  28. package/src/__tests__/capture-engine.test.ts +1238 -0
  29. package/src/__tests__/capture-heuristic.test.ts +171 -0
  30. package/src/__tests__/cascade-forget.test.ts +210 -0
  31. package/src/__tests__/category-min-scores.test.ts +33 -0
  32. package/src/__tests__/cc8-cc1-essential-context.test.ts +298 -0
  33. package/src/__tests__/circuit-breaker.test.ts +99 -0
  34. package/src/__tests__/cluster-consolidation.test.ts +782 -0
  35. package/src/__tests__/confidence-metadata.test.ts +125 -0
  36. package/src/__tests__/confidence-tracker.test.ts +261 -0
  37. package/src/__tests__/conflict-advisor.test.ts +206 -0
  38. package/src/__tests__/conflict-escalation.test.ts +149 -0
  39. package/src/__tests__/conflict-lifecycle.test.ts +83 -0
  40. package/src/__tests__/conflict-output.test.ts +85 -0
  41. package/src/__tests__/conflict-store.test.ts +374 -0
  42. package/src/__tests__/connector-v1.test.ts +181 -0
  43. package/src/__tests__/consolidation-engine.test.ts +333 -0
  44. package/src/__tests__/constructive-retrieval.test.ts +509 -0
  45. package/src/__tests__/context-collapse-renderer.test.ts +214 -0
  46. package/src/__tests__/context-composer-pins.test.ts +64 -0
  47. package/src/__tests__/context-composer-task-selection.test.ts +24 -0
  48. package/src/__tests__/context-reconstructor.test.ts +65 -0
  49. package/src/__tests__/context-renderer.test.ts +91 -0
  50. package/src/__tests__/continuity-eval.test.ts +275 -0
  51. package/src/__tests__/continuity-schema.test.ts +97 -0
  52. package/src/__tests__/contracts.test.ts +216 -0
  53. package/src/__tests__/conversation-importer.test.ts +692 -0
  54. package/src/__tests__/core-recall-eval.test.ts +235 -0
  55. package/src/__tests__/core-summary.test.ts +109 -0
  56. package/src/__tests__/data-checkup.test.ts +276 -0
  57. package/src/__tests__/decay-exemption.test.ts +84 -0
  58. package/src/__tests__/dedup-actions.test.ts +58 -0
  59. package/src/__tests__/dedup-guard.test.ts +39 -0
  60. package/src/__tests__/deterministic-id.test.ts +39 -0
  61. package/src/__tests__/distill-lock.test.ts +305 -0
  62. package/src/__tests__/distill-session-argshape.test.ts +79 -0
  63. package/src/__tests__/doctor.test.ts +319 -0
  64. package/src/__tests__/dream-pipeline.test.ts +321 -0
  65. package/src/__tests__/drill-down.test.ts +108 -0
  66. package/src/__tests__/embedder.test.ts +122 -0
  67. package/src/__tests__/emotion-decay.test.ts +46 -0
  68. package/src/__tests__/emotion-detector.test.ts +56 -0
  69. package/src/__tests__/emotion-phase1-integration.test.ts +153 -0
  70. package/src/__tests__/emotion-retrieval.test.ts +56 -0
  71. package/src/__tests__/entity-resolver.test.ts +58 -0
  72. package/src/__tests__/env-config.test.ts +151 -0
  73. package/src/__tests__/error-signature-boost.test.ts +87 -0
  74. package/src/__tests__/error-signature.test.ts +95 -0
  75. package/src/__tests__/error-taxonomy.test.ts +129 -0
  76. package/src/__tests__/ethics-layer.test.ts +476 -0
  77. package/src/__tests__/event-segmenter.test.ts +153 -0
  78. package/src/__tests__/feature-flags-integration.test.ts +54 -0
  79. package/src/__tests__/frequency-tracker.test.ts +113 -0
  80. package/src/__tests__/graph-export.test.ts +489 -0
  81. package/src/__tests__/hotness-blend.test.ts +76 -0
  82. package/src/__tests__/ingest-chunking.test.ts +44 -0
  83. package/src/__tests__/ingest.test.ts +360 -0
  84. package/src/__tests__/interference-detector.test.ts +203 -0
  85. package/src/__tests__/kg-extractor.test.ts +192 -0
  86. package/src/__tests__/kg-store.test.ts +300 -0
  87. package/src/__tests__/llm-consolidation.test.ts +226 -0
  88. package/src/__tests__/maintenance-locks.test.ts +174 -0
  89. package/src/__tests__/mcp-efficiency.test.ts +288 -0
  90. package/src/__tests__/mcp-related-scopes.test.ts +151 -0
  91. package/src/__tests__/memory-boundaries.test.ts +250 -0
  92. package/src/__tests__/memory-evolution-b2-b3-e1.test.ts +345 -0
  93. package/src/__tests__/memory-evolution.test.ts +271 -0
  94. package/src/__tests__/memory-health-rebalance.test.ts +144 -0
  95. package/src/__tests__/memory-lint.test.ts +421 -0
  96. package/src/__tests__/memory-output.test.ts +215 -0
  97. package/src/__tests__/memory-promotion.test.ts +315 -0
  98. package/src/__tests__/migrate-dedup-ids.test.ts +65 -0
  99. package/src/__tests__/multi-vector.test.ts +242 -0
  100. package/src/__tests__/narrative-architecture.test.ts +456 -0
  101. package/src/__tests__/noise-filter.test.ts +205 -0
  102. package/src/__tests__/obsidian-connector.test.ts +363 -0
  103. package/src/__tests__/omitted-reporting.test.ts +98 -0
  104. package/src/__tests__/pending-review.test.ts +77 -0
  105. package/src/__tests__/pii-redact.test.ts +314 -0
  106. package/src/__tests__/post-retrieval-filter.test.ts +178 -0
  107. package/src/__tests__/ppr-traversal.test.ts +256 -0
  108. package/src/__tests__/prediction-engine.test.ts +349 -0
  109. package/src/__tests__/predictive-prospective-memory.test.ts +416 -0
  110. package/src/__tests__/preference-guard-smoke.test.ts +211 -0
  111. package/src/__tests__/preference-matcher.test.ts +230 -0
  112. package/src/__tests__/preference-slots.test.ts +205 -0
  113. package/src/__tests__/prospective-memory.test.ts +283 -0
  114. package/src/__tests__/query-entity-detector.test.ts +171 -0
  115. package/src/__tests__/query-expander-alias.test.ts +146 -0
  116. package/src/__tests__/query-expander.test.ts +34 -0
  117. package/src/__tests__/recall-governor.test.ts +227 -0
  118. package/src/__tests__/recall-mode.test.ts +64 -0
  119. package/src/__tests__/result-synthesizer.test.ts +198 -0
  120. package/src/__tests__/resume-context.test.ts +4898 -0
  121. package/src/__tests__/retrieval-trace.test.ts +213 -0
  122. package/src/__tests__/retriever-boundary-weight.test.ts +136 -0
  123. package/src/__tests__/retroactive-boost.test.ts +223 -0
  124. package/src/__tests__/salience-scoring.test.ts +106 -0
  125. package/src/__tests__/scope-inventory.test.ts +200 -0
  126. package/src/__tests__/scope-policy.test.ts +69 -0
  127. package/src/__tests__/scope-suggester.test.ts +80 -0
  128. package/src/__tests__/session-checkpoint.test.ts +291 -0
  129. package/src/__tests__/session-distiller.test.ts +640 -0
  130. package/src/__tests__/session-gc.test.ts +215 -0
  131. package/src/__tests__/skill-engine.test.ts +552 -0
  132. package/src/__tests__/skill-promotion.test.ts +601 -0
  133. package/src/__tests__/skill-verifier.test.ts +122 -0
  134. package/src/__tests__/source-heartbeat.test.ts +250 -0
  135. package/src/__tests__/store-patch-metadata.test.ts +205 -0
  136. package/src/__tests__/store-scope-audit.test.ts +81 -0
  137. package/src/__tests__/store-upsert.test.ts +184 -0
  138. package/src/__tests__/supersede-chain.test.ts +154 -0
  139. package/src/__tests__/temporal-parser.test.ts +241 -0
  140. package/src/__tests__/temporal-validity.test.ts +160 -0
  141. package/src/__tests__/term-registry.test.ts +121 -0
  142. package/src/__tests__/tool-error-surfacing.test.ts +98 -0
  143. package/src/__tests__/tool-output-compressor.test.ts +160 -0
  144. package/src/__tests__/topic-tag.test.ts +113 -0
  145. package/src/__tests__/trusted-memory.test.ts +839 -0
  146. package/src/__tests__/usage-tracker.test.ts +287 -0
  147. package/src/__tests__/version-manager.test.ts +213 -0
  148. package/src/__tests__/workflow-observation-skill-outcome.test.ts +352 -0
  149. package/src/__tests__/workflow-observation.test.ts +433 -0
  150. package/src/__tests__/write-verifier.test.ts +122 -0
  151. package/src/access-tracker.ts +38 -32
  152. package/src/activity-counter.ts +46 -18
  153. package/src/aliases.ts +133 -0
  154. package/src/api-server.ts +27 -7
  155. package/src/audit-log.ts +4 -2
  156. package/src/auto-consolidation.ts +8 -3
  157. package/src/auto-gc.ts +85 -21
  158. package/src/capture-engine.ts +54 -21
  159. package/src/cli.ts +199 -37
  160. package/src/confidence-tracker.ts +36 -18
  161. package/src/connector-types.ts +57 -0
  162. package/src/consolidation-engine.ts +109 -11
  163. package/src/context-composer.ts +8 -1
  164. package/src/conversation-importer.ts +25 -1
  165. package/src/data-checkup.ts +126 -7
  166. package/src/distill-lock.ts +194 -15
  167. package/src/doctor.ts +38 -2
  168. package/src/dream-pipeline.ts +118 -34
  169. package/src/env-config.ts +77 -0
  170. package/src/error-signature.ts +153 -0
  171. package/src/error-taxonomy.ts +115 -0
  172. package/src/eval.ts +251 -6
  173. package/src/idempotency.ts +8 -0
  174. package/src/ingest.ts +234 -10
  175. package/src/kg-extractor.ts +6 -2
  176. package/src/kg-store.ts +236 -44
  177. package/src/llm-consolidation.ts +2 -1
  178. package/src/mcp-server.ts +85 -1799
  179. package/src/mcp-tool-deps.ts +48 -0
  180. package/src/mcp-tools-advanced.ts +941 -0
  181. package/src/mcp-tools-core.ts +633 -0
  182. package/src/mcp-tools-governance.ts +475 -0
  183. package/src/memory-boundaries.ts +3 -1
  184. package/src/memory-evolution.ts +73 -1
  185. package/src/memory-lint.ts +183 -10
  186. package/src/memory-output.ts +114 -3
  187. package/src/memory-promotion.ts +246 -0
  188. package/src/memory-schema.ts +25 -2
  189. package/src/memory-store-port.ts +43 -0
  190. package/src/multi-vector.ts +2 -1
  191. package/src/narrative-schema.ts +2 -1
  192. package/src/noise-filter.ts +57 -6
  193. package/src/obsidian-connector.ts +282 -0
  194. package/src/pii-detector.ts +157 -5
  195. package/src/query-expander.ts +90 -9
  196. package/src/result-synthesizer.ts +2 -1
  197. package/src/retention-policy.ts +2 -1
  198. package/src/retriever.ts +259 -139
  199. package/src/runtime-config.ts +8 -1
  200. package/src/scope-suggester.ts +113 -0
  201. package/src/session-distiller.ts +23 -2
  202. package/src/session-engine.ts +2 -1
  203. package/src/session-schema.ts +3 -2
  204. package/src/session-store.ts +5 -0
  205. package/src/skill-engine.ts +78 -0
  206. package/src/skill-promotion.ts +247 -47
  207. package/src/skill-schema.ts +16 -3
  208. package/src/skill-verifier.ts +152 -0
  209. package/src/source-heartbeat.ts +108 -0
  210. package/src/store.ts +267 -38
  211. package/src/tool-output-compressor.ts +3 -1
  212. package/src/ui-server.ts +2 -1
  213. package/src/usage-tracker.ts +242 -0
  214. package/src/version-manager.ts +3 -2
  215. package/src/workflow-observation-engine.ts +2 -1
  216. package/src/workflow-observation-schema.ts +2 -1
  217. package/src/workflow-observation-store.ts +6 -2
  218. package/.env +0 -4
  219. package/CLAUDE.md +0 -46
  220. package/config.json +0 -55
  221. package/daily-recall.sh +0 -110
  222. package/logs/daily-recall.error.log +0 -0
  223. package/logs/daily-recall.log +0 -30
  224. package/logs/ingest-2026-04-11.log +0 -110
  225. package/logs/ingest-2026-04-12.log +0 -90
  226. package/logs/launchagent-stderr.log +0 -0
  227. package/logs/launchagent-stdout.log +0 -0
@@ -0,0 +1,144 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import {
4
+ buildMemoryHealthRebalancePlan,
5
+ computeRebalancedImportance,
6
+ getMemoryHealthAccessCount,
7
+ getStoredMemoryTier,
8
+ parseMemoryHealthMetadata,
9
+ resolveRebalancedTier,
10
+ summarizeMemoryHealthPlans,
11
+ } from "../memory-health-rebalance.js";
12
+
13
+ const datasetStats = {
14
+ maxAccessCount: 19,
15
+ minTimestamp: Date.parse("2026-03-02T00:00:00.000Z"),
16
+ maxTimestamp: Date.parse("2026-03-19T00:00:00.000Z"),
17
+ };
18
+
19
+ describe("memory health rebalance", () => {
20
+ it("parses metadata safely and supports both accessCount key styles", () => {
21
+ expect(parseMemoryHealthMetadata("{")).toEqual({});
22
+ expect(getMemoryHealthAccessCount({ accessCount: 3 })).toBe(3);
23
+ expect(getMemoryHealthAccessCount({ access_count: 4 })).toBe(4);
24
+ expect(getStoredMemoryTier({ tier: "working" })).toBe("working");
25
+ expect(getStoredMemoryTier({ tier: "unknown" })).toBe("unknown");
26
+ });
27
+
28
+ it("demotes dead memories to peripheral even when they already had a hotter tier", () => {
29
+ const plan = buildMemoryHealthRebalancePlan({
30
+ id: "dead-memory",
31
+ importance: 0.8,
32
+ timestamp: datasetStats.minTimestamp,
33
+ metadata: JSON.stringify({ tier: "working", accessCount: 0 }),
34
+ }, datasetStats);
35
+
36
+ expect(resolveRebalancedTier("working", 0)).toBe("peripheral");
37
+ expect(plan.targetTier).toBe("peripheral");
38
+ expect(plan.deadMemoryRow).toBe(true);
39
+ expect(plan.deadMemoryDemoted).toBe(true);
40
+ expect(plan.nextImportance).toBeGreaterThanOrEqual(0.3);
41
+ expect(plan.nextImportance).toBeLessThanOrEqual(0.5);
42
+ expect(plan.nextMetadata.tier).toBe("peripheral");
43
+ expect(plan.nextMetadata.importance).toBe(plan.nextImportance);
44
+ });
45
+
46
+ it("backfills unknown tiers from access counts", () => {
47
+ const corePlan = buildMemoryHealthRebalancePlan({
48
+ id: "unknown-core",
49
+ importance: 0.7,
50
+ timestamp: datasetStats.maxTimestamp,
51
+ metadata: JSON.stringify({ accessCount: 6 }),
52
+ }, datasetStats);
53
+ const workingPlan = buildMemoryHealthRebalancePlan({
54
+ id: "unknown-working",
55
+ importance: 0.7,
56
+ timestamp: datasetStats.maxTimestamp,
57
+ metadata: JSON.stringify({ accessCount: 3 }),
58
+ }, datasetStats);
59
+
60
+ expect(corePlan.currentTier).toBe("unknown");
61
+ expect(corePlan.targetTier).toBe("core");
62
+ expect(corePlan.tierBackfilled).toBe(true);
63
+ expect(corePlan.nextImportance).toBeGreaterThanOrEqual(0.85);
64
+ expect(corePlan.nextImportance).toBeLessThanOrEqual(0.95);
65
+
66
+ expect(workingPlan.targetTier).toBe("working");
67
+ expect(workingPlan.nextImportance).toBeGreaterThanOrEqual(0.6);
68
+ expect(workingPlan.nextImportance).toBeLessThanOrEqual(0.8);
69
+ });
70
+
71
+ it("keeps existing non-dead tiers and only reshapes importance within the tier band", () => {
72
+ const lowPlan = buildMemoryHealthRebalancePlan({
73
+ id: "working-low",
74
+ importance: 0.6,
75
+ timestamp: datasetStats.minTimestamp,
76
+ metadata: JSON.stringify({ tier: "working", accessCount: 2 }),
77
+ }, datasetStats);
78
+ const highPlan = buildMemoryHealthRebalancePlan({
79
+ id: "working-high",
80
+ importance: 0.8,
81
+ timestamp: datasetStats.maxTimestamp,
82
+ metadata: JSON.stringify({ tier: "working", accessCount: 5 }),
83
+ }, datasetStats);
84
+
85
+ expect(lowPlan.targetTier).toBe("working");
86
+ expect(highPlan.targetTier).toBe("working");
87
+ expect(lowPlan.nextImportance).toBeLessThan(highPlan.nextImportance);
88
+ expect(lowPlan.nextImportance).toBeGreaterThanOrEqual(0.6);
89
+ expect(highPlan.nextImportance).toBeLessThanOrEqual(0.8);
90
+ });
91
+
92
+ it("uses access_count and existing importance together instead of hard-overwriting values", () => {
93
+ const cooler = computeRebalancedImportance(0.6, "core", 6, 19, 0.2);
94
+ const hotter = computeRebalancedImportance(0.9, "core", 19, 19, 0.9);
95
+
96
+ expect(cooler).toBeGreaterThanOrEqual(0.85);
97
+ expect(hotter).toBeLessThanOrEqual(0.95);
98
+ expect(hotter).toBeGreaterThan(cooler);
99
+ });
100
+
101
+ it("uses recency to spread dead peripheral memories within the peripheral band", () => {
102
+ const older = buildMemoryHealthRebalancePlan({
103
+ id: "dead-old",
104
+ importance: 0.35,
105
+ timestamp: datasetStats.minTimestamp,
106
+ metadata: JSON.stringify({ accessCount: 0 }),
107
+ }, datasetStats);
108
+ const newer = buildMemoryHealthRebalancePlan({
109
+ id: "dead-new",
110
+ importance: 0.35,
111
+ timestamp: datasetStats.maxTimestamp,
112
+ metadata: JSON.stringify({ accessCount: 0 }),
113
+ }, datasetStats);
114
+
115
+ expect(older.targetTier).toBe("peripheral");
116
+ expect(newer.targetTier).toBe("peripheral");
117
+ expect(older.nextImportance).toBeGreaterThanOrEqual(0.3);
118
+ expect(newer.nextImportance).toBeLessThanOrEqual(0.5);
119
+ expect(newer.nextImportance).toBeGreaterThan(older.nextImportance);
120
+ });
121
+
122
+ it("summarizes rebalance plans for reporting", () => {
123
+ const summary = summarizeMemoryHealthPlans([
124
+ buildMemoryHealthRebalancePlan({
125
+ id: "a",
126
+ importance: 0.7,
127
+ timestamp: datasetStats.minTimestamp,
128
+ metadata: JSON.stringify({ accessCount: 0 }),
129
+ }, datasetStats),
130
+ buildMemoryHealthRebalancePlan({
131
+ id: "b",
132
+ importance: 0.7,
133
+ timestamp: datasetStats.maxTimestamp,
134
+ metadata: JSON.stringify({ tier: "working", accessCount: 4 }),
135
+ }, datasetStats),
136
+ ]);
137
+
138
+ expect(summary.totalRows).toBe(2);
139
+ expect(summary.changedRows).toBe(2);
140
+ expect(summary.deadMemoryRows).toBe(1);
141
+ expect(summary.tierBackfills).toBe(1);
142
+ expect(summary.importanceChanges).toBe(2);
143
+ });
144
+ });
@@ -0,0 +1,421 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { runMemoryLint, formatMemoryLintReport, computeHealthScore, type MemoryLintReport } from "../memory-lint.js";
3
+ import type { MemoryEntry, MemoryStore } from "../store.js";
4
+
5
+ // ---------------------------------------------------------------------------
6
+ // Helpers
7
+ // ---------------------------------------------------------------------------
8
+
9
+ function makeEntry(overrides: Partial<MemoryEntry> & { id: string }): MemoryEntry {
10
+ return {
11
+ text: "test memory",
12
+ vector: [1, 0, 0, 0, 0],
13
+ category: "events",
14
+ scope: "project:test",
15
+ importance: 0.7,
16
+ timestamp: Date.now(),
17
+ metadata: JSON.stringify({
18
+ evolution: {
19
+ status: "active",
20
+ version: 1,
21
+ accessCount: 0,
22
+ lastAccessedAt: null,
23
+ supersededBy: null,
24
+ supersedes: null,
25
+ evolutionNote: null,
26
+ consolidatedInto: null,
27
+ contributedToPattern: null,
28
+ sourceMemories: [],
29
+ validFrom: Date.now(),
30
+ validUntil: null,
31
+ },
32
+ }),
33
+ ...overrides,
34
+ };
35
+ }
36
+
37
+ function createMockStore(entries: MemoryEntry[]): Pick<MemoryStore, "list" | "getVectors"> {
38
+ return {
39
+ // 复刻真实 store:list() 为性能不返回向量(vector: []),lint 需经 getVectors 补回。
40
+ // 旧 mock 直接返回带向量的 entry,与生产行为不符,曾掩盖矛盾/去重在生产哑火的 bug。
41
+ async list() { return entries.map(e => ({ ...e, vector: [] })); },
42
+ async getVectors(ids: string[]) {
43
+ const map = new Map<string, number[]>();
44
+ for (const e of entries) {
45
+ if (ids.includes(e.id) && e.vector.length > 0) map.set(e.id, e.vector);
46
+ }
47
+ return map;
48
+ },
49
+ } as Pick<MemoryStore, "list" | "getVectors">;
50
+ }
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Cold memories (P0 B-1 observation)
54
+ // ---------------------------------------------------------------------------
55
+
56
+ describe("cold memory lint (P0 B-1)", () => {
57
+ it("aggregates cold memories into a single info finding with top ids (flag on)", async () => {
58
+ process.env.RECALLNEST_CONSTRUCTIVE_RETRIEVAL = "true";
59
+ try {
60
+ const coldMeta = (n: number) => JSON.stringify({
61
+ accessCount: n,
62
+ evolution: { status: "active", version: 1 },
63
+ });
64
+ // 向量彼此正交、文本不同,避免触发 duplicate/contradiction 干扰
65
+ const entries = [
66
+ makeEntry({ id: "cold-a", text: "alpha topic", vector: [1, 0, 0, 0, 0], metadata: coldMeta(12) }),
67
+ makeEntry({ id: "cold-b", text: "beta topic", vector: [0, 1, 0, 0, 0], metadata: coldMeta(7) }),
68
+ makeEntry({ id: "warm-c", text: "gamma topic", vector: [0, 0, 1, 0, 0], metadata: JSON.stringify({ accessCount: 9, usage: { useCount: 2 }, evolution: { status: "active", version: 1 } }) }),
69
+ ];
70
+
71
+ const report = await runMemoryLint({ store: createMockStore(entries) as MemoryStore });
72
+
73
+ expect(report.summary.coldMemories).toBe(2);
74
+ const finding = report.findings.find(f => f.check === "coldMemory");
75
+ expect(finding).toBeTruthy();
76
+ expect(finding!.severity).toBe("info");
77
+ // top ids sorted by injection desc
78
+ expect(finding!.memoryIds[0]).toBe("cold-a");
79
+ expect(finding!.memoryIds).toContain("cold-b");
80
+ expect(formatMemoryLintReport(report)).toContain("Cold Memories (2)");
81
+ } finally {
82
+ delete process.env.RECALLNEST_CONSTRUCTIVE_RETRIEVAL;
83
+ }
84
+ });
85
+
86
+ it("skips cold detection entirely when use signal is inactive (flag off)", async () => {
87
+ delete process.env.RECALLNEST_CONSTRUCTIVE_RETRIEVAL;
88
+ const coldishMeta = JSON.stringify({ accessCount: 12, evolution: { status: "active", version: 1 } });
89
+ const report = await runMemoryLint({
90
+ store: createMockStore([makeEntry({ id: "a", text: "alpha", metadata: coldishMeta })]) as MemoryStore,
91
+ });
92
+ expect(report.summary.coldMemories).toBe(0);
93
+ expect(report.findings.find(f => f.check === "coldMemory")).toBeUndefined();
94
+ });
95
+
96
+ it("health score dents only when cold share exceeds 10%, capped at 10", () => {
97
+ const base = { contradictions: 0, duplicates: 0, staleMemories: 0, orphans: 0, weakLessons: 0 };
98
+ // 5% cold -> no penalty
99
+ expect(computeHealthScore({ ...base, coldMemories: 5 }, 100)).toBe(100);
100
+ // 15% cold -> floor(15-10)=5 penalty
101
+ expect(computeHealthScore({ ...base, coldMemories: 15 }, 100)).toBe(95);
102
+ // 60% cold -> capped at 10
103
+ expect(computeHealthScore({ ...base, coldMemories: 60 }, 100)).toBe(90);
104
+ // backward compat: summary without coldMemories
105
+ expect(computeHealthScore(base, 100)).toBe(100);
106
+ });
107
+ });
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // runMemoryLint
111
+ // ---------------------------------------------------------------------------
112
+
113
+ describe("runMemoryLint", () => {
114
+ it("returns all-clear for healthy data", async () => {
115
+ const entries = [
116
+ makeEntry({ id: "a1", text: "User prefers dark mode", category: "preferences", vector: [1, 0, 0, 0, 0] }),
117
+ makeEntry({ id: "a2", text: "Project uses Bun runtime", category: "entities", vector: [0, 1, 0, 0, 0] }),
118
+ ];
119
+ const store = createMockStore(entries);
120
+ const report = await runMemoryLint({ store });
121
+
122
+ expect(report.healthScore).toBe(100);
123
+ expect(report.findings).toHaveLength(0);
124
+ expect(report.summary.contradictions).toBe(0);
125
+ expect(report.summary.duplicates).toBe(0);
126
+ expect(report.totalScanned).toBe(2);
127
+ });
128
+
129
+ it("detects contradictions in same scope+category", async () => {
130
+ const entries = [
131
+ makeEntry({ id: "c1", text: "Always use Bun for scripts", scope: "project:x", category: "patterns" }),
132
+ makeEntry({ id: "c2", text: "Never use Bun for scripts", scope: "project:x", category: "patterns" }),
133
+ ];
134
+ const store = createMockStore(entries);
135
+ const report = await runMemoryLint({ store });
136
+
137
+ expect(report.summary.contradictions).toBeGreaterThanOrEqual(1);
138
+ const finding = report.findings.find(f => f.check === "contradiction");
139
+ expect(finding).toBeDefined();
140
+ expect(finding!.memoryIds).toContain("c1");
141
+ expect(finding!.memoryIds).toContain("c2");
142
+ });
143
+
144
+ it("detects duplicates by vector similarity", async () => {
145
+ const vec = [0.5, 0.5, 0.5, 0.5, 0.5];
146
+ const entries = [
147
+ makeEntry({ id: "d1", text: "Docker port is 4318", vector: vec, scope: "project:x", category: "entities" }),
148
+ makeEntry({ id: "d2", text: "Docker port is 4318 config", vector: vec, scope: "project:x", category: "entities" }),
149
+ ];
150
+ const store = createMockStore(entries);
151
+ const report = await runMemoryLint({ store });
152
+
153
+ expect(report.summary.duplicates).toBeGreaterThanOrEqual(1);
154
+ const finding = report.findings.find(f => f.check === "duplicate");
155
+ expect(finding).toBeDefined();
156
+ });
157
+
158
+ it("detects stale memories (old, never accessed)", async () => {
159
+ const oldTimestamp = Date.now() - 120 * 24 * 60 * 60 * 1000; // 120 days ago
160
+ const entries = [
161
+ makeEntry({
162
+ id: "s1",
163
+ text: "Some old fact",
164
+ timestamp: oldTimestamp,
165
+ metadata: JSON.stringify({
166
+ evolution: {
167
+ status: "active",
168
+ version: 1,
169
+ accessCount: 0,
170
+ lastAccessedAt: null,
171
+ supersededBy: null,
172
+ supersedes: null,
173
+ evolutionNote: null,
174
+ consolidatedInto: null,
175
+ contributedToPattern: null,
176
+ sourceMemories: [],
177
+ validFrom: oldTimestamp,
178
+ validUntil: null,
179
+ },
180
+ }),
181
+ }),
182
+ ];
183
+ const store = createMockStore(entries);
184
+ const report = await runMemoryLint({ store });
185
+
186
+ expect(report.summary.staleMemories).toBe(1);
187
+ const finding = report.findings.find(f => f.check === "stale");
188
+ expect(finding).toBeDefined();
189
+ expect(finding!.severity).toBe("info");
190
+ });
191
+
192
+ it("detects orphans with missing scope", async () => {
193
+ const entries = [
194
+ makeEntry({ id: "o1", text: "Orphan memory", scope: "" }),
195
+ makeEntry({ id: "o2", text: "Schema entry", scope: "__schema__" }),
196
+ ];
197
+ const store = createMockStore(entries);
198
+ const report = await runMemoryLint({ store });
199
+
200
+ expect(report.summary.orphans).toBe(2);
201
+ });
202
+
203
+ it("detects broken consolidation links", async () => {
204
+ const entries = [
205
+ makeEntry({
206
+ id: "b1",
207
+ text: "Points to deleted",
208
+ metadata: JSON.stringify({
209
+ evolution: {
210
+ status: "active",
211
+ version: 1,
212
+ accessCount: 5,
213
+ lastAccessedAt: Date.now(),
214
+ supersededBy: null,
215
+ supersedes: null,
216
+ evolutionNote: null,
217
+ consolidatedInto: "nonexistent-id-12345",
218
+ contributedToPattern: null,
219
+ sourceMemories: [],
220
+ validFrom: Date.now(),
221
+ validUntil: null,
222
+ },
223
+ }),
224
+ }),
225
+ ];
226
+ const store = createMockStore(entries);
227
+ const report = await runMemoryLint({ store });
228
+
229
+ expect(report.summary.orphans).toBe(1);
230
+ const finding = report.findings.find(f => f.check === "orphan" && f.severity === "warning");
231
+ expect(finding).toBeDefined();
232
+ });
233
+
234
+ it("skips non-active entries", async () => {
235
+ const entries = [
236
+ makeEntry({
237
+ id: "arc1",
238
+ text: "Archived memory",
239
+ scope: "",
240
+ metadata: JSON.stringify({
241
+ evolution: {
242
+ status: "archived",
243
+ version: 1,
244
+ accessCount: 0,
245
+ lastAccessedAt: null,
246
+ supersededBy: null,
247
+ supersedes: null,
248
+ evolutionNote: null,
249
+ consolidatedInto: null,
250
+ contributedToPattern: null,
251
+ sourceMemories: [],
252
+ validFrom: Date.now(),
253
+ validUntil: null,
254
+ },
255
+ }),
256
+ }),
257
+ ];
258
+ const store = createMockStore(entries);
259
+ const report = await runMemoryLint({ store });
260
+
261
+ // Archived entry should be skipped, so no orphan finding
262
+ expect(report.totalScanned).toBe(0);
263
+ expect(report.findings).toHaveLength(0);
264
+ });
265
+
266
+ // ---- Weak lessons (action-verb heuristic, inspired by Orb) ----------------
267
+
268
+ it("flags patterns without any action verb as weak lessons", async () => {
269
+ const entries = [
270
+ makeEntry({
271
+ id: "wl1",
272
+ text: "This phenomenon is very interesting and noteworthy",
273
+ category: "patterns",
274
+ scope: "project:x",
275
+ vector: [1, 0, 0, 0, 0],
276
+ }),
277
+ ];
278
+ const store = createMockStore(entries);
279
+ const report = await runMemoryLint({ store });
280
+
281
+ expect(report.summary.weakLessons).toBe(1);
282
+ const finding = report.findings.find(f => f.check === "weakLesson");
283
+ expect(finding).toBeDefined();
284
+ expect(finding!.severity).toBe("info");
285
+ expect(finding!.memoryIds).toContain("wl1");
286
+ });
287
+
288
+ it("does not flag patterns that contain action verbs (English or Chinese)", async () => {
289
+ const entries = [
290
+ makeEntry({
291
+ id: "wl2",
292
+ text: "Use Bun to run scripts; verify output before committing",
293
+ category: "patterns",
294
+ scope: "project:x",
295
+ vector: [1, 0, 0, 0, 0],
296
+ }),
297
+ makeEntry({
298
+ id: "wl3",
299
+ text: "使用 playwright 验证网页交互,失败时重试最多三次",
300
+ category: "patterns",
301
+ scope: "project:x",
302
+ vector: [0, 1, 0, 0, 0],
303
+ }),
304
+ ];
305
+ const store = createMockStore(entries);
306
+ const report = await runMemoryLint({ store });
307
+
308
+ expect(report.summary.weakLessons).toBe(0);
309
+ });
310
+
311
+ it("does not flag non-pattern categories for weak lessons (events/profile exempt)", async () => {
312
+ const entries = [
313
+ makeEntry({
314
+ id: "wl4",
315
+ text: "This phenomenon is interesting", // no verb, but not a pattern
316
+ category: "events",
317
+ scope: "project:x",
318
+ vector: [1, 0, 0, 0, 0],
319
+ }),
320
+ makeEntry({
321
+ id: "wl5",
322
+ text: "User background info without verbs",
323
+ category: "profile",
324
+ scope: "project:x",
325
+ vector: [0, 1, 0, 0, 0],
326
+ }),
327
+ ];
328
+ const store = createMockStore(entries);
329
+ const report = await runMemoryLint({ store });
330
+
331
+ expect(report.summary.weakLessons).toBe(0);
332
+ });
333
+ });
334
+
335
+ // ---------------------------------------------------------------------------
336
+ // computeHealthScore
337
+ // ---------------------------------------------------------------------------
338
+
339
+ describe("computeHealthScore", () => {
340
+ it("returns 100 when no issues", () => {
341
+ expect(computeHealthScore({ contradictions: 0, duplicates: 0, staleMemories: 0, orphans: 0 }, 100)).toBe(100);
342
+ });
343
+
344
+ it("deducts correctly for mixed findings", () => {
345
+ // 1 contradiction (-10) + 2 duplicates (-10) + 4 stale (-2) + 1 orphan (-3) = -25 → 75
346
+ expect(computeHealthScore({ contradictions: 1, duplicates: 2, staleMemories: 4, orphans: 1 }, 100)).toBe(75);
347
+ });
348
+
349
+ it("clamps to 0", () => {
350
+ expect(computeHealthScore({ contradictions: 20, duplicates: 0, staleMemories: 0, orphans: 0 }, 10)).toBe(0);
351
+ });
352
+ });
353
+
354
+ // ---------------------------------------------------------------------------
355
+ // formatMemoryLintReport
356
+ // ---------------------------------------------------------------------------
357
+
358
+ describe("formatMemoryLintReport", () => {
359
+ it("shows all-clear when no findings", () => {
360
+ const report: MemoryLintReport = {
361
+ findings: [],
362
+ healthScore: 100,
363
+ totalScanned: 50,
364
+ timestamp: "2026-04-08T12:00:00Z",
365
+ summary: { contradictions: 0, duplicates: 0, staleMemories: 0, orphans: 0, weakLessons: 0 },
366
+ };
367
+ const output = formatMemoryLintReport(report);
368
+ expect(output).toContain("All Clear");
369
+ expect(output).toContain("100/100");
370
+ });
371
+
372
+ it("includes findings when present", () => {
373
+ const report: MemoryLintReport = {
374
+ findings: [
375
+ { check: "contradiction", severity: "warning", detail: '"A" vs "B"', memoryIds: ["id1", "id2"] },
376
+ ],
377
+ healthScore: 90,
378
+ totalScanned: 100,
379
+ timestamp: "2026-04-08T12:00:00Z",
380
+ summary: { contradictions: 1, duplicates: 0, staleMemories: 0, orphans: 0, weakLessons: 0 },
381
+ };
382
+ const output = formatMemoryLintReport(report);
383
+ expect(output).toContain("Contradictions (1)");
384
+ expect(output).toContain("90/100");
385
+ });
386
+
387
+ it("summarizes stale when count > 5", () => {
388
+ const staleFindings = Array.from({ length: 10 }, (_, i) => ({
389
+ check: "stale" as const,
390
+ severity: "info" as const,
391
+ detail: `${100 + i}d old`,
392
+ memoryIds: [`stale${i}`],
393
+ }));
394
+ const report: MemoryLintReport = {
395
+ findings: staleFindings,
396
+ healthScore: 95,
397
+ totalScanned: 200,
398
+ timestamp: "2026-04-08T12:00:00Z",
399
+ summary: { contradictions: 0, duplicates: 0, staleMemories: 10, orphans: 0, weakLessons: 0 },
400
+ };
401
+ const output = formatMemoryLintReport(report);
402
+ expect(output).toContain("Stale (10)");
403
+ expect(output).toContain("10 memories not accessed");
404
+ });
405
+
406
+ it("renders weak lessons section when present", () => {
407
+ const report: MemoryLintReport = {
408
+ findings: [
409
+ { check: "weakLesson", severity: "info", detail: 'Pattern without action verbs: "X is Y"', memoryIds: ["wl1"] },
410
+ { check: "weakLesson", severity: "info", detail: 'Pattern without action verbs: "abstract note"', memoryIds: ["wl2"] },
411
+ ],
412
+ healthScore: 96,
413
+ totalScanned: 10,
414
+ timestamp: "2026-04-16T12:00:00Z",
415
+ summary: { contradictions: 0, duplicates: 0, staleMemories: 0, orphans: 0, weakLessons: 2 },
416
+ };
417
+ const output = formatMemoryLintReport(report);
418
+ expect(output).toContain("Weak Lessons (2)");
419
+ expect(output).toContain("96/100");
420
+ });
421
+ });