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,125 +0,0 @@
1
- /**
2
- * F1: Memory Confidence Meta-tags — tests for structured confidence,
3
- * source-based assignment, retrieval integration, and backward compat.
4
- */
5
-
6
- import { describe, expect, test } from "bun:test";
7
- import {
8
- assignDefaultConfidence,
9
- getConfidence,
10
- getConfidenceMetadata,
11
- CONFIDENCE_DEFAULT,
12
- type ConfidenceMetadata,
13
- } from "../confidence-tracker.js";
14
- import type { MemoryEntry } from "../store.js";
15
-
16
- // ---------------------------------------------------------------------------
17
- // Helper
18
- // ---------------------------------------------------------------------------
19
-
20
- function makeEntry(metadataObj: Record<string, unknown>): MemoryEntry {
21
- return {
22
- id: "test-001",
23
- text: "test",
24
- vector: [],
25
- category: "events",
26
- scope: "test",
27
- importance: 0.7,
28
- timestamp: Date.now(),
29
- metadata: JSON.stringify(metadataObj),
30
- };
31
- }
32
-
33
- // ---------------------------------------------------------------------------
34
- // assignDefaultConfidence
35
- // ---------------------------------------------------------------------------
36
-
37
- describe("F1: assignDefaultConfidence", () => {
38
- test("manual source → direct reliability, score 0.9", () => {
39
- const c = assignDefaultConfidence("manual");
40
- expect(c.score).toBe(0.9);
41
- expect(c.reliability).toBe("direct");
42
- });
43
-
44
- test("agent source → inferred reliability, score 0.7", () => {
45
- const c = assignDefaultConfidence("agent");
46
- expect(c.score).toBe(0.7);
47
- expect(c.reliability).toBe("inferred");
48
- });
49
-
50
- test("conversation_import source → hearsay, score 0.5", () => {
51
- const c = assignDefaultConfidence("conversation_import");
52
- expect(c.score).toBe(0.5);
53
- expect(c.reliability).toBe("hearsay");
54
- });
55
-
56
- test("session_distill source → inferred, score 0.6", () => {
57
- const c = assignDefaultConfidence("session_distill");
58
- expect(c.score).toBe(0.6);
59
- expect(c.reliability).toBe("inferred");
60
- });
61
-
62
- test("explicit override takes precedence", () => {
63
- const c = assignDefaultConfidence("agent", { score: 0.95, reliability: "direct" });
64
- expect(c.score).toBe(0.95);
65
- expect(c.reliability).toBe("direct");
66
- });
67
-
68
- test("explicit score only, reliability defaults to inferred", () => {
69
- const c = assignDefaultConfidence("manual", { score: 0.3 });
70
- expect(c.score).toBe(0.3);
71
- expect(c.reliability).toBe("inferred");
72
- });
73
- });
74
-
75
- // ---------------------------------------------------------------------------
76
- // getConfidence — backward compat
77
- // ---------------------------------------------------------------------------
78
-
79
- describe("F1: getConfidence backward compatibility", () => {
80
- test("reads flat number confidence (legacy format)", () => {
81
- const entry = makeEntry({ confidence: 0.42 });
82
- expect(getConfidence(entry)).toBe(0.42);
83
- });
84
-
85
- test("reads structured confidence object", () => {
86
- const entry = makeEntry({ confidence: { score: 0.88, reliability: "direct" } });
87
- expect(getConfidence(entry)).toBe(0.88);
88
- });
89
-
90
- test("returns default when confidence missing", () => {
91
- const entry = makeEntry({});
92
- expect(getConfidence(entry)).toBe(CONFIDENCE_DEFAULT);
93
- });
94
- });
95
-
96
- // ---------------------------------------------------------------------------
97
- // getConfidenceMetadata
98
- // ---------------------------------------------------------------------------
99
-
100
- describe("F1: getConfidenceMetadata", () => {
101
- test("extracts structured ConfidenceMetadata", () => {
102
- const entry = makeEntry({
103
- confidence: { score: 0.75, reliability: "hearsay", verifiedAt: 1000, verifiedBy: "user" },
104
- });
105
- const meta = getConfidenceMetadata(entry);
106
- expect(meta).not.toBeNull();
107
- expect(meta!.score).toBe(0.75);
108
- expect(meta!.reliability).toBe("hearsay");
109
- expect(meta!.verifiedAt).toBe(1000);
110
- expect(meta!.verifiedBy).toBe("user");
111
- });
112
-
113
- test("wraps legacy flat number into ConfidenceMetadata", () => {
114
- const entry = makeEntry({ confidence: 0.55 });
115
- const meta = getConfidenceMetadata(entry);
116
- expect(meta).not.toBeNull();
117
- expect(meta!.score).toBe(0.55);
118
- expect(meta!.reliability).toBe("inferred");
119
- });
120
-
121
- test("returns null when confidence missing", () => {
122
- const entry = makeEntry({});
123
- expect(getConfidenceMetadata(entry)).toBeNull();
124
- });
125
- });
@@ -1,261 +0,0 @@
1
- import { describe, expect, it } from "bun:test";
2
-
3
- import {
4
- confirmMemory,
5
- correctMemory,
6
- contradictMemory,
7
- buildConfirmPatch,
8
- buildCorrectPatch,
9
- buildContradictPatch,
10
- getConfidence,
11
- applyConfidenceWeight,
12
- CONFIDENCE_DEFAULT,
13
- CONFIDENCE_CONFIRMED,
14
- CONFIDENCE_CORRECTED,
15
- CONFIDENCE_CONTRADICTED,
16
- } from "../confidence-tracker.js";
17
- import type { MemoryEntry } from "../store.js";
18
-
19
- // ---------------------------------------------------------------------------
20
- // Helpers
21
- // ---------------------------------------------------------------------------
22
-
23
- function makeEntry(id: string, text: string, overrides: Partial<MemoryEntry> = {}): MemoryEntry {
24
- return {
25
- id,
26
- text,
27
- vector: [1, 0, 0],
28
- category: "events",
29
- scope: "project:test",
30
- importance: 0.7,
31
- timestamp: Date.now(),
32
- metadata: "{}",
33
- ...overrides,
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
- // 模拟 store.patchMetadata 单写通道:读最新 metadata → patchFn → 写回。
42
- return {
43
- updates,
44
- data,
45
- async patchMetadata(
46
- id: string,
47
- patchFn: (meta: Record<string, unknown>, entry: MemoryEntry) => Record<string, unknown>,
48
- _scopeFilter?: string[],
49
- ) {
50
- const entry = data.get(id);
51
- if (!entry) return null;
52
- let meta: Record<string, unknown>;
53
- try {
54
- const parsed: unknown = JSON.parse(entry.metadata || "{}");
55
- meta = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
56
- ? (parsed as Record<string, unknown>)
57
- : {};
58
- } catch {
59
- meta = {};
60
- }
61
- const patched = patchFn(meta, entry);
62
- entry.metadata = JSON.stringify(patched);
63
- updates.push({ id, metadata: entry.metadata });
64
- return entry;
65
- },
66
- } as any;
67
- }
68
-
69
- // ---------------------------------------------------------------------------
70
- // Tests
71
- // ---------------------------------------------------------------------------
72
-
73
- describe("confidence-tracker", () => {
74
- describe("getConfidence", () => {
75
- it("returns default for entries without confidence", () => {
76
- const entry = makeEntry("e1", "test");
77
- expect(getConfidence(entry)).toBe(CONFIDENCE_DEFAULT);
78
- });
79
-
80
- it("returns stored confidence", () => {
81
- const entry = makeEntry("e1", "test", {
82
- metadata: JSON.stringify({ confidence: 0.9 }),
83
- });
84
- expect(getConfidence(entry)).toBe(0.9);
85
- });
86
-
87
- it("returns default for malformed metadata", () => {
88
- const entry = makeEntry("e1", "test", { metadata: "not-json" });
89
- expect(getConfidence(entry)).toBe(CONFIDENCE_DEFAULT);
90
- });
91
- });
92
-
93
- describe("confirmMemory", () => {
94
- it("sets confidence to 1.0", async () => {
95
- const entry = makeEntry("e1", "user likes TypeScript");
96
- const store = createMockStore([entry]);
97
-
98
- const result = await confirmMemory(store, "e1", "project:test");
99
- expect(result).not.toBeNull();
100
- expect(result!.newConfidence).toBe(CONFIDENCE_CONFIRMED);
101
- expect(result!.oldConfidence).toBe(CONFIDENCE_DEFAULT);
102
-
103
- const meta = JSON.parse(store.data.get("e1")!.metadata!);
104
- expect(meta.confidence).toBe(1.0);
105
- expect(meta.confidence_history).toHaveLength(1);
106
- expect(meta.confidence_history[0].action).toBe("confirmed");
107
- });
108
-
109
- it("returns null for missing entry", async () => {
110
- const store = createMockStore([]);
111
- const result = await confirmMemory(store, "missing", "project:test");
112
- expect(result).toBeNull();
113
- });
114
- });
115
-
116
- describe("correctMemory", () => {
117
- it("drops confidence to 0.3", async () => {
118
- const entry = makeEntry("e1", "user uses Python");
119
- const store = createMockStore([entry]);
120
-
121
- const result = await correctMemory(store, "e1", "project:test", "new-entry-id");
122
- expect(result).not.toBeNull();
123
- expect(result!.newConfidence).toBe(CONFIDENCE_CORRECTED);
124
-
125
- const meta = JSON.parse(store.data.get("e1")!.metadata!);
126
- expect(meta.confidence).toBe(0.3);
127
- expect(meta.corrected_by).toBe("new-entry-id");
128
- expect(meta.confidence_history[0].correctedBy).toBe("new-entr"); // 8 chars
129
- });
130
-
131
- it("works without correctedById", async () => {
132
- const entry = makeEntry("e1", "old info");
133
- const store = createMockStore([entry]);
134
-
135
- const result = await correctMemory(store, "e1", "project:test");
136
- expect(result!.newConfidence).toBe(CONFIDENCE_CORRECTED);
137
-
138
- const meta = JSON.parse(store.data.get("e1")!.metadata!);
139
- expect(meta.corrected_by).toBeUndefined();
140
- });
141
- });
142
-
143
- describe("contradictMemory", () => {
144
- it("drops confidence to 0.0", async () => {
145
- const entry = makeEntry("e1", "wrong fact");
146
- const store = createMockStore([entry]);
147
-
148
- const result = await contradictMemory(store, "e1", "project:test");
149
- expect(result).not.toBeNull();
150
- expect(result!.newConfidence).toBe(CONFIDENCE_CONTRADICTED);
151
-
152
- const meta = JSON.parse(store.data.get("e1")!.metadata!);
153
- expect(meta.confidence).toBe(0.0);
154
- });
155
- });
156
-
157
- describe("applyConfidenceWeight", () => {
158
- it("no penalty at confidence=1.0", () => {
159
- const entry = makeEntry("e1", "test", {
160
- metadata: JSON.stringify({ confidence: 1.0 }),
161
- });
162
- expect(applyConfidenceWeight(1.0, entry)).toBe(1.0);
163
- });
164
-
165
- it("slight penalty at default confidence=0.7", () => {
166
- const entry = makeEntry("e1", "test");
167
- const weighted = applyConfidenceWeight(1.0, entry);
168
- expect(weighted).toBeCloseTo(0.85, 2);
169
- });
170
-
171
- it("significant penalty at corrected confidence=0.3", () => {
172
- const entry = makeEntry("e1", "test", {
173
- metadata: JSON.stringify({ confidence: 0.3 }),
174
- });
175
- const weighted = applyConfidenceWeight(1.0, entry);
176
- expect(weighted).toBeCloseTo(0.65, 2);
177
- });
178
-
179
- it("heavy penalty at contradicted confidence=0.0", () => {
180
- const entry = makeEntry("e1", "test", {
181
- metadata: JSON.stringify({ confidence: 0.0 }),
182
- });
183
- const weighted = applyConfidenceWeight(1.0, entry);
184
- expect(weighted).toBe(0.5);
185
- });
186
-
187
- it("scales with input score", () => {
188
- const entry = makeEntry("e1", "test", {
189
- metadata: JSON.stringify({ confidence: 0.3 }),
190
- });
191
- const weighted = applyConfidenceWeight(0.8, entry);
192
- expect(weighted).toBeCloseTo(0.8 * 0.65, 2);
193
- });
194
- });
195
-
196
- describe("patch builders (store-agnostic)", () => {
197
- it("buildConfirmPatch returns metadata patch without touching store", () => {
198
- const entry = makeEntry("e1", "test fact");
199
- const patch = buildConfirmPatch(entry);
200
- expect(patch).not.toBeNull();
201
- expect(patch!.metadata.confidence).toBe(CONFIDENCE_CONFIRMED);
202
- expect(patch!.update.entryId).toBe("e1");
203
- expect(patch!.update.newConfidence).toBe(CONFIDENCE_CONFIRMED);
204
- // Original entry metadata should NOT be mutated
205
- expect(JSON.parse(entry.metadata!).confidence).toBeUndefined();
206
- });
207
-
208
- it("buildCorrectPatch includes correctedBy in history", () => {
209
- const entry = makeEntry("e1", "old info");
210
- const patch = buildCorrectPatch(entry, "new-id-123");
211
- expect(patch).not.toBeNull();
212
- expect(patch!.metadata.confidence).toBe(CONFIDENCE_CORRECTED);
213
- expect(patch!.metadata.corrected_by).toBe("new-id-123");
214
- const history = patch!.metadata.confidence_history as Array<{ correctedBy?: string }>;
215
- expect(history[0].correctedBy).toBe("new-id-1"); // 8 chars
216
- });
217
-
218
- it("buildContradictPatch returns zero confidence", () => {
219
- const entry = makeEntry("e1", "wrong");
220
- const patch = buildContradictPatch(entry);
221
- expect(patch!.metadata.confidence).toBe(CONFIDENCE_CONTRADICTED);
222
- });
223
-
224
- it("all patch builders return null for null entry", () => {
225
- expect(buildConfirmPatch(null)).toBeNull();
226
- expect(buildCorrectPatch(null)).toBeNull();
227
- expect(buildContradictPatch(null)).toBeNull();
228
- });
229
-
230
- it("caps confidence history at 20 entries", () => {
231
- const longHistory = Array.from({ length: 25 }, (_, i) => ({
232
- action: "confirmed",
233
- from: 0.5,
234
- to: 1.0,
235
- date: `2026-01-${String(i + 1).padStart(2, "0")}`,
236
- }));
237
- const entry = makeEntry("e1", "test", {
238
- metadata: JSON.stringify({ confidence: 0.5, confidence_history: longHistory }),
239
- });
240
- const patch = buildConfirmPatch(entry);
241
- const history = patch!.metadata.confidence_history as unknown[];
242
- expect(history.length).toBeLessThanOrEqual(20);
243
- });
244
- });
245
-
246
- describe("confidence history", () => {
247
- it("accumulates multiple changes", async () => {
248
- const entry = makeEntry("e1", "evolving fact");
249
- const store = createMockStore([entry]);
250
-
251
- await correctMemory(store, "e1", "project:test");
252
- await confirmMemory(store, "e1", "project:test");
253
-
254
- const meta = JSON.parse(store.data.get("e1")!.metadata!);
255
- expect(meta.confidence_history).toHaveLength(2);
256
- expect(meta.confidence_history[0].action).toBe("corrected");
257
- expect(meta.confidence_history[1].action).toBe("confirmed");
258
- expect(meta.confidence).toBe(CONFIDENCE_CONFIRMED);
259
- });
260
- });
261
- });
@@ -1,206 +0,0 @@
1
- import { describe, expect, it } from "bun:test";
2
-
3
- import { buildConflictCandidateRecord } from "../conflict-engine.js";
4
- import { buildConflictAuditSummary, clusterConflicts, summarizeConflictAdvice } from "../conflict-advisor.js";
5
-
6
- /** Returns an ISO timestamp N days before now (defaults to 4 days = firmly "stale"). */
7
- function daysAgo(n: number): string {
8
- return new Date(Date.now() - n * 24 * 60 * 60 * 1000).toISOString();
9
- }
10
-
11
- function createConflictRecord(overrides: Record<string, unknown> = {}) {
12
- const defaultTs = daysAgo(4); // 4 days ago → "stale" (3-6 days range)
13
- return {
14
- ...buildConflictCandidateRecord({
15
- canonicalKey: "user-reply-style",
16
- category: "preferences",
17
- fingerprint: "user-reply-style--durable-1--source-1--new-text",
18
- reason: "promotion_conflicts_with_existing_durable",
19
- existing: {
20
- memoryId: "durable-1",
21
- text: "User prefers concise, direct, technical replies.",
22
- category: "preferences",
23
- scope: "memory:agent",
24
- importance: 0.84,
25
- metadata: "{\"source\":\"agent\"}",
26
- canonicalKey: "user-reply-style",
27
- },
28
- incoming: {
29
- text: "User prefers concise direct technical replies.",
30
- category: "preferences",
31
- scope: "memory:agent",
32
- importance: 0.78,
33
- metadata: "{\"source\":\"agent\"}",
34
- source: "agent",
35
- sourceMemoryId: "source-1",
36
- sourceCategory: "events",
37
- },
38
- createdAt: defaultTs,
39
- updatedAt: defaultTs,
40
- }),
41
- ...overrides,
42
- };
43
- }
44
-
45
- describe("summarizeConflictAdvice", () => {
46
- it("suggests keep_existing for text-equivalent conflicts", () => {
47
- const advice = summarizeConflictAdvice(createConflictRecord() as any);
48
-
49
- expect(advice.suggestedResolution).toBe("keep_existing");
50
- expect(advice.confidence).toBe("high");
51
- expect(advice.similarity).toBe(1);
52
- });
53
-
54
- it("suggests keep_existing for cross-category canonical key conflicts", () => {
55
- const advice = summarizeConflictAdvice(createConflictRecord({
56
- reason: "canonical_key_conflicts_with_existing_durable",
57
- category: "events",
58
- incoming: {
59
- text: "Reply-style observation imported as an event.",
60
- category: "events",
61
- scope: "memory:agent",
62
- importance: 0.78,
63
- metadata: "{\"source\":\"agent\"}",
64
- source: "agent",
65
- sourceMemoryId: "source-2",
66
- sourceCategory: "events",
67
- },
68
- }) as any);
69
-
70
- expect(advice.suggestedResolution).toBe("keep_existing");
71
- expect(["medium", "high"]).toContain(advice.confidence);
72
- expect(advice.reasons.some((reason) => reason.includes("canonical key"))).toBe(true);
73
- });
74
-
75
- it("suggests accept_incoming when the incoming text is a tighter rewrite of the same memory", () => {
76
- const advice = summarizeConflictAdvice(createConflictRecord({
77
- existing: {
78
- memoryId: "durable-1",
79
- text: "User prefers concise grounded technical replies and avoids sales language in the final copy.",
80
- category: "preferences",
81
- scope: "memory:agent",
82
- importance: 0.84,
83
- metadata: "{\"source\":\"agent\"}",
84
- canonicalKey: "user-reply-style",
85
- },
86
- incoming: {
87
- text: "User prefers concise grounded technical replies and avoids sales language.",
88
- category: "preferences",
89
- scope: "memory:agent",
90
- importance: 0.78,
91
- metadata: "{\"source\":\"agent\"}",
92
- source: "agent",
93
- sourceMemoryId: "source-1",
94
- sourceCategory: "events",
95
- },
96
- }) as any);
97
-
98
- expect(advice.suggestedResolution).toBe("accept_incoming");
99
- expect(advice.confidence).toBe("medium");
100
- expect(advice.similarity).toBeGreaterThanOrEqual(0.72);
101
- expect(advice.mergeSuggestion).toBeUndefined();
102
- });
103
-
104
- it("offers a merged wording suggestion for same-category manual_review conflicts", () => {
105
- const advice = summarizeConflictAdvice(createConflictRecord({
106
- existing: {
107
- memoryId: "durable-1",
108
- text: "User prefers concise grounded technical replies; avoid sales language.",
109
- category: "preferences",
110
- scope: "memory:agent",
111
- importance: 0.84,
112
- metadata: "{\"source\":\"agent\"}",
113
- canonicalKey: "user-reply-style",
114
- },
115
- incoming: {
116
- text: "User prefers concise grounded technical replies; keep the tone colloquial.",
117
- category: "preferences",
118
- scope: "memory:agent",
119
- importance: 0.78,
120
- metadata: "{\"source\":\"agent\"}",
121
- source: "agent",
122
- sourceMemoryId: "source-1",
123
- sourceCategory: "events",
124
- },
125
- }) as any);
126
-
127
- expect(advice.suggestedResolution).toBe("manual_review");
128
- expect(advice.mergeSuggestion).toContain("User prefers concise grounded technical replies");
129
- expect(advice.mergeSuggestion).toContain("avoid sales language");
130
- expect(advice.mergeSuggestion).toContain("keep the tone colloquial");
131
- expect(advice.reasons.some((reason) => reason.includes("merged durable wording"))).toBe(true);
132
- });
133
- });
134
-
135
- describe("clusterConflicts", () => {
136
- it("groups conflicts by canonical key, reason, and category", () => {
137
- const clusters = clusterConflicts([
138
- createConflictRecord({
139
- conflictId: "00000000-0000-0000-0000-000000000001",
140
- createdAt: daysAgo(4),
141
- updatedAt: daysAgo(4),
142
- }) as any,
143
- createConflictRecord({
144
- conflictId: "00000000-0000-0000-0000-000000000002",
145
- createdAt: daysAgo(4),
146
- updatedAt: daysAgo(3),
147
- }) as any,
148
- createConflictRecord({
149
- canonicalKey: "project-entity-owner",
150
- conflictId: "00000000-0000-0000-0000-000000000003",
151
- fingerprint: "project-entity-owner--durable-1--source-1--new-text",
152
- }) as any,
153
- ]);
154
-
155
- expect(clusters).toHaveLength(2);
156
- expect(clusters[0]?.canonicalKey).toBe("user-reply-style");
157
- expect(clusters[0]?.totalCount).toBe(2);
158
- expect(clusters[0]?.latestConflictId).toBe("00000000-0000-0000-0000-000000000002");
159
- expect(clusters[0]?.attention).toBe("stale");
160
- });
161
- });
162
-
163
- describe("buildConflictAuditSummary", () => {
164
- it("highlights escalated or stale open clusters first", () => {
165
- const summary = buildConflictAuditSummary([
166
- createConflictRecord({
167
- conflictId: "00000000-0000-0000-0000-000000000001",
168
- createdAt: daysAgo(14),
169
- updatedAt: daysAgo(14),
170
- }) as any,
171
- createConflictRecord({
172
- canonicalKey: "project-entity-owner",
173
- conflictId: "00000000-0000-0000-0000-000000000002",
174
- fingerprint: "project-entity-owner--durable-1--source-1--new-text",
175
- createdAt: daysAgo(1),
176
- updatedAt: daysAgo(1),
177
- }) as any,
178
- createConflictRecord({
179
- conflictId: "00000000-0000-0000-0000-000000000003",
180
- status: "kept-existing",
181
- resolvedAt: daysAgo(0),
182
- updatedAt: daysAgo(0),
183
- }) as any,
184
- ], 3);
185
-
186
- expect(summary.totalConflicts).toBe(3);
187
- expect(summary.openConflicts).toBe(2);
188
- expect(summary.attentionCounts.resolved).toBe(1);
189
- expect(summary.priorityClusters[0]?.attention).toBe("escalated");
190
- expect(summary.suggestedActions.some((action) => action.includes("escalated"))).toBe(true);
191
- });
192
-
193
- it("returns a no-open-conflicts message when nothing is pending", () => {
194
- const summary = buildConflictAuditSummary([
195
- createConflictRecord({
196
- conflictId: "00000000-0000-0000-0000-000000000001",
197
- status: "kept-existing",
198
- resolvedAt: "2026-03-16T00:00:00.000Z",
199
- }) as any,
200
- ], 3);
201
-
202
- expect(summary.openConflicts).toBe(0);
203
- expect(summary.priorityClusters).toHaveLength(0);
204
- expect(summary.suggestedActions).toEqual(["No open conflicts need review."]);
205
- });
206
- });