@nicia-ai/typegraph 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/node.ts","../src/core/edge.ts","../src/ontology/types.ts","../src/ontology/core-meta-edges.ts","../src/schema/migration.ts","../src/registry/kind-registry.ts","../src/schema/serializer.ts","../src/graph-extension/compiler.ts","../src/graph-extension/ontology-keys.ts","../src/graph-extension/merge.ts","../src/schema/types.ts","../src/schema/manager.ts","../src/errors/validation.ts"],"names":["validateSchemaKeys","narrower","broader","z","declaration"],"mappings":";;;;;;;;;;AAmCA,SAAS,kBAAA,CACP,QACA,IAAA,EACM;AACN,EAAA,uBAAA;AAAA,IACE,MAAA;AAAA,IACA,IAAA;AAAA,IACA,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAAA,IACxB;AAAA,GACF;AACF;AAgBO,SAAS,UAAA,CAGd,MAAS,OAAA,EAA+C;AACxD,EAAA,kBAAA,CAAmB,OAAA,CAAQ,QAAQ,IAAI,CAAA;AACvC,EAAA,IAAI,OAAA,CAAQ,gBAAgB,MAAA,EAAW;AACrC,IAAA,eAAA,CAAgB,OAAA,CAAQ,WAAA,EAAa,aAAA,EAAe,CAAA,MAAA,EAAS,IAAI,CAAA,CAAA,CAAG,CAAA;AAAA,EACtE;AAEA,EAAA,OAAO,OAAO,MAAA,CAAO;AAAA,IACnB,CAAC,eAAe,GAAG,IAAA;AAAA,IACnB,IAAA,EAAM,IAAA;AAAA,IACN,QAAQ,OAAA,CAAQ,MAAA;AAAA,IAChB,aAAa,OAAA,CAAQ,WAAA;AAAA,IACrB,aAAa,OAAA,CAAQ;AAAA,GACtB,CAAA;AACH;AC7BA,IAAM,YAAA,GAAe,CAAA,CAAE,MAAA,CAAO,EAAE,CAAA;AAOhC,SAASA,mBAAAA,CACP,QACA,IAAA,EACM;AACN,EAAA,uBAAA;AAAA,I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O,CAAA,CAAA;AAAA,IACzE;AAAA,MACE,YAAY,OAAA,CAAQ,UAAA;AAAA,MACpB,MAAM,OAAA,CAAQ,IAAA;AAAA,MACd,WAAW,OAAA,CAAQ,SAAA;AAAA,MACnB,GAAI,OAAA,CAAQ,EAAA,KAAO,UAAa,EAAE,EAAA,EAAI,QAAQ,EAAA,EAAG;AAAA,MACjD;AAAA,KACF;AAAA,IACA,EAAE,OAAO,KAAA;AAAM,GACjB;AACF;AAkBO,SAAS,qBAAA,CACd,OAAA,EACA,MAAA,EACA,OAAA,EACiB;AACjB,EAAA,OAAO,IAAI,gBAAgB,OAAA,EAAS;AAAA,IAClC,GAAI,OAAA,EAAS,UAAA,KAAe,MAAA,IAAa;AAAA,MACvC,YAAY,OAAA,CAAQ;AAAA,KACtB;AAAA,IACA,GAAI,OAAA,EAAS,IAAA,KAAS,UAAa,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAK;AAAA,IACxD,GAAI,OAAA,EAAS,SAAA,KAAc,UAAa,EAAE,SAAA,EAAW,QAAQ,SAAA,EAAU;AAAA,IACvE,GAAI,OAAA,EAAS,EAAA,KAAO,UAAa,EAAE,EAAA,EAAI,QAAQ,EAAA,EAAG;AAAA,IAClD;AAAA,GACD,CAAA;AACH","file":"chunk-X53YKGHR.js","sourcesContent":["import { type z } from \"zod\";\n\nimport {\n assertSchemaKeysAreFree,\n RESERVED_NODE_KEYS,\n} from \"../store/reserved-keys\";\nimport { assertJsonValue } from \"./json-value\";\nimport { type KindAnnotations, NODE_TYPE_BRAND, type NodeType } from \"./types\";\n\n// ============================================================\n// Node Factory Options\n// ============================================================\n\n/**\n * Options for defining a node type.\n */\nexport type DefineNodeOptions<S extends z.ZodObject<z.ZodRawShape>> = Readonly<{\n /** Zod schema for node properties */\n schema: S;\n /** Optional description for documentation */\n description?: string;\n /**\n * Consumer-owned structured annotations for the kind.\n *\n * Stored in the canonical schema and **participates in schema hashing** —\n * any change bumps the schema version and shows up as a `safe`-severity\n * diff in `getSchemaChanges`. See `KindAnnotations` for the contract.\n */\n annotations?: KindAnnotations;\n}>;\n\n// ============================================================\n// Node Factory\n// ============================================================\n\nfunction validateSchemaKeys(\n schema: z.ZodObject<z.ZodRawShape>,\n name: string,\n): void {\n assertSchemaKeysAreFree(\n \"Node\",\n name,\n Object.keys(schema.shape),\n RESERVED_NODE_KEYS,\n );\n}\n\n/**\n * Creates a node type definition.\n *\n * @example\n * ```typescript\n * const Person = defineNode(\"Person\", {\n * schema: z.object({\n * fullName: z.string().min(1),\n * email: z.string().email().optional(),\n * }),\n * description: \"A person in the system\",\n * });\n * ```\n */\nexport function defineNode<\n K extends string,\n S extends z.ZodObject<z.ZodRawShape>,\n>(name: K, options: DefineNodeOptions<S>): NodeType<K, S> {\n validateSchemaKeys(options.schema, name);\n if (options.annotations !== undefined) {\n assertJsonValue(options.annotations, \"annotations\", `Node \"${name}\"`);\n }\n\n return Object.freeze({\n [NODE_TYPE_BRAND]: true as const,\n kind: name,\n schema: options.schema,\n description: options.description,\n annotations: options.annotations,\n });\n}\n","import { z } from \"zod\";\n\nimport {\n assertSchemaKeysAreFree,\n RESERVED_EDGE_KEYS,\n} from \"../store/reserved-keys\";\nimport { assertJsonValue } from \"./json-value\";\nimport {\n EDGE_TYPE_BRAND,\n type EdgeType,\n type KindAnnotations,\n type NodeType,\n} from \"./types\";\n\n// ============================================================\n// Edge Factory Options\n// ============================================================\n\n/**\n * Options for defining an edge type.\n */\nexport type DefineEdgeOptions<\n S extends z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[] | undefined = undefined,\n To extends readonly NodeType[] | undefined = undefined,\n> = Readonly<{\n /** Zod schema for edge properties (defaults to empty object) */\n schema?: S;\n /** Optional description for documentation */\n description?: string;\n /**\n * Consumer-owned structured annotations for the kind.\n *\n * Stored in the canonical schema and **participates in schema hashing** —\n * any change bumps the schema version and shows up as a `safe`-severity\n * diff in `getSchemaChanges`. See `KindAnnotations` for the contract.\n */\n annotations?: KindAnnotations;\n /** Node types that can be the source of this edge (domain constraint) */\n from?: From;\n /** Node types that can be the target of this edge (range constraint) */\n to?: To;\n}>;\n\n// ============================================================\n// Empty Schema\n// ============================================================\n\nconst EMPTY_SCHEMA = z.object({});\ntype EmptySchema = typeof EMPTY_SCHEMA;\n\n// ============================================================\n// Edge Factory\n// ============================================================\n\nfunction validateSchemaKeys(\n schema: z.ZodObject<z.ZodRawShape>,\n name: string,\n): void {\n assertSchemaKeysAreFree(\n \"Edge\",\n name,\n Object.keys(schema.shape),\n RESERVED_EDGE_KEYS,\n );\n}\n\n/**\n * Creates an edge type definition.\n *\n * @example\n * ```typescript\n * // Edge with no properties\n * const hasEpisode = defineEdge(\"hasEpisode\");\n *\n * // Edge with properties\n * const employedAt = defineEdge(\"employedAt\", {\n * schema: z.object({\n * isPrimary: z.boolean().default(true),\n * startedAt: z.date(),\n * }),\n * description: \"Employment relationship\",\n * });\n *\n * // Edge with domain/range constraints (can be used directly in defineGraph)\n * const worksAt = defineEdge(\"worksAt\", {\n * schema: z.object({ role: z.string() }),\n * from: [Person],\n * to: [Company],\n * });\n * ```\n */\n// Overload: no options - returns edge without domain/range\nexport function defineEdge<K extends string>(name: K): EdgeType<K, EmptySchema>;\n\n// Overload: options with both from and to - returns edge with domain/range\nexport function defineEdge<\n K extends string,\n S extends z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[],\n To extends readonly NodeType[],\n>(\n name: K,\n options: DefineEdgeOptions<S, From, To> & { from: From; to: To },\n): EdgeType<K, S, From, To>;\n\n// Overload: options without from/to - returns edge without domain/range\nexport function defineEdge<\n K extends string,\n S extends z.ZodObject<z.ZodRawShape>,\n>(name: K, options: DefineEdgeOptions<S>): EdgeType<K, S>;\n\n// Implementation\nexport function defineEdge<\n K extends string,\n S extends z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[] | undefined,\n To extends readonly NodeType[] | undefined,\n>(\n name: K,\n options?: DefineEdgeOptions<S, From, To>,\n): EdgeType<K, S, From, To> | EdgeType<K, EmptySchema> {\n const schema = options?.schema ?? EMPTY_SCHEMA;\n validateSchemaKeys(schema, name);\n if (options?.annotations !== undefined) {\n assertJsonValue(options.annotations, \"annotations\", `Edge \"${name}\"`);\n }\n\n return Object.freeze({\n [EDGE_TYPE_BRAND]: true as const,\n kind: name,\n schema,\n description: options?.description,\n annotations: options?.annotations,\n from: options?.from,\n to: options?.to,\n }) as EdgeType<K, S, From, To> | EdgeType<K, EmptySchema>;\n}\n","import { type EdgeType, type NodeType } from \"../core/types\";\n\n// ============================================================\n// Brand Key\n// ============================================================\n\n/** Brand key for MetaEdge */\nexport const META_EDGE_BRAND = \"__metaEdge\" as const;\n\n// ============================================================\n// Inference Types\n// ============================================================\n\n/**\n * How a meta-edge affects queries and validation.\n */\nexport type InferenceType =\n | \"subsumption\" // Query for X includes instances of subclasses\n | \"hierarchy\" // Enables broader/narrower traversal\n | \"substitution\" // Can substitute equivalent types\n | \"constraint\" // Validation rules\n | \"composition\" // Part-whole navigation\n | \"association\" // Discovery/recommendation\n | \"none\"; // No automatic inference\n\n// ============================================================\n// Meta-Edge Properties\n// ============================================================\n\n/**\n * Properties of a meta-edge.\n */\nexport type MetaEdgeProperties = Readonly<{\n transitive: boolean; // A→B, B→C implies A→C\n symmetric: boolean; // A→B implies B→A\n reflexive: boolean; // A→A is always true\n inverse: string | undefined; // Name of inverse meta-edge\n inference: InferenceType; // How this affects queries\n description: string | undefined;\n}>;\n\n// ============================================================\n// Meta-Edge Type\n// ============================================================\n\n/**\n * A meta-edge definition.\n *\n * Meta-edges represent type-level relationships (between kinds),\n * not instance-level relationships (between nodes).\n */\nexport type MetaEdge<K extends string = string> = Readonly<{\n [META_EDGE_BRAND]: true;\n name: K;\n properties: MetaEdgeProperties;\n}>;\n\n// ============================================================\n// Ontology Relation\n// ============================================================\n\n/**\n * A relation in the ontology (instance of meta-edge between types).\n *\n * @example\n * ```typescript\n * // Podcast subClassOf Media\n * subClassOf(Podcast, Media)\n *\n * // Person equivalentTo schema:Person\n * equivalentTo(Person, \"https://schema.org/Person\")\n * ```\n */\nexport type OntologyRelation = Readonly<{\n metaEdge: MetaEdge;\n from: NodeType | EdgeType | string; // string for external IRIs\n to: NodeType | EdgeType | string;\n}>;\n\n// ============================================================\n// Type Guards\n// ============================================================\n\n/**\n * Checks if a value is a MetaEdge.\n */\nexport function isMetaEdge(value: unknown): value is MetaEdge {\n return (\n typeof value === \"object\" &&\n value !== null &&\n META_EDGE_BRAND in value &&\n (value as Record<string, unknown>)[META_EDGE_BRAND] === true\n );\n}\n\n/**\n * Gets the type name from a NodeType, EdgeType, or IRI string.\n */\nexport function getTypeName(typeOrIri: NodeType | EdgeType | string): string {\n if (typeof typeOrIri === \"string\") {\n return typeOrIri;\n }\n return typeOrIri.kind;\n}\n","import { type EdgeType, type NodeType } from \"../core/types\";\nimport {\n META_EDGE_BROADER,\n META_EDGE_DIFFERENT_FROM,\n META_EDGE_DISJOINT_WITH,\n META_EDGE_EQUIVALENT_TO,\n META_EDGE_HAS_PART,\n META_EDGE_IMPLIES,\n META_EDGE_INVERSE_OF,\n META_EDGE_NARROWER,\n META_EDGE_PART_OF,\n META_EDGE_RELATED_TO,\n META_EDGE_SAME_AS,\n META_EDGE_SUB_CLASS_OF,\n} from \"./constants\";\nimport { META_EDGE_BRAND, type MetaEdge, type OntologyRelation } from \"./types\";\n\n// ============================================================\n// Helper to Create Meta-Edge\n// ============================================================\n\nfunction createMetaEdge<K extends string>(\n name: K,\n properties: {\n transitive?: boolean;\n symmetric?: boolean;\n reflexive?: boolean;\n inverse?: string;\n inference:\n | \"subsumption\"\n | \"hierarchy\"\n | \"substitution\"\n | \"constraint\"\n | \"composition\"\n | \"association\"\n | \"none\";\n description: string;\n },\n): MetaEdge<K> {\n return Object.freeze({\n [META_EDGE_BRAND]: true as const,\n name,\n properties: {\n transitive: properties.transitive ?? false,\n symmetric: properties.symmetric ?? false,\n reflexive: properties.reflexive ?? false,\n inverse: properties.inverse,\n inference: properties.inference,\n description: properties.description,\n },\n });\n}\n\n// ============================================================\n// Subsumption & Classification\n// ============================================================\n\n/**\n * Type inheritance relationship.\n * A subClassOf B means instances of A are also instances of B.\n */\nconst subClassOfMetaEdge = createMetaEdge(META_EDGE_SUB_CLASS_OF, {\n transitive: true,\n inference: \"subsumption\",\n description: \"Type inheritance (Podcast subClassOf Media)\",\n});\n\n/**\n * Creates a subClassOf ontology relation.\n */\nexport function subClassOf(\n child: NodeType,\n parent: NodeType,\n): OntologyRelation {\n return {\n metaEdge: subClassOfMetaEdge,\n from: child,\n to: parent,\n };\n}\n\n// ============================================================\n// Hierarchical (SKOS-inspired)\n// ============================================================\n\n/**\n * Broader concept relationship.\n * A broader B means A is a more specific concept than B.\n */\nconst broaderMetaEdge = createMetaEdge(META_EDGE_BROADER, {\n transitive: true,\n inverse: META_EDGE_NARROWER,\n inference: \"hierarchy\",\n description: \"Broader concept (ML broader AI)\",\n});\n\n/**\n * Creates a broader ontology relation.\n */\nexport function broader(\n narrowerConcept: NodeType,\n broaderConcept: NodeType,\n): OntologyRelation {\n return {\n metaEdge: broaderMetaEdge,\n from: narrowerConcept,\n to: broaderConcept,\n };\n}\n\n/**\n * Narrower concept relationship.\n * A narrower B means A is a more general concept than B.\n */\nconst narrowerMetaEdge = createMetaEdge(META_EDGE_NARROWER, {\n transitive: true,\n inverse: META_EDGE_BROADER,\n inference: \"hierarchy\",\n description: \"Narrower concept (AI narrower ML)\",\n});\n\n/**\n * Creates a narrower ontology relation.\n */\nexport function narrower(\n broaderConcept: NodeType,\n narrowerConcept: NodeType,\n): OntologyRelation {\n return {\n metaEdge: narrowerMetaEdge,\n from: broaderConcept,\n to: narrowerConcept,\n };\n}\n\n/**\n * Related concept relationship.\n * Non-hierarchical association between concepts.\n */\nconst relatedToMetaEdge = createMetaEdge(META_EDGE_RELATED_TO, {\n symmetric: true,\n inference: \"association\",\n description: \"Non-hierarchical association\",\n});\n\n/**\n * Creates a relatedTo ontology relation.\n */\nexport function relatedTo(\n conceptA: NodeType,\n conceptB: NodeType,\n): OntologyRelation {\n return {\n metaEdge: relatedToMetaEdge,\n from: conceptA,\n to: conceptB,\n };\n}\n\n// ============================================================\n// Equivalence & Identity (OWL-inspired)\n// ============================================================\n\n/**\n * Type equivalence relationship.\n * A equivalentTo B means they represent the same class.\n */\nconst equivalentToMetaEdge = createMetaEdge(META_EDGE_EQUIVALENT_TO, {\n symmetric: true,\n transitive: true,\n inference: \"substitution\",\n description: \"Same class, different representation\",\n});\n\n/**\n * Creates an equivalentTo ontology relation.\n * Can be used with external IRIs for cross-system mapping.\n */\nexport function equivalentTo(\n kindA: NodeType,\n kindBOrIri: NodeType | string,\n): OntologyRelation {\n return {\n metaEdge: equivalentToMetaEdge,\n from: kindA,\n to: kindBOrIri,\n };\n}\n\n/**\n * Instance identity relationship.\n * A sameAs B means they refer to the same individual.\n */\nconst sameAsMetaEdge = createMetaEdge(META_EDGE_SAME_AS, {\n symmetric: true,\n transitive: true,\n inference: \"substitution\",\n description: \"Same individual (for deduplication)\",\n});\n\n/**\n * Creates a sameAs ontology relation.\n */\nexport function sameAs(\n kindA: NodeType,\n kindBOrIri: NodeType | string,\n): OntologyRelation {\n return {\n metaEdge: sameAsMetaEdge,\n from: kindA,\n to: kindBOrIri,\n };\n}\n\n/**\n * Explicit non-identity relationship.\n * A differentFrom B means they are definitely different individuals.\n */\nconst differentFromMetaEdge = createMetaEdge(META_EDGE_DIFFERENT_FROM, {\n symmetric: true,\n inference: \"constraint\",\n description: \"Explicitly different individuals\",\n});\n\n/**\n * Creates a differentFrom ontology relation.\n */\nexport function differentFrom(\n kindA: NodeType,\n kindB: NodeType,\n): OntologyRelation {\n return {\n metaEdge: differentFromMetaEdge,\n from: kindA,\n to: kindB,\n };\n}\n\n/**\n * Disjoint types relationship.\n * A disjointWith B means nothing can be both an A and a B.\n */\nconst disjointWithMetaEdge = createMetaEdge(META_EDGE_DISJOINT_WITH, {\n symmetric: true,\n inference: \"constraint\",\n description: \"Mutually exclusive types\",\n});\n\n/**\n * Creates a disjointWith ontology relation.\n */\nexport function disjointWith(\n kindA: NodeType,\n kindB: NodeType,\n): OntologyRelation {\n return {\n metaEdge: disjointWithMetaEdge,\n from: kindA,\n to: kindB,\n };\n}\n\n// ============================================================\n// Mereological (Part-Whole)\n// ============================================================\n\n/**\n * Part-of relationship.\n * A partOf B means A is a component of B.\n */\nconst partOfMetaEdge = createMetaEdge(META_EDGE_PART_OF, {\n transitive: true,\n inverse: META_EDGE_HAS_PART,\n inference: \"composition\",\n description: \"X is part of Y\",\n});\n\n/**\n * Creates a partOf ontology relation.\n */\nexport function partOf(part: NodeType, whole: NodeType): OntologyRelation {\n return {\n metaEdge: partOfMetaEdge,\n from: part,\n to: whole,\n };\n}\n\n/**\n * Has-part relationship.\n * A hasPart B means A contains B as a component.\n */\nconst hasPartMetaEdge = createMetaEdge(META_EDGE_HAS_PART, {\n transitive: true,\n inverse: META_EDGE_PART_OF,\n inference: \"composition\",\n description: \"Y has part X\",\n});\n\n/**\n * Creates a hasPart ontology relation.\n */\nexport function hasPart(whole: NodeType, part: NodeType): OntologyRelation {\n return {\n metaEdge: hasPartMetaEdge,\n from: whole,\n to: part,\n };\n}\n\n// ============================================================\n// Property Relationships\n// ============================================================\n\n/**\n * Inverse edge relationship.\n * Edge A inverseOf edge B means traversing A is equivalent to traversing B backwards.\n */\nconst inverseOfMetaEdge = createMetaEdge(META_EDGE_INVERSE_OF, {\n symmetric: true,\n inference: \"none\",\n description: \"Edge A is inverse of edge B\",\n});\n\n/**\n * Implication relationship.\n * Edge A implies edge B means if A exists, B should also exist.\n */\nconst impliesMetaEdge = createMetaEdge(META_EDGE_IMPLIES, {\n transitive: true,\n inference: \"none\",\n description: \"Edge A implies edge B exists\",\n});\n\n/**\n * Creates an inverseOf ontology relation.\n * Edge A inverseOf edge B means traversing A is equivalent to traversing B backwards.\n */\nexport function inverseOf(edgeA: EdgeType, edgeB: EdgeType): OntologyRelation {\n return {\n metaEdge: inverseOfMetaEdge,\n from: edgeA,\n to: edgeB,\n };\n}\n\n/**\n * Creates an implies ontology relation.\n * Edge A implies edge B means if A exists between two nodes, B should also exist.\n */\nexport function implies(edgeA: EdgeType, edgeB: EdgeType): OntologyRelation {\n return {\n metaEdge: impliesMetaEdge,\n from: edgeA,\n to: edgeB,\n };\n}\n\n// ============================================================\n// Core Ontology Export\n// ============================================================\n\n/**\n * The core ontology module containing all built-in meta-edges\n * and their relation factory functions.\n */\nexport const core = {\n // Meta-edges\n subClassOfMetaEdge,\n broaderMetaEdge,\n narrowerMetaEdge,\n relatedToMetaEdge,\n equivalentToMetaEdge,\n sameAsMetaEdge,\n differentFromMetaEdge,\n disjointWithMetaEdge,\n partOfMetaEdge,\n hasPartMetaEdge,\n inverseOfMetaEdge,\n impliesMetaEdge,\n\n // Relation factories\n subClassOf,\n broader,\n narrower,\n relatedTo,\n equivalentTo,\n sameAs,\n differentFrom,\n disjointWith,\n partOf,\n hasPart,\n inverseOf,\n implies,\n} as const;\n","/**\n * Schema migration utilities.\n *\n * Provides diff detection between schema versions to identify\n * what has changed and what migrations might be needed.\n */\nimport { type IndexEntity } from \"../core/types\";\nimport { type IndexDeclaration } from \"../indexes/types\";\nimport { canonicalEqual } from \"./canonical\";\nimport {\n type SerializedEdgeDef,\n type SerializedNodeDef,\n type SerializedOntology,\n type SerializedSchema,\n} from \"./types\";\n\n// ============================================================\n// Change Types\n// ============================================================\n\n/**\n * Types of changes that can occur in a schema.\n */\nexport type ChangeType = \"added\" | \"removed\" | \"modified\" | \"renamed\";\n\n/**\n * Severity of a change for migration purposes.\n */\nexport type ChangeSeverity =\n | \"safe\" // No data migration needed\n | \"warning\" // Might need attention\n | \"breaking\"; // Requires data migration\n\n// ============================================================\n// Node Changes\n// ============================================================\n\n/**\n * A change to a node definition.\n */\nexport type NodeChange = Readonly<{\n type: ChangeType;\n kind: string;\n severity: ChangeSeverity;\n details: string;\n before?: SerializedNodeDef | undefined;\n after?: SerializedNodeDef | undefined;\n}>;\n\n// ============================================================\n// Edge Changes\n// ============================================================\n\n/**\n * A change to an edge definition.\n */\nexport type EdgeChange = Readonly<{\n type: ChangeType;\n kind: string;\n severity: ChangeSeverity;\n details: string;\n before?: SerializedEdgeDef | undefined;\n after?: SerializedEdgeDef | undefined;\n}>;\n\n// ============================================================\n// Ontology Changes\n// ============================================================\n\n/**\n * A change to the ontology.\n */\nexport type OntologyChange = Readonly<{\n type: ChangeType;\n entity: \"metaEdge\" | \"relation\";\n name: string;\n severity: ChangeSeverity;\n details: string;\n}>;\n\n// ============================================================\n// Index Changes\n// ============================================================\n\n/**\n * A change to an index declaration.\n *\n * Index changes are always `safe`-severity: index DDL is materialized\n * separately and never blocks schema-version commits or migrations.\n * Adding, removing, or modifying an index never invalidates existing\n * data — it only changes which physical indexes the deployment will\n * materialize on its next pass.\n */\nexport type IndexChange = Readonly<{\n type: ChangeType;\n /** Index name (the diffing identity key). */\n name: string;\n /**\n * Whether this index is on a node, edge, or vector field. Vector\n * index changes flow through the same diff classification as\n * relational ones.\n */\n entity: IndexEntity;\n severity: ChangeSeverity;\n details: string;\n before?: IndexDeclaration | undefined;\n after?: IndexDeclaration | undefined;\n}>;\n\n// ============================================================\n// Graph Extension Document Changes\n// ============================================================\n\n/**\n * A change to the persisted graph-extension document.\n *\n * Graph-extension document changes are committed only through the\n * graph-extension lifecycle verbs (`evolve` and `removeKinds`), so the\n * extension-slice change itself is `safe`-severity. The detailed\n * per-kind effect is captured in the corresponding node/edge/ontology\n * changes the merged document produced.\n */\nexport type ExtensionChange = Readonly<{\n type: ChangeType;\n severity: ChangeSeverity;\n details: string;\n}>;\n\n// ============================================================\n// Deprecated Kinds Changes\n// ============================================================\n\n/**\n * Change to the soft-deprecated kind set. `safe`-severity by\n * construction — deprecation is a metadata signal that doesn't gate\n * reads, writes, or queries. The `added` and `removed` arrays carry\n * the per-name deltas so consumers can render granular diffs.\n */\nexport type DeprecatedKindsChange = Readonly<{\n added: readonly string[];\n removed: readonly string[];\n severity: ChangeSeverity;\n details: string;\n}>;\n\n// ============================================================\n// Schema Diff\n// ============================================================\n\n/**\n * A complete diff between two schema versions.\n */\nexport type SchemaDiff = Readonly<{\n fromVersion: number;\n toVersion: number;\n\n /** Changes to node definitions */\n nodes: readonly NodeChange[];\n\n /** Changes to edge definitions */\n edges: readonly EdgeChange[];\n\n /** Changes to ontology */\n ontology: readonly OntologyChange[];\n\n /** Changes to index declarations */\n indexes: readonly IndexChange[];\n\n /**\n * Change to the graph-extension document, if any. `undefined` when\n * the slice is unchanged on both sides (the common case).\n */\n extension?: ExtensionChange;\n\n /**\n * Change to the soft-deprecated kind set, if any. `undefined` when\n * the set is unchanged on both sides.\n */\n deprecatedKinds?: DeprecatedKindsChange;\n\n /** Whether any breaking changes exist */\n hasBreakingChanges: boolean;\n\n /** Whether the change is backwards compatible (no breaking changes) */\n isBackwardsCompatible: boolean;\n\n /** Whether any changes exist at all */\n hasChanges: boolean;\n\n /** Summary of changes */\n summary: string;\n}>;\n\n// ============================================================\n// Diff Computation\n// ============================================================\n\n/**\n * Computes the diff between two schema versions.\n *\n * @param before - The previous schema version\n * @param after - The new schema version\n * @returns A diff describing all changes\n */\nexport function computeSchemaDiff(\n before: SerializedSchema,\n after: SerializedSchema,\n): SchemaDiff {\n const nodeChanges = diffNodes(before.nodes, after.nodes);\n const edgeChanges = diffEdges(before.edges, after.edges);\n const ontologyChanges = diffOntology(before.ontology, after.ontology);\n const indexChanges = diffIndexes(before.indexes, after.indexes);\n const extensionChange = diffExtension(before.extension, after.extension);\n const deprecatedKindsChange = diffDeprecatedKinds(\n before.deprecatedKinds,\n after.deprecatedKinds,\n );\n\n const allChanges = [\n ...nodeChanges,\n ...edgeChanges,\n ...ontologyChanges,\n ...indexChanges,\n ];\n const hasBreakingChanges = allChanges.some(\n (change) => change.severity === \"breaking\",\n );\n const hasChanges =\n allChanges.length > 0 ||\n extensionChange !== undefined ||\n deprecatedKindsChange !== undefined;\n\n const summary = generateSummary(\n nodeChanges,\n edgeChanges,\n ontologyChanges,\n indexChanges,\n extensionChange,\n deprecatedKindsChange,\n );\n\n return {\n fromVersion: before.version,\n toVersion: after.version,\n nodes: nodeChanges,\n edges: edgeChanges,\n ontology: ontologyChanges,\n indexes: indexChanges,\n ...(extensionChange === undefined ? {} : { extension: extensionChange }),\n ...(deprecatedKindsChange === undefined ?\n {}\n : { deprecatedKinds: deprecatedKindsChange }),\n hasBreakingChanges,\n isBackwardsCompatible: !hasBreakingChanges,\n hasChanges,\n summary,\n };\n}\n\n// ============================================================\n// Node Diff\n// ============================================================\n\n/**\n * Computes changes between node definitions.\n */\nfunction diffNodes(\n before: Record<string, SerializedNodeDef>,\n after: Record<string, SerializedNodeDef>,\n): readonly NodeChange[] {\n const changes: NodeChange[] = [];\n const beforeNames = new Set(Object.keys(before));\n const afterNames = new Set(Object.keys(after));\n\n // Find removed nodes\n for (const name of beforeNames) {\n if (!afterNames.has(name)) {\n changes.push({\n type: \"removed\",\n kind: name,\n severity: \"breaking\",\n details: `Node kind \"${name}\" was removed`,\n before: before[name],\n });\n }\n }\n\n // Find added nodes\n for (const name of afterNames) {\n if (!beforeNames.has(name)) {\n changes.push({\n type: \"added\",\n kind: name,\n severity: \"safe\",\n details: `Node kind \"${name}\" was added`,\n after: after[name],\n });\n }\n }\n\n // Find modified nodes\n for (const name of beforeNames) {\n if (afterNames.has(name)) {\n const nodeBefore = before[name]!;\n const nodeAfter = after[name]!;\n const nodeChanges = diffNodeDef(name, nodeBefore, nodeAfter);\n changes.push(...nodeChanges);\n }\n }\n\n return changes;\n}\n\n/**\n * Computes changes to a single node definition.\n */\nfunction diffNodeDef(\n name: string,\n before: SerializedNodeDef,\n after: SerializedNodeDef,\n): readonly NodeChange[] {\n const changes: NodeChange[] = [];\n\n // Check property schema changes\n if (!canonicalEqual(before.properties, after.properties)) {\n // Determine if properties were added or removed\n const beforeProps = before.properties.properties ?? {};\n const afterProps = after.properties.properties ?? {};\n const beforeRequired = new Set(before.properties.required);\n const afterRequired = new Set(after.properties.required);\n\n const addedProps = Object.keys(afterProps).filter(\n (p) => !(p in beforeProps),\n );\n const removedProps = Object.keys(beforeProps).filter(\n (p) => !(p in afterProps),\n );\n const newRequired = [...afterRequired].filter(\n (p) => !beforeRequired.has(p),\n );\n\n const { severity, details } = computePropertyChangeSeverity(\n name,\n removedProps,\n addedProps,\n newRequired,\n );\n\n changes.push({\n type: \"modified\",\n kind: name,\n severity,\n details,\n before,\n after,\n });\n }\n\n // Check onDelete behavior\n if (before.onDelete !== after.onDelete) {\n changes.push({\n type: \"modified\",\n kind: name,\n severity: \"warning\",\n details: `onDelete changed from \"${before.onDelete}\" to \"${after.onDelete}\" for \"${name}\"`,\n before,\n after,\n });\n }\n\n // Check unique constraints\n if (!canonicalEqual(before.uniqueConstraints, after.uniqueConstraints)) {\n changes.push({\n type: \"modified\",\n kind: name,\n severity: \"warning\",\n details: `Unique constraints changed for \"${name}\"`,\n before,\n after,\n });\n }\n\n if (annotationsChanged(before.annotations, after.annotations)) {\n changes.push({\n type: \"modified\",\n kind: name,\n severity: \"safe\",\n details: `Annotations changed for \"${name}\"`,\n before,\n after,\n });\n }\n\n return changes;\n}\n\n/**\n * Computes the severity and details message for property changes.\n */\nfunction computePropertyChangeSeverity(\n name: string,\n removedProps: readonly string[],\n addedProps: readonly string[],\n newRequired: readonly string[],\n): { severity: ChangeSeverity; details: string } {\n if (removedProps.length > 0) {\n return {\n severity: \"breaking\",\n details: `Properties removed from \"${name}\": ${removedProps.join(\", \")}`,\n };\n }\n if (newRequired.length > 0) {\n return {\n severity: \"breaking\",\n details: `New required properties in \"${name}\": ${newRequired.join(\", \")}`,\n };\n }\n if (addedProps.length > 0) {\n return {\n severity: \"safe\",\n details: `Properties added to \"${name}\": ${addedProps.join(\", \")}`,\n };\n }\n return {\n severity: \"safe\",\n details: `Properties changed in \"${name}\"`,\n };\n}\n\n// ============================================================\n// Edge Diff\n// ============================================================\n\n/**\n * Computes changes between edge definitions.\n */\nfunction diffEdges(\n before: Record<string, SerializedEdgeDef>,\n after: Record<string, SerializedEdgeDef>,\n): readonly EdgeChange[] {\n const changes: EdgeChange[] = [];\n const beforeNames = new Set(Object.keys(before));\n const afterNames = new Set(Object.keys(after));\n\n // Find removed edges\n for (const name of beforeNames) {\n if (!afterNames.has(name)) {\n changes.push({\n type: \"removed\",\n kind: name,\n severity: \"breaking\",\n details: `Edge kind \"${name}\" was removed`,\n before: before[name],\n });\n }\n }\n\n // Find added edges\n for (const name of afterNames) {\n if (!beforeNames.has(name)) {\n changes.push({\n type: \"added\",\n kind: name,\n severity: \"safe\",\n details: `Edge kind \"${name}\" was added`,\n after: after[name],\n });\n }\n }\n\n // Find modified edges\n for (const name of beforeNames) {\n if (afterNames.has(name)) {\n const edgeBefore = before[name]!;\n const edgeAfter = after[name]!;\n const edgeChanges = diffEdgeDef(name, edgeBefore, edgeAfter);\n changes.push(...edgeChanges);\n }\n }\n\n return changes;\n}\n\n/**\n * Computes changes to a single edge definition.\n */\nfunction diffEdgeDef(\n name: string,\n before: SerializedEdgeDef,\n after: SerializedEdgeDef,\n): readonly EdgeChange[] {\n const changes: EdgeChange[] = [];\n\n // Check endpoint kinds\n if (!canonicalEqual(before.fromKinds, after.fromKinds)) {\n changes.push({\n type: \"modified\",\n kind: name,\n severity: \"warning\",\n details: `fromKinds changed for \"${name}\"`,\n before,\n after,\n });\n }\n\n if (!canonicalEqual(before.toKinds, after.toKinds)) {\n changes.push({\n type: \"modified\",\n kind: name,\n severity: \"warning\",\n details: `toKinds changed for \"${name}\"`,\n before,\n after,\n });\n }\n\n // Check cardinality\n if (before.cardinality !== after.cardinality) {\n changes.push({\n type: \"modified\",\n kind: name,\n severity: \"warning\",\n details: `Cardinality changed from \"${before.cardinality}\" to \"${after.cardinality}\" for \"${name}\"`,\n before,\n after,\n });\n }\n\n // Check properties\n if (!canonicalEqual(before.properties, after.properties)) {\n changes.push({\n type: \"modified\",\n kind: name,\n severity: \"safe\",\n details: `Properties changed for \"${name}\"`,\n before,\n after,\n });\n }\n\n if (annotationsChanged(before.annotations, after.annotations)) {\n changes.push({\n type: \"modified\",\n kind: name,\n severity: \"safe\",\n details: `Annotations changed for \"${name}\"`,\n before,\n after,\n });\n }\n\n return changes;\n}\n\nfunction annotationsChanged(before: unknown, after: unknown): boolean {\n if (before === undefined && after === undefined) return false;\n if (before === undefined || after === undefined) return true;\n return !canonicalEqual(before, after);\n}\n\n// ============================================================\n// Ontology Diff\n// ============================================================\n\n/**\n * Computes changes to the ontology.\n */\nfunction diffOntology(\n before: SerializedOntology,\n after: SerializedOntology,\n): readonly OntologyChange[] {\n const changes: OntologyChange[] = [];\n\n // Diff meta-edges\n const metaEdgesBefore = new Set(Object.keys(before.metaEdges));\n const metaEdgesAfter = new Set(Object.keys(after.metaEdges));\n\n for (const name of metaEdgesBefore) {\n if (!metaEdgesAfter.has(name)) {\n changes.push({\n type: \"removed\",\n entity: \"metaEdge\",\n name,\n severity: \"breaking\",\n details: `Meta-edge \"${name}\" was removed`,\n });\n }\n }\n\n for (const name of metaEdgesAfter) {\n if (!metaEdgesBefore.has(name)) {\n changes.push({\n type: \"added\",\n entity: \"metaEdge\",\n name,\n severity: \"safe\",\n details: `Meta-edge \"${name}\" was added`,\n });\n }\n }\n\n // Diff relations (simplified - just detect additions/removals)\n const relationsBefore = new Set(\n before.relations.map((r) => `${r.metaEdge}:${r.from}:${r.to}`),\n );\n const relationsAfter = new Set(\n after.relations.map((r) => `${r.metaEdge}:${r.from}:${r.to}`),\n );\n\n for (const relationKey of relationsBefore) {\n if (!relationsAfter.has(relationKey)) {\n const [metaEdge, from, to] = relationKey.split(\":\");\n changes.push({\n type: \"removed\",\n entity: \"relation\",\n name: relationKey,\n severity: \"warning\",\n details: `Relation ${metaEdge}(${from}, ${to}) was removed`,\n });\n }\n }\n\n for (const relationKey of relationsAfter) {\n if (!relationsBefore.has(relationKey)) {\n const [metaEdge, from, to] = relationKey.split(\":\");\n changes.push({\n type: \"added\",\n entity: \"relation\",\n name: relationKey,\n severity: \"safe\",\n details: `Relation ${metaEdge}(${from}, ${to}) was added`,\n });\n }\n }\n\n return changes;\n}\n\n// ============================================================\n// Index Diff\n// ============================================================\n\n/**\n * Computes changes between index declarations.\n *\n * Indexes are identified by `name`. Add/remove/modify produce\n * `safe`-severity changes — index DDL is materialized separately and\n * never blocks schema-version commits.\n */\nfunction diffIndexes(\n before: readonly IndexDeclaration[] | undefined,\n after: readonly IndexDeclaration[] | undefined,\n): readonly IndexChange[] {\n const beforeIndexes = before ?? [];\n const afterIndexes = after ?? [];\n\n const beforeByName = new Map<string, IndexDeclaration>();\n for (const index of beforeIndexes) {\n beforeByName.set(index.name, index);\n }\n const afterByName = new Map<string, IndexDeclaration>();\n for (const index of afterIndexes) {\n afterByName.set(index.name, index);\n }\n\n const changes: IndexChange[] = [];\n\n for (const [name, index] of beforeByName) {\n if (!afterByName.has(name)) {\n changes.push({\n type: \"removed\",\n name,\n entity: index.entity,\n severity: \"safe\",\n details: `Index \"${name}\" was removed`,\n before: index,\n });\n }\n }\n\n for (const [name, index] of afterByName) {\n if (!beforeByName.has(name)) {\n changes.push({\n type: \"added\",\n name,\n entity: index.entity,\n severity: \"safe\",\n details: `Index \"${name}\" was added`,\n after: index,\n });\n }\n }\n\n for (const [name, beforeIndex] of beforeByName) {\n const afterIndex = afterByName.get(name);\n if (!afterIndex) continue;\n if (!canonicalEqual(beforeIndex, afterIndex)) {\n changes.push({\n type: \"modified\",\n name,\n entity: beforeIndex.entity,\n severity: \"safe\",\n details: `Index \"${name}\" was modified`,\n before: beforeIndex,\n after: afterIndex,\n });\n }\n }\n\n return changes;\n}\n\n// ============================================================\n// Graph Extension Document Diff\n// ============================================================\n\n/**\n * Computes the change to the graph-extension document, if any. The\n * extension-slice change itself is always `safe` — the per-kind effects\n * of the merged document already surface as node/edge/ontology changes.\n */\nfunction diffExtension(\n before: SerializedSchema[\"extension\"],\n after: SerializedSchema[\"extension\"],\n): ExtensionChange | undefined {\n // Reference-equality short-circuit: when the loader threads the same\n // persisted document reference into the merged graph (the common\n // restart-with-no-evolve case), we avoid stringifying potentially\n // large agent-generated documents on every ensureSchema call.\n if (before === after) return undefined;\n if (before === undefined) {\n return {\n type: \"added\",\n severity: \"safe\",\n details: \"Graph extension document was added\",\n };\n }\n if (after === undefined) {\n return {\n type: \"removed\",\n severity: \"safe\",\n details: \"Graph extension document was removed\",\n };\n }\n if (canonicalEqual(before, after)) return undefined;\n return {\n type: \"modified\",\n severity: \"safe\",\n details: \"Graph extension document was modified\",\n };\n}\n\n// ============================================================\n// Deprecated Kinds Diff\n// ============================================================\n\n/**\n * Computes the change to the soft-deprecated kind set, if any.\n * `safe`-severity by construction; the per-name `added` / `removed`\n * deltas let consumers render granular diffs without re-comparing the\n * whole set.\n */\nfunction diffDeprecatedKinds(\n before: SerializedSchema[\"deprecatedKinds\"],\n after: SerializedSchema[\"deprecatedKinds\"],\n): DeprecatedKindsChange | undefined {\n // Compare by value. The parse cache may share array identity between\n // repeated reads of the same row, but schema diffs still need to be\n // independent of object identity.\n const beforeSet = new Set(before);\n const afterSet = new Set(after);\n const added: string[] = [];\n const removed: string[] = [];\n for (const name of afterSet) {\n if (!beforeSet.has(name)) added.push(name);\n }\n for (const name of beforeSet) {\n if (!afterSet.has(name)) removed.push(name);\n }\n if (added.length === 0 && removed.length === 0) return undefined;\n added.sort();\n removed.sort();\n const parts: string[] = [];\n if (added.length > 0) parts.push(`added ${added.join(\", \")}`);\n if (removed.length > 0) parts.push(`removed ${removed.join(\", \")}`);\n return {\n added,\n removed,\n severity: \"safe\",\n details: `Deprecated kinds: ${parts.join(\"; \")}`,\n };\n}\n\n// ============================================================\n// Summary Generation\n// ============================================================\n\n/**\n * Generates a human-readable summary of changes.\n */\nfunction generateSummary(\n nodeChanges: readonly NodeChange[],\n edgeChanges: readonly EdgeChange[],\n ontologyChanges: readonly OntologyChange[],\n indexChanges: readonly IndexChange[],\n extensionChange: ExtensionChange | undefined,\n deprecatedKindsChange: DeprecatedKindsChange | undefined,\n): string {\n const parts: string[] = [];\n\n const nodeAdded = nodeChanges.filter((c) => c.type === \"added\").length;\n const nodeRemoved = nodeChanges.filter((c) => c.type === \"removed\").length;\n const nodeModified = nodeChanges.filter((c) => c.type === \"modified\").length;\n\n if (nodeAdded > 0 || nodeRemoved > 0 || nodeModified > 0) {\n parts.push(\n `Nodes: ${nodeAdded} added, ${nodeRemoved} removed, ${nodeModified} modified`,\n );\n }\n\n const edgeAdded = edgeChanges.filter((c) => c.type === \"added\").length;\n const edgeRemoved = edgeChanges.filter((c) => c.type === \"removed\").length;\n const edgeModified = edgeChanges.filter((c) => c.type === \"modified\").length;\n\n if (edgeAdded > 0 || edgeRemoved > 0 || edgeModified > 0) {\n parts.push(\n `Edges: ${edgeAdded} added, ${edgeRemoved} removed, ${edgeModified} modified`,\n );\n }\n\n const ontologyAdded = ontologyChanges.filter(\n (c) => c.type === \"added\",\n ).length;\n const ontologyRemoved = ontologyChanges.filter(\n (c) => c.type === \"removed\",\n ).length;\n\n if (ontologyAdded > 0 || ontologyRemoved > 0) {\n parts.push(`Ontology: ${ontologyAdded} added, ${ontologyRemoved} removed`);\n }\n\n const indexAdded = indexChanges.filter((c) => c.type === \"added\").length;\n const indexRemoved = indexChanges.filter((c) => c.type === \"removed\").length;\n const indexModified = indexChanges.filter(\n (c) => c.type === \"modified\",\n ).length;\n\n if (indexAdded > 0 || indexRemoved > 0 || indexModified > 0) {\n parts.push(\n `Indexes: ${indexAdded} added, ${indexRemoved} removed, ${indexModified} modified`,\n );\n }\n\n if (extensionChange !== undefined) {\n parts.push(`Graph extension document: ${extensionChange.type}`);\n }\n\n if (deprecatedKindsChange !== undefined) {\n const { added, removed } = deprecatedKindsChange;\n parts.push(\n `Deprecated kinds: ${added.length} added, ${removed.length} removed`,\n );\n }\n\n if (parts.length === 0) {\n return \"No changes\";\n }\n\n return parts.join(\"; \");\n}\n\n// ============================================================\n// Migration Helpers\n// ============================================================\n\n/**\n * Checks if a schema change is backwards compatible.\n *\n * A change is backwards compatible if:\n * - No nodes or edges were removed\n * - No required properties were added\n * - No existing properties were removed\n */\nexport function isBackwardsCompatible(diff: SchemaDiff): boolean {\n return !diff.hasBreakingChanges;\n}\n\n/**\n * Gets a list of actions needed for migration.\n */\nexport function getMigrationActions(diff: SchemaDiff): readonly string[] {\n const actions: string[] = [];\n\n for (const change of diff.nodes) {\n if (change.type === \"removed\") {\n actions.push(`DELETE data for removed node kind \"${change.kind}\"`);\n }\n if (change.severity === \"breaking\" && change.type === \"modified\") {\n actions.push(\n `MIGRATE data for node kind \"${change.kind}\": ${change.details}`,\n );\n }\n }\n\n for (const change of diff.edges) {\n if (change.type === \"removed\") {\n actions.push(`DELETE data for removed edge kind \"${change.kind}\"`);\n }\n }\n\n return actions;\n}\n","import { type AnyEdgeType, type NodeType } from \"../core/types\";\nimport {\n computeTransitiveClosure,\n invertClosure,\n isReachable,\n} from \"../ontology/closures\";\nimport {\n META_EDGE_BROADER,\n META_EDGE_DISJOINT_WITH,\n META_EDGE_EQUIVALENT_TO,\n META_EDGE_HAS_PART,\n META_EDGE_IMPLIES,\n META_EDGE_INVERSE_OF,\n META_EDGE_NARROWER,\n META_EDGE_PART_OF,\n META_EDGE_SAME_AS,\n META_EDGE_SUB_CLASS_OF,\n} from \"../ontology/constants\";\nimport { type OntologyRelation } from \"../ontology/types\";\n\n/**\n * KindRegistry holds precomputed closures for ontological reasoning.\n *\n * Computed at store initialization and cached for fast query-time lookups.\n */\nexport class KindRegistry {\n // === Node & Edge Kinds ===\n readonly nodeKinds: ReadonlyMap<string, NodeType>;\n readonly edgeKinds: ReadonlyMap<string, AnyEdgeType>;\n\n // === Subsumption (subClassOf) ===\n // Transitive closure for inheritance\n readonly subClassAncestors: ReadonlyMap<string, ReadonlySet<string>>;\n readonly subClassDescendants: ReadonlyMap<string, ReadonlySet<string>>;\n\n // === Hierarchy (broader/narrower) ===\n // Transitive closure for concept hierarchy (separate from subClassOf!)\n readonly broaderClosure: ReadonlyMap<string, ReadonlySet<string>>;\n readonly narrowerClosure: ReadonlyMap<string, ReadonlySet<string>>;\n\n // === Equivalence ===\n readonly equivalenceSets: ReadonlyMap<string, ReadonlySet<string>>;\n readonly iriToKind: ReadonlyMap<string, string>;\n\n // === Constraints ===\n readonly disjointPairs: ReadonlySet<string>; // Normalized pairs: \"Organization|Person\"\n\n // === Composition ===\n readonly partOfClosure: ReadonlyMap<string, ReadonlySet<string>>;\n readonly hasPartClosure: ReadonlyMap<string, ReadonlySet<string>>;\n\n // === Edge Relationships ===\n readonly edgeInverses: ReadonlyMap<string, string>;\n readonly edgeImplicationsClosure: ReadonlyMap<string, ReadonlySet<string>>;\n readonly edgeImplyingClosure: ReadonlyMap<string, ReadonlySet<string>>;\n\n constructor(\n nodeKinds: ReadonlyMap<string, NodeType>,\n edgeKinds: ReadonlyMap<string, AnyEdgeType>,\n closures: {\n subClassAncestors: ReadonlyMap<string, ReadonlySet<string>>;\n subClassDescendants: ReadonlyMap<string, ReadonlySet<string>>;\n broaderClosure: ReadonlyMap<string, ReadonlySet<string>>;\n narrowerClosure: ReadonlyMap<string, ReadonlySet<string>>;\n equivalenceSets: ReadonlyMap<string, ReadonlySet<string>>;\n iriToKind: ReadonlyMap<string, string>;\n disjointPairs: ReadonlySet<string>;\n partOfClosure: ReadonlyMap<string, ReadonlySet<string>>;\n hasPartClosure: ReadonlyMap<string, ReadonlySet<string>>;\n edgeInverses: ReadonlyMap<string, string>;\n edgeImplicationsClosure: ReadonlyMap<string, ReadonlySet<string>>;\n edgeImplyingClosure: ReadonlyMap<string, ReadonlySet<string>>;\n },\n ) {\n this.nodeKinds = nodeKinds;\n this.edgeKinds = edgeKinds;\n this.subClassAncestors = closures.subClassAncestors;\n this.subClassDescendants = closures.subClassDescendants;\n this.broaderClosure = closures.broaderClosure;\n this.narrowerClosure = closures.narrowerClosure;\n this.equivalenceSets = closures.equivalenceSets;\n this.iriToKind = closures.iriToKind;\n this.disjointPairs = closures.disjointPairs;\n this.partOfClosure = closures.partOfClosure;\n this.hasPartClosure = closures.hasPartClosure;\n this.edgeInverses = closures.edgeInverses;\n this.edgeImplicationsClosure = closures.edgeImplicationsClosure;\n this.edgeImplyingClosure = closures.edgeImplyingClosure;\n }\n\n // === Subsumption Methods ===\n\n /**\n * Checks if child is a subclass of parent (directly or transitively).\n */\n isSubClassOf(child: string, parent: string): boolean {\n return isReachable(this.subClassAncestors, child, parent);\n }\n\n /**\n * Expands a kind to include all its subclasses.\n * Returns [kind, ...subclasses].\n */\n expandSubClasses(kind: string): readonly string[] {\n const descendants = this.subClassDescendants.get(kind) ?? new Set();\n return [kind, ...descendants];\n }\n\n /**\n * Gets all ancestors of a kind (via subClassOf).\n */\n getAncestors(kind: string): ReadonlySet<string> {\n return this.subClassAncestors.get(kind) ?? new Set();\n }\n\n /**\n * Gets all descendants of a kind (via subClassOf).\n */\n getDescendants(kind: string): ReadonlySet<string> {\n return this.subClassDescendants.get(kind) ?? new Set();\n }\n\n // === Hierarchy Methods ===\n\n /**\n * Checks if narrowerConcept is narrower than broaderConcept.\n */\n isNarrowerThan(narrowerConcept: string, broaderConcept: string): boolean {\n return isReachable(this.broaderClosure, narrowerConcept, broaderConcept);\n }\n\n /**\n * Checks if broaderConcept is broader than narrowerConcept.\n */\n isBroaderThan(broaderConcept: string, narrowerConcept: string): boolean {\n return isReachable(this.narrowerClosure, broaderConcept, narrowerConcept);\n }\n\n /**\n * Expands to include all narrower concepts.\n */\n expandNarrower(kind: string): readonly string[] {\n const narrower = this.narrowerClosure.get(kind) ?? new Set();\n return [kind, ...narrower];\n }\n\n /**\n * Expands to include all broader concepts.\n */\n expandBroader(kind: string): readonly string[] {\n const broader = this.broaderClosure.get(kind) ?? new Set();\n return [kind, ...broader];\n }\n\n // === Equivalence Methods ===\n\n /**\n * Checks if two kinds are equivalent.\n */\n areEquivalent(a: string, b: string): boolean {\n const equivalents = this.equivalenceSets.get(a);\n return equivalents?.has(b) ?? false;\n }\n\n /**\n * Gets all equivalents of a kind (including external IRIs).\n */\n getEquivalents(kind: string): readonly string[] {\n const equivalents = this.equivalenceSets.get(kind);\n return equivalents ? [...equivalents] : [];\n }\n\n /**\n * Resolves an external IRI to an internal kind name.\n */\n resolveIri(iri: string): string | undefined {\n return this.iriToKind.get(iri);\n }\n\n // === Constraint Methods ===\n\n /**\n * Checks if two kinds are disjoint.\n */\n areDisjoint(a: string, b: string): boolean {\n const normalizedPair = a < b ? `${a}|${b}` : `${b}|${a}`;\n return this.disjointPairs.has(normalizedPair);\n }\n\n /**\n * Gets all kinds that are disjoint with the given kind.\n */\n getDisjointKinds(kind: string): readonly string[] {\n const result: string[] = [];\n for (const pair of this.disjointPairs) {\n const parts = pair.split(\"|\");\n const firstKind = parts[0]!;\n const secondKind = parts[1]!;\n if (firstKind === kind) result.push(secondKind);\n else if (secondKind === kind) result.push(firstKind);\n }\n return result;\n }\n\n // === Composition Methods ===\n\n /**\n * Checks if part is part of whole (directly or transitively).\n */\n isPartOf(part: string, whole: string): boolean {\n return isReachable(this.partOfClosure, part, whole);\n }\n\n /**\n * Gets all wholes that contain this part.\n */\n getWholes(part: string): readonly string[] {\n const wholes = this.partOfClosure.get(part);\n return wholes ? [...wholes] : [];\n }\n\n /**\n * Gets all parts of this whole.\n */\n getParts(whole: string): readonly string[] {\n const parts = this.hasPartClosure.get(whole);\n return parts ? [...parts] : [];\n }\n\n // === Edge Relationship Methods ===\n\n /**\n * Gets the inverse edge kind for a given edge kind.\n * If edgeA inverseOf edgeB, then getInverseEdge(\"edgeA\") returns \"edgeB\".\n */\n getInverseEdge(edgeKind: string): string | undefined {\n return this.edgeInverses.get(edgeKind);\n }\n\n /**\n * Gets all edges implied by a given edge (transitively).\n * If A implies B and B implies C, then getImpliedEdges(\"A\") returns [\"B\", \"C\"].\n */\n getImpliedEdges(edgeKind: string): readonly string[] {\n const implied = this.edgeImplicationsClosure.get(edgeKind);\n return implied ? [...implied] : [];\n }\n\n /**\n * Gets all edges that imply a given edge (transitively).\n * If A implies B and B implies C, then getImplyingEdges(\"C\") returns [\"A\", \"B\"].\n * Used for query-time expansion: when querying for C, also include A and B edges.\n */\n getImplyingEdges(edgeKind: string): readonly string[] {\n const implying = this.edgeImplyingClosure.get(edgeKind);\n return implying ? [...implying] : [];\n }\n\n /**\n * Expands an edge kind to include all edges that imply it.\n * Returns [edgeKind, ...implyingEdges].\n */\n expandImplyingEdges(edgeKind: string): readonly string[] {\n const implying = this.edgeImplyingClosure.get(edgeKind) ?? new Set();\n return [edgeKind, ...implying];\n }\n\n // === Edge Endpoint Validation ===\n\n /**\n * Checks if a concrete kind is assignable to a target kind.\n * Uses subsumption: Company is assignable to Organization if Company subClassOf Organization.\n */\n isAssignableTo(concreteKind: string, targetKind: string): boolean {\n if (concreteKind === targetKind) return true;\n return this.isSubClassOf(concreteKind, targetKind);\n }\n\n /**\n * Validates that a kind exists in the registry.\n */\n hasNodeType(name: string): boolean {\n return this.nodeKinds.has(name);\n }\n\n /**\n * Validates that an edge kind exists in the registry.\n */\n hasEdgeType(name: string): boolean {\n return this.edgeKinds.has(name);\n }\n\n /**\n * Gets a node kind by name.\n */\n getNodeType(name: string): NodeType | undefined {\n return this.nodeKinds.get(name);\n }\n\n /**\n * Gets an edge kind by name.\n */\n getEdgeType(name: string): AnyEdgeType | undefined {\n return this.edgeKinds.get(name);\n }\n}\n\n/**\n * Builder function to create empty closures.\n */\nexport function createEmptyClosures(): {\n subClassAncestors: ReadonlyMap<string, ReadonlySet<string>>;\n subClassDescendants: ReadonlyMap<string, ReadonlySet<string>>;\n broaderClosure: ReadonlyMap<string, ReadonlySet<string>>;\n narrowerClosure: ReadonlyMap<string, ReadonlySet<string>>;\n equivalenceSets: ReadonlyMap<string, ReadonlySet<string>>;\n iriToKind: ReadonlyMap<string, string>;\n disjointPairs: ReadonlySet<string>;\n partOfClosure: ReadonlyMap<string, ReadonlySet<string>>;\n hasPartClosure: ReadonlyMap<string, ReadonlySet<string>>;\n edgeInverses: ReadonlyMap<string, string>;\n edgeImplicationsClosure: ReadonlyMap<string, ReadonlySet<string>>;\n edgeImplyingClosure: ReadonlyMap<string, ReadonlySet<string>>;\n} {\n return {\n subClassAncestors: new Map(),\n subClassDescendants: new Map(),\n broaderClosure: new Map(),\n narrowerClosure: new Map(),\n equivalenceSets: new Map(),\n iriToKind: new Map(),\n disjointPairs: new Set(),\n partOfClosure: new Map(),\n hasPartClosure: new Map(),\n edgeInverses: new Map(),\n edgeImplicationsClosure: new Map(),\n edgeImplyingClosure: new Map(),\n };\n}\n\n/**\n * Computes all closures from an ontology.\n */\nexport function computeClosuresFromOntology(\n ontology: readonly OntologyRelation[],\n): {\n subClassAncestors: ReadonlyMap<string, ReadonlySet<string>>;\n subClassDescendants: ReadonlyMap<string, ReadonlySet<string>>;\n broaderClosure: ReadonlyMap<string, ReadonlySet<string>>;\n narrowerClosure: ReadonlyMap<string, ReadonlySet<string>>;\n equivalenceSets: ReadonlyMap<string, ReadonlySet<string>>;\n iriToKind: ReadonlyMap<string, string>;\n disjointPairs: ReadonlySet<string>;\n partOfClosure: ReadonlyMap<string, ReadonlySet<string>>;\n hasPartClosure: ReadonlyMap<string, ReadonlySet<string>>;\n edgeInverses: ReadonlyMap<string, string>;\n edgeImplicationsClosure: ReadonlyMap<string, ReadonlySet<string>>;\n edgeImplyingClosure: ReadonlyMap<string, ReadonlySet<string>>;\n} {\n // Collect relations by type\n const subClassRelations: [string, string][] = [];\n const broaderRelations: [string, string][] = [];\n const equivalentRelations: [string, string][] = [];\n const disjointRelations: [string, string][] = [];\n const partOfRelations: [string, string][] = [];\n const inverseOfRelations: [string, string][] = [];\n const impliesRelations: [string, string][] = [];\n\n for (const relation of ontology) {\n const fromName = getKindName(relation.from);\n const toName = getKindName(relation.to);\n\n switch (relation.metaEdge.name) {\n case META_EDGE_SUB_CLASS_OF: {\n subClassRelations.push([fromName, toName]);\n break;\n }\n case META_EDGE_BROADER: {\n broaderRelations.push([fromName, toName]);\n break;\n }\n case META_EDGE_NARROWER: {\n // narrower is inverse of broader\n broaderRelations.push([toName, fromName]);\n break;\n }\n case META_EDGE_EQUIVALENT_TO:\n case META_EDGE_SAME_AS: {\n equivalentRelations.push([fromName, toName]);\n break;\n }\n case META_EDGE_DISJOINT_WITH: {\n disjointRelations.push([fromName, toName]);\n break;\n }\n case META_EDGE_PART_OF: {\n partOfRelations.push([fromName, toName]);\n break;\n }\n case META_EDGE_HAS_PART: {\n // hasPart is inverse of partOf\n partOfRelations.push([toName, fromName]);\n break;\n }\n case META_EDGE_INVERSE_OF: {\n // inverseOf is symmetric: if A inverseOf B, then B inverseOf A\n inverseOfRelations.push([fromName, toName]);\n break;\n }\n case META_EDGE_IMPLIES: {\n impliesRelations.push([fromName, toName]);\n break;\n }\n }\n }\n\n // Compute subClassOf closures\n const subClassAncestors = computeTransitiveClosure(subClassRelations);\n const subClassDescendants = invertClosure(subClassAncestors);\n\n // Compute broader/narrower closures\n const broaderClosure = computeTransitiveClosure(broaderRelations);\n const narrowerClosure = invertClosure(broaderClosure);\n\n // Compute equivalence sets and IRI mappings\n const equivalenceSets = computeEquivalenceSets(equivalentRelations);\n const iriToKind = computeIriMapping(equivalentRelations);\n\n // Compute disjoint pairs (normalize for symmetric lookup)\n const disjointPairs = computeDisjointPairs(disjointRelations);\n\n // Compute partOf closures\n const partOfClosure = computeTransitiveClosure(partOfRelations);\n const hasPartClosure = invertClosure(partOfClosure);\n\n // Compute edge inverses (symmetric: store both directions)\n const edgeInverses = computeEdgeInverses(inverseOfRelations);\n\n // Compute edge implications closure (transitive)\n // edgeImplicationsClosure: A -> [B, C] means A implies B and C\n // edgeImplyingClosure: C -> [A, B] means A and B imply C (inverse direction)\n const edgeImplicationsClosure = computeTransitiveClosure(impliesRelations);\n const edgeImplyingClosure = invertClosure(edgeImplicationsClosure);\n\n return {\n subClassAncestors,\n subClassDescendants,\n broaderClosure,\n narrowerClosure,\n equivalenceSets,\n iriToKind,\n disjointPairs,\n partOfClosure,\n hasPartClosure,\n edgeInverses,\n edgeImplicationsClosure,\n edgeImplyingClosure,\n };\n}\n\n/**\n * Gets the name from a NodeType, EdgeType, or string.\n */\nfunction getKindName(kindOrIri: NodeType | AnyEdgeType | string): string {\n if (typeof kindOrIri === \"string\") {\n return kindOrIri;\n }\n return kindOrIri.kind;\n}\n\n/**\n * Checks if a string is an external IRI (not a local kind name).\n */\nfunction isExternalIri(value: string): boolean {\n return value.startsWith(\"http://\") || value.startsWith(\"https://\");\n}\n\n/**\n * Computes equivalence sets (symmetric + transitive closure).\n */\nfunction computeEquivalenceSets(\n relations: readonly (readonly [string, string])[],\n): ReadonlyMap<string, ReadonlySet<string>> {\n // Use union-find to compute equivalence classes\n const parent = new Map<string, string>();\n\n function find(x: string): string {\n if (!parent.has(x)) {\n parent.set(x, x);\n return x;\n }\n // Safe: has() check above guarantees key exists\n const parentNode = parent.get(x)!;\n if (parentNode === x) return x;\n const root = find(parentNode);\n parent.set(x, root); // Path compression\n return root;\n }\n\n function union(a: string, b: string): void {\n const rootA = find(a);\n const rootB = find(b);\n if (rootA !== rootB) {\n parent.set(rootA, rootB);\n }\n }\n\n // Build equivalence classes\n for (const [a, b] of relations) {\n union(a, b);\n }\n\n // Collect all members of each equivalence class\n const classes = new Map<string, Set<string>>();\n for (const key of parent.keys()) {\n const root = find(key);\n const existing = classes.get(root) ?? new Set();\n existing.add(key);\n classes.set(root, existing);\n }\n\n // Build result: each node maps to its equivalence set\n const result = new Map<string, ReadonlySet<string>>();\n for (const members of classes.values()) {\n for (const member of members) {\n // Exclude self from equivalence set\n const others = new Set(members);\n others.delete(member);\n result.set(member, others);\n }\n }\n\n return result;\n}\n\n/**\n * Computes mapping from external IRIs to internal kind names.\n */\nfunction computeIriMapping(\n relations: readonly (readonly [string, string])[],\n): ReadonlyMap<string, string> {\n const result = new Map<string, string>();\n\n for (const [a, b] of relations) {\n // If one is an IRI and other is a kind name, map IRI → kind\n if (isExternalIri(a) && !isExternalIri(b)) {\n result.set(a, b);\n } else if (isExternalIri(b) && !isExternalIri(a)) {\n result.set(b, a);\n }\n }\n\n return result;\n}\n\n/**\n * Computes normalized disjoint pairs.\n */\nfunction computeDisjointPairs(\n relations: readonly (readonly [string, string])[],\n): ReadonlySet<string> {\n const result = new Set<string>();\n\n for (const [a, b] of relations) {\n // Normalize pair for consistent lookup\n const normalized = a < b ? `${a}|${b}` : `${b}|${a}`;\n result.add(normalized);\n }\n\n return result;\n}\n\n/**\n * Computes edge inverse mapping (symmetric: stores both directions).\n */\nfunction computeEdgeInverses(\n relations: readonly (readonly [string, string])[],\n): ReadonlyMap<string, string> {\n const result = new Map<string, string>();\n\n for (const [a, b] of relations) {\n // inverseOf is symmetric: A inverseOf B means B inverseOf A too\n result.set(a, b);\n result.set(b, a);\n }\n\n return result;\n}\n","/**\n * Schema serializer for homoiconic storage.\n *\n * Converts a GraphDef to a SerializedSchema for database storage.\n * Uses Zod's toJSONSchema() for property schema serialization.\n */\nimport { z } from \"zod\";\n\nimport {\n getEdgeKinds,\n getNodeKinds,\n type GraphDef,\n} from \"../core/define-graph\";\nimport {\n type EdgeRegistration,\n type KindAnnotations,\n type NodeRegistration,\n type NullCheckOp,\n type UniqueConstraint,\n} from \"../core/types\";\nimport {\n type GraphExtension,\n LEGACY_GRAPH_EXTENSION_VERSION,\n} from \"../graph-extension/extension-types\";\nimport {\n type EdgeIndexDeclaration,\n type IndexDeclaration,\n type NodeIndexDeclaration,\n type VectorIndexDeclaration,\n} from \"../indexes/types\";\nimport {\n getTypeName,\n type MetaEdge,\n type OntologyRelation,\n} from \"../ontology/types\";\nimport { computeClosuresFromOntology } from \"../registry/kind-registry\";\nimport { nowIso } from \"../utils/date\";\nimport { sha256Hex } from \"../utils/hash\";\nimport { sortedReplacer } from \"./canonical\";\nimport {\n type JsonSchema,\n type SchemaHash,\n type SerializedClosures,\n type SerializedEdgeDef,\n type SerializedMetaEdge,\n type SerializedNodeDef,\n type SerializedOntology,\n type SerializedOntologyRelation,\n type SerializedSchema,\n type SerializedUniqueConstraint,\n} from \"./types\";\n\n// ============================================================\n// Main Serialization\n// ============================================================\n\n/**\n * Serializes a GraphDef to a SerializedSchema.\n *\n * @param graph - The graph definition to serialize\n * @param version - The schema version number\n * @returns The serialized schema\n */\nexport function serializeSchema<G extends GraphDef>(\n graph: G,\n version: number,\n): SerializedSchema {\n const nodes = serializeNodes(graph);\n const edges = serializeEdges(graph);\n const ontology = serializeOntology(graph.ontology);\n const indexes = serializeIndexes(graph.indexes);\n const extension = canonicalExtension(graph.extension);\n const deprecatedKinds = serializeDeprecatedKinds(graph.deprecatedKinds);\n\n return {\n graphId: graph.id,\n version,\n generatedAt: nowIso(),\n nodes,\n edges,\n ontology,\n defaults: {\n onNodeDelete: graph.defaults.onNodeDelete,\n temporalMode: graph.defaults.temporalMode,\n },\n // `serializeIndexes` collapses both absent and empty inputs to\n // `undefined` (see the helper's docstring); omit the field entirely\n // in that case so legacy graphs hash byte-identically to the\n // pre-`indexes` form.\n ...(indexes === undefined ? {} : { indexes }),\n // The graph extension is the durable source the loader uses to\n // rebuild extension-kind Zod validators on restart. Omitted on\n // graphs that have never been extended so legacy schemas hash\n // byte-identically.\n ...(extension === undefined ? {} : { extension }),\n // Soft-deprecated kind names. Omitted when empty so legacy\n // schemas hash byte-identically; sorted for canonical-form\n // stability across insertion-order differences.\n ...(deprecatedKinds === undefined ? {} : { deprecatedKinds }),\n };\n}\n\nfunction serializeDeprecatedKinds(\n set: ReadonlySet<string> | undefined,\n): readonly string[] | undefined {\n if (set === undefined || set.size === 0) return undefined;\n return [...set].toSorted();\n}\n\n/**\n * Strips `version` from the persisted extension when it equals\n * the legacy default (a stable `1`). The version is metadata about\n * the document format, not semantic schema content; omitting the\n * default value from the canonical form means documents persisted\n * before the version field existed (no `version`) hash byte-identically\n * with documents persisted after (`version: 1`).\n *\n * Pinned to `LEGACY_GRAPH_EXTENSION_VERSION` rather than\n * `CURRENT_GRAPH_EXTENSION_VERSION` so future major bumps don't\n * silently re-classify already-stored documents — when v2 ships,\n * v1 documents continue to omit `version` (because `1 ===\n * LEGACY`), and v2 documents emit `version: 2` explicitly. The\n * canonical-form rule stays stable across library versions.\n */\nfunction canonicalExtension(\n document: GraphExtension | undefined,\n): GraphExtension | undefined {\n if (document === undefined) return undefined;\n if (document.version === undefined) return document;\n\n if (document.version !== LEGACY_GRAPH_EXTENSION_VERSION) return document;\n const { version: _omit, ...rest } = document;\n return rest;\n}\n\n/**\n * Annotations are omitted from the canonical form when absent OR\n * empty (`{}`). Mirrors the omit-when-empty rule applied to\n * `indexes` and `deprecatedKinds` so that legacy graphs without\n * annotations and graphs declaring `annotations: {}` hash\n * byte-identically.\n */\nfunction canonicalAnnotations(\n annotations: KindAnnotations | undefined,\n): KindAnnotations | undefined {\n if (annotations === undefined) return undefined;\n if (Object.keys(annotations).length === 0) return undefined;\n return annotations;\n}\n\n// ============================================================\n// Index Serialization\n// ============================================================\n\n/**\n * Returns the canonical-form `indexes` slice for the schema document, or\n * `undefined` when the input graph never declared the slice (so the\n * field is omitted entirely).\n *\n * Canonical-form rules (load-bearing for hash stability):\n * - `origin: \"compile-time\"` is the default and is omitted from the\n * serialized form. Only `origin: \"runtime\"` is emitted explicitly so\n * the loader can route the declaration through the runtime compiler on\n * restart.\n *\n * The slice is order-canonicalized (sorted by name) and collapses both\n * `undefined` and an empty array to \"no slice\" so the hash and the diff\n * agree: indexes are an unordered set keyed by name, and an empty list\n * carries no semantic meaning that an absent slice doesn't.\n */\nfunction serializeIndexes(\n indexes: readonly IndexDeclaration[] | undefined,\n): readonly IndexDeclaration[] | undefined {\n if (indexes === undefined || indexes.length === 0) return undefined;\n return indexes\n .toSorted((a, b) =>\n a.name < b.name ? -1\n : a.name > b.name ? 1\n : 0,\n )\n .map((index) => serializeIndexDeclaration(index));\n}\n\nfunction serializeIndexDeclaration(\n declaration: IndexDeclaration,\n): IndexDeclaration {\n if (declaration.entity === \"node\") {\n return serializeNodeIndexDeclaration(declaration);\n }\n if (declaration.entity === \"edge\") {\n return serializeEdgeIndexDeclaration(declaration);\n }\n return serializeVectorIndexDeclaration(declaration);\n}\n\nfunction serializeVectorIndexDeclaration(\n declaration: VectorIndexDeclaration,\n): VectorIndexDeclaration {\n return {\n entity: \"vector\",\n kind: declaration.kind,\n name: declaration.name,\n fieldPath: declaration.fieldPath,\n dimensions: declaration.dimensions,\n metric: declaration.metric,\n indexType: declaration.indexType,\n indexParams: declaration.indexParams,\n ...(declaration.origin === \"runtime\" ? { origin: \"runtime\" as const } : {}),\n };\n}\n\nfunction serializeNodeIndexDeclaration(\n declaration: NodeIndexDeclaration,\n): NodeIndexDeclaration {\n return {\n entity: \"node\",\n kind: declaration.kind,\n name: declaration.name,\n fields: declaration.fields,\n fieldValueTypes: declaration.fieldValueTypes,\n coveringFields: declaration.coveringFields,\n coveringFieldValueTypes: declaration.coveringFieldValueTypes,\n unique: declaration.unique,\n scope: declaration.scope,\n where: declaration.where,\n // `origin: \"compile-time\"` is the default and is omitted from the\n // canonical form (absence == compile-time). Only `runtime` is\n // emitted explicitly so the restart loader can route the declaration\n // through the runtime compiler.\n ...(declaration.origin === \"runtime\" ? { origin: \"runtime\" as const } : {}),\n };\n}\n\nfunction serializeEdgeIndexDeclaration(\n declaration: EdgeIndexDeclaration,\n): EdgeIndexDeclaration {\n return {\n entity: \"edge\",\n kind: declaration.kind,\n name: declaration.name,\n direction: declaration.direction,\n fields: declaration.fields,\n fieldValueTypes: declaration.fieldValueTypes,\n coveringFields: declaration.coveringFields,\n coveringFieldValueTypes: declaration.coveringFieldValueTypes,\n unique: declaration.unique,\n scope: declaration.scope,\n where: declaration.where,\n ...(declaration.origin === \"runtime\" ? { origin: \"runtime\" as const } : {}),\n };\n}\n\n// ============================================================\n// Node Serialization\n// ============================================================\n\n/**\n * Serializes all node definitions.\n */\nfunction serializeNodes<G extends GraphDef>(\n graph: G,\n): Record<string, SerializedNodeDef> {\n const result: Record<string, SerializedNodeDef> = {};\n\n for (const kindName of getNodeKinds(graph)) {\n const registration = graph.nodes[kindName];\n if (registration === undefined) continue;\n result[kindName] = serializeNodeDef(registration);\n }\n\n return result;\n}\n\n/**\n * Serializes a single node registration.\n */\nfunction serializeNodeDef(registration: NodeRegistration): SerializedNodeDef {\n const node = registration.type;\n const annotations = canonicalAnnotations(node.annotations);\n\n return {\n kind: node.kind,\n properties: serializeZodSchema(node.schema),\n uniqueConstraints: serializeUniqueConstraints(registration.unique ?? []),\n onDelete: registration.onDelete ?? \"restrict\",\n description: node.description,\n ...(annotations === undefined ? {} : { annotations }),\n };\n}\n\n/**\n * Serializes unique constraints.\n */\nfunction serializeUniqueConstraints(\n constraints: readonly UniqueConstraint[],\n): readonly SerializedUniqueConstraint[] {\n return constraints.map((constraint) => ({\n name: constraint.name,\n fields: [...constraint.fields],\n where:\n constraint.where ? serializeWherePredicate(constraint.where) : undefined,\n scope: constraint.scope,\n collation: constraint.collation,\n }));\n}\n\n/**\n * A serialized predicate structure (matches UniqueConstraintPredicate from core/types).\n */\ntype SerializedPredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: NullCheckOp;\n}>;\n\n/**\n * Field builder returned by the predicate proxy.\n */\ntype FieldPredicateBuilder = Readonly<{\n isNull: () => SerializedPredicate;\n isNotNull: () => SerializedPredicate;\n}>;\n\n/**\n * Predicate builder type for where clause serialization.\n */\ntype PredicateBuilder = Readonly<Record<string, FieldPredicateBuilder>>;\n\n/**\n * Serializes a where predicate function to a JSON-serializable structure.\n *\n * The where function is called with a proxy builder that captures the\n * field and operation, which can then be serialized and later deserialized.\n */\nfunction serializeWherePredicate(\n whereFunction: (builder: PredicateBuilder) => SerializedPredicate,\n): string {\n // Create a proxy builder that captures the predicate structure\n const builder = new Proxy(\n {},\n {\n get(_target, field: string): FieldPredicateBuilder {\n return {\n isNull: (): SerializedPredicate => ({\n __type: \"unique_predicate\",\n field,\n op: \"isNull\" as const,\n }),\n isNotNull: (): SerializedPredicate => ({\n __type: \"unique_predicate\",\n field,\n op: \"isNotNull\" as const,\n }),\n };\n },\n },\n );\n\n // Call the where function to get the predicate\n const predicate = whereFunction(builder);\n\n // Serialize the predicate structure as JSON\n return JSON.stringify({ field: predicate.field, op: predicate.op });\n}\n\n/**\n * Deserializes a where predicate JSON back to a predicate function.\n *\n * This can be used to reconstruct a UniqueConstraint's where clause\n * from a serialized schema.\n *\n * @param serialized - The JSON string from serialization\n * @returns A where function that returns the predicate structure\n */\n/**\n * Unique predicate result type.\n */\ntype UniquePredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: NullCheckOp;\n}>;\n\nexport function deserializeWherePredicate(\n serialized: string,\n): (builder: PredicateBuilder) => UniquePredicate {\n const parsed = JSON.parse(serialized) as {\n field: string;\n op: NullCheckOp;\n };\n\n return (builder: PredicateBuilder): UniquePredicate => {\n const fieldBuilder = builder[parsed.field];\n if (!fieldBuilder) {\n throw new Error(`Unknown field in where predicate: ${parsed.field}`);\n }\n\n const result =\n parsed.op === \"isNull\" ? fieldBuilder.isNull() : fieldBuilder.isNotNull();\n return {\n __type: \"unique_predicate\",\n field: result.field,\n op: result.op,\n };\n };\n}\n\n// ============================================================\n// Edge Serialization\n// ============================================================\n\n/**\n * Serializes all edge definitions.\n */\nfunction serializeEdges<G extends GraphDef>(\n graph: G,\n): Record<string, SerializedEdgeDef> {\n const result: Record<string, SerializedEdgeDef> = {};\n\n for (const kindName of getEdgeKinds(graph)) {\n const registration = graph.edges[kindName];\n if (registration === undefined) continue;\n result[kindName] = serializeEdgeDef(registration);\n }\n\n return result;\n}\n\n/**\n * Serializes a single edge registration.\n */\nfunction serializeEdgeDef(registration: EdgeRegistration): SerializedEdgeDef {\n const edge = registration.type;\n const annotations = canonicalAnnotations(edge.annotations);\n\n return {\n kind: edge.kind,\n fromKinds: registration.from.map((node) => node.kind),\n toKinds: registration.to.map((node) => node.kind),\n properties: serializeZodSchema(edge.schema),\n cardinality: registration.cardinality ?? \"many\",\n endpointExistence: registration.endpointExistence ?? \"notDeleted\",\n description: edge.description,\n ...(annotations === undefined ? {} : { annotations }),\n };\n}\n\n// ============================================================\n// Ontology Serialization\n// ============================================================\n\n/**\n * Serializes the complete ontology.\n */\nfunction serializeOntology(\n relations: readonly OntologyRelation[],\n): SerializedOntology {\n // Collect unique meta-edges\n const metaEdgeMap = new Map<string, MetaEdge>();\n for (const relation of relations) {\n const metaEdge = relation.metaEdge;\n if (!metaEdgeMap.has(metaEdge.name)) {\n metaEdgeMap.set(metaEdge.name, metaEdge);\n }\n }\n\n // Serialize meta-edges\n const metaEdges: Record<string, SerializedMetaEdge> = {};\n for (const [name, metaEdge] of metaEdgeMap) {\n metaEdges[name] = serializeMetaEdge(metaEdge);\n }\n\n // Serialize relations\n const serializedRelations = relations.map((relation) =>\n serializeOntologyRelation(relation),\n );\n\n // Compute and serialize closures\n const closures = serializeClosures(relations);\n\n return {\n metaEdges,\n relations: serializedRelations,\n closures,\n };\n}\n\n/**\n * Serializes a meta-edge.\n */\nfunction serializeMetaEdge(metaEdge: MetaEdge): SerializedMetaEdge {\n return {\n name: metaEdge.name,\n transitive: metaEdge.properties.transitive,\n symmetric: metaEdge.properties.symmetric,\n reflexive: metaEdge.properties.reflexive,\n inverse: metaEdge.properties.inverse,\n inference: metaEdge.properties.inference,\n description: metaEdge.properties.description,\n };\n}\n\n/**\n * Serializes an ontology relation.\n */\nfunction serializeOntologyRelation(\n relation: OntologyRelation,\n): SerializedOntologyRelation {\n return {\n metaEdge: relation.metaEdge.name,\n from: getTypeName(relation.from),\n to: getTypeName(relation.to),\n };\n}\n\n/**\n * Serializes precomputed closures.\n */\nfunction serializeClosures(\n relations: readonly OntologyRelation[],\n): SerializedClosures {\n if (relations.length === 0) {\n return {\n subClassAncestors: {},\n subClassDescendants: {},\n broaderClosure: {},\n narrowerClosure: {},\n equivalenceSets: {},\n disjointPairs: [],\n partOfClosure: {},\n hasPartClosure: {},\n iriToKind: {},\n edgeInverses: {},\n edgeImplicationsClosure: {},\n edgeImplyingClosure: {},\n };\n }\n\n const computed = computeClosuresFromOntology(relations);\n\n return {\n subClassAncestors: mapToRecord(computed.subClassAncestors),\n subClassDescendants: mapToRecord(computed.subClassDescendants),\n broaderClosure: mapToRecord(computed.broaderClosure),\n narrowerClosure: mapToRecord(computed.narrowerClosure),\n equivalenceSets: mapToRecord(computed.equivalenceSets),\n disjointPairs: [...computed.disjointPairs],\n partOfClosure: mapToRecord(computed.partOfClosure),\n hasPartClosure: mapToRecord(computed.hasPartClosure),\n iriToKind: mapToSimpleRecord(computed.iriToKind),\n edgeInverses: mapToSimpleRecord(computed.edgeInverses),\n edgeImplicationsClosure: mapToRecord(computed.edgeImplicationsClosure),\n edgeImplyingClosure: mapToRecord(computed.edgeImplyingClosure),\n };\n}\n\n/**\n * Converts a Map<string, Set<string>> to Record<string, string[]>.\n */\nfunction mapToRecord(\n map: ReadonlyMap<string, ReadonlySet<string>>,\n): Record<string, readonly string[]> {\n const result: Record<string, readonly string[]> = {};\n for (const [key, values] of map) {\n result[key] = [...values];\n }\n return result;\n}\n\n/**\n * Converts a Map<string, string> to Record<string, string>.\n */\nfunction mapToSimpleRecord(\n map: ReadonlyMap<string, string>,\n): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [key, value] of map) {\n result[key] = value;\n }\n return result;\n}\n\n// ============================================================\n// Zod Schema Serialization\n// ============================================================\n\n/**\n * Memoizes `z.toJSONSchema` results keyed by Zod schema identity.\n * `z.toJSONSchema` walks the entire schema tree on every call;\n * `Store.introspect()` and any poll-driven UI built on top of it\n * runs the conversion per kind per call. Schemas are immutable for\n * the lifetime of a `NodeType` / `EdgeType`, so the cache is sound;\n * `WeakMap` follows the schema's lifetime so there's no memory leak\n * when the registry is rebuilt by `evolve` / `removeKinds` /\n * `deprecateKinds` (the old registry's schemas are unreferenced and\n * the cache entries become eligible for GC alongside them).\n */\nconst SCHEMA_PROPERTIES_CACHE = new WeakMap<z.ZodType, JsonSchema>();\n\n/**\n * Serializes a Zod schema to JSON Schema. Memoized — repeated calls\n * with the same schema reference return the cached output without\n * re-walking the tree.\n *\n * Uses Zod 4's toJSONSchema() method for conversion. Re-exported for\n * `store.introspect()` so the in-memory graph can produce the same\n * JSON-Schema view of properties that the persisted form carries.\n */\nexport function serializeSchemaProperties(schema: z.ZodType): JsonSchema {\n const cached = SCHEMA_PROPERTIES_CACHE.get(schema);\n if (cached !== undefined) return cached;\n const computed = serializeZodSchema(schema);\n SCHEMA_PROPERTIES_CACHE.set(schema, computed);\n return computed;\n}\n\nfunction serializeZodSchema(schema: z.ZodType): JsonSchema {\n try {\n // Zod 4 has toJSONSchema as a standard export\n const jsonSchema = z.toJSONSchema(schema);\n return jsonSchema as JsonSchema;\n } catch {\n // Fallback for schemas that can't be converted\n return { type: \"object\" };\n }\n}\n\n// ============================================================\n// Schema Hashing\n// ============================================================\n\n/**\n * Per-graph schema-hash cache. Keyed on the frozen `GraphDef` reference\n * (identity-stable across calls because `defineGraph` freezes its\n * output). Inner Map carries one entry per `version` ever computed for\n * that graph — typically 1-2 entries per graph (current + next-pending).\n *\n * Cache hit skips both `serializeSchema` (the per-kind walk is cached\n * separately by `SCHEMA_PROPERTIES_CACHE`, but the top-level assembly +\n * `JSON.stringify(sortedReplacer)` walk is not) and the SHA-256 hash —\n * the dominant cost on `ensureSchema` boots that observe an unchanged\n * schema. The cache lives on a `WeakMap` so retired graphs (after\n * `evolve`/`removeKinds` produce a new one) become eligible for GC\n * alongside their entries.\n */\nconst SCHEMA_HASH_CACHE = new WeakMap<GraphDef, Map<number, SchemaHash>>();\n\n/**\n * Cached `(graph, version) → SchemaHash` lookup. Use this when the hash\n * is the only thing the caller needs (the most common case in\n * `ensureSchema`'s \"are we up to date?\" path). On cache miss, this\n * serializes and hashes once, populates the cache, and returns.\n */\nexport async function getSchemaHash(\n graph: GraphDef,\n version: number,\n): Promise<SchemaHash> {\n const perGraph = SCHEMA_HASH_CACHE.get(graph);\n const cached = perGraph?.get(version);\n if (cached !== undefined) return cached;\n const hash = await computeSchemaHash(serializeSchema(graph, version));\n if (perGraph === undefined) {\n SCHEMA_HASH_CACHE.set(graph, new Map([[version, hash]]));\n } else {\n perGraph.set(version, hash);\n }\n return hash;\n}\n\n/**\n * Computes a hash of the schema content for change detection.\n *\n * Excludes version and generatedAt since those change on every save.\n */\nexport async function computeSchemaHash(\n schema: SerializedSchema,\n): Promise<SchemaHash> {\n // Create a hashable representation excluding dynamic fields\n // (version, generatedAt). Optional slices are included only when\n // set so legacy schemas without them hash byte-identically — the\n // per-slice canonical-form rules (e.g., `indexes` sort + origin\n // omission, `deprecatedKinds` sort) are applied at serialize time.\n const hashable = {\n graphId: schema.graphId,\n nodes: schema.nodes,\n edges: schema.edges,\n ontology: schema.ontology,\n defaults: schema.defaults,\n ...(schema.indexes === undefined ? {} : { indexes: schema.indexes }),\n ...(schema.extension === undefined ? {} : { extension: schema.extension }),\n ...(schema.deprecatedKinds === undefined ?\n {}\n : { deprecatedKinds: schema.deprecatedKinds }),\n };\n\n // Serialize with sorted keys for deterministic output\n const json = JSON.stringify(hashable, sortedReplacer);\n return sha256Hex(json);\n}\n","/**\n * One-way compiler from a validated `GraphExtension` to Zod-bearing\n * `NodeType` / `EdgeType` / `OntologyRelation` values.\n *\n * The output is structurally indistinguishable from equivalent\n * compile-time `defineNode` / `defineEdge` declarations: `searchable()`\n * and `embedding()` wrappers are reapplied so introspection helpers see\n * the same metadata, optional properties use the standard `.optional()`\n * chain, and unique-constraint `where` callbacks return the predicate\n * shape `serializeWherePredicate` consumes.\n */\nimport { z, type ZodObject, type ZodRawShape, type ZodType } from \"zod\";\n\nimport { embedding } from \"../core/embedding\";\nimport { defineNode } from \"../core/node\";\nimport { searchable } from \"../core/searchable\";\nimport {\n type KindAnnotations,\n type NodeType,\n type NullCheckOp,\n type UniqueConstraint,\n} from \"../core/types\";\nimport { ALL_META_EDGE_NAMES, type MetaEdgeName } from \"../ontology/constants\";\nimport { core as coreOntology } from \"../ontology/core-meta-edges\";\nimport { type MetaEdge, type OntologyRelation } from \"../ontology/types\";\nimport { compactUndefined } from \"../utils/object\";\nimport {\n type ExtensionArrayItemType,\n type ExtensionArrayProperty,\n type ExtensionEdgeDef,\n type ExtensionEnumProperty,\n type ExtensionIndex,\n type ExtensionNodeDef,\n type ExtensionNumberProperty,\n type ExtensionObjectProperty,\n type ExtensionOntologyRelation,\n type ExtensionPropertyType,\n type ExtensionStringProperty,\n type ExtensionUniqueConstraint,\n type GraphExtension,\n} from \"./extension-types\";\n\n// ============================================================\n// Public types\n// ============================================================\n\n/**\n * Compiled output of a graph-extension document, ready to merge into a\n * host `GraphDef`. Each `OntologyRelation`'s `from` / `to` is a `NodeType`\n * when the document name matches a declared kind, or the raw string\n * (treated as an external IRI by downstream code) otherwise.\n *\n * `indexes` are pass-through document entries — their final\n * `IndexDeclaration` shape requires Zod-introspection of the target\n * kind's schema, which depends on cross-graph kind resolution that\n * only the host-graph merge step has full information about. The\n * compiler validates the document; the merge resolves the kind\n * reference and calls the appropriate `defineNodeIndex` /\n * `defineEdgeIndex`.\n */\ntype CompiledExtension = Readonly<{\n nodes: readonly CompiledNode[];\n edges: readonly CompiledEdge[];\n ontology: readonly OntologyRelation[];\n indexes: readonly ExtensionIndex[];\n}>;\n\ntype CompiledNode = Readonly<{\n type: NodeType;\n unique: readonly UniqueConstraint[];\n}>;\n\n/**\n * Compiled edge — schema and metadata, with raw endpoints. `from` / `to`\n * each carry one entry per endpoint name from the document: a\n * `NodeType` when the name resolves to a kind declared in this same\n * extension, or the raw string otherwise. Unresolved strings are\n * preserved (not dropped) so the host-graph merge step can resolve them\n * against compile-time kinds or treat them as external IRIs.\n *\n * The compiler does NOT build an `EdgeType` here — that needs the full\n * cross-graph endpoint resolution and is built once at merge time.\n * The earlier \"build a throwaway EdgeType, then rebuild at merge\"\n * pattern was unnecessary work and required a parallel\n * `resolvedFrom` / `resolvedTo` filtered copy.\n */\ntype CompiledEdge = Readonly<{\n kindName: string;\n schema: ZodObject<ZodRawShape>;\n description?: string;\n annotations?: KindAnnotations;\n from: readonly (NodeType | string)[];\n to: readonly (NodeType | string)[];\n}>;\n\n// ============================================================\n// Compilation entry point\n// ============================================================\n\n/**\n * Per-kind compile caches. Validated `ExtensionNodeDef` /\n * `ExtensionEdgeDef` values are frozen by the validator, so identical\n * unchanged kinds flow through `unionDocuments` with stable references.\n * The outer `Map<kindName, ...>` exists because the same doc reference\n * could in principle appear under a different kindName across calls\n * (rare, but the kindName is bound into `defineNode`'s output, so\n * cache identity needs both); the inner `WeakMap` lets entries GC when\n * the doc itself is dropped.\n *\n * Hits the \"evolve, then evolve again with one kind added\" pattern,\n * where N-1 kinds in the union are reference-identical to the\n * prior call's compiled output.\n */\nconst COMPILE_NODE_CACHE = new Map<\n string,\n WeakMap<ExtensionNodeDef, CompiledNode>\n>();\nconst COMPILE_EDGE_SCHEMA_CACHE = new WeakMap<\n ExtensionEdgeDef,\n ZodObject<ZodRawShape>\n>();\n\n/**\n * Compiles a validated graph-extension document into Zod-bearing kinds.\n *\n * Pure function with no I/O. Assumes the input has already passed\n * `validateGraphExtension(...)` — invariant violations (e.g. unknown\n * meta-edge name) are programming bugs and surface as plain `Error`s.\n */\nexport function compileGraphExtension(\n document: GraphExtension,\n): CompiledExtension {\n const nodes: CompiledNode[] = [];\n const nodeTypeByName = new Map<string, NodeType>();\n\n for (const [kindName, nodeDocument] of Object.entries(document.nodes ?? {})) {\n const compiled = compileNodeCached(kindName, nodeDocument);\n nodes.push(compiled);\n nodeTypeByName.set(kindName, compiled.type);\n }\n\n const edges: CompiledEdge[] = [];\n for (const [kindName, edgeDocument] of Object.entries(document.edges ?? {})) {\n const compiled = compileEdge(kindName, edgeDocument, nodeTypeByName);\n edges.push(compiled);\n }\n\n const ontology: OntologyRelation[] = [];\n for (const relation of document.ontology ?? []) {\n ontology.push(compileOntologyRelation(relation, nodeTypeByName));\n }\n\n return Object.freeze({\n nodes: Object.freeze(nodes),\n edges: Object.freeze(edges),\n ontology: Object.freeze(ontology),\n // Indexes pass through — the merge step resolves the kind name\n // against graph-extension-or-compile-time NodeType / EdgeType and builds\n // the final `IndexDeclaration` via `defineNodeIndex` /\n // `defineEdgeIndex`.\n indexes: Object.freeze([...(document.indexes ?? [])]),\n });\n}\n\n// ============================================================\n// Node compilation\n// ============================================================\n\nfunction compileNodeCached(\n kindName: string,\n document: ExtensionNodeDef,\n): CompiledNode {\n const perName = COMPILE_NODE_CACHE.get(kindName);\n const cached = perName?.get(document);\n if (cached !== undefined) return cached;\n const computed = compileNode(kindName, document);\n if (perName === undefined) {\n COMPILE_NODE_CACHE.set(kindName, new WeakMap([[document, computed]]));\n } else {\n perName.set(document, computed);\n }\n return computed;\n}\n\nfunction compileNode(\n kindName: string,\n document: ExtensionNodeDef,\n): CompiledNode {\n const schema = buildObjectSchema(document.properties);\n\n const type = defineNode(\n kindName,\n compactUndefined({\n schema,\n description: document.description,\n annotations: document.annotations,\n }),\n );\n\n const unique = (document.unique ?? []).map((constraint) =>\n compileUniqueConstraint(constraint),\n );\n\n return Object.freeze({ type, unique: Object.freeze(unique) });\n}\n\n// ============================================================\n// Edge compilation\n// ============================================================\n\nfunction compileEdge(\n kindName: string,\n document: ExtensionEdgeDef,\n nodeTypeByName: ReadonlyMap<string, NodeType>,\n): CompiledEdge {\n // The schema-build step is the expensive part of edge compilation\n // (the resolved-endpoint arrays are O(N) string lookups); cache it\n // per-document so unchanged edges across evolves skip the rebuild.\n // The from/to resolution can't be cached at this level because it\n // depends on the per-call `nodeTypeByName`.\n let schema = COMPILE_EDGE_SCHEMA_CACHE.get(document);\n if (schema === undefined) {\n schema = buildObjectSchema(document.properties ?? {});\n COMPILE_EDGE_SCHEMA_CACHE.set(document, schema);\n }\n\n const from = document.from.map(\n (name): NodeType | string => nodeTypeByName.get(name) ?? name,\n );\n const to = document.to.map(\n (name): NodeType | string => nodeTypeByName.get(name) ?? name,\n );\n\n return Object.freeze(\n compactUndefined<CompiledEdge>({\n kindName,\n schema,\n description: document.description,\n annotations: document.annotations,\n from: Object.freeze(from),\n to: Object.freeze(to),\n }),\n );\n}\n\nfunction buildObjectSchema(\n properties: Readonly<Record<string, ExtensionPropertyType>>,\n): ZodObject<ZodRawShape> {\n const shape: Record<string, ZodType> = {};\n for (const [propertyName, propertyType] of Object.entries(properties)) {\n shape[propertyName] = applyOptional(\n compileProperty(propertyType),\n propertyType,\n );\n }\n return z.object(shape);\n}\n\n// ============================================================\n// Property compilation (ExtensionPropertyType -> z.ZodType)\n// ============================================================\n\nfunction compileProperty(property: ExtensionPropertyType): ZodType {\n switch (property.type) {\n case \"string\": {\n return compileStringProperty(property);\n }\n case \"number\": {\n return compileNumberProperty(property);\n }\n case \"boolean\": {\n return z.boolean();\n }\n case \"enum\": {\n return compileEnumProperty(property);\n }\n case \"array\": {\n return compileArrayProperty(property);\n }\n case \"object\": {\n return compileObjectProperty(property);\n }\n }\n}\n\nfunction compileStringProperty(property: ExtensionStringProperty): ZodType {\n // `searchable` and `format` are mutually exclusive (rejected by\n // validation): the format-routed schemas aren't `z.ZodString`\n // subclasses we can chain `searchable()` through.\n if (property.searchable !== undefined) {\n return applyStringRefinements(searchable(property.searchable), property);\n }\n if (property.format === undefined) {\n return applyStringRefinements(z.string(), property);\n }\n switch (property.format) {\n case \"datetime\": {\n return z.iso.datetime();\n }\n case \"date\": {\n return z.iso.date();\n }\n case \"uri\": {\n return z.url();\n }\n case \"email\": {\n return z.email();\n }\n case \"uuid\": {\n return z.uuid();\n }\n }\n}\n\nfunction applyStringRefinements(\n base: z.ZodString,\n property: ExtensionStringProperty,\n): z.ZodString {\n let schema = base;\n if (property.minLength !== undefined) schema = schema.min(property.minLength);\n if (property.maxLength !== undefined) schema = schema.max(property.maxLength);\n if (property.pattern !== undefined) {\n schema = schema.regex(new RegExp(property.pattern));\n }\n return schema;\n}\n\nfunction compileNumberProperty(property: ExtensionNumberProperty): ZodType {\n let schema: z.ZodNumber = z.number();\n if (property.int === true) {\n schema = schema.int();\n }\n if (property.min !== undefined) {\n schema = schema.min(property.min);\n }\n if (property.max !== undefined) {\n schema = schema.max(property.max);\n }\n return schema;\n}\n\nfunction compileEnumProperty(property: ExtensionEnumProperty): ZodType {\n // `z.enum([...])` requires at least one value; validation guarantees\n // this. The cast quiets the readonly-tuple check Zod's overload uses.\n return z.enum(property.values as unknown as [string, ...string[]]);\n}\n\nfunction compileArrayProperty(property: ExtensionArrayProperty): ZodType {\n if (property.embedding !== undefined) {\n // The embedding modifier replaces the ordinary `z.array(z.number())`\n // with the branded `embedding(dimensions)` schema so downstream\n // vector-search code recognises it via `getEmbeddingDimensions`.\n return embedding(property.embedding.dimensions);\n }\n const inner = compilePropertyForArrayItem(property.items);\n return z.array(inner);\n}\n\nfunction compilePropertyForArrayItem(item: ExtensionArrayItemType): ZodType {\n return applyOptional(compileProperty(item), item);\n}\n\nfunction compileObjectProperty(property: ExtensionObjectProperty): ZodType {\n return buildObjectSchema(property.properties);\n}\n\nfunction applyOptional(\n schema: ZodType,\n property: { optional?: boolean },\n): ZodType {\n return property.optional === true ? schema.optional() : schema;\n}\n\n// ============================================================\n// Unique constraint compilation\n// ============================================================\n\nfunction compileUniqueConstraint(\n document: ExtensionUniqueConstraint,\n): UniqueConstraint {\n const base = {\n name: document.name,\n fields: document.fields,\n scope: document.scope ?? \"kind\",\n collation: document.collation ?? \"binary\",\n };\n if (document.where === undefined) {\n return base;\n }\n return {\n ...base,\n where: makeWherePredicate(document.where.field, document.where.op),\n };\n}\n\n/**\n * One-arg field-builder shape consumers pass into `where`. Exposed as\n * its own type so the predicate factory can be typed without leaking\n * the internal predicate-builder generic from `core/types.ts`.\n */\ntype UniquePredicateFieldBuilder = Readonly<{\n isNull: () => unknown;\n isNotNull: () => unknown;\n}>;\n\ntype UniqueWhereCallback = (\n props: Readonly<Record<string, UniquePredicateFieldBuilder>>,\n) => Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: NullCheckOp;\n}>;\n\n/**\n * Builds the `where` callback `defineGraph`'s constraint plumbing\n * expects. The callback receives a per-field predicate builder and must\n * return `{ __type: \"unique_predicate\", field, op }`. Mirrors the shape\n * `serializeWherePredicate` walks at persistence time.\n */\nfunction makeWherePredicate(\n field: string,\n op: NullCheckOp,\n): UniqueWhereCallback {\n return (props) => {\n const builder = props[field];\n if (builder === undefined) {\n // The runtime predicate object is the source of truth — even if the\n // builder is missing (which validation should have prevented) the\n // returned shape matches what consumers and serialization expect.\n return { __type: \"unique_predicate\", field, op };\n }\n const result = op === \"isNull\" ? builder.isNull() : builder.isNotNull();\n return result as ReturnType<UniqueWhereCallback>;\n };\n}\n\n// ============================================================\n// Ontology compilation\n// ============================================================\n\nconst META_EDGE_BY_NAME: Readonly<Record<MetaEdgeName, MetaEdge>> =\n Object.fromEntries(\n ALL_META_EDGE_NAMES.map((name) => [name, coreOntology[`${name}MetaEdge`]]),\n ) as Readonly<Record<MetaEdgeName, MetaEdge>>;\n\nfunction compileOntologyRelation(\n relation: ExtensionOntologyRelation,\n nodeTypeByName: ReadonlyMap<string, NodeType>,\n): OntologyRelation {\n // `relation.metaEdge` is typed as `MetaEdgeName` so the lookup is\n // total. Validation rejects out-of-range names before they ever\n // reach the compiler.\n const metaEdge = META_EDGE_BY_NAME[relation.metaEdge];\n\n const fromNode = nodeTypeByName.get(relation.from);\n const toNode = nodeTypeByName.get(relation.to);\n\n // Mirror the `OntologyRelation` shape used by compile-time relation\n // factories: NodeType references when resolvable, raw string for\n // external IRIs.\n return {\n metaEdge,\n from: fromNode ?? relation.from,\n to: toNode ?? relation.to,\n };\n}\n","/**\n * Canonical-key encoding for ontology relations across the graph-extension\n * layer.\n *\n * The graph-extension side stores `(metaEdge, from, to)` triples on the\n * pure-value `ExtensionOntologyRelation`; the compile-time side stores\n * `OntologyRelation` with a `MetaEdge` value, a `NodeType | string`\n * `from`, and a `NodeType | string` `to`. Three distinct call sites\n * (`graph-extension/merge.ts`, `graph-extension/remove.ts`, `store/introspect.ts`)\n * need a single canonical-string key that compares the two sides for\n * \"is this compile-time relation also in the graph-extension document?\". One\n * encoding here keeps the four sites from drifting apart.\n */\nimport { getTypeName, type OntologyRelation } from \"../ontology/types\";\nimport {\n type ExtensionOntologyRelation,\n type GraphExtension,\n} from \"./extension-types\";\n\nexport function graphExtensionOntologyKey(\n entry: ExtensionOntologyRelation,\n): string {\n return `${entry.metaEdge}|${entry.from}|${entry.to}`;\n}\n\nexport function compileTimeOntologyKey(relation: OntologyRelation): string {\n return `${relation.metaEdge.name}|${getTypeName(relation.from)}|${getTypeName(relation.to)}`;\n}\n\n/**\n * Builds the set of `graphExtensionOntologyKey(...)` values for a\n * graph-extension document's ontology relations. Used to filter\n * compile-time relations away from graph-extension ones in merge /\n * introspect / remove flows.\n */\nexport function buildGraphExtensionOntologyKeySet(\n document: GraphExtension | undefined,\n): ReadonlySet<string> {\n return new Set(\n (document?.ontology ?? []).map((entry) => graphExtensionOntologyKey(entry)),\n );\n}\n\n/**\n * Sets of node and edge kind names declared in the extension document.\n * Consumers use these to distinguish runtime-origin kinds from\n * compile-time ones — re-applying the same runtime kind is a noop, not\n * a collision; removing a runtime kind partitions the merged graph\n * differently from removing a compile-time one. Used by `merge.ts`,\n * `remove.ts`, and `store/introspect.ts`.\n */\nexport function extensionKindNames(\n document: GraphExtension | undefined,\n): Readonly<{ nodes: ReadonlySet<string>; edges: ReadonlySet<string> }> {\n return {\n nodes: new Set(Object.keys(document?.nodes ?? {})),\n edges: new Set(Object.keys(document?.edges ?? {})),\n };\n}\n","import { type GraphDef } from \"../core/define-graph\";\nimport { defineEdge } from \"../core/edge\";\nimport {\n type AnyEdgeType,\n type EdgeRegistration,\n type EdgeType,\n type KindEntity,\n type NodeRegistration,\n type NodeType,\n} from \"../core/types\";\nimport { ConfigurationError, KindNotFoundError } from \"../errors\";\nimport {\n autoDeriveVectorIndexes,\n mergeVectorIndexes,\n} from \"../indexes/auto-derive\";\nimport { defineEdgeIndex, defineNodeIndex } from \"../indexes/define-index\";\nimport {\n type EdgeIndexConfig,\n type IndexDeclaration,\n type NodeIndexConfig,\n type VectorIndexDeclaration,\n} from \"../indexes/types\";\nimport { type OntologyRelation } from \"../ontology/types\";\nimport { canonicalEqual } from \"../schema/canonical\";\nimport { compactUndefined } from \"../utils/object\";\nimport { unwrap } from \"../utils/result\";\nimport { compileGraphExtension } from \"./compiler\";\nimport {\n GraphExtensionUnresolvedEndpointError,\n KindCollisionError,\n} from \"./errors\";\nimport { type ExtensionIndex, type GraphExtension } from \"./extension-types\";\nimport {\n buildGraphExtensionOntologyKeySet,\n compileTimeOntologyKey,\n extensionKindNames,\n graphExtensionOntologyKey,\n} from \"./ontology-keys\";\nimport { validateGraphExtension } from \"./validation\";\n\n/**\n * Compiles a graph extension and merges the result into a host\n * `GraphDef`. The merge is **additive over the canonical extension**:\n *\n * - New kinds, new edges referencing existing kinds (compile-time or\n * extension), and new ontology relations are allowed.\n * - Re-declaring an existing extension kind with the **same shape** is a\n * no-op (the idempotent re-evolve hot path).\n * - Re-declaring an existing extension kind with a **narrowing change**\n * that existing rows can't satisfy is classified at the call site\n * (`Store.evolve` / `Store.removeKinds`) and surfaces as\n * `IncompatibleChangeError`. v1 supports a curated allowed set of\n * additive modifications; everything else gets rejected.\n * - Collisions with **compile-time** kinds (any name reuse) throw\n * `KindCollisionError` (code `KIND_COLLISION`).\n * - Edge endpoints that don't resolve against either the extension\n * or the host graph throw `GraphExtensionUnresolvedEndpointError`\n * (code `GRAPH_EXTENSION_UNRESOLVED_ENDPOINT`) — the startup-conflict\n * case for stale persisted extensions.\n *\n * The returned graph carries the union of the host's existing\n * `extension` and the new extension, so re-serialization is\n * stable across restarts. When the union is structurally equal to the\n * existing document, the host graph is returned unchanged so no-op\n * evolves skip the compile + filter + merge work entirely.\n *\n * Validates the merged union before compiling — every load path goes\n * through here, so persisted documents that drift from the v1 subset\n * surface as `GraphExtensionValidationError` rather than raw compiler\n * crashes. Callers that want input-only error precision (e.g. the\n * `defineGraphExtension` authoring path) call `validateGraphExtension`\n * themselves first; the merge runs the validator only against the\n * union so a single walk covers both cross-document invariants and the\n * input's own shape.\n */\nexport function mergeGraphExtension<G extends GraphDef>(\n graph: G,\n document: GraphExtension,\n): G {\n const existingDocument: GraphExtension = graph.extension ?? Object.freeze({});\n\n // Modification compatibility (REMOVE_PROPERTY, TYPE_CHANGE,\n // ADD_REQUIRED_PROPERTY on populated kinds, etc.) is classified\n // and rejected at the call site (`Store.evolve` / `Store.removeKinds`)\n // because the empty-kind probes that promote allowed-on-empty\n // deltas to allowed need backend access. The merge itself just\n // unions the documents — same-shape re-evolves collapse via the\n // canonicalEqual short-circuit below; truly incompatible deltas\n // would never reach the merge in production code paths.\n\n const unionDocument = unionDocuments(existingDocument, document);\n\n // Fast path: when the union is structurally equal to the existing\n // graph-extension document (the \"I evolved with the same extension\n // again\" case, plus any subset-of-existing case), there's\n // no work to do. The existing document was already validated by the\n // upstream merge that installed it, so we skip the validation walk\n // (which would otherwise repeat the 2200-line validator over a\n // known-good document) AND the compile + filter pipeline.\n if (\n graph.extension !== undefined &&\n canonicalEqual(unionDocument, existingDocument)\n ) {\n return graph;\n }\n\n // Single validate covers both the input's shape and cross-document\n // invariants (ontology cycles, index-name uniqueness across docs,\n // etc.). The input doc's invariants are a subset of the union's, so\n // bad input still surfaces here — error paths just refer to union\n // pointers rather than input pointers. Callers wanting input-precise\n // errors call `validateGraphExtension(document)` themselves first.\n const validatedUnion = unwrap(validateGraphExtension(unionDocument));\n\n const compiled = compileGraphExtension(validatedUnion);\n\n // Existing runtime-origin kind names — these aren't compile-time\n // collisions when re-applied, so we skip the collision check for them\n // and let the union document overwrite the previous compiled form.\n const { nodes: runtimeNodeNames, edges: runtimeEdgeNames } =\n extensionKindNames(existingDocument);\n\n const nodeKinds = new Map<string, NodeType>();\n for (const registration of Object.values(graph.nodes)) {\n if (runtimeNodeNames.has(registration.type.kind)) continue;\n nodeKinds.set(registration.type.kind, registration.type);\n }\n for (const node of compiled.nodes) {\n assertNoCollision(\n node.type.kind,\n \"node\",\n nodeKinds.has(node.type.kind),\n graph.id,\n );\n nodeKinds.set(node.type.kind, node.type);\n }\n\n const mergedNodes: Record<string, NodeRegistration> = {};\n for (const [name, registration] of Object.entries(graph.nodes)) {\n if (runtimeNodeNames.has(name)) continue;\n mergedNodes[name] = registration;\n }\n for (const node of compiled.nodes) {\n mergedNodes[node.type.kind] = {\n type: node.type,\n ...(node.unique.length === 0 ? {} : { unique: [...node.unique] }),\n };\n }\n\n const mergedEdges: Record<string, EdgeRegistration> = {};\n for (const [name, registration] of Object.entries(graph.edges)) {\n if (runtimeEdgeNames.has(name)) continue;\n mergedEdges[name] = registration;\n }\n for (const edge of compiled.edges) {\n assertNoCollision(\n edge.kindName,\n \"edge\",\n mergedEdges[edge.kindName] !== undefined,\n graph.id,\n );\n const from = resolveEndpoints(edge.from, nodeKinds, {\n graphId: graph.id,\n edgeKind: edge.kindName,\n side: \"from\",\n });\n const to = resolveEndpoints(edge.to, nodeKinds, {\n graphId: graph.id,\n edgeKind: edge.kindName,\n side: \"to\",\n });\n // Build the EdgeType once with the cross-graph-resolved endpoints.\n // The compiler intentionally doesn't construct an EdgeType — its\n // view is graph-extension-only, so endpoint resolution against\n // compile-time host kinds isn't possible there.\n const type = defineEdge(\n edge.kindName,\n compactUndefined({\n schema: edge.schema,\n description: edge.description,\n annotations: edge.annotations,\n from,\n to,\n }),\n ) as unknown as EdgeType;\n mergedEdges[edge.kindName] = { type, from, to };\n }\n\n // Drop ontology relations that came from the previous graph-extension\n // document — `compiled.ontology` reproduces them from the union, so\n // keeping the originals would double-stack. Pre-build a Set of\n // canonical keys for O(1) lookup; the naive per-relation `.some`\n // scan was O(N×M).\n const runtimeOntologyKeys =\n buildGraphExtensionOntologyKeySet(existingDocument);\n const compileTimeOntology = graph.ontology.filter(\n (relation) => !runtimeOntologyKeys.has(compileTimeOntologyKey(relation)),\n );\n const mergedOntology: readonly OntologyRelation[] = [\n ...compileTimeOntology,\n ...compiled.ontology.map((relation) =>\n resolveOntologyEndpoints(relation, nodeKinds),\n ),\n ];\n\n // Auto-derive vector indexes from `embedding()` brands on the\n // graph-extension kinds in the union document. Compile-time vector indexes\n // already live on `graph.indexes` from `defineGraph`; we drop any\n // prior runtime-origin entries (the union document is the source of\n // truth) and re-derive against the current graph-extension nodes so the\n // result is correct after add / replace cycles. Explicit compile-\n // time indexes win on (kind, fieldPath) collisions per the\n // `mergeVectorIndexes` contract.\n const runtimeVectorIndexes: readonly VectorIndexDeclaration[] =\n deriveGraphExtensionVectorIndexes(compiled.nodes);\n // Document-declared relational indexes (analogue of compile-time\n // `defineNodeIndex` / `defineEdgeIndex` passed to defineGraph).\n // Resolved here because schema introspection requires the merged\n // NodeType / EdgeType — graph-extension-declared kinds AND compile-time\n // host kinds are both reachable as targets.\n const runtimeRelationalIndexes = compileGraphExtensionRelationalIndexes(\n compiled.indexes,\n nodeKinds,\n mergedEdges,\n graph.id,\n );\n const mergedIndexes = mergeIndexesWithGraphExtension(\n graph.indexes,\n [...runtimeVectorIndexes, ...runtimeRelationalIndexes],\n graph.id,\n );\n\n // Returned as `G` even though graph-extension kinds aren't in the static\n // type — consumers reach them via the registry.\n return Object.freeze({\n ...graph,\n nodes: mergedNodes,\n edges: mergedEdges,\n ontology: mergedOntology,\n indexes: mergedIndexes,\n extension: validatedUnion,\n });\n}\n\nfunction deriveGraphExtensionVectorIndexes(\n compiledNodes: ReturnType<typeof compileGraphExtension>[\"nodes\"],\n): readonly VectorIndexDeclaration[] {\n if (compiledNodes.length === 0) return [];\n const registrations: Record<string, NodeRegistration> = {};\n for (const compiled of compiledNodes) {\n registrations[compiled.type.kind] = {\n type: compiled.type,\n ...(compiled.unique.length === 0 ? {} : { unique: [...compiled.unique] }),\n };\n }\n return autoDeriveVectorIndexes(registrations).map((index) =>\n Object.freeze({ ...index, origin: \"runtime\" as const }),\n );\n}\n\nfunction mergeIndexesWithGraphExtension(\n existing: readonly IndexDeclaration[] | undefined,\n runtimeIndexes: readonly IndexDeclaration[],\n graphId: string,\n): readonly IndexDeclaration[] | undefined {\n // Preserve \"no indexes anywhere\" as `undefined` so legacy graphs\n // that never declared indexes keep the same canonical-form hash.\n if (existing === undefined && runtimeIndexes.length === 0) {\n return undefined;\n }\n const compileTimeIndexes = (existing ?? []).filter(\n (index) => index.origin !== \"runtime\",\n );\n if (runtimeIndexes.length === 0) return compileTimeIndexes;\n\n // Vector entries dedup by (kind, fieldPath); explicit declarations\n // win over auto-derived. Run that pass first against vector inputs\n // only, then concatenate the (already-validated) relational\n // entries — they pass through `defineNodeIndex` /\n // `defineEdgeIndex` which enforces name uniqueness, so collisions\n // are caught earlier.\n const runtimeVectors = runtimeIndexes.filter(\n (index): index is VectorIndexDeclaration => index.entity === \"vector\",\n );\n const runtimeRelational = runtimeIndexes.filter(\n (index) => index.entity !== \"vector\",\n );\n const vectorMerged = mergeVectorIndexes(compileTimeIndexes, runtimeVectors);\n const merged = [...vectorMerged, ...runtimeRelational];\n assertUniqueIndexNames(merged, graphId);\n return merged;\n}\n\nfunction assertUniqueIndexNames(\n indexes: readonly IndexDeclaration[],\n graphId: string,\n): void {\n const seen = new Set<string>();\n for (const index of indexes) {\n if (!seen.has(index.name)) {\n seen.add(index.name);\n continue;\n }\n throw new ConfigurationError(\n `Duplicate index name \"${index.name}\" after merging graph extension into graph \"${graphId}\". Index names must be unique within a graph.`,\n { graphId, indexName: index.name, code: \"DUPLICATE_INDEX_NAME\" },\n {\n suggestion:\n \"Give the graph-extension index a unique `name`, or remove the duplicate declaration.\",\n },\n );\n }\n}\n\nfunction compileGraphExtensionRelationalIndexes(\n documents: readonly ExtensionIndex[],\n nodeKinds: ReadonlyMap<string, NodeType>,\n mergedEdges: Readonly<Record<string, EdgeRegistration>>,\n graphId: string,\n): readonly IndexDeclaration[] {\n if (documents.length === 0) return [];\n const result: IndexDeclaration[] = [];\n for (const document of documents) {\n if (document.entity === \"node\") {\n const node = nodeKinds.get(document.kind);\n if (node === undefined) {\n throw new KindNotFoundError(document.kind, \"node\", {\n graphId,\n suggestion:\n \"Declare the kind under `nodes` in this graph extension, or remove the index from `indexes`.\",\n });\n }\n const declaration = defineNodeIndex(\n node,\n toNodeIndexConfig(document) as NodeIndexConfig<NodeType>,\n );\n result.push(Object.freeze({ ...declaration, origin: \"runtime\" }));\n continue;\n }\n\n const edgeRegistration = mergedEdges[document.kind];\n if (edgeRegistration === undefined) {\n throw new KindNotFoundError(document.kind, \"edge\", {\n graphId,\n suggestion:\n \"Declare the edge under `edges` in this graph extension, or remove the index from `indexes`.\",\n });\n }\n const declaration = defineEdgeIndex(\n edgeRegistration.type,\n toEdgeIndexConfig(document) as EdgeIndexConfig<AnyEdgeType>,\n );\n result.push(Object.freeze({ ...declaration, origin: \"runtime\" }));\n }\n return result;\n}\n\n// Document-side `where` carries the persistence-round-trippable\n// `{ field, op: \"isNull\" | \"isNotNull\" }` shape. The compile-time\n// API takes a builder callback that returns `IndexWhereExpression`;\n// translate one into the other so `defineNodeIndex` / `defineEdgeIndex`\n// can produce the canonical declaration.\nfunction buildWhereCallback(where: NonNullable<ExtensionIndex[\"where\"]>) {\n return (\n props: Record<string, { isNull: () => unknown; isNotNull: () => unknown }>,\n ) => {\n const builder = props[where.field];\n if (builder === undefined) {\n throw new ConfigurationError(\n `Graph-extension index \\`where\\` references unknown field \"${where.field}\".`,\n { field: where.field, code: \"EXTENSION_INDEX_WHERE_UNKNOWN_FIELD\" },\n );\n }\n return where.op === \"isNull\" ? builder.isNull() : builder.isNotNull();\n };\n}\n\nfunction toNodeIndexConfig(\n document: Extract<ExtensionIndex, { entity: \"node\" }>,\n): Readonly<Record<string, unknown>> {\n return compactUndefined<Record<string, unknown>>({\n fields: document.fields,\n coveringFields: document.coveringFields,\n unique: document.unique,\n name: document.name,\n scope: document.scope,\n where:\n document.where === undefined ?\n undefined\n : buildWhereCallback(document.where),\n });\n}\n\nfunction toEdgeIndexConfig(\n document: Extract<ExtensionIndex, { entity: \"edge\" }>,\n): Readonly<Record<string, unknown>> {\n return compactUndefined<Record<string, unknown>>({\n fields: document.fields,\n coveringFields: document.coveringFields,\n unique: document.unique,\n name: document.name,\n scope: document.scope,\n direction: document.direction,\n where:\n document.where === undefined ?\n undefined\n : buildWhereCallback(document.where),\n });\n}\n\n/**\n * Combines two graph-extension documents into one. Same-named nodes\n * and edges in `next` overwrite their `existing` counterpart (the\n * structural-equal redefinition case is caught upstream by\n * `assertNoRedefinitions`, so the overwrite is always with an equal\n * value here). Ontology relations are deduped by `(metaEdge, from, to)`\n * — re-applying the same relation twice would otherwise persist\n * duplicates that the next restart's validator rejects with\n * `DUPLICATE_ONTOLOGY_RELATION`.\n */\nfunction unionDocuments(\n existing: GraphExtension,\n next: GraphExtension,\n): GraphExtension {\n // First-evolve fast path: when there's no existing document, the\n // already-frozen `next` IS the union. Skips four object spreads and\n // a freeze on the cold path.\n if (isEmptyExtension(existing)) {\n return next;\n }\n\n const nodes =\n existing.nodes === undefined && next.nodes === undefined ?\n undefined\n : { ...existing.nodes, ...next.nodes };\n const edges =\n existing.edges === undefined && next.edges === undefined ?\n undefined\n : { ...existing.edges, ...next.edges };\n const ontology =\n existing.ontology === undefined && next.ontology === undefined ?\n undefined\n : dedupBy(\n [...(existing.ontology ?? []), ...(next.ontology ?? [])],\n graphExtensionOntologyKey,\n );\n const indexes =\n existing.indexes === undefined && next.indexes === undefined ?\n undefined\n : dedupBy(\n [...(existing.indexes ?? []), ...(next.indexes ?? [])],\n indexCompositeKey,\n \"last\",\n );\n\n // Both inputs come through the validator, so `version` is always\n // populated. Forward it on the merged document so the canonical-form\n // hash agrees between the first-evolve fast path (which returns\n // `next` directly) and this re-merge path.\n const version = next.version ?? existing.version;\n\n return Object.freeze({\n ...(version === undefined ? {} : { version }),\n ...(nodes === undefined ? {} : { nodes }),\n ...(edges === undefined ? {} : { edges }),\n ...(ontology === undefined ? {} : { ontology }),\n ...(indexes === undefined ? {} : { indexes }),\n });\n}\n\n/**\n * Dedupe `items` by `keyFn`, preserving first-seen order. `strategy`\n * controls which entry survives a key collision:\n *\n * - `\"first\"` (default): drop later duplicates. Used for ontology\n * relations — re-applying the same relation in a later evolve is a\n * no-op, not a redefinition.\n * - `\"last\"`: keep the most-recent value. Used for indexes — declared\n * indexes don't carry independent identity beyond the composite key,\n * so the most recent declaration wins. Idempotent re-evolve relies\n * on `canonicalEqual(merged, existing)`, which is\n * preserved as long as `next` carries an identical entry.\n */\nfunction dedupBy<T>(\n items: readonly T[],\n keyFunction: (item: T) => string,\n strategy: \"first\" | \"last\" = \"first\",\n): readonly T[] {\n const seen = new Map<string, T>();\n const order: string[] = [];\n for (const item of items) {\n const key = keyFunction(item);\n if (!seen.has(key)) {\n order.push(key);\n seen.set(key, item);\n } else if (strategy === \"last\") {\n seen.set(key, item);\n }\n }\n return order.map((key) => seen.get(key)!);\n}\n\nfunction indexCompositeKey(entry: ExtensionIndex): string {\n return `${entry.entity}|${entry.kind}|${entry.name ?? \"\"}|${entry.fields.join(\",\")}`;\n}\n\n/**\n * `true` when none of the v1 content slots carry data. Drives the\n * first-evolve fast path in `unionDocuments`, and any future caller\n * that needs to short-circuit on a \"nothing to merge\" document.\n */\nfunction isEmptyExtension(extension: GraphExtension): boolean {\n return (\n extension.nodes === undefined &&\n extension.edges === undefined &&\n extension.ontology === undefined &&\n extension.indexes === undefined\n );\n}\n\nfunction assertNoCollision(\n kindName: string,\n entity: KindEntity,\n collides: boolean,\n graphId: string,\n): void {\n if (!collides) return;\n throw new KindCollisionError(kindName, entity, graphId);\n}\n\nfunction resolveEndpoints(\n entries: readonly (NodeType | string)[],\n nodeKinds: ReadonlyMap<string, NodeType>,\n context: Readonly<{ graphId: string; edgeKind: string; side: \"from\" | \"to\" }>,\n): readonly NodeType[] {\n return entries.map((entry) => {\n if (typeof entry !== \"string\") return entry;\n const resolved = nodeKinds.get(entry);\n if (resolved === undefined) {\n throw new GraphExtensionUnresolvedEndpointError(\n context.edgeKind,\n context.side,\n entry,\n context.graphId,\n );\n }\n return resolved;\n });\n}\n\nfunction resolveOntologyEndpoints(\n relation: OntologyRelation,\n nodeKinds: ReadonlyMap<string, NodeType>,\n): OntologyRelation {\n // Ontology endpoints are intentionally permissive — unresolved strings\n // pass through as external IRIs (matching the existing runtime\n // compiler behavior). Cross-graph kind validation only fires for edge\n // endpoints, which require a NodeType reference.\n const from =\n typeof relation.from === \"string\" ?\n (nodeKinds.get(relation.from) ?? relation.from)\n : relation.from;\n const to =\n typeof relation.to === \"string\" ?\n (nodeKinds.get(relation.to) ?? relation.to)\n : relation.to;\n return { ...relation, from, to };\n}\n","/**\n * Types for serialized schema storage.\n *\n * These types represent the JSON-serializable format used for\n * homoiconic schema storage in the database.\n *\n * The Zod schema (serializedSchemaZod) is the single source of truth.\n * The TypeScript type (SerializedSchema) is inferred from it.\n */\nimport { z } from \"zod\";\n\nimport {\n type Cardinality,\n type Collation,\n type DeleteBehavior,\n type EndpointExistence,\n type KindAnnotations,\n type TemporalMode,\n type UniquenessScope,\n} from \"../core/types\";\nimport { type GraphExtension } from \"../graph-extension/extension-types\";\nimport { type IndexDeclaration } from \"../indexes/types\";\nimport { type InferenceType } from \"../ontology/types\";\nimport { type JsonPointer } from \"../query/json-pointer\";\n\n// ============================================================\n// Enum Zod Schemas\n//\n// These mirror the literal union types from core/types.ts and\n// ontology/types.ts. The Zod schema validates that stored values\n// are members of the known set — unknown enum values from newer\n// schema versions are rejected at the parse boundary rather than\n// silently cast to narrow union types.\n// ============================================================\n\nconst deleteBehaviorZod = z.enum([\"restrict\", \"cascade\", \"disconnect\"]);\n\nconst cardinalityZod = z.enum([\"many\", \"one\", \"unique\", \"oneActive\"]);\n\nconst endpointExistenceZod = z.enum([\"notDeleted\", \"currentlyValid\", \"ever\"]);\n\nconst temporalModeZod = z.enum([\n \"current\",\n \"asOf\",\n \"includeEnded\",\n \"includeTombstones\",\n]);\n\nconst uniquenessScopeZod = z.enum([\"kind\", \"kindWithSubClasses\"]);\n\nconst collationZod = z.enum([\"binary\", \"caseInsensitive\"]);\n\nconst inferenceTypeZod = z.enum([\n \"subsumption\",\n \"hierarchy\",\n \"substitution\",\n \"constraint\",\n \"composition\",\n \"association\",\n \"none\",\n]);\n\nconst indexScopeZod = z.enum([\"graphAndKind\", \"graph\", \"none\"]);\n\nconst indexOriginZod = z.enum([\"compile-time\", \"runtime\"]);\n\nconst edgeIndexDirectionZod = z.enum([\"out\", \"in\", \"none\"]);\n\nconst valueTypeZod = z.enum([\n \"string\",\n \"number\",\n \"boolean\",\n \"date\",\n \"array\",\n \"object\",\n \"embedding\",\n \"unknown\",\n]);\n\nconst valueTypeOrUndefinedZod = valueTypeZod.optional();\n\n// ============================================================\n// Index WHERE expression Zod schemas\n// ============================================================\n\nconst systemColumnNameZod = z.enum([\n \"graph_id\",\n \"kind\",\n \"id\",\n \"from_kind\",\n \"from_id\",\n \"to_kind\",\n \"to_id\",\n \"deleted_at\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"version\",\n]);\n\nconst indexWhereOperandZod = z.discriminatedUnion(\"__type\", [\n z.object({\n __type: z.literal(\"index_operand_system\"),\n column: systemColumnNameZod,\n valueType: valueTypeOrUndefinedZod,\n }),\n z.object({\n __type: z.literal(\"index_operand_prop\"),\n field: z.string(),\n valueType: valueTypeOrUndefinedZod,\n }),\n]);\n\nconst indexWhereLiteralZod = z.object({\n __type: z.literal(\"index_where_literal\"),\n value: z.union([z.string(), z.number(), z.boolean()]),\n valueType: valueTypeZod,\n});\n\nconst indexWhereOpZod = z.enum([\n \"eq\",\n \"neq\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"in\",\n \"notIn\",\n]);\n\ninterface IndexWhereExpressionShape {\n __type:\n | \"index_where_and\"\n | \"index_where_or\"\n | \"index_where_not\"\n | \"index_where_comparison\"\n | \"index_where_null_check\";\n}\n\nconst indexWhereExpressionZod: z.ZodType<IndexWhereExpressionShape> = z.lazy(\n () =>\n z.discriminatedUnion(\"__type\", [\n z.object({\n __type: z.literal(\"index_where_and\"),\n predicates: z.array(indexWhereExpressionZod),\n }),\n z.object({\n __type: z.literal(\"index_where_or\"),\n predicates: z.array(indexWhereExpressionZod),\n }),\n z.object({\n __type: z.literal(\"index_where_not\"),\n predicate: indexWhereExpressionZod,\n }),\n z.object({\n __type: z.literal(\"index_where_comparison\"),\n left: indexWhereOperandZod,\n op: indexWhereOpZod,\n right: z.union([indexWhereLiteralZod, z.array(indexWhereLiteralZod)]),\n }),\n z.object({\n __type: z.literal(\"index_where_null_check\"),\n operand: indexWhereOperandZod,\n op: z.enum([\"isNull\", \"isNotNull\"]),\n }),\n ]) as unknown as z.ZodType<IndexWhereExpressionShape>,\n);\n\n// ============================================================\n// IndexDeclaration Zod schema\n// ============================================================\n\n// `JsonPointer` is a branded `string`. Validating with the brand\n// preserved keeps `SerializedSchema` and the Zod-inferred type aligned\n// without an `as unknown` cast at the parse boundary in `manager.ts`.\nconst jsonPointerZod = z.custom<JsonPointer>(\n (value) => typeof value === \"string\",\n { message: \"Expected a JSON pointer string\" },\n);\n\nconst indexDeclarationCommonShape = {\n name: z.string(),\n // `origin` is optional. `\"compile-time\"` is the default and is omitted\n // from canonical form so legacy graphs without indexes hash\n // byte-identically. Consumers that need a concrete value should\n // coalesce `index.origin ?? \"compile-time\"`.\n origin: indexOriginZod.optional(),\n fields: z.array(jsonPointerZod),\n fieldValueTypes: z.array(valueTypeOrUndefinedZod),\n coveringFields: z.array(jsonPointerZod),\n coveringFieldValueTypes: z.array(valueTypeOrUndefinedZod),\n unique: z.boolean(),\n scope: indexScopeZod,\n where: indexWhereExpressionZod.optional(),\n} as const;\n\nconst nodeIndexDeclarationZod = z\n .object({\n entity: z.literal(\"node\"),\n kind: z.string(),\n ...indexDeclarationCommonShape,\n })\n .loose();\n\nconst edgeIndexDeclarationZod = z\n .object({\n entity: z.literal(\"edge\"),\n kind: z.string(),\n direction: edgeIndexDirectionZod,\n ...indexDeclarationCommonShape,\n })\n .loose();\n\nconst vectorIndexMetricZod = z.enum([\"cosine\", \"l2\", \"inner_product\"]);\n\nconst vectorIndexImplementationZod = z.enum([\"hnsw\", \"ivfflat\", \"none\"]);\n\nconst vectorIndexParamsZod = z\n .object({\n m: z.number(),\n efConstruction: z.number(),\n lists: z.number().optional(),\n })\n .loose();\n\nconst vectorIndexDeclarationZod = z\n .object({\n entity: z.literal(\"vector\"),\n name: z.string(),\n origin: indexOriginZod.optional(),\n kind: z.string(),\n fieldPath: z.string(),\n dimensions: z.number(),\n metric: vectorIndexMetricZod,\n indexType: vectorIndexImplementationZod,\n indexParams: vectorIndexParamsZod,\n })\n .loose();\n\nconst indexDeclarationZod = z.discriminatedUnion(\"entity\", [\n nodeIndexDeclarationZod,\n edgeIndexDeclarationZod,\n vectorIndexDeclarationZod,\n]);\n\n// ============================================================\n// GraphExtension Zod schema\n// ============================================================\n\n// Boundary parser for the persisted graph extension. The pure-value\n// validator in `graph-extension/validation.ts` is the authoritative shape\n// check (re-run on every load via the extension compiler); this\n// schema's job is only to confirm the JSON shape is round-trippable\n// and to keep `SerializedSchema.extension` typed.\n//\n// `.loose()` on every nested object accepts forward-compatible\n// extensions without breaking older readers — same posture as the rest\n// of the schema document.\nconst runtimePropertyZod = z.record(z.string(), z.unknown());\n\nconst runtimeNodeDocumentZod = z\n .object({\n description: z.string().optional(),\n annotations: z.record(z.string(), z.json()).optional(),\n properties: z.record(z.string(), runtimePropertyZod),\n unique: z.array(z.object({}).loose()).optional(),\n })\n .loose();\n\nconst runtimeEdgeDocumentZod = z\n .object({\n description: z.string().optional(),\n annotations: z.record(z.string(), z.json()).optional(),\n from: z.array(z.string()),\n to: z.array(z.string()),\n properties: z.record(z.string(), runtimePropertyZod).optional(),\n })\n .loose();\n\nconst runtimeOntologyRelationZod = z\n .object({\n metaEdge: z.string(),\n from: z.string(),\n to: z.string(),\n })\n .loose();\n\n// Graph-extension-declared relational indexes (analogue of compile-time\n// `defineNodeIndex` / `defineEdgeIndex` passed to defineGraph).\n// Persisted with `.loose()` so future v1.x.y additive fields ride\n// forward without a major bump.\nconst runtimeIndexDocumentZod = z\n .object({\n entity: z.string(),\n kind: z.string(),\n name: z.string().optional(),\n fields: z.array(z.string()).optional(),\n coveringFields: z.array(z.string()).optional(),\n unique: z.boolean().optional(),\n scope: z.string().optional(),\n direction: z.string().optional(),\n where: z.object({ field: z.string(), op: z.string() }).loose().optional(),\n })\n .loose();\n\nconst graphExtensionZod = z\n .object({\n // Version is parsed loosely here so the persistence boundary\n // never rejects a stored document — the runtime validator owns\n // the version check and produces actionable errors. Documents\n // that pre-date the field round-trip as `version: undefined`.\n version: z.number().optional(),\n nodes: z.record(z.string(), runtimeNodeDocumentZod).optional(),\n edges: z.record(z.string(), runtimeEdgeDocumentZod).optional(),\n ontology: z.array(runtimeOntologyRelationZod).optional(),\n indexes: z.array(runtimeIndexDocumentZod).optional(),\n })\n .loose() as unknown as z.ZodType<GraphExtension>;\n\n// ============================================================\n// JSON Schema Types (from Zod)\n// ============================================================\n\n/**\n * JSON Schema type (subset used by Zod toJSONSchema).\n *\n * This is a simplified version - the actual JSON Schema has many more properties.\n */\nexport type JsonSchema = Readonly<{\n $schema?: string;\n type?: string | readonly string[];\n properties?: Record<string, JsonSchema>;\n required?: readonly string[];\n items?: JsonSchema;\n additionalProperties?: boolean | JsonSchema;\n enum?: readonly unknown[];\n const?: unknown;\n anyOf?: readonly JsonSchema[];\n oneOf?: readonly JsonSchema[];\n allOf?: readonly JsonSchema[];\n not?: JsonSchema;\n description?: string;\n default?: unknown;\n minimum?: number;\n maximum?: number;\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n format?: string;\n [key: string]: unknown;\n}>;\n\n// ============================================================\n// Serialized Meta-Edge\n// ============================================================\n\n/**\n * Serialized representation of a meta-edge.\n */\nexport type SerializedMetaEdge = Readonly<{\n name: string;\n transitive: boolean;\n symmetric: boolean;\n reflexive: boolean;\n inverse: string | undefined;\n inference: InferenceType;\n description: string | undefined;\n}>;\n\n// ============================================================\n// Serialized Ontology Relation\n// ============================================================\n\n/**\n * Serialized representation of an ontology relation.\n */\nexport type SerializedOntologyRelation = Readonly<{\n metaEdge: string; // Meta-edge name\n from: string; // Node kind name or external IRI\n to: string; // Node kind name or external IRI\n}>;\n\n// ============================================================\n// Serialized Closures\n// ============================================================\n\n/**\n * Precomputed closures stored in the schema for fast runtime lookup.\n */\nexport type SerializedClosures = Readonly<{\n subClassAncestors: Record<string, readonly string[]>;\n subClassDescendants: Record<string, readonly string[]>;\n broaderClosure: Record<string, readonly string[]>;\n narrowerClosure: Record<string, readonly string[]>;\n equivalenceSets: Record<string, readonly string[]>;\n disjointPairs: readonly string[]; // [\"Organization|Person\", ...]\n partOfClosure: Record<string, readonly string[]>;\n hasPartClosure: Record<string, readonly string[]>;\n iriToKind: Record<string, string>;\n edgeInverses: Record<string, string>; // {\"likes\": \"likedBy\", ...}\n edgeImplicationsClosure: Record<string, readonly string[]>;\n edgeImplyingClosure: Record<string, readonly string[]>;\n}>;\n\n// ============================================================\n// Serialized Ontology\n// ============================================================\n\n/**\n * Complete serialized ontology section.\n */\nexport type SerializedOntology = Readonly<{\n metaEdges: Record<string, SerializedMetaEdge>;\n relations: readonly SerializedOntologyRelation[];\n closures: SerializedClosures;\n}>;\n\n// ============================================================\n// Serialized Uniqueness Constraint\n// ============================================================\n\n/**\n * Serialized representation of a uniqueness constraint.\n */\nexport type SerializedUniqueConstraint = Readonly<{\n name: string;\n fields: readonly string[];\n where: string | undefined; // Serialized predicate or undefined\n scope: UniquenessScope;\n collation: Collation;\n}>;\n\n// ============================================================\n// Serialized Node Definition\n// ============================================================\n\n/**\n * Serialized representation of a node kind.\n */\nexport type SerializedNodeDef = Readonly<{\n kind: string;\n properties: JsonSchema;\n uniqueConstraints: readonly SerializedUniqueConstraint[];\n onDelete: DeleteBehavior;\n description: string | undefined;\n annotations?: KindAnnotations;\n}>;\n\n// ============================================================\n// Serialized Edge Definition\n// ============================================================\n\n/**\n * Serialized representation of an edge kind.\n */\nexport type SerializedEdgeDef = Readonly<{\n kind: string;\n fromKinds: readonly string[];\n toKinds: readonly string[];\n properties: JsonSchema;\n cardinality: Cardinality;\n endpointExistence: EndpointExistence;\n description: string | undefined;\n annotations?: KindAnnotations;\n}>;\n\n// ============================================================\n// Serialized Schema\n// ============================================================\n\n/**\n * Validates that each record key matches the identifier field inside its value.\n * Catches corruption like `nodes.Person.kind = \"Company\"`.\n */\nfunction checkRecordKeyMatchesField(\n field: string,\n section: string,\n): (\n record: Record<string, Record<string, unknown>>,\n ctx: z.RefinementCtx,\n) => void {\n return (record, ctx) => {\n for (const [key, value] of Object.entries(record)) {\n const embedded = value[field];\n if (typeof embedded === \"string\" && embedded !== key) {\n ctx.addIssue({\n code: \"custom\",\n path: [key, field],\n message: `Record key \"${key}\" does not match ${field} \"${embedded}\" in ${section}`,\n });\n }\n }\n };\n}\n\n/**\n * Zod schema for validating serialized schema documents read from the database.\n *\n * Enum fields (temporalMode, cardinality, deleteBehavior, etc.) are validated\n * against the real literal unions — unknown enum values from newer schema\n * versions are rejected at the parse boundary.\n *\n * Nested objects use .loose() so that extra structural fields added by newer\n * versions are accepted without failing validation (forward compatibility for\n * shape, strict for semantics).\n */\nexport const serializedSchemaZod = z.object({\n graphId: z.string(),\n version: z.number(),\n generatedAt: z.string(),\n nodes: z\n .record(\n z.string(),\n z\n .object({\n kind: z.string(),\n properties: z.record(z.string(), z.unknown()),\n uniqueConstraints: z.array(\n z\n .object({\n name: z.string(),\n fields: z.array(z.string()),\n where: z.string().optional(),\n scope: uniquenessScopeZod,\n collation: collationZod,\n })\n .loose(),\n ),\n onDelete: deleteBehaviorZod,\n description: z.string().optional(),\n annotations: z.record(z.string(), z.json()).optional(),\n })\n .loose(),\n )\n .superRefine(checkRecordKeyMatchesField(\"kind\", \"nodes\")),\n edges: z\n .record(\n z.string(),\n z\n .object({\n kind: z.string(),\n fromKinds: z.array(z.string()),\n toKinds: z.array(z.string()),\n properties: z.record(z.string(), z.unknown()),\n cardinality: cardinalityZod,\n endpointExistence: endpointExistenceZod,\n description: z.string().optional(),\n annotations: z.record(z.string(), z.json()).optional(),\n })\n .loose(),\n )\n .superRefine(checkRecordKeyMatchesField(\"kind\", \"edges\")),\n ontology: z\n .object({\n metaEdges: z\n .record(\n z.string(),\n z\n .object({\n name: z.string(),\n transitive: z.boolean(),\n symmetric: z.boolean(),\n reflexive: z.boolean(),\n inference: inferenceTypeZod,\n inverse: z.string().optional(),\n description: z.string().optional(),\n })\n .loose(),\n )\n .superRefine(checkRecordKeyMatchesField(\"name\", \"ontology.metaEdges\")),\n relations: z.array(\n z\n .object({\n metaEdge: z.string(),\n from: z.string(),\n to: z.string(),\n })\n .loose(),\n ),\n closures: z\n .object({\n subClassAncestors: z.record(z.string(), z.array(z.string())),\n subClassDescendants: z.record(z.string(), z.array(z.string())),\n broaderClosure: z.record(z.string(), z.array(z.string())),\n narrowerClosure: z.record(z.string(), z.array(z.string())),\n equivalenceSets: z.record(z.string(), z.array(z.string())),\n disjointPairs: z.array(z.string()),\n partOfClosure: z.record(z.string(), z.array(z.string())),\n hasPartClosure: z.record(z.string(), z.array(z.string())),\n iriToKind: z.record(z.string(), z.string()),\n edgeInverses: z.record(z.string(), z.string()),\n edgeImplicationsClosure: z.record(z.string(), z.array(z.string())),\n edgeImplyingClosure: z.record(z.string(), z.array(z.string())),\n })\n .loose(),\n })\n .loose(),\n defaults: z\n .object({\n onNodeDelete: deleteBehaviorZod,\n temporalMode: temporalModeZod,\n })\n .loose(),\n /**\n * Index declarations attached to the graph.\n *\n * Optional: graphs that never declared the slice omit the field\n * entirely so their canonical-form hash is byte-identical to graphs\n * authored before `indexes` existed.\n */\n indexes: z.array(indexDeclarationZod).optional(),\n /**\n * Graph extension persisted alongside the compiled `nodes` / `edges`\n * / `ontology` slices. The loader rebuilds extension-kind Zod\n * validators from this value (the only durable source); legacy\n * graphs omit the field and hash byte-identically to before\n * extensions existed.\n *\n * `.loose()` on the inner shape accepts forward-compatible additions\n * without breaking older readers.\n */\n extension: graphExtensionZod.optional(),\n /**\n * Names of node and edge kinds the operator has soft-deprecated via\n * `store.deprecateKinds(...)`. Surfaces in introspection so consumers\n * (codegen, UI tooling, lints) can route around them. Does not affect\n * reads, writes, or queries.\n *\n * Omitted when empty so legacy schemas hash byte-identically.\n */\n deprecatedKinds: z.array(z.string()).optional(),\n});\n\n/**\n * Complete serialized schema document.\n *\n * This is the format stored in the schema_doc column of\n * typegraph_schema_versions. The type is kept explicit rather than\n * inferred from the Zod schema so that downstream code sees the\n * precise literal union types (DeleteBehavior, TemporalMode, etc.)\n * instead of the broader `string` type that Zod's passthrough schema uses.\n */\nexport type SerializedSchema = Readonly<{\n graphId: string;\n version: number;\n generatedAt: string;\n nodes: Record<string, SerializedNodeDef>;\n edges: Record<string, SerializedEdgeDef>;\n ontology: SerializedOntology;\n defaults: Readonly<{\n onNodeDelete: DeleteBehavior;\n temporalMode: TemporalMode;\n }>;\n /**\n * Index declarations attached to the graph.\n *\n * Omitted entirely when the graph never declared the slice — legacy\n * schemas hash byte-identically to before `indexes` existed. Each\n * entry carries an `origin` discriminator: `\"compile-time\"` is the\n * default and is omitted from the canonical form (see `serializer.ts`);\n * only `\"runtime\"` is emitted explicitly.\n */\n indexes?: readonly IndexDeclaration[];\n /**\n * Graph extension, when this schema was produced from a graph that\n * had been merged with one. The loader uses this value (and only\n * this value) to rebuild extension-kind Zod validators on restart —\n * the merged `nodes` / `edges` / `ontology` maps above carry the\n * JSON-Schema-shaped views for diff machinery and human-readable\n * reporting, but they cannot reconstruct Zod alone.\n *\n * Omitted entirely on graphs that have never been extended — legacy\n * schemas hash byte-identically.\n */\n extension?: GraphExtension;\n /**\n * Soft-deprecated node and edge kind names. Set by\n * `store.deprecateKinds(...)`; cleared by `store.undeprecateKinds(...)`.\n * Surfaces in introspection but does not affect reads, writes, or\n * queries. Omitted entirely when empty so legacy schemas hash\n * byte-identically.\n */\n deprecatedKinds?: readonly string[];\n}>;\n\n// ============================================================\n// Schema Hash\n// ============================================================\n\n/**\n * A schema hash for detecting changes.\n *\n * We hash the schema content (excluding version and generatedAt)\n * to detect if the schema has actually changed.\n */\nexport type SchemaHash = string;\n","/**\n * Schema manager for TypeGraph.\n *\n * Provides schema lifecycle management:\n * - Initialization on first store creation\n * - Validation on store open\n * - Auto-migration for safe changes\n * - Error reporting for breaking changes\n */\nimport { type GraphBackend, type SchemaVersionRow } from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport {\n ConfigurationError,\n DatabaseOperationError,\n MigrationError,\n} from \"../errors\";\nimport { mergeGraphExtension } from \"../graph-extension/merge\";\nimport { freezeDeep } from \"../utils/object\";\nimport { isMissingTableError } from \"../utils/sql-errors\";\nimport {\n computeSchemaDiff,\n getMigrationActions,\n isBackwardsCompatible,\n type SchemaDiff,\n} from \"./migration\";\nimport {\n computeSchemaHash,\n getSchemaHash,\n serializeSchema,\n} from \"./serializer\";\nimport { type SerializedSchema, serializedSchemaZod } from \"./types\";\n\n/**\n * Bounded LRU cache for `parseSerializedSchema` results, keyed on the\n * raw schema_doc string. Multi-tenant servers re-read the same row\n * across tenants on every store boot, and the full Zod parse + JSON\n * walk is ~0.5ms on a 50KB schema. Capped at 100 entries (~5MB worst\n * case) so a long-running process holding many distinct schemas\n * doesn't grow the cache unbounded.\n */\nconst PARSE_CACHE_LIMIT = 100;\nconst PARSE_CACHE = new Map<string, SerializedSchema>();\n\n/**\n * Parses and validates a serialized schema document from the database.\n *\n * Uses the Zod schema to validate the full nested structure, catching\n * corruption, incompatible schema versions, or truncated JSON at the\n * parse boundary rather than letting invalid data propagate silently.\n */\nexport function parseSerializedSchema(json: string): SerializedSchema {\n const cached = PARSE_CACHE.get(json);\n if (cached !== undefined) {\n // LRU touch: re-insert to mark as most-recently-used.\n PARSE_CACHE.delete(json);\n PARSE_CACHE.set(json, cached);\n return cached;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch {\n throw new DatabaseOperationError(\n \"Stored schema document is not valid JSON\",\n { operation: \"select\", entity: \"schema\" },\n );\n }\n\n const result = serializedSchemaZod.safeParse(parsed);\n if (!result.success) {\n const issues = result.error.issues\n .map((issue) => `${issue.path.join(\".\")}: ${issue.message}`)\n .join(\"; \");\n throw new DatabaseOperationError(\n `Stored schema document is malformed: ${issues}`,\n { operation: \"select\", entity: \"schema\" },\n );\n }\n\n // The Zod schema validates enum fields (temporalMode, cardinality, etc.)\n // against the real literal unions. The cast is sound — the only\n // broadening is `.loose()` on objects (extra fields), not on enum\n // values.\n const validated = freezeDeep(result.data as SerializedSchema);\n\n if (PARSE_CACHE.size >= PARSE_CACHE_LIMIT) {\n // Drop the oldest entry. JS Map iteration is insertion-ordered, so\n // the first key is the least-recently-used.\n const oldest = PARSE_CACHE.keys().next().value;\n if (oldest !== undefined) PARSE_CACHE.delete(oldest);\n }\n PARSE_CACHE.set(json, validated);\n return validated;\n}\n\n// ============================================================\n// Helpers\n// ============================================================\n\n/**\n * Reads the active schema row, bootstrapping the base tables on the\n * first call against an empty database.\n *\n * Deliberately does NOT materialize runtime contributions (fulltext)\n * here. Contribution DDL is derived from the *current code graph*; when\n * the persisted schema is behind by a breaking change, running it here\n * would apply vN+1 DDL against the vN table shape before `ensureSchema`\n * computes the diff and throws `MigrationError`. On Postgres the first\n * failing statement poisons the surrounding transaction, so the error\n * that escapes is the idempotent marker-table\n * `CREATE TABLE IF NOT EXISTS` (collateral damage) rather than a clean\n * `MigrationError` — breaking the documented migrate-on-`MigrationError`\n * recovery path (#143). `createStoreWithSchema` is the single canonical\n * durable-marker writer (#135) and materializes runtime contributions\n * only AFTER the schema gate has run, so the breaking-change check is\n * always reached first.\n */\nexport async function loadActiveSchemaWithBootstrap(\n backend: GraphBackend,\n graphId: string,\n): Promise<SchemaVersionRow | undefined> {\n try {\n return await backend.getActiveSchema(graphId);\n } catch (error) {\n if (backend.bootstrapTables && isMissingTableError(error)) {\n await backend.bootstrapTables();\n return await backend.getActiveSchema(graphId);\n }\n throw error;\n }\n}\n\n/**\n * Reads the active schema, parses it, and folds any persisted graph-extension\n * document into the supplied compile-time graph. Returns the\n * merged graph alongside the prefetched row + parsed schema so the\n * caller can pass them through to `ensureSchema` without paying for a\n * second `getActiveSchema` round trip or a second\n * `serializedSchemaZod` walk.\n *\n * Throws `ConfigurationError` if the persisted graph-extension document\n * references a compile-time kind that no longer exists (the\n * startup-conflict case).\n */\nexport async function loadAndMergeGraphExtensionDocument<G extends GraphDef>(\n backend: GraphBackend,\n graph: G,\n): Promise<\n Readonly<{\n graph: G;\n activeRow: SchemaVersionRow | undefined;\n storedSchema: SerializedSchema | undefined;\n }>\n> {\n const activeRow = await loadActiveSchemaWithBootstrap(backend, graph.id);\n if (activeRow === undefined) {\n return { graph, activeRow: undefined, storedSchema: undefined };\n }\n const { graph: merged, storedSchema } = mergeStoredGraphExtension(\n graph,\n activeRow,\n );\n return { graph: merged, activeRow, storedSchema };\n}\n\n/**\n * Pure parse + extension-merge + deprecated-kind application. Factored\n * out so the SELECT-only verifier (`assertSchemaCurrent`) can fold the\n * persisted graph extension into the supplied graph without paying for a\n * second `getActiveSchema` round trip or going through the\n * bootstrap-capable loader.\n */\nfunction mergeStoredGraphExtension<G extends GraphDef>(\n graph: G,\n activeRow: SchemaVersionRow,\n): Readonly<{ graph: G; storedSchema: SerializedSchema }> {\n const storedSchema = parseSerializedSchema(activeRow.schema_doc);\n const merged =\n storedSchema.extension === undefined ?\n graph\n : mergeGraphExtension(graph, storedSchema.extension);\n return {\n graph: applyDeprecatedKinds(merged, storedSchema.deprecatedKinds),\n storedSchema,\n };\n}\n\n/**\n * Returns a graph carrying the supplied deprecated-kind names. Used by\n * the loader to propagate `SerializedSchema.deprecatedKinds` onto the\n * `GraphDef` that the Store sees, and by `Store.deprecateKinds` /\n * `Store.undeprecateKinds` to construct the next graph.\n *\n * Returns the original graph reference when the desired set already\n * matches `graph.deprecatedKinds` — covers both the no-deprecations\n * load path (empty equals empty) and the loader's restart-with-same-\n * persisted-set hot path. Skips a Set allocation + spread + freeze.\n */\nexport function applyDeprecatedKinds<G extends GraphDef>(\n graph: G,\n names: Iterable<string> | undefined,\n): G {\n const current = graph.deprecatedKinds;\n // Identity short-circuit: callers commonly pass `graph.deprecatedKinds`\n // directly (or another graph's set that was carried through unchanged).\n if (names === current) return graph;\n\n const nextSet: ReadonlySet<string> =\n names === undefined ? new Set<string>()\n : names instanceof Set ? (names as ReadonlySet<string>)\n : new Set<string>(names);\n\n if (nextSet.size === 0 && current.size === 0) return graph;\n if (\n nextSet.size === current.size &&\n [...nextSet].every((name) => current.has(name))\n ) {\n return graph;\n }\n return Object.freeze({\n ...graph,\n deprecatedKinds: Object.freeze(new Set(nextSet)),\n });\n}\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Result of schema validation.\n *\n * The `initialized` and `migrated` statuses carry the committed\n * `SchemaVersionRow` directly so callers building post-commit metadata\n * (e.g. `Store.deprecateKinds`) can skip a `getActiveSchema` round-trip.\n */\nexport type SchemaValidationResult =\n | {\n status: \"initialized\";\n version: number;\n committedRow: SchemaVersionRow;\n }\n | { status: \"unchanged\"; version: number }\n | {\n status: \"migrated\";\n fromVersion: number;\n toVersion: number;\n diff: SchemaDiff;\n committedRow: SchemaVersionRow;\n }\n | { status: \"pending\"; version: number; diff: SchemaDiff }\n | { status: \"breaking\"; diff: SchemaDiff; actions: readonly string[] };\n\n/**\n * Context passed to migration lifecycle hooks.\n *\n * Hooks are intended for observability (logging, metrics, alerts),\n * not for data transformations. Use an explicit migration runner\n * for backfill scripts — see the schema evolution guide.\n */\nexport type MigrationHookContext = Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n diff: SchemaDiff;\n}>;\n\n/**\n * Options for schema management.\n */\nexport type SchemaManagerOptions = Readonly<{\n /** If true, auto-migrate safe changes. Default: true */\n autoMigrate?: boolean;\n /** If true, throw on breaking changes. Default: true */\n throwOnBreaking?: boolean;\n /** Called before a safe auto-migration is applied. For observability only. */\n onBeforeMigrate?: (context: MigrationHookContext) => void | Promise<void>;\n /** Called after a safe auto-migration is applied. For observability only. */\n onAfterMigrate?: (context: MigrationHookContext) => void | Promise<void>;\n}>;\n\n// ============================================================\n// Schema Manager\n// ============================================================\n\n/**\n * Ensures the schema is initialized and up-to-date.\n *\n * This is the main entry point for schema management. It:\n * 1. Initializes the schema if this is the first run (version 1)\n * 2. Returns \"unchanged\" if the schema matches the current graph\n * 3. Auto-migrates safe changes if autoMigrate is true\n * 4. Throws MigrationError for breaking changes if throwOnBreaking is true\n *\n * @param backend - The database backend\n * @param graph - The current graph definition\n * @param options - Schema management options\n * @returns The result of schema validation\n * @throws MigrationError if breaking changes detected and throwOnBreaking is true\n */\nexport async function ensureSchema<G extends GraphDef>(\n backend: GraphBackend,\n graph: G,\n options?: SchemaManagerOptions & {\n /**\n * Pre-fetched active row + parsed stored schema. When the loader\n * (`createStoreWithSchema`) has already paid for `getActiveSchema`\n * and `parseSerializedSchema` to peek at `extension`, it\n * passes the results through here so `ensureSchema` doesn't repeat\n * the round trip + Zod walk on every Store boot.\n */\n preloaded?: Readonly<{\n activeRow: SchemaVersionRow | undefined;\n storedSchema: SerializedSchema | undefined;\n }>;\n },\n): Promise<SchemaValidationResult> {\n const autoMigrate = options?.autoMigrate ?? true;\n const throwOnBreaking = options?.throwOnBreaking ?? true;\n\n // When `preloaded` is supplied we trust both fields verbatim, even\n // when `activeRow` is undefined — that means the loader explicitly\n // checked and saw no schema yet. Falling back to `??` would refetch\n // and could observe a row that another process committed in the\n // race window between the loader's read and this point; ensureSchema\n // would then diff a persisted schema with graph extensions against the\n // unmerged graph and throw a misleading MigrationError. With the\n // sentinel check the race surfaces as a clean `StaleVersionError`\n // from `commitSchemaVersion` inside `initializeSchema` instead.\n const preloaded = options?.preloaded;\n const activeSchema =\n preloaded === undefined ?\n await loadActiveSchemaWithBootstrap(backend, graph.id)\n : preloaded.activeRow;\n\n if (activeSchema === undefined) {\n // No schema exists - initialize with version 1\n const result = await initializeSchema(backend, graph);\n return {\n status: \"initialized\",\n version: result.version,\n committedRow: result,\n };\n }\n\n // Quick hash check first — uses the per-graph hash cache so repeated\n // boots against the same graph reference skip the full serialize +\n // SHA-256 walk. When the hash matches, we never need the\n // `currentSchema` or the `storedSchema` (no diff is computed), so\n // defer those allocations until they're actually needed.\n const storedHash = activeSchema.schema_hash;\n const currentHash = await getSchemaHash(graph, activeSchema.version + 1);\n\n if (storedHash === currentHash) {\n return { status: \"unchanged\", version: activeSchema.version };\n }\n\n // Hashes differ - serialize both sides to compute the diff.\n const storedSchema =\n preloaded?.storedSchema ?? parseSerializedSchema(activeSchema.schema_doc);\n const currentSchema = serializeSchema(graph, activeSchema.version + 1);\n const diff = computeSchemaDiff(storedSchema, currentSchema);\n\n if (!diff.hasChanges) {\n // Hash changed but no semantic changes (shouldn't happen, but handle it)\n return { status: \"unchanged\", version: activeSchema.version };\n }\n\n // Check if changes are backwards compatible\n if (isBackwardsCompatible(diff)) {\n if (autoMigrate) {\n // Safe changes - auto-migrate\n const hookContext: MigrationHookContext = {\n graphId: graph.id,\n fromVersion: activeSchema.version,\n toVersion: activeSchema.version + 1,\n diff,\n };\n await options?.onBeforeMigrate?.(hookContext);\n const committedRow = await commitNewSchemaVersion(\n backend,\n graph,\n activeSchema.version,\n );\n await options?.onAfterMigrate?.(hookContext);\n return {\n status: \"migrated\",\n fromVersion: activeSchema.version,\n toVersion: committedRow.version,\n diff,\n committedRow,\n };\n }\n // Auto-migrate disabled but changes are safe\n return {\n status: \"pending\",\n version: activeSchema.version,\n diff,\n };\n }\n\n // Breaking changes detected\n const actions = getMigrationActions(diff);\n\n if (throwOnBreaking) {\n throw new MigrationError(\n `Schema migration required: ${diff.summary}. ` +\n `${actions.length} migration action(s) needed. ` +\n `Use getSchemaChanges() to review, then migrateSchema() to apply.`,\n {\n graphId: graph.id,\n fromVersion: activeSchema.version,\n toVersion: activeSchema.version + 1,\n },\n );\n }\n\n return { status: \"breaking\", diff, actions };\n}\n\n// ============================================================\n// SELECT-only schema verification (least-privilege runtime)\n// ============================================================\n\n/**\n * SELECT-only sibling of `loadAndMergeGraphExtensionDocument` for the\n * least-privilege runtime path: reads the active schema row, folds any\n * persisted graph extension into the supplied graph, and classifies\n * whether the database is current relative to that merged graph — all\n * **without DDL, bootstrap, or writes**. Returns the merged graph\n * alongside the active row and the validation result so a caller can\n * build a `Store` on the correct graph without paying for a second\n * `getActiveSchema` round trip or re-merging.\n *\n * @throws ConfigurationError if no schema has been initialized for\n * `graph.id` (the privileged migration step has not run, or the base\n * tables do not exist on this connection).\n * @throws MigrationError if the persisted schema is behind the code\n * graph — for **any** pending change, safe or breaking. The\n * least-privilege runtime cannot migrate; \"behind\" means the\n * privileged migrator has not yet caught up.\n */\nexport async function loadAndVerifyGraph<G extends GraphDef>(\n backend: GraphBackend,\n graph: G,\n): Promise<\n Readonly<{\n graph: G;\n activeRow: SchemaVersionRow;\n result: SchemaValidationResult;\n }>\n> {\n const activeRow = await readActiveSchemaPure(backend, graph.id);\n const { graph: merged, storedSchema } = mergeStoredGraphExtension(\n graph,\n activeRow,\n );\n\n // Hash short-circuit avoids the serialize + diff walk on the steady-\n // state warm path. A semantic no-op (hash differs but `hasChanges` is\n // false) takes the same return path.\n const storedHash = activeRow.schema_hash;\n const currentHash = await getSchemaHash(merged, activeRow.version + 1);\n if (storedHash !== currentHash) {\n const currentSchema = serializeSchema(merged, activeRow.version + 1);\n const diff = computeSchemaDiff(storedSchema, currentSchema);\n if (diff.hasChanges) {\n throw schemaBehindError(merged.id, activeRow.version, diff);\n }\n }\n\n await backend.assertRuntimeContributionsInitialized?.(merged.id);\n return {\n graph: merged,\n activeRow,\n result: { status: \"unchanged\", version: activeRow.version },\n };\n}\n\nfunction schemaBehindError(\n graphId: string,\n fromVersion: number,\n diff: SchemaDiff,\n): MigrationError {\n const actions = getMigrationActions(diff);\n const qualifier =\n isBackwardsCompatible(diff) ? \"safe auto-migration\" : \"breaking change\";\n return new MigrationError(\n `Schema verification failed for graph \"${graphId}\": ${diff.summary} ` +\n `(${qualifier}). ${actions.length} migration action(s) needed. ` +\n `The least-privilege runtime cannot migrate — run ` +\n `createStoreWithSchema(graph, adminBackend) under a privileged role ` +\n `(after any generated migration SQL, if you manage DDL externally) ` +\n `before attaching with createStore() / createVerifiedStore().`,\n {\n graphId,\n fromVersion,\n toVersion: fromVersion + 1,\n },\n );\n}\n\n/**\n * Verifies the database is at the same schema version as the code\n * graph, **without** running DDL, bootstrapping tables, or writing\n * markers. The runtime-side counterpart of `ensureSchema` for the\n * least-privilege deployment model documented in \"Database roles &\n * least privilege\": `createStoreWithSchema` (run once under a privileged\n * role, optionally after applying generated migration SQL externally) is\n * responsible for advancing the schema; runtimes assert it.\n *\n * @throws ConfigurationError if no schema has been initialized.\n * @throws MigrationError if the persisted schema is behind the code\n * graph by any change (safe or breaking).\n * @throws StoreNotInitializedError if the schema is current but the\n * runtime-contribution markers are missing/stale/failed (the\n * privileged migrator has not materialized strategy-owned storage for\n * this graph on this connection).\n */\nexport async function assertSchemaCurrent<G extends GraphDef>(\n backend: GraphBackend,\n graph: G,\n): Promise<SchemaValidationResult> {\n const { result } = await loadAndVerifyGraph(backend, graph);\n return result;\n}\n\n/**\n * Strict SELECT-only read of the active schema row. Unlike\n * `loadActiveSchemaWithBootstrap`, this never calls `bootstrapTables` —\n * a missing-table error or an absent row both surface as\n * `ConfigurationError` so a least-privilege runtime never attempts DDL\n * it can't run. Real system faults (connection, permission, driver)\n * still propagate as themselves.\n */\nasync function readActiveSchemaPure(\n backend: GraphBackend,\n graphId: string,\n): Promise<SchemaVersionRow> {\n let activeRow: SchemaVersionRow | undefined;\n try {\n activeRow = await backend.getActiveSchema(graphId);\n } catch (error) {\n if (isMissingTableError(error)) {\n throw schemaNotInitializedError(graphId, error);\n }\n throw error;\n }\n if (activeRow === undefined) {\n throw schemaNotInitializedError(graphId);\n }\n return activeRow;\n}\n\nfunction schemaNotInitializedError(\n graphId: string,\n cause?: unknown,\n): ConfigurationError {\n return new ConfigurationError(\n `Cannot verify graph \"${graphId}\": no schema has been initialized. ` +\n `Run createStoreWithSchema(graph, adminBackend) once under a ` +\n `privileged role (which commits the schema_versions row and ` +\n `materializes contribution markers) before attaching with ` +\n `createStore() / createVerifiedStore(). Generated migration SQL ` +\n `creates the tables but does not initialize the schema row.`,\n { graphId },\n {\n cause,\n suggestion:\n \"Run createStoreWithSchema(graph, adminBackend) once under a \" +\n \"privileged role. If you manage DDL externally with drizzle-kit / \" +\n \"generatePostgresMigrationSQL / generateSqliteMigrationSQL, apply \" +\n \"that first, then still run createStoreWithSchema to commit the \" +\n \"schema row and contribution markers.\",\n },\n );\n}\n\n/**\n * Initializes the schema for a new graph.\n *\n * Creates version 1 of the schema and marks it as active. Goes through\n * the same `commitSchemaVersion` primitive as `migrateSchema` so the\n * initial-commit race (two processes booting against an empty database\n * simultaneously) resolves with `StaleVersionError` or idempotent\n * success rather than a raw PK violation.\n *\n * @param backend - The database backend\n * @param graph - The graph definition\n * @returns The created schema version row\n */\nexport async function initializeSchema<G extends GraphDef>(\n backend: GraphBackend,\n graph: G,\n): Promise<SchemaVersionRow> {\n const schema = serializeSchema(graph, 1);\n const hash = await computeSchemaHash(schema);\n\n return backend.commitSchemaVersion({\n graphId: graph.id,\n expected: { kind: \"initial\" },\n version: 1,\n schemaHash: hash,\n schemaDoc: schema,\n });\n}\n\n/**\n * Migrates the schema to match the current graph definition.\n *\n * Creates a new schema version and atomically activates it via the\n * `commitSchemaVersion` backend primitive — insert and activate happen\n * in a single transactional unit with optimistic compare-and-swap on\n * the currently-active version. If another writer has advanced the\n * active version since `currentVersion` was read, this throws\n * `StaleVersionError`; the caller should refetch and retry.\n *\n * @param backend - The database backend\n * @param graph - The current graph definition\n * @param currentVersion - The current active schema version\n * @returns The new version number\n */\nexport async function migrateSchema<G extends GraphDef>(\n backend: GraphBackend,\n graph: G,\n currentVersion: number,\n): Promise<number> {\n const committed = await commitNewSchemaVersion(\n backend,\n graph,\n currentVersion,\n );\n return committed.version;\n}\n\n/**\n * Internal sibling of `migrateSchema` that surfaces the committed\n * `SchemaVersionRow` directly. The public `migrateSchema` keeps its\n * `number`-returning signature for API stability; callers that already\n * own the row (`Store.evolve`, `Store.removeKinds`) use this to skip a\n * post-commit `getActiveSchema` round-trip.\n */\nexport async function commitNewSchemaVersion<G extends GraphDef>(\n backend: GraphBackend,\n graph: G,\n currentVersion: number,\n): Promise<SchemaVersionRow> {\n const newVersion = currentVersion + 1;\n const schema = serializeSchema(graph, newVersion);\n const hash = await computeSchemaHash(schema);\n\n return backend.commitSchemaVersion({\n graphId: graph.id,\n expected: { kind: \"active\", version: currentVersion },\n version: newVersion,\n schemaHash: hash,\n schemaDoc: schema,\n });\n}\n\n/**\n * Rolls back the active schema to a previous version.\n *\n * The target version must already exist in the version history.\n * This does not delete newer versions — it simply switches the active pointer.\n *\n * Uses the `setActiveVersion` backend primitive, which performs the flip\n * atomically with optimistic compare-and-swap on the currently-active\n * version. Concurrent rollbacks or commits surface as\n * `StaleVersionError`.\n *\n * @param backend - The database backend\n * @param graphId - The graph ID\n * @param targetVersion - The version to roll back to\n * @throws MigrationError if the target version does not exist\n * @throws StaleVersionError if another writer changed the active version concurrently\n */\nexport async function rollbackSchema(\n backend: GraphBackend,\n graphId: string,\n targetVersion: number,\n): Promise<void> {\n const activeRow = await backend.getActiveSchema(graphId);\n if (activeRow === undefined) {\n throw new MigrationError(\n `Cannot rollback graph \"${graphId}\": no active schema version exists.`,\n { graphId, fromVersion: 0, toVersion: targetVersion },\n );\n }\n await backend.setActiveVersion({\n graphId,\n expected: { kind: \"active\", version: activeRow.version },\n version: targetVersion,\n });\n}\n\n/**\n * Gets the current active schema for a graph.\n *\n * @param backend - The database backend\n * @param graphId - The graph ID\n * @returns The active schema or undefined if not initialized\n */\nexport async function getActiveSchema(\n backend: GraphBackend,\n graphId: string,\n): Promise<SerializedSchema | undefined> {\n const row = await backend.getActiveSchema(graphId);\n if (row === undefined) return undefined;\n return parseSerializedSchema(row.schema_doc);\n}\n\n/**\n * Checks if a graph's schema has been initialized.\n *\n * @param backend - The database backend\n * @param graphId - The graph ID\n * @returns True if the schema has been initialized\n */\nexport async function isSchemaInitialized(\n backend: GraphBackend,\n graphId: string,\n): Promise<boolean> {\n const row = await backend.getActiveSchema(graphId);\n return row !== undefined;\n}\n\n/**\n * Gets the schema diff between the stored schema and current graph.\n *\n * @param backend - The database backend\n * @param graph - The current graph definition\n * @returns The diff, or undefined if schema not initialized\n */\nexport async function getSchemaChanges<G extends GraphDef>(\n backend: GraphBackend,\n graph: G,\n): Promise<SchemaDiff | undefined> {\n const activeSchema = await backend.getActiveSchema(graph.id);\n if (activeSchema === undefined) return undefined;\n\n const storedSchema = parseSerializedSchema(activeSchema.schema_doc);\n const currentSchema = serializeSchema(graph, activeSchema.version + 1);\n\n return computeSchemaDiff(storedSchema, currentSchema);\n}\n","/**\n * Contextual Validation Utilities\n *\n * Provides Zod validation wrappers that include full context about\n * which entity (node/edge) and operation (create/update) failed.\n *\n * @example\n * ```typescript\n * const props = validateNodeProps(schema, input, {\n * kind: \"Person\",\n * operation: \"create\",\n * });\n * ```\n */\n\nimport { type ZodError, type ZodType } from \"zod\";\n\nimport type { KindEntity } from \"../core/types\";\nimport { ValidationError, type ValidationIssue } from \"./index\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Context for validation operations.\n */\nexport type ValidationContext = Readonly<{\n /** Type of entity being validated */\n entityType: KindEntity;\n /** Kind/type name of the entity */\n kind: string;\n /** Operation being performed */\n operation: \"create\" | \"update\";\n /** Entity ID (for updates) */\n id?: string;\n}>;\n\n// ============================================================\n// Validation Functions\n// ============================================================\n\n/**\n * Converts Zod issues to ValidationIssue format.\n */\nfunction zodIssuesToValidationIssues(error: ZodError): ValidationIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path.join(\".\"),\n message: issue.message,\n code: issue.code,\n }));\n}\n\n/**\n * Builds a descriptive location string for error messages.\n */\nfunction buildLocationString(context: ValidationContext): string {\n if (context.id) {\n return `${context.kind}/${context.id}`;\n }\n return `new ${context.kind}`;\n}\n\n/**\n * Validates props with full context for error messages.\n *\n * @param schema - Zod schema to validate against\n * @param props - Properties to validate\n * @param context - Context about the entity and operation\n * @returns Validated and transformed props\n * @throws ValidationError with full context if validation fails\n *\n * @example\n * ```typescript\n * const validatedProps = validateProps(personSchema, input, {\n * entityType: \"node\",\n * kind: \"Person\",\n * operation: \"create\",\n * });\n * ```\n */\nexport function validateProps<T>(\n schema: ZodType<T>,\n props: unknown,\n context: ValidationContext,\n): T {\n const result = schema.safeParse(props);\n\n if (result.success) {\n return result.data;\n }\n\n const issues = zodIssuesToValidationIssues(result.error);\n const location = buildLocationString(context);\n\n throw new ValidationError(\n `Invalid ${context.entityType} props for ${location}: ${result.error.message}`,\n {\n entityType: context.entityType,\n kind: context.kind,\n operation: context.operation,\n ...(context.id !== undefined && { id: context.id }),\n issues,\n },\n { cause: result.error },\n );\n}\n\n/**\n * Validates node props with full context.\n *\n * Convenience wrapper around validateProps for node operations.\n *\n * @example\n * ```typescript\n * const props = validateNodeProps(schema, input, {\n * kind: \"Person\",\n * operation: \"create\",\n * });\n * ```\n */\nexport function validateNodeProps<T>(\n schema: ZodType<T>,\n props: unknown,\n context: Readonly<{\n kind: string;\n operation: \"create\" | \"update\";\n id?: string;\n }>,\n): T {\n return validateProps(schema, props, {\n entityType: \"node\",\n ...context,\n });\n}\n\n/**\n * Validates edge props with full context.\n *\n * Convenience wrapper around validateProps for edge operations.\n *\n * @example\n * ```typescript\n * const props = validateEdgeProps(schema, input, {\n * kind: \"worksAt\",\n * operation: \"create\",\n * });\n * ```\n */\nexport function validateEdgeProps<T>(\n schema: ZodType<T>,\n props: unknown,\n context: Readonly<{\n kind: string;\n operation: \"create\" | \"update\";\n id?: string;\n }>,\n): T {\n return validateProps(schema, props, {\n entityType: \"edge\",\n ...context,\n });\n}\n\n/**\n * Wraps a Zod error with TypeGraph context.\n *\n * Use this when you've already caught a ZodError and want to\n * convert it to a ValidationError with context.\n *\n * @example\n * ```typescript\n * try {\n * schema.parse(input);\n * } catch (error) {\n * if (error instanceof ZodError) {\n * throw wrapZodError(error, {\n * entityType: \"node\",\n * kind: \"Person\",\n * operation: \"create\",\n * });\n * }\n * throw error;\n * }\n * ```\n */\nexport function wrapZodError(\n error: ZodError,\n context: ValidationContext,\n): ValidationError {\n const issues = zodIssuesToValidationIssues(error);\n const location = buildLocationString(context);\n\n return new ValidationError(\n `Validation failed for ${context.entityType} ${location}: ${error.message}`,\n {\n entityType: context.entityType,\n kind: context.kind,\n operation: context.operation,\n ...(context.id !== undefined && { id: context.id }),\n issues,\n },\n { cause: error },\n );\n}\n\n/**\n * Creates a simple ValidationError without Zod context.\n *\n * Use this for custom validation rules that aren't part of a Zod schema.\n *\n * @example\n * ```typescript\n * if (startDate > endDate) {\n * throw createValidationError(\n * \"Start date must be before end date\",\n * [{ path: \"startDate\", message: \"Must be before endDate\" }],\n * { entityType: \"edge\", kind: \"employment\", operation: \"create\" }\n * );\n * }\n * ```\n */\nexport function createValidationError(\n message: string,\n issues: ValidationIssue[],\n context?: Partial<ValidationContext>,\n): ValidationError {\n return new ValidationError(message, {\n ...(context?.entityType !== undefined && {\n entityType: context.entityType,\n }),\n ...(context?.kind !== undefined && { kind: context.kind }),\n ...(context?.operation !== undefined && { operation: context.operation }),\n ...(context?.id !== undefined && { id: context.id }),\n issues,\n });\n}\n"]}