@anvia/neo4j 1.1.3 → 1.1.5

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.
package/README.md CHANGED
@@ -1,49 +1,38 @@
1
1
  # @anvia/neo4j
2
2
 
3
- Schema-first local GraphRAG for Neo4j 2026.01 and newer.
3
+ Build GraphRAG applications on Neo4j with typed schemas, document ingestion, and
4
+ retrieval that follows connected entities back to their source evidence.
4
5
 
5
- Provider-neutral schemas from `@anvia/graph` are accepted alongside the compatibility
6
- `defineNeo4jGraphSchema()` API. Registered graphs expose `graph.retrieve()`, and the shared
7
- `createGraphSearchTool()` factory gives Neo4j and Memgraph the same Agent tool API.
8
-
9
- ## Installation
6
+ ## Install
10
7
 
11
8
  ```sh
12
- pnpm add @anvia/graph @anvia/neo4j @anvia/core
9
+ pnpm add @anvia/neo4j @anvia/graph @anvia/core @anvia/openai zod
13
10
  ```
14
11
 
15
- ## Managed knowledge graph
12
+ Requires Neo4j 2026.01 or newer. `@anvia/openai` supplies the example's models.
13
+
14
+ ## Quickstart
15
+
16
+ Set `NEO4J_URI`, `NEO4J_USERNAME`, `NEO4J_PASSWORD`, and `OPENAI_API_KEY`.
16
17
 
17
18
  ```ts
18
- import { Agent } from "@anvia/core/agent";
19
- import { createGraphSearchTool, ingestGraphText } from "@anvia/graph";
20
- import { Neo4jClient, defineNeo4jGraphSchema } from "@anvia/neo4j";
19
+ import { defineGraphSchema, ingestGraphText } from "@anvia/graph";
20
+ import { Neo4jClient } from "@anvia/neo4j";
21
+ import { OpenAIClient } from "@anvia/openai";
21
22
  import { z } from "zod";
22
23
 
23
- const schema = defineNeo4jGraphSchema({
24
+ const schema = defineGraphSchema({
24
25
  nodes: {
25
26
  Product: {
26
27
  description: "A product or service.",
27
28
  identity: ["id"],
28
29
  properties: z.strictObject({ id: z.string(), name: z.string() }),
29
30
  },
30
- Incident: {
31
- description: "An operational incident.",
32
- identity: ["id"],
33
- properties: z.strictObject({ id: z.string(), title: z.string() }),
34
- },
35
- },
36
- relationships: {
37
- AFFECTS: {
38
- description: "An incident affects a product.",
39
- from: "Incident",
40
- to: "Product",
41
- properties: z.strictObject({ severity: z.enum(["low", "high"]) }),
42
- },
43
31
  },
32
+ relationships: {},
44
33
  });
45
-
46
- await using client = new Neo4jClient({
34
+ const models = new OpenAIClient({ apiKey: process.env.OPENAI_API_KEY! });
35
+ const client = new Neo4jClient({
47
36
  uri: process.env.NEO4J_URI!,
48
37
  auth: {
49
38
  username: process.env.NEO4J_USERNAME!,
@@ -56,209 +45,40 @@ const graph = client.managedKnowledgeGraph({
56
45
  resources: {
57
46
  labels: { document: "SupportDocument", chunk: "SupportChunk", entity: "SupportEntity" },
58
47
  indexes: {
59
- chunks: {
60
- vector: { name: "support_chunks_vector", dimensions: 1536, similarity: "cosine" },
61
- fulltext: { name: "support_chunks_text" },
62
- },
63
- entities: {
64
- vector: { name: "support_entities_vector", dimensions: 1536, similarity: "cosine" },
65
- fulltext: { name: "support_entities_text", properties: ["id", "name", "title"] },
66
- },
67
- },
68
- },
69
- });
70
-
71
- await graph.ensure({ indexTimeoutMs: 60_000 });
72
-
73
- const ingestion = await ingestGraphText({
74
- graph,
75
- document: { id: "incident-42", text },
76
- extractionModel,
77
- embeddingModel,
78
- chunking: {
79
- strategy: "recursive",
80
- maxSize: 1_000,
81
- overlap: 100,
82
- separators: ["\n\n", "\n", " "],
83
- },
84
- conflict: "error",
85
- orphanEntities: "delete",
86
- });
87
- console.log(ingestion.write);
88
-
89
- const searchGraph = createGraphSearchTool({
90
- name: "search_support_graph",
91
- description: "Search connected support incidents and products.",
92
- graph,
93
- model: embeddingModel,
94
- search: {
95
- type: "hybrid",
96
- seeds: ["chunks", "entities"],
97
- topK: 8,
98
- candidatesPerSeed: 20,
99
- rrfK: 60,
100
- },
101
- traversal: {
102
- relationships: ["AFFECTS"],
103
- direction: "both",
104
- maxDepth: 2,
105
- maxNodes: 40,
106
- maxRelationships: 80,
107
- },
108
- evidence: { type: "chunks", maxChunks: 12 },
109
- });
110
-
111
- const agent = new Agent({ id: "support", model: chatModel, tools: [searchGraph] });
112
- ```
113
-
114
- Call `ensure()` once during application startup or deployment initialization, then reuse the graph
115
- handle in jobs. It is idempotent, but calling it for every ingestion job adds version, schema, and
116
- index checks to the hot path. Call `validate()` for readiness checks that must never provision.
117
-
118
- ## Tenant namespaces
119
-
120
- Reuse the same labels, indexes, and Qdrant collection across tenants without constructing resource
121
- names from user input:
122
-
123
- ```ts
124
- const tenant = client.tenant(userId);
125
- const graph = tenant.managedKnowledgeGraph({ name: "support", schema, resources });
126
-
127
- const qdrantTenant = qdrant.tenant(userId);
128
- const vectors = qdrantTenant.vectorStore({
129
- collectionName: "support_documents",
130
- dimensions: 1536,
131
- });
132
- ```
133
-
134
- Both adapters hash the tenant ID using the same deterministic namespace. Neo4j includes that
135
- namespace in managed uniqueness constraints, indexed vector filtering, writes, retrieval,
136
- traversal, evidence, deletion, and exploration. Do not mix namespaced and non-namespaced handles
137
- with the same Neo4j resource definitions; `validate()` reports the incompatible constraint or
138
- index so it can be migrated explicitly.
139
-
140
- Tenant handles scope Anvia's managed lifecycle, retrieval, and exploration APIs; they are not a
141
- database authorization boundary. `graph.query()` and `client.nativeDriver()` intentionally expose
142
- raw Cypher access. Use separate Neo4j credentials or databases when untrusted callers require a
143
- hard security boundary.
144
-
145
- The application owns file discovery, reading, model loading, retry policy, and Agent lifecycle.
146
- `ingestGraphText()` and `ingestGraphDocuments()` provide the convenient end-to-end path. Advanced
147
- callers can compose `prepareGraphDocuments()`, `extractGraphFacts()`, `embedDocuments()`, and
148
- `replaceDocuments()` directly when they need custom orchestration.
149
-
150
- Graph property schemas must use `z.strictObject()` and must not coerce, default, transform,
151
- preprocess, catch, trim, or otherwise overwrite values. This keeps extraction, comparison, and
152
- stored Neo4j properties exact.
153
-
154
- Re-ingestion is document-scoped. `replaceDocuments()` removes the old chunks and their provenance
155
- before inserting the new representation. Facts supported by other documents remain. Use
156
- `deleteDocuments({ documentIds, orphanEntities })` for explicit removal.
157
-
158
- Both write operations return exact logical before-and-after counts for documents, chunks, entities,
159
- relationships, and mentions. A resource is `created`, `updated`, `deleted`, or `unchanged` by its
160
- stable public identity; the result is produced inside the same transaction as the mutation.
161
-
162
- Retrieval always requires an explicit evidence mode. `{ type: "none" }` performs no evidence read.
163
- Managed graphs can use `{ type: "chunks", maxChunks }` to hydrate exact source chunks in ranked
164
- provenance order. Seeds, nodes, and relationships refer to those records through `sourceChunkIds`.
165
-
166
- ## Existing graph
167
-
168
- ```ts
169
- const graph = client.knowledgeGraph({
170
- schema,
171
- seeds: {
172
- incidents: {
173
- nodeTypes: ["Incident"],
174
- vectorIndex: {
175
- name: "existing_incident_vectors",
176
- property: "embedding",
177
- dimensions: 1536,
178
- similarity: "cosine",
179
- },
180
- fulltextIndex: {
181
- name: "existing_incident_text",
182
- properties: ["title"],
183
- },
184
- },
185
- products: {
186
- nodeTypes: ["Product"],
187
- vectorIndex: {
188
- name: "existing_product_vectors",
189
- property: "embedding",
190
- dimensions: 1536,
191
- similarity: "cosine",
192
- },
193
- fulltextIndex: {
194
- name: "existing_product_text",
195
- properties: ["name"],
196
- },
48
+ chunks: { vector: { name: "support_chunks", dimensions: 1536, similarity: "cosine" } },
49
+ entities: { vector: { name: "support_entities", dimensions: 1536, similarity: "cosine" } },
197
50
  },
198
51
  },
199
52
  });
200
53
 
201
- await graph.validate();
202
- ```
203
-
204
- ## Graph explorer
205
-
206
- Managed and existing graph registrations implement the shared `GraphExplorer` contract:
207
-
208
- ```ts
209
- const overview = await graph.explore({ mode: "overview", maxNodes: 100 });
210
- const neighborhood = await graph.explore({
211
- mode: "expand",
212
- nodeIds: [overview.nodes[0]!.id],
213
- maxDepth: 1,
214
- });
54
+ try {
55
+ await graph.ensure({ indexTimeoutMs: 60_000 });
56
+ const result = await ingestGraphText({
57
+ graph,
58
+ document: { id: "products", text: "The product with ID anvia is named Anvia." },
59
+ extractionModel: models.completionModel({ modelId: "gpt-5.6", api: "responses" }),
60
+ embeddingModel: models.embeddingModel({ modelId: "text-embedding-3-small" }),
61
+ conflict: "error",
62
+ orphanEntities: "delete",
63
+ });
64
+ console.log(result.write);
65
+ } finally {
66
+ await client.close();
67
+ }
215
68
  ```
216
69
 
217
- Pass `includeProvenance: true` to expose supported source document and chunk IDs on explorer nodes
218
- and relationships. This can drive article-to-entity UI links without a separate identity mapping
219
- table; Neo4j element IDs remain opaque expansion cursors.
220
-
221
- ## Production ingestion workflow
222
-
223
- For a queue worker (including BullMQ), use stable document IDs, attach a monotonic revision, and
224
- call `ingestGraphTextToStores({ graph, vectorStore, ... })`. Persist its receipt as the job result.
225
- Retry extraction/provider failures as a whole. If `GraphIngestionStageError.stage === "vector"`,
226
- the graph transaction already committed; re-run the idempotent job with `conflict: "overwrite"`.
227
- Refresh by replacing the same document ID;
228
- delete from both stores and record each completed stage. Pass the queue cancellation signal through
229
- `abortSignal`, create tenant-scoped handles before processing user-owned jobs, and request explorer
230
- provenance for source attribution.
70
+ ## What you can build
231
71
 
232
- The explorer returns Neo4j element IDs as opaque strings, limits every query, and omits embeddings
233
- and other `__anvia_*` properties. Use stable graph identity properties for application logic; use the
234
- opaque IDs only to expand the current view.
72
+ - Managed graphs with explicit provisioning and document-scoped replacement.
73
+ - Vector and hybrid retrieval with bounded traversal and source chunk evidence.
74
+ - Agent search tools through `createGraphSearchTool()` from `@anvia/graph`.
75
+ - Bounded exploration and read-only registration of existing graphs.
235
76
 
236
- Existing registrations are read-only and expose no provisioning or write methods. Use
237
- `client.nativeDriver()` for application-owned Cypher.
77
+ Tenant handles scope managed graph operations in shared resources. They are not a database
78
+ authorization boundary. Existing graph registrations are read-only.
238
79
 
239
- Existing graph registrations do not own Anvia document and chunk resources, so their retrieval and
240
- tool registrations accept only `evidence: { type: "none" }`.
80
+ ## Learn more
241
81
 
242
- Each existing seed describes exactly one indexed node type and the complete expected vector and
243
- full-text index definitions. Register additional node types as separate seeds and fuse them with
244
- hybrid retrieval.
245
-
246
- Package operations use explicit transactions and do not invoke Neo4j's managed retry APIs. Abort
247
- signals roll back the active transaction. Applications decide whether and how to retry an entire
248
- operation.
249
-
250
- `Neo4jClient` supports `await using` and closes a driver that it creates from `uri` and `auth`.
251
- When a caller supplies `driver`, that driver remains caller-owned; closing or disposing the client
252
- only closes the Anvia client handle.
253
-
254
- The public property boundary is intentionally JSON-safe. Unsafe Neo4j integers, temporal and
255
- spatial objects, nodes, relationships, paths, maps, and heterogeneous property arrays are rejected
256
- instead of being coerced.
257
-
258
- ## Development
259
-
260
- ```sh
261
- pnpm --filter @anvia/neo4j typecheck
262
- pnpm --filter @anvia/neo4j test
263
- pnpm --filter @anvia/neo4j build
264
- ```
82
+ - [Usage guide](https://github.com/anvia-hq/anvia/blob/main/docs/packages/graph-neo4j.md)
83
+ - [Anvia overview](https://github.com/anvia-hq/anvia/blob/main/README.md)
84
+ - [Contributing](https://github.com/anvia-hq/anvia/blob/main/CONTRIBUTING.md)
@@ -310,14 +310,14 @@ var Neo4jKnowledgeGraphBase = class {
310
310
  );
311
311
  }
312
312
  async retrieve(options) {
313
- const { retrieveGraphContext } = await import("./retrieve-IJVPFOPP.js");
313
+ const { retrieveGraphContext } = await import("./retrieve-A6UD55NM.js");
314
314
  return retrieveGraphContext({
315
315
  ...options,
316
316
  graph: this
317
317
  });
318
318
  }
319
319
  async explore(options) {
320
- const { exploreGraph } = await import("./explore-HRISJG7V.js");
320
+ const { exploreGraph } = await import("./explore-PNLRCONH.js");
321
321
  return exploreGraph(this, options);
322
322
  }
323
323
  seed(name) {
@@ -416,14 +416,13 @@ var ManagedNeo4jKnowledgeGraph = class extends Neo4jKnowledgeGraphBase {
416
416
  entryRelationshipType: "ANVIA_MENTIONS"
417
417
  };
418
418
  if (this.resources.indexes.chunks.fulltext !== void 0) {
419
+ const chunkFulltextProperties = ["__anvia_text"];
420
+ if (this.namespace !== void 0) chunkFulltextProperties.push("__anvia_namespace");
419
421
  chunks = {
420
422
  ...chunks,
421
423
  fulltextIndex: Object.freeze({
422
424
  ...this.resources.indexes.chunks.fulltext,
423
- properties: Object.freeze([
424
- "__anvia_text",
425
- ...this.namespace === void 0 ? [] : ["__anvia_namespace"]
426
- ])
425
+ properties: Object.freeze(chunkFulltextProperties)
427
426
  })
428
427
  };
429
428
  }
@@ -436,14 +435,15 @@ var ManagedNeo4jKnowledgeGraph = class extends Neo4jKnowledgeGraphBase {
436
435
  vectorFilterProperties: this.namespace === void 0 ? void 0 : Object.freeze(["__anvia_namespace"])
437
436
  };
438
437
  if (this.resources.indexes.entities.fulltext !== void 0) {
438
+ const entityFulltextProperties = [
439
+ ...this.resources.indexes.entities.fulltext.properties ?? []
440
+ ];
441
+ if (this.namespace !== void 0) entityFulltextProperties.push("__anvia_namespace");
439
442
  entities = {
440
443
  ...entities,
441
444
  fulltextIndex: Object.freeze({
442
445
  ...this.resources.indexes.entities.fulltext,
443
- properties: Object.freeze([
444
- ...this.resources.indexes.entities.fulltext.properties ?? [],
445
- ...this.namespace === void 0 ? [] : ["__anvia_namespace"]
446
- ])
446
+ properties: Object.freeze(entityFulltextProperties)
447
447
  })
448
448
  };
449
449
  }
@@ -480,19 +480,17 @@ var ManagedNeo4jKnowledgeGraph = class extends Neo4jKnowledgeGraphBase {
480
480
  vectorIndex(indexes.entities.vector, labels.entity, this.namespace !== void 0)
481
481
  ];
482
482
  if (indexes.chunks.fulltext !== void 0) {
483
+ const chunkIndexProperties = ["__anvia_text"];
484
+ if (this.namespace !== void 0) chunkIndexProperties.push("__anvia_namespace");
483
485
  statements.push(
484
- fulltextIndex(indexes.chunks.fulltext.name, labels.chunk, [
485
- "__anvia_text",
486
- ...this.namespace === void 0 ? [] : ["__anvia_namespace"]
487
- ])
486
+ fulltextIndex(indexes.chunks.fulltext.name, labels.chunk, chunkIndexProperties)
488
487
  );
489
488
  }
490
489
  if (indexes.entities.fulltext !== void 0) {
490
+ const entityIndexProperties = [...indexes.entities.fulltext.properties ?? []];
491
+ if (this.namespace !== void 0) entityIndexProperties.push("__anvia_namespace");
491
492
  statements.push(
492
- fulltextIndex(indexes.entities.fulltext.name, labels.entity, [
493
- ...indexes.entities.fulltext.properties ?? [],
494
- ...this.namespace === void 0 ? [] : ["__anvia_namespace"]
495
- ])
493
+ fulltextIndex(indexes.entities.fulltext.name, labels.entity, entityIndexProperties)
496
494
  );
497
495
  }
498
496
  for (const statement of statements)
@@ -1606,4 +1604,4 @@ export {
1606
1604
  Neo4jKnowledgeGraph,
1607
1605
  ManagedNeo4jKnowledgeGraph
1608
1606
  };
1609
- //# sourceMappingURL=chunk-EUZ5C6OC.js.map
1607
+ //# sourceMappingURL=chunk-IVKNAFKG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schema.ts","../src/helpers.ts","../src/managed-scope.ts","../src/graph.ts"],"sourcesContent":["import { z } from \"zod\";\nimport type {\n Neo4jGraphSchema,\n Neo4jGraphSchemaOptions,\n Neo4jProperties,\n Neo4jPropertyPrimitive,\n Neo4jPropertyValue,\n} from \"./types.js\";\n\nconst reservedPrefix = \"__anvia_\";\n\nexport function defineNeo4jGraphSchema<const Options extends Neo4jGraphSchemaOptions>(\n options: Options,\n): Neo4jGraphSchema<Options> {\n if (Object.keys(options.nodes).length === 0) {\n throw new TypeError(\"A Neo4j graph schema requires at least one node type.\");\n }\n for (const [type, definition] of Object.entries(options.nodes)) {\n assertName(type, \"node type\");\n assertDescription(definition.description, `node ${type}`);\n if (!(definition.properties instanceof z.ZodObject)) {\n throw new TypeError(`Properties for node ${type} must be a Zod object schema.`);\n }\n assertExactPropertySchema(definition.properties, `node ${type}`);\n if (\n definition.identity.length === 0 ||\n new Set(definition.identity).size !== definition.identity.length\n ) {\n throw new TypeError(`Node ${type} must declare unique identity properties.`);\n }\n const shape = definition.properties.shape;\n for (const property of definition.identity) {\n assertPropertyName(property);\n if (!(property in shape)) {\n throw new TypeError(`Identity property ${property} is not declared by node ${type}.`);\n }\n }\n for (const property of Object.keys(shape)) assertPropertyName(property);\n }\n for (const [type, definition] of Object.entries(options.relationships)) {\n assertName(type, \"relationship type\");\n assertDescription(definition.description, `relationship ${type}`);\n if (!(definition.from in options.nodes) || !(definition.to in options.nodes)) {\n throw new TypeError(`Relationship ${type} references an unknown endpoint type.`);\n }\n if (!(definition.properties instanceof z.ZodObject)) {\n throw new TypeError(`Properties for relationship ${type} must be a Zod object schema.`);\n }\n assertExactPropertySchema(definition.properties, `relationship ${type}`);\n const identity = definition.identity ?? [];\n if (new Set(identity).size !== identity.length) {\n throw new TypeError(`Relationship ${type} contains duplicate identity properties.`);\n }\n for (const property of Object.keys(definition.properties.shape)) assertPropertyName(property);\n for (const property of identity) {\n if (!(property in definition.properties.shape)) {\n throw new TypeError(\n `Identity property ${property} is not declared by relationship ${type}.`,\n );\n }\n }\n }\n const nodes = Object.fromEntries(\n Object.entries(options.nodes).map(([type, definition]) => [\n type,\n Object.freeze({ ...definition, identity: Object.freeze([...definition.identity]) }),\n ]),\n );\n const relationships = Object.fromEntries(\n Object.entries(options.relationships).map(([type, definition]) => {\n const copy = { ...definition };\n if (definition.identity !== undefined) {\n Object.assign(copy, { identity: Object.freeze([...definition.identity]) });\n }\n return [type, Object.freeze(copy)];\n }),\n );\n return Object.freeze({\n nodes: Object.freeze(nodes),\n relationships: Object.freeze(relationships),\n kind: \"neo4j-graph-schema\" as const,\n }) as Neo4jGraphSchema<Options>;\n}\n\nexport function parseNeo4jProperties(value: unknown, label: string): Neo4jProperties {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} must be an object of Neo4j property values.`);\n }\n const output: Record<string, Neo4jPropertyValue> = {};\n for (const [key, item] of Object.entries(value)) {\n assertPropertyName(key);\n output[key] = parseNeo4jPropertyValue(item, `${label}.${key}`);\n }\n return output;\n}\n\nexport function parseNeo4jPropertyValue(value: unknown, label: string): Neo4jPropertyValue {\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new TypeError(`${label} must be finite.`);\n if (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n throw new TypeError(`${label} must be a safe integer.`);\n }\n return value;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) return [];\n const parsed = value.map((item, index) => parsePrimitive(item, `${label}[${index}]`));\n const type = typeof parsed[0];\n if (!parsed.every((item) => typeof item === type)) {\n throw new TypeError(`${label} must be a homogeneous array.`);\n }\n return parsed as Neo4jPropertyValue;\n }\n throw new TypeError(`${label} is not a supported Neo4j property value.`);\n}\n\nfunction parsePrimitive(value: unknown, label: string): Neo4jPropertyPrimitive {\n const parsed = parseNeo4jPropertyValue(value, label);\n if (typeof parsed === \"string\" || typeof parsed === \"number\" || typeof parsed === \"boolean\") {\n return parsed;\n }\n throw new TypeError(`${label} must be a primitive property value.`);\n}\n\nexport function assertName(value: string, label: string): void {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string.`);\n }\n}\n\nexport function assertPropertyName(value: string): void {\n assertName(value, \"Neo4j property name\");\n if (value.startsWith(reservedPrefix)) {\n throw new TypeError(`Neo4j property names beginning with ${reservedPrefix} are reserved.`);\n }\n}\n\nfunction assertDescription(value: string, label: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`${label} requires a non-empty description.`);\n }\n}\n\nfunction assertExactPropertySchema(schema: z.ZodObject<z.ZodRawShape>, label: string): void {\n const definition = schema._zod.def;\n if (!(definition.catchall instanceof z.ZodNever)) {\n throw new TypeError(`${label} properties must use a strict Zod object schema.`);\n }\n for (const [property, propertySchema] of Object.entries(schema.shape)) {\n assertNonEffectfulSchema(propertySchema, `${label} property ${property}`, new Set());\n }\n}\n\nfunction assertNonEffectfulSchema(value: unknown, label: string, visited: Set<z.ZodType>): void {\n if (!(value instanceof z.ZodType)) {\n throw new TypeError(`${label} must be a Zod schema.`);\n }\n const schema = value;\n if (visited.has(schema)) return;\n visited.add(schema);\n const definition = schema._zod.def as unknown as Record<string, unknown>;\n const type = definition.type;\n if (\n definition.coerce === true ||\n type === \"default\" ||\n type === \"prefault\" ||\n type === \"catch\" ||\n type === \"transform\" ||\n type === \"pipe\"\n ) {\n throw new TypeError(\n `${label} must not coerce, default, transform, preprocess, or catch values.`,\n );\n }\n const checks = definition.checks;\n if (\n Array.isArray(checks) &&\n checks.some((check) => {\n if (typeof check !== \"object\" || check === null) return false;\n const internals = (check as { _zod?: { def?: { check?: unknown } } })._zod;\n return internals?.def?.check === \"overwrite\";\n })\n ) {\n throw new TypeError(`${label} must not normalize or overwrite values.`);\n }\n for (const child of schemaChildren(definition)) {\n assertNonEffectfulSchema(child, label, visited);\n }\n}\n\nfunction schemaChildren(definition: Record<string, unknown>): z.ZodType[] {\n const children: z.ZodType[] = [];\n for (const key of [\"innerType\", \"element\", \"left\", \"right\", \"rest\", \"keyType\", \"valueType\"]) {\n const value = definition[key];\n if (value instanceof z.ZodType) children.push(value);\n }\n for (const key of [\"options\", \"items\"]) {\n const value = definition[key];\n if (Array.isArray(value)) {\n for (const item of value) if (item instanceof z.ZodType) children.push(item);\n }\n }\n return children;\n}\n","import { isInt } from \"neo4j-driver\";\nimport { parseNeo4jProperties } from \"./schema.js\";\nimport type { Neo4jProperties } from \"./types.js\";\n\nexport function quoteIdentifier(value: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(\"Neo4j identifiers must be non-empty strings.\");\n }\n if (value.includes(\"\\u0000\")) throw new TypeError(\"Neo4j identifiers must not contain NUL.\");\n return `\\`${value.replaceAll(\"`\", \"``\")}\\``;\n}\n\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw abortError();\n }\n}\n\nexport function abortError(): Error {\n const error = new Error(\"The operation was aborted.\");\n error.name = \"AbortError\";\n return error;\n}\n\nexport function positiveInteger(value: number, label: string, maximum?: number): number {\n if (!Number.isSafeInteger(value) || value < 1 || (maximum !== undefined && value > maximum)) {\n throw new RangeError(\n `${label} must be a positive safe integer${maximum === undefined ? \"\" : ` no greater than ${maximum}`}.`,\n );\n }\n return value;\n}\n\nexport function finiteScore(value: number | undefined, label: string): void {\n if (value !== undefined && !Number.isFinite(value))\n throw new RangeError(`${label} must be finite.`);\n}\n\nexport function strictProperties(value: unknown, label: string): Neo4jProperties {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} must be an object.`);\n }\n const normalized: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value))\n normalized[key] = normalizeDriverValue(item, `${label}.${key}`);\n return parseNeo4jProperties(normalized, label);\n}\n\nfunction normalizeDriverValue(value: unknown, label: string): unknown {\n if (isInt(value)) {\n if (!value.inSafeRange()) throw new TypeError(`${label} contains an unsafe Neo4j integer.`);\n return value.toNumber();\n }\n if (Array.isArray(value))\n return value.map((item, index) => normalizeDriverValue(item, `${label}[${index}]`));\n return value;\n}\n\nexport function stableObject(value: Readonly<Record<string, unknown>>): string {\n return JSON.stringify(\n Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right))),\n );\n}\n","import { quoteIdentifier } from \"./helpers.js\";\n\nexport type Neo4jManagedScope = Readonly<{\n graph: string;\n namespace?: string | undefined;\n}>;\n\nexport function managedScopeParameters(\n scope: Neo4jManagedScope | undefined,\n parameters: Record<string, unknown>,\n): Record<string, unknown> {\n return scope === undefined\n ? parameters\n : { graph: scope.graph, namespace: scope.namespace ?? null, ...parameters };\n}\n\nexport function managedScopePredicate(\n scope: Neo4jManagedScope | undefined,\n variable: string,\n prefix: \" WHERE\" | \" AND\" | \"WHERE\" | \"AND\",\n): string {\n if (scope === undefined) return \"\";\n return `${prefix} ${variable}.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(scope, variable, \" AND\")}`;\n}\n\nexport function namespacePredicate(\n scope: Neo4jManagedScope,\n variable: string,\n prefix: \" WHERE\" | \" AND\" | \"WHERE\" | \"AND\",\n): string {\n return scope.namespace === undefined\n ? \"\"\n : `${prefix} ${variable}.${quoteIdentifier(\"__anvia_namespace\")} = $namespace`;\n}\n\nexport function tenantScopePredicate(\n scope: Neo4jManagedScope,\n variable: string,\n prefix: \" WHERE\" | \" AND\" | \"WHERE\" | \"AND\",\n): string {\n return scope.namespace === undefined ? \"\" : managedScopePredicate(scope, variable, prefix);\n}\n\nexport function managedPathPredicate(\n scope: Neo4jManagedScope | undefined,\n relationships: boolean,\n): string {\n if (scope === undefined) return \"\";\n const item = `item.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(scope, \"item\", \" AND\")}`;\n const nodes = ` AND all(item IN nodes(path) WHERE ${item})`;\n return relationships ? `${nodes}\\n AND all(item IN relationships(path) WHERE ${item})` : nodes;\n}\n\nexport function namespaceMapEntry(scope: Neo4jManagedScope): string {\n return scope.namespace === undefined\n ? \"\"\n : `, ${quoteIdentifier(\"__anvia_namespace\")}: $namespace`;\n}\n\nexport function tenantMapEntries(scope: Neo4jManagedScope): string {\n return scope.namespace === undefined\n ? \"\"\n : `, ${quoteIdentifier(\"__anvia_graph\")}: $graph, ${quoteIdentifier(\"__anvia_namespace\")}: $namespace`;\n}\n\nexport function tenantRelationshipProperties(scope: Neo4jManagedScope): string {\n return scope.namespace === undefined\n ? \"\"\n : ` {${quoteIdentifier(\"__anvia_graph\")}: $graph, ${quoteIdentifier(\"__anvia_namespace\")}: $namespace}`;\n}\n","import {\n type GraphContext,\n type GraphExploreOptions,\n type GraphExploreResult,\n type GraphRetrieveOptions,\n} from \"@anvia/graph\";\nimport {\n isInt,\n type ManagedTransaction,\n type Record as Neo4jRecord,\n type QueryResult,\n type SessionConfig,\n} from \"neo4j-driver\";\nimport type { Neo4jClient } from \"./client.js\";\nimport {\n abortError,\n positiveInteger,\n quoteIdentifier,\n stableObject,\n throwIfAborted,\n} from \"./helpers.js\";\nimport {\n managedScopeParameters,\n namespaceMapEntry as scopeNamespaceMapEntry,\n namespacePredicate as scopeNamespacePredicate,\n tenantMapEntries as scopeTenantMapEntries,\n tenantRelationshipProperties as scopeTenantRelationshipProperties,\n tenantScopePredicate,\n} from \"./managed-scope.js\";\nimport {\n assertName,\n assertPropertyName,\n parseNeo4jProperties,\n parseNeo4jPropertyValue,\n} from \"./schema.js\";\nimport type {\n DeleteNeo4jDocumentsOptions,\n ExistingNeo4jSeed,\n ManagedNeo4jKnowledgeGraphOptions,\n Neo4jFulltextIndex,\n Neo4jGraphConflict,\n Neo4jGraphEnsureOptions,\n Neo4jGraphEvidenceCapability,\n Neo4jGraphSchema,\n Neo4jGraphValidateOptions,\n Neo4jGraphWriteResult,\n Neo4jKnowledgeGraphOptions,\n Neo4jNodeIdentity,\n Neo4jProperties,\n Neo4jVectorIndex,\n ReplaceNeo4jDocumentsOptions,\n} from \"./types.js\";\n\ntype SeedRegistration = Readonly<{\n labels: readonly string[];\n vectorIndex: Neo4jVectorIndex & Readonly<{ property: string }>;\n vectorFilterProperties?: readonly string[] | undefined;\n fulltextIndex?: (Neo4jFulltextIndex & Readonly<{ properties: readonly string[] }>) | undefined;\n entryRelationshipType?: string | undefined;\n}>;\n\ntype ExpectedConstraint = Readonly<{\n name: string;\n label: string;\n properties: readonly string[];\n}>;\n\ntype GraphTransaction = Pick<ManagedTransaction, \"run\">;\n\nconst tenantScopeBrand: unique symbol = Symbol(\"Neo4jTenantScope\");\n\nexport type Neo4jTenantScope = Readonly<{\n namespace: string;\n [tenantScopeBrand]: true;\n}>;\n\nexport function neo4jTenantScope(namespace: string): Neo4jTenantScope {\n return Object.freeze({ namespace, [tenantScopeBrand]: true as const });\n}\n\nexport abstract class Neo4jKnowledgeGraphBase<\n Schema extends Neo4jGraphSchema = Neo4jGraphSchema,\n Evidence extends Neo4jGraphEvidenceCapability = Neo4jGraphEvidenceCapability,\n> {\n abstract readonly seeds: Readonly<Record<string, SeedRegistration>>;\n abstract readonly evidenceCapability: Evidence;\n\n protected constructor(\n protected readonly owner: Neo4jClient,\n readonly schema: Schema,\n readonly namespace?: string | undefined,\n ) {\n if (schema.kind !== \"neo4j-graph-schema\" && schema.kind !== \"graph-schema\") {\n throw new TypeError(\n \"Neo4j knowledge graphs require defineGraphSchema() or defineNeo4jGraphSchema().\",\n );\n }\n }\n\n async validate(options: Neo4jGraphValidateOptions = {}): Promise<void> {\n throwIfAborted(options.abortSignal);\n await this.assertSupportedVersion(options.abortSignal);\n const expected = expectedIndexes(this.seeds);\n const names = [...expected.keys()];\n const result = await this.query(\n \"SHOW INDEXES YIELD name, state, type, entityType, labelsOrTypes, properties, options WHERE name IN $names RETURN name, state, type, entityType, labelsOrTypes, properties, options\",\n { names },\n options.abortSignal,\n );\n const actual = new Map(\n result.records.map((record) => [\n requiredString(record.get(\"name\"), \"Neo4j index name\"),\n record,\n ]),\n );\n for (const [name, definition] of expected) {\n const record = actual.get(name);\n if (record === undefined) throw new Error(`Neo4j index ${name} does not exist.`);\n validateIndexRecord(record, definition);\n }\n }\n\n async query(\n text: string,\n parameters: Record<string, unknown>,\n abortSignal?: AbortSignal,\n access: \"read\" | \"write\" = \"read\",\n ): Promise<QueryResult> {\n return this.runTransaction(\n access,\n abortSignal,\n async (transaction) => await transaction.run(text, parameters),\n );\n }\n\n async retrieve(options: GraphRetrieveOptions<Schema, Evidence>): Promise<GraphContext> {\n const { retrieveGraphContext } = await import(\"./retrieve.js\");\n return retrieveGraphContext({\n ...options,\n graph: this,\n } as import(\"./types.js\").RetrieveGraphContextOptions<Schema>);\n }\n\n async explore(options: GraphExploreOptions<Schema>): Promise<GraphExploreResult> {\n const { exploreGraph } = await import(\"./explore.js\");\n return exploreGraph(this, options);\n }\n\n seed(name: string): SeedRegistration {\n const seed = this.seeds[name];\n if (seed === undefined) throw new TypeError(`Unknown Neo4j graph seed: ${name}`);\n return seed;\n }\n\n protected async transaction<T>(\n abortSignal: AbortSignal | undefined,\n run: (transaction: GraphTransaction) => Promise<T>,\n ): Promise<T> {\n return this.runTransaction(\"write\", abortSignal, run);\n }\n\n private async runTransaction<T>(\n access: \"read\" | \"write\",\n abortSignal: AbortSignal | undefined,\n run: (transaction: GraphTransaction) => Promise<T>,\n ): Promise<T> {\n throwIfAborted(abortSignal);\n const sessionOptions: SessionConfig = {\n defaultAccessMode: access === \"read\" ? \"READ\" : \"WRITE\",\n };\n if (this.owner.database !== undefined) {\n Object.assign(sessionOptions, { database: this.owner.database });\n }\n const session = this.owner.nativeDriver().session(sessionOptions);\n const transaction = session.beginTransaction();\n let rejectAbort: ((error: Error) => void) | undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n });\n const onAbort = () => {\n rejectAbort?.(abortError());\n };\n abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n let committing = false;\n try {\n const value = await Promise.race([run(transaction), aborted]);\n throwIfAborted(abortSignal);\n committing = true;\n await transaction.commit();\n return value;\n } catch (error) {\n if (transaction.isOpen()) await transaction.rollback();\n if (!committing && abortSignal?.aborted) throw abortError();\n throw error;\n } finally {\n abortSignal?.removeEventListener(\"abort\", onAbort);\n if (transaction.isOpen()) await transaction.rollback();\n await session.close();\n }\n }\n\n private async assertSupportedVersion(abortSignal?: AbortSignal): Promise<void> {\n const result = await this.query(\n \"CALL dbms.components() YIELD versions RETURN versions[0] AS version LIMIT 1\",\n {},\n abortSignal,\n );\n const version = result.records[0]?.get(\"version\");\n if (typeof version !== \"string\") {\n throw new TypeError(\"Neo4j returned a non-string server version.\");\n }\n if (!supportedVersion(version)) {\n throw new Error(`@anvia/neo4j requires Neo4j 2026.01 or newer; received ${version}.`);\n }\n }\n}\n\nexport class Neo4jKnowledgeGraph<Schema extends Neo4jGraphSchema> extends Neo4jKnowledgeGraphBase<\n Schema,\n \"none\"\n> {\n readonly evidenceCapability = \"none\" as const;\n readonly seeds: Readonly<Record<string, SeedRegistration>>;\n\n constructor(owner: Neo4jClient, options: Neo4jKnowledgeGraphOptions<Schema>) {\n super(owner, options.schema);\n if (Object.keys(options.seeds).length === 0) {\n throw new TypeError(\"An existing Neo4j knowledge graph requires at least one seed.\");\n }\n const seeds: Record<string, SeedRegistration> = {};\n for (const [name, seed] of Object.entries(options.seeds)) {\n assertName(name, \"Neo4j seed name\");\n seeds[name] = validateExistingSeed(options.schema, seed);\n }\n this.seeds = Object.freeze(seeds);\n }\n}\n\nexport class ManagedNeo4jKnowledgeGraph<\n Schema extends Neo4jGraphSchema,\n> extends Neo4jKnowledgeGraphBase<Schema, \"chunks\"> {\n readonly evidenceCapability = \"chunks\" as const;\n readonly seeds: Readonly<Record<string, SeedRegistration>>;\n readonly resources: ManagedNeo4jKnowledgeGraphOptions<Schema>[\"resources\"];\n readonly name: string;\n\n constructor(\n owner: Neo4jClient,\n options: ManagedNeo4jKnowledgeGraphOptions<Schema>,\n tenantScope?: Neo4jTenantScope,\n ) {\n const namespace = tenantScope?.namespace;\n super(owner, options.schema, namespace);\n assertName(options.name, \"Managed Neo4j graph name\");\n if (namespace !== undefined) assertName(namespace, \"Managed Neo4j namespace\");\n this.name = options.name;\n this.resources = validateManagedResources(options.resources);\n let chunks: SeedRegistration = {\n labels: Object.freeze([this.resources.labels.chunk]),\n vectorIndex: Object.freeze({\n ...this.resources.indexes.chunks.vector,\n property: \"__anvia_embedding\",\n }),\n vectorFilterProperties:\n this.namespace === undefined ? undefined : Object.freeze([\"__anvia_namespace\"]),\n entryRelationshipType: \"ANVIA_MENTIONS\",\n };\n if (this.resources.indexes.chunks.fulltext !== undefined) {\n const chunkFulltextProperties = [\"__anvia_text\"];\n if (this.namespace !== undefined) chunkFulltextProperties.push(\"__anvia_namespace\");\n chunks = {\n ...chunks,\n fulltextIndex: Object.freeze({\n ...this.resources.indexes.chunks.fulltext,\n properties: Object.freeze(chunkFulltextProperties),\n }),\n };\n }\n let entities: SeedRegistration = {\n labels: Object.freeze([this.resources.labels.entity]),\n vectorIndex: Object.freeze({\n ...this.resources.indexes.entities.vector,\n property: \"__anvia_embedding\",\n }),\n vectorFilterProperties:\n this.namespace === undefined ? undefined : Object.freeze([\"__anvia_namespace\"]),\n };\n if (this.resources.indexes.entities.fulltext !== undefined) {\n const entityFulltextProperties = [\n ...(this.resources.indexes.entities.fulltext.properties ?? []),\n ];\n if (this.namespace !== undefined) entityFulltextProperties.push(\"__anvia_namespace\");\n entities = {\n ...entities,\n fulltextIndex: Object.freeze({\n ...this.resources.indexes.entities.fulltext,\n properties: Object.freeze(entityFulltextProperties),\n }),\n };\n }\n this.seeds = Object.freeze({\n chunks: Object.freeze(chunks),\n entities: Object.freeze(entities),\n });\n }\n\n async ensure(options: Neo4jGraphEnsureOptions): Promise<void> {\n positiveInteger(options.indexTimeoutMs, \"Neo4j index timeout\");\n throwIfAborted(options.abortSignal);\n const { labels, indexes } = this.resources;\n const identityPrefix = this.namespace === undefined ? [] : [\"__anvia_namespace\"];\n const statements = [\n uniquenessConstraint(constraintName(this.name, \"document\"), labels.document, [\n ...identityPrefix,\n \"__anvia_id\",\n ]),\n uniquenessConstraint(constraintName(this.name, \"chunk\"), labels.chunk, [\n ...identityPrefix,\n \"__anvia_id\",\n ]),\n uniquenessConstraint(constraintName(this.name, \"entity\"), labels.entity, [\n ...identityPrefix,\n \"__anvia_key\",\n ]),\n ...Object.entries(this.schema.nodes).map(([type, definition]) =>\n uniquenessConstraint(constraintName(this.name, `entity_${type}`), type, [\n ...identityPrefix,\n ...definition.identity,\n ]),\n ),\n vectorIndex(indexes.chunks.vector, labels.chunk, this.namespace !== undefined),\n vectorIndex(indexes.entities.vector, labels.entity, this.namespace !== undefined),\n ];\n if (indexes.chunks.fulltext !== undefined) {\n const chunkIndexProperties = [\"__anvia_text\"];\n if (this.namespace !== undefined) chunkIndexProperties.push(\"__anvia_namespace\");\n statements.push(\n fulltextIndex(indexes.chunks.fulltext.name, labels.chunk, chunkIndexProperties),\n );\n }\n if (indexes.entities.fulltext !== undefined) {\n const entityIndexProperties = [...(indexes.entities.fulltext.properties ?? [])];\n if (this.namespace !== undefined) entityIndexProperties.push(\"__anvia_namespace\");\n statements.push(\n fulltextIndex(indexes.entities.fulltext.name, labels.entity, entityIndexProperties),\n );\n }\n for (const statement of statements)\n await this.query(statement, {}, options.abortSignal, \"write\");\n await this.query(\n \"CALL db.awaitIndexes($timeoutSeconds)\",\n { timeoutSeconds: Math.ceil(options.indexTimeoutMs / 1000) },\n options.abortSignal,\n );\n await this.validate({ abortSignal: options.abortSignal });\n }\n\n override async validate(options: Neo4jGraphValidateOptions = {}): Promise<void> {\n await super.validate(options);\n const expected = this.expectedConstraints();\n const names = expected.map((constraint) => constraint.name);\n const result = await this.query(\n \"SHOW CONSTRAINTS YIELD name, type, entityType, labelsOrTypes, properties WHERE name IN $names RETURN name, type, entityType, labelsOrTypes, properties\",\n { names },\n options.abortSignal,\n );\n const actual = new Map(\n result.records.map((record) => [\n requiredString(record.get(\"name\"), \"Neo4j constraint name\"),\n record,\n ]),\n );\n for (const constraint of expected) {\n const record = actual.get(constraint.name);\n if (record === undefined) {\n throw new Error(`Neo4j constraint ${constraint.name} does not exist.`);\n }\n validateConstraintRecord(record, constraint);\n }\n }\n\n async replaceDocuments(\n options: ReplaceNeo4jDocumentsOptions<Schema>,\n ): Promise<Neo4jGraphWriteResult> {\n validateReplacement(options, this.resources.indexes, this.schema);\n if (options.documents.length === 0) return emptyWriteResult();\n const documentIds = options.documents.map((document) => document.id);\n const chunksById = new Map(options.chunks.map((chunk) => [chunk.id, chunk.document]));\n const sourceDocuments = (sourceChunkIds: readonly string[]) => [\n ...new Set(\n sourceChunkIds.map((chunkId) => {\n const chunk = chunksById.get(chunkId);\n if (chunk === undefined)\n throw new TypeError(`Graph fact references unknown chunk ${chunkId}.`);\n return chunk.documentId;\n }),\n ),\n ];\n return await this.transaction(options.abortSignal, async (transaction) => {\n const targets = replacementSnapshotTargets(options);\n const before = await snapshotGraphState(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n targets,\n );\n await removeDocuments(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n documentIds,\n options.orphanEntities,\n );\n await writeDocuments(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n options.documents,\n );\n await writeChunks(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n options.chunks,\n );\n await writeEntities(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels.entity,\n options.entities,\n options.conflict,\n sourceDocuments,\n );\n await writeMentions(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n options.mentions,\n );\n await writeRelationships(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels.entity,\n options.relationships,\n options.conflict,\n sourceDocuments,\n );\n const after = await snapshotGraphState(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n expandSnapshotTargets(targets, before),\n );\n return diffGraphSnapshots(before, after);\n });\n }\n\n async deleteDocuments(options: DeleteNeo4jDocumentsOptions): Promise<Neo4jGraphWriteResult> {\n validateOrphanPolicy(options.orphanEntities);\n const ids = uniqueIds(options.documentIds, \"document\");\n if (ids.length === 0) return emptyWriteResult();\n return await this.transaction(options.abortSignal, async (transaction) => {\n const targets = emptySnapshotTargets(ids);\n const before = await snapshotGraphState(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n targets,\n );\n await removeDocuments(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n ids,\n options.orphanEntities,\n );\n const after = await snapshotGraphState(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n expandSnapshotTargets(targets, before),\n );\n return diffGraphSnapshots(before, after);\n });\n }\n\n private expectedConstraints(): readonly ExpectedConstraint[] {\n const identityPrefix = this.namespace === undefined ? [] : [\"__anvia_namespace\"];\n return [\n {\n name: constraintName(this.name, \"document\"),\n label: this.resources.labels.document,\n properties: [...identityPrefix, \"__anvia_id\"],\n },\n {\n name: constraintName(this.name, \"chunk\"),\n label: this.resources.labels.chunk,\n properties: [...identityPrefix, \"__anvia_id\"],\n },\n {\n name: constraintName(this.name, \"entity\"),\n label: this.resources.labels.entity,\n properties: [...identityPrefix, \"__anvia_key\"],\n },\n ...Object.entries(this.schema.nodes).map(([type, definition]) => ({\n name: constraintName(this.name, `entity_${type}`),\n label: type,\n properties: [...identityPrefix, ...definition.identity],\n })),\n ];\n }\n}\n\nfunction validateExistingSeed(schema: Neo4jGraphSchema, seed: ExistingNeo4jSeed): SeedRegistration {\n if (seed.nodeTypes.length !== 1) {\n throw new TypeError(\n \"Each existing Neo4j seed requires exactly one indexed node type; register additional indexes as separate seeds.\",\n );\n }\n for (const type of seed.nodeTypes) {\n if (!(type in schema.nodes))\n throw new TypeError(`Neo4j seed references unknown node type ${type}.`);\n }\n validateVectorIndex(seed.vectorIndex);\n assertPropertyName(seed.vectorIndex.property);\n if (seed.fulltextIndex !== undefined) {\n validateFulltextIndex(seed.fulltextIndex, \"Existing Neo4j full-text index\");\n }\n let registration: SeedRegistration = {\n labels: Object.freeze([...seed.nodeTypes]),\n vectorIndex: Object.freeze({ ...seed.vectorIndex }),\n };\n if (seed.fulltextIndex !== undefined) {\n registration = {\n ...registration,\n fulltextIndex: Object.freeze({\n ...seed.fulltextIndex,\n properties: Object.freeze([...seed.fulltextIndex.properties]),\n }),\n };\n }\n return Object.freeze(registration);\n}\n\nfunction validateManagedResources<Schema extends Neo4jGraphSchema>(\n resources: ManagedNeo4jKnowledgeGraphOptions<Schema>[\"resources\"],\n): ManagedNeo4jKnowledgeGraphOptions<Schema>[\"resources\"] {\n const labels = Object.values(resources.labels);\n for (const label of labels) assertName(label, \"Neo4j managed label\");\n if (new Set(labels).size !== labels.length)\n throw new TypeError(\"Managed Neo4j graph labels must be distinct.\");\n const indexes = [resources.indexes.chunks.vector, resources.indexes.entities.vector];\n for (const index of indexes) validateVectorIndex(index);\n const names = [\n ...indexes.map((index) => index.name),\n resources.indexes.chunks.fulltext?.name,\n resources.indexes.entities.fulltext?.name,\n ].filter((name): name is string => name !== undefined);\n if (new Set(names).size !== names.length)\n throw new TypeError(\"Managed Neo4j index names must be unique.\");\n if (resources.indexes.entities.fulltext !== undefined) {\n const properties = resources.indexes.entities.fulltext.properties ?? [];\n if (properties.length === 0)\n throw new TypeError(\"Entity full-text indexes require explicit properties.\");\n }\n if (resources.indexes.chunks.fulltext !== undefined) {\n validateFulltextIndex(\n { ...resources.indexes.chunks.fulltext, properties: [\"__anvia_text\"] },\n \"Chunk full-text index\",\n true,\n );\n }\n if (resources.indexes.entities.fulltext !== undefined) {\n validateFulltextIndex(\n {\n ...resources.indexes.entities.fulltext,\n properties: resources.indexes.entities.fulltext.properties ?? [],\n },\n \"Entity full-text index\",\n );\n }\n const copyFulltext = (fulltext: Neo4jFulltextIndex): Neo4jFulltextIndex => {\n let copy: Neo4jFulltextIndex = { ...fulltext };\n if (fulltext.properties !== undefined) {\n copy = { ...copy, properties: Object.freeze([...fulltext.properties]) };\n }\n return Object.freeze(copy);\n };\n let chunks: (typeof resources)[\"indexes\"][\"chunks\"] = Object.freeze({\n vector: Object.freeze({ ...resources.indexes.chunks.vector }),\n });\n if (resources.indexes.chunks.fulltext !== undefined) {\n chunks = Object.freeze({\n ...chunks,\n fulltext: copyFulltext(resources.indexes.chunks.fulltext),\n });\n }\n let entities: (typeof resources)[\"indexes\"][\"entities\"] = Object.freeze({\n vector: Object.freeze({ ...resources.indexes.entities.vector }),\n });\n if (resources.indexes.entities.fulltext !== undefined) {\n entities = Object.freeze({\n ...entities,\n fulltext: copyFulltext(resources.indexes.entities.fulltext),\n });\n }\n return Object.freeze({\n labels: Object.freeze({ ...resources.labels }),\n indexes: Object.freeze({\n chunks,\n entities,\n }),\n });\n}\n\nfunction validateVectorIndex(index: Neo4jVectorIndex): void {\n assertName(index.name, \"Neo4j vector index name\");\n positiveInteger(index.dimensions, \"Neo4j vector dimensions\", 4096);\n if (index.similarity !== \"cosine\" && index.similarity !== \"euclidean\") {\n throw new TypeError(\"Neo4j vector similarity must be cosine or euclidean.\");\n }\n}\n\nfunction validateFulltextIndex(\n index: Neo4jFulltextIndex & Readonly<{ properties: readonly string[] }>,\n label: string,\n allowReservedProperties = false,\n): void {\n assertName(index.name, `${label} name`);\n if (index.properties.length === 0 || new Set(index.properties).size !== index.properties.length) {\n throw new TypeError(`${label} requires unique properties.`);\n }\n for (const property of index.properties) {\n if (allowReservedProperties) assertName(property, `${label} property`);\n else assertPropertyName(property);\n }\n}\n\ntype ExpectedIndex =\n | Readonly<{\n kind: \"vector\";\n name: string;\n labels: readonly string[];\n properties: readonly string[];\n dimensions: number;\n similarity: \"cosine\" | \"euclidean\";\n }>\n | Readonly<{\n kind: \"fulltext\";\n name: string;\n labels: readonly string[];\n properties: readonly string[];\n }>;\n\nfunction expectedIndexes(\n seeds: Readonly<Record<string, SeedRegistration>>,\n): Map<string, ExpectedIndex> {\n const expected = new Map<string, ExpectedIndex>();\n const register = (index: ExpectedIndex) => {\n const previous = expected.get(index.name);\n if (previous !== undefined && stableObject(previous) !== stableObject(index)) {\n throw new TypeError(`Neo4j index ${index.name} has conflicting registrations.`);\n }\n expected.set(index.name, index);\n };\n for (const seed of Object.values(seeds)) {\n register({\n kind: \"vector\",\n name: seed.vectorIndex.name,\n labels: seed.labels,\n properties: [seed.vectorIndex.property, ...(seed.vectorFilterProperties ?? [])],\n dimensions: seed.vectorIndex.dimensions,\n similarity: seed.vectorIndex.similarity,\n });\n if (seed.fulltextIndex !== undefined) {\n register({\n kind: \"fulltext\",\n name: seed.fulltextIndex.name,\n labels: seed.labels,\n properties: seed.fulltextIndex.properties,\n });\n }\n }\n return expected;\n}\n\nfunction validateIndexRecord(record: Neo4jRecord, expected: ExpectedIndex): void {\n const state = requiredString(record.get(\"state\"), `Neo4j index ${expected.name} state`);\n if (state !== \"ONLINE\") throw new Error(`Neo4j index ${expected.name} is ${state}, not ONLINE.`);\n const type = requiredString(record.get(\"type\"), `Neo4j index ${expected.name} type`);\n const entityType = requiredString(\n record.get(\"entityType\"),\n `Neo4j index ${expected.name} entity type`,\n );\n const labels = requiredStringArray(\n record.get(\"labelsOrTypes\"),\n `Neo4j index ${expected.name} labels`,\n );\n const properties = requiredStringArray(\n record.get(\"properties\"),\n `Neo4j index ${expected.name} properties`,\n );\n if (\n entityType !== \"NODE\" ||\n type !== expected.kind.toUpperCase() ||\n !sameStrings(labels, expected.labels) ||\n !sameStrings(properties, expected.properties)\n ) {\n throw new Error(`Neo4j index ${expected.name} does not match its registration.`);\n }\n if (expected.kind === \"vector\") {\n const options = requiredObject(record.get(\"options\"), `Neo4j index ${expected.name} options`);\n const config = requiredObject(\n options.indexConfig,\n `Neo4j index ${expected.name} vector configuration`,\n );\n const dimensions = requiredSafeInteger(\n config[\"vector.dimensions\"],\n `Neo4j index ${expected.name} dimensions`,\n );\n const similarity = requiredString(\n config[\"vector.similarity_function\"],\n `Neo4j index ${expected.name} similarity`,\n ).toLowerCase();\n if (dimensions !== expected.dimensions || similarity !== expected.similarity) {\n throw new Error(`Neo4j index ${expected.name} has incompatible vector configuration.`);\n }\n }\n}\n\nfunction validateConstraintRecord(record: Neo4jRecord, expected: ExpectedConstraint): void {\n const type = requiredString(record.get(\"type\"), `Neo4j constraint ${expected.name} type`);\n const entityType = requiredString(\n record.get(\"entityType\"),\n `Neo4j constraint ${expected.name} entity type`,\n );\n const labels = requiredStringArray(\n record.get(\"labelsOrTypes\"),\n `Neo4j constraint ${expected.name} labels`,\n );\n const properties = requiredStringArray(\n record.get(\"properties\"),\n `Neo4j constraint ${expected.name} properties`,\n );\n if (\n entityType !== \"NODE\" ||\n type !== \"UNIQUENESS\" ||\n !sameStrings(labels, [expected.label]) ||\n !sameStrings(properties, expected.properties)\n ) {\n throw new Error(`Neo4j constraint ${expected.name} does not match its registration.`);\n }\n}\n\nfunction requiredObject(value: unknown, label: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} must be an object.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction requiredStringArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value) || !value.every((item) => typeof item === \"string\")) {\n throw new TypeError(`${label} must be a string array.`);\n }\n return [...value];\n}\n\nfunction requiredSafeInteger(value: unknown, label: string): number {\n if (isInt(value)) {\n if (!value.inSafeRange()) throw new TypeError(`${label} must be a safe integer.`);\n return value.toNumber();\n }\n if (!Number.isSafeInteger(value)) throw new TypeError(`${label} must be a safe integer.`);\n return value as number;\n}\n\nfunction sameStrings(left: readonly string[], right: readonly string[]): boolean {\n if (left.length !== right.length) return false;\n const sortedLeft = [...left].sort();\n const sortedRight = [...right].sort();\n return sortedLeft.every((value, index) => value === sortedRight[index]);\n}\n\nfunction supportedVersion(value: string): boolean {\n const match = /^(\\d{4})\\.(\\d+)/.exec(value);\n if (match === null) return false;\n const year = Number(match[1]);\n const month = Number(match[2]);\n return year > 2026 || (year === 2026 && month >= 1);\n}\n\nfunction constraintName(graph: string, resource: string): string {\n return `anvia_${graph}_${resource}_identity`;\n}\n\nfunction uniquenessConstraint(name: string, label: string, properties: readonly string[]): string {\n const expression =\n properties.length === 1\n ? `n.${quoteIdentifier(properties[0] as string)}`\n : `(${properties.map((property) => `n.${quoteIdentifier(property)}`).join(\", \")})`;\n return `CREATE CONSTRAINT ${quoteIdentifier(name)} IF NOT EXISTS FOR (n:${quoteIdentifier(label)}) REQUIRE ${expression} IS UNIQUE`;\n}\n\nfunction vectorIndex(index: Neo4jVectorIndex, label: string, namespaced: boolean): string {\n const filterProperties = namespaced ? ` WITH [n.${quoteIdentifier(\"__anvia_namespace\")}]` : \"\";\n return `CREATE VECTOR INDEX ${quoteIdentifier(index.name)} IF NOT EXISTS FOR (n:${quoteIdentifier(label)}) ON (n.${quoteIdentifier(\"__anvia_embedding\")})${filterProperties} OPTIONS {indexConfig: {\\`vector.dimensions\\`: ${index.dimensions}, \\`vector.similarity_function\\`: '${index.similarity}'}}`;\n}\n\nfunction fulltextIndex(name: string, label: string, properties: readonly string[]): string {\n if (properties.length === 0) throw new TypeError(`Full-text index ${name} requires properties.`);\n return `CREATE FULLTEXT INDEX ${quoteIdentifier(name)} IF NOT EXISTS FOR (n:${quoteIdentifier(label)}) ON EACH [${properties.map((property) => `n.${quoteIdentifier(property)}`).join(\", \")}]`;\n}\n\nfunction validateReplacement<Schema extends Neo4jGraphSchema>(\n options: ReplaceNeo4jDocumentsOptions<Schema>,\n indexes: ManagedNeo4jKnowledgeGraphOptions<Schema>[\"resources\"][\"indexes\"],\n schema: Schema,\n): void {\n if (\n !Array.isArray(options.documents) ||\n !Array.isArray(options.chunks) ||\n !Array.isArray(options.entities) ||\n !Array.isArray(options.relationships) ||\n !Array.isArray(options.mentions)\n ) {\n throw new TypeError(\"Neo4j replacement collections must be arrays.\");\n }\n if (\n options.conflict !== \"error\" &&\n options.conflict !== \"overwrite\" &&\n options.conflict !== \"keep-existing\"\n ) {\n throw new TypeError(\"Neo4j conflict policy must be error, overwrite, or keep-existing.\");\n }\n validateOrphanPolicy(options.orphanEntities);\n const documentIds = uniqueIds(\n options.documents.map((document, index) => {\n requiredObject(document, `Neo4j document at index ${index}`);\n return document.id;\n }),\n \"document\",\n );\n const documentSet = new Set(documentIds);\n const chunkIds = uniqueIds(\n options.chunks.map((chunk, index) => {\n requiredObject(chunk, `Neo4j chunk at index ${index}`);\n requiredObject(chunk.document, `Neo4j chunk document at index ${index}`);\n return chunk.id;\n }),\n \"chunk\",\n );\n const chunkSet = new Set(chunkIds);\n const entityIds = uniqueIds(\n options.entities.map((entity, index) => {\n requiredObject(entity, `Neo4j entity at index ${index}`);\n requiredObject(entity.document, `Neo4j entity document at index ${index}`);\n return entity.id;\n }),\n \"entity\",\n );\n const entitySet = new Set(entityIds);\n for (const document of options.documents)\n parseNeo4jProperties(document.properties ?? {}, `document ${document.id}`);\n const chunkPositions = new Set<string>();\n for (const chunk of options.chunks) {\n if (!documentSet.has(chunk.document.documentId))\n throw new TypeError(`Chunk ${chunk.id} references an unknown document.`);\n if (chunk.document.id !== chunk.id)\n throw new TypeError(`Embedded chunk ${chunk.id} has a mismatched document id.`);\n if (!Number.isSafeInteger(chunk.document.index) || chunk.document.index < 0) {\n throw new TypeError(`Chunk ${chunk.id} index must be a non-negative safe integer.`);\n }\n if (typeof chunk.document.text !== \"string\") {\n throw new TypeError(`Chunk ${chunk.id} text must be a string.`);\n }\n const position = `${chunk.document.documentId}\\u0000${chunk.document.index}`;\n if (chunkPositions.has(position)) {\n throw new TypeError(\n `Document ${chunk.document.documentId} contains duplicate chunk index ${chunk.document.index}.`,\n );\n }\n chunkPositions.add(position);\n singleEmbedding(chunk.embeddings, indexes.chunks.vector.dimensions, `chunk ${chunk.id}`);\n parseNeo4jProperties(chunk.document.metadata ?? {}, `chunk ${chunk.id} metadata`);\n }\n const entityTypes = new Map<string, string>();\n const entitySourceChunks = new Map<string, ReadonlySet<string>>();\n for (const entity of options.entities) {\n if (entity.document.key !== entity.id)\n throw new TypeError(`Embedded entity ${entity.id} has a mismatched key.`);\n singleEmbedding(entity.embeddings, indexes.entities.vector.dimensions, `entity ${entity.id}`);\n const type = entity.document.type;\n if (typeof type !== \"string\") throw new TypeError(`Entity ${entity.id} type must be a string.`);\n const definition = schema.nodes[type];\n if (definition === undefined)\n throw new TypeError(`Entity ${entity.id} has unknown type ${type}.`);\n const properties = parseExactSchemaProperties(\n definition.properties,\n entity.document.properties,\n `entity ${entity.id} properties`,\n );\n const identity = parseIdentity(entity.document.identity, definition.identity, properties, type);\n const expectedKey = `${type}:${stableObject(identity)}`;\n if (entity.id !== expectedKey) {\n throw new TypeError(`Entity ${entity.id} does not match its canonical identity key.`);\n }\n const sourceChunkIds = validateSourceChunkIds(\n entity.document.sourceChunkIds,\n chunkSet,\n `entity ${entity.id}`,\n );\n entityTypes.set(entity.id, type);\n entitySourceChunks.set(entity.id, new Set(sourceChunkIds));\n }\n uniqueIds(\n options.relationships.map((relationship, index) => {\n requiredObject(relationship, `Neo4j relationship at index ${index}`);\n return relationship.key;\n }),\n \"relationship\",\n );\n for (const relationship of options.relationships) {\n const definition = schema.relationships[relationship.type];\n if (definition === undefined) {\n throw new TypeError(\n `Relationship ${relationship.key} has unknown type ${relationship.type}.`,\n );\n }\n if (!entitySet.has(relationship.from) || !entitySet.has(relationship.to)) {\n throw new TypeError(`Relationship ${relationship.key} references an unknown entity.`);\n }\n if (\n entityTypes.get(relationship.from) !== definition.from ||\n entityTypes.get(relationship.to) !== definition.to\n ) {\n throw new TypeError(`Relationship ${relationship.key} has incompatible endpoint types.`);\n }\n const properties = parseExactSchemaProperties(\n definition.properties,\n relationship.properties,\n `relationship ${relationship.key} properties`,\n );\n const identity = identityFromProperties(\n definition.identity ?? [],\n properties,\n relationship.type,\n );\n const expectedKey = `${relationship.type}:${relationship.from}->${relationship.to}:${stableObject(identity)}`;\n if (relationship.key !== expectedKey) {\n throw new TypeError(`Relationship ${relationship.key} does not match its canonical key.`);\n }\n const sourceChunkIds = validateSourceChunkIds(\n relationship.sourceChunkIds,\n chunkSet,\n `relationship ${relationship.key}`,\n );\n const fromSources = entitySourceChunks.get(relationship.from);\n const toSources = entitySourceChunks.get(relationship.to);\n if (\n fromSources === undefined ||\n toSources === undefined ||\n sourceChunkIds.some((chunkId) => !fromSources.has(chunkId) || !toSources.has(chunkId))\n ) {\n throw new TypeError(\n `Relationship ${relationship.key} source chunks must support both endpoint entities.`,\n );\n }\n }\n const mentionKeys = new Set<string>();\n const mentionChunksByEntity = new Map<string, Set<string>>();\n for (const [index, mention] of options.mentions.entries()) {\n requiredObject(mention, `Neo4j mention at index ${index}`);\n if (!chunkSet.has(mention.chunkId) || !entitySet.has(mention.entityKey)) {\n throw new TypeError(`Mention at index ${index} references an unknown chunk or entity.`);\n }\n const key = `${mention.chunkId}\\u0000${mention.entityKey}`;\n if (mentionKeys.has(key)) throw new TypeError(`Duplicate Neo4j mention at index ${index}.`);\n mentionKeys.add(key);\n const chunks = mentionChunksByEntity.get(mention.entityKey);\n if (chunks === undefined)\n mentionChunksByEntity.set(mention.entityKey, new Set([mention.chunkId]));\n else chunks.add(mention.chunkId);\n }\n for (const entityId of entityIds) {\n const sources = Array.from(entitySourceChunks.get(entityId) ?? []);\n const mentions = Array.from(mentionChunksByEntity.get(entityId) ?? []);\n if (!sameStrings(sources, mentions)) {\n throw new TypeError(`Entity ${entityId} source chunks must exactly match its mentions.`);\n }\n }\n}\n\nfunction parseExactSchemaProperties(\n schema: Neo4jGraphSchema[\"nodes\"][string][\"properties\"],\n value: unknown,\n label: string,\n): Neo4jProperties {\n const input = parseNeo4jProperties(value, label);\n const result = schema.safeParse(value);\n if (!result.success) throw new TypeError(`${label} does not match the graph schema.`);\n const output = parseNeo4jProperties(result.data, `${label} output`);\n if (stableObject(input) !== stableObject(output)) {\n throw new TypeError(`${label} must not be coerced, defaulted, transformed, or stripped.`);\n }\n return input;\n}\n\nfunction parseIdentity(\n value: unknown,\n keys: readonly string[],\n properties: Neo4jProperties,\n type: string,\n): Neo4jNodeIdentity {\n const identity = identityFromProperties(\n keys,\n parseNeo4jProperties(value, `${type} identity`),\n type,\n );\n if (!sameStrings(Object.keys(identity), keys)) {\n throw new TypeError(`Entity ${type} identity must contain exactly its declared properties.`);\n }\n for (const key of keys) {\n if (identity[key] !== properties[key]) {\n throw new TypeError(`Entity ${type} identity property ${key} does not match its properties.`);\n }\n }\n return identity;\n}\n\nfunction identityFromProperties(\n keys: readonly string[],\n properties: Neo4jProperties,\n type: string,\n): Neo4jNodeIdentity {\n const identity: Record<string, string | number | boolean> = {};\n for (const key of keys) {\n const value = properties[key];\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n throw new TypeError(`Identity property ${key} for ${type} must be a primitive value.`);\n }\n identity[key] = value;\n }\n return identity;\n}\n\nfunction validateSourceChunkIds(\n value: readonly string[],\n chunkIds: ReadonlySet<string>,\n label: string,\n): string[] {\n const ids = uniqueIds(value, `${label} source chunk`);\n if (ids.length === 0) throw new TypeError(`${label} requires source chunk provenance.`);\n for (const id of ids) {\n if (!chunkIds.has(id)) throw new TypeError(`${label} references unknown source chunk ${id}.`);\n }\n return ids;\n}\n\nfunction validateOrphanPolicy(value: unknown): asserts value is \"delete\" | \"keep\" {\n if (value !== \"delete\" && value !== \"keep\") {\n throw new TypeError(\"Neo4j orphan entity policy must be delete or keep.\");\n }\n}\n\nfunction singleEmbedding(\n embeddings: readonly { vector: number[] }[],\n dimensions: number,\n label: string,\n): number[] {\n if (!Array.isArray(embeddings)) throw new TypeError(`${label} embeddings must be an array.`);\n if (embeddings.length !== 1) throw new TypeError(`${label} requires exactly one embedding.`);\n const vector = embeddings[0]?.vector;\n if (vector === undefined || vector.length !== dimensions || !vector.every(Number.isFinite)) {\n throw new TypeError(`${label} has an invalid ${dimensions}-dimension embedding.`);\n }\n return vector;\n}\n\nfunction uniqueIds(ids: readonly string[], label: string): string[] {\n if (!Array.isArray(ids)) throw new TypeError(`Neo4j ${label} ids must be an array.`);\n const seen = new Set<string>();\n for (const id of ids) {\n if (typeof id !== \"string\" || id.length === 0)\n throw new TypeError(`Neo4j ${label} ids must be non-empty strings.`);\n if (seen.has(id)) throw new TypeError(`Duplicate Neo4j ${label} id: ${id}`);\n seen.add(id);\n }\n return [...seen];\n}\n\ntype SnapshotTargets = Readonly<{\n documentIds: readonly string[];\n chunkIds: readonly string[];\n entityKeys: readonly string[];\n relationshipKeys: readonly string[];\n mentions: readonly Readonly<{ chunkId: string; entityKey: string }>[];\n}>;\n\ntype GraphSnapshot = Readonly<{\n documents: ReadonlyMap<string, string>;\n chunks: ReadonlyMap<string, string>;\n entities: ReadonlyMap<string, string>;\n relationships: ReadonlyMap<string, string>;\n mentions: ReadonlyMap<string, string>;\n}>;\n\nfunction replacementSnapshotTargets(\n options: ReplaceNeo4jDocumentsOptions<Neo4jGraphSchema>,\n): SnapshotTargets {\n return {\n documentIds: options.documents.map((document) => document.id),\n chunkIds: options.chunks.map((chunk) => chunk.id),\n entityKeys: options.entities.map((entity) => entity.id),\n relationshipKeys: options.relationships.map((relationship) => relationship.key),\n mentions: options.mentions,\n };\n}\n\nfunction emptySnapshotTargets(documentIds: readonly string[]): SnapshotTargets {\n return {\n documentIds,\n chunkIds: [],\n entityKeys: [],\n relationshipKeys: [],\n mentions: [],\n };\n}\n\nfunction expandSnapshotTargets(targets: SnapshotTargets, snapshot: GraphSnapshot): SnapshotTargets {\n const mentions = new Map(\n targets.mentions.map((mention) => [mentionKey(mention.chunkId, mention.entityKey), mention]),\n );\n for (const key of snapshot.mentions.keys()) {\n const separator = key.indexOf(\"\\u0000\");\n if (separator < 0) throw new TypeError(\"Stored Neo4j mention has an invalid identity.\");\n mentions.set(key, { chunkId: key.slice(0, separator), entityKey: key.slice(separator + 1) });\n }\n return {\n documentIds: targets.documentIds,\n chunkIds: [...new Set([...targets.chunkIds, ...snapshot.chunks.keys()])],\n entityKeys: [...new Set([...targets.entityKeys, ...snapshot.entities.keys()])],\n relationshipKeys: [...new Set([...targets.relationshipKeys, ...snapshot.relationships.keys()])],\n mentions: [...mentions.values()],\n };\n}\n\nasync function snapshotGraphState(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n labels: { document: string; chunk: string; entity: string },\n targets: SnapshotTargets,\n): Promise<GraphSnapshot> {\n const documentsResult = await transaction.run(\n `MATCH (d:${quoteIdentifier(labels.document)})\nWHERE d.${quoteIdentifier(\"__anvia_id\")} IN $documentIds${tenantPredicate(\"d\", namespace, \" AND\")}\nRETURN d.${quoteIdentifier(\"__anvia_id\")} AS key, properties(d) AS properties`,\n managedParameters(graphName, namespace, { documentIds: targets.documentIds }),\n );\n const chunksResult = await transaction.run(\n `MATCH (c:${quoteIdentifier(labels.chunk)})\nOPTIONAL MATCH (d:${quoteIdentifier(labels.document)})-[:${quoteIdentifier(\"ANVIA_HAS_CHUNK\")}]->(c)\nWITH c, d WHERE (c.${quoteIdentifier(\"__anvia_id\")} IN $chunkIds OR d.${quoteIdentifier(\"__anvia_id\")} IN $documentIds)${tenantPredicate(\"c\", namespace, \" AND\")}\nRETURN c.${quoteIdentifier(\"__anvia_id\")} AS key, properties(c) AS properties`,\n managedParameters(graphName, namespace, {\n chunkIds: targets.chunkIds,\n documentIds: targets.documentIds,\n }),\n );\n const entitiesResult = await transaction.run(\n `MATCH (e:${quoteIdentifier(labels.entity)})\nWHERE e.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(\"e\", namespace, \" AND\")} AND (\n e.${quoteIdentifier(\"__anvia_key\")} IN $entityKeys OR\n any(id IN coalesce(e.${quoteIdentifier(\"__anvia_source_document_ids\")}, []) WHERE id IN $documentIds)\n)\nRETURN e.${quoteIdentifier(\"__anvia_key\")} AS key, labels(e) AS labels, properties(e) AS properties`,\n managedParameters(graphName, namespace, {\n entityKeys: targets.entityKeys,\n documentIds: targets.documentIds,\n }),\n );\n const relationshipsResult = await transaction.run(\n `MATCH ()-[r]->()\nWHERE r.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(\"r\", namespace, \" AND\")} AND (\n r.${quoteIdentifier(\"__anvia_key\")} IN $relationshipKeys OR\n any(id IN coalesce(r.${quoteIdentifier(\"__anvia_source_document_ids\")}, []) WHERE id IN $documentIds)\n)\nRETURN r.${quoteIdentifier(\"__anvia_key\")} AS key,\n type(r) AS type,\n startNode(r).${quoteIdentifier(\"__anvia_key\")} AS source,\n endNode(r).${quoteIdentifier(\"__anvia_key\")} AS target,\n properties(r) AS properties`,\n managedParameters(graphName, namespace, {\n relationshipKeys: targets.relationshipKeys,\n documentIds: targets.documentIds,\n }),\n );\n const mentionsResult = await transaction.run(\n `MATCH (c:${quoteIdentifier(labels.chunk)})-[:${quoteIdentifier(\"ANVIA_MENTIONS\")}]->(e:${quoteIdentifier(labels.entity)})\nOPTIONAL MATCH (d:${quoteIdentifier(labels.document)})-[:${quoteIdentifier(\"ANVIA_HAS_CHUNK\")}]->(c)\nWITH c, e, d WHERE (d.${quoteIdentifier(\"__anvia_id\")} IN $documentIds OR\n any(item IN $mentions WHERE item.chunkId = c.${quoteIdentifier(\"__anvia_id\")} AND item.entityKey = e.${quoteIdentifier(\"__anvia_key\")})\n)${tenantPredicate(\"c\", namespace, \" AND\")}\nRETURN c.${quoteIdentifier(\"__anvia_id\")} AS chunkId, e.${quoteIdentifier(\"__anvia_key\")} AS entityKey`,\n managedParameters(graphName, namespace, {\n documentIds: targets.documentIds,\n mentions: targets.mentions,\n }),\n );\n return {\n documents: snapshotProperties(documentsResult.records, \"document\"),\n chunks: snapshotProperties(chunksResult.records, \"chunk\"),\n entities: snapshotProperties(entitiesResult.records, \"entity\", true),\n relationships: snapshotRelationships(relationshipsResult.records),\n mentions: snapshotMentions(mentionsResult.records),\n };\n}\n\nfunction snapshotProperties(\n records: readonly Neo4jRecord[],\n resource: string,\n includeLabels = false,\n): Map<string, string> {\n const output = new Map<string, string>();\n for (const record of records) {\n const key = requiredString(record.get(\"key\"), `Neo4j ${resource} snapshot key`);\n if (output.has(key))\n throw new TypeError(`Neo4j ${resource} snapshot contains duplicate ${key}.`);\n const properties = normalizedSnapshotProperties(\n record.get(\"properties\"),\n `Neo4j ${resource} snapshot`,\n );\n const labels = includeLabels\n ? requiredStringArray(record.get(\"labels\"), `Neo4j ${resource} snapshot labels`).sort()\n : [];\n output.set(key, stableObject({ labels: labels.join(\"\\u0000\"), properties }));\n }\n return output;\n}\n\nfunction snapshotRelationships(records: readonly Neo4jRecord[]): Map<string, string> {\n const output = new Map<string, string>();\n for (const record of records) {\n const key = requiredString(record.get(\"key\"), \"Neo4j relationship snapshot key\");\n if (output.has(key))\n throw new TypeError(`Neo4j relationship snapshot contains duplicate ${key}.`);\n output.set(\n key,\n stableObject({\n source: requiredString(record.get(\"source\"), \"Neo4j relationship snapshot source\"),\n target: requiredString(record.get(\"target\"), \"Neo4j relationship snapshot target\"),\n type: requiredString(record.get(\"type\"), \"Neo4j relationship snapshot type\"),\n properties: normalizedSnapshotProperties(\n record.get(\"properties\"),\n \"Neo4j relationship snapshot\",\n ),\n }),\n );\n }\n return output;\n}\n\nfunction snapshotMentions(records: readonly Neo4jRecord[]): Map<string, string> {\n const output = new Map<string, string>();\n for (const record of records) {\n const key = mentionKey(\n requiredString(record.get(\"chunkId\"), \"Neo4j mention chunk id\"),\n requiredString(record.get(\"entityKey\"), \"Neo4j mention entity key\"),\n );\n if (output.has(key)) throw new TypeError(`Neo4j mention snapshot contains duplicate ${key}.`);\n output.set(key, key);\n }\n return output;\n}\n\nfunction normalizedSnapshotProperties(value: unknown, label: string): string {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} properties must be an object.`);\n }\n const normalized: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n normalized[key] = parseNeo4jPropertyValue(\n normalizeSnapshotDriverValue(item, `${label}.${key}`),\n `${label}.${key}`,\n );\n }\n for (const property of [\"__anvia_source_document_ids\", \"__anvia_source_chunk_ids\"]) {\n const items = normalized[property];\n if (items !== undefined) {\n if (!Array.isArray(items) || !items.every((item) => typeof item === \"string\")) {\n throw new TypeError(`${label}.${property} must be a string array.`);\n }\n normalized[property] = [...new Set(items)].sort();\n }\n }\n return stableObject(normalized);\n}\n\nfunction normalizeSnapshotDriverValue(value: unknown, label: string): unknown {\n if (isInt(value)) {\n if (!value.inSafeRange()) throw new TypeError(`${label} contains an unsafe Neo4j integer.`);\n return value.toNumber();\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => normalizeSnapshotDriverValue(item, `${label}[${index}]`));\n }\n return value;\n}\n\nfunction mentionKey(chunkId: string, entityKey: string): string {\n return `${chunkId}\\u0000${entityKey}`;\n}\n\nfunction diffGraphSnapshots(before: GraphSnapshot, after: GraphSnapshot): Neo4jGraphWriteResult {\n return {\n documents: diffSnapshotMaps(before.documents, after.documents),\n chunks: diffSnapshotMaps(before.chunks, after.chunks),\n entities: diffSnapshotMaps(before.entities, after.entities),\n relationships: diffSnapshotMaps(before.relationships, after.relationships),\n mentions: diffSnapshotMaps(before.mentions, after.mentions),\n };\n}\n\nfunction diffSnapshotMaps(\n before: ReadonlyMap<string, string>,\n after: ReadonlyMap<string, string>,\n): Neo4jGraphWriteResult[\"documents\"] {\n let created = 0;\n let updated = 0;\n let deleted = 0;\n let unchanged = 0;\n for (const key of new Set([...before.keys(), ...after.keys()])) {\n const previous = before.get(key);\n const next = after.get(key);\n if (previous === undefined) created += 1;\n else if (next === undefined) deleted += 1;\n else if (previous === next) unchanged += 1;\n else updated += 1;\n }\n return { created, updated, deleted, unchanged };\n}\n\nfunction emptyWriteResult(): Neo4jGraphWriteResult {\n const empty = () => ({ created: 0, updated: 0, deleted: 0, unchanged: 0 });\n return {\n documents: empty(),\n chunks: empty(),\n entities: empty(),\n relationships: empty(),\n mentions: empty(),\n };\n}\n\nfunction managedParameters(\n graph: string,\n namespace: string | undefined,\n parameters: Record<string, unknown>,\n): Record<string, unknown> {\n return managedScopeParameters({ graph, namespace }, parameters);\n}\n\nfunction namespacePredicate(\n variable: string,\n namespace: string | undefined,\n prefix: \" AND\" | \" WHERE\",\n): string {\n return scopeNamespacePredicate({ graph: \"\", namespace }, variable, prefix);\n}\n\nfunction tenantPredicate(\n variable: string,\n namespace: string | undefined,\n prefix: \" AND\" | \" WHERE\",\n): string {\n return tenantScopePredicate({ graph: \"\", namespace }, variable, prefix);\n}\n\nfunction namespaceMapEntry(namespace: string | undefined): string {\n return scopeNamespaceMapEntry({ graph: \"\", namespace });\n}\n\nfunction tenantMapEntries(namespace: string | undefined): string {\n return scopeTenantMapEntries({ graph: \"\", namespace });\n}\n\nfunction tenantRelationshipProperties(namespace: string | undefined): string {\n return scopeTenantRelationshipProperties({ graph: \"\", namespace });\n}\n\nasync function removeDocuments(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n labels: { document: string; chunk: string; entity: string },\n documentIds: readonly string[],\n orphanEntities: \"delete\" | \"keep\",\n): Promise<void> {\n const chunks = await transaction.run(\n `MATCH (d:${quoteIdentifier(labels.document)})-[:${quoteIdentifier(\"ANVIA_HAS_CHUNK\")}]->(c:${quoteIdentifier(labels.chunk)}) WHERE d.${quoteIdentifier(\"__anvia_id\")} IN $documentIds${tenantPredicate(\"d\", namespace, \" AND\")} RETURN collect(c.${quoteIdentifier(\"__anvia_id\")}) AS chunkIds`,\n managedParameters(graphName, namespace, { documentIds }),\n );\n const chunkIdsValue = chunks.records[0]?.get(\"chunkIds\");\n const chunkIds = requiredStringArray(chunkIdsValue, \"Neo4j replacement chunk ids\");\n await transaction.run(\n `MATCH ()-[r]->() WHERE r.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(\"r\", namespace, \" AND\")} AND any(id IN r.${quoteIdentifier(\"__anvia_source_document_ids\")} WHERE id IN $documentIds)\nSET r.${quoteIdentifier(\"__anvia_source_document_ids\")} = [id IN r.${quoteIdentifier(\"__anvia_source_document_ids\")} WHERE NOT id IN $documentIds]\nSET r.${quoteIdentifier(\"__anvia_source_chunk_ids\")} = [id IN coalesce(r.${quoteIdentifier(\"__anvia_source_chunk_ids\")}, []) WHERE NOT id IN $chunkIds]\nWITH r WHERE size(r.${quoteIdentifier(\"__anvia_source_document_ids\")}) = 0 DELETE r`,\n managedParameters(graphName, namespace, { documentIds, chunkIds }),\n );\n await transaction.run(\n `MATCH (d:${quoteIdentifier(labels.document)}) WHERE d.${quoteIdentifier(\"__anvia_id\")} IN $documentIds${tenantPredicate(\"d\", namespace, \" AND\")}\nOPTIONAL MATCH (d)-[:${quoteIdentifier(\"ANVIA_HAS_CHUNK\")}]->(c:${quoteIdentifier(labels.chunk)})\nDETACH DELETE c, d`,\n managedParameters(graphName, namespace, { documentIds }),\n );\n await transaction.run(\n `MATCH (e:${quoteIdentifier(labels.entity)})\nWHERE e.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(\"e\", namespace, \" AND\")} AND\n any(id IN coalesce(e.${quoteIdentifier(\"__anvia_source_document_ids\")}, []) WHERE id IN $documentIds)\nSET e.${quoteIdentifier(\"__anvia_source_document_ids\")} = [id IN e.${quoteIdentifier(\"__anvia_source_document_ids\")} WHERE NOT id IN $documentIds],\n e.${quoteIdentifier(\"__anvia_source_chunk_ids\")} = [id IN coalesce(e.${quoteIdentifier(\"__anvia_source_chunk_ids\")}, []) WHERE NOT id IN $chunkIds]\nWITH e WHERE $deleteOrphans AND size(e.${quoteIdentifier(\"__anvia_source_document_ids\")}) = 0\nDETACH DELETE e`,\n managedParameters(graphName, namespace, {\n documentIds,\n chunkIds,\n deleteOrphans: orphanEntities === \"delete\",\n }),\n );\n}\n\nasync function writeDocuments(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n labels: { document: string },\n documents: readonly { id: string; properties?: Neo4jProperties | undefined }[],\n): Promise<void> {\n await transaction.run(\n `UNWIND $rows AS row MERGE (d:${quoteIdentifier(labels.document)} {${quoteIdentifier(\"__anvia_id\")}: row.id${namespaceMapEntry(namespace)}}) ${namespace === undefined ? \"SET d += row.properties\" : `SET d.${quoteIdentifier(\"__anvia_graph\")} = $graph, d += row.properties`}`,\n managedParameters(graphName, namespace, {\n rows: documents.map((document) => ({\n id: document.id,\n properties: document.properties ?? {},\n })),\n }),\n );\n}\n\nasync function writeChunks(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n labels: { document: string; chunk: string },\n chunks: ReplaceNeo4jDocumentsOptions<Neo4jGraphSchema>[\"chunks\"],\n): Promise<void> {\n const rows = chunks.map((chunk) => ({\n id: chunk.id,\n documentId: chunk.document.documentId,\n index: chunk.document.index,\n text: chunk.document.text,\n metadata: chunk.document.metadata ?? {},\n embedding: chunk.embeddings[0]?.vector,\n }));\n await transaction.run(\n `UNWIND $rows AS row\nMATCH (d:${quoteIdentifier(labels.document)} {${quoteIdentifier(\"__anvia_id\")}: row.documentId})\n${tenantPredicate(\"d\", namespace, \" WHERE\")}\nCREATE (c:${quoteIdentifier(labels.chunk)} {${quoteIdentifier(\"__anvia_id\")}: row.id, ${quoteIdentifier(\"__anvia_document_id\")}: row.documentId, ${quoteIdentifier(\"__anvia_index\")}: row.index, ${quoteIdentifier(\"__anvia_text\")}: row.text, ${quoteIdentifier(\"__anvia_embedding\")}: row.embedding${tenantMapEntries(namespace)}})\nSET c += row.metadata\nCREATE (d)-[:${quoteIdentifier(\"ANVIA_HAS_CHUNK\")}${tenantRelationshipProperties(namespace)}]->(c)`,\n managedParameters(graphName, namespace, { rows }),\n );\n const pairs = [...rows]\n .sort(\n (left, right) => left.documentId.localeCompare(right.documentId) || left.index - right.index,\n )\n .flatMap((row, index, all) => {\n const next = all[index + 1];\n return next !== undefined && next.documentId === row.documentId\n ? [{ from: row.id, to: next.id }]\n : [];\n });\n if (pairs.length > 0) {\n await transaction.run(\n `UNWIND $rows AS row MATCH (a:${quoteIdentifier(labels.chunk)} {${quoteIdentifier(\"__anvia_id\")}: row.from${namespaceMapEntry(namespace)}}), (b:${quoteIdentifier(labels.chunk)} {${quoteIdentifier(\"__anvia_id\")}: row.to${namespaceMapEntry(namespace)}}) CREATE (a)-[:${quoteIdentifier(\"ANVIA_NEXT_CHUNK\")}${tenantRelationshipProperties(namespace)}]->(b)`,\n managedParameters(graphName, namespace, { rows: pairs }),\n );\n }\n}\n\nasync function writeEntities<Schema extends Neo4jGraphSchema>(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n entityLabel: string,\n entities: ReplaceNeo4jDocumentsOptions<Schema>[\"entities\"],\n conflict: ReplaceNeo4jDocumentsOptions<Schema>[\"conflict\"],\n sourceDocuments: (sourceChunkIds: readonly string[]) => readonly string[],\n): Promise<void> {\n const grouped = groupBy(entities, (entity) => entity.document.type);\n for (const [type, values] of grouped) {\n const rows = values.map((entity) => ({\n key: entity.id,\n properties: entity.document.properties,\n embedding: entity.embeddings[0]?.vector,\n sourceDocumentIds: sourceDocuments(entity.document.sourceChunkIds),\n sourceChunkIds: entity.document.sourceChunkIds,\n }));\n if (conflict === \"error\")\n await assertEntityConflicts(transaction, graphName, namespace, entityLabel, rows);\n const propertySet = conflictPropertySet(\"e\", conflict);\n const embedding = entityEmbeddingExpression(conflict);\n await transaction.run(\n `UNWIND $rows AS row\nMERGE (e:${quoteIdentifier(entityLabel)}:${quoteIdentifier(type)} {${quoteIdentifier(\"__anvia_key\")}: row.key${namespaceMapEntry(namespace)}})\n${propertySet}\nSET e.${quoteIdentifier(\"__anvia_key\")} = row.key,\n e.${quoteIdentifier(\"__anvia_graph\")} = $graph,\n e.${quoteIdentifier(\"__anvia_namespace\")} = coalesce($namespace, e.${quoteIdentifier(\"__anvia_namespace\")}),\n e.${quoteIdentifier(\"__anvia_embedding\")} = ${embedding},\n e.${quoteIdentifier(\"__anvia_source_document_ids\")} = reduce(all = existingDocumentIds, id IN row.sourceDocumentIds | CASE WHEN id IN all THEN all ELSE all + id END),\n e.${quoteIdentifier(\"__anvia_source_chunk_ids\")} = reduce(all = existingChunkIds, id IN row.sourceChunkIds | CASE WHEN id IN all THEN all ELSE all + id END)`,\n managedParameters(graphName, namespace, { rows }),\n );\n }\n}\n\nasync function assertEntityConflicts(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n entityLabel: string,\n rows: readonly { key: string; properties: Neo4jProperties }[],\n): Promise<void> {\n const result = await transaction.run(\n `UNWIND $keys AS key MATCH (e:${quoteIdentifier(entityLabel)} {${quoteIdentifier(\"__anvia_key\")}: key${namespaceMapEntry(namespace)}}) WHERE e.${quoteIdentifier(\"__anvia_graph\")} = $graph RETURN key, properties(e) AS properties`,\n managedParameters(graphName, namespace, { keys: rows.map((row) => row.key) }),\n );\n const incoming = new Map(rows.map((row) => [row.key, row.properties]));\n for (const record of result.records) {\n const key = requiredString(record.get(\"key\"), \"Neo4j entity key\");\n const existing = applicationProperties(record.get(\"properties\"));\n if (stableObject(existing) !== stableObject(incoming.get(key) ?? {})) {\n throw new Error(`Neo4j entity ${key} conflicts with existing properties.`);\n }\n }\n}\n\nasync function writeMentions(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n labels: { chunk: string; entity: string },\n mentions: readonly { chunkId: string; entityKey: string }[],\n): Promise<void> {\n if (mentions.length === 0) return;\n await transaction.run(\n `UNWIND $rows AS row\nMATCH (c:${quoteIdentifier(labels.chunk)} {${quoteIdentifier(\"__anvia_id\")}: row.chunkId${namespaceMapEntry(namespace)}}), (e:${quoteIdentifier(labels.entity)} {${quoteIdentifier(\"__anvia_key\")}: row.entityKey${namespaceMapEntry(namespace)}})\n${namespace === undefined ? \"\" : `WHERE c.${quoteIdentifier(\"__anvia_graph\")} = $graph AND e.${quoteIdentifier(\"__anvia_graph\")} = $graph`}\nMERGE (c)-[:${quoteIdentifier(\"ANVIA_MENTIONS\")}${tenantRelationshipProperties(namespace)}]->(e)`,\n managedParameters(graphName, namespace, { rows: mentions }),\n );\n}\n\nasync function writeRelationships<Schema extends Neo4jGraphSchema>(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n entityLabel: string,\n relationships: readonly import(\"./types.js\").Neo4jGraphRelationship<Schema>[],\n conflict: ReplaceNeo4jDocumentsOptions<Schema>[\"conflict\"],\n sourceDocuments: (sourceChunkIds: readonly string[]) => readonly string[],\n): Promise<void> {\n const grouped = groupBy(relationships, (relationship) => relationship.type);\n for (const [type, values] of grouped) {\n const rows = values.map((relationship) => ({\n key: relationship.key,\n from: relationship.from,\n to: relationship.to,\n properties: relationship.properties,\n sourceDocumentIds: sourceDocuments(relationship.sourceChunkIds),\n sourceChunkIds: relationship.sourceChunkIds,\n }));\n if (conflict === \"error\") {\n const existing = await transaction.run(\n `UNWIND $keys AS key MATCH ()-[r:${quoteIdentifier(type)} {${quoteIdentifier(\"__anvia_key\")}: key${namespaceMapEntry(namespace)}}]->() WHERE r.${quoteIdentifier(\"__anvia_graph\")} = $graph RETURN key, properties(r) AS properties`,\n managedParameters(graphName, namespace, { keys: rows.map((row) => row.key) }),\n );\n const incoming = new Map(rows.map((row) => [row.key, row.properties]));\n for (const record of existing.records) {\n const key = requiredString(record.get(\"key\"), \"Neo4j relationship key\");\n if (\n stableObject(applicationProperties(record.get(\"properties\"))) !==\n stableObject(incoming.get(key) ?? {})\n ) {\n throw new Error(`Neo4j relationship ${key} conflicts with existing properties.`);\n }\n }\n }\n const propertySet = conflictPropertySet(\"r\", conflict);\n await transaction.run(\n `UNWIND $rows AS row\nMATCH (a:${quoteIdentifier(entityLabel)} {${quoteIdentifier(\"__anvia_key\")}: row.from${namespaceMapEntry(namespace)}}), (b:${quoteIdentifier(entityLabel)} {${quoteIdentifier(\"__anvia_key\")}: row.to${namespaceMapEntry(namespace)}})\nWHERE a.${quoteIdentifier(\"__anvia_graph\")} = $graph AND b.${quoteIdentifier(\"__anvia_graph\")} = $graph\nMERGE (a)-[r:${quoteIdentifier(type)} {${quoteIdentifier(\"__anvia_key\")}: row.key${namespaceMapEntry(namespace)}}]->(b)\n${propertySet}\nSET r.${quoteIdentifier(\"__anvia_key\")} = row.key,\n r.${quoteIdentifier(\"__anvia_graph\")} = $graph,\n r.${quoteIdentifier(\"__anvia_namespace\")} = coalesce($namespace, r.${quoteIdentifier(\"__anvia_namespace\")}),\n r.${quoteIdentifier(\"__anvia_source_document_ids\")} = reduce(all = existingDocumentIds, id IN row.sourceDocumentIds | CASE WHEN id IN all THEN all ELSE all + id END),\n r.${quoteIdentifier(\"__anvia_source_chunk_ids\")} = reduce(all = existingChunkIds, id IN row.sourceChunkIds | CASE WHEN id IN all THEN all ELSE all + id END)`,\n managedParameters(graphName, namespace, { rows }),\n );\n }\n}\n\nfunction conflictPropertySet(variable: \"e\" | \"r\", conflict: Neo4jGraphConflict): string {\n const sourceDocuments = quoteIdentifier(\"__anvia_source_document_ids\");\n const sourceChunks = quoteIdentifier(\"__anvia_source_chunk_ids\");\n const existingSources = `WITH ${variable}, row,\n coalesce(${variable}.${sourceDocuments}, []) AS existingDocumentIds,\n coalesce(${variable}.${sourceChunks}, []) AS existingChunkIds`;\n if (conflict === \"keep-existing\") {\n return `ON CREATE SET ${variable} += row.properties\n${existingSources}`;\n }\n if (conflict === \"overwrite\") {\n return `${existingSources}\nSET ${variable} = row.properties`;\n }\n return `${existingSources}\nSET ${variable} += row.properties`;\n}\n\nfunction entityEmbeddingExpression(conflict: Neo4jGraphConflict): string {\n if (conflict === \"keep-existing\") {\n return `coalesce(e.${quoteIdentifier(\"__anvia_embedding\")}, row.embedding)`;\n }\n return \"row.embedding\";\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== \"string\") throw new TypeError(`${label} must be a string.`);\n return value;\n}\n\nfunction applicationProperties(value: unknown): Neo4jProperties {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return {};\n return parseNeo4jProperties(\n Object.fromEntries(Object.entries(value).filter(([key]) => !key.startsWith(\"__anvia_\"))),\n \"stored Neo4j properties\",\n );\n}\n\nfunction groupBy<Value, Key>(\n values: readonly Value[],\n keyFor: (value: Value) => Key,\n): Map<Key, Value[]> {\n const groups = new Map<Key, Value[]>();\n for (const value of values) {\n const key = keyFor(value);\n const group = groups.get(key);\n if (group === undefined) groups.set(key, [value]);\n else group.push(value);\n }\n return groups;\n}\n"],"mappings":";AAAA,SAAS,SAAS;AASlB,IAAM,iBAAiB;AAEhB,SAAS,uBACd,SAC2B;AAC3B,MAAI,OAAO,KAAK,QAAQ,KAAK,EAAE,WAAW,GAAG;AAC3C,UAAM,IAAI,UAAU,uDAAuD;AAAA,EAC7E;AACA,aAAW,CAAC,MAAM,UAAU,KAAK,OAAO,QAAQ,QAAQ,KAAK,GAAG;AAC9D,eAAW,MAAM,WAAW;AAC5B,sBAAkB,WAAW,aAAa,QAAQ,IAAI,EAAE;AACxD,QAAI,EAAE,WAAW,sBAAsB,EAAE,YAAY;AACnD,YAAM,IAAI,UAAU,uBAAuB,IAAI,+BAA+B;AAAA,IAChF;AACA,8BAA0B,WAAW,YAAY,QAAQ,IAAI,EAAE;AAC/D,QACE,WAAW,SAAS,WAAW,KAC/B,IAAI,IAAI,WAAW,QAAQ,EAAE,SAAS,WAAW,SAAS,QAC1D;AACA,YAAM,IAAI,UAAU,QAAQ,IAAI,2CAA2C;AAAA,IAC7E;AACA,UAAM,QAAQ,WAAW,WAAW;AACpC,eAAW,YAAY,WAAW,UAAU;AAC1C,yBAAmB,QAAQ;AAC3B,UAAI,EAAE,YAAY,QAAQ;AACxB,cAAM,IAAI,UAAU,qBAAqB,QAAQ,4BAA4B,IAAI,GAAG;AAAA,MACtF;AAAA,IACF;AACA,eAAW,YAAY,OAAO,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AAC;AAAA,IACvF;AAAA,EACF;AACF;AAEA,SAAS,QACP,QACA,QACmB;AACnB,QAAM,SAAS,oBAAI,IAAkB;AACrC,aAAW,SAAS,QAAQ;AAC1B,UAAM,MAAM,OAAO,KAAK;AACxB,UAAM,QAAQ,OAAO,IAAI,GAAG;AAC5B,QAAI,UAAU,OAAW,QAAO,IAAI,KAAK,CAAC,KAAK,CAAC;AAAA,QAC3C,OAAM,KAAK,KAAK;AAAA,EACvB;AACA,SAAO;AACT;","names":["isInt","isInt","namespacePredicate","namespaceMapEntry","tenantMapEntries","tenantRelationshipProperties"]}
@@ -10,7 +10,7 @@ import {
10
10
  strictProperties,
11
11
  tenantScopePredicate,
12
12
  throwIfAborted
13
- } from "./chunk-EUZ5C6OC.js";
13
+ } from "./chunk-IVKNAFKG.js";
14
14
 
15
15
  // src/retrieve.ts
16
16
  import { embedText } from "@anvia/core/embeddings";
@@ -524,4 +524,4 @@ function groupBy(values, keyFor) {
524
524
  export {
525
525
  retrieveGraphContext
526
526
  };
527
- //# sourceMappingURL=chunk-YCJZAWLH.js.map
527
+ //# sourceMappingURL=chunk-QTIUFXDY.js.map
@@ -6,7 +6,7 @@ import {
6
6
  managedScopePredicate,
7
7
  parseNeo4jProperties,
8
8
  quoteIdentifier
9
- } from "./chunk-EUZ5C6OC.js";
9
+ } from "./chunk-IVKNAFKG.js";
10
10
 
11
11
  // src/explore.ts
12
12
  import {
@@ -211,4 +211,4 @@ function objectValue(value, label) {
211
211
  export {
212
212
  exploreGraph
213
213
  };
214
- //# sourceMappingURL=chunk-QY7IO247.js.map
214
+ //# sourceMappingURL=chunk-V33PR5HS.js.map
@@ -0,0 +1,8 @@
1
+ import {
2
+ exploreGraph
3
+ } from "./chunk-V33PR5HS.js";
4
+ import "./chunk-IVKNAFKG.js";
5
+ export {
6
+ exploreGraph
7
+ };
8
+ //# sourceMappingURL=explore-PNLRCONH.js.map
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import {
2
2
  retrieveGraphContext
3
- } from "./chunk-YCJZAWLH.js";
3
+ } from "./chunk-QTIUFXDY.js";
4
4
  import {
5
5
  exploreGraph
6
- } from "./chunk-QY7IO247.js";
6
+ } from "./chunk-V33PR5HS.js";
7
7
  import {
8
8
  ManagedNeo4jKnowledgeGraph,
9
9
  Neo4jKnowledgeGraph,
10
10
  defineNeo4jGraphSchema,
11
11
  neo4jTenantScope
12
- } from "./chunk-EUZ5C6OC.js";
12
+ } from "./chunk-IVKNAFKG.js";
13
13
 
14
14
  // src/client.ts
15
15
  import { createHash } from "crypto";
@@ -0,0 +1,8 @@
1
+ import {
2
+ retrieveGraphContext
3
+ } from "./chunk-QTIUFXDY.js";
4
+ import "./chunk-IVKNAFKG.js";
5
+ export {
6
+ retrieveGraphContext
7
+ };
8
+ //# sourceMappingURL=retrieve-A6UD55NM.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anvia/neo4j",
3
- "version": "1.1.3",
3
+ "version": "1.1.5",
4
4
  "description": "Schema-first Neo4j GraphRAG integration for Anvia.",
5
5
  "author": "anvia",
6
6
  "license": "MIT",
@@ -26,19 +26,19 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "neo4j-driver": "^6.2.0",
29
- "@anvia/graph": "1.1.3"
29
+ "@anvia/graph": "1.1.5"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "^24.9.1",
33
33
  "tsup": "^8.5.0",
34
34
  "typescript": "^5.9.3",
35
- "vitest": "^4.0.8",
36
- "zod": "^4.5.4",
37
- "@anvia/core": "1.2.0"
35
+ "vitest": "^4.1.11",
36
+ "zod": "^4.6.5",
37
+ "@anvia/core": "1.6.1"
38
38
  },
39
39
  "peerDependencies": {
40
- "zod": "^4.4.0",
41
- "@anvia/core": "^1.2.0"
40
+ "zod": "^4.6.5",
41
+ "@anvia/core": "^1.6.1"
42
42
  },
43
43
  "scripts": {
44
44
  "build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/schema.ts","../src/helpers.ts","../src/managed-scope.ts","../src/graph.ts"],"sourcesContent":["import { z } from \"zod\";\nimport type {\n Neo4jGraphSchema,\n Neo4jGraphSchemaOptions,\n Neo4jProperties,\n Neo4jPropertyPrimitive,\n Neo4jPropertyValue,\n} from \"./types.js\";\n\nconst reservedPrefix = \"__anvia_\";\n\nexport function defineNeo4jGraphSchema<const Options extends Neo4jGraphSchemaOptions>(\n options: Options,\n): Neo4jGraphSchema<Options> {\n if (Object.keys(options.nodes).length === 0) {\n throw new TypeError(\"A Neo4j graph schema requires at least one node type.\");\n }\n for (const [type, definition] of Object.entries(options.nodes)) {\n assertName(type, \"node type\");\n assertDescription(definition.description, `node ${type}`);\n if (!(definition.properties instanceof z.ZodObject)) {\n throw new TypeError(`Properties for node ${type} must be a Zod object schema.`);\n }\n assertExactPropertySchema(definition.properties, `node ${type}`);\n if (\n definition.identity.length === 0 ||\n new Set(definition.identity).size !== definition.identity.length\n ) {\n throw new TypeError(`Node ${type} must declare unique identity properties.`);\n }\n const shape = definition.properties.shape;\n for (const property of definition.identity) {\n assertPropertyName(property);\n if (!(property in shape)) {\n throw new TypeError(`Identity property ${property} is not declared by node ${type}.`);\n }\n }\n for (const property of Object.keys(shape)) assertPropertyName(property);\n }\n for (const [type, definition] of Object.entries(options.relationships)) {\n assertName(type, \"relationship type\");\n assertDescription(definition.description, `relationship ${type}`);\n if (!(definition.from in options.nodes) || !(definition.to in options.nodes)) {\n throw new TypeError(`Relationship ${type} references an unknown endpoint type.`);\n }\n if (!(definition.properties instanceof z.ZodObject)) {\n throw new TypeError(`Properties for relationship ${type} must be a Zod object schema.`);\n }\n assertExactPropertySchema(definition.properties, `relationship ${type}`);\n const identity = definition.identity ?? [];\n if (new Set(identity).size !== identity.length) {\n throw new TypeError(`Relationship ${type} contains duplicate identity properties.`);\n }\n for (const property of Object.keys(definition.properties.shape)) assertPropertyName(property);\n for (const property of identity) {\n if (!(property in definition.properties.shape)) {\n throw new TypeError(\n `Identity property ${property} is not declared by relationship ${type}.`,\n );\n }\n }\n }\n const nodes = Object.fromEntries(\n Object.entries(options.nodes).map(([type, definition]) => [\n type,\n Object.freeze({ ...definition, identity: Object.freeze([...definition.identity]) }),\n ]),\n );\n const relationships = Object.fromEntries(\n Object.entries(options.relationships).map(([type, definition]) => {\n const copy = { ...definition };\n if (definition.identity !== undefined) {\n Object.assign(copy, { identity: Object.freeze([...definition.identity]) });\n }\n return [type, Object.freeze(copy)];\n }),\n );\n return Object.freeze({\n nodes: Object.freeze(nodes),\n relationships: Object.freeze(relationships),\n kind: \"neo4j-graph-schema\" as const,\n }) as Neo4jGraphSchema<Options>;\n}\n\nexport function parseNeo4jProperties(value: unknown, label: string): Neo4jProperties {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} must be an object of Neo4j property values.`);\n }\n const output: Record<string, Neo4jPropertyValue> = {};\n for (const [key, item] of Object.entries(value)) {\n assertPropertyName(key);\n output[key] = parseNeo4jPropertyValue(item, `${label}.${key}`);\n }\n return output;\n}\n\nexport function parseNeo4jPropertyValue(value: unknown, label: string): Neo4jPropertyValue {\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new TypeError(`${label} must be finite.`);\n if (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n throw new TypeError(`${label} must be a safe integer.`);\n }\n return value;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) return [];\n const parsed = value.map((item, index) => parsePrimitive(item, `${label}[${index}]`));\n const type = typeof parsed[0];\n if (!parsed.every((item) => typeof item === type)) {\n throw new TypeError(`${label} must be a homogeneous array.`);\n }\n return parsed as Neo4jPropertyValue;\n }\n throw new TypeError(`${label} is not a supported Neo4j property value.`);\n}\n\nfunction parsePrimitive(value: unknown, label: string): Neo4jPropertyPrimitive {\n const parsed = parseNeo4jPropertyValue(value, label);\n if (typeof parsed === \"string\" || typeof parsed === \"number\" || typeof parsed === \"boolean\") {\n return parsed;\n }\n throw new TypeError(`${label} must be a primitive property value.`);\n}\n\nexport function assertName(value: string, label: string): void {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string.`);\n }\n}\n\nexport function assertPropertyName(value: string): void {\n assertName(value, \"Neo4j property name\");\n if (value.startsWith(reservedPrefix)) {\n throw new TypeError(`Neo4j property names beginning with ${reservedPrefix} are reserved.`);\n }\n}\n\nfunction assertDescription(value: string, label: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`${label} requires a non-empty description.`);\n }\n}\n\nfunction assertExactPropertySchema(schema: z.ZodObject<z.ZodRawShape>, label: string): void {\n const definition = schema._zod.def;\n if (!(definition.catchall instanceof z.ZodNever)) {\n throw new TypeError(`${label} properties must use a strict Zod object schema.`);\n }\n for (const [property, propertySchema] of Object.entries(schema.shape)) {\n assertNonEffectfulSchema(propertySchema, `${label} property ${property}`, new Set());\n }\n}\n\nfunction assertNonEffectfulSchema(value: unknown, label: string, visited: Set<z.ZodType>): void {\n if (!(value instanceof z.ZodType)) {\n throw new TypeError(`${label} must be a Zod schema.`);\n }\n const schema = value;\n if (visited.has(schema)) return;\n visited.add(schema);\n const definition = schema._zod.def as unknown as Record<string, unknown>;\n const type = definition.type;\n if (\n definition.coerce === true ||\n type === \"default\" ||\n type === \"prefault\" ||\n type === \"catch\" ||\n type === \"transform\" ||\n type === \"pipe\"\n ) {\n throw new TypeError(\n `${label} must not coerce, default, transform, preprocess, or catch values.`,\n );\n }\n const checks = definition.checks;\n if (\n Array.isArray(checks) &&\n checks.some((check) => {\n if (typeof check !== \"object\" || check === null) return false;\n const internals = (check as { _zod?: { def?: { check?: unknown } } })._zod;\n return internals?.def?.check === \"overwrite\";\n })\n ) {\n throw new TypeError(`${label} must not normalize or overwrite values.`);\n }\n for (const child of schemaChildren(definition)) {\n assertNonEffectfulSchema(child, label, visited);\n }\n}\n\nfunction schemaChildren(definition: Record<string, unknown>): z.ZodType[] {\n const children: z.ZodType[] = [];\n for (const key of [\"innerType\", \"element\", \"left\", \"right\", \"rest\", \"keyType\", \"valueType\"]) {\n const value = definition[key];\n if (value instanceof z.ZodType) children.push(value);\n }\n for (const key of [\"options\", \"items\"]) {\n const value = definition[key];\n if (Array.isArray(value)) {\n for (const item of value) if (item instanceof z.ZodType) children.push(item);\n }\n }\n return children;\n}\n","import { isInt } from \"neo4j-driver\";\nimport { parseNeo4jProperties } from \"./schema.js\";\nimport type { Neo4jProperties } from \"./types.js\";\n\nexport function quoteIdentifier(value: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(\"Neo4j identifiers must be non-empty strings.\");\n }\n if (value.includes(\"\\u0000\")) throw new TypeError(\"Neo4j identifiers must not contain NUL.\");\n return `\\`${value.replaceAll(\"`\", \"``\")}\\``;\n}\n\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw abortError();\n }\n}\n\nexport function abortError(): Error {\n const error = new Error(\"The operation was aborted.\");\n error.name = \"AbortError\";\n return error;\n}\n\nexport function positiveInteger(value: number, label: string, maximum?: number): number {\n if (!Number.isSafeInteger(value) || value < 1 || (maximum !== undefined && value > maximum)) {\n throw new RangeError(\n `${label} must be a positive safe integer${maximum === undefined ? \"\" : ` no greater than ${maximum}`}.`,\n );\n }\n return value;\n}\n\nexport function finiteScore(value: number | undefined, label: string): void {\n if (value !== undefined && !Number.isFinite(value))\n throw new RangeError(`${label} must be finite.`);\n}\n\nexport function strictProperties(value: unknown, label: string): Neo4jProperties {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} must be an object.`);\n }\n const normalized: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value))\n normalized[key] = normalizeDriverValue(item, `${label}.${key}`);\n return parseNeo4jProperties(normalized, label);\n}\n\nfunction normalizeDriverValue(value: unknown, label: string): unknown {\n if (isInt(value)) {\n if (!value.inSafeRange()) throw new TypeError(`${label} contains an unsafe Neo4j integer.`);\n return value.toNumber();\n }\n if (Array.isArray(value))\n return value.map((item, index) => normalizeDriverValue(item, `${label}[${index}]`));\n return value;\n}\n\nexport function stableObject(value: Readonly<Record<string, unknown>>): string {\n return JSON.stringify(\n Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right))),\n );\n}\n","import { quoteIdentifier } from \"./helpers.js\";\n\nexport type Neo4jManagedScope = Readonly<{\n graph: string;\n namespace?: string | undefined;\n}>;\n\nexport function managedScopeParameters(\n scope: Neo4jManagedScope | undefined,\n parameters: Record<string, unknown>,\n): Record<string, unknown> {\n return scope === undefined\n ? parameters\n : { graph: scope.graph, namespace: scope.namespace ?? null, ...parameters };\n}\n\nexport function managedScopePredicate(\n scope: Neo4jManagedScope | undefined,\n variable: string,\n prefix: \" WHERE\" | \" AND\" | \"WHERE\" | \"AND\",\n): string {\n if (scope === undefined) return \"\";\n return `${prefix} ${variable}.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(scope, variable, \" AND\")}`;\n}\n\nexport function namespacePredicate(\n scope: Neo4jManagedScope,\n variable: string,\n prefix: \" WHERE\" | \" AND\" | \"WHERE\" | \"AND\",\n): string {\n return scope.namespace === undefined\n ? \"\"\n : `${prefix} ${variable}.${quoteIdentifier(\"__anvia_namespace\")} = $namespace`;\n}\n\nexport function tenantScopePredicate(\n scope: Neo4jManagedScope,\n variable: string,\n prefix: \" WHERE\" | \" AND\" | \"WHERE\" | \"AND\",\n): string {\n return scope.namespace === undefined ? \"\" : managedScopePredicate(scope, variable, prefix);\n}\n\nexport function managedPathPredicate(\n scope: Neo4jManagedScope | undefined,\n relationships: boolean,\n): string {\n if (scope === undefined) return \"\";\n const item = `item.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(scope, \"item\", \" AND\")}`;\n const nodes = ` AND all(item IN nodes(path) WHERE ${item})`;\n return relationships ? `${nodes}\\n AND all(item IN relationships(path) WHERE ${item})` : nodes;\n}\n\nexport function namespaceMapEntry(scope: Neo4jManagedScope): string {\n return scope.namespace === undefined\n ? \"\"\n : `, ${quoteIdentifier(\"__anvia_namespace\")}: $namespace`;\n}\n\nexport function tenantMapEntries(scope: Neo4jManagedScope): string {\n return scope.namespace === undefined\n ? \"\"\n : `, ${quoteIdentifier(\"__anvia_graph\")}: $graph, ${quoteIdentifier(\"__anvia_namespace\")}: $namespace`;\n}\n\nexport function tenantRelationshipProperties(scope: Neo4jManagedScope): string {\n return scope.namespace === undefined\n ? \"\"\n : ` {${quoteIdentifier(\"__anvia_graph\")}: $graph, ${quoteIdentifier(\"__anvia_namespace\")}: $namespace}`;\n}\n","import {\n type GraphContext,\n type GraphExploreOptions,\n type GraphExploreResult,\n type GraphRetrieveOptions,\n} from \"@anvia/graph\";\nimport {\n isInt,\n type ManagedTransaction,\n type Record as Neo4jRecord,\n type QueryResult,\n type SessionConfig,\n} from \"neo4j-driver\";\nimport type { Neo4jClient } from \"./client.js\";\nimport {\n abortError,\n positiveInteger,\n quoteIdentifier,\n stableObject,\n throwIfAborted,\n} from \"./helpers.js\";\nimport {\n managedScopeParameters,\n namespaceMapEntry as scopeNamespaceMapEntry,\n namespacePredicate as scopeNamespacePredicate,\n tenantMapEntries as scopeTenantMapEntries,\n tenantRelationshipProperties as scopeTenantRelationshipProperties,\n tenantScopePredicate,\n} from \"./managed-scope.js\";\nimport {\n assertName,\n assertPropertyName,\n parseNeo4jProperties,\n parseNeo4jPropertyValue,\n} from \"./schema.js\";\nimport type {\n DeleteNeo4jDocumentsOptions,\n ExistingNeo4jSeed,\n ManagedNeo4jKnowledgeGraphOptions,\n Neo4jFulltextIndex,\n Neo4jGraphConflict,\n Neo4jGraphEnsureOptions,\n Neo4jGraphEvidenceCapability,\n Neo4jGraphSchema,\n Neo4jGraphValidateOptions,\n Neo4jGraphWriteResult,\n Neo4jKnowledgeGraphOptions,\n Neo4jNodeIdentity,\n Neo4jProperties,\n Neo4jVectorIndex,\n ReplaceNeo4jDocumentsOptions,\n} from \"./types.js\";\n\ntype SeedRegistration = Readonly<{\n labels: readonly string[];\n vectorIndex: Neo4jVectorIndex & Readonly<{ property: string }>;\n vectorFilterProperties?: readonly string[] | undefined;\n fulltextIndex?: (Neo4jFulltextIndex & Readonly<{ properties: readonly string[] }>) | undefined;\n entryRelationshipType?: string | undefined;\n}>;\n\ntype ExpectedConstraint = Readonly<{\n name: string;\n label: string;\n properties: readonly string[];\n}>;\n\ntype GraphTransaction = Pick<ManagedTransaction, \"run\">;\n\nconst tenantScopeBrand: unique symbol = Symbol(\"Neo4jTenantScope\");\n\nexport type Neo4jTenantScope = Readonly<{\n namespace: string;\n [tenantScopeBrand]: true;\n}>;\n\nexport function neo4jTenantScope(namespace: string): Neo4jTenantScope {\n return Object.freeze({ namespace, [tenantScopeBrand]: true as const });\n}\n\nexport abstract class Neo4jKnowledgeGraphBase<\n Schema extends Neo4jGraphSchema = Neo4jGraphSchema,\n Evidence extends Neo4jGraphEvidenceCapability = Neo4jGraphEvidenceCapability,\n> {\n abstract readonly seeds: Readonly<Record<string, SeedRegistration>>;\n abstract readonly evidenceCapability: Evidence;\n\n protected constructor(\n protected readonly owner: Neo4jClient,\n readonly schema: Schema,\n readonly namespace?: string | undefined,\n ) {\n if (schema.kind !== \"neo4j-graph-schema\" && schema.kind !== \"graph-schema\") {\n throw new TypeError(\n \"Neo4j knowledge graphs require defineGraphSchema() or defineNeo4jGraphSchema().\",\n );\n }\n }\n\n async validate(options: Neo4jGraphValidateOptions = {}): Promise<void> {\n throwIfAborted(options.abortSignal);\n await this.assertSupportedVersion(options.abortSignal);\n const expected = expectedIndexes(this.seeds);\n const names = [...expected.keys()];\n const result = await this.query(\n \"SHOW INDEXES YIELD name, state, type, entityType, labelsOrTypes, properties, options WHERE name IN $names RETURN name, state, type, entityType, labelsOrTypes, properties, options\",\n { names },\n options.abortSignal,\n );\n const actual = new Map(\n result.records.map((record) => [\n requiredString(record.get(\"name\"), \"Neo4j index name\"),\n record,\n ]),\n );\n for (const [name, definition] of expected) {\n const record = actual.get(name);\n if (record === undefined) throw new Error(`Neo4j index ${name} does not exist.`);\n validateIndexRecord(record, definition);\n }\n }\n\n async query(\n text: string,\n parameters: Record<string, unknown>,\n abortSignal?: AbortSignal,\n access: \"read\" | \"write\" = \"read\",\n ): Promise<QueryResult> {\n return this.runTransaction(\n access,\n abortSignal,\n async (transaction) => await transaction.run(text, parameters),\n );\n }\n\n async retrieve(options: GraphRetrieveOptions<Schema, Evidence>): Promise<GraphContext> {\n const { retrieveGraphContext } = await import(\"./retrieve.js\");\n return retrieveGraphContext({\n ...options,\n graph: this,\n } as import(\"./types.js\").RetrieveGraphContextOptions<Schema>);\n }\n\n async explore(options: GraphExploreOptions<Schema>): Promise<GraphExploreResult> {\n const { exploreGraph } = await import(\"./explore.js\");\n return exploreGraph(this, options);\n }\n\n seed(name: string): SeedRegistration {\n const seed = this.seeds[name];\n if (seed === undefined) throw new TypeError(`Unknown Neo4j graph seed: ${name}`);\n return seed;\n }\n\n protected async transaction<T>(\n abortSignal: AbortSignal | undefined,\n run: (transaction: GraphTransaction) => Promise<T>,\n ): Promise<T> {\n return this.runTransaction(\"write\", abortSignal, run);\n }\n\n private async runTransaction<T>(\n access: \"read\" | \"write\",\n abortSignal: AbortSignal | undefined,\n run: (transaction: GraphTransaction) => Promise<T>,\n ): Promise<T> {\n throwIfAborted(abortSignal);\n const sessionOptions: SessionConfig = {\n defaultAccessMode: access === \"read\" ? \"READ\" : \"WRITE\",\n };\n if (this.owner.database !== undefined) {\n Object.assign(sessionOptions, { database: this.owner.database });\n }\n const session = this.owner.nativeDriver().session(sessionOptions);\n const transaction = session.beginTransaction();\n let rejectAbort: ((error: Error) => void) | undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n });\n const onAbort = () => {\n rejectAbort?.(abortError());\n };\n abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n let committing = false;\n try {\n const value = await Promise.race([run(transaction), aborted]);\n throwIfAborted(abortSignal);\n committing = true;\n await transaction.commit();\n return value;\n } catch (error) {\n if (transaction.isOpen()) await transaction.rollback();\n if (!committing && abortSignal?.aborted) throw abortError();\n throw error;\n } finally {\n abortSignal?.removeEventListener(\"abort\", onAbort);\n if (transaction.isOpen()) await transaction.rollback();\n await session.close();\n }\n }\n\n private async assertSupportedVersion(abortSignal?: AbortSignal): Promise<void> {\n const result = await this.query(\n \"CALL dbms.components() YIELD versions RETURN versions[0] AS version LIMIT 1\",\n {},\n abortSignal,\n );\n const version = result.records[0]?.get(\"version\");\n if (typeof version !== \"string\") {\n throw new TypeError(\"Neo4j returned a non-string server version.\");\n }\n if (!supportedVersion(version)) {\n throw new Error(`@anvia/neo4j requires Neo4j 2026.01 or newer; received ${version}.`);\n }\n }\n}\n\nexport class Neo4jKnowledgeGraph<Schema extends Neo4jGraphSchema> extends Neo4jKnowledgeGraphBase<\n Schema,\n \"none\"\n> {\n readonly evidenceCapability = \"none\" as const;\n readonly seeds: Readonly<Record<string, SeedRegistration>>;\n\n constructor(owner: Neo4jClient, options: Neo4jKnowledgeGraphOptions<Schema>) {\n super(owner, options.schema);\n if (Object.keys(options.seeds).length === 0) {\n throw new TypeError(\"An existing Neo4j knowledge graph requires at least one seed.\");\n }\n const seeds: Record<string, SeedRegistration> = {};\n for (const [name, seed] of Object.entries(options.seeds)) {\n assertName(name, \"Neo4j seed name\");\n seeds[name] = validateExistingSeed(options.schema, seed);\n }\n this.seeds = Object.freeze(seeds);\n }\n}\n\nexport class ManagedNeo4jKnowledgeGraph<\n Schema extends Neo4jGraphSchema,\n> extends Neo4jKnowledgeGraphBase<Schema, \"chunks\"> {\n readonly evidenceCapability = \"chunks\" as const;\n readonly seeds: Readonly<Record<string, SeedRegistration>>;\n readonly resources: ManagedNeo4jKnowledgeGraphOptions<Schema>[\"resources\"];\n readonly name: string;\n\n constructor(\n owner: Neo4jClient,\n options: ManagedNeo4jKnowledgeGraphOptions<Schema>,\n tenantScope?: Neo4jTenantScope,\n ) {\n const namespace = tenantScope?.namespace;\n super(owner, options.schema, namespace);\n assertName(options.name, \"Managed Neo4j graph name\");\n if (namespace !== undefined) assertName(namespace, \"Managed Neo4j namespace\");\n this.name = options.name;\n this.resources = validateManagedResources(options.resources);\n let chunks: SeedRegistration = {\n labels: Object.freeze([this.resources.labels.chunk]),\n vectorIndex: Object.freeze({\n ...this.resources.indexes.chunks.vector,\n property: \"__anvia_embedding\",\n }),\n vectorFilterProperties:\n this.namespace === undefined ? undefined : Object.freeze([\"__anvia_namespace\"]),\n entryRelationshipType: \"ANVIA_MENTIONS\",\n };\n if (this.resources.indexes.chunks.fulltext !== undefined) {\n chunks = {\n ...chunks,\n fulltextIndex: Object.freeze({\n ...this.resources.indexes.chunks.fulltext,\n properties: Object.freeze([\n \"__anvia_text\",\n ...(this.namespace === undefined ? [] : [\"__anvia_namespace\"]),\n ]),\n }),\n };\n }\n let entities: SeedRegistration = {\n labels: Object.freeze([this.resources.labels.entity]),\n vectorIndex: Object.freeze({\n ...this.resources.indexes.entities.vector,\n property: \"__anvia_embedding\",\n }),\n vectorFilterProperties:\n this.namespace === undefined ? undefined : Object.freeze([\"__anvia_namespace\"]),\n };\n if (this.resources.indexes.entities.fulltext !== undefined) {\n entities = {\n ...entities,\n fulltextIndex: Object.freeze({\n ...this.resources.indexes.entities.fulltext,\n properties: Object.freeze([\n ...(this.resources.indexes.entities.fulltext.properties ?? []),\n ...(this.namespace === undefined ? [] : [\"__anvia_namespace\"]),\n ]),\n }),\n };\n }\n this.seeds = Object.freeze({\n chunks: Object.freeze(chunks),\n entities: Object.freeze(entities),\n });\n }\n\n async ensure(options: Neo4jGraphEnsureOptions): Promise<void> {\n positiveInteger(options.indexTimeoutMs, \"Neo4j index timeout\");\n throwIfAborted(options.abortSignal);\n const { labels, indexes } = this.resources;\n const identityPrefix = this.namespace === undefined ? [] : [\"__anvia_namespace\"];\n const statements = [\n uniquenessConstraint(constraintName(this.name, \"document\"), labels.document, [\n ...identityPrefix,\n \"__anvia_id\",\n ]),\n uniquenessConstraint(constraintName(this.name, \"chunk\"), labels.chunk, [\n ...identityPrefix,\n \"__anvia_id\",\n ]),\n uniquenessConstraint(constraintName(this.name, \"entity\"), labels.entity, [\n ...identityPrefix,\n \"__anvia_key\",\n ]),\n ...Object.entries(this.schema.nodes).map(([type, definition]) =>\n uniquenessConstraint(constraintName(this.name, `entity_${type}`), type, [\n ...identityPrefix,\n ...definition.identity,\n ]),\n ),\n vectorIndex(indexes.chunks.vector, labels.chunk, this.namespace !== undefined),\n vectorIndex(indexes.entities.vector, labels.entity, this.namespace !== undefined),\n ];\n if (indexes.chunks.fulltext !== undefined) {\n statements.push(\n fulltextIndex(indexes.chunks.fulltext.name, labels.chunk, [\n \"__anvia_text\",\n ...(this.namespace === undefined ? [] : [\"__anvia_namespace\"]),\n ]),\n );\n }\n if (indexes.entities.fulltext !== undefined) {\n statements.push(\n fulltextIndex(indexes.entities.fulltext.name, labels.entity, [\n ...(indexes.entities.fulltext.properties ?? []),\n ...(this.namespace === undefined ? [] : [\"__anvia_namespace\"]),\n ]),\n );\n }\n for (const statement of statements)\n await this.query(statement, {}, options.abortSignal, \"write\");\n await this.query(\n \"CALL db.awaitIndexes($timeoutSeconds)\",\n { timeoutSeconds: Math.ceil(options.indexTimeoutMs / 1000) },\n options.abortSignal,\n );\n await this.validate({ abortSignal: options.abortSignal });\n }\n\n override async validate(options: Neo4jGraphValidateOptions = {}): Promise<void> {\n await super.validate(options);\n const expected = this.expectedConstraints();\n const names = expected.map((constraint) => constraint.name);\n const result = await this.query(\n \"SHOW CONSTRAINTS YIELD name, type, entityType, labelsOrTypes, properties WHERE name IN $names RETURN name, type, entityType, labelsOrTypes, properties\",\n { names },\n options.abortSignal,\n );\n const actual = new Map(\n result.records.map((record) => [\n requiredString(record.get(\"name\"), \"Neo4j constraint name\"),\n record,\n ]),\n );\n for (const constraint of expected) {\n const record = actual.get(constraint.name);\n if (record === undefined) {\n throw new Error(`Neo4j constraint ${constraint.name} does not exist.`);\n }\n validateConstraintRecord(record, constraint);\n }\n }\n\n async replaceDocuments(\n options: ReplaceNeo4jDocumentsOptions<Schema>,\n ): Promise<Neo4jGraphWriteResult> {\n validateReplacement(options, this.resources.indexes, this.schema);\n if (options.documents.length === 0) return emptyWriteResult();\n const documentIds = options.documents.map((document) => document.id);\n const chunksById = new Map(options.chunks.map((chunk) => [chunk.id, chunk.document]));\n const sourceDocuments = (sourceChunkIds: readonly string[]) => [\n ...new Set(\n sourceChunkIds.map((chunkId) => {\n const chunk = chunksById.get(chunkId);\n if (chunk === undefined)\n throw new TypeError(`Graph fact references unknown chunk ${chunkId}.`);\n return chunk.documentId;\n }),\n ),\n ];\n return await this.transaction(options.abortSignal, async (transaction) => {\n const targets = replacementSnapshotTargets(options);\n const before = await snapshotGraphState(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n targets,\n );\n await removeDocuments(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n documentIds,\n options.orphanEntities,\n );\n await writeDocuments(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n options.documents,\n );\n await writeChunks(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n options.chunks,\n );\n await writeEntities(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels.entity,\n options.entities,\n options.conflict,\n sourceDocuments,\n );\n await writeMentions(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n options.mentions,\n );\n await writeRelationships(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels.entity,\n options.relationships,\n options.conflict,\n sourceDocuments,\n );\n const after = await snapshotGraphState(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n expandSnapshotTargets(targets, before),\n );\n return diffGraphSnapshots(before, after);\n });\n }\n\n async deleteDocuments(options: DeleteNeo4jDocumentsOptions): Promise<Neo4jGraphWriteResult> {\n validateOrphanPolicy(options.orphanEntities);\n const ids = uniqueIds(options.documentIds, \"document\");\n if (ids.length === 0) return emptyWriteResult();\n return await this.transaction(options.abortSignal, async (transaction) => {\n const targets = emptySnapshotTargets(ids);\n const before = await snapshotGraphState(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n targets,\n );\n await removeDocuments(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n ids,\n options.orphanEntities,\n );\n const after = await snapshotGraphState(\n transaction,\n this.name,\n this.namespace,\n this.resources.labels,\n expandSnapshotTargets(targets, before),\n );\n return diffGraphSnapshots(before, after);\n });\n }\n\n private expectedConstraints(): readonly ExpectedConstraint[] {\n const identityPrefix = this.namespace === undefined ? [] : [\"__anvia_namespace\"];\n return [\n {\n name: constraintName(this.name, \"document\"),\n label: this.resources.labels.document,\n properties: [...identityPrefix, \"__anvia_id\"],\n },\n {\n name: constraintName(this.name, \"chunk\"),\n label: this.resources.labels.chunk,\n properties: [...identityPrefix, \"__anvia_id\"],\n },\n {\n name: constraintName(this.name, \"entity\"),\n label: this.resources.labels.entity,\n properties: [...identityPrefix, \"__anvia_key\"],\n },\n ...Object.entries(this.schema.nodes).map(([type, definition]) => ({\n name: constraintName(this.name, `entity_${type}`),\n label: type,\n properties: [...identityPrefix, ...definition.identity],\n })),\n ];\n }\n}\n\nfunction validateExistingSeed(schema: Neo4jGraphSchema, seed: ExistingNeo4jSeed): SeedRegistration {\n if (seed.nodeTypes.length !== 1) {\n throw new TypeError(\n \"Each existing Neo4j seed requires exactly one indexed node type; register additional indexes as separate seeds.\",\n );\n }\n for (const type of seed.nodeTypes) {\n if (!(type in schema.nodes))\n throw new TypeError(`Neo4j seed references unknown node type ${type}.`);\n }\n validateVectorIndex(seed.vectorIndex);\n assertPropertyName(seed.vectorIndex.property);\n if (seed.fulltextIndex !== undefined) {\n validateFulltextIndex(seed.fulltextIndex, \"Existing Neo4j full-text index\");\n }\n let registration: SeedRegistration = {\n labels: Object.freeze([...seed.nodeTypes]),\n vectorIndex: Object.freeze({ ...seed.vectorIndex }),\n };\n if (seed.fulltextIndex !== undefined) {\n registration = {\n ...registration,\n fulltextIndex: Object.freeze({\n ...seed.fulltextIndex,\n properties: Object.freeze([...seed.fulltextIndex.properties]),\n }),\n };\n }\n return Object.freeze(registration);\n}\n\nfunction validateManagedResources<Schema extends Neo4jGraphSchema>(\n resources: ManagedNeo4jKnowledgeGraphOptions<Schema>[\"resources\"],\n): ManagedNeo4jKnowledgeGraphOptions<Schema>[\"resources\"] {\n const labels = Object.values(resources.labels);\n for (const label of labels) assertName(label, \"Neo4j managed label\");\n if (new Set(labels).size !== labels.length)\n throw new TypeError(\"Managed Neo4j graph labels must be distinct.\");\n const indexes = [resources.indexes.chunks.vector, resources.indexes.entities.vector];\n for (const index of indexes) validateVectorIndex(index);\n const names = [\n ...indexes.map((index) => index.name),\n resources.indexes.chunks.fulltext?.name,\n resources.indexes.entities.fulltext?.name,\n ].filter((name): name is string => name !== undefined);\n if (new Set(names).size !== names.length)\n throw new TypeError(\"Managed Neo4j index names must be unique.\");\n if (resources.indexes.entities.fulltext !== undefined) {\n const properties = resources.indexes.entities.fulltext.properties ?? [];\n if (properties.length === 0)\n throw new TypeError(\"Entity full-text indexes require explicit properties.\");\n }\n if (resources.indexes.chunks.fulltext !== undefined) {\n validateFulltextIndex(\n { ...resources.indexes.chunks.fulltext, properties: [\"__anvia_text\"] },\n \"Chunk full-text index\",\n true,\n );\n }\n if (resources.indexes.entities.fulltext !== undefined) {\n validateFulltextIndex(\n {\n ...resources.indexes.entities.fulltext,\n properties: resources.indexes.entities.fulltext.properties ?? [],\n },\n \"Entity full-text index\",\n );\n }\n const copyFulltext = (fulltext: Neo4jFulltextIndex): Neo4jFulltextIndex => {\n let copy: Neo4jFulltextIndex = { ...fulltext };\n if (fulltext.properties !== undefined) {\n copy = { ...copy, properties: Object.freeze([...fulltext.properties]) };\n }\n return Object.freeze(copy);\n };\n let chunks: (typeof resources)[\"indexes\"][\"chunks\"] = Object.freeze({\n vector: Object.freeze({ ...resources.indexes.chunks.vector }),\n });\n if (resources.indexes.chunks.fulltext !== undefined) {\n chunks = Object.freeze({\n ...chunks,\n fulltext: copyFulltext(resources.indexes.chunks.fulltext),\n });\n }\n let entities: (typeof resources)[\"indexes\"][\"entities\"] = Object.freeze({\n vector: Object.freeze({ ...resources.indexes.entities.vector }),\n });\n if (resources.indexes.entities.fulltext !== undefined) {\n entities = Object.freeze({\n ...entities,\n fulltext: copyFulltext(resources.indexes.entities.fulltext),\n });\n }\n return Object.freeze({\n labels: Object.freeze({ ...resources.labels }),\n indexes: Object.freeze({\n chunks,\n entities,\n }),\n });\n}\n\nfunction validateVectorIndex(index: Neo4jVectorIndex): void {\n assertName(index.name, \"Neo4j vector index name\");\n positiveInteger(index.dimensions, \"Neo4j vector dimensions\", 4096);\n if (index.similarity !== \"cosine\" && index.similarity !== \"euclidean\") {\n throw new TypeError(\"Neo4j vector similarity must be cosine or euclidean.\");\n }\n}\n\nfunction validateFulltextIndex(\n index: Neo4jFulltextIndex & Readonly<{ properties: readonly string[] }>,\n label: string,\n allowReservedProperties = false,\n): void {\n assertName(index.name, `${label} name`);\n if (index.properties.length === 0 || new Set(index.properties).size !== index.properties.length) {\n throw new TypeError(`${label} requires unique properties.`);\n }\n for (const property of index.properties) {\n if (allowReservedProperties) assertName(property, `${label} property`);\n else assertPropertyName(property);\n }\n}\n\ntype ExpectedIndex =\n | Readonly<{\n kind: \"vector\";\n name: string;\n labels: readonly string[];\n properties: readonly string[];\n dimensions: number;\n similarity: \"cosine\" | \"euclidean\";\n }>\n | Readonly<{\n kind: \"fulltext\";\n name: string;\n labels: readonly string[];\n properties: readonly string[];\n }>;\n\nfunction expectedIndexes(\n seeds: Readonly<Record<string, SeedRegistration>>,\n): Map<string, ExpectedIndex> {\n const expected = new Map<string, ExpectedIndex>();\n const register = (index: ExpectedIndex) => {\n const previous = expected.get(index.name);\n if (previous !== undefined && stableObject(previous) !== stableObject(index)) {\n throw new TypeError(`Neo4j index ${index.name} has conflicting registrations.`);\n }\n expected.set(index.name, index);\n };\n for (const seed of Object.values(seeds)) {\n register({\n kind: \"vector\",\n name: seed.vectorIndex.name,\n labels: seed.labels,\n properties: [seed.vectorIndex.property, ...(seed.vectorFilterProperties ?? [])],\n dimensions: seed.vectorIndex.dimensions,\n similarity: seed.vectorIndex.similarity,\n });\n if (seed.fulltextIndex !== undefined) {\n register({\n kind: \"fulltext\",\n name: seed.fulltextIndex.name,\n labels: seed.labels,\n properties: seed.fulltextIndex.properties,\n });\n }\n }\n return expected;\n}\n\nfunction validateIndexRecord(record: Neo4jRecord, expected: ExpectedIndex): void {\n const state = requiredString(record.get(\"state\"), `Neo4j index ${expected.name} state`);\n if (state !== \"ONLINE\") throw new Error(`Neo4j index ${expected.name} is ${state}, not ONLINE.`);\n const type = requiredString(record.get(\"type\"), `Neo4j index ${expected.name} type`);\n const entityType = requiredString(\n record.get(\"entityType\"),\n `Neo4j index ${expected.name} entity type`,\n );\n const labels = requiredStringArray(\n record.get(\"labelsOrTypes\"),\n `Neo4j index ${expected.name} labels`,\n );\n const properties = requiredStringArray(\n record.get(\"properties\"),\n `Neo4j index ${expected.name} properties`,\n );\n if (\n entityType !== \"NODE\" ||\n type !== expected.kind.toUpperCase() ||\n !sameStrings(labels, expected.labels) ||\n !sameStrings(properties, expected.properties)\n ) {\n throw new Error(`Neo4j index ${expected.name} does not match its registration.`);\n }\n if (expected.kind === \"vector\") {\n const options = requiredObject(record.get(\"options\"), `Neo4j index ${expected.name} options`);\n const config = requiredObject(\n options.indexConfig,\n `Neo4j index ${expected.name} vector configuration`,\n );\n const dimensions = requiredSafeInteger(\n config[\"vector.dimensions\"],\n `Neo4j index ${expected.name} dimensions`,\n );\n const similarity = requiredString(\n config[\"vector.similarity_function\"],\n `Neo4j index ${expected.name} similarity`,\n ).toLowerCase();\n if (dimensions !== expected.dimensions || similarity !== expected.similarity) {\n throw new Error(`Neo4j index ${expected.name} has incompatible vector configuration.`);\n }\n }\n}\n\nfunction validateConstraintRecord(record: Neo4jRecord, expected: ExpectedConstraint): void {\n const type = requiredString(record.get(\"type\"), `Neo4j constraint ${expected.name} type`);\n const entityType = requiredString(\n record.get(\"entityType\"),\n `Neo4j constraint ${expected.name} entity type`,\n );\n const labels = requiredStringArray(\n record.get(\"labelsOrTypes\"),\n `Neo4j constraint ${expected.name} labels`,\n );\n const properties = requiredStringArray(\n record.get(\"properties\"),\n `Neo4j constraint ${expected.name} properties`,\n );\n if (\n entityType !== \"NODE\" ||\n type !== \"UNIQUENESS\" ||\n !sameStrings(labels, [expected.label]) ||\n !sameStrings(properties, expected.properties)\n ) {\n throw new Error(`Neo4j constraint ${expected.name} does not match its registration.`);\n }\n}\n\nfunction requiredObject(value: unknown, label: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} must be an object.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction requiredStringArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value) || !value.every((item) => typeof item === \"string\")) {\n throw new TypeError(`${label} must be a string array.`);\n }\n return [...value];\n}\n\nfunction requiredSafeInteger(value: unknown, label: string): number {\n if (isInt(value)) {\n if (!value.inSafeRange()) throw new TypeError(`${label} must be a safe integer.`);\n return value.toNumber();\n }\n if (!Number.isSafeInteger(value)) throw new TypeError(`${label} must be a safe integer.`);\n return value as number;\n}\n\nfunction sameStrings(left: readonly string[], right: readonly string[]): boolean {\n if (left.length !== right.length) return false;\n const sortedLeft = [...left].sort();\n const sortedRight = [...right].sort();\n return sortedLeft.every((value, index) => value === sortedRight[index]);\n}\n\nfunction supportedVersion(value: string): boolean {\n const match = /^(\\d{4})\\.(\\d+)/.exec(value);\n if (match === null) return false;\n const year = Number(match[1]);\n const month = Number(match[2]);\n return year > 2026 || (year === 2026 && month >= 1);\n}\n\nfunction constraintName(graph: string, resource: string): string {\n return `anvia_${graph}_${resource}_identity`;\n}\n\nfunction uniquenessConstraint(name: string, label: string, properties: readonly string[]): string {\n const expression =\n properties.length === 1\n ? `n.${quoteIdentifier(properties[0] as string)}`\n : `(${properties.map((property) => `n.${quoteIdentifier(property)}`).join(\", \")})`;\n return `CREATE CONSTRAINT ${quoteIdentifier(name)} IF NOT EXISTS FOR (n:${quoteIdentifier(label)}) REQUIRE ${expression} IS UNIQUE`;\n}\n\nfunction vectorIndex(index: Neo4jVectorIndex, label: string, namespaced: boolean): string {\n const filterProperties = namespaced ? ` WITH [n.${quoteIdentifier(\"__anvia_namespace\")}]` : \"\";\n return `CREATE VECTOR INDEX ${quoteIdentifier(index.name)} IF NOT EXISTS FOR (n:${quoteIdentifier(label)}) ON (n.${quoteIdentifier(\"__anvia_embedding\")})${filterProperties} OPTIONS {indexConfig: {\\`vector.dimensions\\`: ${index.dimensions}, \\`vector.similarity_function\\`: '${index.similarity}'}}`;\n}\n\nfunction fulltextIndex(name: string, label: string, properties: readonly string[]): string {\n if (properties.length === 0) throw new TypeError(`Full-text index ${name} requires properties.`);\n return `CREATE FULLTEXT INDEX ${quoteIdentifier(name)} IF NOT EXISTS FOR (n:${quoteIdentifier(label)}) ON EACH [${properties.map((property) => `n.${quoteIdentifier(property)}`).join(\", \")}]`;\n}\n\nfunction validateReplacement<Schema extends Neo4jGraphSchema>(\n options: ReplaceNeo4jDocumentsOptions<Schema>,\n indexes: ManagedNeo4jKnowledgeGraphOptions<Schema>[\"resources\"][\"indexes\"],\n schema: Schema,\n): void {\n if (\n !Array.isArray(options.documents) ||\n !Array.isArray(options.chunks) ||\n !Array.isArray(options.entities) ||\n !Array.isArray(options.relationships) ||\n !Array.isArray(options.mentions)\n ) {\n throw new TypeError(\"Neo4j replacement collections must be arrays.\");\n }\n if (\n options.conflict !== \"error\" &&\n options.conflict !== \"overwrite\" &&\n options.conflict !== \"keep-existing\"\n ) {\n throw new TypeError(\"Neo4j conflict policy must be error, overwrite, or keep-existing.\");\n }\n validateOrphanPolicy(options.orphanEntities);\n const documentIds = uniqueIds(\n options.documents.map((document, index) => {\n requiredObject(document, `Neo4j document at index ${index}`);\n return document.id;\n }),\n \"document\",\n );\n const documentSet = new Set(documentIds);\n const chunkIds = uniqueIds(\n options.chunks.map((chunk, index) => {\n requiredObject(chunk, `Neo4j chunk at index ${index}`);\n requiredObject(chunk.document, `Neo4j chunk document at index ${index}`);\n return chunk.id;\n }),\n \"chunk\",\n );\n const chunkSet = new Set(chunkIds);\n const entityIds = uniqueIds(\n options.entities.map((entity, index) => {\n requiredObject(entity, `Neo4j entity at index ${index}`);\n requiredObject(entity.document, `Neo4j entity document at index ${index}`);\n return entity.id;\n }),\n \"entity\",\n );\n const entitySet = new Set(entityIds);\n for (const document of options.documents)\n parseNeo4jProperties(document.properties ?? {}, `document ${document.id}`);\n const chunkPositions = new Set<string>();\n for (const chunk of options.chunks) {\n if (!documentSet.has(chunk.document.documentId))\n throw new TypeError(`Chunk ${chunk.id} references an unknown document.`);\n if (chunk.document.id !== chunk.id)\n throw new TypeError(`Embedded chunk ${chunk.id} has a mismatched document id.`);\n if (!Number.isSafeInteger(chunk.document.index) || chunk.document.index < 0) {\n throw new TypeError(`Chunk ${chunk.id} index must be a non-negative safe integer.`);\n }\n if (typeof chunk.document.text !== \"string\") {\n throw new TypeError(`Chunk ${chunk.id} text must be a string.`);\n }\n const position = `${chunk.document.documentId}\\u0000${chunk.document.index}`;\n if (chunkPositions.has(position)) {\n throw new TypeError(\n `Document ${chunk.document.documentId} contains duplicate chunk index ${chunk.document.index}.`,\n );\n }\n chunkPositions.add(position);\n singleEmbedding(chunk.embeddings, indexes.chunks.vector.dimensions, `chunk ${chunk.id}`);\n parseNeo4jProperties(chunk.document.metadata ?? {}, `chunk ${chunk.id} metadata`);\n }\n const entityTypes = new Map<string, string>();\n const entitySourceChunks = new Map<string, ReadonlySet<string>>();\n for (const entity of options.entities) {\n if (entity.document.key !== entity.id)\n throw new TypeError(`Embedded entity ${entity.id} has a mismatched key.`);\n singleEmbedding(entity.embeddings, indexes.entities.vector.dimensions, `entity ${entity.id}`);\n const type = entity.document.type;\n if (typeof type !== \"string\") throw new TypeError(`Entity ${entity.id} type must be a string.`);\n const definition = schema.nodes[type];\n if (definition === undefined)\n throw new TypeError(`Entity ${entity.id} has unknown type ${type}.`);\n const properties = parseExactSchemaProperties(\n definition.properties,\n entity.document.properties,\n `entity ${entity.id} properties`,\n );\n const identity = parseIdentity(entity.document.identity, definition.identity, properties, type);\n const expectedKey = `${type}:${stableObject(identity)}`;\n if (entity.id !== expectedKey) {\n throw new TypeError(`Entity ${entity.id} does not match its canonical identity key.`);\n }\n const sourceChunkIds = validateSourceChunkIds(\n entity.document.sourceChunkIds,\n chunkSet,\n `entity ${entity.id}`,\n );\n entityTypes.set(entity.id, type);\n entitySourceChunks.set(entity.id, new Set(sourceChunkIds));\n }\n uniqueIds(\n options.relationships.map((relationship, index) => {\n requiredObject(relationship, `Neo4j relationship at index ${index}`);\n return relationship.key;\n }),\n \"relationship\",\n );\n for (const relationship of options.relationships) {\n const definition = schema.relationships[relationship.type];\n if (definition === undefined) {\n throw new TypeError(\n `Relationship ${relationship.key} has unknown type ${relationship.type}.`,\n );\n }\n if (!entitySet.has(relationship.from) || !entitySet.has(relationship.to)) {\n throw new TypeError(`Relationship ${relationship.key} references an unknown entity.`);\n }\n if (\n entityTypes.get(relationship.from) !== definition.from ||\n entityTypes.get(relationship.to) !== definition.to\n ) {\n throw new TypeError(`Relationship ${relationship.key} has incompatible endpoint types.`);\n }\n const properties = parseExactSchemaProperties(\n definition.properties,\n relationship.properties,\n `relationship ${relationship.key} properties`,\n );\n const identity = identityFromProperties(\n definition.identity ?? [],\n properties,\n relationship.type,\n );\n const expectedKey = `${relationship.type}:${relationship.from}->${relationship.to}:${stableObject(identity)}`;\n if (relationship.key !== expectedKey) {\n throw new TypeError(`Relationship ${relationship.key} does not match its canonical key.`);\n }\n const sourceChunkIds = validateSourceChunkIds(\n relationship.sourceChunkIds,\n chunkSet,\n `relationship ${relationship.key}`,\n );\n const fromSources = entitySourceChunks.get(relationship.from);\n const toSources = entitySourceChunks.get(relationship.to);\n if (\n fromSources === undefined ||\n toSources === undefined ||\n sourceChunkIds.some((chunkId) => !fromSources.has(chunkId) || !toSources.has(chunkId))\n ) {\n throw new TypeError(\n `Relationship ${relationship.key} source chunks must support both endpoint entities.`,\n );\n }\n }\n const mentionKeys = new Set<string>();\n const mentionChunksByEntity = new Map<string, Set<string>>();\n for (const [index, mention] of options.mentions.entries()) {\n requiredObject(mention, `Neo4j mention at index ${index}`);\n if (!chunkSet.has(mention.chunkId) || !entitySet.has(mention.entityKey)) {\n throw new TypeError(`Mention at index ${index} references an unknown chunk or entity.`);\n }\n const key = `${mention.chunkId}\\u0000${mention.entityKey}`;\n if (mentionKeys.has(key)) throw new TypeError(`Duplicate Neo4j mention at index ${index}.`);\n mentionKeys.add(key);\n const chunks = mentionChunksByEntity.get(mention.entityKey);\n if (chunks === undefined)\n mentionChunksByEntity.set(mention.entityKey, new Set([mention.chunkId]));\n else chunks.add(mention.chunkId);\n }\n for (const entityId of entityIds) {\n const sources = Array.from(entitySourceChunks.get(entityId) ?? []);\n const mentions = Array.from(mentionChunksByEntity.get(entityId) ?? []);\n if (!sameStrings(sources, mentions)) {\n throw new TypeError(`Entity ${entityId} source chunks must exactly match its mentions.`);\n }\n }\n}\n\nfunction parseExactSchemaProperties(\n schema: Neo4jGraphSchema[\"nodes\"][string][\"properties\"],\n value: unknown,\n label: string,\n): Neo4jProperties {\n const input = parseNeo4jProperties(value, label);\n const result = schema.safeParse(value);\n if (!result.success) throw new TypeError(`${label} does not match the graph schema.`);\n const output = parseNeo4jProperties(result.data, `${label} output`);\n if (stableObject(input) !== stableObject(output)) {\n throw new TypeError(`${label} must not be coerced, defaulted, transformed, or stripped.`);\n }\n return input;\n}\n\nfunction parseIdentity(\n value: unknown,\n keys: readonly string[],\n properties: Neo4jProperties,\n type: string,\n): Neo4jNodeIdentity {\n const identity = identityFromProperties(\n keys,\n parseNeo4jProperties(value, `${type} identity`),\n type,\n );\n if (!sameStrings(Object.keys(identity), keys)) {\n throw new TypeError(`Entity ${type} identity must contain exactly its declared properties.`);\n }\n for (const key of keys) {\n if (identity[key] !== properties[key]) {\n throw new TypeError(`Entity ${type} identity property ${key} does not match its properties.`);\n }\n }\n return identity;\n}\n\nfunction identityFromProperties(\n keys: readonly string[],\n properties: Neo4jProperties,\n type: string,\n): Neo4jNodeIdentity {\n const identity: Record<string, string | number | boolean> = {};\n for (const key of keys) {\n const value = properties[key];\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n throw new TypeError(`Identity property ${key} for ${type} must be a primitive value.`);\n }\n identity[key] = value;\n }\n return identity;\n}\n\nfunction validateSourceChunkIds(\n value: readonly string[],\n chunkIds: ReadonlySet<string>,\n label: string,\n): string[] {\n const ids = uniqueIds(value, `${label} source chunk`);\n if (ids.length === 0) throw new TypeError(`${label} requires source chunk provenance.`);\n for (const id of ids) {\n if (!chunkIds.has(id)) throw new TypeError(`${label} references unknown source chunk ${id}.`);\n }\n return ids;\n}\n\nfunction validateOrphanPolicy(value: unknown): asserts value is \"delete\" | \"keep\" {\n if (value !== \"delete\" && value !== \"keep\") {\n throw new TypeError(\"Neo4j orphan entity policy must be delete or keep.\");\n }\n}\n\nfunction singleEmbedding(\n embeddings: readonly { vector: number[] }[],\n dimensions: number,\n label: string,\n): number[] {\n if (!Array.isArray(embeddings)) throw new TypeError(`${label} embeddings must be an array.`);\n if (embeddings.length !== 1) throw new TypeError(`${label} requires exactly one embedding.`);\n const vector = embeddings[0]?.vector;\n if (vector === undefined || vector.length !== dimensions || !vector.every(Number.isFinite)) {\n throw new TypeError(`${label} has an invalid ${dimensions}-dimension embedding.`);\n }\n return vector;\n}\n\nfunction uniqueIds(ids: readonly string[], label: string): string[] {\n if (!Array.isArray(ids)) throw new TypeError(`Neo4j ${label} ids must be an array.`);\n const seen = new Set<string>();\n for (const id of ids) {\n if (typeof id !== \"string\" || id.length === 0)\n throw new TypeError(`Neo4j ${label} ids must be non-empty strings.`);\n if (seen.has(id)) throw new TypeError(`Duplicate Neo4j ${label} id: ${id}`);\n seen.add(id);\n }\n return [...seen];\n}\n\ntype SnapshotTargets = Readonly<{\n documentIds: readonly string[];\n chunkIds: readonly string[];\n entityKeys: readonly string[];\n relationshipKeys: readonly string[];\n mentions: readonly Readonly<{ chunkId: string; entityKey: string }>[];\n}>;\n\ntype GraphSnapshot = Readonly<{\n documents: ReadonlyMap<string, string>;\n chunks: ReadonlyMap<string, string>;\n entities: ReadonlyMap<string, string>;\n relationships: ReadonlyMap<string, string>;\n mentions: ReadonlyMap<string, string>;\n}>;\n\nfunction replacementSnapshotTargets(\n options: ReplaceNeo4jDocumentsOptions<Neo4jGraphSchema>,\n): SnapshotTargets {\n return {\n documentIds: options.documents.map((document) => document.id),\n chunkIds: options.chunks.map((chunk) => chunk.id),\n entityKeys: options.entities.map((entity) => entity.id),\n relationshipKeys: options.relationships.map((relationship) => relationship.key),\n mentions: options.mentions,\n };\n}\n\nfunction emptySnapshotTargets(documentIds: readonly string[]): SnapshotTargets {\n return {\n documentIds,\n chunkIds: [],\n entityKeys: [],\n relationshipKeys: [],\n mentions: [],\n };\n}\n\nfunction expandSnapshotTargets(targets: SnapshotTargets, snapshot: GraphSnapshot): SnapshotTargets {\n const mentions = new Map(\n targets.mentions.map((mention) => [mentionKey(mention.chunkId, mention.entityKey), mention]),\n );\n for (const key of snapshot.mentions.keys()) {\n const separator = key.indexOf(\"\\u0000\");\n if (separator < 0) throw new TypeError(\"Stored Neo4j mention has an invalid identity.\");\n mentions.set(key, { chunkId: key.slice(0, separator), entityKey: key.slice(separator + 1) });\n }\n return {\n documentIds: targets.documentIds,\n chunkIds: [...new Set([...targets.chunkIds, ...snapshot.chunks.keys()])],\n entityKeys: [...new Set([...targets.entityKeys, ...snapshot.entities.keys()])],\n relationshipKeys: [...new Set([...targets.relationshipKeys, ...snapshot.relationships.keys()])],\n mentions: [...mentions.values()],\n };\n}\n\nasync function snapshotGraphState(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n labels: { document: string; chunk: string; entity: string },\n targets: SnapshotTargets,\n): Promise<GraphSnapshot> {\n const documentsResult = await transaction.run(\n `MATCH (d:${quoteIdentifier(labels.document)})\nWHERE d.${quoteIdentifier(\"__anvia_id\")} IN $documentIds${tenantPredicate(\"d\", namespace, \" AND\")}\nRETURN d.${quoteIdentifier(\"__anvia_id\")} AS key, properties(d) AS properties`,\n managedParameters(graphName, namespace, { documentIds: targets.documentIds }),\n );\n const chunksResult = await transaction.run(\n `MATCH (c:${quoteIdentifier(labels.chunk)})\nOPTIONAL MATCH (d:${quoteIdentifier(labels.document)})-[:${quoteIdentifier(\"ANVIA_HAS_CHUNK\")}]->(c)\nWITH c, d WHERE (c.${quoteIdentifier(\"__anvia_id\")} IN $chunkIds OR d.${quoteIdentifier(\"__anvia_id\")} IN $documentIds)${tenantPredicate(\"c\", namespace, \" AND\")}\nRETURN c.${quoteIdentifier(\"__anvia_id\")} AS key, properties(c) AS properties`,\n managedParameters(graphName, namespace, {\n chunkIds: targets.chunkIds,\n documentIds: targets.documentIds,\n }),\n );\n const entitiesResult = await transaction.run(\n `MATCH (e:${quoteIdentifier(labels.entity)})\nWHERE e.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(\"e\", namespace, \" AND\")} AND (\n e.${quoteIdentifier(\"__anvia_key\")} IN $entityKeys OR\n any(id IN coalesce(e.${quoteIdentifier(\"__anvia_source_document_ids\")}, []) WHERE id IN $documentIds)\n)\nRETURN e.${quoteIdentifier(\"__anvia_key\")} AS key, labels(e) AS labels, properties(e) AS properties`,\n managedParameters(graphName, namespace, {\n entityKeys: targets.entityKeys,\n documentIds: targets.documentIds,\n }),\n );\n const relationshipsResult = await transaction.run(\n `MATCH ()-[r]->()\nWHERE r.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(\"r\", namespace, \" AND\")} AND (\n r.${quoteIdentifier(\"__anvia_key\")} IN $relationshipKeys OR\n any(id IN coalesce(r.${quoteIdentifier(\"__anvia_source_document_ids\")}, []) WHERE id IN $documentIds)\n)\nRETURN r.${quoteIdentifier(\"__anvia_key\")} AS key,\n type(r) AS type,\n startNode(r).${quoteIdentifier(\"__anvia_key\")} AS source,\n endNode(r).${quoteIdentifier(\"__anvia_key\")} AS target,\n properties(r) AS properties`,\n managedParameters(graphName, namespace, {\n relationshipKeys: targets.relationshipKeys,\n documentIds: targets.documentIds,\n }),\n );\n const mentionsResult = await transaction.run(\n `MATCH (c:${quoteIdentifier(labels.chunk)})-[:${quoteIdentifier(\"ANVIA_MENTIONS\")}]->(e:${quoteIdentifier(labels.entity)})\nOPTIONAL MATCH (d:${quoteIdentifier(labels.document)})-[:${quoteIdentifier(\"ANVIA_HAS_CHUNK\")}]->(c)\nWITH c, e, d WHERE (d.${quoteIdentifier(\"__anvia_id\")} IN $documentIds OR\n any(item IN $mentions WHERE item.chunkId = c.${quoteIdentifier(\"__anvia_id\")} AND item.entityKey = e.${quoteIdentifier(\"__anvia_key\")})\n)${tenantPredicate(\"c\", namespace, \" AND\")}\nRETURN c.${quoteIdentifier(\"__anvia_id\")} AS chunkId, e.${quoteIdentifier(\"__anvia_key\")} AS entityKey`,\n managedParameters(graphName, namespace, {\n documentIds: targets.documentIds,\n mentions: targets.mentions,\n }),\n );\n return {\n documents: snapshotProperties(documentsResult.records, \"document\"),\n chunks: snapshotProperties(chunksResult.records, \"chunk\"),\n entities: snapshotProperties(entitiesResult.records, \"entity\", true),\n relationships: snapshotRelationships(relationshipsResult.records),\n mentions: snapshotMentions(mentionsResult.records),\n };\n}\n\nfunction snapshotProperties(\n records: readonly Neo4jRecord[],\n resource: string,\n includeLabels = false,\n): Map<string, string> {\n const output = new Map<string, string>();\n for (const record of records) {\n const key = requiredString(record.get(\"key\"), `Neo4j ${resource} snapshot key`);\n if (output.has(key))\n throw new TypeError(`Neo4j ${resource} snapshot contains duplicate ${key}.`);\n const properties = normalizedSnapshotProperties(\n record.get(\"properties\"),\n `Neo4j ${resource} snapshot`,\n );\n const labels = includeLabels\n ? requiredStringArray(record.get(\"labels\"), `Neo4j ${resource} snapshot labels`).sort()\n : [];\n output.set(key, stableObject({ labels: labels.join(\"\\u0000\"), properties }));\n }\n return output;\n}\n\nfunction snapshotRelationships(records: readonly Neo4jRecord[]): Map<string, string> {\n const output = new Map<string, string>();\n for (const record of records) {\n const key = requiredString(record.get(\"key\"), \"Neo4j relationship snapshot key\");\n if (output.has(key))\n throw new TypeError(`Neo4j relationship snapshot contains duplicate ${key}.`);\n output.set(\n key,\n stableObject({\n source: requiredString(record.get(\"source\"), \"Neo4j relationship snapshot source\"),\n target: requiredString(record.get(\"target\"), \"Neo4j relationship snapshot target\"),\n type: requiredString(record.get(\"type\"), \"Neo4j relationship snapshot type\"),\n properties: normalizedSnapshotProperties(\n record.get(\"properties\"),\n \"Neo4j relationship snapshot\",\n ),\n }),\n );\n }\n return output;\n}\n\nfunction snapshotMentions(records: readonly Neo4jRecord[]): Map<string, string> {\n const output = new Map<string, string>();\n for (const record of records) {\n const key = mentionKey(\n requiredString(record.get(\"chunkId\"), \"Neo4j mention chunk id\"),\n requiredString(record.get(\"entityKey\"), \"Neo4j mention entity key\"),\n );\n if (output.has(key)) throw new TypeError(`Neo4j mention snapshot contains duplicate ${key}.`);\n output.set(key, key);\n }\n return output;\n}\n\nfunction normalizedSnapshotProperties(value: unknown, label: string): string {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} properties must be an object.`);\n }\n const normalized: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n normalized[key] = parseNeo4jPropertyValue(\n normalizeSnapshotDriverValue(item, `${label}.${key}`),\n `${label}.${key}`,\n );\n }\n for (const property of [\"__anvia_source_document_ids\", \"__anvia_source_chunk_ids\"]) {\n const items = normalized[property];\n if (items !== undefined) {\n if (!Array.isArray(items) || !items.every((item) => typeof item === \"string\")) {\n throw new TypeError(`${label}.${property} must be a string array.`);\n }\n normalized[property] = [...new Set(items)].sort();\n }\n }\n return stableObject(normalized);\n}\n\nfunction normalizeSnapshotDriverValue(value: unknown, label: string): unknown {\n if (isInt(value)) {\n if (!value.inSafeRange()) throw new TypeError(`${label} contains an unsafe Neo4j integer.`);\n return value.toNumber();\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => normalizeSnapshotDriverValue(item, `${label}[${index}]`));\n }\n return value;\n}\n\nfunction mentionKey(chunkId: string, entityKey: string): string {\n return `${chunkId}\\u0000${entityKey}`;\n}\n\nfunction diffGraphSnapshots(before: GraphSnapshot, after: GraphSnapshot): Neo4jGraphWriteResult {\n return {\n documents: diffSnapshotMaps(before.documents, after.documents),\n chunks: diffSnapshotMaps(before.chunks, after.chunks),\n entities: diffSnapshotMaps(before.entities, after.entities),\n relationships: diffSnapshotMaps(before.relationships, after.relationships),\n mentions: diffSnapshotMaps(before.mentions, after.mentions),\n };\n}\n\nfunction diffSnapshotMaps(\n before: ReadonlyMap<string, string>,\n after: ReadonlyMap<string, string>,\n): Neo4jGraphWriteResult[\"documents\"] {\n let created = 0;\n let updated = 0;\n let deleted = 0;\n let unchanged = 0;\n for (const key of new Set([...before.keys(), ...after.keys()])) {\n const previous = before.get(key);\n const next = after.get(key);\n if (previous === undefined) created += 1;\n else if (next === undefined) deleted += 1;\n else if (previous === next) unchanged += 1;\n else updated += 1;\n }\n return { created, updated, deleted, unchanged };\n}\n\nfunction emptyWriteResult(): Neo4jGraphWriteResult {\n const empty = () => ({ created: 0, updated: 0, deleted: 0, unchanged: 0 });\n return {\n documents: empty(),\n chunks: empty(),\n entities: empty(),\n relationships: empty(),\n mentions: empty(),\n };\n}\n\nfunction managedParameters(\n graph: string,\n namespace: string | undefined,\n parameters: Record<string, unknown>,\n): Record<string, unknown> {\n return managedScopeParameters({ graph, namespace }, parameters);\n}\n\nfunction namespacePredicate(\n variable: string,\n namespace: string | undefined,\n prefix: \" AND\" | \" WHERE\",\n): string {\n return scopeNamespacePredicate({ graph: \"\", namespace }, variable, prefix);\n}\n\nfunction tenantPredicate(\n variable: string,\n namespace: string | undefined,\n prefix: \" AND\" | \" WHERE\",\n): string {\n return tenantScopePredicate({ graph: \"\", namespace }, variable, prefix);\n}\n\nfunction namespaceMapEntry(namespace: string | undefined): string {\n return scopeNamespaceMapEntry({ graph: \"\", namespace });\n}\n\nfunction tenantMapEntries(namespace: string | undefined): string {\n return scopeTenantMapEntries({ graph: \"\", namespace });\n}\n\nfunction tenantRelationshipProperties(namespace: string | undefined): string {\n return scopeTenantRelationshipProperties({ graph: \"\", namespace });\n}\n\nasync function removeDocuments(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n labels: { document: string; chunk: string; entity: string },\n documentIds: readonly string[],\n orphanEntities: \"delete\" | \"keep\",\n): Promise<void> {\n const chunks = await transaction.run(\n `MATCH (d:${quoteIdentifier(labels.document)})-[:${quoteIdentifier(\"ANVIA_HAS_CHUNK\")}]->(c:${quoteIdentifier(labels.chunk)}) WHERE d.${quoteIdentifier(\"__anvia_id\")} IN $documentIds${tenantPredicate(\"d\", namespace, \" AND\")} RETURN collect(c.${quoteIdentifier(\"__anvia_id\")}) AS chunkIds`,\n managedParameters(graphName, namespace, { documentIds }),\n );\n const chunkIdsValue = chunks.records[0]?.get(\"chunkIds\");\n const chunkIds = requiredStringArray(chunkIdsValue, \"Neo4j replacement chunk ids\");\n await transaction.run(\n `MATCH ()-[r]->() WHERE r.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(\"r\", namespace, \" AND\")} AND any(id IN r.${quoteIdentifier(\"__anvia_source_document_ids\")} WHERE id IN $documentIds)\nSET r.${quoteIdentifier(\"__anvia_source_document_ids\")} = [id IN r.${quoteIdentifier(\"__anvia_source_document_ids\")} WHERE NOT id IN $documentIds]\nSET r.${quoteIdentifier(\"__anvia_source_chunk_ids\")} = [id IN coalesce(r.${quoteIdentifier(\"__anvia_source_chunk_ids\")}, []) WHERE NOT id IN $chunkIds]\nWITH r WHERE size(r.${quoteIdentifier(\"__anvia_source_document_ids\")}) = 0 DELETE r`,\n managedParameters(graphName, namespace, { documentIds, chunkIds }),\n );\n await transaction.run(\n `MATCH (d:${quoteIdentifier(labels.document)}) WHERE d.${quoteIdentifier(\"__anvia_id\")} IN $documentIds${tenantPredicate(\"d\", namespace, \" AND\")}\nOPTIONAL MATCH (d)-[:${quoteIdentifier(\"ANVIA_HAS_CHUNK\")}]->(c:${quoteIdentifier(labels.chunk)})\nDETACH DELETE c, d`,\n managedParameters(graphName, namespace, { documentIds }),\n );\n await transaction.run(\n `MATCH (e:${quoteIdentifier(labels.entity)})\nWHERE e.${quoteIdentifier(\"__anvia_graph\")} = $graph${namespacePredicate(\"e\", namespace, \" AND\")} AND\n any(id IN coalesce(e.${quoteIdentifier(\"__anvia_source_document_ids\")}, []) WHERE id IN $documentIds)\nSET e.${quoteIdentifier(\"__anvia_source_document_ids\")} = [id IN e.${quoteIdentifier(\"__anvia_source_document_ids\")} WHERE NOT id IN $documentIds],\n e.${quoteIdentifier(\"__anvia_source_chunk_ids\")} = [id IN coalesce(e.${quoteIdentifier(\"__anvia_source_chunk_ids\")}, []) WHERE NOT id IN $chunkIds]\nWITH e WHERE $deleteOrphans AND size(e.${quoteIdentifier(\"__anvia_source_document_ids\")}) = 0\nDETACH DELETE e`,\n managedParameters(graphName, namespace, {\n documentIds,\n chunkIds,\n deleteOrphans: orphanEntities === \"delete\",\n }),\n );\n}\n\nasync function writeDocuments(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n labels: { document: string },\n documents: readonly { id: string; properties?: Neo4jProperties | undefined }[],\n): Promise<void> {\n await transaction.run(\n `UNWIND $rows AS row MERGE (d:${quoteIdentifier(labels.document)} {${quoteIdentifier(\"__anvia_id\")}: row.id${namespaceMapEntry(namespace)}}) ${namespace === undefined ? \"SET d += row.properties\" : `SET d.${quoteIdentifier(\"__anvia_graph\")} = $graph, d += row.properties`}`,\n managedParameters(graphName, namespace, {\n rows: documents.map((document) => ({\n id: document.id,\n properties: document.properties ?? {},\n })),\n }),\n );\n}\n\nasync function writeChunks(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n labels: { document: string; chunk: string },\n chunks: ReplaceNeo4jDocumentsOptions<Neo4jGraphSchema>[\"chunks\"],\n): Promise<void> {\n const rows = chunks.map((chunk) => ({\n id: chunk.id,\n documentId: chunk.document.documentId,\n index: chunk.document.index,\n text: chunk.document.text,\n metadata: chunk.document.metadata ?? {},\n embedding: chunk.embeddings[0]?.vector,\n }));\n await transaction.run(\n `UNWIND $rows AS row\nMATCH (d:${quoteIdentifier(labels.document)} {${quoteIdentifier(\"__anvia_id\")}: row.documentId})\n${tenantPredicate(\"d\", namespace, \" WHERE\")}\nCREATE (c:${quoteIdentifier(labels.chunk)} {${quoteIdentifier(\"__anvia_id\")}: row.id, ${quoteIdentifier(\"__anvia_document_id\")}: row.documentId, ${quoteIdentifier(\"__anvia_index\")}: row.index, ${quoteIdentifier(\"__anvia_text\")}: row.text, ${quoteIdentifier(\"__anvia_embedding\")}: row.embedding${tenantMapEntries(namespace)}})\nSET c += row.metadata\nCREATE (d)-[:${quoteIdentifier(\"ANVIA_HAS_CHUNK\")}${tenantRelationshipProperties(namespace)}]->(c)`,\n managedParameters(graphName, namespace, { rows }),\n );\n const pairs = [...rows]\n .sort(\n (left, right) => left.documentId.localeCompare(right.documentId) || left.index - right.index,\n )\n .flatMap((row, index, all) => {\n const next = all[index + 1];\n return next !== undefined && next.documentId === row.documentId\n ? [{ from: row.id, to: next.id }]\n : [];\n });\n if (pairs.length > 0) {\n await transaction.run(\n `UNWIND $rows AS row MATCH (a:${quoteIdentifier(labels.chunk)} {${quoteIdentifier(\"__anvia_id\")}: row.from${namespaceMapEntry(namespace)}}), (b:${quoteIdentifier(labels.chunk)} {${quoteIdentifier(\"__anvia_id\")}: row.to${namespaceMapEntry(namespace)}}) CREATE (a)-[:${quoteIdentifier(\"ANVIA_NEXT_CHUNK\")}${tenantRelationshipProperties(namespace)}]->(b)`,\n managedParameters(graphName, namespace, { rows: pairs }),\n );\n }\n}\n\nasync function writeEntities<Schema extends Neo4jGraphSchema>(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n entityLabel: string,\n entities: ReplaceNeo4jDocumentsOptions<Schema>[\"entities\"],\n conflict: ReplaceNeo4jDocumentsOptions<Schema>[\"conflict\"],\n sourceDocuments: (sourceChunkIds: readonly string[]) => readonly string[],\n): Promise<void> {\n const grouped = groupBy(entities, (entity) => entity.document.type);\n for (const [type, values] of grouped) {\n const rows = values.map((entity) => ({\n key: entity.id,\n properties: entity.document.properties,\n embedding: entity.embeddings[0]?.vector,\n sourceDocumentIds: sourceDocuments(entity.document.sourceChunkIds),\n sourceChunkIds: entity.document.sourceChunkIds,\n }));\n if (conflict === \"error\")\n await assertEntityConflicts(transaction, graphName, namespace, entityLabel, rows);\n const propertySet = conflictPropertySet(\"e\", conflict);\n const embedding = entityEmbeddingExpression(conflict);\n await transaction.run(\n `UNWIND $rows AS row\nMERGE (e:${quoteIdentifier(entityLabel)}:${quoteIdentifier(type)} {${quoteIdentifier(\"__anvia_key\")}: row.key${namespaceMapEntry(namespace)}})\n${propertySet}\nSET e.${quoteIdentifier(\"__anvia_key\")} = row.key,\n e.${quoteIdentifier(\"__anvia_graph\")} = $graph,\n e.${quoteIdentifier(\"__anvia_namespace\")} = coalesce($namespace, e.${quoteIdentifier(\"__anvia_namespace\")}),\n e.${quoteIdentifier(\"__anvia_embedding\")} = ${embedding},\n e.${quoteIdentifier(\"__anvia_source_document_ids\")} = reduce(all = existingDocumentIds, id IN row.sourceDocumentIds | CASE WHEN id IN all THEN all ELSE all + id END),\n e.${quoteIdentifier(\"__anvia_source_chunk_ids\")} = reduce(all = existingChunkIds, id IN row.sourceChunkIds | CASE WHEN id IN all THEN all ELSE all + id END)`,\n managedParameters(graphName, namespace, { rows }),\n );\n }\n}\n\nasync function assertEntityConflicts(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n entityLabel: string,\n rows: readonly { key: string; properties: Neo4jProperties }[],\n): Promise<void> {\n const result = await transaction.run(\n `UNWIND $keys AS key MATCH (e:${quoteIdentifier(entityLabel)} {${quoteIdentifier(\"__anvia_key\")}: key${namespaceMapEntry(namespace)}}) WHERE e.${quoteIdentifier(\"__anvia_graph\")} = $graph RETURN key, properties(e) AS properties`,\n managedParameters(graphName, namespace, { keys: rows.map((row) => row.key) }),\n );\n const incoming = new Map(rows.map((row) => [row.key, row.properties]));\n for (const record of result.records) {\n const key = requiredString(record.get(\"key\"), \"Neo4j entity key\");\n const existing = applicationProperties(record.get(\"properties\"));\n if (stableObject(existing) !== stableObject(incoming.get(key) ?? {})) {\n throw new Error(`Neo4j entity ${key} conflicts with existing properties.`);\n }\n }\n}\n\nasync function writeMentions(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n labels: { chunk: string; entity: string },\n mentions: readonly { chunkId: string; entityKey: string }[],\n): Promise<void> {\n if (mentions.length === 0) return;\n await transaction.run(\n `UNWIND $rows AS row\nMATCH (c:${quoteIdentifier(labels.chunk)} {${quoteIdentifier(\"__anvia_id\")}: row.chunkId${namespaceMapEntry(namespace)}}), (e:${quoteIdentifier(labels.entity)} {${quoteIdentifier(\"__anvia_key\")}: row.entityKey${namespaceMapEntry(namespace)}})\n${namespace === undefined ? \"\" : `WHERE c.${quoteIdentifier(\"__anvia_graph\")} = $graph AND e.${quoteIdentifier(\"__anvia_graph\")} = $graph`}\nMERGE (c)-[:${quoteIdentifier(\"ANVIA_MENTIONS\")}${tenantRelationshipProperties(namespace)}]->(e)`,\n managedParameters(graphName, namespace, { rows: mentions }),\n );\n}\n\nasync function writeRelationships<Schema extends Neo4jGraphSchema>(\n transaction: GraphTransaction,\n graphName: string,\n namespace: string | undefined,\n entityLabel: string,\n relationships: readonly import(\"./types.js\").Neo4jGraphRelationship<Schema>[],\n conflict: ReplaceNeo4jDocumentsOptions<Schema>[\"conflict\"],\n sourceDocuments: (sourceChunkIds: readonly string[]) => readonly string[],\n): Promise<void> {\n const grouped = groupBy(relationships, (relationship) => relationship.type);\n for (const [type, values] of grouped) {\n const rows = values.map((relationship) => ({\n key: relationship.key,\n from: relationship.from,\n to: relationship.to,\n properties: relationship.properties,\n sourceDocumentIds: sourceDocuments(relationship.sourceChunkIds),\n sourceChunkIds: relationship.sourceChunkIds,\n }));\n if (conflict === \"error\") {\n const existing = await transaction.run(\n `UNWIND $keys AS key MATCH ()-[r:${quoteIdentifier(type)} {${quoteIdentifier(\"__anvia_key\")}: key${namespaceMapEntry(namespace)}}]->() WHERE r.${quoteIdentifier(\"__anvia_graph\")} = $graph RETURN key, properties(r) AS properties`,\n managedParameters(graphName, namespace, { keys: rows.map((row) => row.key) }),\n );\n const incoming = new Map(rows.map((row) => [row.key, row.properties]));\n for (const record of existing.records) {\n const key = requiredString(record.get(\"key\"), \"Neo4j relationship key\");\n if (\n stableObject(applicationProperties(record.get(\"properties\"))) !==\n stableObject(incoming.get(key) ?? {})\n ) {\n throw new Error(`Neo4j relationship ${key} conflicts with existing properties.`);\n }\n }\n }\n const propertySet = conflictPropertySet(\"r\", conflict);\n await transaction.run(\n `UNWIND $rows AS row\nMATCH (a:${quoteIdentifier(entityLabel)} {${quoteIdentifier(\"__anvia_key\")}: row.from${namespaceMapEntry(namespace)}}), (b:${quoteIdentifier(entityLabel)} {${quoteIdentifier(\"__anvia_key\")}: row.to${namespaceMapEntry(namespace)}})\nWHERE a.${quoteIdentifier(\"__anvia_graph\")} = $graph AND b.${quoteIdentifier(\"__anvia_graph\")} = $graph\nMERGE (a)-[r:${quoteIdentifier(type)} {${quoteIdentifier(\"__anvia_key\")}: row.key${namespaceMapEntry(namespace)}}]->(b)\n${propertySet}\nSET r.${quoteIdentifier(\"__anvia_key\")} = row.key,\n r.${quoteIdentifier(\"__anvia_graph\")} = $graph,\n r.${quoteIdentifier(\"__anvia_namespace\")} = coalesce($namespace, r.${quoteIdentifier(\"__anvia_namespace\")}),\n r.${quoteIdentifier(\"__anvia_source_document_ids\")} = reduce(all = existingDocumentIds, id IN row.sourceDocumentIds | CASE WHEN id IN all THEN all ELSE all + id END),\n r.${quoteIdentifier(\"__anvia_source_chunk_ids\")} = reduce(all = existingChunkIds, id IN row.sourceChunkIds | CASE WHEN id IN all THEN all ELSE all + id END)`,\n managedParameters(graphName, namespace, { rows }),\n );\n }\n}\n\nfunction conflictPropertySet(variable: \"e\" | \"r\", conflict: Neo4jGraphConflict): string {\n const sourceDocuments = quoteIdentifier(\"__anvia_source_document_ids\");\n const sourceChunks = quoteIdentifier(\"__anvia_source_chunk_ids\");\n const existingSources = `WITH ${variable}, row,\n coalesce(${variable}.${sourceDocuments}, []) AS existingDocumentIds,\n coalesce(${variable}.${sourceChunks}, []) AS existingChunkIds`;\n if (conflict === \"keep-existing\") {\n return `ON CREATE SET ${variable} += row.properties\n${existingSources}`;\n }\n if (conflict === \"overwrite\") {\n return `${existingSources}\nSET ${variable} = row.properties`;\n }\n return `${existingSources}\nSET ${variable} += row.properties`;\n}\n\nfunction entityEmbeddingExpression(conflict: Neo4jGraphConflict): string {\n if (conflict === \"keep-existing\") {\n return `coalesce(e.${quoteIdentifier(\"__anvia_embedding\")}, row.embedding)`;\n }\n return \"row.embedding\";\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== \"string\") throw new TypeError(`${label} must be a string.`);\n return value;\n}\n\nfunction applicationProperties(value: unknown): Neo4jProperties {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return {};\n return parseNeo4jProperties(\n Object.fromEntries(Object.entries(value).filter(([key]) => !key.startsWith(\"__anvia_\"))),\n \"stored Neo4j properties\",\n );\n}\n\nfunction groupBy<Value, Key>(\n values: readonly Value[],\n keyFor: (value: Value) => Key,\n): Map<Key, Value[]> {\n const groups = new Map<Key, Value[]>();\n for (const value of values) {\n const key = keyFor(value);\n const group = groups.get(key);\n if (group === undefined) groups.set(key, [value]);\n else group.push(value);\n }\n return groups;\n}\n"],"mappings":";AAAA,SAAS,SAAS;AASlB,IAAM,iBAAiB;AAEhB,SAAS,uBACd,SAC2B;AAC3B,MAAI,OAAO,KAAK,QAAQ,KAAK,EAAE,WAAW,GAAG;A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AACtC,MAAI,aAAa,iBAAiB;AAChC,WAAO,iBAAiB,QAAQ;AAAA,EAClC,eAAe;AAAA,EACf;AACA,MAAI,aAAa,aAAa;AAC5B,WAAO,GAAG,eAAe;AAAA,MACvB,QAAQ;AAAA,EACZ;AACA,SAAO,GAAG,eAAe;AAAA,MACrB,QAAQ;AACd;AAEA,SAAS,0BAA0B,UAAsC;AACvE,MAAI,aAAa,iBAAiB;AAChC,WAAO,cAAc,gBAAgB,mBAAmB,CAAC;AAAA,EAC3D;AACA,SAAO;AACT;AAEA,SAAS,eAAe,OAAgB,OAAuB;AAC7D,MAAI,OAAO,UAAU,SAAU,OAAM,IAAI,UAAU,GAAG,KAAK,oBAAoB;AAC/E,SAAO;AACT;AAEA,SAAS,sBAAsB,OAAiC;AAC9D,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACjF,SAAO;AAAA,IACL,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,OAAO,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,WAAW,UAAU,CAAC,CAAC;AAAA,IACvF;AAAA,EACF;AACF;AAEA,SAAS,QACP,QACA,QACmB;AACnB,QAAM,SAAS,oBAAI,IAAkB;AACrC,aAAW,SAAS,QAAQ;AAC1B,UAAM,MAAM,OAAO,KAAK;AACxB,UAAM,QAAQ,OAAO,IAAI,GAAG;AAC5B,QAAI,UAAU,OAAW,QAAO,IAAI,KAAK,CAAC,KAAK,CAAC;AAAA,QAC3C,OAAM,KAAK,KAAK;AAAA,EACvB;AACA,SAAO;AACT;","names":["isInt","isInt","namespacePredicate","namespaceMapEntry","tenantMapEntries","tenantRelationshipProperties"]}
@@ -1,8 +0,0 @@
1
- import {
2
- exploreGraph
3
- } from "./chunk-QY7IO247.js";
4
- import "./chunk-EUZ5C6OC.js";
5
- export {
6
- exploreGraph
7
- };
8
- //# sourceMappingURL=explore-HRISJG7V.js.map
@@ -1,8 +0,0 @@
1
- import {
2
- retrieveGraphContext
3
- } from "./chunk-YCJZAWLH.js";
4
- import "./chunk-EUZ5C6OC.js";
5
- export {
6
- retrieveGraphContext
7
- };
8
- //# sourceMappingURL=retrieve-IJVPFOPP.js.map