recallnest 2.3.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/CHANGELOG.md +187 -0
  2. package/README.md +49 -38
  3. package/README_CN.md +46 -31
  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/docs/api-reference.md +1291 -0
  9. package/docs/architecture.md +168 -0
  10. package/docs/connector-spec.md +126 -0
  11. package/eval/cases-canary.json +58 -0
  12. package/eval/cases-scope-robustness.json +278 -0
  13. package/eval/cases.json +117 -20
  14. package/package.json +25 -4
  15. package/src/__tests__/access-tracker-novelty.test.ts +304 -0
  16. package/src/__tests__/activity-counter.test.ts +125 -0
  17. package/src/__tests__/adaptive-fidelity.test.ts +102 -0
  18. package/src/__tests__/admission-control.test.ts +206 -0
  19. package/src/__tests__/anchor-generator.test.ts +67 -0
  20. package/src/__tests__/api-server-security.test.ts +102 -0
  21. package/src/__tests__/auto-consolidation.test.ts +168 -0
  22. package/src/__tests__/auto-recall.test.ts +131 -0
  23. package/src/__tests__/babel-integration.test.ts +144 -0
  24. package/src/__tests__/batch-dedup.test.ts +65 -0
  25. package/src/__tests__/belief-history.test.ts +220 -0
  26. package/src/__tests__/canary-eval.test.ts +114 -0
  27. package/src/__tests__/capture-engine.test.ts +1328 -0
  28. package/src/__tests__/capture-heuristic.test.ts +171 -0
  29. package/src/__tests__/cascade-forget.test.ts +210 -0
  30. package/src/__tests__/category-min-scores.test.ts +116 -0
  31. package/src/__tests__/cc8-cc1-essential-context.test.ts +298 -0
  32. package/src/__tests__/circuit-breaker.test.ts +99 -0
  33. package/src/__tests__/cluster-consolidation.test.ts +945 -0
  34. package/src/__tests__/confidence-metadata.test.ts +125 -0
  35. package/src/__tests__/confidence-tracker.test.ts +261 -0
  36. package/src/__tests__/conflict-advisor.test.ts +206 -0
  37. package/src/__tests__/conflict-escalation.test.ts +149 -0
  38. package/src/__tests__/conflict-lifecycle.test.ts +83 -0
  39. package/src/__tests__/conflict-output.test.ts +85 -0
  40. package/src/__tests__/conflict-store.test.ts +418 -0
  41. package/src/__tests__/connector-v1.test.ts +181 -0
  42. package/src/__tests__/consolidation-engine.test.ts +430 -0
  43. package/src/__tests__/constructive-retrieval.test.ts +509 -0
  44. package/src/__tests__/context-collapse-renderer.test.ts +214 -0
  45. package/src/__tests__/context-composer-pins.test.ts +64 -0
  46. package/src/__tests__/context-composer-task-selection.test.ts +24 -0
  47. package/src/__tests__/context-reconstructor.test.ts +65 -0
  48. package/src/__tests__/context-renderer.test.ts +91 -0
  49. package/src/__tests__/continuity-eval.test.ts +275 -0
  50. package/src/__tests__/continuity-schema.test.ts +97 -0
  51. package/src/__tests__/contracts.test.ts +262 -0
  52. package/src/__tests__/conversation-importer.test.ts +692 -0
  53. package/src/__tests__/core-recall-eval.test.ts +235 -0
  54. package/src/__tests__/core-summary.test.ts +109 -0
  55. package/src/__tests__/data-checkup.test.ts +276 -0
  56. package/src/__tests__/decay-exemption.test.ts +129 -0
  57. package/src/__tests__/dedup-actions.test.ts +58 -0
  58. package/src/__tests__/dedup-guard.test.ts +39 -0
  59. package/src/__tests__/deterministic-id.test.ts +39 -0
  60. package/src/__tests__/distill-lock.test.ts +305 -0
  61. package/src/__tests__/distill-session-argshape.test.ts +79 -0
  62. package/src/__tests__/doctor.test.ts +319 -0
  63. package/src/__tests__/dream-pipeline.test.ts +780 -0
  64. package/src/__tests__/drill-down.test.ts +108 -0
  65. package/src/__tests__/embedder.test.ts +122 -0
  66. package/src/__tests__/emotion-decay.test.ts +46 -0
  67. package/src/__tests__/emotion-detector.test.ts +56 -0
  68. package/src/__tests__/emotion-phase1-integration.test.ts +153 -0
  69. package/src/__tests__/emotion-retrieval.test.ts +56 -0
  70. package/src/__tests__/entity-resolver.test.ts +58 -0
  71. package/src/__tests__/env-config.test.ts +151 -0
  72. package/src/__tests__/error-signature-boost.test.ts +87 -0
  73. package/src/__tests__/error-signature.test.ts +95 -0
  74. package/src/__tests__/error-taxonomy.test.ts +129 -0
  75. package/src/__tests__/ethics-layer.test.ts +476 -0
  76. package/src/__tests__/event-segmenter.test.ts +153 -0
  77. package/src/__tests__/feature-flags-integration.test.ts +54 -0
  78. package/src/__tests__/frequency-tracker.test.ts +113 -0
  79. package/src/__tests__/freshness.test.ts +186 -0
  80. package/src/__tests__/graph-export.test.ts +489 -0
  81. package/src/__tests__/hotness-blend.test.ts +283 -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-client-pivot.test.ts +628 -0
  88. package/src/__tests__/llm-consolidation.test.ts +226 -0
  89. package/src/__tests__/maintenance-locks.test.ts +189 -0
  90. package/src/__tests__/mcp-efficiency.test.ts +288 -0
  91. package/src/__tests__/mcp-related-scopes.test.ts +151 -0
  92. package/src/__tests__/memory-boundaries.test.ts +282 -0
  93. package/src/__tests__/memory-evolution-b2-b3-e1.test.ts +345 -0
  94. package/src/__tests__/memory-evolution.test.ts +271 -0
  95. package/src/__tests__/memory-health-rebalance.test.ts +144 -0
  96. package/src/__tests__/memory-lint.test.ts +421 -0
  97. package/src/__tests__/memory-output.test.ts +215 -0
  98. package/src/__tests__/memory-promotion.test.ts +315 -0
  99. package/src/__tests__/migrate-dedup-ids.test.ts +65 -0
  100. package/src/__tests__/multi-vector.test.ts +242 -0
  101. package/src/__tests__/narrative-architecture.test.ts +456 -0
  102. package/src/__tests__/noise-filter.test.ts +205 -0
  103. package/src/__tests__/noise-prototype-bank.test.ts +280 -0
  104. package/src/__tests__/obsidian-connector.test.ts +363 -0
  105. package/src/__tests__/omitted-reporting.test.ts +98 -0
  106. package/src/__tests__/pending-review.test.ts +77 -0
  107. package/src/__tests__/pii-redact.test.ts +333 -0
  108. package/src/__tests__/pivot-apply.test.ts +373 -0
  109. package/src/__tests__/pivot-distill-supervisor.test.ts +457 -0
  110. package/src/__tests__/pivot-distill.test.ts +1178 -0
  111. package/src/__tests__/post-retrieval-filter.test.ts +178 -0
  112. package/src/__tests__/ppr-traversal.test.ts +256 -0
  113. package/src/__tests__/prediction-engine.test.ts +349 -0
  114. package/src/__tests__/predictive-prospective-memory.test.ts +416 -0
  115. package/src/__tests__/preference-guard-smoke.test.ts +211 -0
  116. package/src/__tests__/preference-matcher.test.ts +282 -0
  117. package/src/__tests__/preference-slots.test.ts +205 -0
  118. package/src/__tests__/prospective-memory.test.ts +283 -0
  119. package/src/__tests__/pull-from-macbook-sync-only.test.ts +679 -0
  120. package/src/__tests__/query-entity-detector.test.ts +171 -0
  121. package/src/__tests__/query-expander-alias.test.ts +146 -0
  122. package/src/__tests__/query-expander.test.ts +34 -0
  123. package/src/__tests__/recall-gate.test.ts +266 -0
  124. package/src/__tests__/recall-governor.test.ts +227 -0
  125. package/src/__tests__/recall-mode.test.ts +64 -0
  126. package/src/__tests__/resolve-db-path.test.ts +130 -0
  127. package/src/__tests__/resolve-tier.test.ts +64 -0
  128. package/src/__tests__/result-synthesizer.test.ts +198 -0
  129. package/src/__tests__/resume-context.test.ts +4898 -0
  130. package/src/__tests__/retrieval-eval.test.ts +163 -0
  131. package/src/__tests__/retrieval-trace.test.ts +213 -0
  132. package/src/__tests__/retriever-boundary-weight.test.ts +136 -0
  133. package/src/__tests__/retriever-lazy-init-dispatch.test.ts +123 -0
  134. package/src/__tests__/retroactive-boost.test.ts +223 -0
  135. package/src/__tests__/salience-scoring.test.ts +106 -0
  136. package/src/__tests__/scope-inventory.test.ts +200 -0
  137. package/src/__tests__/scope-policy.test.ts +69 -0
  138. package/src/__tests__/scope-suggester.test.ts +80 -0
  139. package/src/__tests__/session-checkpoint.test.ts +291 -0
  140. package/src/__tests__/session-distiller.test.ts +640 -0
  141. package/src/__tests__/session-gc.test.ts +215 -0
  142. package/src/__tests__/skill-engine.test.ts +552 -0
  143. package/src/__tests__/skill-promotion.test.ts +654 -0
  144. package/src/__tests__/skill-verifier.test.ts +122 -0
  145. package/src/__tests__/source-heartbeat.test.ts +250 -0
  146. package/src/__tests__/stable-context-length-contract.test.ts +62 -0
  147. package/src/__tests__/store-patch-metadata.test.ts +205 -0
  148. package/src/__tests__/store-read-consistency.test.ts +122 -0
  149. package/src/__tests__/store-schema-migration.test.ts +87 -0
  150. package/src/__tests__/store-scope-audit.test.ts +81 -0
  151. package/src/__tests__/store-upsert.test.ts +201 -0
  152. package/src/__tests__/supersede-chain.test.ts +154 -0
  153. package/src/__tests__/temporal-parser.test.ts +241 -0
  154. package/src/__tests__/temporal-validity.test.ts +160 -0
  155. package/src/__tests__/term-registry-terminal-roster.test.ts +127 -0
  156. package/src/__tests__/term-registry.test.ts +121 -0
  157. package/src/__tests__/tool-error-surfacing.test.ts +98 -0
  158. package/src/__tests__/tool-output-compressor.test.ts +160 -0
  159. package/src/__tests__/topic-tag.test.ts +113 -0
  160. package/src/__tests__/trusted-memory.test.ts +839 -0
  161. package/src/__tests__/ui-server-security.test.ts +93 -0
  162. package/src/__tests__/usage-tracker.test.ts +287 -0
  163. package/src/__tests__/version-manager.test.ts +213 -0
  164. package/src/__tests__/workflow-observation-skill-outcome.test.ts +352 -0
  165. package/src/__tests__/workflow-observation.test.ts +433 -0
  166. package/src/__tests__/write-verifier.test.ts +122 -0
  167. package/src/access-tracker.ts +90 -34
  168. package/src/activity-counter.ts +46 -18
  169. package/src/adaptive-retrieval.ts +11 -0
  170. package/src/aliases.ts +133 -0
  171. package/src/api-server.ts +36 -9
  172. package/src/audit-log.ts +4 -2
  173. package/src/auto-consolidation.ts +8 -3
  174. package/src/auto-gc.ts +85 -21
  175. package/src/auto-recall.ts +61 -1
  176. package/src/belief-history.ts +164 -0
  177. package/src/capture-engine.ts +142 -32
  178. package/src/cli.ts +268 -41
  179. package/src/confidence-tracker.ts +36 -18
  180. package/src/conflict-engine.ts +24 -3
  181. package/src/consolidation-engine.ts +255 -23
  182. package/src/context-composer-stable-selection.ts +7 -1
  183. package/src/context-composer.ts +8 -1
  184. package/src/data-checkup.ts +96 -7
  185. package/src/decay-engine.ts +59 -7
  186. package/src/distill-lock.ts +194 -15
  187. package/src/doctor.ts +13 -4
  188. package/src/dream-pipeline.ts +473 -41
  189. package/src/env-config.ts +118 -0
  190. package/src/error-signature.ts +153 -0
  191. package/src/error-taxonomy.ts +115 -0
  192. package/src/eval.ts +402 -14
  193. package/src/freshness.ts +192 -0
  194. package/src/http-request-policy.ts +148 -0
  195. package/src/idempotency.ts +8 -0
  196. package/src/ingest.ts +308 -12
  197. package/src/kg-extractor.ts +13 -3
  198. package/src/kg-store.ts +236 -44
  199. package/src/llm-client.ts +106 -11
  200. package/src/llm-consolidation.ts +2 -1
  201. package/src/mcp-server.ts +87 -1800
  202. package/src/mcp-tool-deps.ts +48 -0
  203. package/src/mcp-tools-advanced.ts +954 -0
  204. package/src/mcp-tools-core.ts +637 -0
  205. package/src/mcp-tools-governance.ts +475 -0
  206. package/src/memory-boundaries.ts +26 -3
  207. package/src/memory-evolution.ts +73 -1
  208. package/src/memory-health-rebalance.ts +4 -0
  209. package/src/memory-lint.ts +183 -10
  210. package/src/memory-output.ts +129 -4
  211. package/src/memory-promotion.ts +246 -0
  212. package/src/memory-schema.ts +25 -2
  213. package/src/memory-store-port.ts +46 -0
  214. package/src/multi-vector.ts +2 -1
  215. package/src/narrative-schema.ts +2 -1
  216. package/src/noise-filter.ts +57 -6
  217. package/src/noise-prototype-bank.ts +408 -0
  218. package/src/pii-detector.ts +207 -5
  219. package/src/pivot-apply.ts +399 -0
  220. package/src/preference-matcher.ts +37 -3
  221. package/src/query-expander.ts +90 -9
  222. package/src/recall-gate.ts +305 -0
  223. package/src/result-synthesizer.ts +2 -1
  224. package/src/retention-policy.ts +2 -1
  225. package/src/retrieval-profiles.ts +46 -4
  226. package/src/retriever.ts +354 -157
  227. package/src/retroactive-boost.ts +6 -2
  228. package/src/runtime-config.ts +78 -6
  229. package/src/scope-suggester.ts +113 -0
  230. package/src/session-distiller.ts +23 -2
  231. package/src/session-engine.ts +2 -1
  232. package/src/session-schema.ts +1 -0
  233. package/src/session-store.ts +5 -0
  234. package/src/skill-engine.ts +78 -0
  235. package/src/skill-promotion.ts +304 -48
  236. package/src/skill-schema.ts +16 -3
  237. package/src/skill-verifier.ts +152 -0
  238. package/src/store.ts +321 -57
  239. package/src/term-registry.ts +35 -0
  240. package/src/tool-output-compressor.ts +3 -1
  241. package/src/ui-server.ts +9 -1
  242. package/src/usage-tracker.ts +242 -0
  243. package/src/version-manager.ts +3 -2
  244. package/src/version.ts +19 -0
  245. package/src/workflow-observation-engine.ts +2 -1
  246. package/src/workflow-observation-schema.ts +2 -1
  247. package/src/workflow-observation-store.ts +6 -2
  248. package/.env +0 -4
  249. package/CLAUDE.md +0 -46
  250. package/config.json +0 -55
  251. package/daily-recall.sh +0 -110
  252. package/logs/daily-recall.error.log +0 -0
  253. package/logs/daily-recall.log +0 -60
  254. package/logs/ingest-2026-04-11.log +0 -110
  255. package/logs/ingest-2026-04-12.log +0 -90
  256. package/logs/ingest-2026-04-13.log +0 -87
  257. package/logs/launchagent-stderr.log +0 -0
  258. package/logs/launchagent-stdout.log +0 -0
@@ -0,0 +1,283 @@
1
+ import { describe, it, expect } from "bun:test";
2
+ import { computeHotnessScore, parseAccessMetadata } from "../access-tracker.js";
3
+ import { TraceCollector } from "../retrieval-trace.js";
4
+ import {
5
+ createRetriever,
6
+ DEFAULT_CATEGORY_MIN_SCORES,
7
+ } from "../retriever.js";
8
+
9
+ function applyHotnessBlend(
10
+ score: number,
11
+ accessCount: number,
12
+ lastAccessedAt: number,
13
+ ): number {
14
+ const retriever = createRetriever({} as any, {} as any, { hotnessWeight: 0.15 });
15
+ retriever.setAccessTracker({} as any);
16
+ const results = [{
17
+ entry: {
18
+ id: "hotness-test",
19
+ text: "hotness test",
20
+ vector: [],
21
+ category: "events",
22
+ scope: "test:hotness",
23
+ importance: 0.5,
24
+ timestamp: Date.now(),
25
+ metadata: JSON.stringify({ accessCount, lastAccessedAt }),
26
+ },
27
+ score,
28
+ sources: {},
29
+ }];
30
+ return (retriever as any).applyHotnessBlend(results)[0].score;
31
+ }
32
+
33
+ describe("computeHotnessScore", () => {
34
+ it("returns 0 for zero accesses", () => {
35
+ expect(computeHotnessScore(0, Date.now())).toBe(0);
36
+ });
37
+
38
+ it("returns positive score for accessed memories", () => {
39
+ const score = computeHotnessScore(5, Date.now());
40
+ expect(score).toBeGreaterThan(0);
41
+ expect(score).toBeLessThanOrEqual(1);
42
+ });
43
+
44
+ it("higher access count yields higher score", () => {
45
+ const now = Date.now();
46
+ const low = computeHotnessScore(1, now);
47
+ const mid = computeHotnessScore(5, now);
48
+ const high = computeHotnessScore(50, now);
49
+ expect(low).toBeLessThan(mid);
50
+ expect(mid).toBeLessThan(high);
51
+ });
52
+
53
+ it("recent access yields higher score than old access", () => {
54
+ const now = Date.now();
55
+ const recent = computeHotnessScore(5, now);
56
+ const weekAgo = computeHotnessScore(5, now - 7 * 86_400_000);
57
+ const monthAgo = computeHotnessScore(5, now - 30 * 86_400_000);
58
+ expect(recent).toBeGreaterThan(weekAgo);
59
+ expect(weekAgo).toBeGreaterThan(monthAgo);
60
+ });
61
+
62
+ it("decays to near-zero for very old accesses", () => {
63
+ const score = computeHotnessScore(5, Date.now() - 365 * 86_400_000);
64
+ expect(score).toBeLessThan(0.01);
65
+ });
66
+
67
+ it("caps at 1.0 even with extreme access counts", () => {
68
+ const score = computeHotnessScore(10_000, Date.now());
69
+ expect(score).toBeLessThanOrEqual(1.0);
70
+ });
71
+
72
+ it("respects custom decay rate", () => {
73
+ const now = Date.now();
74
+ const fast = computeHotnessScore(5, now - 7 * 86_400_000, 0.5);
75
+ const slow = computeHotnessScore(5, now - 7 * 86_400_000, 0.01);
76
+ expect(slow).toBeGreaterThan(fast);
77
+ });
78
+ });
79
+
80
+ describe("parseAccessMetadata", () => {
81
+ it("parses valid metadata", () => {
82
+ const meta = JSON.stringify({ accessCount: 5, lastAccessedAt: 1234567890 });
83
+ const result = parseAccessMetadata(meta);
84
+ expect(result.accessCount).toBe(5);
85
+ expect(result.lastAccessedAt).toBe(1234567890);
86
+ });
87
+
88
+ it("returns defaults for missing fields", () => {
89
+ const result = parseAccessMetadata("{}");
90
+ expect(result.accessCount).toBe(0);
91
+ expect(result.lastAccessedAt).toBe(0);
92
+ });
93
+
94
+ it("handles undefined input", () => {
95
+ const result = parseAccessMetadata(undefined);
96
+ expect(result.accessCount).toBe(0);
97
+ expect(result.lastAccessedAt).toBe(0);
98
+ });
99
+
100
+ it("handles malformed JSON", () => {
101
+ const result = parseAccessMetadata("not-json");
102
+ expect(result.accessCount).toBe(0);
103
+ expect(result.lastAccessedAt).toBe(0);
104
+ });
105
+ });
106
+
107
+ describe("applyHotnessBlend", () => {
108
+ it("does not penalize a zero-access row", () => {
109
+ expect(applyHotnessBlend(0.6, 0, 0)).toBe(0.6);
110
+ });
111
+
112
+ it("preserves the existing blend formula for an accessed row", () => {
113
+ const futureAccess = Date.now() + 60_000;
114
+ const hotness = computeHotnessScore(5, futureAccess);
115
+ expect(applyHotnessBlend(0.6, 5, futureAccess)).toBeCloseTo(
116
+ 0.6 * 0.85 + hotness * 0.15,
117
+ 12,
118
+ );
119
+ });
120
+
121
+ it("still applies the existing penalty when an accessed row's hotness decays to zero", () => {
122
+ expect(computeHotnessScore(1, 1)).toBe(0);
123
+ expect(applyHotnessBlend(0.6, 1, 1)).toBeCloseTo(0.6 * 0.85, 12);
124
+ });
125
+ });
126
+
127
+ describe("cold-start hotness pipeline regression", () => {
128
+ it("recalls a78ad478 without dropping control dd05b422", async () => {
129
+ const query = "owner 模型 任务锁 并发 谁在干活 责任层 资源层";
130
+ const now = Date.now();
131
+ const text = `${query} `.repeat(80).slice(0, 1900);
132
+
133
+ expect(text).toHaveLength(1900);
134
+
135
+ function metadata(
136
+ source: "agent" | "manual",
137
+ confidence: number,
138
+ accessCount: number,
139
+ ): string {
140
+ const lastAccessedAt = accessCount > 0 ? now : 0;
141
+
142
+ return JSON.stringify({
143
+ source,
144
+ confidence: {
145
+ score: confidence,
146
+ reliability: source === "manual" ? "direct" : "inferred",
147
+ },
148
+ accessCount,
149
+ lastAccessedAt,
150
+ boundary: {
151
+ layer: "durable",
152
+ authority: "structured-memory",
153
+ conflictPolicy: "latest-wins",
154
+ originalCategory: "patterns",
155
+ },
156
+ evolution: {
157
+ status: "active",
158
+ version: 1,
159
+ accessCount,
160
+ lastAccessedAt: accessCount > 0 ? lastAccessedAt : null,
161
+ validFrom: now,
162
+ validUntil: null,
163
+ },
164
+ });
165
+ }
166
+
167
+ const candidates = [
168
+ {
169
+ entry: {
170
+ id: "a78ad478",
171
+ text,
172
+ vector: [1, 0, 0],
173
+ category: "patterns",
174
+ scope: "project:hippo-wiki",
175
+ importance: 0.8,
176
+ timestamp: now,
177
+ metadata: metadata("agent", 0.7, 0),
178
+ },
179
+ score: 0.8628,
180
+ },
181
+ {
182
+ entry: {
183
+ id: "dd05b422",
184
+ text,
185
+ vector: [0.99, 0.01, 0],
186
+ category: "patterns",
187
+ scope: "project:hippo-wiki",
188
+ importance: 0.8,
189
+ timestamp: now,
190
+ metadata: metadata("manual", 0.9, 4),
191
+ },
192
+ score: 0.8579,
193
+ },
194
+ ];
195
+
196
+ let vectorSearchCalls = 0;
197
+
198
+ const store = {
199
+ hasFtsSupport: false,
200
+ async vectorSearch(
201
+ _queryVector: number[],
202
+ limit: number,
203
+ minScore: number,
204
+ scopeFilter?: string[],
205
+ ) {
206
+ vectorSearchCalls += 1;
207
+ return candidates
208
+ .filter(candidate => candidate.score >= minScore)
209
+ .filter(candidate =>
210
+ !scopeFilter || scopeFilter.includes(candidate.entry.scope),
211
+ )
212
+ .slice(0, limit);
213
+ },
214
+ };
215
+
216
+ const embedder = {
217
+ async embedQuery() {
218
+ return [1, 0, 0];
219
+ },
220
+ async embedPassage() {
221
+ return [1, 0, 0];
222
+ },
223
+ };
224
+
225
+ const retriever = createRetriever(
226
+ store as any,
227
+ embedder as any,
228
+ {
229
+ mode: "vector",
230
+ rerank: "none",
231
+ candidatePoolSize: 5,
232
+ minScore: 0.3,
233
+ hardMinScore: 0.38,
234
+ recencyHalfLifeDays: 14,
235
+ recencyWeight: 0.15,
236
+ lengthNormAnchor: 700,
237
+ timeDecayHalfLifeDays: 60,
238
+ hotnessWeight: 0.15,
239
+ filterNoise: false,
240
+ enableRIF: false,
241
+ sourceDiversity: 0,
242
+ multiHop: false,
243
+ },
244
+ );
245
+
246
+ retriever.setAccessTracker({
247
+ computeEffectiveHalfLife(baseHalfLife: number) {
248
+ return baseHalfLife;
249
+ },
250
+ recordAccess() {
251
+ throw new Error("pipeline regression must not record access");
252
+ },
253
+ } as any);
254
+
255
+ const trace = new TraceCollector();
256
+ const results = await retriever.retrieve({
257
+ query,
258
+ limit: 5,
259
+ scopeFilter: ["project:hippo-wiki"],
260
+ category: "patterns",
261
+ source: "auto-recall",
262
+ trace,
263
+ });
264
+
265
+ const ids = results.map(result => result.entry.id);
266
+ const cold = results.find(result => result.entry.id === "a78ad478");
267
+ const hardMin = trace
268
+ .finalize(query, "vector")
269
+ .stages.find(stage => stage.name === "hard_min_score");
270
+
271
+ expect(ids).toContain("a78ad478");
272
+ expect(ids).toContain("dd05b422");
273
+ expect(cold?.score).toBeGreaterThanOrEqual(
274
+ DEFAULT_CATEGORY_MIN_SCORES.patterns,
275
+ );
276
+ expect(hardMin).toMatchObject({
277
+ inputCount: 2,
278
+ outputCount: 2,
279
+ droppedCount: 0,
280
+ });
281
+ expect(vectorSearchCalls).toBe(1);
282
+ });
283
+ });
@@ -0,0 +1,44 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { groupTurnsIntoChunks } from "../ingest.js";
4
+ import { isNoise } from "../noise-filter.js";
5
+
6
+ // P1 defence-in-depth: groupTurnsIntoChunks pre-filters whole turns via
7
+ // filterNoiseTurns BEFORE chunking, but long turns then get split — and the
8
+ // split fragments were never re-checked. A long turn whose tail is orphaned
9
+ // context-JSON therefore leaks severed JSON field-lines as standalone chunks.
10
+ // This guards that no chunk survives as noise, without over-deleting real talk.
11
+
12
+ function userTurn(text: string) {
13
+ return { role: "user" as const, text, timestamp: "2026-05-21T00:00:00Z", sessionId: "s1" };
14
+ }
15
+ function assistantTurn(text: string) {
16
+ return { role: "assistant" as const, text, timestamp: "2026-05-21T00:00:01Z", sessionId: "s1" };
17
+ }
18
+
19
+ describe("groupTurnsIntoChunks — post-split noise filtering (P1)", () => {
20
+ it("drops severed context-JSON fragments produced by splitting a long turn", () => {
21
+ // Real-content opener (passes turn-level filterNoiseTurns), then a long tail
22
+ // of orphaned JSON field-lines that chunking peels into standalone chunks.
23
+ const opener = "我们今天把记忆系统这周的进展过一遍,重点是噪声治理和召回质量的提升。".repeat(8);
24
+ const jsonTail = Array.from(
25
+ { length: 60 },
26
+ (_, i) => `"time": "2026-05-21T15:${String(i).padStart(2, "0")}:03.796Z",`,
27
+ ).join("\n");
28
+ const chunks = groupTurnsIntoChunks([userTurn(`${opener}\n${jsonTail}`)]);
29
+
30
+ expect(chunks.length).toBeGreaterThan(0); // real content survives
31
+ // No chunk may survive as a recognizable noise fragment.
32
+ expect(chunks.every((c) => !isNoise(c.text))).toBe(true);
33
+ });
34
+
35
+ it("keeps a normal long Q&A conversation intact (no over-deletion)", () => {
36
+ const longQuestion = "你帮我想想这个方案怎么落地,我担心几个点没考虑周全,得一起捋一捋。".repeat(20);
37
+ const longAnswer = "可以分三步走,先做最小验证看效果,再逐步扩展覆盖面,最后补回归测试兜底。".repeat(20);
38
+ const chunks = groupTurnsIntoChunks([userTurn(longQuestion), assistantTurn(longAnswer)]);
39
+
40
+ expect(chunks.length).toBeGreaterThan(0);
41
+ expect(chunks.every((c) => !isNoise(c.text))).toBe(true); // real talk not deleted
42
+ expect(chunks.some((c) => c.text.includes("最小验证"))).toBe(true); // content retained
43
+ });
44
+ });
@@ -0,0 +1,360 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { dedupCheck } from "../ingest.js";
4
+
5
+ function buildSearchResult(text: string, score: number) {
6
+ return {
7
+ score,
8
+ entry: {
9
+ id: `memory-${score}`,
10
+ text,
11
+ vector: [score],
12
+ category: "events",
13
+ scope: "cc:test-session",
14
+ importance: 0.6,
15
+ timestamp: 1_700_000_000_000,
16
+ metadata: "{}",
17
+ },
18
+ };
19
+ }
20
+
21
+ describe("dedupCheck", () => {
22
+ it("stores a new same-brand item preference instead of treating it as a duplicate topic", async () => {
23
+ let llmCalls = 0;
24
+ const store = {
25
+ async vectorSearch() {
26
+ return [
27
+ buildSearchResult("喜欢吃麦当劳的麦旋风", 0.92),
28
+ buildSearchResult("喜欢吃麦当劳的板烧鸡腿堡", 0.89),
29
+ ];
30
+ },
31
+ };
32
+ const llm = {
33
+ async dedupDecision() {
34
+ llmCalls += 1;
35
+ return { action: "SKIP" as const, reason: "same topic" };
36
+ },
37
+ };
38
+
39
+ const result = await dedupCheck(
40
+ store as any,
41
+ [1, 0, 0],
42
+ "我喜欢吃麦当劳的麦辣鸡翅",
43
+ llm as any,
44
+ );
45
+
46
+ expect(result.action).toBe("store");
47
+ expect(result.reason).toBe("unique");
48
+ expect(result.existingText).toBe("喜欢吃麦当劳的板烧鸡腿堡");
49
+ expect(llmCalls).toBe(0);
50
+ });
51
+
52
+ it("stores a new atomic preference even when the closest match is an aggregate summary", async () => {
53
+ const store = {
54
+ async vectorSearch() {
55
+ return [
56
+ buildSearchResult("喜欢吃麦当劳的麦旋风、板烧鸡腿堡和藤椒鸡派", 0.94),
57
+ ];
58
+ },
59
+ };
60
+
61
+ const result = await dedupCheck(
62
+ store as any,
63
+ [1, 0, 0],
64
+ "我喜欢吃麦当劳的麦辣鸡翅",
65
+ );
66
+
67
+ expect(result.action).toBe("store");
68
+ expect(result.reason).toBe("unique");
69
+ expect(result.existingText).toContain("麦旋风");
70
+ });
71
+
72
+ it("still skips when an exact atomic preference already exists among the candidates", async () => {
73
+ const store = {
74
+ async vectorSearch() {
75
+ return [
76
+ buildSearchResult("喜欢吃麦当劳的麦旋风、板烧鸡腿堡和藤椒鸡派", 0.94),
77
+ buildSearchResult("我喜欢吃麦当劳的麦辣鸡翅", 0.82),
78
+ ];
79
+ },
80
+ };
81
+
82
+ const result = await dedupCheck(
83
+ store as any,
84
+ [1, 0, 0],
85
+ "我喜欢吃麦当劳的麦辣鸡翅",
86
+ );
87
+
88
+ expect(result.action).toBe("skip");
89
+ expect(result.reason).toBe("exact");
90
+ expect(result.existingText).toBe("我喜欢吃麦当劳的麦辣鸡翅");
91
+ });
92
+
93
+ it("does not force-create when the same brand-item preference is only rephrased", async () => {
94
+ let llmCalls = 0;
95
+ const store = {
96
+ async vectorSearch() {
97
+ return [
98
+ buildSearchResult("我喜欢吃麦当劳的麦辣鸡翅", 0.75),
99
+ ];
100
+ },
101
+ };
102
+ const llm = {
103
+ async dedupDecision() {
104
+ llmCalls += 1;
105
+ return { action: "SKIP" as const, reason: "same item, rephrased" };
106
+ },
107
+ };
108
+
109
+ const result = await dedupCheck(
110
+ store as any,
111
+ [1, 0, 0],
112
+ "用户喜欢麦当劳的麦辣鸡翅",
113
+ llm as any,
114
+ );
115
+
116
+ expect(result.action).toBe("skip");
117
+ expect(result.reason).toBe("llm-skip");
118
+ expect(result.existingText).toBe("我喜欢吃麦当劳的麦辣鸡翅");
119
+ expect(llmCalls).toBe(1);
120
+ });
121
+
122
+ it("does not trigger the brand-item guard for non-preference text that mentions the same brand and item", async () => {
123
+ let llmCalls = 0;
124
+ const store = {
125
+ async vectorSearch() {
126
+ return [
127
+ buildSearchResult("我喜欢喝星巴克的抹茶拿铁", 0.75),
128
+ ];
129
+ },
130
+ };
131
+ const llm = {
132
+ async dedupDecision() {
133
+ llmCalls += 1;
134
+ return { action: "SKIP" as const, reason: "same context, not a new preference" };
135
+ },
136
+ };
137
+
138
+ const result = await dedupCheck(
139
+ store as any,
140
+ [1, 0, 0],
141
+ "我们刚讨论过星巴克的抹茶拿铁做法",
142
+ llm as any,
143
+ );
144
+
145
+ expect(result.action).toBe("skip");
146
+ expect(result.reason).toBe("llm-skip");
147
+ expect(result.existingText).toBe("我喜欢喝星巴克的抹茶拿铁");
148
+ expect(llmCalls).toBe(1);
149
+ });
150
+
151
+ it("stores a new reply-style preference instead of collapsing different style traits into one topic", async () => {
152
+ let llmCalls = 0;
153
+ const store = {
154
+ async vectorSearch() {
155
+ return [
156
+ buildSearchResult("User prefers concise, direct replies.", 0.91),
157
+ ];
158
+ },
159
+ };
160
+ const llm = {
161
+ async dedupDecision() {
162
+ llmCalls += 1;
163
+ return { action: "SKIP" as const, reason: "same topic" };
164
+ },
165
+ };
166
+
167
+ const result = await dedupCheck(
168
+ store as any,
169
+ [1, 0, 0],
170
+ "User prefers colloquial, grounded replies.",
171
+ llm as any,
172
+ );
173
+
174
+ expect(result.action).toBe("store");
175
+ expect(result.reason).toBe("unique");
176
+ expect(result.existingText).toBe("User prefers concise, direct replies.");
177
+ expect(llmCalls).toBe(0);
178
+ });
179
+
180
+ it("does not trigger the reply-style guard for descriptive text about a draft", async () => {
181
+ let llmCalls = 0;
182
+ const store = {
183
+ async vectorSearch() {
184
+ return [
185
+ buildSearchResult("User prefers colloquial, grounded replies.", 0.75),
186
+ ];
187
+ },
188
+ };
189
+ const llm = {
190
+ async dedupDecision() {
191
+ llmCalls += 1;
192
+ return { action: "SKIP" as const, reason: "draft note, not a user preference" };
193
+ },
194
+ };
195
+
196
+ const result = await dedupCheck(
197
+ store as any,
198
+ [1, 0, 0],
199
+ "这段文案简洁直接,先别改。",
200
+ llm as any,
201
+ );
202
+
203
+ expect(result.action).toBe("skip");
204
+ expect(result.reason).toBe("llm-skip");
205
+ expect(result.existingText).toBe("User prefers colloquial, grounded replies.");
206
+ expect(llmCalls).toBe(1);
207
+ });
208
+
209
+ it("stores a new tool-choice preference instead of collapsing different tool choices into one topic", async () => {
210
+ let llmCalls = 0;
211
+ const store = {
212
+ async vectorSearch() {
213
+ return [
214
+ buildSearchResult("Uses Bun over Node.", 0.91),
215
+ ];
216
+ },
217
+ };
218
+ const llm = {
219
+ async dedupDecision() {
220
+ llmCalls += 1;
221
+ return { action: "SKIP" as const, reason: "same topic" };
222
+ },
223
+ };
224
+
225
+ const result = await dedupCheck(
226
+ store as any,
227
+ [1, 0, 0],
228
+ "Prefers rg over grep.",
229
+ llm as any,
230
+ );
231
+
232
+ expect(result.action).toBe("store");
233
+ expect(result.reason).toBe("unique");
234
+ expect(result.existingText).toBe("Uses Bun over Node.");
235
+ expect(llmCalls).toBe(0);
236
+ });
237
+
238
+ it("does not trigger the tool-choice guard for narrative migration text", async () => {
239
+ let llmCalls = 0;
240
+ const store = {
241
+ async vectorSearch() {
242
+ return [
243
+ buildSearchResult("Prefers rg over grep.", 0.75),
244
+ ];
245
+ },
246
+ };
247
+ const llm = {
248
+ async dedupDecision() {
249
+ llmCalls += 1;
250
+ return { action: "SKIP" as const, reason: "migration note, not a tool preference" };
251
+ },
252
+ };
253
+
254
+ const result = await dedupCheck(
255
+ store as any,
256
+ [1, 0, 0],
257
+ "文档里写了 uses Bun over Node 的迁移说明。",
258
+ llm as any,
259
+ );
260
+
261
+ expect(result.action).toBe("skip");
262
+ expect(result.reason).toBe("llm-skip");
263
+ expect(result.existingText).toBe("Prefers rg over grep.");
264
+ expect(llmCalls).toBe(1);
265
+ });
266
+
267
+ it("stores a borderline chunk when LLM says it should CREATE", async () => {
268
+ let llmCalls = 0;
269
+ const store = {
270
+ async vectorSearch() {
271
+ return [
272
+ buildSearchResult(
273
+ "A2A gateway 之前是先本地 smoke,再补 Claude SDK 配置。",
274
+ 0.74,
275
+ ),
276
+ ];
277
+ },
278
+ };
279
+ const llm = {
280
+ async dedupDecision() {
281
+ llmCalls += 1;
282
+ return { action: "CREATE" as const, reason: "new implementation branch" };
283
+ },
284
+ };
285
+
286
+ const result = await dedupCheck(
287
+ store as any,
288
+ [1, 0, 0],
289
+ "A2A gateway 升级后要补 MCP transport 配置和 LaunchAgent 环境变量,不是原来的 smoke 流程。",
290
+ llm as any,
291
+ );
292
+
293
+ expect(result.action).toBe("store");
294
+ expect(result.reason).toBe("unique");
295
+ expect(llmCalls).toBe(1);
296
+ });
297
+
298
+ it("stores a borderline chunk when LLM says it adds new information and should MERGE", async () => {
299
+ let llmCalls = 0;
300
+ const store = {
301
+ async vectorSearch() {
302
+ return [
303
+ buildSearchResult(
304
+ "A2A 调 Claude SDK 时,可以先看 `adapters/claude.js` 里的权限相关配置。",
305
+ 0.77,
306
+ ),
307
+ ];
308
+ },
309
+ };
310
+ const llm = {
311
+ async dedupDecision() {
312
+ llmCalls += 1;
313
+ return { action: "MERGE" as const, reason: "same topic but new implementation detail" };
314
+ },
315
+ };
316
+
317
+ const result = await dedupCheck(
318
+ store as any,
319
+ [1, 0, 0],
320
+ "给 A2A 调用传 permissionMode: \"dontAsk\" + allowedTools,避免 Claude SDK 在后台 HTTP handler 里卡死等权限确认。",
321
+ llm as any,
322
+ );
323
+
324
+ expect(result.action).toBe("store");
325
+ expect(result.reason).toBe("llm-merge");
326
+ expect(result.existingText).toContain("权限相关配置");
327
+ expect(llmCalls).toBe(1);
328
+ });
329
+
330
+ it("skips a hard-threshold duplicate without calling the LLM", async () => {
331
+ let llmCalls = 0;
332
+ const store = {
333
+ async vectorSearch() {
334
+ return [
335
+ buildSearchResult(
336
+ "OpenClaw provider 配置里已经写过 `ANTHROPIC_BASE_URL` 和 `ANTHROPIC_AUTH_TOKEN` 的设置方法。",
337
+ 0.95,
338
+ ),
339
+ ];
340
+ },
341
+ };
342
+ const llm = {
343
+ async dedupDecision() {
344
+ llmCalls += 1;
345
+ return { action: "MERGE" as const, reason: "should never be called" };
346
+ },
347
+ };
348
+
349
+ const result = await dedupCheck(
350
+ store as any,
351
+ [1, 0, 0],
352
+ "OpenClaw provider 配置里已经写过 `ANTHROPIC_BASE_URL` 和 `ANTHROPIC_AUTH_TOKEN` 的设置方法,但这里重复了一遍。",
353
+ llm as any,
354
+ );
355
+
356
+ expect(result.action).toBe("skip");
357
+ expect(result.reason).toBe("hard");
358
+ expect(llmCalls).toBe(0);
359
+ });
360
+ });