recallnest 3.0.0 → 4.0.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 (246) hide show
  1. package/CHANGELOG.md +304 -0
  2. package/README.md +251 -258
  3. package/README_CN.md +226 -247
  4. package/assets/ui/app.js +6 -1
  5. package/bin/recallnest.mjs +20 -37
  6. package/docs/api-reference.md +8 -0
  7. package/docs/architecture.md +18 -13
  8. package/eval/cases-canary.json +107 -9
  9. package/integrations/examples/claude-agent-sdk/memory-agent.ts +2 -0
  10. package/integrations/examples/langchain/memory-chain.py +4 -0
  11. package/integrations/examples/openai-agents-sdk/memory-agent.py +4 -0
  12. package/package.json +12 -3
  13. package/src/activity-counter.ts +1 -0
  14. package/src/adaptive-retrieval.ts +23 -0
  15. package/src/api-server.ts +13 -11
  16. package/src/asset-sync.ts +26 -2
  17. package/src/audit-log.ts +2 -0
  18. package/src/auto-gc.ts +4 -3
  19. package/src/belief-history.ts +137 -31
  20. package/src/capture-engine.ts +459 -71
  21. package/src/cascade-forget.ts +7 -3
  22. package/src/checkpoint-mirror.ts +417 -0
  23. package/src/cli.ts +574 -54
  24. package/src/conflict-engine.ts +43 -15
  25. package/src/consolidation-engine.ts +24 -3
  26. package/src/context-collapse-renderer.ts +8 -1
  27. package/src/context-composer-stable.ts +5 -1
  28. package/src/context-composer.ts +11 -2
  29. package/src/distill-lock.ts +246 -74
  30. package/src/dream-pipeline.ts +3 -1
  31. package/src/embedder.ts +24 -0
  32. package/src/env-config.ts +136 -0
  33. package/src/flock.ts +97 -0
  34. package/src/forget-engine.ts +342 -58
  35. package/src/gateway-server.ts +4 -0
  36. package/src/ingest-plan.ts +56 -0
  37. package/src/ingest.ts +294 -121
  38. package/src/kg-contradiction.ts +753 -0
  39. package/src/kg-extractor.ts +17 -0
  40. package/src/kg-store.ts +1 -1
  41. package/src/known-item-eval.ts +455 -0
  42. package/src/llm-client.ts +13 -26
  43. package/src/llm-consolidation.ts +2 -2
  44. package/src/mcp-tool-deps.ts +6 -0
  45. package/src/mcp-tools-advanced.ts +80 -45
  46. package/src/mcp-tools-core.ts +23 -17
  47. package/src/mcp-tools-governance.ts +13 -7
  48. package/src/memory-assets.ts +144 -8
  49. package/src/memory-boundaries.ts +19 -0
  50. package/src/memory-evolution.ts +9 -0
  51. package/src/memory-lint.ts +1 -1
  52. package/src/memory-output.ts +311 -14
  53. package/src/memory-reconcile.ts +1437 -0
  54. package/src/memory-schema.ts +11 -0
  55. package/src/memory-store-port.ts +1 -0
  56. package/src/minis-archive.ts +151 -0
  57. package/src/noise-filter.ts +15 -2
  58. package/src/pii-detector.ts +31 -1
  59. package/src/pivot-apply.ts +55 -5
  60. package/src/pivot-evidence.ts +128 -0
  61. package/src/ppr-traversal.ts +25 -1
  62. package/src/preference-matcher.ts +40 -28
  63. package/src/prospective-memory.ts +7 -4
  64. package/src/retriever.ts +297 -57
  65. package/src/retroactive-boost.ts +3 -2
  66. package/src/runtime-config.ts +15 -1
  67. package/src/scope-policy.ts +1 -0
  68. package/src/session-distiller.ts +6 -2
  69. package/src/session-engine.ts +11 -4
  70. package/src/session-output.ts +20 -1
  71. package/src/session-schema.ts +5 -2
  72. package/src/session-store.ts +59 -12
  73. package/src/skill-promotion.ts +67 -1
  74. package/src/store-receipts.ts +109 -0
  75. package/src/store-write-budget.ts +37 -0
  76. package/src/store.ts +298 -57
  77. package/src/text-fingerprint.ts +25 -0
  78. package/src/trigger-store.ts +443 -0
  79. package/src/ui-server.ts +22 -21
  80. package/src/version-manager.ts +19 -5
  81. package/src/write-verifier.ts +16 -11
  82. package/src/__tests__/access-tracker-novelty.test.ts +0 -324
  83. package/src/__tests__/activity-counter.test.ts +0 -125
  84. package/src/__tests__/adaptive-fidelity.test.ts +0 -102
  85. package/src/__tests__/admission-control.test.ts +0 -206
  86. package/src/__tests__/age-label.test.ts +0 -33
  87. package/src/__tests__/anchor-generator.test.ts +0 -67
  88. package/src/__tests__/api-server-security.test.ts +0 -102
  89. package/src/__tests__/auto-consolidation.test.ts +0 -168
  90. package/src/__tests__/auto-recall.test.ts +0 -131
  91. package/src/__tests__/babel-integration.test.ts +0 -144
  92. package/src/__tests__/batch-dedup.test.ts +0 -65
  93. package/src/__tests__/belief-history.test.ts +0 -220
  94. package/src/__tests__/canary-eval.test.ts +0 -114
  95. package/src/__tests__/capture-engine.test.ts +0 -1328
  96. package/src/__tests__/capture-heuristic.test.ts +0 -171
  97. package/src/__tests__/cascade-forget.test.ts +0 -210
  98. package/src/__tests__/category-min-scores.test.ts +0 -116
  99. package/src/__tests__/cc8-cc1-essential-context.test.ts +0 -298
  100. package/src/__tests__/circuit-breaker.test.ts +0 -99
  101. package/src/__tests__/cluster-consolidation.test.ts +0 -1236
  102. package/src/__tests__/confidence-metadata.test.ts +0 -125
  103. package/src/__tests__/confidence-tracker.test.ts +0 -261
  104. package/src/__tests__/conflict-advisor.test.ts +0 -206
  105. package/src/__tests__/conflict-escalation.test.ts +0 -149
  106. package/src/__tests__/conflict-lifecycle.test.ts +0 -83
  107. package/src/__tests__/conflict-output.test.ts +0 -85
  108. package/src/__tests__/conflict-store.test.ts +0 -418
  109. package/src/__tests__/connector-v1.test.ts +0 -181
  110. package/src/__tests__/consolidation-engine.test.ts +0 -520
  111. package/src/__tests__/constructive-retrieval.test.ts +0 -509
  112. package/src/__tests__/context-collapse-renderer.test.ts +0 -214
  113. package/src/__tests__/context-composer-pins.test.ts +0 -64
  114. package/src/__tests__/context-composer-task-selection.test.ts +0 -24
  115. package/src/__tests__/context-reconstructor.test.ts +0 -65
  116. package/src/__tests__/context-renderer.test.ts +0 -91
  117. package/src/__tests__/continuity-eval.test.ts +0 -275
  118. package/src/__tests__/continuity-schema.test.ts +0 -97
  119. package/src/__tests__/contracts.test.ts +0 -262
  120. package/src/__tests__/conversation-importer.test.ts +0 -692
  121. package/src/__tests__/core-recall-eval.test.ts +0 -235
  122. package/src/__tests__/core-summary.test.ts +0 -109
  123. package/src/__tests__/data-checkup.test.ts +0 -304
  124. package/src/__tests__/decay-exemption.test.ts +0 -129
  125. package/src/__tests__/dedup-actions.test.ts +0 -58
  126. package/src/__tests__/dedup-guard.test.ts +0 -39
  127. package/src/__tests__/deterministic-id.test.ts +0 -39
  128. package/src/__tests__/distill-lock.test.ts +0 -305
  129. package/src/__tests__/distill-session-argshape.test.ts +0 -79
  130. package/src/__tests__/doctor.test.ts +0 -319
  131. package/src/__tests__/dream-pipeline.test.ts +0 -820
  132. package/src/__tests__/dream-scope-isolation.test.ts +0 -386
  133. package/src/__tests__/dream-write-batching.test.ts +0 -211
  134. package/src/__tests__/drill-down.test.ts +0 -108
  135. package/src/__tests__/embedder.test.ts +0 -122
  136. package/src/__tests__/emotion-decay.test.ts +0 -46
  137. package/src/__tests__/emotion-detector.test.ts +0 -56
  138. package/src/__tests__/emotion-phase1-integration.test.ts +0 -153
  139. package/src/__tests__/emotion-retrieval.test.ts +0 -56
  140. package/src/__tests__/entity-resolver.test.ts +0 -58
  141. package/src/__tests__/env-config-invariant.test.ts +0 -80
  142. package/src/__tests__/env-config.test.ts +0 -211
  143. package/src/__tests__/error-signature-boost.test.ts +0 -87
  144. package/src/__tests__/error-signature.test.ts +0 -95
  145. package/src/__tests__/error-taxonomy.test.ts +0 -129
  146. package/src/__tests__/ethics-layer.test.ts +0 -476
  147. package/src/__tests__/event-segmenter.test.ts +0 -153
  148. package/src/__tests__/feature-flags-integration.test.ts +0 -54
  149. package/src/__tests__/frequency-tracker.test.ts +0 -113
  150. package/src/__tests__/freshness.test.ts +0 -186
  151. package/src/__tests__/graph-export.test.ts +0 -489
  152. package/src/__tests__/hotness-blend.test.ts +0 -283
  153. package/src/__tests__/ingest-chunking.test.ts +0 -44
  154. package/src/__tests__/ingest-scope-prefix.test.ts +0 -69
  155. package/src/__tests__/ingest.test.ts +0 -360
  156. package/src/__tests__/interference-detector.test.ts +0 -203
  157. package/src/__tests__/kg-extractor.test.ts +0 -192
  158. package/src/__tests__/kg-store.test.ts +0 -300
  159. package/src/__tests__/llm-client-pivot.test.ts +0 -628
  160. package/src/__tests__/llm-consolidation.test.ts +0 -226
  161. package/src/__tests__/maintenance-locks.test.ts +0 -197
  162. package/src/__tests__/mcp-efficiency.test.ts +0 -288
  163. package/src/__tests__/mcp-related-scopes.test.ts +0 -151
  164. package/src/__tests__/memory-boundaries.test.ts +0 -282
  165. package/src/__tests__/memory-evolution-b2-b3-e1.test.ts +0 -362
  166. package/src/__tests__/memory-evolution.test.ts +0 -271
  167. package/src/__tests__/memory-health-rebalance.test.ts +0 -144
  168. package/src/__tests__/memory-lint.test.ts +0 -421
  169. package/src/__tests__/memory-output.test.ts +0 -224
  170. package/src/__tests__/memory-promotion.test.ts +0 -315
  171. package/src/__tests__/memory-utility.test.ts +0 -256
  172. package/src/__tests__/migrate-dedup-ids.test.ts +0 -65
  173. package/src/__tests__/multi-vector.test.ts +0 -242
  174. package/src/__tests__/narrative-architecture.test.ts +0 -456
  175. package/src/__tests__/noise-filter.test.ts +0 -205
  176. package/src/__tests__/noise-prototype-bank.test.ts +0 -280
  177. package/src/__tests__/obsidian-connector.test.ts +0 -363
  178. package/src/__tests__/omitted-reporting.test.ts +0 -98
  179. package/src/__tests__/openai-contract.test.ts +0 -513
  180. package/src/__tests__/pending-review.test.ts +0 -77
  181. package/src/__tests__/pii-redact.test.ts +0 -333
  182. package/src/__tests__/pivot-apply.test.ts +0 -373
  183. package/src/__tests__/pivot-distill-supervisor.test.ts +0 -457
  184. package/src/__tests__/pivot-distill.test.ts +0 -1178
  185. package/src/__tests__/post-retrieval-filter.test.ts +0 -178
  186. package/src/__tests__/ppr-traversal.test.ts +0 -256
  187. package/src/__tests__/prediction-engine.test.ts +0 -349
  188. package/src/__tests__/predictive-prospective-memory.test.ts +0 -416
  189. package/src/__tests__/preference-guard-smoke.test.ts +0 -211
  190. package/src/__tests__/preference-matcher.test.ts +0 -282
  191. package/src/__tests__/preference-slots.test.ts +0 -205
  192. package/src/__tests__/promotion-distinct-sources.test.ts +0 -162
  193. package/src/__tests__/prospective-memory.test.ts +0 -283
  194. package/src/__tests__/pull-from-macbook-sync-only.test.ts +0 -679
  195. package/src/__tests__/query-entity-detector.test.ts +0 -171
  196. package/src/__tests__/query-expander-alias.test.ts +0 -146
  197. package/src/__tests__/query-expander.test.ts +0 -34
  198. package/src/__tests__/recall-gate.test.ts +0 -266
  199. package/src/__tests__/recall-governor.test.ts +0 -227
  200. package/src/__tests__/recall-mode.test.ts +0 -64
  201. package/src/__tests__/resolve-db-path.test.ts +0 -130
  202. package/src/__tests__/resolve-tier.test.ts +0 -64
  203. package/src/__tests__/result-synthesizer.test.ts +0 -198
  204. package/src/__tests__/resume-context.test.ts +0 -4898
  205. package/src/__tests__/retrieval-eval.test.ts +0 -163
  206. package/src/__tests__/retrieval-trace.test.ts +0 -213
  207. package/src/__tests__/retrieve-audit-revision.test.ts +0 -255
  208. package/src/__tests__/retriever-boundary-weight.test.ts +0 -136
  209. package/src/__tests__/retriever-lazy-init-dispatch.test.ts +0 -123
  210. package/src/__tests__/retroactive-boost.test.ts +0 -223
  211. package/src/__tests__/salience-scoring.test.ts +0 -106
  212. package/src/__tests__/scope-inventory.test.ts +0 -200
  213. package/src/__tests__/scope-policy.test.ts +0 -69
  214. package/src/__tests__/scope-suggester.test.ts +0 -80
  215. package/src/__tests__/session-checkpoint.test.ts +0 -291
  216. package/src/__tests__/session-distiller.test.ts +0 -640
  217. package/src/__tests__/session-gc.test.ts +0 -215
  218. package/src/__tests__/skill-engine.test.ts +0 -552
  219. package/src/__tests__/skill-promotion.test.ts +0 -654
  220. package/src/__tests__/skill-verifier.test.ts +0 -122
  221. package/src/__tests__/source-heartbeat.test.ts +0 -254
  222. package/src/__tests__/stable-context-length-contract.test.ts +0 -62
  223. package/src/__tests__/store-patch-metadata.test.ts +0 -235
  224. package/src/__tests__/store-read-consistency.test.ts +0 -122
  225. package/src/__tests__/store-schema-migration.test.ts +0 -87
  226. package/src/__tests__/store-scope-audit.test.ts +0 -81
  227. package/src/__tests__/store-upsert.test.ts +0 -201
  228. package/src/__tests__/supersede-chain.test.ts +0 -154
  229. package/src/__tests__/synthesis-contract.test.ts +0 -252
  230. package/src/__tests__/synthesis-promotion.test.ts +0 -369
  231. package/src/__tests__/temporal-parser.test.ts +0 -241
  232. package/src/__tests__/temporal-validity.test.ts +0 -160
  233. package/src/__tests__/term-registry-terminal-roster.test.ts +0 -127
  234. package/src/__tests__/term-registry.test.ts +0 -121
  235. package/src/__tests__/tool-error-surfacing.test.ts +0 -98
  236. package/src/__tests__/tool-output-compressor.test.ts +0 -160
  237. package/src/__tests__/topic-tag.test.ts +0 -113
  238. package/src/__tests__/trusted-memory.test.ts +0 -867
  239. package/src/__tests__/ui-server-security.test.ts +0 -93
  240. package/src/__tests__/usage-tracker.test.ts +0 -287
  241. package/src/__tests__/utility-weight.test.ts +0 -57
  242. package/src/__tests__/verbatim-self-recall.test.ts +0 -279
  243. package/src/__tests__/version-manager.test.ts +0 -248
  244. package/src/__tests__/workflow-observation-skill-outcome.test.ts +0 -352
  245. package/src/__tests__/workflow-observation.test.ts +0 -433
  246. package/src/__tests__/write-verifier.test.ts +0 -122
@@ -1,226 +0,0 @@
1
- /**
2
- * Tests for Tier 3.7: LLM-Driven Consolidation
3
- *
4
- * Validates:
5
- * 1. evaluateCluster returns merge decisions from LLM
6
- * 2. evaluateCluster falls back conservatively on LLM failure
7
- * 3. executeMergeDecisions creates version groups for merge groups
8
- * 4. executeMergeDecisions handles empty merge groups
9
- * 5. isLLMConsolidationEnabled respects env var
10
- */
11
- import { describe, expect, it, afterEach } from "bun:test";
12
- import {
13
- evaluateCluster,
14
- executeMergeDecisions,
15
- isLLMConsolidationEnabled,
16
- } from "../llm-consolidation.js";
17
- import type { MemoryEntry } from "../store.js";
18
- import type { LLMClient } from "../llm-client.js";
19
-
20
- // ---------------------------------------------------------------------------
21
- // Helpers
22
- // ---------------------------------------------------------------------------
23
-
24
- function makeEntry(id: string, text: string, importance = 0.7): MemoryEntry {
25
- return {
26
- id,
27
- text,
28
- vector: [1, 0, 0],
29
- category: "preferences",
30
- scope: "project:test",
31
- importance,
32
- timestamp: Date.now(),
33
- metadata: JSON.stringify({ confidence: 0.7, accessCount: 0 }),
34
- };
35
- }
36
-
37
- function createMockStore(entries: MemoryEntry[]) {
38
- const data = new Map(entries.map(e => [e.id, { ...e }]));
39
- const updates: Array<{ id: string; metadata: string }> = [];
40
-
41
- return {
42
- data,
43
- updates,
44
- async getById(id: string) { return data.get(id) ?? null; },
45
- async update(id: string, upd: { metadata?: string }, _scope?: string[]) {
46
- const entry = data.get(id);
47
- if (!entry) return null;
48
- if (upd.metadata) {
49
- entry.metadata = upd.metadata;
50
- updates.push({ id, metadata: upd.metadata });
51
- }
52
- return entry;
53
- },
54
- };
55
- }
56
-
57
- function createMockLLM(response: string): LLMClient {
58
- return {
59
- async synthesizeFragments() {
60
- return response;
61
- },
62
- } as any;
63
- }
64
-
65
- // ---------------------------------------------------------------------------
66
- // evaluateCluster
67
- // ---------------------------------------------------------------------------
68
-
69
- describe("evaluateCluster", () => {
70
- it("returns merge groups from LLM response", async () => {
71
- const entries = [
72
- makeEntry("a", "User prefers dark mode"),
73
- makeEntry("b", "User likes dark theme"),
74
- makeEntry("c", "User uses vim keybindings"),
75
- ];
76
-
77
- const llm = createMockLLM(JSON.stringify({
78
- mergeGroups: [[0, 1]],
79
- keepSeparate: [2],
80
- reasoning: "0 and 1 express same preference, 2 is different",
81
- }));
82
-
83
- const decision = await evaluateCluster(llm, entries);
84
-
85
- expect(decision.mergeGroups.length).toBe(1);
86
- expect(decision.mergeGroups[0]).toEqual([0, 1]);
87
- expect(decision.keepSeparate).toEqual([2]);
88
- });
89
-
90
- it("returns conservative fallback on LLM failure", async () => {
91
- const entries = [makeEntry("a", "text a"), makeEntry("b", "text b")];
92
- const llm = {
93
- async synthesizeFragments() { throw new Error("LLM down"); },
94
- } as any;
95
-
96
- const decision = await evaluateCluster(llm, entries);
97
-
98
- expect(decision.mergeGroups.length).toBe(0);
99
- expect(decision.keepSeparate.length).toBe(2);
100
- });
101
-
102
- it("returns conservative fallback on null response", async () => {
103
- const entries = [makeEntry("a", "text a"), makeEntry("b", "text b")];
104
- const llm = createMockLLM("");
105
-
106
- // Empty string → null synthesis → fallback
107
- const decision = await evaluateCluster({ async synthesizeFragments() { return null; } } as any, entries);
108
-
109
- expect(decision.mergeGroups.length).toBe(0);
110
- });
111
-
112
- it("handles single entry", async () => {
113
- const entries = [makeEntry("a", "only one")];
114
- const llm = createMockLLM("{}");
115
-
116
- const decision = await evaluateCluster(llm, entries);
117
-
118
- expect(decision.mergeGroups.length).toBe(0);
119
- expect(decision.keepSeparate).toEqual([0]);
120
- });
121
-
122
- it("filters invalid indices from LLM response", async () => {
123
- const entries = [makeEntry("a", "text a"), makeEntry("b", "text b")];
124
- const llm = createMockLLM(JSON.stringify({
125
- mergeGroups: [[0, 5]], // index 5 out of range
126
- keepSeparate: [0, 1],
127
- reasoning: "test",
128
- }));
129
-
130
- const decision = await evaluateCluster(llm, entries);
131
-
132
- // Invalid group should be filtered out
133
- expect(decision.mergeGroups.length).toBe(0);
134
- });
135
- });
136
-
137
- // ---------------------------------------------------------------------------
138
- // executeMergeDecisions
139
- // ---------------------------------------------------------------------------
140
-
141
- describe("executeMergeDecisions", () => {
142
- it("creates version groups for merge groups", async () => {
143
- const entries = [
144
- makeEntry("a", "dark mode pref", 0.9),
145
- makeEntry("b", "dark theme pref", 0.5),
146
- makeEntry("c", "vim pref", 0.7),
147
- ];
148
- const store = createMockStore(entries);
149
-
150
- const decision = {
151
- mergeGroups: [[0, 1]],
152
- keepSeparate: [2],
153
- reasoning: "similar preferences",
154
- };
155
-
156
- const mergeCount = await executeMergeDecisions(store as any, entries, decision, "project:test");
157
-
158
- expect(mergeCount).toBe(1);
159
- // Both a and b should now have version_group
160
- const metaA = JSON.parse(store.data.get("a")!.metadata);
161
- const metaB = JSON.parse(store.data.get("b")!.metadata);
162
- expect(metaA.version_group).toBeTruthy();
163
- expect(metaB.version_group).toBe(metaA.version_group);
164
- });
165
-
166
- it("handles empty merge groups", async () => {
167
- const entries = [makeEntry("a", "text a")];
168
- const store = createMockStore(entries);
169
-
170
- const decision = {
171
- mergeGroups: [],
172
- keepSeparate: [0],
173
- reasoning: "nothing to merge",
174
- };
175
-
176
- const mergeCount = await executeMergeDecisions(store as any, entries, decision, "project:test");
177
-
178
- expect(mergeCount).toBe(0);
179
- });
180
-
181
- it("handles multi-entry merge group", async () => {
182
- const entries = [
183
- makeEntry("a", "pref 1", 0.9),
184
- makeEntry("b", "pref 2", 0.7),
185
- makeEntry("c", "pref 3", 0.5),
186
- ];
187
- const store = createMockStore(entries);
188
-
189
- const decision = {
190
- mergeGroups: [[0, 1, 2]],
191
- keepSeparate: [],
192
- reasoning: "all same",
193
- };
194
-
195
- const mergeCount = await executeMergeDecisions(store as any, entries, decision, "project:test");
196
-
197
- // a is canonical, b and c are members → 2 merges
198
- expect(mergeCount).toBe(2);
199
- });
200
- });
201
-
202
- // ---------------------------------------------------------------------------
203
- // isLLMConsolidationEnabled
204
- // ---------------------------------------------------------------------------
205
-
206
- describe("isLLMConsolidationEnabled", () => {
207
- const originalEnv = process.env.RECALLNEST_LLM_CONSOLIDATION;
208
-
209
- afterEach(() => {
210
- if (originalEnv !== undefined) {
211
- process.env.RECALLNEST_LLM_CONSOLIDATION = originalEnv;
212
- } else {
213
- delete process.env.RECALLNEST_LLM_CONSOLIDATION;
214
- }
215
- });
216
-
217
- it("returns false when not set", () => {
218
- delete process.env.RECALLNEST_LLM_CONSOLIDATION;
219
- expect(isLLMConsolidationEnabled()).toBe(false);
220
- });
221
-
222
- it("returns true when set to 'true'", () => {
223
- process.env.RECALLNEST_LLM_CONSOLIDATION = "true";
224
- expect(isLLMConsolidationEnabled()).toBe(true);
225
- });
226
- });
@@ -1,197 +0,0 @@
1
- import { afterEach, describe, expect, it } from "bun:test";
2
- import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { dirname, join } from "node:path";
5
-
6
- import { runDream } from "../dream-pipeline.js";
7
- import { maybeRunGc, resetGcTimestamp, type AutoGcConfig, DEFAULT_AUTO_GC_CONFIG } from "../auto-gc.js";
8
- import { lockPathForKey } from "../distill-lock.js";
9
- import { incrementWriteCount, getWriteCount } from "../activity-counter.js";
10
-
11
- // Isolate dream's activity-counter reads/writes to a temp file so tests never touch the
12
- // repo's data/activity-stats.json (which the production dream scheduler reads).
13
- const DREAM_STATS = join(mkdtempSync(join(tmpdir(), "rn-dream-stats-")), "activity-stats.json");
14
-
15
- /**
16
- * P0-1 接线回归:dream/gc 维护入口接了跨进程锁。用「预写一个当前进程 PID 的锁文件」
17
- * 模拟「另一进程持有锁」(同进程 PID 恒活,acquireLock 判定为被占)。
18
- */
19
-
20
- const createdLocks: string[] = [];
21
- function holdLock(key: string): string {
22
- const p = lockPathForKey(key);
23
- mkdirSync(dirname(p), { recursive: true });
24
- writeFileSync(p, String(process.pid), "utf-8"); // current pid ⇒ acquireLock sees it as a live holder
25
- createdLocks.push(p);
26
- return p;
27
- }
28
-
29
- afterEach(() => {
30
- while (createdLocks.length > 0) {
31
- try {
32
- rmSync(createdLocks.pop()!, { force: true });
33
- } catch {
34
- /* ignore */
35
- }
36
- }
37
- resetGcTimestamp();
38
- });
39
-
40
- describe("runDream cross-process lock", () => {
41
- it("skips (ran:false, locked) and does not run the body when the scope lock is held", async () => {
42
- const scope = "project:dream-lock-test";
43
- holdLock(`dream-${scope}`);
44
-
45
- let bodyRan = false;
46
- const store = {
47
- stats: async () => {
48
- bodyRan = true;
49
- return { totalCount: 100, scopeCounts: {}, categoryCounts: {} };
50
- },
51
- repairSingletonVersionGroups: async () => 0,
52
- list: async () => [],
53
- listPage: async () => [],
54
- update: async () => null,
55
- patchMetadataBatch: async (patches: Array<{ id: string; patchFn: unknown }>) => patches.length,
56
- patchMetadata: async () => null,
57
- };
58
-
59
- const result = await runDream({
60
- store: store as any,
61
- llm: null,
62
- embedder: { embedPassage: async () => [0, 0, 0] },
63
- scope,
64
- force: true,
65
- activityStatsPath: DREAM_STATS,
66
- });
67
-
68
- expect(result.ran).toBe(false);
69
- expect(result.reason).toBe("locked_by_another_process");
70
- expect(bodyRan).toBe(false); // runDreamInner never entered
71
- });
72
-
73
- it("skips its consolidation phase when the scope's consolidate lock is held", async () => {
74
- const scope = "project:dream-consolidate-test";
75
- holdLock(`consolidate-${scope}`); // simulate a standalone consolidate_memories running
76
- // 2026-08-12:预置写计数,用于在末尾断言「锁被占 = 没真正处理 = 计数必须留着」。
77
- incrementWriteCount(scope, 15, { statsPath: DREAM_STATS });
78
-
79
- const activeMeta = JSON.stringify({
80
- evolution: { status: "active", version: 1, accessCount: 0, lastAccessedAt: null, validFrom: Date.now(), validUntil: null },
81
- });
82
- const entries = [1, 2, 3].map((i) => ({
83
- id: `dc-e${i}`, text: `t${i}`, vector: [1, 0, 0], category: "events", scope,
84
- importance: 0.5, timestamp: Date.now(), metadata: activeMeta, language: "en", fts_text: `t${i}`,
85
- }));
86
- const store = {
87
- stats: async () => ({ totalCount: 100, scopeCounts: {}, categoryCounts: {} }),
88
- repairSingletonVersionGroups: async () => 0,
89
- list: async () => entries,
90
- listPage: async () => [],
91
- update: async () => null,
92
- patchMetadataBatch: async (patches: Array<{ id: string; patchFn: unknown }>) => patches.length,
93
- patchMetadata: async () => null,
94
- getById: async () => null,
95
- vectorSearch: async () => [],
96
- };
97
-
98
- const result = await runDream({
99
- store: store as any,
100
- llm: null,
101
- embedder: { embedPassage: async () => [0, 0, 0] },
102
- scope,
103
- force: true,
104
- activityStatsPath: DREAM_STATS,
105
- });
106
-
107
- // Dream itself ran (its own dream lock was free), but the consolidation phase saw the
108
- // held consolidate lock and skipped rather than running concurrently.
109
- expect(result.ran).toBe(true);
110
- const consolidatePhase = result.phases.find((p) => p.phase === "consolidate");
111
- expect(consolidatePhase?.detail).toContain("skipped");
112
-
113
- // 2026-08-12 防「修过头」:末尾的 reset 必须是 `if (consolidateOutcome.ran)` 条件式。
114
- // 锁被占时这个 scope 并没有被真正处理完,若无条件清计数,它会被当成「已处理」而
115
- // 丢掉本轮积累的写入,下次要重新攒够阈值才轮得到 —— 是比原 bug 更隐蔽的数据损失。
116
- // 注意本条不是必红测试:修复前的无参 resetWriteCount() 什么也不清,同样是绿。
117
- // 它守的是修复的形状,不是修复的存在(存在性由 dream-pipeline.test.ts 那条守)。
118
- expect(getWriteCount(scope, { statsPath: DREAM_STATS })).toBe(15);
119
- });
120
-
121
- it("resets the scope's write counter after a run (no perpetual self-triggering)", async () => {
122
- const scope = "project:dream-reset-test";
123
- const statsPath = join(mkdtempSync(join(tmpdir(), "rn-reset-")), "activity-stats.json");
124
- // Pre-load above threshold, standing in for accumulated writes (incl. any dream self-writes).
125
- incrementWriteCount(scope, 15, { statsPath });
126
- expect(getWriteCount(scope, { statsPath })).toBe(15);
127
-
128
- const store = {
129
- stats: async () => ({ totalCount: 5, scopeCounts: {}, categoryCounts: {} }),
130
- repairSingletonVersionGroups: async () => 0,
131
- // ⚠️ 2026-08-12 标注:这里 list 返回空数组,走的是 **completed_early 早退路径**,
132
- // 而早退路径 (dream-pipeline.ts:226) 的 resetWriteCount(scope, statsCfg) 一直是对的。
133
- // 本条测试因此从未覆盖「完整跑完」那条路径 —— 而 bug 恰恰在那条路径上(:301 漏传 scope)。
134
- // 测试名 "resets the scope's write counter after a run" 读起来像覆盖了 reset 全部行为,
135
- // 实际只覆盖了两条路径中正确的那一条,于是 bug 在有测试的情况下活了 41 天。
136
- // 完整路径的覆盖已补在 dream-pipeline.test.ts「清空已处理 scope 的写计数」一条。
137
- list: async () => [], // no active entries → completed_early path (still resets)
138
- listPage: async () => [],
139
- update: async () => null,
140
- patchMetadataBatch: async (patches: Array<{ id: string; patchFn: unknown }>) => patches.length,
141
- patchMetadata: async () => null,
142
- getById: async () => null,
143
- vectorSearch: async () => [],
144
- };
145
- const result = await runDream({
146
- store: store as any,
147
- llm: null,
148
- embedder: { embedPassage: async () => [0, 0, 0] },
149
- scope,
150
- force: true,
151
- activityStatsPath: statsPath,
152
- });
153
-
154
- expect(result.ran).toBe(true);
155
- // Reset at dream's end clears the counter, so dream won't immediately self-retrigger —
156
- // fresh external writes must accumulate past the threshold again.
157
- expect(getWriteCount(scope, { statsPath })).toBe(0);
158
- });
159
- });
160
-
161
- describe("maybeRunGc cross-process lock + throttle", () => {
162
- function makeStore(totalCount: number) {
163
- return {
164
- stats: async () => ({ totalCount, scopeCounts: {}, categoryCounts: {} }),
165
- repairSingletonVersionGroups: async () => 0,
166
- listPage: async () => [] as unknown[],
167
- update: async () => null,
168
- patchMetadataBatch: async (patches: Array<{ id: string; patchFn: unknown }>) => patches.length,
169
- list: async () => [],
170
- } as any;
171
- }
172
-
173
- it("skips (locked) when another process holds the gc run lock", async () => {
174
- resetGcTimestamp();
175
- holdLock("gc-run");
176
- const config: AutoGcConfig = { ...DEFAULT_AUTO_GC_CONFIG, minMemoryCount: 1, minHoursSinceLastGc: 24 };
177
- const result = await maybeRunGc(makeStore(10), config);
178
- expect(result.triggered).toBe(false);
179
- expect(result.reason).toBe("locked_by_another_process");
180
- });
181
-
182
- it("throttles a second run within the window, then runs again after reset", async () => {
183
- resetGcTimestamp();
184
- const config: AutoGcConfig = { ...DEFAULT_AUTO_GC_CONFIG, minMemoryCount: 1, minHoursSinceLastGc: 24 };
185
-
186
- const first = await maybeRunGc(makeStore(10), config);
187
- expect(first.triggered).toBe(true);
188
-
189
- const second = await maybeRunGc(makeStore(10), config);
190
- expect(second.triggered).toBe(false);
191
- expect(second.reason).toBe("too_soon");
192
-
193
- resetGcTimestamp();
194
- const third = await maybeRunGc(makeStore(10), config);
195
- expect(third.triggered).toBe(true);
196
- });
197
- });