recallnest 3.0.0 → 3.0.1

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 (184) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +222 -254
  3. package/README_CN.md +206 -243
  4. package/package.json +3 -2
  5. package/src/capture-engine.ts +26 -4
  6. package/src/context-composer-stable.ts +5 -1
  7. package/src/embedder.ts +24 -0
  8. package/src/env-config.ts +18 -0
  9. package/src/ingest.ts +225 -17
  10. package/src/kg-extractor.ts +17 -0
  11. package/src/memory-output.ts +35 -0
  12. package/src/pivot-apply.ts +52 -1
  13. package/src/pivot-evidence.ts +128 -0
  14. package/src/ppr-traversal.ts +25 -1
  15. package/src/runtime-config.ts +9 -0
  16. package/src/session-engine.ts +11 -4
  17. package/src/session-output.ts +9 -1
  18. package/src/session-store.ts +2 -3
  19. package/src/skill-promotion.ts +67 -1
  20. package/src/__tests__/access-tracker-novelty.test.ts +0 -324
  21. package/src/__tests__/activity-counter.test.ts +0 -125
  22. package/src/__tests__/adaptive-fidelity.test.ts +0 -102
  23. package/src/__tests__/admission-control.test.ts +0 -206
  24. package/src/__tests__/age-label.test.ts +0 -33
  25. package/src/__tests__/anchor-generator.test.ts +0 -67
  26. package/src/__tests__/api-server-security.test.ts +0 -102
  27. package/src/__tests__/auto-consolidation.test.ts +0 -168
  28. package/src/__tests__/auto-recall.test.ts +0 -131
  29. package/src/__tests__/babel-integration.test.ts +0 -144
  30. package/src/__tests__/batch-dedup.test.ts +0 -65
  31. package/src/__tests__/belief-history.test.ts +0 -220
  32. package/src/__tests__/canary-eval.test.ts +0 -114
  33. package/src/__tests__/capture-engine.test.ts +0 -1328
  34. package/src/__tests__/capture-heuristic.test.ts +0 -171
  35. package/src/__tests__/cascade-forget.test.ts +0 -210
  36. package/src/__tests__/category-min-scores.test.ts +0 -116
  37. package/src/__tests__/cc8-cc1-essential-context.test.ts +0 -298
  38. package/src/__tests__/circuit-breaker.test.ts +0 -99
  39. package/src/__tests__/cluster-consolidation.test.ts +0 -1236
  40. package/src/__tests__/confidence-metadata.test.ts +0 -125
  41. package/src/__tests__/confidence-tracker.test.ts +0 -261
  42. package/src/__tests__/conflict-advisor.test.ts +0 -206
  43. package/src/__tests__/conflict-escalation.test.ts +0 -149
  44. package/src/__tests__/conflict-lifecycle.test.ts +0 -83
  45. package/src/__tests__/conflict-output.test.ts +0 -85
  46. package/src/__tests__/conflict-store.test.ts +0 -418
  47. package/src/__tests__/connector-v1.test.ts +0 -181
  48. package/src/__tests__/consolidation-engine.test.ts +0 -520
  49. package/src/__tests__/constructive-retrieval.test.ts +0 -509
  50. package/src/__tests__/context-collapse-renderer.test.ts +0 -214
  51. package/src/__tests__/context-composer-pins.test.ts +0 -64
  52. package/src/__tests__/context-composer-task-selection.test.ts +0 -24
  53. package/src/__tests__/context-reconstructor.test.ts +0 -65
  54. package/src/__tests__/context-renderer.test.ts +0 -91
  55. package/src/__tests__/continuity-eval.test.ts +0 -275
  56. package/src/__tests__/continuity-schema.test.ts +0 -97
  57. package/src/__tests__/contracts.test.ts +0 -262
  58. package/src/__tests__/conversation-importer.test.ts +0 -692
  59. package/src/__tests__/core-recall-eval.test.ts +0 -235
  60. package/src/__tests__/core-summary.test.ts +0 -109
  61. package/src/__tests__/data-checkup.test.ts +0 -304
  62. package/src/__tests__/decay-exemption.test.ts +0 -129
  63. package/src/__tests__/dedup-actions.test.ts +0 -58
  64. package/src/__tests__/dedup-guard.test.ts +0 -39
  65. package/src/__tests__/deterministic-id.test.ts +0 -39
  66. package/src/__tests__/distill-lock.test.ts +0 -305
  67. package/src/__tests__/distill-session-argshape.test.ts +0 -79
  68. package/src/__tests__/doctor.test.ts +0 -319
  69. package/src/__tests__/dream-pipeline.test.ts +0 -820
  70. package/src/__tests__/dream-scope-isolation.test.ts +0 -386
  71. package/src/__tests__/dream-write-batching.test.ts +0 -211
  72. package/src/__tests__/drill-down.test.ts +0 -108
  73. package/src/__tests__/embedder.test.ts +0 -122
  74. package/src/__tests__/emotion-decay.test.ts +0 -46
  75. package/src/__tests__/emotion-detector.test.ts +0 -56
  76. package/src/__tests__/emotion-phase1-integration.test.ts +0 -153
  77. package/src/__tests__/emotion-retrieval.test.ts +0 -56
  78. package/src/__tests__/entity-resolver.test.ts +0 -58
  79. package/src/__tests__/env-config-invariant.test.ts +0 -80
  80. package/src/__tests__/env-config.test.ts +0 -211
  81. package/src/__tests__/error-signature-boost.test.ts +0 -87
  82. package/src/__tests__/error-signature.test.ts +0 -95
  83. package/src/__tests__/error-taxonomy.test.ts +0 -129
  84. package/src/__tests__/ethics-layer.test.ts +0 -476
  85. package/src/__tests__/event-segmenter.test.ts +0 -153
  86. package/src/__tests__/feature-flags-integration.test.ts +0 -54
  87. package/src/__tests__/frequency-tracker.test.ts +0 -113
  88. package/src/__tests__/freshness.test.ts +0 -186
  89. package/src/__tests__/graph-export.test.ts +0 -489
  90. package/src/__tests__/hotness-blend.test.ts +0 -283
  91. package/src/__tests__/ingest-chunking.test.ts +0 -44
  92. package/src/__tests__/ingest-scope-prefix.test.ts +0 -69
  93. package/src/__tests__/ingest.test.ts +0 -360
  94. package/src/__tests__/interference-detector.test.ts +0 -203
  95. package/src/__tests__/kg-extractor.test.ts +0 -192
  96. package/src/__tests__/kg-store.test.ts +0 -300
  97. package/src/__tests__/llm-client-pivot.test.ts +0 -628
  98. package/src/__tests__/llm-consolidation.test.ts +0 -226
  99. package/src/__tests__/maintenance-locks.test.ts +0 -197
  100. package/src/__tests__/mcp-efficiency.test.ts +0 -288
  101. package/src/__tests__/mcp-related-scopes.test.ts +0 -151
  102. package/src/__tests__/memory-boundaries.test.ts +0 -282
  103. package/src/__tests__/memory-evolution-b2-b3-e1.test.ts +0 -362
  104. package/src/__tests__/memory-evolution.test.ts +0 -271
  105. package/src/__tests__/memory-health-rebalance.test.ts +0 -144
  106. package/src/__tests__/memory-lint.test.ts +0 -421
  107. package/src/__tests__/memory-output.test.ts +0 -224
  108. package/src/__tests__/memory-promotion.test.ts +0 -315
  109. package/src/__tests__/memory-utility.test.ts +0 -256
  110. package/src/__tests__/migrate-dedup-ids.test.ts +0 -65
  111. package/src/__tests__/multi-vector.test.ts +0 -242
  112. package/src/__tests__/narrative-architecture.test.ts +0 -456
  113. package/src/__tests__/noise-filter.test.ts +0 -205
  114. package/src/__tests__/noise-prototype-bank.test.ts +0 -280
  115. package/src/__tests__/obsidian-connector.test.ts +0 -363
  116. package/src/__tests__/omitted-reporting.test.ts +0 -98
  117. package/src/__tests__/openai-contract.test.ts +0 -513
  118. package/src/__tests__/pending-review.test.ts +0 -77
  119. package/src/__tests__/pii-redact.test.ts +0 -333
  120. package/src/__tests__/pivot-apply.test.ts +0 -373
  121. package/src/__tests__/pivot-distill-supervisor.test.ts +0 -457
  122. package/src/__tests__/pivot-distill.test.ts +0 -1178
  123. package/src/__tests__/post-retrieval-filter.test.ts +0 -178
  124. package/src/__tests__/ppr-traversal.test.ts +0 -256
  125. package/src/__tests__/prediction-engine.test.ts +0 -349
  126. package/src/__tests__/predictive-prospective-memory.test.ts +0 -416
  127. package/src/__tests__/preference-guard-smoke.test.ts +0 -211
  128. package/src/__tests__/preference-matcher.test.ts +0 -282
  129. package/src/__tests__/preference-slots.test.ts +0 -205
  130. package/src/__tests__/promotion-distinct-sources.test.ts +0 -162
  131. package/src/__tests__/prospective-memory.test.ts +0 -283
  132. package/src/__tests__/pull-from-macbook-sync-only.test.ts +0 -679
  133. package/src/__tests__/query-entity-detector.test.ts +0 -171
  134. package/src/__tests__/query-expander-alias.test.ts +0 -146
  135. package/src/__tests__/query-expander.test.ts +0 -34
  136. package/src/__tests__/recall-gate.test.ts +0 -266
  137. package/src/__tests__/recall-governor.test.ts +0 -227
  138. package/src/__tests__/recall-mode.test.ts +0 -64
  139. package/src/__tests__/resolve-db-path.test.ts +0 -130
  140. package/src/__tests__/resolve-tier.test.ts +0 -64
  141. package/src/__tests__/result-synthesizer.test.ts +0 -198
  142. package/src/__tests__/resume-context.test.ts +0 -4898
  143. package/src/__tests__/retrieval-eval.test.ts +0 -163
  144. package/src/__tests__/retrieval-trace.test.ts +0 -213
  145. package/src/__tests__/retrieve-audit-revision.test.ts +0 -255
  146. package/src/__tests__/retriever-boundary-weight.test.ts +0 -136
  147. package/src/__tests__/retriever-lazy-init-dispatch.test.ts +0 -123
  148. package/src/__tests__/retroactive-boost.test.ts +0 -223
  149. package/src/__tests__/salience-scoring.test.ts +0 -106
  150. package/src/__tests__/scope-inventory.test.ts +0 -200
  151. package/src/__tests__/scope-policy.test.ts +0 -69
  152. package/src/__tests__/scope-suggester.test.ts +0 -80
  153. package/src/__tests__/session-checkpoint.test.ts +0 -291
  154. package/src/__tests__/session-distiller.test.ts +0 -640
  155. package/src/__tests__/session-gc.test.ts +0 -215
  156. package/src/__tests__/skill-engine.test.ts +0 -552
  157. package/src/__tests__/skill-promotion.test.ts +0 -654
  158. package/src/__tests__/skill-verifier.test.ts +0 -122
  159. package/src/__tests__/source-heartbeat.test.ts +0 -254
  160. package/src/__tests__/stable-context-length-contract.test.ts +0 -62
  161. package/src/__tests__/store-patch-metadata.test.ts +0 -235
  162. package/src/__tests__/store-read-consistency.test.ts +0 -122
  163. package/src/__tests__/store-schema-migration.test.ts +0 -87
  164. package/src/__tests__/store-scope-audit.test.ts +0 -81
  165. package/src/__tests__/store-upsert.test.ts +0 -201
  166. package/src/__tests__/supersede-chain.test.ts +0 -154
  167. package/src/__tests__/synthesis-contract.test.ts +0 -252
  168. package/src/__tests__/synthesis-promotion.test.ts +0 -369
  169. package/src/__tests__/temporal-parser.test.ts +0 -241
  170. package/src/__tests__/temporal-validity.test.ts +0 -160
  171. package/src/__tests__/term-registry-terminal-roster.test.ts +0 -127
  172. package/src/__tests__/term-registry.test.ts +0 -121
  173. package/src/__tests__/tool-error-surfacing.test.ts +0 -98
  174. package/src/__tests__/tool-output-compressor.test.ts +0 -160
  175. package/src/__tests__/topic-tag.test.ts +0 -113
  176. package/src/__tests__/trusted-memory.test.ts +0 -867
  177. package/src/__tests__/ui-server-security.test.ts +0 -93
  178. package/src/__tests__/usage-tracker.test.ts +0 -287
  179. package/src/__tests__/utility-weight.test.ts +0 -57
  180. package/src/__tests__/verbatim-self-recall.test.ts +0 -279
  181. package/src/__tests__/version-manager.test.ts +0 -248
  182. package/src/__tests__/workflow-observation-skill-outcome.test.ts +0 -352
  183. package/src/__tests__/workflow-observation.test.ts +0 -433
  184. 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
- });