@fgv/ts-agent-memory 5.1.0-37 → 5.1.0-39

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 (197) hide show
  1. package/.rush/temp/{6dfc331ddf74dc2db0d4483d0c96ea971f351c83.tar.log → b82cf6bdece20481260e6bab946179eeec9d7b46.tar.log} +116 -2
  2. package/.rush/temp/chunked-rush-logs/ts-agent-memory.build.chunks.jsonl +4 -4
  3. package/.rush/temp/operation/build/all.log +4 -4
  4. package/.rush/temp/operation/build/log-chunks.jsonl +4 -4
  5. package/.rush/temp/operation/build/state.json +1 -1
  6. package/.rush/temp/shrinkwrap-deps.json +222 -221
  7. package/config/jest.config.json +1 -1
  8. package/dist/index.js +2 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/packlets/ingest/cycleGuard.js +111 -0
  11. package/dist/packlets/ingest/cycleGuard.js.map +1 -0
  12. package/dist/packlets/ingest/hostStages.js +6 -0
  13. package/dist/packlets/ingest/hostStages.js.map +1 -0
  14. package/dist/packlets/ingest/index.js +9 -0
  15. package/dist/packlets/ingest/index.js.map +1 -0
  16. package/dist/packlets/ingest/model.js +6 -0
  17. package/dist/packlets/ingest/model.js.map +1 -0
  18. package/dist/packlets/ingest/orchestrator.js +438 -0
  19. package/dist/packlets/ingest/orchestrator.js.map +1 -0
  20. package/dist/packlets/retrieve/index.js +1 -0
  21. package/dist/packlets/retrieve/index.js.map +1 -1
  22. package/dist/packlets/retrieve/temporalRetrievers.js +172 -0
  23. package/dist/packlets/retrieve/temporalRetrievers.js.map +1 -0
  24. package/dist/packlets/store/fileTreeMemoryStore.js +323 -41
  25. package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -1
  26. package/dist/packlets/tools/index.js +6 -0
  27. package/dist/packlets/tools/index.js.map +1 -0
  28. package/dist/packlets/tools/memoryTools.js +337 -0
  29. package/dist/packlets/tools/memoryTools.js.map +1 -0
  30. package/dist/packlets/types/identityCodec.js +115 -0
  31. package/dist/packlets/types/identityCodec.js.map +1 -1
  32. package/dist/packlets/types/index.js +1 -0
  33. package/dist/packlets/types/index.js.map +1 -1
  34. package/dist/packlets/types/temporal.js +85 -0
  35. package/dist/packlets/types/temporal.js.map +1 -0
  36. package/dist/packlets/types/writePolicy.js +96 -0
  37. package/dist/packlets/types/writePolicy.js.map +1 -1
  38. package/dist/test/unit/converters/antagonistRoundTrip.test.js +95 -0
  39. package/dist/test/unit/converters/antagonistRoundTrip.test.js.map +1 -0
  40. package/dist/test/unit/ingest/antagonistCycleAndParity.test.js +273 -0
  41. package/dist/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -0
  42. package/dist/test/unit/ingest/cycleGuard.test.js +54 -0
  43. package/dist/test/unit/ingest/cycleGuard.test.js.map +1 -0
  44. package/dist/test/unit/ingest/orchestrator.test.js +913 -0
  45. package/dist/test/unit/ingest/orchestrator.test.js.map +1 -0
  46. package/dist/test/unit/retrieve/temporalRetrievers.test.js +182 -0
  47. package/dist/test/unit/retrieve/temporalRetrievers.test.js.map +1 -0
  48. package/dist/test/unit/store/antagonistTemporalBoundary.test.js +120 -0
  49. package/dist/test/unit/store/antagonistTemporalBoundary.test.js.map +1 -0
  50. package/dist/test/unit/store/fileTreeMemoryStore.test.js +74 -7
  51. package/dist/test/unit/store/fileTreeMemoryStore.test.js.map +1 -1
  52. package/dist/test/unit/store/temporalStore.test.js +398 -0
  53. package/dist/test/unit/store/temporalStore.test.js.map +1 -0
  54. package/dist/test/unit/tools/memoryTools.test.js +572 -0
  55. package/dist/test/unit/tools/memoryTools.test.js.map +1 -0
  56. package/dist/test/unit/types/temporalCodec.test.js +203 -0
  57. package/dist/test/unit/types/temporalCodec.test.js.map +1 -0
  58. package/dist/test/unit/types/temporalPolicy.test.js +62 -0
  59. package/dist/test/unit/types/temporalPolicy.test.js.map +1 -0
  60. package/dist/ts-agent-memory.d.ts +1042 -10
  61. package/dist/tsdoc-metadata.json +1 -1
  62. package/etc/ts-agent-memory.api.md +284 -0
  63. package/lib/index.d.ts +2 -0
  64. package/lib/index.d.ts.map +1 -1
  65. package/lib/index.js +2 -0
  66. package/lib/index.js.map +1 -1
  67. package/lib/packlets/ingest/cycleGuard.d.ts +41 -0
  68. package/lib/packlets/ingest/cycleGuard.d.ts.map +1 -0
  69. package/lib/packlets/ingest/cycleGuard.js +115 -0
  70. package/lib/packlets/ingest/cycleGuard.js.map +1 -0
  71. package/lib/packlets/ingest/hostStages.d.ts +88 -0
  72. package/lib/packlets/ingest/hostStages.d.ts.map +1 -0
  73. package/lib/packlets/ingest/hostStages.js +7 -0
  74. package/lib/packlets/ingest/hostStages.js.map +1 -0
  75. package/lib/packlets/ingest/index.d.ts +5 -0
  76. package/lib/packlets/ingest/index.d.ts.map +1 -0
  77. package/lib/packlets/ingest/index.js +25 -0
  78. package/lib/packlets/ingest/index.js.map +1 -0
  79. package/lib/packlets/ingest/model.d.ts +177 -0
  80. package/lib/packlets/ingest/model.d.ts.map +1 -0
  81. package/lib/packlets/ingest/model.js +7 -0
  82. package/lib/packlets/ingest/model.js.map +1 -0
  83. package/lib/packlets/ingest/orchestrator.d.ts +206 -0
  84. package/lib/packlets/ingest/orchestrator.d.ts.map +1 -0
  85. package/lib/packlets/ingest/orchestrator.js +442 -0
  86. package/lib/packlets/ingest/orchestrator.js.map +1 -0
  87. package/lib/packlets/retrieve/index.d.ts +1 -0
  88. package/lib/packlets/retrieve/index.d.ts.map +1 -1
  89. package/lib/packlets/retrieve/index.js +1 -0
  90. package/lib/packlets/retrieve/index.js.map +1 -1
  91. package/lib/packlets/retrieve/temporalRetrievers.d.ts +78 -0
  92. package/lib/packlets/retrieve/temporalRetrievers.d.ts.map +1 -0
  93. package/lib/packlets/retrieve/temporalRetrievers.js +178 -0
  94. package/lib/packlets/retrieve/temporalRetrievers.js.map +1 -0
  95. package/lib/packlets/store/fileTreeMemoryStore.d.ts +118 -9
  96. package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -1
  97. package/lib/packlets/store/fileTreeMemoryStore.js +322 -40
  98. package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -1
  99. package/lib/packlets/tools/index.d.ts +2 -0
  100. package/lib/packlets/tools/index.d.ts.map +1 -0
  101. package/lib/packlets/tools/index.js +22 -0
  102. package/lib/packlets/tools/index.js.map +1 -0
  103. package/lib/packlets/tools/memoryTools.d.ts +139 -0
  104. package/lib/packlets/tools/memoryTools.d.ts.map +1 -0
  105. package/lib/packlets/tools/memoryTools.js +341 -0
  106. package/lib/packlets/tools/memoryTools.js.map +1 -0
  107. package/lib/packlets/types/identityCodec.d.ts +86 -0
  108. package/lib/packlets/types/identityCodec.d.ts.map +1 -1
  109. package/lib/packlets/types/identityCodec.js +118 -1
  110. package/lib/packlets/types/identityCodec.js.map +1 -1
  111. package/lib/packlets/types/index.d.ts +1 -0
  112. package/lib/packlets/types/index.d.ts.map +1 -1
  113. package/lib/packlets/types/index.js +1 -0
  114. package/lib/packlets/types/index.js.map +1 -1
  115. package/lib/packlets/types/temporal.d.ts +40 -0
  116. package/lib/packlets/types/temporal.d.ts.map +1 -0
  117. package/lib/packlets/types/temporal.js +92 -0
  118. package/lib/packlets/types/temporal.js.map +1 -0
  119. package/lib/packlets/types/writePolicy.d.ts +49 -0
  120. package/lib/packlets/types/writePolicy.d.ts.map +1 -1
  121. package/lib/packlets/types/writePolicy.js +98 -1
  122. package/lib/packlets/types/writePolicy.js.map +1 -1
  123. package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts +10 -0
  124. package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts.map +1 -0
  125. package/lib/test/unit/converters/antagonistRoundTrip.test.js +97 -0
  126. package/lib/test/unit/converters/antagonistRoundTrip.test.js.map +1 -0
  127. package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts +9 -0
  128. package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts.map +1 -0
  129. package/lib/test/unit/ingest/antagonistCycleAndParity.test.js +275 -0
  130. package/lib/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -0
  131. package/lib/test/unit/ingest/cycleGuard.test.d.ts +2 -0
  132. package/lib/test/unit/ingest/cycleGuard.test.d.ts.map +1 -0
  133. package/lib/test/unit/ingest/cycleGuard.test.js +56 -0
  134. package/lib/test/unit/ingest/cycleGuard.test.js.map +1 -0
  135. package/lib/test/unit/ingest/orchestrator.test.d.ts +2 -0
  136. package/lib/test/unit/ingest/orchestrator.test.d.ts.map +1 -0
  137. package/lib/test/unit/ingest/orchestrator.test.js +915 -0
  138. package/lib/test/unit/ingest/orchestrator.test.js.map +1 -0
  139. package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts +2 -0
  140. package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts.map +1 -0
  141. package/lib/test/unit/retrieve/temporalRetrievers.test.js +184 -0
  142. package/lib/test/unit/retrieve/temporalRetrievers.test.js.map +1 -0
  143. package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts +9 -0
  144. package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts.map +1 -0
  145. package/lib/test/unit/store/antagonistTemporalBoundary.test.js +122 -0
  146. package/lib/test/unit/store/antagonistTemporalBoundary.test.js.map +1 -0
  147. package/lib/test/unit/store/fileTreeMemoryStore.test.js +74 -7
  148. package/lib/test/unit/store/fileTreeMemoryStore.test.js.map +1 -1
  149. package/lib/test/unit/store/temporalStore.test.d.ts +2 -0
  150. package/lib/test/unit/store/temporalStore.test.d.ts.map +1 -0
  151. package/lib/test/unit/store/temporalStore.test.js +400 -0
  152. package/lib/test/unit/store/temporalStore.test.js.map +1 -0
  153. package/lib/test/unit/tools/memoryTools.test.d.ts +2 -0
  154. package/lib/test/unit/tools/memoryTools.test.d.ts.map +1 -0
  155. package/lib/test/unit/tools/memoryTools.test.js +574 -0
  156. package/lib/test/unit/tools/memoryTools.test.js.map +1 -0
  157. package/lib/test/unit/types/temporalCodec.test.d.ts +2 -0
  158. package/lib/test/unit/types/temporalCodec.test.d.ts.map +1 -0
  159. package/lib/test/unit/types/temporalCodec.test.js +205 -0
  160. package/lib/test/unit/types/temporalCodec.test.js.map +1 -0
  161. package/lib/test/unit/types/temporalPolicy.test.d.ts +2 -0
  162. package/lib/test/unit/types/temporalPolicy.test.d.ts.map +1 -0
  163. package/lib/test/unit/types/temporalPolicy.test.js +64 -0
  164. package/lib/test/unit/types/temporalPolicy.test.js.map +1 -0
  165. package/package.json +7 -7
  166. package/rush-logs/ts-agent-memory.build.cache.log +1 -1
  167. package/rush-logs/ts-agent-memory.build.log +4 -4
  168. package/src/index.ts +2 -0
  169. package/src/packlets/ingest/cycleGuard.ts +142 -0
  170. package/src/packlets/ingest/hostStages.ts +111 -0
  171. package/src/packlets/ingest/index.ts +9 -0
  172. package/src/packlets/ingest/model.ts +184 -0
  173. package/src/packlets/ingest/orchestrator.ts +797 -0
  174. package/src/packlets/retrieve/index.ts +1 -0
  175. package/src/packlets/retrieve/temporalRetrievers.ts +210 -0
  176. package/src/packlets/store/fileTreeMemoryStore.ts +460 -66
  177. package/src/packlets/tools/index.ts +6 -0
  178. package/src/packlets/tools/memoryTools.ts +579 -0
  179. package/src/packlets/types/identityCodec.ts +184 -0
  180. package/src/packlets/types/index.ts +1 -0
  181. package/src/packlets/types/temporal.ts +96 -0
  182. package/src/packlets/types/writePolicy.ts +127 -0
  183. package/src/test/unit/converters/antagonistRoundTrip.test.ts +110 -0
  184. package/src/test/unit/ingest/antagonistCycleAndParity.test.ts +362 -0
  185. package/src/test/unit/ingest/cycleGuard.test.ts +68 -0
  186. package/src/test/unit/ingest/orchestrator.test.ts +1158 -0
  187. package/src/test/unit/retrieve/temporalRetrievers.test.ts +226 -0
  188. package/src/test/unit/store/antagonistTemporalBoundary.test.ts +158 -0
  189. package/src/test/unit/store/fileTreeMemoryStore.test.ts +98 -7
  190. package/src/test/unit/store/temporalStore.test.ts +469 -0
  191. package/src/test/unit/tools/memoryTools.test.ts +771 -0
  192. package/src/test/unit/types/temporalCodec.test.ts +259 -0
  193. package/src/test/unit/types/temporalPolicy.test.ts +96 -0
  194. package/temp/build/lint/_eslint-5eVG3S6w.json +85 -9
  195. package/temp/build/typescript/ts_8nwakTlr.json +1 -1
  196. package/temp/ts-agent-memory.api.json +11984 -6314
  197. package/temp/ts-agent-memory.api.md +284 -0
@@ -0,0 +1,913 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+ import '@fgv/ts-utils-jest';
6
+ import { Converters, Logging, fail, succeed } from '@fgv/ts-utils';
7
+ import { FileTree } from '@fgv/ts-json-base';
8
+ import { BodyConverterRegistry, CONTRADICTS_LINK_TYPE, DEFAULT_SIMILARITY_THRESHOLD, DEFAULT_SIMILARITY_TOP_K, FileTreeMemoryStore, HOST_INGEST_PROVENANCE_SOURCE, InMemoryCosineIndex, KnowledgeIdentityCodec, LtmIdentityCodec, MemoryIngestOrchestrator, TemporalIdentityCodec, TemporalVersionedPolicy, serializeMemoryFile } from '../../../index';
9
+ // --- kinds --------------------------------------------------------------------
10
+ const noteKind = 'note';
11
+ const factKind = 'fact';
12
+ const numKind = 'num';
13
+ const orphanKind = 'orphan';
14
+ const ltmKind = 'ltm';
15
+ // --- shared fixtures ----------------------------------------------------------
16
+ let clockValue;
17
+ const clock = () => clockValue;
18
+ function mutableRoot(files = []) {
19
+ const tree = FileTree.inMemory([...files], { mutable: true }).orThrow();
20
+ const root = tree.getDirectory('/').orThrow();
21
+ if (!FileTree.isMutableDirectoryItem(root)) {
22
+ throw new Error('expected a mutable root directory');
23
+ }
24
+ return root;
25
+ }
26
+ function registry() {
27
+ const reg = BodyConverterRegistry.create().orThrow();
28
+ reg.register(noteKind, Converters.string);
29
+ reg.register(factKind, Converters.string);
30
+ reg.register(numKind, Converters.number);
31
+ reg.register(orphanKind, Converters.string);
32
+ reg.register(ltmKind, Converters.string);
33
+ return reg;
34
+ }
35
+ const codecs = new Map([
36
+ [noteKind, new KnowledgeIdentityCodec()],
37
+ [numKind, new KnowledgeIdentityCodec()],
38
+ [ltmKind, new LtmIdentityCodec()],
39
+ [factKind, TemporalIdentityCodec.create('facts').orThrow()]
40
+ ]);
41
+ const policies = new Map([
42
+ [factKind, TemporalVersionedPolicy.create().orThrow()]
43
+ ]);
44
+ // A deterministic embedder keyed by body text (three-dimensional vectors so
45
+ // cosine relationships are controllable). Unknown bodies map to a distinct axis.
46
+ const VECTORS = new Map([
47
+ ['apple pie', [1, 0, 0]],
48
+ ['apple tart', [0.99, 0.14, 0]],
49
+ ['banana bread', [0, 1, 0]]
50
+ ]);
51
+ const embed = (record) => {
52
+ var _a;
53
+ if (record.body === 'boom') {
54
+ return Promise.resolve(fail('embed boom'));
55
+ }
56
+ const vec = (_a = VECTORS.get(record.body)) !== null && _a !== void 0 ? _a : [0, 0, 1];
57
+ return Promise.resolve(succeed(Float32Array.from(vec)));
58
+ };
59
+ // --- mock host stages ---------------------------------------------------------
60
+ function classifier(fn) {
61
+ return { classify: (item) => Promise.resolve(fn(item)) };
62
+ }
63
+ function throwingClassifier() {
64
+ return {
65
+ classify: () => {
66
+ throw new Error('classifier boom');
67
+ }
68
+ };
69
+ }
70
+ function extractor(fn) {
71
+ return { extract: (item, c) => Promise.resolve(fn(item, c)) };
72
+ }
73
+ function resolver(fn) {
74
+ return { resolve: (candidate, similar) => Promise.resolve(fn(candidate, similar)) };
75
+ }
76
+ function relater(fn) {
77
+ return { relate: (ctx) => Promise.resolve(fn(ctx)) };
78
+ }
79
+ const noEdges = relater(() => succeed([]));
80
+ const classifyNote = classifier(() => succeed({ kind: noteKind, confidence: 0.9 }));
81
+ /** Extractor that emits one note candidate per item, body = item.content, entityId = item.id. */
82
+ function oneNoteExtractor() {
83
+ return extractor((item) => succeed([candidate(noteKind, item.id, item.content)]));
84
+ }
85
+ function candidate(kind, entityId, body, opts = {}) {
86
+ var _a, _b, _c;
87
+ return {
88
+ envelope: Object.assign({ entityId: entityId, kind, tags: ((_a = opts.tags) !== null && _a !== void 0 ? _a : []), links: (_b = opts.links) !== null && _b !== void 0 ? _b : [], provenance: (_c = opts.provenance) !== null && _c !== void 0 ? _c : { source: 'agent' } }, (opts.temporal !== undefined ? { temporal: opts.temporal } : {})),
89
+ body
90
+ };
91
+ }
92
+ function candEdge(source, type, target, confidence) {
93
+ return {
94
+ source: source,
95
+ edge: Object.assign({ type: type, target: target }, (confidence !== undefined ? { confidence } : {}))
96
+ };
97
+ }
98
+ function buildStore(params = {}) {
99
+ var _a;
100
+ return FileTreeMemoryStore.create({
101
+ root: mutableRoot(params.files),
102
+ registry: (_a = params.registry) !== null && _a !== void 0 ? _a : registry(),
103
+ codecs,
104
+ writePolicies: policies,
105
+ clock,
106
+ vectorIndex: params.vectorIndex,
107
+ embed: params.embed
108
+ }).orThrow();
109
+ }
110
+ function buildOrchestrator(params) {
111
+ var _a, _b, _c, _d;
112
+ return MemoryIngestOrchestrator.create({
113
+ store: params.store,
114
+ registry: (_a = params.registry) !== null && _a !== void 0 ? _a : registry(),
115
+ codecs,
116
+ classifier: (_b = params.classifier) !== null && _b !== void 0 ? _b : classifyNote,
117
+ extractor: (_c = params.extractor) !== null && _c !== void 0 ? _c : oneNoteExtractor(),
118
+ relationExtractor: (_d = params.relationExtractor) !== null && _d !== void 0 ? _d : noEdges,
119
+ entityResolver: params.entityResolver,
120
+ vectorIndex: params.vectorIndex,
121
+ embed: params.embed,
122
+ similarityThreshold: params.similarityThreshold,
123
+ cycleGuard: params.cycleGuard
124
+ }).orThrow();
125
+ }
126
+ /** A seeded note file with only `source` provenance (the additive-provenance baseline). */
127
+ function seedNote(id, body, provenance = { source: 'agent' }) {
128
+ const envelope = {
129
+ id: id,
130
+ entityId: id,
131
+ kind: noteKind,
132
+ tags: [],
133
+ links: [],
134
+ created: 1,
135
+ updated: 1,
136
+ seq: 4,
137
+ contentHash: 'seed',
138
+ provenance: provenance
139
+ };
140
+ return { path: `knowledge/${id}.md`, contents: serializeMemoryFile(envelope, body).orThrow() };
141
+ }
142
+ beforeEach(() => {
143
+ clockValue = 1000;
144
+ });
145
+ describe('MemoryIngestOrchestrator', () => {
146
+ describe('create', () => {
147
+ test('constructs via the factory', () => {
148
+ expect(MemoryIngestOrchestrator.create({
149
+ store: buildStore(),
150
+ registry: registry(),
151
+ codecs,
152
+ classifier: classifyNote,
153
+ extractor: oneNoteExtractor(),
154
+ relationExtractor: noEdges
155
+ })).toSucceed();
156
+ });
157
+ test('exposes the documented similarity defaults', () => {
158
+ expect(DEFAULT_SIMILARITY_THRESHOLD).toBe(0.85);
159
+ expect(DEFAULT_SIMILARITY_TOP_K).toBe(5);
160
+ });
161
+ });
162
+ describe('single-item ingest (first-class path)', () => {
163
+ test('classifies, extracts, and writes one record end-to-end with host-ingest provenance + derivedFrom', async () => {
164
+ const store = buildStore();
165
+ const orch = buildOrchestrator({ store });
166
+ const sourceId = 'turn-3';
167
+ const result = await orch.ingestItem({ id: 'doc-1', content: 'the sky is blue', sourceId });
168
+ expect(result).toSucceedAndSatisfy((r) => {
169
+ var _a, _b, _c;
170
+ expect(r.item.id).toBe('doc-1');
171
+ expect(r.records).toHaveLength(1);
172
+ const rec = r.records[0];
173
+ expect(rec.disposition).toBe('written');
174
+ expect(rec.resolution.verdict).toBe('new');
175
+ expect(rec.id).toBe('doc-1');
176
+ expect((_a = rec.record) === null || _a === void 0 ? void 0 : _a.envelope.provenance.source).toBe(HOST_INGEST_PROVENANCE_SOURCE);
177
+ expect((_b = rec.record) === null || _b === void 0 ? void 0 : _b.envelope.provenance.derivedFrom).toBe('turn-3');
178
+ expect((_c = rec.record) === null || _c === void 0 ? void 0 : _c.body).toBe('the sky is blue');
179
+ expect(rec.interlock).toBeUndefined();
180
+ });
181
+ expect(await store.get(noteKind, 'doc-1')).toSucceedAndSatisfy((rec) => {
182
+ expect(rec === null || rec === void 0 ? void 0 : rec.body).toBe('the sky is blue');
183
+ });
184
+ });
185
+ test('omits derivedFrom when the item carries no sourceId', async () => {
186
+ const store = buildStore();
187
+ const orch = buildOrchestrator({ store });
188
+ const result = await orch.ingestItem({ id: 'doc-1', content: 'a fact' });
189
+ expect(result).toSucceedAndSatisfy((r) => {
190
+ var _a, _b;
191
+ expect((_a = r.records[0].record) === null || _a === void 0 ? void 0 : _a.envelope.provenance.derivedFrom).toBeUndefined();
192
+ expect((_b = r.records[0].record) === null || _b === void 0 ? void 0 : _b.envelope.provenance.source).toBe(HOST_INGEST_PROVENANCE_SOURCE);
193
+ });
194
+ });
195
+ test('yields an empty record set when the extractor finds nothing memorable', async () => {
196
+ const store = buildStore();
197
+ const orch = buildOrchestrator({ store, extractor: extractor(() => succeed([])) });
198
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'noise' })).toSucceedAndSatisfy((r) => {
199
+ expect(r.records).toEqual([]);
200
+ });
201
+ });
202
+ });
203
+ describe('host-stage failures abort loudly', () => {
204
+ test('classifier failure', async () => {
205
+ const orch = buildOrchestrator({
206
+ store: buildStore(),
207
+ classifier: classifier(() => fail('cannot classify'))
208
+ });
209
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'x' })).toFailWith(/cannot classify/);
210
+ });
211
+ test('classifier throw is captured as a failure', async () => {
212
+ const orch = buildOrchestrator({ store: buildStore(), classifier: throwingClassifier() });
213
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'x' })).toFailWith(/classify threw.*classifier boom/);
214
+ });
215
+ test('extractor failure', async () => {
216
+ const orch = buildOrchestrator({
217
+ store: buildStore(),
218
+ extractor: extractor(() => fail('extract error'))
219
+ });
220
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'x' })).toFailWith(/extract error/);
221
+ });
222
+ test('relation-extractor failure', async () => {
223
+ const orch = buildOrchestrator({
224
+ store: buildStore(),
225
+ relationExtractor: relater(() => fail('relate error'))
226
+ });
227
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'x' })).toFailWith(/relate error/);
228
+ });
229
+ });
230
+ describe('stage 3b — typed validation boundary', () => {
231
+ test('rejects a candidate whose body fails the kind converter', async () => {
232
+ const orch = buildOrchestrator({
233
+ store: buildStore(),
234
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-1', 42)]))
235
+ });
236
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'x' })).toFailWith(/candidate body for kind 'note' is invalid/);
237
+ });
238
+ test('rejects a non-string body even when the converter accepts it', async () => {
239
+ const orch = buildOrchestrator({
240
+ store: buildStore(),
241
+ extractor: extractor(() => succeed([candidate(numKind, 'n-1', 42)]))
242
+ });
243
+ expect(await orch.ingestItem({ id: 'n-1', content: 'x' })).toFailWith(/must be a string/);
244
+ });
245
+ test('fails when no identity codec is registered for the candidate kind', async () => {
246
+ const orch = buildOrchestrator({
247
+ store: buildStore(),
248
+ extractor: extractor(() => succeed([candidate(orphanKind, 'o-1', 'body')]))
249
+ });
250
+ expect(await orch.ingestItem({ id: 'o-1', content: 'x' })).toFailWith(/no identity codec/);
251
+ });
252
+ });
253
+ describe('stage 4 — exact dedup (layer 1)', () => {
254
+ test('an exact {kind,body} match in scope is duplicate-of (no resolver)', async () => {
255
+ const store = buildStore({ files: [seedNote('doc-a', 'hello')] });
256
+ const orch = buildOrchestrator({
257
+ store,
258
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'hello')]))
259
+ });
260
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
261
+ expect(r.records[0].disposition).toBe('deduped');
262
+ expect(r.records[0].resolution).toEqual({ verdict: 'duplicate-of', target: 'doc-a' });
263
+ expect(r.records[0].id).toBe('doc-a');
264
+ });
265
+ // doc-b was never written.
266
+ expect(await store.get(noteKind, 'doc-b')).toSucceedWith(undefined);
267
+ });
268
+ test('exact dedup takes precedence over the resolver (resolver never called)', async () => {
269
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
270
+ const store = buildStore({ files: [seedNote('doc-a', 'hello')] });
271
+ const orch = buildOrchestrator({
272
+ store,
273
+ entityResolver: resolver(() => fail('resolver must not be called')),
274
+ vectorIndex,
275
+ embed,
276
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'hello')]))
277
+ });
278
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
279
+ expect(r.records[0].disposition).toBe('deduped');
280
+ });
281
+ });
282
+ test('a distinct body is a fresh write (no resolver → exact-only fall-back)', async () => {
283
+ const store = buildStore({ files: [seedNote('doc-a', 'hello')] });
284
+ const orch = buildOrchestrator({
285
+ store,
286
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'goodbye')]))
287
+ });
288
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
289
+ expect(r.records[0].disposition).toBe('written');
290
+ expect(r.records[0].resolution.verdict).toBe('new');
291
+ });
292
+ });
293
+ });
294
+ });
295
+ // --- similarity + resolver fixtures ------------------------------------------
296
+ const classifyFact = classifier(() => succeed({ kind: factKind }));
297
+ function oneFactExtractor() {
298
+ return extractor((item) => succeed([candidate(factKind, item.id, item.content)]));
299
+ }
300
+ async function putNote(store, id, body) {
301
+ const rec = {
302
+ envelope: {
303
+ id: id,
304
+ entityId: id,
305
+ kind: noteKind,
306
+ tags: [],
307
+ links: [],
308
+ created: 0,
309
+ updated: 0,
310
+ seq: 0,
311
+ contentHash: '',
312
+ provenance: { source: 'agent' }
313
+ },
314
+ body
315
+ };
316
+ (await store.put(rec)).orThrow();
317
+ }
318
+ function mockStore(overrides) {
319
+ var _a, _b, _c, _d, _e;
320
+ return {
321
+ get: (_a = overrides.get) !== null && _a !== void 0 ? _a : (() => Promise.resolve(succeed(undefined))),
322
+ getById: (_b = overrides.getById) !== null && _b !== void 0 ? _b : (() => Promise.resolve(succeed(undefined))),
323
+ list: (_c = overrides.list) !== null && _c !== void 0 ? _c : (() => Promise.resolve(succeed([]))),
324
+ put: (_d = overrides.put) !== null && _d !== void 0 ? _d : ((r) => Promise.resolve(succeed(r))),
325
+ delete: (_e = overrides.delete) !== null && _e !== void 0 ? _e : (() => Promise.resolve(fail('n/a')))
326
+ };
327
+ }
328
+ describe('MemoryIngestOrchestrator — stage 4 similarity (layer 2)', () => {
329
+ test('resolver verdict new writes the candidate despite a near-duplicate', async () => {
330
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
331
+ const store = buildStore({ vectorIndex, embed });
332
+ await putNote(store, 'doc-a', 'apple pie');
333
+ const orch = buildOrchestrator({
334
+ store,
335
+ vectorIndex,
336
+ embed,
337
+ entityResolver: resolver(() => succeed({ verdict: 'new' })),
338
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
339
+ });
340
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
341
+ expect(r.records[0].disposition).toBe('written');
342
+ expect(r.records[0].resolution.verdict).toBe('new');
343
+ });
344
+ });
345
+ test('resolver verdict duplicate-of dedups against the surfaced neighbor', async () => {
346
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
347
+ const store = buildStore({ vectorIndex, embed });
348
+ await putNote(store, 'doc-a', 'apple pie');
349
+ const orch = buildOrchestrator({
350
+ store,
351
+ vectorIndex,
352
+ embed,
353
+ entityResolver: resolver((__c, similar) => succeed({ verdict: 'duplicate-of', target: similar[0].id })),
354
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
355
+ });
356
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
357
+ expect(r.records[0].disposition).toBe('deduped');
358
+ expect(r.records[0].id).toBe('doc-a');
359
+ });
360
+ expect(await store.get(noteKind, 'doc-b')).toSucceedWith(undefined);
361
+ });
362
+ test('resolver verdict supersede writes the candidate and records the superseded target', async () => {
363
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
364
+ const store = buildStore({ vectorIndex, embed });
365
+ await putNote(store, 'doc-a', 'apple pie');
366
+ const orch = buildOrchestrator({
367
+ store,
368
+ vectorIndex,
369
+ embed,
370
+ entityResolver: resolver((__c, similar) => succeed({ verdict: 'supersede', target: similar[0].id })),
371
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
372
+ });
373
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
374
+ expect(r.records[0].disposition).toBe('written');
375
+ expect(r.records[0].resolution).toEqual({ verdict: 'supersede', target: 'doc-a' });
376
+ expect(r.records[0].id).toBe('doc-b');
377
+ });
378
+ expect(await store.get(noteKind, 'doc-b')).toSucceedAndSatisfy((rec) => expect(rec === null || rec === void 0 ? void 0 : rec.body).toBe('apple tart'));
379
+ });
380
+ test('resolver verdict merge-into re-addresses the write to the target entity', async () => {
381
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
382
+ const store = buildStore({ vectorIndex, embed });
383
+ await putNote(store, 'doc-a', 'apple pie');
384
+ const orch = buildOrchestrator({
385
+ store,
386
+ vectorIndex,
387
+ embed,
388
+ entityResolver: resolver((__c, similar) => succeed({ verdict: 'merge-into', target: similar[0].id })),
389
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
390
+ });
391
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
392
+ expect(r.records[0].disposition).toBe('merged');
393
+ expect(r.records[0].id).toBe('doc-a');
394
+ });
395
+ // The merge updated doc-a's body (LWW merge patch) and never minted doc-b.
396
+ expect(await store.get(noteKind, 'doc-a')).toSucceedAndSatisfy((rec) => expect(rec === null || rec === void 0 ? void 0 : rec.body).toBe('apple tart'));
397
+ expect(await store.get(noteKind, 'doc-b')).toSucceedWith(undefined);
398
+ });
399
+ test('merge-into with a non-existent target fails loudly', async () => {
400
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
401
+ const store = buildStore({ vectorIndex, embed });
402
+ await putNote(store, 'doc-a', 'apple pie');
403
+ const orch = buildOrchestrator({
404
+ store,
405
+ vectorIndex,
406
+ embed,
407
+ entityResolver: resolver(() => succeed({ verdict: 'merge-into', target: 'ghost' })),
408
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
409
+ });
410
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/merge-into target 'ghost' does not exist/);
411
+ });
412
+ test('a below-threshold neighbor is not surfaced (resolver not called)', async () => {
413
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
414
+ const store = buildStore({ vectorIndex, embed });
415
+ await putNote(store, 'doc-a', 'apple pie');
416
+ const orch = buildOrchestrator({
417
+ store,
418
+ vectorIndex,
419
+ embed,
420
+ entityResolver: resolver(() => fail('resolver must not be called')),
421
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'banana bread')]))
422
+ });
423
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
424
+ expect(r.records[0].resolution.verdict).toBe('new');
425
+ });
426
+ });
427
+ test('the candidate self-hit is excluded from surfaced neighbors', async () => {
428
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
429
+ const store = buildStore({ vectorIndex, embed });
430
+ await putNote(store, 'doc-a', 'apple pie');
431
+ const orch = buildOrchestrator({
432
+ store,
433
+ vectorIndex,
434
+ embed,
435
+ entityResolver: resolver(() => fail('resolver must not be called')),
436
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-a', 'apple tart')]))
437
+ });
438
+ // Re-ingesting the SAME entity: its own prior vector is the only over-threshold
439
+ // hit, and it is skipped as the self-hit, so no resolver dispatch occurs.
440
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
441
+ expect(r.records[0].resolution.verdict).toBe('new');
442
+ expect(r.records[0].disposition).toBe('written');
443
+ });
444
+ });
445
+ test('a surfaced hit with no backing record is skipped', async () => {
446
+ const ghostIndex = {
447
+ add: (id) => Promise.resolve(succeed(id)),
448
+ remove: (id) => Promise.resolve(succeed(id)),
449
+ query: () => Promise.resolve(succeed([{ id: 'ghost', score: 0.99 }]))
450
+ };
451
+ const orch = buildOrchestrator({
452
+ store: buildStore(),
453
+ vectorIndex: ghostIndex,
454
+ embed,
455
+ entityResolver: resolver(() => fail('resolver must not be called')),
456
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
457
+ });
458
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
459
+ expect(r.records[0].resolution.verdict).toBe('new');
460
+ });
461
+ });
462
+ test('an embedder failure surfaces loudly', async () => {
463
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
464
+ const orch = buildOrchestrator({
465
+ store: buildStore(),
466
+ vectorIndex,
467
+ embed,
468
+ entityResolver: resolver(() => succeed({ verdict: 'new' })),
469
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'boom')]))
470
+ });
471
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/embed boom/);
472
+ });
473
+ test('a similarity-query failure surfaces loudly', async () => {
474
+ const failingIndex = {
475
+ add: (id) => Promise.resolve(succeed(id)),
476
+ remove: (id) => Promise.resolve(succeed(id)),
477
+ query: () => Promise.resolve(fail('query kaput'))
478
+ };
479
+ const orch = buildOrchestrator({
480
+ store: buildStore(),
481
+ vectorIndex: failingIndex,
482
+ embed,
483
+ entityResolver: resolver(() => succeed({ verdict: 'new' })),
484
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
485
+ });
486
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/query kaput/);
487
+ });
488
+ test('a custom similarityThreshold gates the resolver dispatch', async () => {
489
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
490
+ const store = buildStore({ vectorIndex, embed });
491
+ await putNote(store, 'doc-a', 'apple pie');
492
+ const orch = buildOrchestrator({
493
+ store,
494
+ vectorIndex,
495
+ embed,
496
+ similarityThreshold: 0.999, // 0.99 neighbor now falls below threshold
497
+ entityResolver: resolver(() => fail('resolver must not be called')),
498
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
499
+ });
500
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
501
+ expect(r.records[0].resolution.verdict).toBe('new');
502
+ });
503
+ });
504
+ });
505
+ describe('MemoryIngestOrchestrator — layer-2 wiring gates (exact-only fall-back)', () => {
506
+ const failResolver = resolver(() => fail('resolver must not be called'));
507
+ const almostSimilar = extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]));
508
+ test('no resolver → exact-only', async () => {
509
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
510
+ const store = buildStore({ vectorIndex, embed });
511
+ await putNote(store, 'doc-a', 'apple pie');
512
+ const orch = buildOrchestrator({ store, vectorIndex, embed, extractor: almostSimilar });
513
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => expect(r.records[0].resolution.verdict).toBe('new'));
514
+ });
515
+ test('resolver + embed but no vector index → exact-only', async () => {
516
+ const orch = buildOrchestrator({
517
+ store: buildStore(),
518
+ embed,
519
+ entityResolver: failResolver,
520
+ extractor: almostSimilar
521
+ });
522
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => expect(r.records[0].resolution.verdict).toBe('new'));
523
+ });
524
+ test('resolver + vector index but no embedder → exact-only', async () => {
525
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
526
+ const orch = buildOrchestrator({
527
+ store: buildStore(),
528
+ vectorIndex,
529
+ entityResolver: failResolver,
530
+ extractor: almostSimilar
531
+ });
532
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => expect(r.records[0].resolution.verdict).toBe('new'));
533
+ });
534
+ });
535
+ describe('MemoryIngestOrchestrator — stage 5 relate + cycle guard', () => {
536
+ test('attaches a valid edge to an existing record', async () => {
537
+ const store = buildStore();
538
+ await putNote(store, 'doc-a', 'anchor');
539
+ const orch = buildOrchestrator({
540
+ store,
541
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'goodbye')])),
542
+ relationExtractor: relater(() => succeed([candEdge('doc-b', 'mentions', 'doc-a', 0.7)]))
543
+ });
544
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
545
+ var _a;
546
+ expect(r.records[0].edges).toHaveLength(1);
547
+ expect((_a = r.records[0].record) === null || _a === void 0 ? void 0 : _a.envelope.links).toEqual([
548
+ { type: 'mentions', target: 'doc-a', confidence: 0.7 }
549
+ ]);
550
+ });
551
+ });
552
+ test('attaches an edge between two sibling candidates', async () => {
553
+ const orch = buildOrchestrator({
554
+ store: buildStore(),
555
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'first'), candidate(noteKind, 'doc-c', 'second')])),
556
+ relationExtractor: relater(() => succeed([candEdge('doc-b', 'rel', 'doc-c')]))
557
+ });
558
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
559
+ var _a;
560
+ expect(r.records).toHaveLength(2);
561
+ expect((_a = r.records[0].record) === null || _a === void 0 ? void 0 : _a.envelope.links).toEqual([{ type: 'rel', target: 'doc-c' }]);
562
+ expect(r.records[1].edges).toEqual([]);
563
+ });
564
+ });
565
+ test('rejects an edge whose source is not a candidate being written', async () => {
566
+ const orch = buildOrchestrator({
567
+ store: buildStore(),
568
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'x')])),
569
+ relationExtractor: relater(() => succeed([candEdge('ghost', 'rel', 'doc-b')]))
570
+ });
571
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/edge source 'ghost' is not a candidate being written/);
572
+ });
573
+ test('rejects an edge whose target resolves to nothing', async () => {
574
+ const orch = buildOrchestrator({
575
+ store: buildStore(),
576
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'x')])),
577
+ relationExtractor: relater(() => succeed([candEdge('doc-b', 'rel', 'ghost')]))
578
+ });
579
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/edge target 'ghost' resolves to neither/);
580
+ });
581
+ test('rejects a cycle-inducing edge (default guard)', async () => {
582
+ const orch = buildOrchestrator({
583
+ store: buildStore(),
584
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'first'), candidate(noteKind, 'doc-c', 'second')])),
585
+ relationExtractor: relater(() => succeed([candEdge('doc-b', 'rel', 'doc-c'), candEdge('doc-c', 'rel', 'doc-b')]))
586
+ });
587
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/would create a cycle/);
588
+ });
589
+ test('cycleGuard "off" admits an otherwise-cyclic edge set', async () => {
590
+ const orch = buildOrchestrator({
591
+ store: buildStore(),
592
+ cycleGuard: 'off',
593
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'first'), candidate(noteKind, 'doc-c', 'second')])),
594
+ relationExtractor: relater(() => succeed([candEdge('doc-b', 'rel', 'doc-c'), candEdge('doc-c', 'rel', 'doc-b')]))
595
+ });
596
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
597
+ var _a, _b;
598
+ expect((_a = r.records[0].record) === null || _a === void 0 ? void 0 : _a.envelope.links).toEqual([{ type: 'rel', target: 'doc-c' }]);
599
+ expect((_b = r.records[1].record) === null || _b === void 0 ? void 0 : _b.envelope.links).toEqual([{ type: 'rel', target: 'doc-b' }]);
600
+ });
601
+ });
602
+ test('a contradicts edge on a NON-temporal kind persists as a plain link (no interlock)', async () => {
603
+ const store = buildStore();
604
+ await putNote(store, 'doc-a', 'anchor');
605
+ const orch = buildOrchestrator({
606
+ store,
607
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'goodbye')])),
608
+ relationExtractor: relater(() => succeed([candEdge('doc-b', 'contradicts', 'doc-a')]))
609
+ });
610
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
611
+ var _a;
612
+ expect(r.records[0].interlock).toBeUndefined();
613
+ expect((_a = r.records[0].record) === null || _a === void 0 ? void 0 : _a.envelope.links).toEqual([{ type: 'contradicts', target: 'doc-a' }]);
614
+ });
615
+ });
616
+ });
617
+ describe('MemoryIngestOrchestrator — contradicts→temporal interlock', () => {
618
+ test('a contradicts edge on a temporal kind invalidates the prior version and writes a new one', async () => {
619
+ const store = buildStore();
620
+ const firstOrch = buildOrchestrator({
621
+ store,
622
+ classifier: classifyFact,
623
+ extractor: oneFactExtractor()
624
+ });
625
+ clockValue = 1000;
626
+ const first = await firstOrch.ingestItem({ id: 'fact-1', content: 'the sky is blue' });
627
+ const v1Id = first.orThrow().records[0].id;
628
+ expect(v1Id).toBe('fact-1-v1');
629
+ clockValue = 2000;
630
+ const secondOrch = buildOrchestrator({
631
+ store,
632
+ classifier: classifyFact,
633
+ extractor: extractor(() => succeed([candidate(factKind, 'fact-1', 'the sky is grey')])),
634
+ relationExtractor: relater(() => succeed([candEdge('fact-1', 'contradicts', v1Id)]))
635
+ });
636
+ expect(await secondOrch.ingestItem({ id: 'fact-1', content: 'the sky is grey' })).toSucceedAndSatisfy((r) => {
637
+ var _a;
638
+ expect(r.records[0].interlock).toBe('temporal-versioned');
639
+ expect(r.records[0].disposition).toBe('written');
640
+ expect((_a = r.records[0].record) === null || _a === void 0 ? void 0 : _a.envelope.links).toEqual([{ type: CONTRADICTS_LINK_TYPE, target: v1Id }]);
641
+ });
642
+ // The current version is the new (contradicting) one.
643
+ expect(await store.get(factKind, 'fact-1')).toSucceedAndSatisfy((rec) => expect(rec === null || rec === void 0 ? void 0 : rec.body).toBe('the sky is grey'));
644
+ // The prior version is invalidated (invalidate-don't-delete).
645
+ expect(await store.list()).toSucceedAndSatisfy((all) => {
646
+ var _a;
647
+ const v1 = all.find((rec) => rec.envelope.id === v1Id);
648
+ expect((_a = v1 === null || v1 === void 0 ? void 0 : v1.envelope.temporal) === null || _a === void 0 ? void 0 : _a.invalid_at).toBe(2000);
649
+ });
650
+ });
651
+ test('an invalidated version does not exact-dedup a later candidate that repeats its body', async () => {
652
+ const store = buildStore();
653
+ clockValue = 1000;
654
+ const o1 = buildOrchestrator({ store, classifier: classifyFact, extractor: oneFactExtractor() });
655
+ const first = await o1.ingestItem({ id: 'fact-1', content: 'blue' });
656
+ const v1Id = first.orThrow().records[0].id;
657
+ clockValue = 2000;
658
+ const o2 = buildOrchestrator({
659
+ store,
660
+ classifier: classifyFact,
661
+ extractor: extractor(() => succeed([candidate(factKind, 'fact-1', 'grey')])),
662
+ relationExtractor: relater(() => succeed([candEdge('fact-1', 'contradicts', v1Id)]))
663
+ });
664
+ (await o2.ingestItem({ id: 'fact-1', content: 'grey' })).orThrow();
665
+ // Re-introduce the ORIGINAL body: the invalidated v1 must be skipped by exact
666
+ // dedup, so this is a NEW version, not a duplicate-of.
667
+ clockValue = 3000;
668
+ const o3 = buildOrchestrator({
669
+ store,
670
+ classifier: classifyFact,
671
+ extractor: extractor(() => succeed([candidate(factKind, 'fact-1', 'blue')]))
672
+ });
673
+ expect(await o3.ingestItem({ id: 'fact-1', content: 'blue' })).toSucceedAndSatisfy((r) => {
674
+ expect(r.records[0].resolution.verdict).toBe('new');
675
+ expect(r.records[0].disposition).toBe('written');
676
+ });
677
+ });
678
+ });
679
+ describe('MemoryIngestOrchestrator — additive-provenance non-regression', () => {
680
+ test('a pre-existing record with only source provenance still loads and validates unchanged', async () => {
681
+ const store = buildStore({ files: [seedNote('legacy', 'old note', { source: 'human' })] });
682
+ // Loads at construction time.
683
+ expect(await store.getById('knowledge', 'legacy')).toSucceedAndSatisfy((rec) => {
684
+ expect(rec === null || rec === void 0 ? void 0 : rec.envelope.provenance).toEqual({ source: 'human' });
685
+ expect(rec === null || rec === void 0 ? void 0 : rec.envelope.provenance.by).toBeUndefined();
686
+ expect(rec === null || rec === void 0 ? void 0 : rec.envelope.provenance.derivedFrom).toBeUndefined();
687
+ });
688
+ // An unrelated ingest does not disturb it.
689
+ const orch = buildOrchestrator({ store });
690
+ (await orch.ingestItem({ id: 'fresh', content: 'new content' })).orThrow();
691
+ expect(await store.getById('knowledge', 'legacy')).toSucceedAndSatisfy((rec) => {
692
+ expect(rec === null || rec === void 0 ? void 0 : rec.envelope.provenance).toEqual({ source: 'human' });
693
+ });
694
+ });
695
+ });
696
+ describe('MemoryIngestOrchestrator — ingestBatch', () => {
697
+ test('ingests a batch in order', async () => {
698
+ const store = buildStore();
699
+ const orch = buildOrchestrator({ store });
700
+ const result = await orch.ingestBatch([
701
+ { id: 'doc-1', content: 'one' },
702
+ { id: 'doc-2', content: 'two' }
703
+ ]);
704
+ expect(result).toSucceedAndSatisfy((results) => {
705
+ expect(results).toHaveLength(2);
706
+ expect(results.map((r) => r.item.id)).toEqual(['doc-1', 'doc-2']);
707
+ expect(results.every((r) => r.records[0].disposition === 'written')).toBe(true);
708
+ });
709
+ });
710
+ test('aborts the batch on the first item failure', async () => {
711
+ const orch = buildOrchestrator({
712
+ store: buildStore(),
713
+ classifier: classifier((item) => item.id === 'bad' ? fail('classify bad') : succeed({ kind: noteKind }))
714
+ });
715
+ expect(await orch.ingestBatch([
716
+ { id: 'bad', content: 'one' },
717
+ { id: 'doc-2', content: 'two' }
718
+ ])).toFailWith(/classify bad/);
719
+ });
720
+ });
721
+ describe('MemoryIngestOrchestrator — store failure paths', () => {
722
+ test('a store snapshot (list) failure aborts the item', async () => {
723
+ const store = mockStore({ list: () => Promise.resolve(fail('list down')) });
724
+ const orch = buildOrchestrator({ store });
725
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'x' })).toFailWith(/failed to snapshot store.*list down/);
726
+ });
727
+ test('a store put failure surfaces as a write failure', async () => {
728
+ const store = mockStore({ put: () => Promise.resolve(fail('put kaput')) });
729
+ const orch = buildOrchestrator({ store });
730
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'x' })).toFailWith(/write failed.*put kaput/);
731
+ });
732
+ });
733
+ describe('MemoryIngestOrchestrator — optional constructor params', () => {
734
+ test('falls back to defaultCodec when no per-kind codec map is supplied', async () => {
735
+ const store = buildStore();
736
+ const orch = MemoryIngestOrchestrator.create({
737
+ store,
738
+ registry: registry(),
739
+ defaultCodec: new KnowledgeIdentityCodec(),
740
+ classifier: classifyNote,
741
+ extractor: oneNoteExtractor(),
742
+ relationExtractor: noEdges
743
+ }).orThrow();
744
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'hello' })).toSucceedAndSatisfy((r) => expect(r.records[0].disposition).toBe('written'));
745
+ });
746
+ test('honors an explicit similarityTopK and logs a captured host throw to the supplied logger', async () => {
747
+ const logger = new Logging.InMemoryLogger('detail');
748
+ const orch = MemoryIngestOrchestrator.create({
749
+ store: buildStore(),
750
+ registry: registry(),
751
+ codecs,
752
+ classifier: throwingClassifier(),
753
+ extractor: oneNoteExtractor(),
754
+ relationExtractor: noEdges,
755
+ similarityTopK: 3,
756
+ logger
757
+ }).orThrow();
758
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'x' })).toFailWith(/classifier boom/);
759
+ expect(logger.logged.some((m) => /classifier boom/.test(m))).toBe(true);
760
+ });
761
+ });
762
+ describe('MemoryIngestOrchestrator — review-punch-list fixes', () => {
763
+ test('a stored record with a non-string body fails the exact-dedup pass loudly', async () => {
764
+ const weird = {
765
+ envelope: {
766
+ id: 'weird',
767
+ entityId: 'weird',
768
+ kind: noteKind,
769
+ tags: [],
770
+ links: [],
771
+ created: 0,
772
+ updated: 0,
773
+ seq: 0,
774
+ contentHash: '',
775
+ provenance: { source: 'agent' }
776
+ },
777
+ body: 42
778
+ };
779
+ const store = mockStore({ list: () => Promise.resolve(succeed([weird])) });
780
+ const orch = buildOrchestrator({ store });
781
+ expect(await orch.ingestItem({ id: 'doc-1', content: 'hello' })).toFailWith(/stored record 'weird' has a non-string body/);
782
+ });
783
+ test('duplicate stage-5 edges are deduped on the written record', async () => {
784
+ const store = buildStore();
785
+ await putNote(store, 'doc-a', 'anchor');
786
+ const orch = buildOrchestrator({
787
+ store,
788
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'goodbye')])),
789
+ relationExtractor: relater(() => succeed([candEdge('doc-b', 'rel', 'doc-a'), candEdge('doc-b', 'rel', 'doc-a')]))
790
+ });
791
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
792
+ var _a;
793
+ expect((_a = r.records[0].record) === null || _a === void 0 ? void 0 : _a.envelope.links).toEqual([{ type: 'rel', target: 'doc-a' }]);
794
+ });
795
+ });
796
+ test('two candidates merging into the same target do not duplicate a shared edge', async () => {
797
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
798
+ const store = buildStore({ vectorIndex, embed });
799
+ await putNote(store, 'doc-a', 'apple pie');
800
+ await putNote(store, 'doc-x', 'target');
801
+ const orch = buildOrchestrator({
802
+ store,
803
+ vectorIndex,
804
+ embed,
805
+ entityResolver: resolver((__c, similar) => succeed({ verdict: 'merge-into', target: similar[0].id })),
806
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart'), candidate(noteKind, 'doc-c', 'apple tart')])),
807
+ relationExtractor: relater(() => succeed([candEdge('doc-a', 'rel', 'doc-x')]))
808
+ });
809
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceed();
810
+ expect(await store.get(noteKind, 'doc-a')).toSucceedAndSatisfy((rec) => {
811
+ expect(rec === null || rec === void 0 ? void 0 : rec.envelope.links).toEqual([{ type: 'rel', target: 'doc-x' }]);
812
+ });
813
+ });
814
+ });
815
+ describe('MemoryIngestOrchestrator — merge-into safety (second review)', () => {
816
+ // Seed a record with pre-existing tags + links under a flat codec (id === entityId).
817
+ async function putFull(store, kind, entityId, body, opts = {}) {
818
+ var _a, _b;
819
+ const rec = {
820
+ envelope: {
821
+ id: entityId,
822
+ entityId: entityId,
823
+ kind,
824
+ tags: ((_a = opts.tags) !== null && _a !== void 0 ? _a : []),
825
+ links: (_b = opts.links) !== null && _b !== void 0 ? _b : [],
826
+ created: 0,
827
+ updated: 0,
828
+ seq: 0,
829
+ contentHash: '',
830
+ provenance: { source: 'agent' }
831
+ },
832
+ body
833
+ };
834
+ (await store.put(rec)).orThrow();
835
+ }
836
+ test('merge-into UNIONs the target’s existing tags + links (never overwrites them)', async () => {
837
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
838
+ const store = buildStore({ vectorIndex, embed });
839
+ await putFull(store, noteKind, 'doc-a', 'apple pie', {
840
+ tags: ['old-tag'],
841
+ links: [{ type: 'existing', target: 'doc-z' }]
842
+ });
843
+ await putFull(store, noteKind, 'doc-x', 'target of stage-5');
844
+ const orch = buildOrchestrator({
845
+ store,
846
+ vectorIndex,
847
+ embed,
848
+ entityResolver: resolver((__c, similar) => succeed({ verdict: 'merge-into', target: similar[0].id })),
849
+ extractor: extractor(() => succeed([
850
+ candidate(noteKind, 'doc-b', 'apple tart', {
851
+ tags: ['new-tag'],
852
+ links: [{ type: 'candlink', target: 'doc-z' }]
853
+ })
854
+ ])),
855
+ relationExtractor: relater(() => succeed([candEdge('doc-a', 'stage5', 'doc-x')]))
856
+ });
857
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
858
+ expect(r.records[0].disposition).toBe('merged');
859
+ });
860
+ expect(await store.get(noteKind, 'doc-a')).toSucceedAndSatisfy((rec) => {
861
+ var _a;
862
+ // Original tag preserved AND the candidate's tag gained, each once.
863
+ expect([...((_a = rec === null || rec === void 0 ? void 0 : rec.envelope.tags) !== null && _a !== void 0 ? _a : [])].sort()).toEqual(['new-tag', 'old-tag']);
864
+ // Original link + candidate link + stage-5 edge, each exactly once.
865
+ expect(rec === null || rec === void 0 ? void 0 : rec.envelope.links).toEqual([
866
+ { type: 'existing', target: 'doc-z' },
867
+ { type: 'candlink', target: 'doc-z' },
868
+ { type: 'stage5', target: 'doc-x' }
869
+ ]);
870
+ });
871
+ });
872
+ test('merge-into a different-kind target fails loudly', async () => {
873
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
874
+ const store = buildStore({ vectorIndex, embed });
875
+ // A DIFFERENT-kind (ltm) record embedded so it surfaces as a neighbor of a note candidate.
876
+ await putFull(store, ltmKind, 'conv-1', 'apple pie');
877
+ const orch = buildOrchestrator({
878
+ store,
879
+ vectorIndex,
880
+ embed,
881
+ entityResolver: resolver((__c, similar) => succeed({ verdict: 'merge-into', target: similar[0].id })),
882
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
883
+ });
884
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/merge-into target 'conv-1' is kind 'ltm' but the candidate is kind 'note'/);
885
+ });
886
+ test('supersede with a non-existent target fails loudly', async () => {
887
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
888
+ const store = buildStore({ vectorIndex, embed });
889
+ await putFull(store, noteKind, 'doc-a', 'apple pie');
890
+ const orch = buildOrchestrator({
891
+ store,
892
+ vectorIndex,
893
+ embed,
894
+ entityResolver: resolver(() => succeed({ verdict: 'supersede', target: 'ghost' })),
895
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
896
+ });
897
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/supersede target 'ghost' does not exist/);
898
+ });
899
+ test('duplicate-of with a non-existent target fails loudly', async () => {
900
+ const vectorIndex = InMemoryCosineIndex.create().orThrow();
901
+ const store = buildStore({ vectorIndex, embed });
902
+ await putFull(store, noteKind, 'doc-a', 'apple pie');
903
+ const orch = buildOrchestrator({
904
+ store,
905
+ vectorIndex,
906
+ embed,
907
+ entityResolver: resolver(() => succeed({ verdict: 'duplicate-of', target: 'ghost' })),
908
+ extractor: extractor(() => succeed([candidate(noteKind, 'doc-b', 'apple tart')]))
909
+ });
910
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/duplicate-of target 'ghost' does not exist/);
911
+ });
912
+ });
913
+ //# sourceMappingURL=orchestrator.test.js.map