@graphrefly/ts 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/index.cjs +9015 -0
  3. package/dist/adapters/index.cjs.map +1 -0
  4. package/dist/adapters/index.d.cts +678 -0
  5. package/dist/adapters/index.d.ts +678 -0
  6. package/dist/adapters/index.js +2894 -0
  7. package/dist/adapters/index.js.map +1 -0
  8. package/dist/adapters/observe-storage.cjs +260 -0
  9. package/dist/adapters/observe-storage.cjs.map +1 -0
  10. package/dist/adapters/observe-storage.d.cts +77 -0
  11. package/dist/adapters/observe-storage.d.ts +77 -0
  12. package/dist/adapters/observe-storage.js +161 -0
  13. package/dist/adapters/observe-storage.js.map +1 -0
  14. package/dist/append-log-DisvEReb.d.cts +189 -0
  15. package/dist/append-log-DzKMmjxx.d.ts +189 -0
  16. package/dist/chunk-2ILL7HQI.js +1189 -0
  17. package/dist/chunk-2ILL7HQI.js.map +1 -0
  18. package/dist/chunk-4VLAQHZI.js +330 -0
  19. package/dist/chunk-4VLAQHZI.js.map +1 -0
  20. package/dist/chunk-6PHB5CJS.js +229 -0
  21. package/dist/chunk-6PHB5CJS.js.map +1 -0
  22. package/dist/chunk-COHO25CZ.js +2449 -0
  23. package/dist/chunk-COHO25CZ.js.map +1 -0
  24. package/dist/chunk-D6BG7U6A.js +161 -0
  25. package/dist/chunk-D6BG7U6A.js.map +1 -0
  26. package/dist/chunk-DJC4CHLQ.js +818 -0
  27. package/dist/chunk-DJC4CHLQ.js.map +1 -0
  28. package/dist/chunk-DK554R7P.js +67 -0
  29. package/dist/chunk-DK554R7P.js.map +1 -0
  30. package/dist/chunk-DKP56CSW.js +322 -0
  31. package/dist/chunk-DKP56CSW.js.map +1 -0
  32. package/dist/chunk-G4M3NHRJ.js +688 -0
  33. package/dist/chunk-G4M3NHRJ.js.map +1 -0
  34. package/dist/chunk-GAJW5I5P.js +1 -0
  35. package/dist/chunk-GAJW5I5P.js.map +1 -0
  36. package/dist/chunk-GDL26N2T.js +282 -0
  37. package/dist/chunk-GDL26N2T.js.map +1 -0
  38. package/dist/chunk-GTPCOEOZ.js +741 -0
  39. package/dist/chunk-GTPCOEOZ.js.map +1 -0
  40. package/dist/chunk-H2HTHFVN.js +1 -0
  41. package/dist/chunk-H2HTHFVN.js.map +1 -0
  42. package/dist/chunk-HDRL4VQQ.js +218 -0
  43. package/dist/chunk-HDRL4VQQ.js.map +1 -0
  44. package/dist/chunk-I3IHOHCJ.js +2267 -0
  45. package/dist/chunk-I3IHOHCJ.js.map +1 -0
  46. package/dist/chunk-JIMUDQN3.js +965 -0
  47. package/dist/chunk-JIMUDQN3.js.map +1 -0
  48. package/dist/chunk-JR4IKCR2.js +462 -0
  49. package/dist/chunk-JR4IKCR2.js.map +1 -0
  50. package/dist/chunk-K3FXTC3I.js +165 -0
  51. package/dist/chunk-K3FXTC3I.js.map +1 -0
  52. package/dist/chunk-OOEN33FB.js +65 -0
  53. package/dist/chunk-OOEN33FB.js.map +1 -0
  54. package/dist/chunk-PKVBHGBM.js +554 -0
  55. package/dist/chunk-PKVBHGBM.js.map +1 -0
  56. package/dist/chunk-RIIOUTGM.js +1857 -0
  57. package/dist/chunk-RIIOUTGM.js.map +1 -0
  58. package/dist/chunk-SCRFRCGR.js +33 -0
  59. package/dist/chunk-SCRFRCGR.js.map +1 -0
  60. package/dist/chunk-SWTLEQL6.js +53 -0
  61. package/dist/chunk-SWTLEQL6.js.map +1 -0
  62. package/dist/chunk-SZAETNNA.js +1 -0
  63. package/dist/chunk-SZAETNNA.js.map +1 -0
  64. package/dist/chunk-TEW47IVR.js +49 -0
  65. package/dist/chunk-TEW47IVR.js.map +1 -0
  66. package/dist/chunk-Y3ZLRGHC.js +1482 -0
  67. package/dist/chunk-Y3ZLRGHC.js.map +1 -0
  68. package/dist/chunk-Z2ANQ6JW.js +149 -0
  69. package/dist/chunk-Z2ANQ6JW.js.map +1 -0
  70. package/dist/codec-BB7p8fJc.d.cts +38 -0
  71. package/dist/codec-BB7p8fJc.d.ts +38 -0
  72. package/dist/composition/index.cjs +2505 -0
  73. package/dist/composition/index.cjs.map +1 -0
  74. package/dist/composition/index.d.cts +95 -0
  75. package/dist/composition/index.d.ts +95 -0
  76. package/dist/composition/index.js +19 -0
  77. package/dist/composition/index.js.map +1 -0
  78. package/dist/core/index.cjs +2475 -0
  79. package/dist/core/index.cjs.map +1 -0
  80. package/dist/core/index.d.cts +25 -0
  81. package/dist/core/index.d.ts +25 -0
  82. package/dist/core/index.js +74 -0
  83. package/dist/core/index.js.map +1 -0
  84. package/dist/cqrs/index.cjs +595 -0
  85. package/dist/cqrs/index.cjs.map +1 -0
  86. package/dist/cqrs/index.d.cts +200 -0
  87. package/dist/cqrs/index.d.ts +200 -0
  88. package/dist/cqrs/index.js +557 -0
  89. package/dist/cqrs/index.js.map +1 -0
  90. package/dist/data-structures/index.cjs +4277 -0
  91. package/dist/data-structures/index.cjs.map +1 -0
  92. package/dist/data-structures/index.d.cts +22 -0
  93. package/dist/data-structures/index.d.ts +22 -0
  94. package/dist/data-structures/index.js +31 -0
  95. package/dist/data-structures/index.js.map +1 -0
  96. package/dist/describe-BZb7AS2y.d.ts +57 -0
  97. package/dist/describe-Ciu8SUnN.d.cts +57 -0
  98. package/dist/graph/index.cjs +7832 -0
  99. package/dist/graph/index.cjs.map +1 -0
  100. package/dist/graph/index.d.cts +251 -0
  101. package/dist/graph/index.d.ts +251 -0
  102. package/dist/graph/index.js +131 -0
  103. package/dist/graph/index.js.map +1 -0
  104. package/dist/graph-DfdF9zy4.d.ts +666 -0
  105. package/dist/graph-s23RbbFO.d.cts +666 -0
  106. package/dist/index-CAEmLCYF.d.cts +166 -0
  107. package/dist/index-SnzZu3x7.d.ts +166 -0
  108. package/dist/index.cjs +15409 -0
  109. package/dist/index.cjs.map +1 -0
  110. package/dist/index.d.cts +23 -0
  111. package/dist/index.d.ts +23 -0
  112. package/dist/index.js +582 -0
  113. package/dist/index.js.map +1 -0
  114. package/dist/messages-BZqrGGm1.d.cts +55 -0
  115. package/dist/messages-BZqrGGm1.d.ts +55 -0
  116. package/dist/messaging/index.cjs +818 -0
  117. package/dist/messaging/index.cjs.map +1 -0
  118. package/dist/messaging/index.d.cts +235 -0
  119. package/dist/messaging/index.d.ts +235 -0
  120. package/dist/messaging/index.js +767 -0
  121. package/dist/messaging/index.js.map +1 -0
  122. package/dist/observe-event-log-0SVsx7JG.d.cts +88 -0
  123. package/dist/observe-event-log-Dnm76owp.d.ts +88 -0
  124. package/dist/operators/index.cjs +3774 -0
  125. package/dist/operators/index.cjs.map +1 -0
  126. package/dist/operators/index.d.cts +308 -0
  127. package/dist/operators/index.d.ts +308 -0
  128. package/dist/operators/index.js +112 -0
  129. package/dist/operators/index.js.map +1 -0
  130. package/dist/orchestration/index.cjs +3541 -0
  131. package/dist/orchestration/index.cjs.map +1 -0
  132. package/dist/orchestration/index.d.cts +302 -0
  133. package/dist/orchestration/index.d.ts +302 -0
  134. package/dist/orchestration/index.js +1004 -0
  135. package/dist/orchestration/index.js.map +1 -0
  136. package/dist/patterns/index.cjs +1045 -0
  137. package/dist/patterns/index.cjs.map +1 -0
  138. package/dist/patterns/index.d.cts +39 -0
  139. package/dist/patterns/index.d.ts +39 -0
  140. package/dist/patterns/index.js +33 -0
  141. package/dist/patterns/index.js.map +1 -0
  142. package/dist/reactive-collection-BxBqtIOE.d.cts +344 -0
  143. package/dist/reactive-collection-Cb1II1Fi.d.ts +344 -0
  144. package/dist/reactive-collection-storage-BNiEc-Gd.d.ts +217 -0
  145. package/dist/reactive-collection-storage-D-KmjE0J.d.cts +217 -0
  146. package/dist/reactive-map-BcB4KsQR.d.ts +256 -0
  147. package/dist/reactive-map-D-g3dv8I.d.cts +256 -0
  148. package/dist/read-through-B1CYPfq_.d.cts +82 -0
  149. package/dist/read-through-DwyJhGs1.d.ts +82 -0
  150. package/dist/render/index.cjs +250 -0
  151. package/dist/render/index.cjs.map +1 -0
  152. package/dist/render/index.d.cts +58 -0
  153. package/dist/render/index.d.ts +58 -0
  154. package/dist/render/index.js +20 -0
  155. package/dist/render/index.js.map +1 -0
  156. package/dist/resilience-Dig3Q7n0.d.cts +45 -0
  157. package/dist/resilience-Dig3Q7n0.d.ts +45 -0
  158. package/dist/semantic-memory-graph-BYoIlP35.d.cts +356 -0
  159. package/dist/semantic-memory-graph-CxyXLms3.d.ts +356 -0
  160. package/dist/solutions/index.cjs +3249 -0
  161. package/dist/solutions/index.cjs.map +1 -0
  162. package/dist/solutions/index.d.cts +520 -0
  163. package/dist/solutions/index.d.ts +520 -0
  164. package/dist/solutions/index.js +31 -0
  165. package/dist/solutions/index.js.map +1 -0
  166. package/dist/sources/browser.cjs +3095 -0
  167. package/dist/sources/browser.cjs.map +1 -0
  168. package/dist/sources/browser.d.cts +39 -0
  169. package/dist/sources/browser.d.ts +39 -0
  170. package/dist/sources/browser.js +137 -0
  171. package/dist/sources/browser.js.map +1 -0
  172. package/dist/sources/index.cjs +3021 -0
  173. package/dist/sources/index.cjs.map +1 -0
  174. package/dist/sources/index.d.cts +7 -0
  175. package/dist/sources/index.d.ts +7 -0
  176. package/dist/sources/index.js +63 -0
  177. package/dist/sources/index.js.map +1 -0
  178. package/dist/sources/node.cjs +675 -0
  179. package/dist/sources/node.cjs.map +1 -0
  180. package/dist/sources/node.d.cts +109 -0
  181. package/dist/sources/node.d.ts +109 -0
  182. package/dist/sources/node.js +639 -0
  183. package/dist/sources/node.js.map +1 -0
  184. package/dist/storage/browser.cjs +777 -0
  185. package/dist/storage/browser.cjs.map +1 -0
  186. package/dist/storage/browser.d.cts +40 -0
  187. package/dist/storage/browser.d.ts +40 -0
  188. package/dist/storage/browser.js +275 -0
  189. package/dist/storage/browser.js.map +1 -0
  190. package/dist/storage/index.cjs +1989 -0
  191. package/dist/storage/index.cjs.map +1 -0
  192. package/dist/storage/index.d.cts +92 -0
  193. package/dist/storage/index.d.ts +92 -0
  194. package/dist/storage/index.js +161 -0
  195. package/dist/storage/index.js.map +1 -0
  196. package/dist/storage/node.cjs +898 -0
  197. package/dist/storage/node.cjs.map +1 -0
  198. package/dist/storage/node.d.cts +66 -0
  199. package/dist/storage/node.d.ts +66 -0
  200. package/dist/storage/node.js +402 -0
  201. package/dist/storage/node.js.map +1 -0
  202. package/dist/testing/index.cjs +95 -0
  203. package/dist/testing/index.cjs.map +1 -0
  204. package/dist/testing/index.d.cts +20 -0
  205. package/dist/testing/index.d.ts +20 -0
  206. package/dist/testing/index.js +8 -0
  207. package/dist/testing/index.js.map +1 -0
  208. package/dist/types-bNMSWKqF.d.cts +732 -0
  209. package/dist/types-h12mNYbq.d.ts +732 -0
  210. package/package.json +250 -0
@@ -0,0 +1,1045 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/patterns/index.ts
21
+ var patterns_exports = {};
22
+ __export(patterns_exports, {
23
+ admissionFilter3D: () => admissionFilter3D,
24
+ admissionScored: () => admissionScored,
25
+ cosineSimilarity: () => cosineSimilarity,
26
+ filterMemoryFragments: () => filterMemoryFragments,
27
+ isMemoryFragment: () => isMemoryFragment,
28
+ knowledgeGraphReducerBundle: () => knowledgeGraphReducerBundle,
29
+ memoryFragmentMatchesQuery: () => memoryFragmentMatchesQuery,
30
+ memoryFragmentValidAt: () => memoryFragmentValidAt,
31
+ memoryRetrievalBundle: () => memoryRetrievalBundle,
32
+ profileSummary: () => profileSummary,
33
+ shardByTenant: () => shardByTenant,
34
+ validateMemoryFragment: () => validateMemoryFragment
35
+ });
36
+ module.exports = __toCommonJS(patterns_exports);
37
+
38
+ // src/patterns/inspection.ts
39
+ function profileSummary(graph, opts = {}) {
40
+ const profile = graph.profile();
41
+ const described = graph.describe();
42
+ const nodeIds = new Set(described.nodes.map((node) => node.id));
43
+ for (const id of Object.keys(profile.nodes)) nodeIds.add(id);
44
+ const byStatus = {};
45
+ const hotNodes = [];
46
+ for (const path of [...nodeIds].sort()) {
47
+ const nodeProfile = profile.nodes[path];
48
+ if (nodeProfile === void 0) continue;
49
+ byStatus[nodeProfile.status] = (byStatus[nodeProfile.status] ?? 0) + 1;
50
+ hotNodes.push({
51
+ path,
52
+ invokes: nodeProfile.invokes,
53
+ totalDurationNs: nodeProfile.totalDurationNs,
54
+ lastDurationNs: nodeProfile.lastDurationNs,
55
+ status: nodeProfile.status
56
+ });
57
+ }
58
+ hotNodes.sort((a, b) => b.invokes - a.invokes || a.path.localeCompare(b.path));
59
+ return {
60
+ nodeCount: nodeIds.size,
61
+ totalInvokes: profile.totalInvokes,
62
+ byStatus,
63
+ hotNodes: hotNodes.slice(0, opts.limit ?? hotNodes.length)
64
+ };
65
+ }
66
+
67
+ // src/patterns/semantic-memory.ts
68
+ function cosineSimilarity(a, b) {
69
+ const n = Math.max(a.length, b.length);
70
+ let dot = 0;
71
+ let na = 0;
72
+ let nb = 0;
73
+ for (let i = 0; i < n; i += 1) {
74
+ const av = a[i] ?? 0;
75
+ const bv = b[i] ?? 0;
76
+ dot += av * bv;
77
+ na += av * av;
78
+ nb += bv * bv;
79
+ }
80
+ if (na === 0 || nb === 0) return 0;
81
+ const score = dot / Math.sqrt(na * nb);
82
+ return Number.isFinite(score) ? score : 0;
83
+ }
84
+ function memoryFragmentValidAt(fragment, asOf) {
85
+ if (asOf === void 0) return fragment.validTo === void 0 && fragment.validFrom === void 0;
86
+ if (fragment.validFrom !== void 0 && fragment.validFrom > asOf) return false;
87
+ if (fragment.validTo !== void 0 && fragment.validTo <= asOf) return false;
88
+ return true;
89
+ }
90
+ function memoryFragmentMatchesQuery(fragment, query = {}) {
91
+ if (!memoryFragmentValidAt(fragment, query.asOf)) return false;
92
+ if (query.minConfidence !== void 0 && fragment.confidence < query.minConfidence) return false;
93
+ if (query.tags && query.tags.length > 0 && !query.tags.some((tag) => fragment.tags.includes(tag))) {
94
+ return false;
95
+ }
96
+ return true;
97
+ }
98
+ function filterMemoryFragments(fragments, query = {}) {
99
+ const results = [...fragments].filter((fragment) => memoryFragmentMatchesQuery(fragment, query));
100
+ results.sort((a, b) => b.confidence - a.confidence || compareBigIntDesc(a.tNs, b.tNs));
101
+ return query.limit === void 0 ? results : results.slice(0, Math.max(0, query.limit));
102
+ }
103
+ function validateMemoryFragment(value) {
104
+ const errors = [];
105
+ if (typeof value !== "object" || value === null) {
106
+ return { ok: false, errors: ["fragment must be an object"] };
107
+ }
108
+ const fragment = value;
109
+ if (typeof fragment.id !== "string" || fragment.id.length === 0) {
110
+ errors.push("id must be a non-empty string");
111
+ }
112
+ if (!Object.hasOwn(fragment, "payload")) {
113
+ errors.push("payload must be present");
114
+ }
115
+ if (typeof fragment.tNs !== "bigint") {
116
+ errors.push("tNs must be a bigint");
117
+ }
118
+ const confidence = fragment.confidence;
119
+ if (!Number.isFinite(confidence) || confidence === void 0 || confidence < 0 || confidence > 1) {
120
+ errors.push("confidence must be a finite number in [0, 1]");
121
+ }
122
+ if (!isDenseArrayOf(fragment.tags, (tag) => typeof tag === "string")) {
123
+ errors.push("tags must be a readonly string array");
124
+ }
125
+ if (!isDenseArrayOf(fragment.sources, (source) => typeof source === "string")) {
126
+ errors.push("sources must be a readonly string array");
127
+ }
128
+ if (fragment.validFrom !== void 0 && typeof fragment.validFrom !== "bigint") {
129
+ errors.push("validFrom must be a bigint when present");
130
+ }
131
+ if (fragment.validTo !== void 0 && typeof fragment.validTo !== "bigint") {
132
+ errors.push("validTo must be a bigint when present");
133
+ }
134
+ if (typeof fragment.validFrom === "bigint" && typeof fragment.validTo === "bigint" && fragment.validFrom >= fragment.validTo) {
135
+ errors.push("validFrom must be earlier than validTo");
136
+ }
137
+ if (fragment.embedding !== void 0 && !isDenseArrayOf(
138
+ fragment.embedding,
139
+ (component) => Number.isFinite(component)
140
+ )) {
141
+ errors.push("embedding must be a finite number array when present");
142
+ }
143
+ if (fragment.parentFragmentId !== void 0 && typeof fragment.parentFragmentId !== "string") {
144
+ errors.push("parentFragmentId must be a string when present");
145
+ }
146
+ if (fragment.provenance !== void 0 && typeof fragment.provenance !== "string") {
147
+ errors.push("provenance must be a string when present");
148
+ }
149
+ return { ok: errors.length === 0, errors };
150
+ }
151
+ function isMemoryFragment(value) {
152
+ return validateMemoryFragment(value).ok;
153
+ }
154
+ function admissionScored(opts) {
155
+ const thresholds = opts.thresholds ?? {};
156
+ return (raw) => {
157
+ const scores = opts.scoreFn(raw);
158
+ for (const dim of Object.keys(thresholds)) {
159
+ const min = thresholds[dim];
160
+ if (min === void 0) continue;
161
+ const score = scores[dim];
162
+ const safe = Number.isFinite(score) ? score : Number.NEGATIVE_INFINITY;
163
+ if (safe < min) return false;
164
+ }
165
+ return true;
166
+ };
167
+ }
168
+ function admissionFilter3D(opts) {
169
+ return (raw) => {
170
+ const scores = opts.scoreFn(raw);
171
+ if (!scoreAtLeast(scores.persistence, opts.persistenceThreshold ?? 0.3)) return false;
172
+ if (!scoreAtLeast(scores.personalValue, opts.personalValueThreshold ?? 0.3)) return false;
173
+ if (!opts.requireStructured) return true;
174
+ return scoreAtLeast(scores.structure, Number.MIN_VALUE);
175
+ };
176
+ }
177
+ function shardByTenant(tenantOf, opts = {}) {
178
+ if (opts.tenants && opts.tenants.length > 0) {
179
+ const tenants = [...new Set(opts.tenants)];
180
+ const index = new Map(tenants.map((tenant, i) => [tenant, i]));
181
+ const overflow = tenants.length;
182
+ return {
183
+ shardBy: (fragment) => index.get(tenantOf(fragment)) ?? overflow,
184
+ shardCount: tenants.length + 1
185
+ };
186
+ }
187
+ const configuredShardCount = opts.shardCount ?? 4;
188
+ const shardCount = Number.isSafeInteger(configuredShardCount) ? Math.max(1, configuredShardCount) : 4;
189
+ return { shardBy: (fragment) => tenantOf(fragment), shardCount };
190
+ }
191
+ function compareBigIntDesc(a, b) {
192
+ if (a === b) return 0;
193
+ return a > b ? -1 : 1;
194
+ }
195
+ function isDenseArrayOf(value, predicate) {
196
+ if (!Array.isArray(value)) return false;
197
+ for (let i = 0; i < value.length; i += 1) {
198
+ if (!Object.hasOwn(value, i) || !predicate(value[i])) return false;
199
+ }
200
+ return true;
201
+ }
202
+ function scoreAtLeast(score, min) {
203
+ return Number.isFinite(score) && score >= min;
204
+ }
205
+
206
+ // src/protocol/messages.ts
207
+ var SENTINEL = void 0;
208
+
209
+ // src/ctx/types.ts
210
+ var CTX_DEP_CACHE = /* @__PURE__ */ Symbol("graphrefly.ctx.depCache");
211
+ function depWaves(ctx, depIndex) {
212
+ return ctx.waveData[depIndex] ?? [];
213
+ }
214
+ function depBatch(ctx, depIndex) {
215
+ const waves = depWaves(ctx, depIndex);
216
+ if (waves.length === 0) return null;
217
+ const flattened = waves.flat().filter((v) => v !== SENTINEL);
218
+ return flattened.length === 0 ? [] : flattened;
219
+ }
220
+ function depLatest(ctx, depIndex) {
221
+ return ctx[CTX_DEP_CACHE]?.latest[depIndex];
222
+ }
223
+
224
+ // src/patterns/semantic-memory-graph.ts
225
+ function memoryRetrievalBundle(graph, opts) {
226
+ const name = opts.name ?? "memoryRetrieval";
227
+ const { fragments, query } = opts;
228
+ const snapshot = graph.node(
229
+ [fragments, query],
230
+ (ctx) => {
231
+ const state = ctx.state.get() ?? { evaluation: 0 };
232
+ state.evaluation += 1;
233
+ const rawFragments = depLatest(ctx, 0);
234
+ const rawQuery = depLatest(ctx, 1);
235
+ const queryValidation = validateMemoryRetrievalQuery(rawQuery);
236
+ const currentQuery = queryValidation.query;
237
+ const valid = [];
238
+ const seenIds = /* @__PURE__ */ new Set();
239
+ const errors = [...queryValidation.errors];
240
+ if (!Array.isArray(rawFragments)) {
241
+ errors.push({
242
+ code: "invalid-fragments-input",
243
+ message: "memoryRetrievalBundle: fragments input must be an array",
244
+ fragment: rawFragments
245
+ });
246
+ } else {
247
+ const length = safeArrayLength(rawFragments);
248
+ if (length === void 0) {
249
+ errors.push({
250
+ code: "invalid-fragments-input",
251
+ message: "memoryRetrievalBundle: fragments input length could not be read",
252
+ fragment: rawFragments
253
+ });
254
+ }
255
+ for (let i = 0; i < (length ?? 0); i += 1) {
256
+ const result = validateAndSnapshotFragment(rawFragments, i);
257
+ if (result.error !== void 0) {
258
+ errors.push(result.error);
259
+ continue;
260
+ }
261
+ const fragment = result.fragment;
262
+ if (seenIds.has(fragment.id)) {
263
+ errors.push({
264
+ code: "duplicate-fragment-id",
265
+ message: "memoryRetrievalBundle: duplicate fragment id",
266
+ index: i,
267
+ fragment,
268
+ validationErrors: [`duplicate fragment id '${fragment.id}'`]
269
+ });
270
+ continue;
271
+ }
272
+ seenIds.add(fragment.id);
273
+ valid.push(fragment);
274
+ }
275
+ }
276
+ const ranked = errors.some((error) => !isRecoverableFragmentError(error)) ? [] : rankFragments(valid, currentQuery);
277
+ const cursor = Object.freeze({
278
+ evaluation: state.evaluation,
279
+ validFragments: valid.length,
280
+ invalidFragments: errors.filter(
281
+ (error) => error.code === "invalid-fragment" || error.code === "duplicate-fragment-id"
282
+ ).length,
283
+ resultCount: ranked.length
284
+ });
285
+ ctx.state.set(state);
286
+ const answer = Object.freeze({
287
+ query: currentQuery,
288
+ results: Object.freeze(ranked)
289
+ });
290
+ const status = Object.freeze({
291
+ state: statusState(errors, ranked.length),
292
+ query: currentQuery,
293
+ cursor
294
+ });
295
+ const indexed = Object.freeze({
296
+ ids: Object.freeze(valid.map((fragment) => fragment.id)),
297
+ byId: indexById(valid),
298
+ cursor
299
+ });
300
+ const errorFacts = Object.freeze(
301
+ errors.map(
302
+ (error) => Object.freeze({
303
+ ...error,
304
+ ...error.validationErrors === void 0 ? {} : { validationErrors: Object.freeze([...error.validationErrors]) },
305
+ cursor
306
+ })
307
+ )
308
+ );
309
+ ctx.down([
310
+ [
311
+ "DATA",
312
+ Object.freeze({
313
+ fragments: Object.freeze([...valid]),
314
+ indexed,
315
+ ranked: answer,
316
+ status,
317
+ errors: errorFacts,
318
+ cursor
319
+ })
320
+ ]
321
+ ]);
322
+ },
323
+ {
324
+ name: `${name}/snapshot`,
325
+ factory: "memoryRetrievalSnapshot",
326
+ completeWhenDepsComplete: false,
327
+ errorWhenDepsError: false
328
+ }
329
+ );
330
+ return {
331
+ input: { fragments, query },
332
+ snapshot,
333
+ fragments: retrievalProjection(
334
+ graph,
335
+ snapshot,
336
+ `${name}/fragments`,
337
+ "memoryRetrievalFragments",
338
+ (fact) => fact.fragments
339
+ ),
340
+ indexed: retrievalProjection(
341
+ graph,
342
+ snapshot,
343
+ `${name}/indexed`,
344
+ "memoryRetrievalIndexed",
345
+ (fact) => fact.indexed
346
+ ),
347
+ ranked: retrievalProjection(
348
+ graph,
349
+ snapshot,
350
+ `${name}/ranked`,
351
+ "memoryRetrievalRanked",
352
+ (fact) => fact.ranked
353
+ ),
354
+ status: retrievalProjection(
355
+ graph,
356
+ snapshot,
357
+ `${name}/status`,
358
+ "memoryRetrievalStatus",
359
+ (fact) => fact.status
360
+ ),
361
+ errors: retrievalProjection(
362
+ graph,
363
+ snapshot,
364
+ `${name}/errors`,
365
+ "memoryRetrievalErrors",
366
+ (fact) => fact.errors
367
+ ),
368
+ cursor: retrievalProjection(
369
+ graph,
370
+ snapshot,
371
+ `${name}/cursor`,
372
+ "memoryRetrievalCursor",
373
+ (fact) => fact.cursor
374
+ )
375
+ };
376
+ }
377
+ function knowledgeGraphReducerBundle(graph, opts) {
378
+ const name = opts.name ?? "knowledgeGraph";
379
+ const deps = opts.policy === void 0 ? [opts.assertions] : [opts.assertions, opts.policy];
380
+ const snapshot = graph.node(
381
+ deps,
382
+ (ctx) => {
383
+ const state = ctx.state.get() ?? { evaluation: 0 };
384
+ state.evaluation += 1;
385
+ const policy = validateKnowledgeGraphPolicy(
386
+ opts.policy === void 0 ? void 0 : depLatest(ctx, 1)
387
+ );
388
+ const reduced = reduceKnowledgeAssertions(depLatest(ctx, 0), policy.policy);
389
+ const pendingErrors = [...policy.errors, ...reduced.errors];
390
+ const cursor = Object.freeze({
391
+ evaluation: state.evaluation,
392
+ validAssertions: reduced.assertions.length,
393
+ invalidAssertions: reduced.invalidAssertions,
394
+ entityCount: reduced.entities.length,
395
+ relationCount: reduced.relations.length,
396
+ predicateCount: reduced.topics.length
397
+ });
398
+ const errors = Object.freeze(
399
+ pendingErrors.map(
400
+ (error) => Object.freeze({
401
+ ...error,
402
+ ...error.validationErrors === void 0 ? {} : { validationErrors: Object.freeze([...error.validationErrors]) },
403
+ cursor
404
+ })
405
+ )
406
+ );
407
+ const status = Object.freeze({
408
+ state: reduced.assertions.length === 0 && errors.length === 0 ? "empty" : errors.length === 0 ? "ready" : reduced.assertions.length > 0 ? "partial" : "error",
409
+ cursor
410
+ });
411
+ ctx.state.set(state);
412
+ ctx.down([
413
+ [
414
+ "DATA",
415
+ Object.freeze({
416
+ assertions: Object.freeze(reduced.assertions),
417
+ entities: Object.freeze(reduced.entities),
418
+ relations: Object.freeze(reduced.relations),
419
+ topics: Object.freeze(reduced.topics),
420
+ index: reduced.index,
421
+ status,
422
+ errors,
423
+ cursor
424
+ })
425
+ ]
426
+ ]);
427
+ },
428
+ {
429
+ name: `${name}/snapshot`,
430
+ factory: "knowledgeGraphReducerSnapshot",
431
+ completeWhenDepsComplete: false,
432
+ errorWhenDepsError: false
433
+ }
434
+ );
435
+ return {
436
+ input: {
437
+ assertions: opts.assertions,
438
+ ...opts.policy === void 0 ? {} : { policy: opts.policy }
439
+ },
440
+ snapshot,
441
+ assertions: kgProjection(
442
+ graph,
443
+ snapshot,
444
+ `${name}/assertions`,
445
+ "knowledgeGraphAssertions",
446
+ (fact) => fact.assertions
447
+ ),
448
+ entities: kgProjection(
449
+ graph,
450
+ snapshot,
451
+ `${name}/entities`,
452
+ "knowledgeGraphEntities",
453
+ (fact) => fact.entities
454
+ ),
455
+ relations: kgProjection(
456
+ graph,
457
+ snapshot,
458
+ `${name}/relations`,
459
+ "knowledgeGraphRelations",
460
+ (fact) => fact.relations
461
+ ),
462
+ topics: kgProjection(
463
+ graph,
464
+ snapshot,
465
+ `${name}/topics`,
466
+ "knowledgeGraphTopics",
467
+ (fact) => fact.topics
468
+ ),
469
+ index: kgProjection(
470
+ graph,
471
+ snapshot,
472
+ `${name}/index`,
473
+ "knowledgeGraphIndex",
474
+ (fact) => fact.index
475
+ ),
476
+ status: kgProjection(
477
+ graph,
478
+ snapshot,
479
+ `${name}/status`,
480
+ "knowledgeGraphStatus",
481
+ (fact) => fact.status
482
+ ),
483
+ errors: kgProjection(
484
+ graph,
485
+ snapshot,
486
+ `${name}/errors`,
487
+ "knowledgeGraphErrors",
488
+ (fact) => fact.errors
489
+ ),
490
+ cursor: kgProjection(
491
+ graph,
492
+ snapshot,
493
+ `${name}/cursor`,
494
+ "knowledgeGraphCursor",
495
+ (fact) => fact.cursor
496
+ )
497
+ };
498
+ }
499
+ function retrievalProjection(graph, snapshot, name, factory, select) {
500
+ return graph.node(
501
+ [snapshot],
502
+ (ctx) => {
503
+ for (const raw of depBatch(ctx, 0) ?? []) {
504
+ const fact = raw;
505
+ const selected = select(fact);
506
+ if (selected !== void 0) ctx.down([["DATA", selected]]);
507
+ }
508
+ },
509
+ {
510
+ name,
511
+ factory,
512
+ completeWhenDepsComplete: false,
513
+ errorWhenDepsError: false
514
+ }
515
+ );
516
+ }
517
+ function kgProjection(graph, snapshot, name, factory, select) {
518
+ return graph.node(
519
+ [snapshot],
520
+ (ctx) => {
521
+ for (const raw of depBatch(ctx, 0) ?? []) {
522
+ ctx.down([["DATA", select(raw)]]);
523
+ }
524
+ },
525
+ {
526
+ name,
527
+ factory,
528
+ completeWhenDepsComplete: false,
529
+ errorWhenDepsError: false
530
+ }
531
+ );
532
+ }
533
+ function validateKnowledgeGraphPolicy(value) {
534
+ if (value === void 0) return { policy: void 0, errors: [] };
535
+ if (!isPlainObject(value)) {
536
+ return {
537
+ errors: [
538
+ {
539
+ code: "invalid-policy",
540
+ message: "knowledgeGraphReducerBundle: policy must be an object",
541
+ assertion: value
542
+ }
543
+ ]
544
+ };
545
+ }
546
+ const errors = [];
547
+ const policy = value;
548
+ if (policy.allowedPredicates !== void 0 && !isDenseArrayOf2(policy.allowedPredicates, (item) => typeof item === "string")) {
549
+ errors.push("allowedPredicates must be a readonly string array");
550
+ }
551
+ if (policy.requireEntityTypes !== void 0 && typeof policy.requireEntityTypes !== "boolean") {
552
+ errors.push("requireEntityTypes must be a boolean when present");
553
+ }
554
+ if (errors.length > 0) {
555
+ return {
556
+ errors: [
557
+ {
558
+ code: "invalid-policy",
559
+ message: "knowledgeGraphReducerBundle: policy is invalid",
560
+ assertion: value,
561
+ validationErrors: Object.freeze(errors)
562
+ }
563
+ ]
564
+ };
565
+ }
566
+ return {
567
+ policy: Object.freeze({
568
+ ...policy.allowedPredicates === void 0 ? {} : { allowedPredicates: Object.freeze([...policy.allowedPredicates]) },
569
+ ...policy.requireEntityTypes === void 0 ? {} : { requireEntityTypes: policy.requireEntityTypes }
570
+ }),
571
+ errors: []
572
+ };
573
+ }
574
+ function reduceKnowledgeAssertions(value, policy) {
575
+ const assertions = [];
576
+ const errors = [];
577
+ const seenAssertions = /* @__PURE__ */ new Set();
578
+ if (!Array.isArray(value)) {
579
+ return {
580
+ assertions,
581
+ entities: [],
582
+ relations: [],
583
+ topics: [],
584
+ index: emptyKnowledgeGraphIndex(),
585
+ errors: [
586
+ {
587
+ code: "invalid-assertions-input",
588
+ message: "knowledgeGraphReducerBundle: assertions input must be an array",
589
+ assertion: value
590
+ }
591
+ ],
592
+ invalidAssertions: 0
593
+ };
594
+ }
595
+ const length = safeArrayLength(value);
596
+ if (length === void 0) {
597
+ return {
598
+ assertions,
599
+ entities: [],
600
+ relations: [],
601
+ topics: [],
602
+ index: emptyKnowledgeGraphIndex(),
603
+ errors: [
604
+ {
605
+ code: "invalid-assertions-input",
606
+ message: "knowledgeGraphReducerBundle: assertions input length could not be read",
607
+ assertion: value
608
+ }
609
+ ],
610
+ invalidAssertions: 0
611
+ };
612
+ }
613
+ for (let i = 0; i < length; i += 1) {
614
+ const result = validateKnowledgeAssertion(value[i], i, policy);
615
+ if (result.error !== void 0) {
616
+ errors.push(result.error);
617
+ continue;
618
+ }
619
+ const assertion = result.assertion;
620
+ if (seenAssertions.has(assertion.id)) {
621
+ errors.push({
622
+ code: "duplicate-assertion-id",
623
+ message: "knowledgeGraphReducerBundle: duplicate assertion id",
624
+ index: i,
625
+ assertionId: assertion.id,
626
+ assertion,
627
+ validationErrors: Object.freeze([`duplicate assertion id '${assertion.id}'`])
628
+ });
629
+ continue;
630
+ }
631
+ seenAssertions.add(assertion.id);
632
+ assertions.push(assertion);
633
+ }
634
+ const materialized = materializeKnowledgeGraph(assertions);
635
+ return {
636
+ assertions: Object.freeze(assertions),
637
+ ...materialized,
638
+ errors,
639
+ invalidAssertions: errors.filter((error) => error.code !== "invalid-policy").length
640
+ };
641
+ }
642
+ function validateKnowledgeAssertion(value, index, policy) {
643
+ if (!isPlainObject(value)) {
644
+ return invalidKnowledgeAssertion(index, value, ["assertion must be an object"]);
645
+ }
646
+ const raw = value;
647
+ const errors = [];
648
+ if (!isNonEmptyString(raw.id)) errors.push("id must be a non-empty string");
649
+ if (!isKnowledgeSubject(raw.subject)) errors.push("subject.id must be a non-empty string");
650
+ if (!isNonEmptyString(raw.predicate)) errors.push("predicate must be a non-empty string");
651
+ if (!isKnowledgeObject(raw.object)) errors.push("object shape is invalid");
652
+ if (raw.confidence !== void 0 && (!Number.isFinite(raw.confidence) || raw.confidence < 0 || raw.confidence > 1)) {
653
+ errors.push("confidence must be a finite number in [0, 1] when present");
654
+ }
655
+ if (raw.sources !== void 0 && !isDenseArrayOf2(raw.sources, isNonEmptyString)) {
656
+ errors.push("sources must be a readonly non-empty string array when present");
657
+ }
658
+ if (policy?.allowedPredicates !== void 0 && !policy.allowedPredicates.includes(raw.predicate ?? "")) {
659
+ errors.push(`predicate '${String(raw.predicate)}' is not allowed by policy`);
660
+ }
661
+ if (policy?.requireEntityTypes === true) {
662
+ if (isKnowledgeSubject(raw.subject) && raw.subject.type === void 0) {
663
+ errors.push("subject.type is required by policy");
664
+ }
665
+ if (isKnowledgeObject(raw.object) && raw.object.kind === "entity" && raw.object.type === void 0) {
666
+ errors.push("object.type is required by policy for entity objects");
667
+ }
668
+ }
669
+ if (errors.length > 0) {
670
+ return invalidKnowledgeAssertion(index, value, errors, raw.id);
671
+ }
672
+ return {
673
+ assertion: Object.freeze({
674
+ id: raw.id,
675
+ ...raw.recordId === void 0 ? {} : { recordId: raw.recordId },
676
+ ...raw.fragmentId === void 0 ? {} : { fragmentId: raw.fragmentId },
677
+ subject: snapshotSubject(raw.subject),
678
+ predicate: raw.predicate,
679
+ object: snapshotObject(raw.object),
680
+ ...raw.confidence === void 0 ? {} : { confidence: raw.confidence },
681
+ sources: Object.freeze([...raw.sources ?? []]),
682
+ ...raw.provenance === void 0 ? {} : { provenance: raw.provenance }
683
+ })
684
+ };
685
+ }
686
+ function invalidKnowledgeAssertion(index, assertion, validationErrors, assertionId) {
687
+ return {
688
+ error: {
689
+ code: "invalid-assertion",
690
+ message: "knowledgeGraphReducerBundle: assertion is invalid",
691
+ index,
692
+ assertionId: typeof assertionId === "string" ? assertionId : void 0,
693
+ assertion,
694
+ validationErrors: Object.freeze([...validationErrors])
695
+ }
696
+ };
697
+ }
698
+ function materializeKnowledgeGraph(assertions) {
699
+ const entityAssertions = /* @__PURE__ */ new Map();
700
+ const topics = /* @__PURE__ */ new Map();
701
+ const relations = [];
702
+ for (const assertion of assertions) {
703
+ const subject = touchEntity(entityAssertions, assertion.subject.id, assertion.subject.type);
704
+ subject.assertionIds.add(assertion.id);
705
+ subject.subjectAssertionIds.add(assertion.id);
706
+ let topic = topics.get(assertion.predicate);
707
+ if (topic === void 0) {
708
+ topic = { assertionIds: /* @__PURE__ */ new Set(), entityIds: /* @__PURE__ */ new Set() };
709
+ topics.set(assertion.predicate, topic);
710
+ }
711
+ topic.assertionIds.add(assertion.id);
712
+ topic.entityIds.add(assertion.subject.id);
713
+ if (assertion.object.kind === "entity") {
714
+ const object = touchEntity(entityAssertions, assertion.object.id, assertion.object.type);
715
+ object.assertionIds.add(assertion.id);
716
+ object.objectAssertionIds.add(assertion.id);
717
+ topic.entityIds.add(assertion.object.id);
718
+ }
719
+ relations.push(
720
+ Object.freeze({
721
+ assertionId: assertion.id,
722
+ subject: assertion.subject,
723
+ predicate: assertion.predicate,
724
+ object: assertion.object,
725
+ ...assertion.confidence === void 0 ? {} : { confidence: assertion.confidence },
726
+ sources: Object.freeze([...assertion.sources ?? []]),
727
+ ...assertion.provenance === void 0 ? {} : { provenance: assertion.provenance }
728
+ })
729
+ );
730
+ }
731
+ const entities = [...entityAssertions.entries()].map(
732
+ ([id, entity]) => Object.freeze({
733
+ id,
734
+ ...entity.type === void 0 ? {} : { type: entity.type },
735
+ assertionIds: freezeSortedSet(entity.assertionIds),
736
+ subjectAssertionIds: freezeSortedSet(entity.subjectAssertionIds),
737
+ objectAssertionIds: freezeSortedSet(entity.objectAssertionIds)
738
+ })
739
+ );
740
+ entities.sort((a, b) => compareString(a.id, b.id));
741
+ relations.sort((a, b) => compareString(a.assertionId, b.assertionId));
742
+ const topicFacts = [...topics.entries()].map(
743
+ ([predicate, topic]) => Object.freeze({
744
+ predicate,
745
+ assertionIds: freezeSortedSet(topic.assertionIds),
746
+ entityIds: freezeSortedSet(topic.entityIds)
747
+ })
748
+ );
749
+ topicFacts.sort((a, b) => compareString(a.predicate, b.predicate));
750
+ const index = Object.freeze({
751
+ assertionIds: Object.freeze(assertions.map((assertion) => assertion.id).sort(compareString)),
752
+ entityIds: Object.freeze(entities.map((entity) => entity.id)),
753
+ relationIds: Object.freeze(relations.map((relation) => relation.assertionId)),
754
+ predicates: Object.freeze(topicFacts.map((topic) => topic.predicate))
755
+ });
756
+ return {
757
+ entities: Object.freeze(entities),
758
+ relations: Object.freeze(relations),
759
+ topics: Object.freeze(topicFacts),
760
+ index
761
+ };
762
+ }
763
+ function touchEntity(entities, id, type) {
764
+ let entity = entities.get(id);
765
+ if (entity === void 0) {
766
+ entity = {
767
+ ...type === void 0 ? {} : { type },
768
+ assertionIds: /* @__PURE__ */ new Set(),
769
+ subjectAssertionIds: /* @__PURE__ */ new Set(),
770
+ objectAssertionIds: /* @__PURE__ */ new Set()
771
+ };
772
+ entities.set(id, entity);
773
+ } else if (entity.type === void 0 && type !== void 0) {
774
+ entity.type = type;
775
+ }
776
+ return entity;
777
+ }
778
+ function emptyKnowledgeGraphIndex() {
779
+ return Object.freeze({
780
+ assertionIds: Object.freeze([]),
781
+ entityIds: Object.freeze([]),
782
+ relationIds: Object.freeze([]),
783
+ predicates: Object.freeze([])
784
+ });
785
+ }
786
+ function snapshotSubject(subject) {
787
+ return Object.freeze({
788
+ id: subject.id,
789
+ ...subject.type === void 0 ? {} : { type: subject.type }
790
+ });
791
+ }
792
+ function snapshotObject(object) {
793
+ return object.kind === "entity" ? Object.freeze({
794
+ kind: "entity",
795
+ id: object.id,
796
+ ...object.type === void 0 ? {} : { type: object.type }
797
+ }) : Object.freeze({
798
+ kind: "value",
799
+ value: object.value,
800
+ ...object.valueType === void 0 ? {} : { valueType: object.valueType }
801
+ });
802
+ }
803
+ function isKnowledgeSubject(value) {
804
+ return isPlainObject(value) && isNonEmptyString(value.id) && (value.type === void 0 || isNonEmptyString(value.type));
805
+ }
806
+ function isKnowledgeObject(value) {
807
+ if (!isPlainObject(value)) return false;
808
+ if (value.kind === "entity") {
809
+ return isNonEmptyString(value.id) && (value.type === void 0 || isNonEmptyString(value.type));
810
+ }
811
+ if (value.kind !== "value") return false;
812
+ return isStrictJsonValue(value.value) && (value.valueType === void 0 || isNonEmptyString(value.valueType));
813
+ }
814
+ function isStrictJsonValue(value) {
815
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
816
+ if (typeof value === "number") return Number.isFinite(value);
817
+ if (Array.isArray(value)) {
818
+ for (let i = 0; i < value.length; i += 1) {
819
+ if (!Object.hasOwn(value, i) || !isStrictJsonValue(value[i])) return false;
820
+ }
821
+ return true;
822
+ }
823
+ if (!isPlainObject(value)) return false;
824
+ for (const key of Object.keys(value)) {
825
+ if (!isStrictJsonValue(value[key])) return false;
826
+ }
827
+ return Object.getOwnPropertySymbols(value).length === 0;
828
+ }
829
+ function freezeSortedSet(value) {
830
+ return Object.freeze([...value].sort(compareString));
831
+ }
832
+ function rankFragments(fragments, query) {
833
+ if (query.vector === void 0) return filterMemoryFragments(fragments, query);
834
+ const ranked = fragments.filter((fragment) => memoryFragmentMatchesQuery(fragment, query));
835
+ ranked.sort((a, b) => {
836
+ const vectorDelta = vectorScore(b, query) - vectorScore(a, query);
837
+ if (vectorDelta !== 0) return vectorDelta;
838
+ const confidenceDelta = b.confidence - a.confidence;
839
+ if (confidenceDelta !== 0) return confidenceDelta;
840
+ return compareBigIntDesc2(a.tNs, b.tNs);
841
+ });
842
+ return query.limit === void 0 ? ranked : ranked.slice(0, Math.max(0, query.limit));
843
+ }
844
+ function vectorScore(fragment, query) {
845
+ if (query.vector === void 0 || fragment.embedding === void 0) return 0;
846
+ return cosineSimilarity(query.vector, fragment.embedding);
847
+ }
848
+ function statusState(errors, resultCount) {
849
+ if (errors.some((error) => !isRecoverableFragmentError(error))) return "error";
850
+ if (errors.length > 0) return "partial";
851
+ return resultCount > 0 ? "ready" : "empty";
852
+ }
853
+ function isRecoverableFragmentError(error) {
854
+ return error.code === "invalid-fragment" || error.code === "duplicate-fragment-id";
855
+ }
856
+ function indexById(fragments) {
857
+ const byId = /* @__PURE__ */ Object.create(null);
858
+ for (const fragment of fragments) byId[fragment.id] = fragment;
859
+ return Object.freeze(byId);
860
+ }
861
+ function isFiniteVector(value) {
862
+ if (!Array.isArray(value)) return false;
863
+ for (let i = 0; i < value.length; i += 1) {
864
+ if (!Object.hasOwn(value, i) || !Number.isFinite(value[i])) return false;
865
+ }
866
+ return true;
867
+ }
868
+ function validateMemoryRetrievalQuery(value) {
869
+ try {
870
+ return validateMemoryRetrievalQueryInner(value);
871
+ } catch (error) {
872
+ return {
873
+ ok: false,
874
+ query: {},
875
+ errors: [
876
+ {
877
+ code: "invalid-query",
878
+ message: `memoryRetrievalBundle: query access failed: ${errorMessage(error)}`,
879
+ fragment: value
880
+ }
881
+ ]
882
+ };
883
+ }
884
+ }
885
+ function validateMemoryRetrievalQueryInner(value) {
886
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
887
+ return invalidQuery(value, "memoryRetrievalBundle: query must be an object");
888
+ }
889
+ const query = value;
890
+ const errors = [];
891
+ if (query.tags !== void 0 && !isDenseArrayOf2(query.tags, (tag) => typeof tag === "string")) {
892
+ errors.push({
893
+ code: "invalid-query",
894
+ message: "memoryRetrievalBundle: query.tags must be a readonly string array",
895
+ fragment: value,
896
+ validationErrors: ["tags must be a readonly string array"]
897
+ });
898
+ }
899
+ if (query.asOf !== void 0 && typeof query.asOf !== "bigint") {
900
+ errors.push({
901
+ code: "invalid-query",
902
+ message: "memoryRetrievalBundle: query.asOf must be a bigint",
903
+ fragment: value,
904
+ validationErrors: ["asOf must be a bigint when present"]
905
+ });
906
+ }
907
+ if (query.minConfidence !== void 0 && (!Number.isFinite(query.minConfidence) || query.minConfidence < 0 || query.minConfidence > 1)) {
908
+ errors.push({
909
+ code: "invalid-query",
910
+ message: "memoryRetrievalBundle: query.minConfidence must be a finite number in [0, 1]",
911
+ fragment: value,
912
+ validationErrors: ["minConfidence must be a finite number in [0, 1]"]
913
+ });
914
+ }
915
+ if (query.limit !== void 0 && (!Number.isSafeInteger(query.limit) || query.limit < 0)) {
916
+ errors.push({
917
+ code: "invalid-query",
918
+ message: "memoryRetrievalBundle: query.limit must be a non-negative safe integer",
919
+ fragment: value,
920
+ validationErrors: ["limit must be a non-negative safe integer"]
921
+ });
922
+ }
923
+ if (query.vector !== void 0 && !isFiniteVector(query.vector)) {
924
+ errors.push({
925
+ code: "invalid-query-vector",
926
+ message: "memoryRetrievalBundle: query.vector must be a finite number array",
927
+ fragment: value,
928
+ validationErrors: ["vector must be a finite number array"]
929
+ });
930
+ }
931
+ if (errors.length > 0) return { ok: false, query: {}, errors };
932
+ return { ok: true, query: snapshotQuery(query), errors };
933
+ }
934
+ function invalidQuery(value, message) {
935
+ return {
936
+ ok: false,
937
+ query: {},
938
+ errors: [
939
+ {
940
+ code: "invalid-query",
941
+ message,
942
+ fragment: value
943
+ }
944
+ ]
945
+ };
946
+ }
947
+ function snapshotQuery(query) {
948
+ return Object.freeze({
949
+ ...query.tags === void 0 ? {} : { tags: Object.freeze([...query.tags]) },
950
+ ...query.asOf === void 0 ? {} : { asOf: query.asOf },
951
+ ...query.minConfidence === void 0 ? {} : { minConfidence: query.minConfidence },
952
+ ...query.limit === void 0 ? {} : { limit: query.limit },
953
+ ...query.vector === void 0 ? {} : { vector: Object.freeze([...query.vector]) }
954
+ });
955
+ }
956
+ function safeArrayLength(value) {
957
+ try {
958
+ return value.length;
959
+ } catch {
960
+ return void 0;
961
+ }
962
+ }
963
+ function validateAndSnapshotFragment(rawFragments, index) {
964
+ let raw;
965
+ try {
966
+ raw = rawFragments[index];
967
+ const validation = validateMemoryFragment(raw);
968
+ if (!validation.ok) {
969
+ return {
970
+ error: {
971
+ code: "invalid-fragment",
972
+ message: "memoryRetrievalBundle: invalid memory fragment",
973
+ index,
974
+ fragment: raw,
975
+ validationErrors: Object.freeze([...validation.errors])
976
+ }
977
+ };
978
+ }
979
+ return { fragment: snapshotFragment(raw) };
980
+ } catch (error) {
981
+ return {
982
+ error: {
983
+ code: "invalid-fragment",
984
+ message: `memoryRetrievalBundle: fragment access failed: ${errorMessage(error)}`,
985
+ index,
986
+ fragment: raw,
987
+ validationErrors: Object.freeze(["fragment access failed"])
988
+ }
989
+ };
990
+ }
991
+ }
992
+ function snapshotFragment(fragment) {
993
+ return Object.freeze({
994
+ id: fragment.id,
995
+ payload: fragment.payload,
996
+ tNs: fragment.tNs,
997
+ ...fragment.validFrom === void 0 ? {} : { validFrom: fragment.validFrom },
998
+ ...fragment.validTo === void 0 ? {} : { validTo: fragment.validTo },
999
+ confidence: fragment.confidence,
1000
+ tags: Object.freeze([...fragment.tags]),
1001
+ sources: Object.freeze([...fragment.sources]),
1002
+ ...fragment.embedding === void 0 ? {} : { embedding: Object.freeze([...fragment.embedding]) },
1003
+ ...fragment.parentFragmentId === void 0 ? {} : { parentFragmentId: fragment.parentFragmentId },
1004
+ ...fragment.provenance === void 0 ? {} : { provenance: fragment.provenance }
1005
+ });
1006
+ }
1007
+ function isDenseArrayOf2(value, predicate) {
1008
+ if (!Array.isArray(value)) return false;
1009
+ for (let i = 0; i < value.length; i += 1) {
1010
+ if (!Object.hasOwn(value, i) || !predicate(value[i])) return false;
1011
+ }
1012
+ return true;
1013
+ }
1014
+ function isPlainObject(value) {
1015
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1016
+ }
1017
+ function isNonEmptyString(value) {
1018
+ return typeof value === "string" && value.length > 0;
1019
+ }
1020
+ function errorMessage(error) {
1021
+ return error instanceof Error ? error.message : String(error);
1022
+ }
1023
+ function compareString(a, b) {
1024
+ return a < b ? -1 : a > b ? 1 : 0;
1025
+ }
1026
+ function compareBigIntDesc2(a, b) {
1027
+ if (a === b) return 0;
1028
+ return a > b ? -1 : 1;
1029
+ }
1030
+ // Annotate the CommonJS export names for ESM import in node:
1031
+ 0 && (module.exports = {
1032
+ admissionFilter3D,
1033
+ admissionScored,
1034
+ cosineSimilarity,
1035
+ filterMemoryFragments,
1036
+ isMemoryFragment,
1037
+ knowledgeGraphReducerBundle,
1038
+ memoryFragmentMatchesQuery,
1039
+ memoryFragmentValidAt,
1040
+ memoryRetrievalBundle,
1041
+ profileSummary,
1042
+ shardByTenant,
1043
+ validateMemoryFragment
1044
+ });
1045
+ //# sourceMappingURL=index.cjs.map