recallnest 2.6.1 → 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 (207) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +280 -195
  3. package/README_CN.md +266 -199
  4. package/config.json.example +8 -1
  5. package/docs/api-reference.md +1 -1
  6. package/integrations/README.md +1 -1
  7. package/integrations/agy/README.md +73 -0
  8. package/integrations/agy/setup.sh +75 -0
  9. package/integrations/setup-all.sh +1 -1
  10. package/package.json +7 -5
  11. package/src/access-tracker.ts +10 -1
  12. package/src/activity-counter.ts +69 -11
  13. package/src/age-label.ts +29 -0
  14. package/src/audit-log.ts +35 -0
  15. package/src/auto-gc.ts +97 -30
  16. package/src/capture-engine.ts +26 -4
  17. package/src/cli.ts +224 -10
  18. package/src/consolidation-engine.ts +317 -123
  19. package/src/context-composer-stable.ts +5 -1
  20. package/src/data-checkup.ts +17 -3
  21. package/src/dream-pipeline.ts +90 -12
  22. package/src/embedder.ts +44 -5
  23. package/src/env-config.ts +71 -0
  24. package/src/forget-engine.ts +8 -2
  25. package/src/gateway-server.ts +272 -0
  26. package/src/ingest.ts +248 -22
  27. package/src/kg-extractor.ts +17 -0
  28. package/src/llm-client.ts +86 -25
  29. package/src/mcp-server.ts +2 -1
  30. package/src/mcp-tools-advanced.ts +7 -2
  31. package/src/mcp-tools-core.ts +11 -1
  32. package/src/mcp-tools-governance.ts +45 -3
  33. package/src/memory-evolution.ts +16 -0
  34. package/src/memory-output.ts +47 -8
  35. package/src/memory-promotion.ts +280 -0
  36. package/src/memory-store-port.ts +32 -3
  37. package/src/memory-utility.ts +314 -0
  38. package/src/pivot-apply.ts +52 -1
  39. package/src/pivot-evidence.ts +128 -0
  40. package/src/ppr-traversal.ts +25 -1
  41. package/src/recall-ledger.ts +76 -0
  42. package/src/retriever.ts +82 -9
  43. package/src/runtime-config.ts +9 -0
  44. package/src/scope-policy.ts +22 -1
  45. package/src/session-engine.ts +11 -4
  46. package/src/session-output.ts +13 -4
  47. package/src/session-store.ts +2 -3
  48. package/src/skill-promotion.ts +218 -1
  49. package/src/store.ts +231 -71
  50. package/src/synthesis-contract.ts +286 -0
  51. package/src/version-manager.ts +83 -0
  52. package/src/workflow-observation-schema.ts +26 -0
  53. package/integrations/gemini-cli/README.md +0 -57
  54. package/integrations/gemini-cli/setup.sh +0 -64
  55. package/src/__tests__/access-tracker-novelty.test.ts +0 -304
  56. package/src/__tests__/activity-counter.test.ts +0 -125
  57. package/src/__tests__/adaptive-fidelity.test.ts +0 -102
  58. package/src/__tests__/admission-control.test.ts +0 -206
  59. package/src/__tests__/anchor-generator.test.ts +0 -67
  60. package/src/__tests__/api-server-security.test.ts +0 -102
  61. package/src/__tests__/auto-consolidation.test.ts +0 -168
  62. package/src/__tests__/auto-recall.test.ts +0 -131
  63. package/src/__tests__/babel-integration.test.ts +0 -144
  64. package/src/__tests__/batch-dedup.test.ts +0 -65
  65. package/src/__tests__/belief-history.test.ts +0 -220
  66. package/src/__tests__/canary-eval.test.ts +0 -114
  67. package/src/__tests__/capture-engine.test.ts +0 -1328
  68. package/src/__tests__/capture-heuristic.test.ts +0 -171
  69. package/src/__tests__/cascade-forget.test.ts +0 -210
  70. package/src/__tests__/category-min-scores.test.ts +0 -116
  71. package/src/__tests__/cc8-cc1-essential-context.test.ts +0 -298
  72. package/src/__tests__/circuit-breaker.test.ts +0 -99
  73. package/src/__tests__/cluster-consolidation.test.ts +0 -945
  74. package/src/__tests__/confidence-metadata.test.ts +0 -125
  75. package/src/__tests__/confidence-tracker.test.ts +0 -261
  76. package/src/__tests__/conflict-advisor.test.ts +0 -206
  77. package/src/__tests__/conflict-escalation.test.ts +0 -149
  78. package/src/__tests__/conflict-lifecycle.test.ts +0 -83
  79. package/src/__tests__/conflict-output.test.ts +0 -85
  80. package/src/__tests__/conflict-store.test.ts +0 -418
  81. package/src/__tests__/connector-v1.test.ts +0 -181
  82. package/src/__tests__/consolidation-engine.test.ts +0 -430
  83. package/src/__tests__/constructive-retrieval.test.ts +0 -509
  84. package/src/__tests__/context-collapse-renderer.test.ts +0 -214
  85. package/src/__tests__/context-composer-pins.test.ts +0 -64
  86. package/src/__tests__/context-composer-task-selection.test.ts +0 -24
  87. package/src/__tests__/context-reconstructor.test.ts +0 -65
  88. package/src/__tests__/context-renderer.test.ts +0 -91
  89. package/src/__tests__/continuity-eval.test.ts +0 -275
  90. package/src/__tests__/continuity-schema.test.ts +0 -97
  91. package/src/__tests__/contracts.test.ts +0 -262
  92. package/src/__tests__/conversation-importer.test.ts +0 -692
  93. package/src/__tests__/core-recall-eval.test.ts +0 -235
  94. package/src/__tests__/core-summary.test.ts +0 -109
  95. package/src/__tests__/data-checkup.test.ts +0 -276
  96. package/src/__tests__/decay-exemption.test.ts +0 -129
  97. package/src/__tests__/dedup-actions.test.ts +0 -58
  98. package/src/__tests__/dedup-guard.test.ts +0 -39
  99. package/src/__tests__/deterministic-id.test.ts +0 -39
  100. package/src/__tests__/distill-lock.test.ts +0 -305
  101. package/src/__tests__/distill-session-argshape.test.ts +0 -79
  102. package/src/__tests__/doctor.test.ts +0 -319
  103. package/src/__tests__/dream-pipeline.test.ts +0 -780
  104. package/src/__tests__/drill-down.test.ts +0 -108
  105. package/src/__tests__/embedder.test.ts +0 -122
  106. package/src/__tests__/emotion-decay.test.ts +0 -46
  107. package/src/__tests__/emotion-detector.test.ts +0 -56
  108. package/src/__tests__/emotion-phase1-integration.test.ts +0 -153
  109. package/src/__tests__/emotion-retrieval.test.ts +0 -56
  110. package/src/__tests__/entity-resolver.test.ts +0 -58
  111. package/src/__tests__/env-config.test.ts +0 -151
  112. package/src/__tests__/error-signature-boost.test.ts +0 -87
  113. package/src/__tests__/error-signature.test.ts +0 -95
  114. package/src/__tests__/error-taxonomy.test.ts +0 -129
  115. package/src/__tests__/ethics-layer.test.ts +0 -476
  116. package/src/__tests__/event-segmenter.test.ts +0 -153
  117. package/src/__tests__/feature-flags-integration.test.ts +0 -54
  118. package/src/__tests__/frequency-tracker.test.ts +0 -113
  119. package/src/__tests__/freshness.test.ts +0 -186
  120. package/src/__tests__/graph-export.test.ts +0 -489
  121. package/src/__tests__/hotness-blend.test.ts +0 -283
  122. package/src/__tests__/ingest-chunking.test.ts +0 -44
  123. package/src/__tests__/ingest.test.ts +0 -360
  124. package/src/__tests__/interference-detector.test.ts +0 -203
  125. package/src/__tests__/kg-extractor.test.ts +0 -192
  126. package/src/__tests__/kg-store.test.ts +0 -300
  127. package/src/__tests__/llm-client-pivot.test.ts +0 -628
  128. package/src/__tests__/llm-consolidation.test.ts +0 -226
  129. package/src/__tests__/maintenance-locks.test.ts +0 -189
  130. package/src/__tests__/mcp-efficiency.test.ts +0 -288
  131. package/src/__tests__/mcp-related-scopes.test.ts +0 -151
  132. package/src/__tests__/memory-boundaries.test.ts +0 -282
  133. package/src/__tests__/memory-evolution-b2-b3-e1.test.ts +0 -345
  134. package/src/__tests__/memory-evolution.test.ts +0 -271
  135. package/src/__tests__/memory-health-rebalance.test.ts +0 -144
  136. package/src/__tests__/memory-lint.test.ts +0 -421
  137. package/src/__tests__/memory-output.test.ts +0 -215
  138. package/src/__tests__/memory-promotion.test.ts +0 -315
  139. package/src/__tests__/migrate-dedup-ids.test.ts +0 -65
  140. package/src/__tests__/multi-vector.test.ts +0 -242
  141. package/src/__tests__/narrative-architecture.test.ts +0 -456
  142. package/src/__tests__/noise-filter.test.ts +0 -205
  143. package/src/__tests__/noise-prototype-bank.test.ts +0 -280
  144. package/src/__tests__/obsidian-connector.test.ts +0 -363
  145. package/src/__tests__/omitted-reporting.test.ts +0 -98
  146. package/src/__tests__/pending-review.test.ts +0 -77
  147. package/src/__tests__/pii-redact.test.ts +0 -333
  148. package/src/__tests__/pivot-apply.test.ts +0 -373
  149. package/src/__tests__/pivot-distill-supervisor.test.ts +0 -457
  150. package/src/__tests__/pivot-distill.test.ts +0 -1178
  151. package/src/__tests__/post-retrieval-filter.test.ts +0 -178
  152. package/src/__tests__/ppr-traversal.test.ts +0 -256
  153. package/src/__tests__/prediction-engine.test.ts +0 -349
  154. package/src/__tests__/predictive-prospective-memory.test.ts +0 -416
  155. package/src/__tests__/preference-guard-smoke.test.ts +0 -211
  156. package/src/__tests__/preference-matcher.test.ts +0 -282
  157. package/src/__tests__/preference-slots.test.ts +0 -205
  158. package/src/__tests__/prospective-memory.test.ts +0 -283
  159. package/src/__tests__/pull-from-macbook-sync-only.test.ts +0 -679
  160. package/src/__tests__/query-entity-detector.test.ts +0 -171
  161. package/src/__tests__/query-expander-alias.test.ts +0 -146
  162. package/src/__tests__/query-expander.test.ts +0 -34
  163. package/src/__tests__/recall-gate.test.ts +0 -266
  164. package/src/__tests__/recall-governor.test.ts +0 -227
  165. package/src/__tests__/recall-mode.test.ts +0 -64
  166. package/src/__tests__/resolve-db-path.test.ts +0 -130
  167. package/src/__tests__/resolve-tier.test.ts +0 -64
  168. package/src/__tests__/result-synthesizer.test.ts +0 -198
  169. package/src/__tests__/resume-context.test.ts +0 -4898
  170. package/src/__tests__/retrieval-eval.test.ts +0 -163
  171. package/src/__tests__/retrieval-trace.test.ts +0 -213
  172. package/src/__tests__/retriever-boundary-weight.test.ts +0 -136
  173. package/src/__tests__/retriever-lazy-init-dispatch.test.ts +0 -123
  174. package/src/__tests__/retroactive-boost.test.ts +0 -223
  175. package/src/__tests__/salience-scoring.test.ts +0 -106
  176. package/src/__tests__/scope-inventory.test.ts +0 -200
  177. package/src/__tests__/scope-policy.test.ts +0 -69
  178. package/src/__tests__/scope-suggester.test.ts +0 -80
  179. package/src/__tests__/session-checkpoint.test.ts +0 -291
  180. package/src/__tests__/session-distiller.test.ts +0 -640
  181. package/src/__tests__/session-gc.test.ts +0 -215
  182. package/src/__tests__/skill-engine.test.ts +0 -552
  183. package/src/__tests__/skill-promotion.test.ts +0 -654
  184. package/src/__tests__/skill-verifier.test.ts +0 -122
  185. package/src/__tests__/source-heartbeat.test.ts +0 -250
  186. package/src/__tests__/stable-context-length-contract.test.ts +0 -62
  187. package/src/__tests__/store-patch-metadata.test.ts +0 -205
  188. package/src/__tests__/store-read-consistency.test.ts +0 -122
  189. package/src/__tests__/store-schema-migration.test.ts +0 -87
  190. package/src/__tests__/store-scope-audit.test.ts +0 -81
  191. package/src/__tests__/store-upsert.test.ts +0 -201
  192. package/src/__tests__/supersede-chain.test.ts +0 -154
  193. package/src/__tests__/temporal-parser.test.ts +0 -241
  194. package/src/__tests__/temporal-validity.test.ts +0 -160
  195. package/src/__tests__/term-registry-terminal-roster.test.ts +0 -127
  196. package/src/__tests__/term-registry.test.ts +0 -121
  197. package/src/__tests__/tool-error-surfacing.test.ts +0 -98
  198. package/src/__tests__/tool-output-compressor.test.ts +0 -160
  199. package/src/__tests__/topic-tag.test.ts +0 -113
  200. package/src/__tests__/trusted-memory.test.ts +0 -839
  201. package/src/__tests__/ui-server-security.test.ts +0 -93
  202. package/src/__tests__/usage-tracker.test.ts +0 -287
  203. package/src/__tests__/version-manager.test.ts +0 -213
  204. package/src/__tests__/workflow-observation-skill-outcome.test.ts +0 -352
  205. package/src/__tests__/workflow-observation.test.ts +0 -433
  206. package/src/__tests__/write-verifier.test.ts +0 -122
  207. /package/integrations/{gemini-cli/gemini-md-snippet.md → agy/agy-md-snippet.md} +0 -0
@@ -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,189 +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
- list: async () => [],
52
- listPage: async () => [],
53
- update: async () => null,
54
- patchMetadata: async () => null,
55
- };
56
-
57
- const result = await runDream({
58
- store: store as any,
59
- llm: null,
60
- embedder: { embedPassage: async () => [0, 0, 0] },
61
- scope,
62
- force: true,
63
- activityStatsPath: DREAM_STATS,
64
- });
65
-
66
- expect(result.ran).toBe(false);
67
- expect(result.reason).toBe("locked_by_another_process");
68
- expect(bodyRan).toBe(false); // runDreamInner never entered
69
- });
70
-
71
- it("skips its consolidation phase when the scope's consolidate lock is held", async () => {
72
- const scope = "project:dream-consolidate-test";
73
- holdLock(`consolidate-${scope}`); // simulate a standalone consolidate_memories running
74
- // 2026-08-12:预置写计数,用于在末尾断言「锁被占 = 没真正处理 = 计数必须留着」。
75
- incrementWriteCount(scope, 15, { statsPath: DREAM_STATS });
76
-
77
- const activeMeta = JSON.stringify({
78
- evolution: { status: "active", version: 1, accessCount: 0, lastAccessedAt: null, validFrom: Date.now(), validUntil: null },
79
- });
80
- const entries = [1, 2, 3].map((i) => ({
81
- id: `dc-e${i}`, text: `t${i}`, vector: [1, 0, 0], category: "events", scope,
82
- importance: 0.5, timestamp: Date.now(), metadata: activeMeta, language: "en", fts_text: `t${i}`,
83
- }));
84
- const store = {
85
- stats: async () => ({ totalCount: 100, scopeCounts: {}, categoryCounts: {} }),
86
- list: async () => entries,
87
- listPage: async () => [],
88
- update: async () => null,
89
- patchMetadata: async () => null,
90
- getById: async () => null,
91
- vectorSearch: async () => [],
92
- };
93
-
94
- const result = await runDream({
95
- store: store as any,
96
- llm: null,
97
- embedder: { embedPassage: async () => [0, 0, 0] },
98
- scope,
99
- force: true,
100
- activityStatsPath: DREAM_STATS,
101
- });
102
-
103
- // Dream itself ran (its own dream lock was free), but the consolidation phase saw the
104
- // held consolidate lock and skipped rather than running concurrently.
105
- expect(result.ran).toBe(true);
106
- const consolidatePhase = result.phases.find((p) => p.phase === "consolidate");
107
- expect(consolidatePhase?.detail).toContain("skipped");
108
-
109
- // 2026-08-12 防「修过头」:末尾的 reset 必须是 `if (consolidateOutcome.ran)` 条件式。
110
- // 锁被占时这个 scope 并没有被真正处理完,若无条件清计数,它会被当成「已处理」而
111
- // 丢掉本轮积累的写入,下次要重新攒够阈值才轮得到 —— 是比原 bug 更隐蔽的数据损失。
112
- // 注意本条不是必红测试:修复前的无参 resetWriteCount() 什么也不清,同样是绿。
113
- // 它守的是修复的形状,不是修复的存在(存在性由 dream-pipeline.test.ts 那条守)。
114
- expect(getWriteCount(scope, { statsPath: DREAM_STATS })).toBe(15);
115
- });
116
-
117
- it("resets the scope's write counter after a run (no perpetual self-triggering)", async () => {
118
- const scope = "project:dream-reset-test";
119
- const statsPath = join(mkdtempSync(join(tmpdir(), "rn-reset-")), "activity-stats.json");
120
- // Pre-load above threshold, standing in for accumulated writes (incl. any dream self-writes).
121
- incrementWriteCount(scope, 15, { statsPath });
122
- expect(getWriteCount(scope, { statsPath })).toBe(15);
123
-
124
- const store = {
125
- stats: async () => ({ totalCount: 5, scopeCounts: {}, categoryCounts: {} }),
126
- // ⚠️ 2026-08-12 标注:这里 list 返回空数组,走的是 **completed_early 早退路径**,
127
- // 而早退路径 (dream-pipeline.ts:226) 的 resetWriteCount(scope, statsCfg) 一直是对的。
128
- // 本条测试因此从未覆盖「完整跑完」那条路径 —— 而 bug 恰恰在那条路径上(:301 漏传 scope)。
129
- // 测试名 "resets the scope's write counter after a run" 读起来像覆盖了 reset 全部行为,
130
- // 实际只覆盖了两条路径中正确的那一条,于是 bug 在有测试的情况下活了 41 天。
131
- // 完整路径的覆盖已补在 dream-pipeline.test.ts「清空已处理 scope 的写计数」一条。
132
- list: async () => [], // no active entries → completed_early path (still resets)
133
- listPage: async () => [],
134
- update: async () => null,
135
- patchMetadata: async () => null,
136
- getById: async () => null,
137
- vectorSearch: async () => [],
138
- };
139
- const result = await runDream({
140
- store: store as any,
141
- llm: null,
142
- embedder: { embedPassage: async () => [0, 0, 0] },
143
- scope,
144
- force: true,
145
- activityStatsPath: statsPath,
146
- });
147
-
148
- expect(result.ran).toBe(true);
149
- // Reset at dream's end clears the counter, so dream won't immediately self-retrigger —
150
- // fresh external writes must accumulate past the threshold again.
151
- expect(getWriteCount(scope, { statsPath })).toBe(0);
152
- });
153
- });
154
-
155
- describe("maybeRunGc cross-process lock + throttle", () => {
156
- function makeStore(totalCount: number) {
157
- return {
158
- stats: async () => ({ totalCount, scopeCounts: {}, categoryCounts: {} }),
159
- listPage: async () => [] as unknown[],
160
- update: async () => null,
161
- list: async () => [],
162
- } as any;
163
- }
164
-
165
- it("skips (locked) when another process holds the gc run lock", async () => {
166
- resetGcTimestamp();
167
- holdLock("gc-run");
168
- const config: AutoGcConfig = { ...DEFAULT_AUTO_GC_CONFIG, minMemoryCount: 1, minHoursSinceLastGc: 24 };
169
- const result = await maybeRunGc(makeStore(10), config);
170
- expect(result.triggered).toBe(false);
171
- expect(result.reason).toBe("locked_by_another_process");
172
- });
173
-
174
- it("throttles a second run within the window, then runs again after reset", async () => {
175
- resetGcTimestamp();
176
- const config: AutoGcConfig = { ...DEFAULT_AUTO_GC_CONFIG, minMemoryCount: 1, minHoursSinceLastGc: 24 };
177
-
178
- const first = await maybeRunGc(makeStore(10), config);
179
- expect(first.triggered).toBe(true);
180
-
181
- const second = await maybeRunGc(makeStore(10), config);
182
- expect(second.triggered).toBe(false);
183
- expect(second.reason).toBe("too_soon");
184
-
185
- resetGcTimestamp();
186
- const third = await maybeRunGc(makeStore(10), config);
187
- expect(third.triggered).toBe(true);
188
- });
189
- });