{"version":3,"sources":["../src/ontology/core-meta-edges.ts","../src/schema/serializer.ts","../src/schema/migration.ts","../src/graph-extension/compiler.ts","../src/graph-extension/ontology-keys.ts","../src/graph-extension/merge.ts","../src/graph-extension/remove.ts","../src/identity/schema-transition.ts","../src/registry/validate-implies.ts","../src/registry/validate-inverse.ts","../src/registry/build-validated.ts","../src/registry/builders.ts","../src/schema/new-schema-version.ts","../src/schema/types.ts","../src/schema/manager.ts"],"names":["META_EDGE_BRAND","META_EDGE_SUB_CLASS_OF","META_EDGE_BROADER","META_EDGE_NARROWER","META_EDGE_RELATED_TO","META_EDGE_EQUIVALENT_TO","META_EDGE_SAME_AS","META_EDGE_DIFFERENT_FROM","META_EDGE_DISJOINT_WITH","META_EDGE_PART_OF","META_EDGE_HAS_PART","META_EDGE_INVERSE_OF","META_EDGE_IMPLIES","canonicalAnnotations","nowIso","LEGACY_GRAPH_EXTENSION_VERSION","createDataKeyedBag","getNodeKinds","captureWherePredicate","ConfigurationError","getEdgeKinds","isEdgeTargetMap","projectTargetKinds","getTypeName","computeClosuresFromOntology","z","sortedReplacer","sha256Hex","canonicalEqual","requireDefined","compareStrings","hasOwnKey","defineNode","compactUndefined","searchable","embedding","ALL_META_EDGE_NAMES","unwrap","validateGraphExtension","defineEdge","mergeGraphAnnotations","autoDeriveVectorIndexes","mergeVectorIndexes","KindNotFoundError","declaration","defineNodeIndex","defineEdgeIndex","KindCollisionError","GraphExtensionUnresolvedEndpointError","isExternalIri","GraphExtensionUnresolvedOntologyEndpointError","RemoveCompileTimeKindError","KindHasReferentsError","separationRebuildRequired","errorChain","isPostgresConcurrentDdlRaceError","resolveWriteFencePlan","requireWriteFence","asCompiledRowsSql","hasAssertionsTouchingKinds","lockRecordedGraphWrite","lockIdentityGraph","lockIdentityEnablementNodes","withRecordedIdentityMutationTarget","purgeAssertionsWithUnregisteredKinds","deleteAssertionsTouchingKinds","rebuildIdentityClosureForContext","registry","KindRegistry","createEmptyClosures","validateOntologyRelations","computeClosuresFromNamedOntology","getEdgeEndpointPairs","NODE_SYSTEM_COLUMN_NAMES","NODE_INDEX_KEY_DIRECTIONS","validateNodeIndexKeyContract","validateEdgeIndexKeysPresence","DatabaseOperationError","freezeDeep","isMissingTableError","MigrationError","resolveGraphVectorSlots","commitWithPreflight","StaleVersionError","assertEdgeMatchIdentityBackendSupport","countSchemaKindRows","createSqlSchema","requireSqlSchema"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,cAAA,CACP,MACA,UAAA,EAea;AACb,EAAA,OAAO,OAAO,MAAA,CAAO;AAAA,IACnB,CAACA,iCAAe,GAAG,IAAA;AAAA,IACnB,IAAA;AAAA,IACA,UAAA,EAAY;AAAA,MACV,UAAA,EAAY,WAAW,UAAA,IAAc,KAAA;AAAA,MACrC,SAAA,EAAW,WAAW,SAAA,IAAa,KAAA;AAAA,MACnC,SAAA,EAAW,WAAW,SAAA,IAAa,KAAA;AAAA,MACnC,SAAS,UAAA,CAAW,OAAA;AAAA,MACpB,WAAW,UAAA,CAAW,SAAA;AAAA,MACtB,aAAa,UAAA,CAAW;AAAA;AAC1B,GACD,CAAA;AACH;AAUA,IAAM,kBAAA,GAAqB,eAAeC,wCAAA,EAAwB;AAAA,EAChE,UAAA,EAAY,IAAA;AAAA,EACZ,SAAA,EAAW,aAAA;AAAA,EACX,WAAA,EAAa;AACf,CAAC,CAAA;AAKM,SAAS,UAAA,CACd,OACA,MAAA,EACkB;AAClB,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,kBAAA;AAAA,IACV,IAAA,EAAM,KAAA;AAAA,IACN,EAAA,EAAI;AAAA,GACN;AACF;AAUA,IAAM,eAAA,GAAkB,eAAeC,mCAAA,EAAmB;AAAA,EACxD,UAAA,EAAY,IAAA;AAAA,EACZ,OAAA,EAASC,oCAAA;AAAA,EACT,SAAA,EAAW,WAAA;AAAA,EACX,WAAA,EAAa;AACf,CAAC,CAAA;AAKM,SAAS,OAAA,CACd,iBACA,cAAA,EACkB;AA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aAAa,IAAA,GAAO,EAAE,GAAG,IAAA,EAAM,SAAA,EAAW,KAAK,WAAA,EAAY;AACzE;AAkBA,eAAsB,iBAAA,CACpB,SACA,KAAA,EACkB;AAClB,EAAA,MAAM,IAAA,GAAO,MAAM,gBAAA,CAAiB,OAAA,EAAS,KAAK,CAAA;AAClD,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,IAAA;AAC/B,EAAA,OAAO,IAAA,CAAK,UAAA;AACd;AA4BA,eAAsB,yBAAA,CACpB,SACA,OAAA,EAC6B;AAC7B,EAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,eAAA,CAAgB,OAAO,CAAA;AACjD,EAAA,OAAO,GAAA,EAAK,OAAA;AACd","file":"chunk-SSDLQPMY.cjs","sourcesContent":["import { type AnyEdgeType, 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/** Type-level compatibility alias retained for migration only. */\nconst sameAsMetaEdge = createMetaEdge(META_EDGE_SAME_AS, {\n  symmetric: true,\n  transitive: true,\n  inference: \"substitution\",\n  description: \"Deprecated type-level equivalence alias\",\n});\n\n/**\n * Creates the deprecated type-level `sameAs` alias of `equivalentTo`.\n *\n * @deprecated Enable `identity: { sameIdAcrossKinds: \"fold\" }` and use the\n * TypeGraph Identity Profile's runtime `store.identity` ledger. The ledger\n * does not perform OWL property substitution or automatic query expansion.\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/** Deprecated decorative type-level non-identity relation. */\nconst differentFromMetaEdge = createMetaEdge(META_EDGE_DIFFERENT_FROM, {\n  symmetric: true,\n  inference: \"constraint\",\n  description: \"Deprecated decorative type-level non-identity relation\",\n});\n\n/**\n * Creates the deprecated decorative type-level `differentFrom` relation.\n *\n * @deprecated Enable `identity: { sameIdAcrossKinds: \"fold\" }` and use the\n * TypeGraph Identity Profile's runtime `store.identity` ledger. The ledger\n * does not perform OWL property substitution or automatic query expansion.\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(\n  edgeA: AnyEdgeType,\n  edgeB: AnyEdgeType,\n): 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(\n  edgeA: AnyEdgeType,\n  edgeB: AnyEdgeType,\n): 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  // eslint-disable-next-line @typescript-eslint/no-deprecated -- compatibility member until the next major\n  sameAs,\n  // eslint-disable-next-line @typescript-eslint/no-deprecated -- compatibility member until the next major\n  differentFrom,\n  disjointWith,\n  partOf,\n  hasPart,\n  inverseOf,\n  implies,\n} as const;\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 { captureWherePredicate } from \"../constraints\";\nimport {\n  getEdgeKinds,\n  getNodeKinds,\n  type GraphDef,\n} from \"../core/define-graph\";\nimport { isEdgeTargetMap, projectTargetKinds } from \"../core/edge-endpoints\";\nimport { canonicalAnnotations } from \"../core/json-value\";\nimport {\n  type EdgeRegistration,\n  type NodeRegistration,\n  type NullCheckOp,\n  type UniqueConstraint,\n} from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\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 { createDataKeyedBag } from \"../utils/object\";\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  const annotations = canonicalAnnotations(graph.annotations);\n\n  return {\n    graphId: graph.id,\n    ...(annotations === undefined ? {} : { annotations }),\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    ...(graph.identity === undefined ? {} : { identity: graph.identity }),\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\nconst SERIALIZED_SCHEMA_TOP_LEVEL_KEYS = new Set([\n  \"graphId\",\n  \"annotations\",\n  \"version\",\n  \"generatedAt\",\n  \"nodes\",\n  \"edges\",\n  \"ontology\",\n  \"defaults\",\n  \"identity\",\n  \"indexes\",\n  \"extension\",\n  \"deprecatedKinds\",\n]);\n\n/**\n * Serializes a graph while retaining top-level fields authored by a newer\n * schema-document format.\n *\n * Known fields always come from the current graph, including omission of\n * optional slices. Only fields this version does not own are carried forward.\n * Every recommit path uses this function so parsing a newer document can never\n * turn a later, otherwise-valid schema write into silent metadata loss.\n */\nexport function serializeSchemaPreservingUnknownFields<G extends GraphDef>(\n  graph: G,\n  version: number,\n  previous: SerializedSchema,\n): SerializedSchema {\n  const unknownFields = Object.fromEntries(\n    Object.entries(previous).filter(\n      ([key]) => !SERIALIZED_SCHEMA_TOP_LEVEL_KEYS.has(key),\n    ),\n  );\n  return { ...unknownFields, ...serializeSchema(graph, version) };\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// 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\n/**\n * Canonicalizes a single index declaration to its serialized form (see\n * {@link serializeIndexes} for the canonical-form rules). Exported so\n * consumers that hash a declaration directly — e.g.\n * `computeIndexSignature` in `store/materialize-indexes.ts` — can\n * normalize it first, rather than hashing the raw object and risking a\n * present-but-canonically-absent field (like an explicit `keySystemColumns:\n * []`) producing a different hash than the omitted form.\n */\nexport function 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    // `method: \"btree\"` is canonicalized by absence, like `origin` below.\n    ...(declaration.method === undefined ? {} : { method: declaration.method }),\n    // `keySystemColumns: []` is canonicalized by absence, same rule. Checked\n    // against length, not just `undefined` — `NodeIndexDeclaration` is\n    // exported and `defineGraph` accepts pre-built declarations directly\n    // (bypassing `defineNodeIndex`'s own canonicalization and the\n    // `nodeIndexDeclarationZod` parse boundary, which rejects an explicit\n    // `[]` via `.min(1)`), so an in-memory declaration can still carry a\n    // present-but-empty array that must canonicalize to absent here.\n    ...((\n      declaration.keySystemColumns === undefined ||\n      declaration.keySystemColumns.length === 0\n    ) ?\n      {}\n    : { keySystemColumns: declaration.keySystemColumns }),\n    ...(declaration.keys === undefined || declaration.keys.length === 0 ?\n      {}\n    : { keys: declaration.keys }),\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    // `method: \"btree\"` is canonicalized by absence, like `origin`.\n    ...(declaration.method === undefined ? {} : { method: declaration.method }),\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 = createDataKeyedBag<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  // Spread at the boundary: this becomes `SerializedSchema.nodes`, which\n  // `serializeSchema` returns. See `createDataKeyedBag` in ../utils/object.ts.\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 * Capture runs through `captureWherePredicate` — the same builder constraint\n * EVALUATION and definition-time VALIDATION use — rather than a second proxy\n * spelled here. Two builders answering the same question is how a persisted\n * `where` drifts from the one the store enforces.\n *\n * No field validation happens here: `defineGraph` refuses an undeclared `where`\n * field before a constraint can be registered (`assertWhereFieldDeclared`), and\n * `validateGraphExtension` refuses the same thing for document-declared kinds,\n * so by the time a graph is serialized its clauses are already declared-field\n * clauses. Re-checking would make persistence a second owner of a decision that\n * has one.\n */\nfunction serializeWherePredicate(\n  whereFunction: (builder: PredicateBuilder) => SerializedPredicate,\n): string {\n  const predicate = captureWherePredicate(whereFunction);\n  if (predicate === undefined) {\n    throw new ConfigurationError(\n      `A unique constraint's \\`where\\` callback did not return a predicate, so it cannot be persisted.`,\n      {},\n      {\n        suggestion: `Return a field predicate, e.g. \\`where: (fields) => fields.someField.isNotNull()\\`.`,\n      },\n    );\n  }\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 = createDataKeyedBag<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  // Spread at the boundary: this becomes `SerializedSchema.edges`.\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  const isMap = isEdgeTargetMap(registration.to);\n  const toKinds =\n    isMap ?\n      projectTargetKinds(registration.to).toSorted()\n    : registration.to.map((node) => node.kind);\n\n  let targetKindsBySource: Record<string, readonly string[]> | undefined;\n  if (isMap) {\n    const map = createDataKeyedBag<readonly string[]>();\n    for (const [sourceKind, targets] of Object.entries(registration.to)) {\n      map[sourceKind] = targets.map((t) => t.kind).toSorted();\n    }\n    targetKindsBySource = { ...map };\n  }\n\n  return {\n    kind: edge.kind,\n    fromKinds: registration.from.map((node) => node.kind),\n    toKinds,\n    ...(targetKindsBySource === undefined ? {} : { targetKindsBySource }),\n    properties: serializeZodSchema(edge.schema),\n    cardinality: registration.cardinality ?? \"many\",\n    endpointExistence: registration.endpointExistence ?? \"notDeleted\",\n    ...(registration.matchIdentity === undefined ?\n      {}\n    : {\n        matchIdentity: {\n          name: registration.matchIdentity.name,\n          fields: [...registration.matchIdentity.fields],\n        },\n      }),\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  // Data-keyed: meta-edge names.\n  const metaEdges = createDataKeyedBag<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: { ...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  // Data-keyed: the map's keys are kind / meta-edge names.\n  const result = createDataKeyedBag<readonly string[]>();\n  for (const [key, values] of map) {\n    result[key] = [...values];\n  }\n  // Spread at the boundary: the closures land in the returned\n  // `SerializedOntology`. See `createDataKeyedBag` in ../utils/object.ts.\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  return Object.fromEntries(map);\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 * The schema-version slot used only to serialize a graph for its\n * {@link getGraphDefinitionHash}. The value is written into the serialized\n * document but {@link computeSchemaHash} deliberately excludes `version` (and\n * `generatedAt`), so the digest is blind to it.\n */\nconst DEFINITION_HASH_VERSION = 1;\n\n/**\n * Deterministic, version-blind hash of a graph DEFINITION.\n *\n * A durable working copy must attest the caller's fork-time definition\n * identity even when it committed no schema row: the identity of a graph\n * definition does not depend on which schema version it happened to be\n * persisted under. This returns exactly the schema-content digest\n * {@link getSchemaHash} produces, at a fixed version slot, so two references\n * to the same definition hash identically regardless of the version argument\n * (which {@link computeSchemaHash} excludes) — and a graph that reuses another\n * graph's id but declares different nodes/edges/constraints hashes\n * differently.\n */\nexport async function getGraphDefinitionHash(\n  graph: GraphDef,\n): Promise<SchemaHash> {\n  return getSchemaHash(graph, DEFINITION_HASH_VERSION);\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.identity === undefined ? {} : { identity: schema.identity }),\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 * 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 { compareStrings } from \"../utils/compare\";\nimport { createDataKeyedBag, hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\nimport { canonicalEqual, sortedReplacer } from \"./canonical\";\nimport {\n  type JsonSchema,\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/** A durable graph-level Operational Identity capability change. */\nexport type IdentityChange = Readonly<{\n  type: ChangeType;\n  severity: ChangeSeverity;\n  details: string;\n}>;\n\n/** A safe metadata-only change to graph-scoped annotations. */\nexport type GraphAnnotationsChange = Readonly<{\n  type: ChangeType;\n  severity: \"safe\";\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  /** Version of the schema being compared from. */\n  fromVersion: number;\n\n  /**\n   * Version of the schema being compared to. For `getSchemaChanges()`, this\n   * is the version a commit would produce and equals `fromVersion` when\n   * `hasChanges` is false. Direct `computeSchemaDiff()` calls preserve the\n   * supplied after-schema version.\n   */\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  /** Change to the graph-level identity capability, if any. */\n  identity?: IdentityChange;\n\n  /** Change to consumer-owned graph-scoped annotations, if any. */\n  annotations?: GraphAnnotationsChange;\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 identityChange = diffIdentity(before.identity, after.identity);\n  const annotationsChange = diffGraphAnnotations(\n    before.annotations,\n    after.annotations,\n  );\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 =\n    allChanges.some((change) => change.severity === \"breaking\") ||\n    identityChange?.severity === \"breaking\";\n  const hasChanges =\n    allChanges.length > 0 ||\n    identityChange !== undefined ||\n    annotationsChange !== undefined ||\n    extensionChange !== undefined ||\n    deprecatedKindsChange !== undefined;\n\n  const summary = generateSummary(\n    nodeChanges,\n    edgeChanges,\n    ontologyChanges,\n    identityChange,\n    annotationsChange,\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    ...(identityChange === undefined ? {} : { identity: identityChange }),\n    ...(annotationsChange === undefined ?\n      {}\n    : { annotations: annotationsChange }),\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\nfunction diffGraphAnnotations(\n  before: SerializedSchema[\"annotations\"],\n  after: SerializedSchema[\"annotations\"],\n): GraphAnnotationsChange | undefined {\n  if (canonicalEqual(before ?? {}, after ?? {})) return undefined;\n  return {\n    type:\n      before === undefined ? \"added\"\n      : after === undefined ? \"removed\"\n      : \"modified\",\n    severity: \"safe\",\n    details: \"Graph annotations changed\",\n  };\n}\n\nfunction diffIdentity(\n  before: SerializedSchema[\"identity\"],\n  after: SerializedSchema[\"identity\"],\n): IdentityChange | undefined {\n  if (before === undefined && after === undefined) return;\n  if (before === undefined) {\n    return {\n      type: \"added\",\n      severity: \"safe\",\n      details: \"Operational Identity enabled\",\n    };\n  }\n  if (after === undefined) {\n    return {\n      type: \"removed\",\n      severity: \"breaking\",\n      details: \"Operational Identity disabled\",\n    };\n  }\n  if (before.sameIdAcrossKinds === after.sameIdAcrossKinds) return;\n  // A fold<->ignore flip rewrites the materialized identity closure and\n  // changes every areSame/membersOf/includeIdentityMembers answer against\n  // existing data — a read-semantics change, not a mechanical migration.\n  // Classified `breaking` (the same severity as identity removal, just\n  // above) so it cannot auto-migrate silently: it requires the same\n  // explicit `migrateSchema()` opt-in as any other breaking change.\n  return {\n    type: \"modified\",\n    severity: \"breaking\",\n    details:\n      `Operational Identity sameIdAcrossKinds changed from ` +\n      `\"${before.sameIdAcrossKinds}\" to \"${after.sameIdAcrossKinds}\"`,\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 = requireDefined(before[name]);\n      const nodeAfter = requireDefined(after[name]);\n      const nodeChanges = diffNodeDef(name, nodeBefore, nodeAfter);\n      changes.push(...nodeChanges);\n    }\n  }\n\n  return changes;\n}\n\n/**\n * JSON-Schema keywords whose array value is semantically a *set*: `required`\n * lists which properties must be present, `enum` lists which values are\n * allowed. Reordering either changes nothing a validator — or a stored row —\n * can observe, so a reordering must not read as a schema change.\n *\n * Other arrays are deliberately left in order: `prefixItems` is positional,\n * and composition members (`allOf` / `anyOf` / `oneOf`) can carry\n * order-dependent evaluation semantics.\n */\nconst SET_VALUED_KEYWORDS: ReadonlySet<string> = new Set([\"required\", \"enum\"]);\n\n/**\n * Keywords whose value is a subschema, or an array of subschemas. Recursion is\n * an **allowlist**: anything not named here is preserved verbatim.\n *\n * That direction matters. Recursing by default would apply schema semantics to\n * values that are not schemas — instance data (`default`, `const`, `examples`)\n * and arbitrary extension keys, which Zod's `.meta()` merges straight into the\n * generated JSON Schema. A key merely *named* `required` inside one of those\n * would then be sorted, silently normalizing away a real change. Failing the\n * other way is safe: an unrecognized schema-valued keyword is left unsorted, so\n * a reordering inside it reads as a change rather than being hidden.\n */\nconst SCHEMA_VALUED_KEYWORDS: ReadonlySet<string> = new Set([\n  \"additionalProperties\",\n  \"allOf\",\n  \"anyOf\",\n  \"contains\",\n  \"contentSchema\",\n  \"else\",\n  \"if\",\n  \"items\",\n  \"not\",\n  \"oneOf\",\n  \"prefixItems\",\n  \"propertyNames\",\n  \"then\",\n  \"unevaluatedItems\",\n  \"unevaluatedProperties\",\n]);\n\n/**\n * Keywords holding a *map of subschemas keyed by user-chosen names*. Their keys\n * are property names, not keywords, so a property called `default` or `enum`\n * must not be read as the keyword of the same name — its value is an ordinary\n * subschema and still needs normalizing.\n */\nconst SUBSCHEMA_MAP_KEYWORDS: ReadonlySet<string> = new Set([\n  \"properties\",\n  \"patternProperties\",\n  \"dependentSchemas\",\n  \"$defs\",\n  \"definitions\",\n]);\n\n/**\n * Maps a property name to the set of property names it requires. User-keyed\n * like {@link SUBSCHEMA_MAP_KEYWORDS}, but each value is a set of names rather\n * than a subschema.\n */\nconst DEPENDENT_REQUIRED_KEYWORD = \"dependentRequired\";\n\nfunction canonicalKey(value: unknown): string {\n  return JSON.stringify(value, sortedReplacer);\n}\n\nfunction sortedByCanonicalForm(items: readonly unknown[]): readonly unknown[] {\n  // `compareStrings`, not `localeCompare`: the ordering has to be identical in\n  // every process that diffs this schema, and locale-aware collation varies\n  // with the host's ICU configuration.\n  return items.toSorted((left, right) =>\n    compareStrings(canonicalKey(left), canonicalKey(right)),\n  );\n}\n\n/**\n * Recursively order-normalizes {@link SET_VALUED_KEYWORDS} arrays so that a\n * pure reordering compares equal.\n *\n * Deliberately *not* folded into `canonicalEqual` / `sortedReplacer`: that\n * canonical form also feeds `computeSchemaHash`, and normalizing arrays there\n * would change the hash of every schema already committed to a database.\n * This normalization is scoped to diff comparison only.\n */\nfunction orderNormalizedSchema(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map((item) => orderNormalizedSchema(item));\n  }\n  if (value !== null && typeof value === \"object\") {\n    const normalized = createDataKeyedBag<unknown>();\n    for (const [key, entry] of Object.entries(value)) {\n      normalized[key] = normalizedKeywordValue(key, entry);\n    }\n    return normalized;\n  }\n  return value;\n}\n\n/**\n * Normalizes one keyword's value according to what that keyword *holds*.\n *\n * The distinction matters: descending into a keyword blindly would apply\n * schema semantics to instance data, so a reordered array inside a `default`\n * (or inside an `enum` member) would be silently treated as unchanged.\n */\nfunction normalizedKeywordValue(key: string, value: unknown): unknown {\n  if (SET_VALUED_KEYWORDS.has(key) && Array.isArray(value)) {\n    // Order-normalize the set itself, but leave each member alone: `enum`\n    // members are instance values and `required` members are plain names.\n    return sortedByCanonicalForm(value);\n  }\n  if (SUBSCHEMA_MAP_KEYWORDS.has(key)) return normalizedSubschemaMap(value);\n  if (key === DEPENDENT_REQUIRED_KEYWORD) {\n    return normalizedDependentRequired(value);\n  }\n  if (SCHEMA_VALUED_KEYWORDS.has(key)) return orderNormalizedSchema(value);\n  // Everything else is preserved verbatim: annotations (`title`), instance\n  // data (`default`, `const`, `examples`), and unknown extension keys. See\n  // {@link SCHEMA_VALUED_KEYWORDS} for why recursion is an allowlist.\n  return value;\n}\n\n/** Order-normalizes each name set in a `dependentRequired` map. */\nfunction normalizedDependentRequired(value: unknown): unknown {\n  if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n    return value;\n  }\n  const normalized = createDataKeyedBag<unknown>();\n  for (const [name, required] of Object.entries(value)) {\n    normalized[name] =\n      Array.isArray(required) ? sortedByCanonicalForm(required) : required;\n  }\n  return normalized;\n}\n\n/**\n * Normalizes a map of subschemas without treating its user-chosen keys as\n * keywords — so a property named `default` is still normalized as the\n * subschema it is.\n */\nfunction normalizedSubschemaMap(value: unknown): unknown {\n  if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n    return orderNormalizedSchema(value);\n  }\n  const normalized = createDataKeyedBag<unknown>();\n  for (const [name, subschema] of Object.entries(value)) {\n    normalized[name] = orderNormalizedSchema(subschema);\n  }\n  return normalized;\n}\n\n/**\n * Whether two property JSON-Schemas are the same schema. Insensitive to the\n * order of set-valued keywords, so restating a kind with its fields declared\n * in a different order is correctly a no-op rather than a \"modified\" kind that\n * forces a migration.\n */\nfunction propertySchemasEqual(before: unknown, after: unknown): boolean {\n  return canonicalEqual(\n    orderNormalizedSchema(before),\n    orderNormalizedSchema(after),\n  );\n}\n\n/**\n * Endpoint kind lists are sets — the order edge endpoints are declared in\n * carries no meaning.\n */\nfunction getSerializedEdgePairs(edge: SerializedEdgeDef): ReadonlySet<string> {\n  const pairs = new Set<string>();\n  if (edge.targetKindsBySource === undefined) {\n    for (const fromKind of edge.fromKinds) {\n      for (const toKind of edge.toKinds) {\n        pairs.add(`${fromKind}\\0${toKind}`);\n      }\n    }\n  } else {\n    for (const [sourceKind, targetKinds] of Object.entries(\n      edge.targetKindsBySource,\n    )) {\n      for (const targetKind of targetKinds) {\n        pairs.add(`${sourceKind}\\0${targetKind}`);\n      }\n    }\n  }\n  return pairs;\n}\n\nfunction endpointKindsEqual(\n  before: readonly string[] | undefined,\n  after: readonly string[] | undefined,\n): boolean {\n  return canonicalEqual(before?.toSorted(), after?.toSorted());\n}\n\nfunction targetKindsBySourceEqual(\n  before: Readonly<Record<string, readonly string[]>> | undefined,\n  after: Readonly<Record<string, readonly string[]>> | undefined,\n): boolean {\n  if (before === undefined && after === undefined) return true;\n  if (before === undefined || after === undefined) return false;\n  const beforeKeys = Object.keys(before).toSorted();\n  const afterKeys = Object.keys(after).toSorted();\n  if (!canonicalEqual(beforeKeys, afterKeys)) return false;\n  for (const key of beforeKeys) {\n    if (!endpointKindsEqual(before[key], after[key])) return false;\n  }\n  return true;\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 (!propertySchemasEqual(before.properties, after.properties)) {\n    const { severity, details } = classifyPropertyChanges(\n      name,\n      before.properties,\n      after.properties,\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 * A comparable token for a property's JSON-Schema type. A change here\n * (`string` → `number`, or scalar → union / enum / const) means existing\n * JSON-encoded props no longer satisfy the declared type, which no data-free\n * migration can reconcile.\n */\nfunction propertyTypeSignature(schema: JsonSchema): string {\n  if (schema.type !== undefined) return JSON.stringify(schema.type);\n  if (schema.const !== undefined) return \"const\";\n  if (schema.enum !== undefined) return \"enum\";\n  if (schema.anyOf !== undefined) return \"anyOf\";\n  if (schema.oneOf !== undefined) return \"oneOf\";\n  if (schema.allOf !== undefined) return \"allOf\";\n  return \"unknown\";\n}\n\n/**\n * Non-constraining JSON-Schema keywords: changing them cannot invalidate an\n * existing stored value, so a diff limited to these is safe.\n */\nconst NON_CONSTRAINING_KEYWORDS = new Set([\n  \"description\",\n  \"title\",\n  \"default\",\n  \"$schema\",\n]);\n\n/** A copy of `schema` with the non-constraining keywords removed. */\nfunction stripSchemaMetadata(schema: JsonSchema): Record<string, unknown> {\n  // Data-keyed: JSON-Schema keywords parsed out of the persisted document.\n  const stripped = createDataKeyedBag<unknown>();\n  for (const [key, value] of Object.entries(schema)) {\n    if (!NON_CONSTRAINING_KEYWORDS.has(key)) stripped[key] = value;\n  }\n  return stripped;\n}\n\nfunction isObjectSchema(schema: JsonSchema): boolean {\n  return schema.type === \"object\" || schema.properties !== undefined;\n}\n\n/**\n * Whether replacing property schema `before` with `after` can invalidate an\n * existing stored value — i.e. whether the change is breaking. Deliberately\n * conservative: it returns `false` (safe) only for changes it can prove are\n * non-breaking, and `true` for everything else.\n *\n * Provably safe: a metadata-only change; an object whose nested change is itself\n * safe (recursively) with no removed or newly-required nested property (so\n * adding an optional nested field stays safe). Everything else — a changed type\n * token, an array whose items changed, an enum/const change, a composition\n * change, or any constraint change on a scalar — is treated as breaking. This\n * mirrors how the top-level property diff classifies node/edge properties, so a\n * change nested inside an object, array, or enum is caught the same way a\n * top-level one is (rather than passing as a non-blocking warning and\n * auto-migrating over rows that no longer satisfy the schema).\n */\nfunction isBreakingPropertyChange(\n  before: JsonSchema,\n  after: JsonSchema,\n): boolean {\n  if (\n    propertySchemasEqual(\n      stripSchemaMetadata(before),\n      stripSchemaMetadata(after),\n    )\n  ) {\n    return false;\n  }\n  if (propertyTypeSignature(before) !== propertyTypeSignature(after)) {\n    return true;\n  }\n  if (isObjectSchema(before) && isObjectSchema(after)) {\n    return isBreakingObjectSchemaChange(before, after);\n  }\n  // Same top-level token, but a constraining change the recursion above does not\n  // model (array items, enum/const values, composition members, scalar bounds).\n  // Cannot prove it is a loosening, so treat it as breaking.\n  return true;\n}\n\n/** Recursive breaking-change check for two object JSON-Schemas. */\nfunction isBreakingObjectSchemaChange(\n  before: JsonSchema,\n  after: JsonSchema,\n): boolean {\n  const beforeProps = before.properties ?? {};\n  const afterProps = after.properties ?? {};\n  const beforeRequired = new Set(before.required);\n  const afterRequired = new Set(after.required);\n\n  for (const key of Object.keys(beforeProps)) {\n    if (!hasOwnKey(afterProps, key)) return true; // nested property removed\n  }\n  for (const key of afterRequired) {\n    if (!beforeRequired.has(key)) return true; // nested property newly required\n  }\n  for (const [key, beforeChild] of Object.entries(beforeProps)) {\n    const afterChild = afterProps[key];\n    if (afterChild === undefined) continue; // removal already handled above\n    if (isBreakingPropertyChange(beforeChild, afterChild)) return true;\n  }\n  return false; // only additive optional / provably-safe nested changes\n}\n\n/**\n * Classifies a change to a node/edge's property JSON-Schema. Props are stored\n * as a single JSON column with no per-field DDL, so the schema is enforced only\n * at the application layer — a diff-based migration cannot rewrite existing\n * rows. A change is therefore only ever **breaking** or **safe**:\n *\n *  - **breaking** when existing rows can no longer be proven to satisfy the new\n *    schema and no data-free migration fixes it: a removed property, a newly\n *    required property, or a shared property whose schema changed in a way that\n *    is not provably a loosening (a changed type token, a changed array item\n *    schema, an enum/const/composition change, a scalar constraint change, or a\n *    breaking change nested inside an object). `ensureSchema` refuses to\n *    auto-migrate these (throws `MigrationError` with the data actions).\n *  - **safe** when the only changes are new optional properties, metadata-only\n *    edits, or additive optional fields nested inside an object.\n *\n * Deliberately conservative: a change is called safe only when\n * {@link isBreakingPropertyChange} can prove it non-breaking, so an ambiguous\n * change (e.g. a scalar → union *widening*, or a same-type constraint change)\n * is reported breaking — a false positive the operator acknowledges — rather\n * than risk auto-migrating over rows that no longer satisfy the schema. There\n * is no \"warning\" bucket: an unproven change blocks rather than silently\n * migrating.\n */\nfunction classifyPropertyChanges(\n  kind: string,\n  before: JsonSchema,\n  after: JsonSchema,\n): { severity: ChangeSeverity; details: string } {\n  const beforeProps = before.properties ?? {};\n  const afterProps = after.properties ?? {};\n  const beforeRequired = new Set(before.required);\n  const afterRequired = new Set(after.required);\n\n  const removed = Object.keys(beforeProps).filter(\n    (property) => !hasOwnKey(afterProps, property),\n  );\n  const added = Object.keys(afterProps).filter(\n    (property) => !hasOwnKey(beforeProps, property),\n  );\n  const newRequired = [...afterRequired].filter(\n    (property) => !beforeRequired.has(property),\n  );\n\n  // A shared property whose schema changed in a way that can invalidate existing\n  // rows (type/shape change, a breaking nested/array/enum/constraint change).\n  const breakingProps: string[] = [];\n  for (const [property, beforeProperty] of Object.entries(beforeProps)) {\n    const afterProperty = afterProps[property];\n    if (afterProperty === undefined) continue; // removed — handled below\n    if (canonicalEqual(beforeProperty, afterProperty)) continue; // unchanged\n    if (isBreakingPropertyChange(beforeProperty, afterProperty)) {\n      breakingProps.push(property);\n    }\n  }\n\n  if (removed.length > 0) {\n    return {\n      severity: \"breaking\",\n      details: `Properties removed from \"${kind}\": ${removed.join(\", \")}`,\n    };\n  }\n  if (breakingProps.length > 0) {\n    return {\n      severity: \"breaking\",\n      details: `Property schemas changed incompatibly in \"${kind}\": ${breakingProps.join(\", \")}`,\n    };\n  }\n  if (newRequired.length > 0) {\n    return {\n      severity: \"breaking\",\n      details: `New required properties in \"${kind}\": ${newRequired.join(\", \")}`,\n    };\n  }\n  if (added.length > 0) {\n    return {\n      severity: \"safe\",\n      details: `Properties added to \"${kind}\": ${added.join(\", \")}`,\n    };\n  }\n  // Only provably non-breaking property changes remain (metadata, additive\n  // optional nested fields, a widened/loosened shape the checks above cleared).\n  return { severity: \"safe\", details: `Properties changed in \"${kind}\"` };\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 = requireDefined(before[name]);\n      const edgeAfter = requireDefined(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 (!endpointKindsEqual(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 (!endpointKindsEqual(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 targetKindsBySource\n  if (\n    !targetKindsBySourceEqual(\n      before.targetKindsBySource,\n      after.targetKindsBySource,\n    )\n  ) {\n    const beforePairs = getSerializedEdgePairs(before);\n    const afterPairs = getSerializedEdgePairs(after);\n    const removedPairs: string[] = [];\n    for (const pair of beforePairs) {\n      if (!afterPairs.has(pair)) {\n        const [from, to] = pair.split(\"\\0\");\n        removedPairs.push(`(${from} -> ${to})`);\n      }\n    }\n\n    const isBreaking = removedPairs.length > 0;\n    const details =\n      isBreaking ?\n        `targetKindsBySource narrowed for \"${name}\"; removed pairs: [${removedPairs.join(\", \")}]`\n      : `targetKindsBySource changed for \"${name}\"`;\n\n    changes.push({\n      type: \"modified\",\n      kind: name,\n      severity: isBreaking ? \"breaking\" : \"warning\",\n      details,\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  if (!matchIdentitiesEqual(before.matchIdentity, after.matchIdentity)) {\n    const details =\n      before.matchIdentity === undefined ?\n        `Match identity added to \"${name}\"; existing edge data must be rekeyed`\n      : after.matchIdentity === undefined ?\n        `Match identity removed from \"${name}\"; existing edge data must be rekeyed`\n      : `Match identity changed for \"${name}\"; existing edge data must be rekeyed`;\n    changes.push({\n      type: \"modified\",\n      kind: name,\n      severity: \"breaking\",\n      details,\n      before,\n      after,\n    });\n  }\n\n  // Check properties\n  if (!propertySchemasEqual(before.properties, after.properties)) {\n    const { severity, details } = classifyPropertyChanges(\n      name,\n      before.properties,\n      after.properties,\n    );\n    changes.push({\n      type: \"modified\",\n      kind: name,\n      severity,\n      details,\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\nexport function matchIdentitiesEqual(\n  before: SerializedEdgeDef[\"matchIdentity\"],\n  after: SerializedEdgeDef[\"matchIdentity\"],\n): boolean {\n  if (before === undefined || after === undefined) return before === after;\n  if (\n    before.name !== after.name ||\n    before.fields.length !== after.fields.length\n  ) {\n    return false;\n  }\n  const beforeFields = before.fields.toSorted();\n  const afterFields = after.fields.toSorted();\n  return beforeFields.every((field, index) => field === afterFields[index]);\n}\n\nfunction isMatchIdentityChange(change: EdgeChange): boolean {\n  return (\n    change.type === \"modified\" &&\n    change.severity === \"breaking\" &&\n    change.before !== undefined &&\n    change.after !== undefined &&\n    !matchIdentitiesEqual(\n      change.before.matchIdentity,\n      change.after.matchIdentity,\n    )\n  );\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  identityChange: IdentityChange | undefined,\n  annotationsChange: GraphAnnotationsChange | undefined,\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  if (identityChange !== undefined) {\n    parts.push(`Identity: ${identityChange.type}`);\n  }\n\n  if (annotationsChange !== undefined) {\n    parts.push(`Graph annotations: ${annotationsChange.type}`);\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 * How a proposed graph relates to the committed schema.\n *\n * - `identical` — a semantic no-op; committing it changes nothing.\n * - `additive` — changes exist and are all backwards compatible.\n * - `incompatible` — at least one breaking change; needs a deliberate\n *   migration decision.\n */\nexport type SchemaChangeClassification =\n  \"identical\" | \"additive\" | \"incompatible\";\n\n/**\n * Classifies a schema diff into the three outcomes a caller actually branches\n * on. Pure — no I/O, no DDL. Pair with `getSchemaChanges(backend, graph)` (or\n * `store.schemaChanges()`) to pre-flight a proposal *before* touching a\n * privileged, migration-gated path.\n */\nexport function classifySchemaChanges(\n  diff: SchemaDiff,\n): SchemaChangeClassification {\n  if (!diff.hasChanges) return \"identical\";\n  return diff.hasBreakingChanges ? \"incompatible\" : \"additive\";\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    if (isMatchIdentityChange(change)) {\n      actions.push(`REKEY edge data for \"${change.kind}\": ${change.details}`);\n    }\n  }\n\n  if (diff.identity !== undefined) {\n    switch (diff.identity.type) {\n      case \"added\": {\n        actions.push(\n          `BUILD Operational Identity closure: ${diff.identity.details} ` +\n            `(materializes the closure table, running a same-id fold scan ` +\n            `when sameIdAcrossKinds is \"fold\")`,\n        );\n        break;\n      }\n      case \"modified\": {\n        actions.push(\n          `REBUILD Operational Identity closure: ${diff.identity.details} ` +\n            `(every areSame/membersOf/includeIdentityMembers answer is ` +\n            `recomputed under the new profile)`,\n        );\n        break;\n      }\n      case \"removed\": {\n        actions.push(\n          `DISABLE Operational Identity: ${diff.identity.details} (the ` +\n            `materialized closure is left in place, unread; the identity ` +\n            `API becomes unavailable)`,\n        );\n        break;\n      }\n      case \"renamed\": {\n        // Unreachable: `diffIdentity` never emits \"renamed\" — identity is a\n        // graph-level capability, not a named entity that can be renamed.\n        // Handled only so the switch stays exhaustive over `ChangeType`.\n        break;\n      }\n    }\n  }\n\n  return actions;\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, createDataKeyedBag } 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:\n    | readonly (NodeType | string)[]\n    | Readonly<Record<string, 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  let to:\n    | readonly (NodeType | string)[]\n    | Readonly<Record<string, readonly (NodeType | string)[]>>;\n  if (Array.isArray(document.to)) {\n    to = Object.freeze(\n      (document.to as readonly string[]).map(\n        (name: string): NodeType | string => nodeTypeByName.get(name) ?? name,\n      ),\n    );\n  } else {\n    const map = createDataKeyedBag<readonly (NodeType | string)[]>();\n    for (const [sourceKind, targets] of Object.entries(document.to)) {\n      map[sourceKind] = Object.freeze(\n        (targets as readonly string[]).map(\n          (name: string): NodeType | string => nodeTypeByName.get(name) ?? name,\n        ),\n      );\n    }\n    to = Object.freeze({ ...map });\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,\n    }),\n  );\n}\n\nfunction buildObjectSchema(\n  properties: Readonly<Record<string, ExtensionPropertyType>>,\n): ZodObject<ZodRawShape> {\n  // Data-keyed: `propertyName` comes from the extension document.\n  const shape = createDataKeyedBag<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    // Not a data-keyed bag: `props` is the predicate-builder surface, a total\n    // Proxy whose `get` trap answers every declared field name, so a\n    // prototype-named field cannot fall through to `Object.prototype` here.\n    // (An own-key read would be wrong against a get-trap-only Proxy.)\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 { mergeGraphAnnotations } from \"../core/json-value\";\nimport {\n  type AnyEdgeType,\n  type EdgeRegistration,\n  type EdgeTargetMap,\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 { META_EDGE_IMPLIES, META_EDGE_INVERSE_OF } from \"../ontology/constants\";\nimport { isExternalIri } from \"../ontology/external-iri\";\nimport { type OntologyRelation } from \"../ontology/types\";\nimport { canonicalEqual } from \"../schema/canonical\";\nimport {\n  compactUndefined,\n  createDataKeyedBag,\n  hasOwnKey,\n} from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\nimport { unwrap } from \"../utils/result\";\nimport { compileGraphExtension } from \"./compiler\";\nimport {\n  GraphExtensionUnresolvedEndpointError,\n  GraphExtensionUnresolvedOntologyEndpointError,\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  // Kind-keyed, and `isValidKindName` admits `__proto__`: a `{}` accumulator\n  // would answer `mergedNodes[\"__proto__\"] = registration` with the prototype\n  // setter, dropping a kind the document legally declared.\n  const mergedNodes = createDataKeyedBag<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 = createDataKeyedBag<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    // Own-key membership: extension kind names match\n    // `/^[A-Za-z_][A-Za-z0-9_]*$/`, which admits `toString`, `constructor`, and\n    // `valueOf`. An `in`-style or `!== undefined` probe against a plain record\n    // reports the inherited member as a collision, so a legally-named\n    // extension edge would be rejected for colliding with nothing.\n    assertNoCollision(\n      edge.kindName,\n      \"edge\",\n      hasOwnKey(mergedEdges, edge.kindName),\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 edgeTo = edge.to;\n    const to =\n      Array.isArray(edgeTo) ?\n        resolveEndpoints(edgeTo, nodeKinds, {\n          graphId: graph.id,\n          edgeKind: edge.kindName,\n          side: \"to\",\n        })\n      : resolveTargetMap(\n          edgeTo as Readonly<Record<string, readonly (NodeType | string)[]>>,\n          nodeKinds,\n          {\n            graphId: graph.id,\n            edgeKind: edge.kindName,\n          },\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 =\n      Array.isArray(to) ?\n        defineEdge(\n          edge.kindName,\n          compactUndefined({\n            schema: edge.schema,\n            description: edge.description,\n            annotations: edge.annotations,\n            from,\n            to,\n          }),\n        )\n      : defineEdge(\n          edge.kindName,\n          compactUndefined({\n            schema: edge.schema,\n            description: edge.description,\n            annotations: edge.annotations,\n            from,\n            to: to as Record<string, readonly [NodeType, ...NodeType[]]>,\n          }),\n        );\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, mergedEdges, graph.id),\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  // Spread the two bags at the boundary: they become `graph.nodes` /\n  // `graph.edges` on the returned (public) `GraphDef`. See\n  // `createDataKeyedBag` in ../utils/object.ts.\n  return Object.freeze({\n    ...graph,\n    annotations: mergeGraphAnnotations(\n      graph.annotations,\n      validatedUnion.annotations,\n    ),\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 = createDataKeyedBag<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 annotations = mergeGraphAnnotations(\n    existing.annotations,\n    next.annotations,\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    ...(annotations === undefined ? {} : { annotations }),\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) => requireDefined(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.annotations === 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 resolveTargetMap(\n  map: Readonly<Record<string, readonly (NodeType | string)[]>>,\n  nodeKinds: ReadonlyMap<string, NodeType>,\n  context: Readonly<{ graphId: string; edgeKind: string }>,\n): EdgeTargetMap {\n  const result = createDataKeyedBag<readonly NodeType[]>();\n  for (const [sourceKind, targets] of Object.entries(map)) {\n    result[sourceKind] = resolveEndpoints(targets, nodeKinds, {\n      graphId: context.graphId,\n      edgeKind: context.edgeKind,\n      side: \"to\",\n    });\n  }\n  return { ...result };\n}\n\nfunction resolveOntologyEndpoints(\n  relation: OntologyRelation,\n  nodeKinds: ReadonlyMap<string, NodeType>,\n  edgeKinds: Readonly<Record<string, EdgeRegistration>>,\n  graphId: string,\n): OntologyRelation {\n  if (\n    relation.metaEdge.name === META_EDGE_INVERSE_OF ||\n    relation.metaEdge.name === META_EDGE_IMPLIES\n  ) {\n    return {\n      ...relation,\n      from: resolveOntologyEdgeEndpoint(\n        relation.metaEdge.name,\n        relation.from,\n        edgeKinds,\n        graphId,\n      ),\n      to: resolveOntologyEdgeEndpoint(\n        relation.metaEdge.name,\n        relation.to,\n        edgeKinds,\n        graphId,\n      ),\n    };\n  }\n\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\nfunction resolveOntologyEdgeEndpoint(\n  metaEdge: \"inverseOf\" | \"implies\",\n  endpoint: OntologyRelation[\"from\"],\n  edgeKinds: Readonly<Record<string, EdgeRegistration>>,\n  graphId: string,\n): OntologyRelation[\"from\"] {\n  if (typeof endpoint !== \"string\") return endpoint;\n  if (Object.hasOwn(edgeKinds, endpoint)) return endpoint;\n  if (isExternalIri(endpoint)) return endpoint;\n  throw new GraphExtensionUnresolvedOntologyEndpointError(\n    metaEdge,\n    endpoint,\n    graphId,\n  );\n}\n","/**\n * Graph-extension removal: mutate a `GraphExtension` to drop a\n * set of graph-extension kinds with cascading edge / ontology cleanup.\n *\n * Pure function — no I/O, no compilation. The caller (`store.removeKinds`)\n * handles persistence (CAS commit of the resulting document) and the\n * deferred data-cleanup phase via `materializeRemovals`. This module\n * answers two questions:\n *\n *   1. Is it valid to remove these names? Compile-time kinds are\n *      rejected (compile-time kinds are removed by recompiling and\n *      redeploying — persisting \"removed-compile-time-kind\" state in\n *      `schema_doc` is incoherent). Graph-extension kinds referenced by a\n *      compile-time edge or ontology relation are also rejected\n *      (removing them would orphan compile-time references at the\n *      next deploy).\n *\n *   2. What does the new document look like? Edges whose endpoint\n *      list becomes empty after removal are cascading-removed; edges\n *      with surviving endpoints are retained with the removed name\n *      dropped from `from`/`to`. Ontology relations referencing any\n *      removed kind are also cascading-removed.\n */\nimport { type GraphDef } from \"../core/define-graph\";\nimport { projectTargetKinds } from \"../core/edge-endpoints\";\nimport { getTypeName } from \"../ontology/types\";\nimport { createDataKeyedBag } from \"../utils/object\";\nimport {\n  KindHasReferentsError,\n  type KindReferent,\n  RemoveCompileTimeKindError,\n} from \"./errors\";\nimport {\n  type ExtensionEdgeDef,\n  type ExtensionIndex,\n  type ExtensionNodeDef,\n  type ExtensionOntologyRelation,\n  type GraphExtension,\n} from \"./extension-types\";\nimport {\n  buildGraphExtensionOntologyKeySet,\n  compileTimeOntologyKey,\n  extensionKindNames,\n} from \"./ontology-keys\";\n\ntype RemovalPlan = Readonly<{\n  /**\n   * The new extension after applying the removals. When the input\n   * list contained only absent names, the document is structurally\n   * equal to the existing extension and the caller short-circuits\n   * the schema commit.\n   */\n  document: GraphExtension | undefined;\n  /** Kinds actually removed (extension kinds present in the document). */\n  removedNodeKinds: readonly string[];\n  /** Edge kinds dropped because every endpoint they connected was removed. */\n  removedEdgeKinds: readonly string[];\n}>;\n\n/**\n * Plans the removal of a set of names from a host graph's\n * extension, validating against the host graph's compile-time\n * kinds and graph-extension kinds. Throws on the rejection cases:\n *\n *   - `RemoveCompileTimeKindError` if any name is a compile-time kind.\n *   - `KindHasReferentsError` if a graph-extension kind is referenced\n *     by a compile-time edge endpoint or ontology relation.\n *\n * Returns a plan describing the new document and which kinds will be\n * cascading-removed alongside the explicitly named ones.\n */\nexport function planRemovals<G extends GraphDef>(\n  graph: G,\n  names: readonly string[],\n): RemovalPlan {\n  const document = graph.extension;\n  const namesSet = new Set(names);\n  if (namesSet.size === 0) {\n    return { document, removedNodeKinds: [], removedEdgeKinds: [] };\n  }\n\n  const { nodes: runtimeNodeNames, edges: runtimeEdgeNames } =\n    extensionKindNames(document);\n  const compileTimeNodeNames = new Set(\n    Object.keys(graph.nodes).filter((name) => !runtimeNodeNames.has(name)),\n  );\n  const compileTimeEdgeNames = new Set(\n    Object.keys(graph.edges).filter((name) => !runtimeEdgeNames.has(name)),\n  );\n\n  // Reject compile-time names first — same shape across the API\n  // surface even when the call also references absent runtime names.\n  for (const name of namesSet) {\n    if (compileTimeNodeNames.has(name)) {\n      throw new RemoveCompileTimeKindError(name, \"node\", graph.id);\n    }\n    if (compileTimeEdgeNames.has(name)) {\n      throw new RemoveCompileTimeKindError(name, \"edge\", graph.id);\n    }\n  }\n\n  const removedNodeKinds = [...namesSet].filter((name) =>\n    runtimeNodeNames.has(name),\n  );\n  const explicitlyRemovedEdgeKinds = [...namesSet].filter((name) =>\n    runtimeEdgeNames.has(name),\n  );\n\n  // Compile-time-edge referent check: a graph-extension kind being\n  // removed cannot remain a target of any compile-time edge or ontology\n  // relation, because the compile-time declaration would resurrect the\n  // reference on the next deploy. Pre-build an inverted index of\n  // `kindName → referents` once so the per-kind check is O(1) instead\n  // of walking all edges + ontology per removed kind.\n  const referentsByKind = buildCompileTimeReferentIndex(\n    graph,\n    runtimeEdgeNames,\n  );\n  for (const kindName of removedNodeKinds) {\n    const referents = referentsByKind.get(kindName);\n    if (referents !== undefined && referents.length > 0) {\n      throw new KindHasReferentsError(kindName, referents, graph.id);\n    }\n  }\n\n  if (document === undefined) {\n    return {\n      document: undefined,\n      removedNodeKinds: [],\n      removedEdgeKinds: [],\n    };\n  }\n\n  // Build the cascading-edges set: any graph-extension edge whose `from` or\n  // `to` becomes empty after removal is also removed; edges with\n  // surviving endpoints are retained with the removed name pruned.\n  const removedNodeKindsSet = new Set(removedNodeKinds);\n  const explicitlyRemovedEdgeKindsSet = new Set(explicitlyRemovedEdgeKinds);\n  const cascadeEdges = new Set<string>();\n  // Data-keyed: edge kind names read out of the persisted document.\n  const updatedEdges = createDataKeyedBag<ExtensionEdgeDef>();\n\n  for (const [edgeName, edgeDocument] of Object.entries(document.edges ?? {})) {\n    if (explicitlyRemovedEdgeKindsSet.has(edgeName)) {\n      cascadeEdges.add(edgeName);\n      continue;\n    }\n    let newFrom = edgeDocument.from.filter(\n      (kind) => !removedNodeKindsSet.has(kind),\n    );\n    const edgeTo = edgeDocument.to;\n    let newTo: readonly string[] | Record<string, readonly string[]>;\n    if (Array.isArray(edgeTo)) {\n      newTo = (edgeTo as readonly string[]).filter(\n        (kind: string): boolean => !removedNodeKindsSet.has(kind),\n      );\n      if (newFrom.length === 0 || newTo.length === 0) {\n        cascadeEdges.add(edgeName);\n        continue;\n      }\n    } else {\n      const updatedMap = createDataKeyedBag<readonly string[]>();\n      const targetMap = edgeTo as Readonly<Record<string, readonly string[]>>;\n      const survivingFrom: string[] = [];\n      for (const sourceKind of newFrom) {\n        const targets = (targetMap[sourceKind] ?? []).filter(\n          (kind: string): boolean => !removedNodeKindsSet.has(kind),\n        );\n        if (targets.length > 0) {\n          survivingFrom.push(sourceKind);\n          updatedMap[sourceKind] = targets;\n        }\n      }\n      if (survivingFrom.length === 0) {\n        cascadeEdges.add(edgeName);\n        continue;\n      }\n      newFrom = survivingFrom;\n      newTo = updatedMap;\n    }\n    updatedEdges[edgeName] = {\n      ...edgeDocument,\n      from: newFrom,\n      to: newTo,\n    };\n  }\n\n  // Filter nodes — explicit removals are dropped.\n  // Data-keyed: node kind names read out of the persisted document.\n  const updatedNodes = createDataKeyedBag<ExtensionNodeDef>();\n  for (const [nodeName, nodeDocument] of Object.entries(document.nodes ?? {})) {\n    if (removedNodeKindsSet.has(nodeName)) continue;\n    updatedNodes[nodeName] = nodeDocument;\n  }\n\n  // Drop ontology relations referencing any removed kind. The compile-\n  // time-referent check above already rejects compile-time-side\n  // ontology referencing the removed kind, so any remaining ontology\n  // is safe to filter.\n  const survivingOntology: ExtensionOntologyRelation[] = (\n    document.ontology ?? []\n  ).filter(\n    (relation) =>\n      !removedNodeKindsSet.has(relation.from) &&\n      !removedNodeKindsSet.has(relation.to),\n  );\n\n  // Drop graph-extension indexes referencing removed kinds (relational + edge\n  // entries; the auto-derived vector indexes follow the graph-extension nodes\n  // they were derived from, so dropping the graph-extension node implicitly\n  // drops the index when `mergeGraphExtension` re-runs auto-derive\n  // against the smaller node set).\n  const allRemovedKinds = new Set([\n    ...removedNodeKindsSet,\n    ...cascadeEdges,\n    ...explicitlyRemovedEdgeKindsSet,\n  ]);\n  const survivingIndexes: ExtensionIndex[] = (document.indexes ?? []).filter(\n    (index) => !allRemovedKinds.has(index.kind),\n  );\n\n  const newDocument: GraphExtension = Object.freeze({\n    ...(document.version === undefined ? {} : { version: document.version }),\n    // Spread at the boundary: these land on the returned extension document,\n    // which is public as `graph.extension`. See `createDataKeyedBag` in\n    // ../utils/object.ts.\n    ...(Object.keys(updatedNodes).length === 0 ?\n      {}\n    : { nodes: { ...updatedNodes } }),\n    ...(Object.keys(updatedEdges).length === 0 ?\n      {}\n    : { edges: { ...updatedEdges } }),\n    ...(survivingOntology.length === 0 ? {} : { ontology: survivingOntology }),\n    ...(survivingIndexes.length === 0 ? {} : { indexes: survivingIndexes }),\n  });\n\n  return {\n    document: newDocument,\n    removedNodeKinds,\n    removedEdgeKinds: [\n      ...explicitlyRemovedEdgeKinds,\n      ...[...cascadeEdges].filter(\n        (name) => !explicitlyRemovedEdgeKindsSet.has(name),\n      ),\n    ],\n  };\n}\n\n/**\n * Returns a graph with the graph-extension slice stripped: nodes and edges\n * registered by `mergeGraphExtension` are dropped along with the\n * `extension` itself, leaving the compile-time-only graph.\n *\n * Used by `removeKinds` as the base for re-merging the post-removal\n * graph-extension document — the alternative (mutating `graph.nodes` /\n * `graph.edges` in-place) would skip the merge step's validation\n * (collision checks, endpoint resolution).\n */\nexport function stripGraphExtension<G extends GraphDef>(graph: G): G {\n  const document = graph.extension;\n  if (document === undefined) return graph;\n  const { nodes: runtimeNodeNames, edges: runtimeEdgeNames } =\n    extensionKindNames(document);\n  const runtimeOntologyKeys = buildGraphExtensionOntologyKeySet(document);\n\n  // Data-keyed: registered node kind names.\n  const compileNodes = createDataKeyedBag<(typeof graph.nodes)[string]>();\n  for (const [name, registration] of Object.entries(graph.nodes)) {\n    if (runtimeNodeNames.has(name)) continue;\n    compileNodes[name] = registration;\n  }\n  // Data-keyed: registered edge kind names.\n  const compileEdges = createDataKeyedBag<(typeof graph.edges)[string]>();\n  for (const [name, registration] of Object.entries(graph.edges)) {\n    if (runtimeEdgeNames.has(name)) continue;\n    compileEdges[name] = registration;\n  }\n  const compileOntology = graph.ontology.filter(\n    (relation) => !runtimeOntologyKeys.has(compileTimeOntologyKey(relation)),\n  );\n  // Drop runtime-origin indexes too — `mergeGraphExtension` re-runs\n  // auto-derivation against the new (smaller) graph-extension kind set.\n  const compileIndexes = (graph.indexes ?? []).filter(\n    (index) => index.origin !== \"runtime\",\n  );\n\n  // Spread at the boundary: these become `graph.nodes` / `graph.edges` on the\n  // returned (public) `GraphDef`.\n  return Object.freeze({\n    ...graph,\n    nodes: { ...compileNodes },\n    edges: { ...compileEdges },\n    ontology: compileOntology,\n    indexes: compileIndexes.length === 0 ? undefined : compileIndexes,\n    extension: undefined,\n  });\n}\n\n/**\n * Builds an inverted index `kindName → KindReferent[]` over the\n * compile-time edges and ontology relations of `graph`. One walk per\n * graph instead of one walk per removed kind, dropping the cost of the\n * referent check from O(K × (E + O)) to O(K + E + O).\n */\nfunction buildCompileTimeReferentIndex<G extends GraphDef>(\n  graph: G,\n  runtimeEdgeNames: ReadonlySet<string>,\n): ReadonlyMap<string, readonly KindReferent[]> {\n  const index = new Map<string, KindReferent[]>();\n  const append = (kindName: string, referent: KindReferent): void => {\n    const existing = index.get(kindName);\n    if (existing === undefined) index.set(kindName, [referent]);\n    else existing.push(referent);\n  };\n\n  for (const [edgeName, registration] of Object.entries(graph.edges)) {\n    if (runtimeEdgeNames.has(edgeName)) continue;\n    const referent: KindReferent = {\n      type: \"compile-time-edge\",\n      name: edgeName,\n    };\n    const seen = new Set<string>();\n    for (const endpoint of registration.from) {\n      if (seen.has(endpoint.kind)) continue;\n      seen.add(endpoint.kind);\n      append(endpoint.kind, referent);\n    }\n    for (const toKind of projectTargetKinds(registration.to)) {\n      if (seen.has(toKind)) continue;\n      seen.add(toKind);\n      append(toKind, referent);\n    }\n  }\n\n  const runtimeOntologyKeys = buildGraphExtensionOntologyKeySet(\n    graph.extension,\n  );\n  for (const relation of graph.ontology) {\n    if (runtimeOntologyKeys.has(compileTimeOntologyKey(relation))) continue;\n    const fromName = getTypeName(relation.from);\n    const toName = getTypeName(relation.to);\n    const referent: KindReferent = {\n      type: \"compile-time-ontology\",\n      name: `${relation.metaEdge.name}(${fromName}, ${toName})`,\n    };\n    append(fromName, referent);\n    if (toName !== fromName) append(toName, referent);\n  }\n\n  return index;\n}\n","import {\n  requireWriteFence,\n  resolveWriteFencePlan,\n} from \"../backend/capabilities/write-fence\";\nimport {\n  type GraphBackend,\n  type IdentityTableNames,\n  type SchemaCommitPreflightBackend,\n  type SchemaWriteTransactionBackend,\n  type TransactionBackend,\n} from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport { ConfigurationError } from \"../errors\";\nimport { type SqlSchema } from \"../query/compiler/schema\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport {\n  lockRecordedGraphWrite,\n  withRecordedIdentityMutationTarget,\n} from \"../store/recorded-capture\";\nimport {\n  errorChain,\n  isPostgresConcurrentDdlRaceError,\n} from \"../utils/sql-errors\";\nimport { separationRebuildRequired } from \"./separation\";\nimport {\n  deleteAssertionsTouchingKinds,\n  hasAssertionsTouchingKinds,\n  type IdentityRebuildContext,\n  lockIdentityEnablementNodes,\n  lockIdentityGraph,\n  purgeAssertionsWithUnregisteredKinds,\n  rebuildIdentityClosureForContext,\n} from \"./service\";\nimport { type IdentityTarget } from \"./sql-target\";\n\n/** The identity relations a schema transition reads, writes, and locks. */\nfunction identityTableNames(schema: SqlSchema): IdentityTableNames {\n  return {\n    identityAssertions: schema.tables.identityAssertions,\n    recordedIdentityAssertions: schema.tables.recordedIdentityAssertions,\n    identityClosure: schema.tables.identityClosure,\n    identitySeparation: schema.tables.identitySeparation,\n  };\n}\n\n/** The logical name of the derived relation the upgrade path provisions. */\nconst IDENTITY_SEPARATION_RELATION = \"identitySeparation\";\n\n/**\n * Identity relations added AFTER the profile shipped. On an already-enabled\n * graph their absence is an upgrade, not data loss: they are derived, so they\n * can be provisioned empty and recomputed from the ledger, while a missing\n * ledger or closure relation stays a refusal.\n */\nconst UPGRADEABLE_DERIVED_RELATIONS: ReadonlySet<string> = new Set([\n  IDENTITY_SEPARATION_RELATION,\n]);\n\n/**\n * Rebuilds the derived identity relations from the assertion ledger, against\n * whichever target the provisioning path can offer — the schema-write\n * transaction when the CREATE has to be published with the fill, the top-level\n * backend when the relation already exists and only its rows are owed.\n *\n * The full backend union rather than {@link IdentityTarget}: the rebuild opens\n * its own write frame on whatever it is handed, so it needs the top-level\n * `transaction` member to tell \"open one\" from \"already inside one\" apart.\n */\nexport type RecomputeDerivedRelations = (\n  target: GraphBackend | TransactionBackend,\n) => Promise<void>;\n\n/**\n * What a schema-commit caller still owes after this call.\n *\n * `provisionInCommit` is the identity DDL the caller's commit transaction must\n * issue before its rebuild — empty when nothing is owed. It is DATA, not an\n * action, precisely so the CREATE can happen inside the commit transaction\n * that also fills the relation; see {@link ensureIdentitySchemaStorage}.\n */\nexport type IdentityStorageProvisioning = Readonly<{\n  provisionInCommit: readonly string[];\n}>;\n\nconst NOTHING_OWED: IdentityStorageProvisioning = { provisionInCommit: [] };\n\nfunction identityDerivedStorageMissing(\n  graphId: string,\n  missingTables: readonly string[],\n): boolean {\n  assertIdentityStoragePresent(\n    graphId,\n    missingTables.filter((name) => !UPGRADEABLE_DERIVED_RELATIONS.has(name)),\n  );\n  return missingTables.includes(IDENTITY_SEPARATION_RELATION);\n}\n\n/**\n * Recheck identity storage on the adopted schema-fenced session. The returned\n * DDL is the existing backend's idempotent identity DDL, to be executed on the\n * same session before the existing commit preflight rebuilds the closure.\n */\nexport async function inspectAdoptedIdentityStorage(\n  target: SchemaWriteTransactionBackend,\n  schema: SqlSchema,\n  options: Readonly<{\n    graphId: string;\n    identityTableDdl?: GraphBackend[\"identityTableDdl\"];\n  }>,\n): Promise<IdentityStorageProvisioning> {\n  const tableNames = identityTableNames(schema);\n  const missingTables: string[] = [];\n  for (const [logicalName, tableName] of Object.entries(tableNames)) {\n    if (!(await target.tableExists(tableName))) missingTables.push(logicalName);\n  }\n  if (!identityDerivedStorageMissing(options.graphId, missingTables))\n    return NOTHING_OWED;\n  const ddl = options.identityTableDdl?.(tableNames);\n  if (ddl === undefined)\n    throw identityDerivedUpgradeUnsupportedError(options.graphId, [\n      \"identityTableDdl\",\n    ]);\n  return { provisionInCommit: ddl };\n}\n\n/**\n * Ensures the identity relations exist for a schema transition, and decides —\n * per graph — whether the derived separation relation still owes rows.\n *\n * `enablement` (the target schema turns identity on for the first time) is the\n * only case allowed to provision a missing LEDGER or closure relation. On an\n * already-enabled graph those going missing is data loss, not a provisioning\n * gap, so it is refused.\n *\n * THE INVARIANT THIS FUNCTION OWNS: *the separation relation is never readable\n * in a state that under-reports separations — on any path, including a schema\n * commit that is refused and two graphs upgrading the same database.* A derived\n * relation created empty is not inert: it is readable, and `isSeparated` reads\n * it as authority. An empty separation relation answers \"not separated\" for\n * EVERY pair, which is precisely the answer that lets `assertSame` fuse two\n * classes a live `different` assertion separates, and the relation's\n * CHECK-constraint backstop cannot fire because there are no rows to collapse.\n * The relation's only safe states are therefore ABSENT (every read raises\n * `IDENTITY_STORAGE_MISSING` — loud, never a wrong answer) and PRESENT AND\n * COMPLETE.\n *\n * Three rules hold that invariant up, and each closes a way the previous\n * \"the table is missing → create it, fill it later\" shape broke it:\n *\n *  1. THE FILL DECISION IS PER GRAPH, never \"does the table exist\".\n *     {@link separationRebuildRequired} asks whether THIS graph has live\n *     `different` assertions and no rows. Identity DDL is database-global while\n *     the ledger is per-graph, so table existence answered for the wrong scope:\n *     graph B creating the relation silently suppressed graph A's fill.\n *  2. NOTHING IS CREATED OUTSIDE THE TRANSACTION THAT FILLS IT. When the caller\n *     supplies `recomputeDerivedRelations`, the CREATE and the fill are one\n *     schema-write transaction. When it does not — the schema-commit paths —\n *     the DDL is RETURNED as `provisionInCommit` and issued inside the commit\n *     transaction by {@link identitySchemaCommitPreflight}. A commit that is\n *     refused (a breaking `IDENTITY_PROFILE_MIGRATION_PENDING` gate, a stale\n *     CAS, a contradiction) therefore creates nothing at all.\n *  3. WHAT RULE 2 CANNOT UNDO, RULE 1 HEALS. A relation left present-and-empty\n *     by an older library version, or by another graph's provisioning, is\n *     rebuilt by the next open of the graph that owns the assertions —\n *     self-healing, rather than permanently under-reporting because \"present\"\n *     was what suppressed the rebuild.\n *  4. HEALING HAPPENS AT AN OPEN, SO A HANDLE THAT PREDATES THE RELATION STAYS\n *     LOUD. Every rule above runs while a Store is being opened; a handle\n *     already open never re-runs them, so one that was opened while the\n *     relation was ABSENT — failing loudly on every identity read — would\n *     otherwise start answering \"not separated\" the moment another graph's\n *     upgrade created the shared relation. {@link separationRebuildRequired} is\n *     therefore consulted on the READ path too ({@link isSeparated}), which\n *     turns that transition into the same loud `IDENTITY_STORAGE_MISSING`\n *     rather than a silent wrong answer. Reopening the Store is what fixes it,\n *     and the error says so.\n *\n * A graph with no live `different` assertion projects to zero separation rows,\n * so creating that graph's relation empty is not a compromise, it is the\n * correct content — that case needs no fill, no fence, and no atomicity.\n */\nexport async function ensureIdentitySchemaStorage(\n  backend: GraphBackend,\n  schema: SqlSchema,\n  options: Readonly<{\n    graphId: string;\n    enablement: boolean;\n    /**\n     * The kind registry the FILL will derive through. The per-graph predicate\n     * scopes the ledger by the same registry, so it never asks for a rebuild\n     * that cannot converge.\n     */\n    registry: KindRegistry;\n    recomputeDerivedRelations?: RecomputeDerivedRelations;\n  }>,\n): Promise<IdentityStorageProvisioning> {\n  const ensureIdentityTables = backend.ensureIdentityTables;\n  if (ensureIdentityTables === undefined) return NOTHING_OWED;\n  const tableNames = identityTableNames(schema);\n  const missingTables = await ensureIdentityTables(tableNames, {\n    provisionMissing: options.enablement,\n  });\n  // Enablement provisions every relation up front: the commit preflight it is\n  // always paired with reads the ledger before it can fill anything, and a\n  // graph whose identity profile is not committed yet has no reader that could\n  // observe the derived relation at all.\n  if (options.enablement) return NOTHING_OWED;\n  const separationMissing = identityDerivedStorageMissing(\n    options.graphId,\n    missingTables,\n  );\n  const rebuildRequired = await separationRebuildRequired(\n    backend,\n    schema,\n    options.graphId,\n    { relationExists: !separationMissing, registry: options.registry },\n  );\n  if (!separationMissing && !rebuildRequired) return NOTHING_OWED;\n  const recompute = options.recomputeDerivedRelations;\n  if (recompute === undefined) {\n    return provisioningForCommit(backend, tableNames, options.graphId, {\n      ensureIdentityTables,\n      separationMissing,\n      rebuildRequired,\n    });\n  }\n  await provisionDerivedRelations(backend, tableNames, options.graphId, {\n    ensureIdentityTables,\n    recompute,\n    separationMissing,\n    rebuildRequired,\n  });\n  return NOTHING_OWED;\n}\n\n/**\n * The schema-commit path's half of rule 2: hand the CREATE to the commit\n * transaction instead of running it here.\n *\n * Creating it here is what stranded a readable-empty relation whenever the\n * commit was then refused — and left it stranded permanently, because the next\n * open saw the table present and never re-triggered the upgrade.\n *\n * The one case that still provisions eagerly is the safe one: a graph with no\n * live `different` assertion, whose relation is correct while empty. That keeps\n * the derived relation reachable for backends that cannot run DDL inside the\n * commit transaction at all, without ever publishing an under-reporting state.\n */\nasync function provisioningForCommit(\n  backend: GraphBackend,\n  tableNames: IdentityTableNames,\n  graphId: string,\n  input: Readonly<{\n    ensureIdentityTables: NonNullable<GraphBackend[\"ensureIdentityTables\"]>;\n    separationMissing: boolean;\n    rebuildRequired: boolean;\n  }>,\n): Promise<IdentityStorageProvisioning> {\n  if (!input.separationMissing) return NOTHING_OWED;\n  const identityTableDdl = backend.identityTableDdl;\n  if (identityTableDdl !== undefined) {\n    return { provisionInCommit: identityTableDdl(tableNames) };\n  }\n  if (input.rebuildRequired) {\n    throw identityDerivedUpgradeUnsupportedError(graphId, [\"identityTableDdl\"]);\n  }\n  await input.ensureIdentityTables(tableNames, { provisionMissing: true });\n  return NOTHING_OWED;\n}\n\n/**\n * Publishes the derived relations this graph owes, atomically.\n *\n * Three shapes, and which one applies is decided by the per-graph predicate,\n * never by the backend's capabilities — a backend that cannot do what the state\n * requires is refused, not quietly given a weaker guarantee:\n *\n *  - CREATE + FILL — needs both ports, because the two steps must reach other\n *    connections as one commit. `identityTableDdl` is DDL as data rather than a\n *    call back into the top-level backend, which inside the fence would re-enter\n *    the backend's serialized statement queue.\n *  - CREATE alone (no live `different` assertion) — empty IS the projection, so\n *    an ordinary idempotent provision is correct and needs no fence.\n *  - FILL alone (the relation exists, empty, and this graph owes rows) — the\n *    self-heal. The recompute opens its own transaction, validates the schema\n *    version its registry came from, then takes the identity lock. No DDL fence\n *    is needed for an already-published relation; the schema-version fence is\n *    still required to prevent a stale opener overwriting a newer migration.\n */\nasync function provisionDerivedRelations(\n  backend: GraphBackend,\n  tableNames: IdentityTableNames,\n  graphId: string,\n  ports: Readonly<{\n    ensureIdentityTables: NonNullable<GraphBackend[\"ensureIdentityTables\"]>;\n    recompute: RecomputeDerivedRelations;\n    separationMissing: boolean;\n    rebuildRequired: boolean;\n  }>,\n): Promise<void> {\n  if (!ports.separationMissing) {\n    await ports.recompute(backend);\n    return;\n  }\n  if (!ports.rebuildRequired) {\n    await ports.ensureIdentityTables(tableNames, { provisionMissing: true });\n    return;\n  }\n  const fence = backend.schemaWriteTransaction;\n  const identityTableDdl = backend.identityTableDdl;\n  if (fence === undefined || identityTableDdl === undefined) {\n    throw identityDerivedUpgradeUnsupportedError(graphId, [\n      ...(fence === undefined ? [\"schemaWriteTransaction\"] : []),\n      ...(identityTableDdl === undefined ? [\"identityTableDdl\"] : []),\n    ]);\n  }\n  await withIdentityDdlRaceRetry(async () =>\n    fence(graphId, async (target) => {\n      await lockIdentityDdl(target);\n      await executeIdentityDdl(\n        (ddl) => target.executeSchemaDdl(ddl),\n        identityTableDdl(tableNames),\n      );\n      await ports.recompute(target);\n    }),\n  );\n}\n\n/**\n * Errors already classified as \"the identity DDL specifically lost a catalog\n * race\".\n *\n * Marked rather than wrapped, so the error a caller finally sees is the\n * driver's own; looked up through the cause chain because both the schema fence\n * and the schema-commit primitive wrap whatever their callback throws.\n */\nconst IDENTITY_DDL_RACES = new WeakSet<object>();\n\nfunction markIdentityDdlRace(error: unknown): unknown {\n  if (typeof error === \"object\" && error !== null) {\n    IDENTITY_DDL_RACES.add(error);\n  }\n  return error;\n}\n\nfunction isIdentityDdlRace(error: unknown): boolean {\n  for (const link of errorChain(error)) {\n    if (\n      typeof link === \"object\" &&\n      link !== null &&\n      IDENTITY_DDL_RACES.has(link)\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Issues identity DDL, tagging the one failure that is worth re-running.\n *\n * The single place identity DDL meets {@link isPostgresConcurrentDdlRaceError},\n * and the reason the retry below can be DDL-scoped while still re-running a\n * whole transaction. That classifier's contract is \"idempotent DDL only\" — on\n * any other statement a 23505 is a real duplicate write — so the surrounding\n * attempt, which also performs the closure/separation FILL, must not be\n * classified by it directly: a uniqueness failure from the fill would be read\n * as a catalog race and silently retried. Tagging at the DDL statement itself\n * keeps the classifier on exactly the statements it is contracted for.\n */\nasync function executeIdentityDdl(\n  execute: (ddl: string) => Promise<void>,\n  statements: readonly string[],\n): Promise<void> {\n  for (const statement of statements) {\n    try {\n      await execute(statement);\n    } catch (error) {\n      if (isPostgresConcurrentDdlRaceError(error)) {\n        throw markIdentityDdlRace(error);\n      }\n      throw error;\n    }\n  }\n}\n\n/**\n * Runs an identity upgrade attempt, retrying the WHOLE attempt once when its\n * DDL — and only its DDL — lost a catalog race.\n *\n * PostgreSQL's `IF NOT EXISTS` cannot see another session's uncommitted\n * pg_class row, so a CREATE issued while an unfenced creator\n * (`bootstrapTables`, first-enablement `ensureIdentityTables`) is mid-flight\n * can come back 23505 (or 42701 for an additive column) — and inside a\n * transaction that aborts everything, so the in-place retry\n * `executeConcurrentCreateDdl` uses is not available, and neither is any\n * in-transaction recovery: after the error the transaction can accept nothing\n * but a rollback. Re-running the attempt from the outside is the only shape\n * left. The second attempt runs against a database where the winner's relation\n * is committed, so the CREATE is a no-op.\n *\n * Retry-worthiness is decided by {@link executeIdentityDdl}'s tag, not by\n * inspecting the failure here: everything else in an attempt (the fill, the\n * locks, the CAS) must stay loud on the first failure.\n *\n * Bounded at one: a second such failure is no longer a race, and staying loud\n * is the point.\n *\n * The DDL advisory lock is what makes this rare rather than routine — it\n * serializes fenced identity DDL across graphs, which is the collision two\n * graphs upgrading the same database would otherwise hit every time.\n */\nexport async function withIdentityDdlRaceRetry<T>(\n  attempt: () => Promise<T>,\n): Promise<T> {\n  try {\n    return await attempt();\n  } catch (error) {\n    if (!isIdentityDdlRace(error)) throw error;\n    return attempt();\n  }\n}\n\n/**\n * The DATABASE-scoped critical section for identity DDL.\n *\n * The schema-write fence is per GRAPH, but the identity relations are shared by\n * every graph in the database, so two graphs upgrading at once are not\n * serialized by it at all — they race the CREATE, and on PostgreSQL the loser\n * gets 23505 inside a transaction it cannot retry in place. One constant-keyed\n * transaction-scoped advisory lock removes the race instead of recovering from\n * it.\n *\n * ORDER: outermost among the IDENTITY locks, innermost to the SCHEMA FENCE.\n * Every path that reaches here is already inside the backend's per-graph\n * schema-write transaction (`schemaWriteTransaction` or\n * `commitSchemaVersionWithPreflight`), which took that graph's fence first;\n * this lock is then taken before the per-graph identity and recorded-write\n * locks, on every path that takes both. Two openers of the SAME graph — one on\n * the boot fence, one in a schema commit — would otherwise be able to hold one\n * lock each and wait for the other.\n *\n * The safety condition for the nesting is that nobody acquires a DIFFERENT\n * graph's schema fence while holding this lock: fence(A) → ddl → fence(B) is\n * the one shape that could close a cycle with fence(B) → ddl → fence(A). No\n * caller does — a schema fence is taken once, at the outside, for the graph\n * being transitioned — and the DDL issued under this lock is graph-agnostic\n * (`CREATE TABLE IF NOT EXISTS` on shared relations), so there is nothing here\n * that would want a second graph's fence.\n *\n * SQLite needs nothing: its writer slot already serializes the whole database —\n * with the adopted-DEFERRED-frame caveat `lockIdentityGraph` documents, which\n * `executeIdentityStatement` turns into a typed refusal (#447). Schema\n * transitions run inside the backend's own schema-write transaction, so this\n * path is not reachable from an adopted frame today.\n *\n * Resolves a {@link resolveWriteFencePlan}: the `lock` arm takes the advisory\n * lock below, and the `engine-serialized` arm is the SQLite writer-slot case\n * this doc already describes.\n */\nasync function lockIdentityDdl(target: IdentityTarget): Promise<void> {\n  const plan = resolveWriteFencePlan(target);\n  const fence = requireWriteFence(plan, \"identity DDL\", \"keyed\");\n  switch (fence.kind) {\n    case \"lock\":\n    case \"row\": {\n      await target.execute(\n        asCompiledRowsSql(fence.sql.acquireKeyed(IDENTITY_DDL_LOCK_KEY, 0)),\n      );\n      return;\n    }\n    case \"engine-serialized\":\n    case \"caller-serialized\": {\n      return;\n    }\n    default: {\n      fence satisfies never;\n    }\n  }\n}\n\nconst IDENTITY_DDL_LOCK_KEY = \"typegraph:identity-ddl\";\n\n/**\n * A backend that cannot publish the derived-relation upgrade atomically, on a\n * graph whose state requires atomicity.\n *\n * Refused rather than degraded. The degraded shape — create the relation, fill\n * it in a second statement — is readable and empty in between, and \"empty\"\n * means \"nothing is separated\", the one wrong answer that lets a contradictory\n * merge commit. An engine gap is declared, never worked around unsafely.\n *\n * Not reachable for the bundled backends: both Drizzle backends implement both\n * ports whenever transactions are enabled, and identity already refuses a\n * non-transactional backend earlier with `IDENTITY_REQUIRES_ATOMIC_BACKEND`.\n * This is the custom-backend path.\n */\nfunction identityDerivedUpgradeUnsupportedError(\n  graphId: string,\n  missingPorts: readonly string[],\n): ConfigurationError {\n  return new ConfigurationError(\n    \"This backend cannot publish an Operational Identity derived-relation upgrade atomically.\",\n    {\n      code: \"IDENTITY_UPGRADE_REQUIRES_ATOMIC_DDL\",\n      graphId,\n      missingPorts,\n      tables: [IDENTITY_SEPARATION_RELATION],\n    },\n    {\n      suggestion:\n        \"Use a backend that implements schemaWriteTransaction and identityTableDdl (both bundled Drizzle backends do when transactions are enabled). Creating the separation relation and filling it as two steps would leave it readable and empty in between, where every pair reads as not separated. To upgrade out of band, create the relation with the standard TypeGraph DDL and run rebuildIdentityClosure(store) before serving traffic.\",\n    },\n  );\n}\n\n/**\n * Whether dropping `droppedNodeKinds` from a graph whose schema carries NO\n * identity profile still leaves assertion rows behind. Disabling identity\n * retains the ledger, so \"no profile\" does not mean \"no assertions\" — a drop\n * committed afterwards strands every assertion naming the kind.\n *\n * Answering `false` keeps the commit on its ordinary path, which matters: that\n * path carries the emptiness fence and its capability requirements. Only a\n * database that genuinely holds affected rows is worth moving to the\n * preflight-carrying primitive, and with no profile nothing can be writing new\n * assertions for this graph while the answer is in flight.\n *\n * Partial storage answers `false` too: an enabled graph treats a missing\n * relation as data loss ({@link assertIdentityStoragePresent}), but a disabled\n * graph must not have its migration refused over a relation nothing reads.\n */\nexport async function identityKindCascadeNeeded(\n  backend: GraphBackend,\n  schema: SqlSchema,\n  graphId: string,\n  droppedNodeKinds: readonly string[],\n): Promise<boolean> {\n  if (droppedNodeKinds.length === 0) return false;\n  const ensureIdentityTables = backend.ensureIdentityTables;\n  if (ensureIdentityTables === undefined) return false;\n  const missingTables = await ensureIdentityTables(identityTableNames(schema), {\n    provisionMissing: false,\n  });\n  if (missingTables.length > 0) return false;\n  return hasAssertionsTouchingKinds(backend, schema, graphId, droppedNodeKinds);\n}\n\nfunction assertIdentityStoragePresent(\n  graphId: string,\n  missingTables: readonly string[],\n): void {\n  if (missingTables.length === 0) return;\n  throw new ConfigurationError(\n    \"Operational Identity storage was missing from an already enabled graph.\",\n    {\n      code: \"IDENTITY_STORAGE_MISSING\",\n      graphId,\n      tables: missingTables,\n    },\n    {\n      suggestion:\n        \"Restore missing assertion-ledger tables from backup. If only the derived relations (closure, separation) are missing, recreate them with the standard TypeGraph DDL, open the Store, and run rebuildIdentityClosure() before serving traffic.\",\n    },\n  );\n}\n\n/**\n * Builds the data preflight a schema commit runs inside its own transaction:\n * provision any derived relation the transition owes, take the recorded-write\n * and identity locks, then re-derive the closure so it matches the schema\n * version being committed.\n *\n * Every path that commits a schema version for an identity-enabled graph uses\n * this — `createStoreWithSchema`, `Store.evolve()`, and the explicit\n * `migrateSchema()` — so a profile flip or a first enablement can never commit\n * against a stale or never-built closure.\n *\n * `provisionDerivedRelations` is the DDL {@link ensureIdentitySchemaStorage}\n * declined to run outside this transaction (its `provisionInCommit`). Issuing\n * it here is what makes the whole upgrade one commit: a refused or failed\n * transition leaves NO relation behind, rather than an empty one that reads as\n * \"nothing is separated\". The DDL runs before the per-graph locks because the\n * database-scoped DDL lock it takes must always be the outer one.\n *\n * First enablement additionally fences legacy node writers: nodes written\n * through a store that predates the enablement would otherwise land after the\n * fold scan and miss the closure.\n */\nexport function identitySchemaCommitPreflight<G extends GraphDef>(\n  ctx: Omit<IdentityRebuildContext<G>, \"backend\">,\n  options: Readonly<{\n    enablement: boolean;\n    droppedNodeKinds?: readonly string[];\n    provisionDerivedRelations?: readonly string[];\n  }>,\n): (target: SchemaCommitPreflightBackend) => Promise<void> {\n  return async (target: SchemaCommitPreflightBackend) => {\n    await provisionDerivedRelationsInCommit(\n      target,\n      ctx.graphId,\n      options.provisionDerivedRelations ?? [],\n    );\n    await lockRecordedGraphWrite(target, ctx.graphId);\n    await lockIdentityGraph(target, ctx.graphId);\n    if (options.enablement) {\n      await lockIdentityEnablementNodes(target, ctx.schema);\n      // Enablement must not ADOPT rows the rebuild below cannot see. A database\n      // that was identity-enabled before, disabled, and then evolved can hold\n      // assertions for kinds this schema never registers; they would stay\n      // current and invisible for exactly the reasons the drop cascade exists.\n      // On a true first enablement the ledger is empty and this is one scan.\n      await withRecordedIdentityMutationTarget(target, (rawTarget, touch) =>\n        purgeAssertionsWithUnregisteredKinds(\n          rawTarget,\n          ctx.schema,\n          ctx.graphId,\n          new Set(ctx.registry.nodeKinds.keys()),\n          touch,\n        ),\n      );\n    }\n    // A commit that DROPS node kinds cascades the assertion ledger exactly as\n    // Store.removeKinds() does. The rebuild below silently FILTERS rows\n    // touching unregistered kinds, so skipping this would leave a dropped\n    // kind's assertions current as orphans — invisible to the closure and to\n    // live-endpoint interchange reads, yet still visible to raw ledger reads\n    // and merge staging, where a later \"no-op\" merge would end them.\n    const droppedNodeKinds = options.droppedNodeKinds ?? [];\n    if (droppedNodeKinds.length > 0) {\n      await withRecordedIdentityMutationTarget(target, (rawTarget, touch) =>\n        deleteAssertionsTouchingKinds(\n          rawTarget,\n          ctx.schema,\n          ctx.graphId,\n          droppedNodeKinds,\n          touch,\n        ),\n      );\n    }\n    await rebuildIdentityClosureForContext({ ...ctx, backend: target });\n  };\n}\n\n/**\n * Issues the transition's derived-relation DDL inside the commit transaction.\n *\n * The port is optional on the preflight target because a custom backend's\n * `commitSchemaVersionWithPreflight` may hand back a transaction that cannot\n * run DDL. That is refused with the same typed capability error as the fenced\n * path, at the moment the DDL is actually needed — never silently skipped,\n * which would let the commit's rebuild write into a relation that does not\n * exist, or (worse, if it were created afterwards) publish it empty.\n *\n * This is the SAME idempotent DDL the fenced path issues, so it can lose the\n * same catalog race — two replicas booting against one database — and it is\n * issued inside the CALLER's schema-commit transaction, where neither an\n * in-place retry nor an in-transaction catch is available (PostgreSQL will\n * accept nothing but a rollback after the error). Hoisting it outside the\n * transaction is refused for the reason the docblock above gives: a relation\n * created but not filled reads as \"nothing is separated\". So it tags the race\n * through {@link executeIdentityDdl} and the whole commit is re-run once by\n * {@link withIdentityDdlRaceRetry} at the call sites in `schema/manager.ts`\n * (#445).\n */\nasync function provisionDerivedRelationsInCommit(\n  target: SchemaCommitPreflightBackend,\n  graphId: string,\n  ddl: readonly string[],\n): Promise<void> {\n  if (ddl.length === 0) return;\n  const executeSchemaDdl = target.executeSchemaDdl;\n  if (executeSchemaDdl === undefined) {\n    throw identityDerivedUpgradeUnsupportedError(graphId, [\"executeSchemaDdl\"]);\n  }\n  await lockIdentityDdl(target);\n  await executeIdentityDdl((statement) => executeSchemaDdl(statement), ddl);\n}\n\n/**\n * The kind-drop cascade alone, for a schema commit whose target graph has NO\n * identity profile while the assertion ledger still exists. Disabling identity\n * retains the ledger deliberately, so the rows survive the profile going away —\n * and a later drop that skipped this would strand them exactly as it would on\n * an enabled graph, until a re-enablement or a \"no-op\" merge tripped over them.\n *\n * No closure rebuild: without a profile there is no closure contract to\n * restore, and the enablement preflight rebuilds it from scratch anyway.\n */\nexport function identityKindCascadePreflight(\n  ctx: Readonly<{ graphId: string; schema: SqlSchema }>,\n  droppedNodeKinds: readonly string[],\n): (target: TransactionBackend) => Promise<void> {\n  return async (target: TransactionBackend) => {\n    await lockRecordedGraphWrite(target, ctx.graphId);\n    await lockIdentityGraph(target, ctx.graphId);\n    await withRecordedIdentityMutationTarget(target, (rawTarget, touch) =>\n      deleteAssertionsTouchingKinds(\n        rawTarget,\n        ctx.schema,\n        ctx.graphId,\n        droppedNodeKinds,\n        touch,\n      ),\n    );\n  };\n}\n","/**\n * Endpoint-compatibility validation for `implies()` ontology relations.\n *\n * Every place that builds a query-capable `KindRegistry` — `buildKindRegistry`\n * for a live `GraphDef`, and the schema deserializer for a persisted schema —\n * calls this so an endpoint-incompatible implication can never reach\n * `KindRegistry.expandImplyingEdges()`. Without this gate, an implying edge\n * would be folded into any `expand: \"implying\"` traversal for the edge it\n * implies even when it connects entirely different node kinds — the query\n * compiler filters by expanded edge kind plus the *queried* node aliases, not\n * by the implied edge's own domain/range, so a mismatched edge would silently\n * satisfy whatever kinds the traversal alias happens to ask for.\n */\nimport { ConfigurationError } from \"../errors/index\";\nimport { META_EDGE_IMPLIES } from \"../ontology/constants\";\nimport { type KindRegistry } from \"./kind-registry\";\n\n/** An edge kind's declared domain (`from`) and range (`to`) kind names and allowed pairs. */\nexport type EdgeEndpointKinds = Readonly<{\n  from: readonly string[];\n  to: readonly string[];\n  pairs?: readonly Readonly<{ from: string; to: string }>[];\n}>;\n\n/**\n * Rejects implications whose implying edge can never be endpoint-compatible\n * with the edge it implies.\n *\n * The check runs over the *effective transitive closure*, not the authored\n * direct relations: for every registered edge `C`, every edge `A` that\n * `registry.expandImplyingEdges(C)` reports as (transitively) implying `C` is\n * validated directly against `C`. This is what keeps the gate sound through an\n * unregistered intermediate — given `A implies B implies C` with `B` absent\n * from `edgeEndpoints`, neither direct hop is individually checkable, yet the\n * precomputed closure still folds `A` into a traversal of `C`, so `A` must be\n * validated against `C` regardless of `B`.\n *\n * A relation is compatible when every kind the implying edge allows on a side\n * is assignable — via `registry.isAssignableToAny` (equal, or a `subClassOf`\n * descendant) — to at least one kind the implied edge allows on that same\n * side, and every allowed endpoint pair of the implying edge is assignable to\n * an allowed endpoint pair of the implied edge. An implying edge kind absent\n * from `edgeEndpoints` is skipped: it is unregistered on this graph, has no\n * stored rows, and so can never fold anything into a traversal.\n */\nexport function validateImpliesEndpointCompatibility(\n  edgeEndpoints: ReadonlyMap<string, EdgeEndpointKinds>,\n  registry: KindRegistry,\n): void {\n  for (const [impliedEdgeKind, impliedEndpoints] of edgeEndpoints) {\n    for (const implyingEdgeKind of registry.expandImplyingEdges(\n      impliedEdgeKind,\n    )) {\n      if (implyingEdgeKind === impliedEdgeKind) continue;\n      const implyingEndpoints = edgeEndpoints.get(implyingEdgeKind);\n      if (!implyingEndpoints) continue;\n\n      assertEndpointCompatible(\n        \"from\",\n        implyingEdgeKind,\n        implyingEndpoints.from,\n        impliedEdgeKind,\n        impliedEndpoints.from,\n        registry,\n      );\n      assertEndpointCompatible(\n        \"to\",\n        implyingEdgeKind,\n        implyingEndpoints.to,\n        impliedEdgeKind,\n        impliedEndpoints.to,\n        registry,\n      );\n\n      if (\n        implyingEndpoints.pairs !== undefined &&\n        impliedEndpoints.pairs !== undefined\n      ) {\n        assertPairsCompatible(\n          implyingEdgeKind,\n          implyingEndpoints.pairs,\n          impliedEdgeKind,\n          impliedEndpoints.pairs,\n          registry,\n        );\n      }\n    }\n  }\n}\n\nfunction assertPairsCompatible(\n  implyingEdgeKind: string,\n  implyingPairs: readonly Readonly<{ from: string; to: string }>[],\n  impliedEdgeKind: string,\n  impliedPairs: readonly Readonly<{ from: string; to: string }>[],\n  registry: KindRegistry,\n): void {\n  for (const implyingPair of implyingPairs) {\n    const compatible = impliedPairs.some(\n      (impliedPair) =>\n        registry.isAssignableTo(implyingPair.from, impliedPair.from) &&\n        registry.isAssignableTo(implyingPair.to, impliedPair.to),\n    );\n    if (!compatible) {\n      const allowedString = impliedPairs\n        .map((p) => `(${p.from} -> ${p.to})`)\n        .join(\", \");\n      throw new ConfigurationError(\n        `implies(\"${implyingEdgeKind}\", \"${impliedEdgeKind}\") is endpoint-incompatible: ` +\n          `endpoint pair (${implyingPair.from} -> ${implyingPair.to}) declared on \"${implyingEdgeKind}\" ` +\n          `cannot be assigned to any allowed pair of \"${impliedEdgeKind}\".`,\n        {\n          metaEdge: META_EDGE_IMPLIES,\n          implyingEdge: implyingEdgeKind,\n          impliedEdge: impliedEdgeKind,\n          incompatiblePair: implyingPair,\n          allowedPairs: impliedPairs,\n        },\n        {\n          suggestion: `Ensure every endpoint pair of \"${implyingEdgeKind}\" is assignable to an allowed pair of \"${impliedEdgeKind}\" (allowed: [${allowedString}]), or remove implies(\"${implyingEdgeKind}\", \"${impliedEdgeKind}\").`,\n        },\n      );\n    }\n  }\n}\n\nfunction assertEndpointCompatible(\n  side: \"from\" | \"to\",\n  implyingEdgeKind: string,\n  implyingKinds: readonly string[],\n  impliedEdgeKind: string,\n  impliedKinds: readonly string[],\n  registry: KindRegistry,\n): void {\n  const incompatibleKinds = implyingKinds.filter(\n    (kind) => !registry.isAssignableToAny(kind, impliedKinds),\n  );\n  if (incompatibleKinds.length === 0) return;\n\n  throw new ConfigurationError(\n    `implies(\"${implyingEdgeKind}\", \"${impliedEdgeKind}\") is endpoint-incompatible: ` +\n      `${side} kind(s) [${incompatibleKinds.join(\", \")}] declared on \"${implyingEdgeKind}\" ` +\n      `cannot be assigned to any of \"${impliedEdgeKind}\"'s ${side} kind(s) [${impliedKinds.join(\", \")}].`,\n    {\n      metaEdge: META_EDGE_IMPLIES,\n      implyingEdge: implyingEdgeKind,\n      impliedEdge: impliedEdgeKind,\n      endpoint: side,\n      incompatibleKinds,\n      allowedKinds: impliedKinds,\n    },\n    {\n      suggestion:\n        `Add a subClassOf relation from each of [${incompatibleKinds.join(\", \")}] to one of ` +\n        `\"${impliedEdgeKind}\"'s ${side} kind(s) [${impliedKinds.join(\", \")}], narrow \"${implyingEdgeKind}\"'s ` +\n        `${side} declaration to exclude [${incompatibleKinds.join(\", \")}], or remove ` +\n        `implies(\"${implyingEdgeKind}\", \"${impliedEdgeKind}\").`,\n    },\n  );\n}\n","import { ConfigurationError } from \"../errors\";\nimport { META_EDGE_INVERSE_OF } from \"../ontology/constants\";\nimport { type NamedOntologyRelation } from \"../ontology/validation\";\nimport { type KindRegistry } from \"./kind-registry\";\nimport { type EdgeEndpointKinds } from \"./validate-implies\";\n\n/** Validates the endpoint reversal required by every registered inverse pair. */\nexport function validateInverseEndpointCompatibility(\n  ontology: readonly NamedOntologyRelation[],\n  edgeEndpoints: ReadonlyMap<string, EdgeEndpointKinds>,\n  registry: KindRegistry,\n): void {\n  for (const relation of ontology) {\n    if (relation.metaEdge !== META_EDGE_INVERSE_OF) continue;\n    const left = edgeEndpoints.get(relation.from);\n    const right = edgeEndpoints.get(relation.to);\n    if (left === undefined || right === undefined) continue;\n\n    assertInverseSideCompatible(\n      relation.from,\n      \"from\",\n      left.from,\n      relation.to,\n      \"to\",\n      right.to,\n      registry,\n    );\n    assertInverseSideCompatible(\n      relation.from,\n      \"to\",\n      left.to,\n      relation.to,\n      \"from\",\n      right.from,\n      registry,\n    );\n    if (relation.from !== relation.to) {\n      assertInverseSideCompatible(\n        relation.to,\n        \"from\",\n        right.from,\n        relation.from,\n        \"to\",\n        left.to,\n        registry,\n      );\n      assertInverseSideCompatible(\n        relation.to,\n        \"to\",\n        right.to,\n        relation.from,\n        \"from\",\n        left.from,\n        registry,\n      );\n    }\n\n    if (left.pairs !== undefined && right.pairs !== undefined) {\n      assertInversePairsCompatible(\n        relation.from,\n        left.pairs,\n        relation.to,\n        right.pairs,\n        registry,\n      );\n      if (relation.from !== relation.to) {\n        assertInversePairsCompatible(\n          relation.to,\n          right.pairs,\n          relation.from,\n          left.pairs,\n          registry,\n        );\n      }\n    }\n  }\n}\n\nfunction assertInversePairsCompatible(\n  sourceEdge: string,\n  sourcePairs: readonly Readonly<{ from: string; to: string }>[],\n  inverseEdge: string,\n  inversePairs: readonly Readonly<{ from: string; to: string }>[],\n  registry: KindRegistry,\n): void {\n  for (const sourcePair of sourcePairs) {\n    const reversed = { from: sourcePair.to, to: sourcePair.from };\n    const compatible = inversePairs.some(\n      (inversePair) =>\n        registry.isAssignableTo(reversed.from, inversePair.from) &&\n        registry.isAssignableTo(reversed.to, inversePair.to),\n    );\n    if (!compatible) {\n      const allowedString = inversePairs\n        .map((p) => `(${p.from} -> ${p.to})`)\n        .join(\", \");\n      throw new ConfigurationError(\n        `inverseOf(\"${sourceEdge}\", \"${inverseEdge}\") is endpoint-incompatible: ` +\n          `endpoint pair (${sourcePair.from} -> ${sourcePair.to}) on \"${sourceEdge}\" ` +\n          `reversed to (${reversed.from} -> ${reversed.to}) cannot be assigned to any allowed pair of \"${inverseEdge}\".`,\n        {\n          metaEdge: META_EDGE_INVERSE_OF,\n          sourceEdge,\n          inverseEdge,\n          sourcePair,\n          reversedPair: reversed,\n          allowedPairs: inversePairs,\n        },\n        {\n          suggestion: `Ensure every reversed pair of \"${sourceEdge}\" matches an allowed pair of \"${inverseEdge}\" (allowed: [${allowedString}]), or remove the inverseOf relation.`,\n        },\n      );\n    }\n  }\n}\n\nfunction assertInverseSideCompatible(\n  sourceEdge: string,\n  sourceSide: \"from\" | \"to\",\n  sourceKinds: readonly string[],\n  inverseEdge: string,\n  inverseSide: \"from\" | \"to\",\n  inverseKinds: readonly string[],\n  registry: KindRegistry,\n): void {\n  const incompatibleKinds = sourceKinds.filter(\n    (kind) => !registry.isAssignableToAny(kind, inverseKinds),\n  );\n  if (incompatibleKinds.length === 0) return;\n\n  throw new ConfigurationError(\n    `inverseOf(\"${sourceEdge}\", \"${inverseEdge}\") is endpoint-incompatible: ` +\n      `${sourceSide} kind(s) [${incompatibleKinds.join(\", \")}] declared on \"${sourceEdge}\" ` +\n      `cannot be assigned to any of \"${inverseEdge}\"'s ${inverseSide} kind(s) [${inverseKinds.join(\", \")}].`,\n    {\n      metaEdge: META_EDGE_INVERSE_OF,\n      sourceEdge,\n      inverseEdge,\n      sourceEndpoint: sourceSide,\n      inverseEndpoint: inverseSide,\n      incompatibleKinds,\n      allowedKinds: inverseKinds,\n    },\n    {\n      suggestion:\n        \"Make the inverse edge declarations exact reversals (allowing subClassOf assignability), or remove the inverseOf relation.\",\n    },\n  );\n}\n","import { type GraphIdentityConfig } from \"../core/define-graph\";\nimport { type AnyEdgeType, type NodeType } from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport {\n  type NamedOntologyRelation,\n  validateOntologyRelations,\n} from \"../ontology/validation\";\nimport { requireDefined } from \"../utils/presence\";\nimport {\n  computeClosuresFromNamedOntology,\n  createEmptyClosures,\n  KindRegistry,\n} from \"./kind-registry\";\nimport {\n  type EdgeEndpointKinds,\n  validateImpliesEndpointCompatibility,\n} from \"./validate-implies\";\nimport { validateInverseEndpointCompatibility } from \"./validate-inverse\";\n\nexport function buildValidatedKindRegistry(\n  input: Readonly<{\n    nodeKinds: ReadonlyMap<string, NodeType>;\n    edgeKinds: ReadonlyMap<string, AnyEdgeType>;\n    ontology: readonly NamedOntologyRelation[];\n    edgeEndpoints: ReadonlyMap<string, EdgeEndpointKinds>;\n    identity?: GraphIdentityConfig;\n  }>,\n): KindRegistry {\n  if (input.ontology.length === 0) {\n    const registry = new KindRegistry(\n      input.nodeKinds,\n      input.edgeKinds,\n      createEmptyClosures(),\n      input.identity,\n    );\n    validateImpliesEndpointCompatibility(input.edgeEndpoints, registry);\n    return registry;\n  }\n\n  const issues = validateOntologyRelations(input.ontology);\n  if (issues.length > 0) {\n    const firstIssue = requireDefined(issues[0]);\n    throw new ConfigurationError(\n      `Ontology is incoherent: ${firstIssue.message}`,\n      {\n        code: firstIssue.code,\n        issues,\n      },\n      {\n        suggestion:\n          \"Correct the ontology relations before constructing or loading the graph registry.\",\n      },\n    );\n  }\n\n  const closures = computeClosuresFromNamedOntology(input.ontology);\n  const registry = new KindRegistry(\n    input.nodeKinds,\n    input.edgeKinds,\n    closures,\n    input.identity,\n  );\n  validateImpliesEndpointCompatibility(input.edgeEndpoints, registry);\n  validateInverseEndpointCompatibility(\n    input.ontology,\n    input.edgeEndpoints,\n    registry,\n  );\n  return registry;\n}\n","/**\n * Builder functions for creating KindRegistry from GraphDef.\n */\nimport {\n  getEdgeKinds,\n  getNodeKinds,\n  type GraphDef,\n} from \"../core/define-graph\";\nimport {\n  getEdgeEndpointPairs,\n  projectTargetKinds,\n} from \"../core/edge-endpoints\";\nimport {\n  type AnyEdgeType,\n  type EdgeRegistration,\n  type NodeRegistration,\n  type NodeType,\n} from \"../core/types\";\nimport { type NamedOntologyRelation } from \"../ontology/validation\";\nimport { buildValidatedKindRegistry } from \"./build-validated\";\nimport type { KindRegistry } from \"./kind-registry\";\nimport { type EdgeEndpointKinds } from \"./validate-implies\";\n\nconst EMPTY_NAMED_ONTOLOGY: readonly NamedOntologyRelation[] = [];\n\n// ============================================================\n// Build Registry from GraphDef\n// ============================================================\n\n/**\n * Builds a KindRegistry from a GraphDef.\n *\n * This precomputes all transitive closures for efficient runtime queries.\n *\n * @example\n * ```typescript\n * const graph = defineGraph({\n *   id: \"my_graph\",\n *   nodes: { Person: { type: Person }, Company: { type: Company } },\n *   edges: { worksAt: { type: worksAt, from: [Person], to: [Company] } },\n *   ontology: [subClassOf(Company, Organization)],\n * });\n *\n * const registry = buildKindRegistry(graph);\n * registry.isSubClassOf(\"Company\", \"Organization\"); // true\n * ```\n */\nexport function buildKindRegistry<G extends GraphDef>(graph: G): KindRegistry {\n  // Extract node types\n  const nodeTypes = extractNodeTypes(graph);\n\n  // Extract edge types\n  const edgeTypes = extractEdgeTypes(graph);\n\n  return buildValidatedKindRegistry({\n    nodeKinds: nodeTypes,\n    edgeKinds: edgeTypes,\n    ontology:\n      graph.ontology.length === 0 ?\n        EMPTY_NAMED_ONTOLOGY\n      : graph.ontology.map((relation): NamedOntologyRelation => ({\n          metaEdge: relation.metaEdge.name,\n          from:\n            typeof relation.from === \"string\" ?\n              relation.from\n            : relation.from.kind,\n          to: typeof relation.to === \"string\" ? relation.to : relation.to.kind,\n        })),\n    edgeEndpoints: buildEdgeEndpointKinds(graph.edges),\n    ...(graph.identity === undefined ? {} : { identity: graph.identity }),\n  });\n}\n\n/**\n * Maps each registered edge kind to its declared domain/range kind names,\n * for `validateImpliesEndpointCompatibility`. A `Map` (rather than the\n * plain `graph.edges` object) so a lookup for an edge kind literally named\n * \"toString\" or another `Object.prototype` member can't resolve to an\n * inherited member instead of `undefined`.\n */\nfunction buildEdgeEndpointKinds(\n  edges: Record<string, EdgeRegistration>,\n): ReadonlyMap<string, EdgeEndpointKinds> {\n  const result = new Map<string, EdgeEndpointKinds>();\n  for (const [kind, registration] of Object.entries(edges)) {\n    result.set(kind, {\n      from: registration.from.map((node) => node.kind),\n      to: projectTargetKinds(registration.to),\n      pairs: getEdgeEndpointPairs(registration.from, registration.to),\n    });\n  }\n  return result;\n}\n\n// ============================================================\n// Node Kind Extraction\n// ============================================================\n\n/**\n * Extracts all node types from a GraphDef into a Map.\n */\nfunction extractNodeTypes<G extends GraphDef>(\n  graph: G,\n): ReadonlyMap<string, NodeType> {\n  const result = new Map<string, NodeType>();\n\n  for (const typeName of getNodeKinds(graph)) {\n    const registration = graph.nodes[typeName] as NodeRegistration;\n    result.set(typeName, registration.type);\n  }\n\n  return result;\n}\n\n// ============================================================\n// Edge Type Extraction\n// ============================================================\n\n/**\n * Extracts all edge types from a GraphDef into a Map.\n */\nfunction extractEdgeTypes<G extends GraphDef>(\n  graph: G,\n): ReadonlyMap<string, AnyEdgeType> {\n  const result = new Map<string, AnyEdgeType>();\n\n  for (const typeName of getEdgeKinds(graph)) {\n    const registration = graph.edges[typeName] as EdgeRegistration;\n    result.set(typeName, registration.type);\n  }\n\n  return result;\n}\n","/** Shared semantic preparation for managed and adopted schema-version writes. */\nimport type { GraphDef } from \"../core/define-graph\";\nimport { buildKindRegistry } from \"../registry\";\nimport {\n  computeSchemaHash,\n  serializeSchema,\n  serializeSchemaPreservingUnknownFields,\n} from \"./serializer\";\nimport type { SchemaHash, SerializedSchema } from \"./types\";\n\nexport type PreparedSchemaVersion = Readonly<{\n  version: number;\n  schemaDocument: SerializedSchema;\n  schemaHash: SchemaHash;\n}>;\n\nexport async function prepareNewSchemaVersion<G extends GraphDef>(\n  graph: G,\n  currentVersion: number,\n  previous: SerializedSchema | undefined,\n): Promise<PreparedSchemaVersion> {\n  // Reject invalid graph relations before a schema row can be written.\n  buildKindRegistry(graph);\n  const version = currentVersion + 1;\n  const schemaDocument =\n    previous === undefined ?\n      serializeSchema(graph, version)\n    : serializeSchemaPreservingUnknownFields(graph, version, previous);\n  const schemaHash = await computeSchemaHash(schemaDocument);\n  return { version, schemaDocument, schemaHash };\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 { type GraphIdentityConfig } from \"../core/define-graph\";\nimport {\n  type Cardinality,\n  type Collation,\n  type DeleteBehavior,\n  type EndpointExistence,\n  type GraphAnnotations,\n  type KindAnnotations,\n  type TemporalMode,\n  type UniquenessScope,\n} from \"../core/types\";\nimport { type GraphExtension } from \"../graph-extension/extension-types\";\nimport {\n  validateEdgeIndexKeysPresence,\n  validateNodeIndexKeyContract,\n} from \"../indexes/node-key-contract\";\nimport {\n  type IndexDeclaration,\n  NODE_INDEX_KEY_DIRECTIONS,\n  NODE_SYSTEM_COLUMN_NAMES,\n} 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\n// Node index keys reject edge-only join columns. The shared runtime tuple also\n// defines the public node-system-column type and the normalized contract guard,\n// keeping construction, persisted schemas, and DDL compilation aligned.\nconst nodeSystemColumnNameZod = z.enum(NODE_SYSTEM_COLUMN_NAMES);\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 nodeIndexKeyZod = z.discriminatedUnion(\"type\", [\n  z.object({\n    type: z.literal(\"field\"),\n    pointer: jsonPointerZod,\n    valueType: valueTypeOrUndefinedZod,\n    direction: z.enum(NODE_INDEX_KEY_DIRECTIONS),\n  }),\n  z.object({\n    type: z.literal(\"system\"),\n    column: nodeSystemColumnNameZod,\n    direction: z.enum(NODE_INDEX_KEY_DIRECTIONS),\n  }),\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    // Node-only; canonicalized by absence like `method`, so absent/optional\n    // here matches `defineNodeIndex` only emitting it when non-empty.\n    // `.min(1)` rejects an explicit `[]` at the boundary rather than\n    // silently accepting a present-but-empty array that would have to be\n    // canonicalized away again downstream (see `serializeNodeIndexDeclaration`).\n    keySystemColumns: z.array(nodeSystemColumnNameZod).min(1).optional(),\n    keys: z.array(nodeIndexKeyZod).min(1).optional(),\n  })\n  .loose()\n  .superRefine((index, ctx) => {\n    if (index.keys === undefined) return;\n    for (const message of validateNodeIndexKeyContract({\n      keys: index.keys.map((key) =>\n        key.type === \"field\" ? { ...key, valueType: key.valueType } : key,\n      ),\n      fields: index.fields,\n      coveringFields: index.coveringFields,\n      keySystemColumns: index.keySystemColumns,\n      unique: index.unique,\n      scope: index.scope,\n      method: index[\"method\"],\n    })) {\n      ctx.addIssue({ code: \"custom\", message });\n    }\n  });\n\nconst edgeIndexDeclarationZod = z\n  .object({\n    entity: z.literal(\"edge\"),\n    kind: z.string(),\n    direction: edgeIndexDirectionZod,\n    ...indexDeclarationCommonShape,\n  })\n  .loose()\n  .superRefine((index, ctx) => {\n    const message = validateEdgeIndexKeysPresence(index);\n    if (message !== undefined) ctx.addIssue({ code: \"custom\", message });\n  });\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());\nconst annotationsZod = z.record(z.string(), z.json());\n\nconst runtimeNodeDocumentZod = z\n  .object({\n    description: z.string().optional(),\n    annotations: annotationsZod.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: annotationsZod.optional(),\n    from: z.array(z.string()),\n    to: z.union([\n      z.array(z.string()),\n      z.record(z.string(), z.array(z.string())),\n    ]),\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    annotations: annotationsZod.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[]; // Injectively encoded unordered pairs\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  targetKindsBySource?: Readonly<Record<string, readonly string[]>>;\n  properties: JsonSchema;\n  cardinality: Cardinality;\n  endpointExistence: EndpointExistence;\n  matchIdentity?: Readonly<{\n    name: string;\n    fields: readonly string[];\n  }>;\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\n  .object({\n    graphId: z.string(),\n    annotations: annotationsZod.optional(),\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.default(\"kind\"),\n                  collation: collationZod.default(\"binary\"),\n                })\n                .loose(),\n            ),\n            onDelete: deleteBehaviorZod,\n            description: z.string().optional(),\n            annotations: annotationsZod.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            targetKindsBySource: z\n              .record(z.string(), z.array(z.string()))\n              .optional(),\n            properties: z.record(z.string(), z.unknown()),\n            cardinality: cardinalityZod,\n            endpointExistence: endpointExistenceZod,\n            matchIdentity: z\n              .object({\n                name: z.string().min(1),\n                fields: z.array(z.string()),\n              })\n              .loose()\n              .optional(),\n            description: z.string().optional(),\n            annotations: annotationsZod.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(\n            checkRecordKeyMatchesField(\"name\", \"ontology.metaEdges\"),\n          ),\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    identity: z\n      .object({ sameIdAcrossKinds: z.enum([\"fold\", \"ignore\"]) })\n      .readonly()\n      .optional(),\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  // Top-level additions from newer TypeGraph versions must survive an older\n  // schema writer's parse-and-recommit cycle. Nested schema shapes already use\n  // the same forward-compatible posture; keeping the root strict would still\n  // strip a newly introduced top-level slice before the writer could preserve\n  // it. TypeGraph 0.54 is the oldest writer floor with this guarantee.\n  .loose();\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  /** Consumer-owned graph-scoped JSON metadata. */\n  annotations?: GraphAnnotations;\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  /** Durable opt-in to the TypeGraph Identity Profile. */\n  identity?: GraphIdentityConfig;\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/** The version and content hash of one stored schema snapshot. */\nexport type SchemaIdentity = Readonly<{\n  version: number;\n  hash: SchemaHash;\n}>;\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 { assertEdgeMatchIdentityBackendSupport } from \"../backend/edge-match-identity\";\nimport { countSchemaKindRows } from \"../backend/schema-kind-emptiness\";\nimport {\n  type CommitSchemaVersionIfKindsEmptyResult,\n  type CommitSchemaVersionParams,\n  type GraphBackend,\n  type PopulatedSchemaKind,\n  type SchemaCommitPreflightBackend,\n  type SchemaKindEmptinessProbe,\n  type SchemaVersionRow,\n  type TransactionBackend,\n} from \"../backend/types\";\nimport {\n  getEdgeKinds,\n  getNodeKinds,\n  type GraphDef,\n} from \"../core/define-graph\";\nimport { resolveGraphVectorSlots } from \"../core/embedding\";\nimport { type KindEntity } from \"../core/types\";\nimport {\n  ConfigurationError,\n  DatabaseOperationError,\n  MigrationError,\n  StaleVersionError,\n} from \"../errors\";\nimport { mergeGraphExtension } from \"../graph-extension/merge\";\nimport { stripGraphExtension } from \"../graph-extension/remove\";\nimport {\n  ensureIdentitySchemaStorage,\n  identityKindCascadeNeeded,\n  identityKindCascadePreflight,\n  identitySchemaCommitPreflight,\n  withIdentityDdlRaceRetry,\n} from \"../identity/schema-transition\";\nimport {\n  createSqlSchema,\n  requireSqlSchema,\n  type SqlSchema,\n} from \"../query/compiler/schema\";\nimport { buildKindRegistry } from \"../registry\";\nimport { freezeDeep } from \"../utils/object\";\nimport { isMissingTableError } from \"../utils/sql-errors\";\nimport {\n  computeSchemaDiff,\n  getMigrationActions,\n  isBackwardsCompatible,\n  matchIdentitiesEqual,\n  type SchemaDiff,\n} from \"./migration\";\nimport { prepareNewSchemaVersion } from \"./new-schema-version\";\nimport {\n  computeSchemaHash,\n  getSchemaHash,\n  serializeSchema,\n  serializeSchemaPreservingUnknownFields,\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 *\n * **The persisted document is the sole authority on extension kinds.** The\n * supplied graph's own extension slice is stripped before the stored one is\n * applied, so the result is a function of `activeRow` alone. Without this, a\n * caller passing an already-merged graph — `store.graph` is public and\n * returns one — resurrects extension kinds another writer has since removed:\n * `unionDocuments` unions the local slice back in and the absent-from-stored\n * kinds win. That silently undoes `Store.removeKinds` while its\n * `typegraph_kind_removals` row stays queued, leaving a kind the schema calls\n * live with a pending cleanup that later deletes its rows.\n *\n * A compile-time graph has no extension slice, so the strip is a no-op for\n * the `createStoreWithSchema` / `assertSchemaCurrent` callers. Mirrors\n * `Store.#catchUpToStored`, which has stripped for this exact reason.\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 compileTimeGraph = stripGraphExtension(graph);\n  const merged =\n    storedSchema.extension === undefined ?\n      compileTimeGraph\n    : mergeGraphExtension(compileTimeGraph, 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  /**\n   * Whether `createStoreWithSchema` brings the base-relation system\n   * indexes up to the running library version at boot. Default:\n   * `\"materialize\"`. Pass `\"skip\"` when a boot must not run potentially\n   * long index builds inline (e.g. a large PostgreSQL deployment behind a\n   * readiness probe) — then run `store.materializeSystemIndexes()`\n   * out-of-band after upgrading.\n   */\n  systemIndexes?: \"materialize\" | \"skip\";\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   * The effective `SqlSchema` (custom table names) the graph's Store reads.\n   * Identity schema commits derive their mandatory closure preflight from it;\n   * the preflight itself is never accepted from callers, so it cannot be\n   * substituted or suppressed.\n   */\n  schema?: SqlSchema;\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  await adoptBaseSchemaStorage(backend);\n  assertGraphEdgeMatchIdentitySupport(backend, graph);\n\n  if (activeSchema === undefined) {\n    // No schema exists - initialize with version 1. Only the effective\n    // `SqlSchema` is threaded through; `initializeSchema` derives the\n    // mandatory identity preflight itself, so no public first-commit path\n    // can skip or replace the enablement work.\n    const result = await initializeSchemaImpl(backend, graph, {\n      ...(options?.schema === undefined ? {} : { schema: options.schema }),\n      baseSchemaPrepared: true,\n    });\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 = serializeSchemaPreservingUnknownFields(\n    graph,\n    activeSchema.version + 1,\n    storedSchema,\n  );\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      // An identity-enabled commit must never land without the closure\n      // preflight, whichever public path drove it. It is derived HERE —\n      // never accepted from the caller — so it cannot be substituted or\n      // suppressed; `options.schema` only points it at the effective tables.\n      const preflight =\n        graph.identity === undefined ?\n          undefined\n        : await prepareIdentitySchemaCommit(backend, graph, {\n            enablement: storedSchema.identity === undefined,\n            ...(options?.schema === undefined ?\n              {}\n            : { schema: options.schema }),\n          });\n      const committedRow =\n        preflight === undefined ?\n          await commitNewSchemaVersion(\n            backend,\n            graph,\n            activeSchema.version,\n            storedSchema,\n          )\n        : await commitNewSchemaVersionWithPreflight(\n            backend,\n            graph,\n            activeSchema.version,\n            preflight,\n            storedSchema,\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    // The kind-removal pointer is noise on the dominant case (a property\n    // change), so it appears only when the diff actually removes a kind —\n    // which is exactly when `migrateSchema()` would refuse the commit.\n    //\n    // It must NOT point at `Store.removeKinds()`. A kind missing from the\n    // *code graph* is a compile-time kind, and `removeKinds` rejects those by\n    // design (`RemoveCompileTimeKindError`) — they are removed by recompiling\n    // and redeploying. `removeKinds` is for runtime extension kinds, which\n    // cannot be the cause of this diff.\n    const removesKind = [...diff.nodes, ...diff.edges].some(\n      (change) => change.type === \"removed\",\n    );\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        (removesKind ?\n          ` This diff removes a kind: migrateSchema() refuses to drop one ` +\n          `that still holds rows, so export or delete those rows first and ` +\n          `retry.`\n        : \"\"),\n      {\n        graphId: graph.id,\n        fromVersion: activeSchema.version,\n        toVersion: activeSchema.version + 1,\n        reason: \"breaking-change\",\n        diff,\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 BaseSchemaMigrationError if deployment-wide base storage is not at\n *   the version required by the backend.\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  await backend.assertBaseSchemaCurrent?.();\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 = serializeSchemaPreservingUnknownFields(\n      merged,\n      activeRow.version + 1,\n      storedSchema,\n    );\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  await assertVectorContributionsInitialized(backend, merged);\n  return {\n    graph: merged,\n    activeRow,\n    result: { status: \"unchanged\", version: activeRow.version },\n  };\n}\n\n/**\n * SELECT-only verification that every embedding `(kind, field)` slot's\n * durable contribution marker is initialized — the vector counterpart of\n * `backend.assertRuntimeContributionsInitialized` (which covers fulltext).\n * Keeps `createVerifiedStore`'s \"throws when runtime-contribution markers\n * are missing/stale\" guarantee honest for vectors: without it the verified\n * attach would pass but the first vector op would then throw. Enumerated\n * from the merged graph (same idiom as the privileged boot materializer);\n * a no-op on backends without vector support or graphs with no embeddings.\n */\nasync function assertVectorContributionsInitialized(\n  backend: GraphBackend,\n  graph: GraphDef,\n): Promise<void> {\n  if (backend.capabilities.vector?.supported !== true) return;\n  const slots = resolveGraphVectorSlots(graph);\n  const assertVectorSlotsInitialized = backend.assertVectorSlotsInitialized;\n  if (assertVectorSlotsInitialized !== undefined) {\n    await assertVectorSlotsInitialized(slots);\n    return;\n  }\n  const assertVectorSlotInitialized = backend.assertVectorSlotInitialized;\n  if (assertVectorSlotInitialized === undefined) return;\n  for (const slot of slots) {\n    await assertVectorSlotInitialized(slot);\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      reason: \"schema-behind\",\n      diff,\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 BaseSchemaMigrationError if deployment-wide base storage is not at\n *   the version required by the backend.\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 * Returns the backend's atomic preflight-commit primitive, throwing\n * `IDENTITY_REQUIRES_ATOMIC_BACKEND` if the backend doesn't support\n * committing identity data atomically with a schema transition.\n */\nfunction requireCommitWithPreflight(\n  backend: GraphBackend,\n  graph: GraphDef,\n): NonNullable<GraphBackend[\"commitSchemaVersionWithPreflight\"]> {\n  const commitWithPreflight = backend.commitSchemaVersionWithPreflight;\n  if (commitWithPreflight === undefined) {\n    throw new ConfigurationError(\n      \"This backend cannot atomically commit identity data with a schema transition.\",\n      {\n        code: \"IDENTITY_REQUIRES_ATOMIC_BACKEND\",\n        graphId: graph.id,\n      },\n    );\n  }\n  return commitWithPreflight;\n}\n\nasync function commitInitialEdgeIdentityOnEmptyKinds(\n  backend: GraphBackend,\n  graph: GraphDef,\n  commit: CommitSchemaVersionParams,\n  edgeKinds: readonly string[],\n): Promise<SchemaVersionRow> {\n  const commitIfKindsEmpty = backend.commitSchemaVersionIfKindsEmpty;\n  if (commitIfKindsEmpty === undefined) {\n    throw new ConfigurationError(\n      \"This backend cannot atomically verify empty edge kinds while adopting durable edge match identity.\",\n      {\n        code: \"EDGE_MATCH_IDENTITY_REQUIRES_ATOMIC_BACKEND\",\n        graphId: graph.id,\n        edgeKinds,\n      },\n    );\n  }\n  const result = await commitIfKindsEmpty(\n    commit,\n    edgeKinds.map((kind) => ({\n      entity: \"edge\" as const,\n      kind,\n      rows: \"all\" as const,\n    })),\n  );\n  if (result.status === \"committed\") return result.row;\n\n  throw edgeMatchIdentityRekeyPopulatedError(\n    graph.id,\n    0,\n    result.kinds.map((entry) => entry.kind),\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 */\ntype InitializeSchemaOptions = Readonly<{\n  /**\n   * The effective `SqlSchema` (custom table names) the graph's Store will\n   * read. The identity enablement preflight is always derived internally.\n   */\n  schema?: SqlSchema;\n}>;\n\ntype InitializeSchemaImplOptions = InitializeSchemaOptions &\n  Readonly<{\n    /** The caller already completed the deployment-wide adoption gate. */\n    baseSchemaPrepared: boolean;\n  }>;\n\nexport async function initializeSchema<G extends GraphDef>(\n  backend: GraphBackend,\n  graph: G,\n  options?: Readonly<{\n    /**\n     * The effective `SqlSchema` (custom table names) the graph's Store will\n     * read. The identity enablement preflight is always derived internally —\n     * it is deliberately not a parameter, so no caller can commit version 1\n     * of an identity-enabled graph without the fold scan, contradiction\n     * validation, and closure build.\n     */\n    schema?: SqlSchema;\n  }>,\n): Promise<SchemaVersionRow> {\n  return initializeSchemaImpl(backend, graph, {\n    ...(options?.schema === undefined ? {} : { schema: options.schema }),\n    baseSchemaPrepared: false,\n  });\n}\n\nasync function initializeSchemaImpl<G extends GraphDef>(\n  backend: GraphBackend,\n  graph: G,\n  options: InitializeSchemaImplOptions,\n): Promise<SchemaVersionRow> {\n  // Structural gates (e.g. endpoint-incompatible implies() relations)\n  // must reject before the schema is durably committed, not only when a\n  // Store is later constructed against it — buildKindRegistry throws the\n  // same ConfigurationError a Store construction would, just earlier.\n  buildKindRegistry(graph);\n\n  if (!options.baseSchemaPrepared) {\n    // Base storage belongs to the running library version, not to this graph\n    // document. Adopt it before publishing schema version 1 so a DDL refusal\n    // cannot leave a current graph schema over obsolete physical relations.\n    await adoptBaseSchemaStorage(backend);\n    assertGraphEdgeMatchIdentitySupport(backend, graph);\n  }\n\n  const edgeIdentityKinds =\n    edgeKindsRequiringMatchIdentityMaterialization(graph);\n  const edgeMatchIdentityPreflight = prepareEdgeMatchIdentityCommitPreflight(\n    graph,\n    edgeIdentityKinds,\n    0,\n  );\n\n  const schema = serializeSchema(graph, 1);\n  const hash = await computeSchemaHash(schema);\n  const commit = {\n    graphId: graph.id,\n    expected: { kind: \"initial\" } as const,\n    version: 1,\n    schemaHash: hash,\n    schemaDoc: schema,\n  };\n\n  if (graph.identity === undefined) {\n    if (edgeMatchIdentityPreflight === undefined) {\n      return backend.commitSchemaVersion(commit);\n    }\n    const commitWithPreflight = backend.commitSchemaVersionWithPreflight;\n    return commitWithPreflight === undefined ?\n        commitInitialEdgeIdentityOnEmptyKinds(\n          backend,\n          graph,\n          commit,\n          edgeIdentityKinds,\n        )\n      : commitWithPreflight(commit, edgeMatchIdentityPreflight);\n  }\n\n  const commitWithPreflight = requireCommitWithPreflight(backend, graph);\n\n  // An identity-enabled graph's FIRST schema commit is an enablement: a\n  // legacy database populated through an unmanaged Store can already hold\n  // same-id peers and assertions, so the fold scan, contradiction\n  // validation, and closure build must commit atomically with version 1 —\n  // exactly like a later enablement migration. Always DERIVED here (over\n  // `options.schema` when supplied, else the backend's effective table\n  // names), never accepted from the caller — a substitutable preflight would\n  // let a no-op callback commit a version 1 that every later hash check\n  // accepts while identity reads answer from a never-built closure.\n  const preflight = await prepareIdentitySchemaCommit(backend, graph, {\n    enablement: true,\n    ...(options.schema === undefined ? {} : { schema: options.schema }),\n  });\n  // The preflight issues idempotent identity DDL INSIDE this transaction (see\n  // `provisionDerivedRelationsInCommit`), so two replicas booting at once can\n  // lose the catalog race here — and PostgreSQL will accept nothing but a\n  // rollback afterwards, which makes the whole attempt the smallest retryable\n  // unit. Safe to re-run: the failed attempt rolled back entirely, `commit` is\n  // precomputed and immutable, and the CAS still decides correctness — if a\n  // writer really did commit in between, the retry surfaces `StaleVersionError`\n  // instead of silently succeeding.\n  return withIdentityDdlRaceRetry(() =>\n    commitWithPreflight(commit, async (transactionBackend) => {\n      await edgeMatchIdentityPreflight?.(transactionBackend);\n      await preflight(transactionBackend);\n    }),\n  );\n}\n\nexport type MigrateSchemaOptions = Readonly<{\n  /**\n   * Commit even when a dropped kind still holds rows.\n   *\n   * **This does not preserve those rows.** They are immediately unreachable —\n   * nothing references the kind any more — and they are not safe from\n   * deletion either: `materializeRemovals` re-derives removals by walking\n   * schema-version history, so the next reconcile finds the dropped kind and\n   * hard-deletes its rows, including soft-deleted ones. The flag buys a\n   * committed schema, not retained data.\n   *\n   * If you need the rows, copy them out **before** committing. If you want\n   * them removed, prefer `Store.removeKinds()`, which queues the cleanup\n   * explicitly instead of relying on history reconciliation.\n   *\n   * Dropping an *empty* kind needs no flag — it strands nothing, and it is\n   * the last step of the documented three-deploy kind-removal flow.\n   *\n   * @defaultValue false\n   */\n  discardDroppedKindRows?: boolean;\n  /**\n   * The effective `SqlSchema` (custom table names) the graph's Store reads.\n   * The identity closure preflight an identity-enabled migration commits is\n   * derived from it and cannot be substituted by callers.\n   */\n  schema?: SqlSchema;\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 * Folds the persisted graph extension into `graph` first, like every other\n * commit path — kinds committed at runtime by `Store.evolve()` live in\n * `schema_doc.extension`, so committing the caller's graph verbatim would\n * erase them while leaving their rows behind. Property-level breaking\n * changes (the documented \"force the contract deploy\" use) are unaffected.\n *\n * @param backend - The database backend\n * @param graph - The current graph definition\n * @param currentVersion - The current active schema version\n * @param options - See {@link MigrateSchemaOptions}\n * @returns The new version number\n * @throws MigrationError with `reason: \"kind-removal\"` when the commit would\n *   drop a kind that still holds rows and `discardDroppedKindRows` is not set.\n */\nexport async function migrateSchema<G extends GraphDef>(\n  backend: GraphBackend,\n  graph: G,\n  currentVersion: number,\n  options?: MigrateSchemaOptions,\n): Promise<number> {\n  const {\n    graph: target,\n    storedSchema,\n    activeRow,\n  } = await loadAndMergeGraphExtensionDocument(backend, graph);\n\n  // Staleness first. The commit's CAS would catch this anyway, but only after\n  // the guard below has probed row counts against a baseline the caller never\n  // saw — so a stale caller dropping a populated kind would get a\n  // `kind-removal` MigrationError quoting versions that were never theirs,\n  // instead of the `StaleVersionError` the concurrency contract documents.\n  // Diagnose the caller's actual problem, and leave the CAS to catch writers\n  // that advance the version after this point.\n  if (activeRow !== undefined && activeRow.version !== currentVersion) {\n    throw new StaleVersionError({\n      graphId: graph.id,\n      expected: currentVersion,\n      actual: activeRow.version,\n    });\n  }\n\n  const dropped =\n    storedSchema === undefined ?\n      []\n    : [\n        ...droppedKinds(storedSchema.nodes, getNodeKinds(target), \"node\"),\n        ...droppedKinds(storedSchema.edges, getEdgeKinds(target), \"edge\"),\n      ];\n  const guardedDrops = options?.discardDroppedKindRows === true ? [] : dropped;\n  const rekeyedEdgeKinds = edgeKindsRequiringMatchIdentityMaterialization(\n    target,\n    storedSchema,\n  );\n  await adoptBaseSchemaStorage(backend);\n  assertGraphEdgeMatchIdentitySupport(backend, target);\n  // No cleanup is queued here, deliberately, and redundancy is the whole\n  // reason. `materializeRemovals` derives removals by walking schema-version\n  // history (`reconcilePendingRemovals` diffs consecutive documents' kind\n  // sets), so a kind dropped by this commit is discovered and reclaimed on\n  // the next reconcile whether or not a `typegraph_kind_removals` row exists\n  // — on every path, `discardDroppedKindRows` included. Writing one would\n  // change nothing except adding a second source of truth.\n  //\n  // The walk is only as good as retained history: `reconcilePendingRemovals`\n  // stops at the first absent prior version, so a drop below a pruned or\n  // gapped range becomes undiscoverable. Callers who prune schema versions\n  // should run `materializeRemovals` before pruning.\n\n  // An identity-enabled target commits through the same data preflight\n  // `createStoreWithSchema` and `Store.evolve()` use: the closure is derived\n  // state, so a version that changes the identity profile — or turns identity\n  // on for the first time — must not become active while the closure still\n  // reflects the previous schema. Explicit `migrateSchema()` is the path the\n  // MigrationError message points operators at, so it cannot be the one path\n  // that skips it.\n  // Node kinds this commit REMOVES cascade the assertion ledger inside the\n  // commit transaction (edge kinds carry no assertions). This uses the full\n  // `dropped` list, not `guardedDrops`: with `discardDroppedKindRows` the rows\n  // are reclaimed later by materializeRemovals, which never touches identity\n  // tables.\n  const droppedNodeKinds = dropped\n    .filter((drop) => drop.entity === \"node\")\n    .map((drop) => drop.kind);\n  const identityPreflight =\n    activeRow === undefined ? undefined\n    : target.identity === undefined ?\n      // Identity being OFF in the target is not evidence the ledger is empty:\n      // disabling retains the assertion rows. A drop committed here would\n      // strand every assertion touching the kind — a later re-enablement\n      // filters them out of the closure while raw ledger reads and merge\n      // staging still see them.\n      await prepareIdentityKindCascade(backend, target, {\n        droppedNodeKinds,\n        probeBeforeCascade: storedSchema?.identity === undefined,\n        ...(options?.schema === undefined ? {} : { schema: options.schema }),\n      })\n    : await prepareIdentitySchemaCommit(backend, target, {\n        enablement: storedSchema?.identity === undefined,\n        droppedNodeKinds,\n        ...(options?.schema === undefined ? {} : { schema: options.schema }),\n      });\n\n  const edgeMatchIdentityPreflight = prepareEdgeMatchIdentityCommitPreflight(\n    target,\n    rekeyedEdgeKinds,\n    currentVersion,\n  );\n\n  const committed =\n    (\n      identityPreflight === undefined &&\n      edgeMatchIdentityPreflight === undefined\n    ) ?\n      guardedDrops.length > 0 ?\n        await commitDroppedKindsOnlyWhenEmpty(\n          backend,\n          target,\n          currentVersion,\n          guardedDrops,\n          storedSchema,\n        )\n      : await commitNewSchemaVersion(\n          backend,\n          target,\n          currentVersion,\n          storedSchema,\n        )\n    : await commitNewSchemaVersionWithPreflight(\n        backend,\n        target,\n        currentVersion,\n        async (transactionBackend) => {\n          // The emptiness fence moves inside the commit transaction here: the\n          // preflight-carrying primitive is the only one that can also run the\n          // identity rebuild atomically, so the probe runs alongside it rather\n          // than through `commitSchemaVersionIfKindsEmpty`.\n          await assertDroppedKindsEmpty(\n            transactionBackend,\n            target.id,\n            currentVersion,\n            guardedDrops,\n          );\n          await edgeMatchIdentityPreflight?.(transactionBackend);\n          await identityPreflight?.(transactionBackend);\n        },\n        storedSchema,\n      );\n  return committed.version;\n}\n\n/**\n * Adopts deployment-wide physical storage required by this library version.\n * This is independent of any one graph's schema document.\n *\n * Bundled backends use a durable version marker, so a warm privileged open is\n * one read and no base-adoption DDL. Runtime-only construction remains\n * DDL-free.\n */\nasync function adoptBaseSchemaStorage(backend: GraphBackend): Promise<void> {\n  if (backend.adoptBaseSchema !== undefined) {\n    await backend.adoptBaseSchema();\n    return;\n  }\n  await backend.ensureEdgeMatchIdentityStorage?.();\n}\n\nfunction assertGraphEdgeMatchIdentitySupport(\n  backend: GraphBackend,\n  graph: GraphDef,\n): void {\n  for (const [kind, registration] of Object.entries(graph.edges)) {\n    const identity = registration.matchIdentity;\n    if (identity === undefined) continue;\n    assertEdgeMatchIdentityBackendSupport(identity, backend.capabilities, kind);\n  }\n}\n\n/**\n * Returns edge kinds whose target schema requires durable keys that existing\n * rows do not carry. Removing a declaration is deliberately excluded: it\n * materializes no keys, so populated rows do not need export/re-import.\n */\nfunction edgeKindsRequiringMatchIdentityMaterialization(\n  target: GraphDef,\n  storedSchema?: SerializedSchema,\n): readonly string[] {\n  return getEdgeKinds(target).filter((kind) => {\n    const after = target.edges[kind]?.matchIdentity;\n    if (after === undefined) return false;\n    const before = storedSchema?.edges[kind]?.matchIdentity;\n    return !matchIdentitiesEqual(before, after);\n  });\n}\n\n/** Refuses identity activation/re-keying while rows still lack target keys. */\nfunction prepareEdgeMatchIdentityCommitPreflight(\n  target: GraphDef,\n  edgeKinds: readonly string[],\n  currentVersion: number,\n): ((backend: SchemaCommitPreflightBackend) => Promise<void>) | undefined {\n  if (edgeKinds.length === 0) return undefined;\n  return async (backend): Promise<void> => {\n    const populated: string[] = [];\n    for (const kind of edgeKinds) {\n      const count = await countSchemaKindRows(backend, target.id, {\n        entity: \"edge\",\n        kind,\n        rows: \"all\",\n      });\n      if (count > 0) populated.push(kind);\n    }\n    if (populated.length === 0) return;\n    throw edgeMatchIdentityRekeyPopulatedError(\n      target.id,\n      currentVersion,\n      populated,\n    );\n  };\n}\n\nfunction edgeMatchIdentityRekeyPopulatedError(\n  graphId: string,\n  currentVersion: number,\n  edgeKinds: readonly string[],\n): MigrationError {\n  return new MigrationError(\n    `Refusing to activate or change match identity for populated edge kinds: ${edgeKinds.join(\", \")}. Export and hard-delete those edges, migrate the schema, then import them so TypeGraph can materialize the new durable keys.`,\n    {\n      graphId,\n      fromVersion: currentVersion,\n      toVersion: currentVersion + 1,\n      reason: \"edge-match-identity-rekey\",\n      edgeKinds,\n    },\n  );\n}\n\n/**\n * Builds the ledger-cleanup preflight for a kind-dropping commit whose target\n * graph has no identity profile. Returns `undefined` when there is nothing to\n * cascade — the ordinary case, which pays one probe and then commits through\n * exactly the primitive it always did, emptiness fence included.\n *\n * The prior schema's profile is deliberately NOT the test. The stranding case\n * is a drop committed one or more versions AFTER identity was switched off, so\n * the immediately-preceding schema has no profile either; only the ledger\n * answers whether rows are there.\n */\nasync function prepareIdentityKindCascade<G extends GraphDef>(\n  backend: GraphBackend,\n  target: G,\n  options: Readonly<{\n    droppedNodeKinds: readonly string[];\n    schema?: SqlSchema;\n    // False when THIS commit is the one disabling identity: writers on the\n    // still-enabled prior schema can commit assertions until the commit\n    // transaction takes its locks, so the outside-transaction emptiness\n    // probe is not sound and the locked cascade must always run.\n    probeBeforeCascade: boolean;\n  }>,\n): Promise<\n  ((transactionBackend: TransactionBackend) => Promise<void>) | undefined\n> {\n  if (options.droppedNodeKinds.length === 0) return undefined;\n  const schema =\n    options.schema === undefined ?\n      createSqlSchema(backend.tableNames)\n    : requireSqlSchema(options.schema, \"The schema option\");\n  if (options.probeBeforeCascade) {\n    const needed = await identityKindCascadeNeeded(\n      backend,\n      schema,\n      target.id,\n      options.droppedNodeKinds,\n    );\n    if (!needed) return undefined;\n  }\n  return identityKindCascadePreflight(\n    { graphId: target.id, schema },\n    options.droppedNodeKinds,\n  );\n}\n\n/**\n * Ensures identity storage exists and builds the preflight the schema commit\n * runs inside its own transaction.\n *\n * Enablement DDL happens *before* the commit transaction opens — issuing it\n * inside would re-enter the per-graph write lock the commit holds. A DERIVED\n * relation this transition still owes is the opposite case: its DDL travels\n * into the preflight as data (`provisionInCommit`) so the CREATE and the fill\n * are one commit, and a refused commit leaves no readable-empty relation.\n */\nasync function prepareIdentitySchemaCommit<G extends GraphDef>(\n  backend: GraphBackend,\n  target: G,\n  options: Readonly<{\n    enablement: boolean;\n    schema?: SqlSchema;\n    droppedNodeKinds?: readonly string[];\n  }>,\n): Promise<\n  (transactionBackend: SchemaCommitPreflightBackend) => Promise<void>\n> {\n  // Brand-validate before any DDL or commit: a schema-shaped plain object\n  // from an untyped caller can expose custom names to provisioning while its\n  // SQL fragments target the default tables, landing the closure where the\n  // Store never reads. Rejection happens before the version commit, so an\n  // invalid schema leaves no active row behind.\n  const schema =\n    options.schema === undefined ?\n      createSqlSchema(backend.tableNames)\n    : requireSqlSchema(options.schema, \"The schema option\");\n  // Built once and shared with the preflight below: the predicate that decides\n  // whether a fill is owed must scope the ledger by exactly the kinds the\n  // preflight's rebuild derives through.\n  const registry = buildKindRegistry(target);\n  // The SECOND call for this transition on the store-open path — `createStore`\n  // already ran one (see the discard note there) and threw its obligation away,\n  // because only this one runs where the obligation can be honored: inside the\n  // commit transaction, via the preflight below. That makes the two calls'\n  // inputs a coupling, not a coincidence: `backend`, `schema`, `registry` and\n  // `enablement` must agree with the earlier call or provisioning and filling\n  // would be decided for different shapes. `ensureIdentitySchemaStorage` is\n  // idempotent, so re-running it costs the probe and no writes.\n  const provisioning = await ensureIdentitySchemaStorage(backend, schema, {\n    graphId: target.id,\n    enablement: options.enablement,\n    registry,\n  });\n  return identitySchemaCommitPreflight(\n    {\n      graphId: target.id,\n      registry,\n      schema,\n      sameIdAcrossKinds: target.identity?.sameIdAcrossKinds ?? \"ignore\",\n    },\n    {\n      enablement: options.enablement,\n      droppedNodeKinds: options.droppedNodeKinds ?? [],\n      provisionDerivedRelations: provisioning.provisionInCommit,\n    },\n  );\n}\n\n/**\n * Refuses a commit that would drop kinds still holding rows, from inside the\n * commit transaction. The transactional sibling of\n * {@link commitDroppedKindsOnlyWhenEmpty}'s backend-side probe.\n */\nasync function assertDroppedKindsEmpty(\n  backend: TransactionBackend,\n  graphId: string,\n  currentVersion: number,\n  dropped: readonly DroppedKind[],\n): Promise<void> {\n  const counts = await Promise.all(\n    dropped.map(async (entry) => ({\n      entity: entry.entity,\n      kind: entry.kind,\n      rows: \"nonDeleted\" as const,\n      count: await countSchemaKindRows(backend, graphId, {\n        ...entry,\n        rows: \"nonDeleted\",\n      }),\n    })),\n  );\n  const populated = counts.filter((entry) => entry.count > 0);\n  if (populated.length === 0) return;\n  throwPopulatedKindRemovalError(graphId, currentVersion, populated);\n}\n\n/**\n * Refuses a schema commit that would destroy rows.\n *\n * The invariant is not \"no kind is dropped\" — it is \"no *populated* kind is\n * destroyed by accident\". Dropping an empty kind loses nothing and is the\n * last step of the documented three-deploy removal flow (stop writing →\n * delete the rows → drop from `defineGraph`). Dropping a kind that still\n * holds rows makes them unreachable immediately, and the next\n * `materializeRemovals` — which re-derives removals from schema history —\n * deletes them. The commit is the point of no return, which is why the\n * refusal happens here rather than being left to the reconciler.\n *\n * The remedy is never `Store.removeKinds()`. The fold re-adds every\n * extension kind before this runs, so a dropped kind is always a\n * *compile-time* kind — exactly the class `removeKinds` rejects\n * (`RemoveCompileTimeKindError`). Callers export or delete the rows and\n * retry, or opt into the loss.\n *\n * Mirrors the probe `Store.evolve` already runs for tightening changes, and\n * lives in the public `migrateSchema` rather than in\n * `commitNewSchemaVersion` because `Store.removeKinds` commits through that\n * primitive and drops populated kinds *by design*, having queued their\n * cleanup rows first.\n *\n * The populated-kind probes and schema CAS run through the backend's atomic\n * `commitSchemaVersionIfKindsEmpty` primitive. PostgreSQL schema changes lock\n * the active schema row FOR UPDATE while managed Store writes lock it FOR SHARE\n * and revalidate its version; SQLite serializes both with its existing BEGIN\n * IMMEDIATE writer slot. This prevents a participating schema-managed Store\n * write from landing between the final count and schema CAS, and rejects a\n * stale Store after the schema change releases the fence. Raw Stores and direct\n * backend writes remain outside this guarantee.\n */\nasync function commitDroppedKindsOnlyWhenEmpty<G extends GraphDef>(\n  backend: GraphBackend,\n  graph: G,\n  currentVersion: number,\n  dropped: readonly DroppedKind[],\n  storedSchema: SerializedSchema | undefined,\n): Promise<SchemaVersionRow> {\n  const result = await commitNewSchemaVersionIfKindsEmpty(\n    backend,\n    graph,\n    currentVersion,\n    dropped.map((entry) => ({ ...entry, rows: \"nonDeleted\" as const })),\n    storedSchema,\n  );\n  if (result.status === \"committed\") return result.row;\n\n  throwPopulatedKindRemovalError(graph.id, currentVersion, result.kinds);\n}\n\nfunction throwPopulatedKindRemovalError(\n  graphId: string,\n  currentVersion: number,\n  populated: readonly PopulatedSchemaKind[],\n): never {\n  const named = populated\n    .map((entry) => `${entry.entity} \"${entry.kind}\" (${String(entry.count)})`)\n    .join(\", \");\n  throw new MigrationError(\n    `Refusing to commit a schema for graph \"${graphId}\" that drops kinds ` +\n      `still holding rows: ${named}. Committing would make those rows ` +\n      `unreachable, and the next materializeRemovals() would delete them. ` +\n      `Export or delete those rows, then retry. Pass ` +\n      `{ discardDroppedKindRows: true } if losing them is the intent.`,\n    {\n      graphId,\n      fromVersion: currentVersion,\n      toVersion: currentVersion + 1,\n      reason: \"kind-removal\",\n      droppedKinds: {\n        nodes: populated\n          .filter((entry) => entry.entity === \"node\")\n          .map((entry) => entry.kind),\n        edges: populated\n          .filter((entry) => entry.entity === \"edge\")\n          .map((entry) => entry.kind),\n      },\n    },\n  );\n}\n\ntype DroppedKind = Readonly<{\n  kind: string;\n  entity: KindEntity;\n}>;\n\n/**\n * Kind names present in a committed schema slice but absent from the graph\n * about to be committed. Sorted so the error message and\n * `details.droppedKinds` are stable across object-key iteration order.\n */\nfunction droppedKinds(\n  committed: Readonly<Record<string, unknown>>,\n  present: readonly string[],\n  entity: KindEntity,\n): readonly DroppedKind[] {\n  const kinds = new Set(present);\n  return Object.keys(committed)\n    .filter((name) => !kinds.has(name))\n    .toSorted()\n    .map((kind) => ({ kind, entity }));\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  previous: SerializedSchema | undefined,\n): Promise<SchemaVersionRow> {\n  const params = await buildNewSchemaVersionCommit(\n    graph,\n    currentVersion,\n    previous,\n  );\n  return backend.commitSchemaVersion(params);\n}\n\n/**\n * Atomic sibling used by compatibility guards that require selected kinds to\n * remain empty through the schema CAS.\n */\nexport async function commitNewSchemaVersionIfKindsEmpty<G extends GraphDef>(\n  backend: GraphBackend,\n  graph: G,\n  currentVersion: number,\n  probes: readonly SchemaKindEmptinessProbe[],\n  previous: SerializedSchema | undefined,\n): Promise<CommitSchemaVersionIfKindsEmptyResult> {\n  const params = await buildNewSchemaVersionCommit(\n    graph,\n    currentVersion,\n    previous,\n  );\n  const commitIfKindsEmpty = backend.commitSchemaVersionIfKindsEmpty;\n  if (commitIfKindsEmpty === undefined) {\n    throw new ConfigurationError(\n      \"This backend cannot atomically fence entity writes while checking \" +\n        \"schema kind emptiness.\",\n      {\n        code: \"SCHEMA_KIND_EMPTINESS_FENCE_UNSUPPORTED\",\n        graphId: graph.id,\n      },\n    );\n  }\n  return commitIfKindsEmpty(params, probes);\n}\n\nasync function buildNewSchemaVersionCommit<G extends GraphDef>(\n  graph: G,\n  currentVersion: number,\n  previous: SerializedSchema | undefined,\n): Promise<CommitSchemaVersionParams> {\n  const prepared = await prepareNewSchemaVersion(\n    graph,\n    currentVersion,\n    previous,\n  );\n  return {\n    graphId: graph.id,\n    expected: { kind: \"active\", version: currentVersion },\n    version: prepared.version,\n    schemaHash: prepared.schemaHash,\n    schemaDoc: prepared.schemaDocument,\n  };\n}\n\n/** @internal Commits a data preflight and schema CAS in one transaction. */\nexport async function commitNewSchemaVersionWithPreflight<G extends GraphDef>(\n  backend: GraphBackend,\n  graph: G,\n  currentVersion: number,\n  preflight: (target: SchemaCommitPreflightBackend) => Promise<void>,\n  previous: SerializedSchema | undefined,\n): Promise<SchemaVersionRow> {\n  if (backend.commitSchemaVersionWithPreflight === undefined) {\n    // Match the graph-validation ordering of the plain path: reject a\n    // structurally invalid graph before probing backend capability.\n    buildKindRegistry(graph);\n  }\n  const commitWithPreflight = requireCommitWithPreflight(backend, graph);\n  // Same catalog-race retry as `initializeSchema`, for the same in-transaction\n  // identity DDL. The commit payload is built once, outside the retry, so a\n  // re-run commits the identical version and hash rather than recomputing one.\n  const commit = await buildNewSchemaVersionCommit(\n    graph,\n    currentVersion,\n    previous,\n  );\n  return withIdentityDdlRaceRetry(() => commitWithPreflight(commit, preflight));\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      {\n        graphId,\n        fromVersion: 0,\n        toVersion: targetVersion,\n        reason: \"no-active-version\",\n      },\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 — the committed document itself,\n * with the `nodes` / `edges` / `ontology` maps the database actually holds.\n *\n * This is the answer to \"what kinds does this database already have?\". Use\n * {@link getCommittedSchemaVersion} when only the version number is needed.\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 activeRow = await backend.getActiveSchema(graph.id);\n  if (activeRow === undefined) return undefined;\n\n  // Fold in the persisted graph-extension first — the same merge the commit\n  // path performs. Without it a compile-time graph is diffed against a stored\n  // schema that also contains runtime-committed kinds, so those kinds read as\n  // removals and an unchanged schema looks like it needs a breaking migration.\n  const { graph: merged, storedSchema } = mergeStoredGraphExtension(\n    graph,\n    activeRow,\n  );\n  const currentSchema = serializeSchemaPreservingUnknownFields(\n    merged,\n    activeRow.version + 1,\n    storedSchema,\n  );\n  const diff = computeSchemaDiff(storedSchema, currentSchema);\n\n  return diff.hasChanges ? diff : { ...diff, toVersion: diff.fromVersion };\n}\n\n/**\n * Whether committing `graph` would require a schema migration — a SELECT-only\n * pre-flight with no DDL and no writes.\n *\n * Returns `true` when the schema has not been initialized yet (the privileged\n * bootstrap is required) and when the committed schema is behind `graph`.\n * This is the predicate a least-privilege runtime checks to route to the\n * privileged path *before* a write discovers the migration wall mid-request.\n *\n * For the additive-vs-incompatible distinction, use `getSchemaChanges` and\n * {@link classifySchemaChanges} instead — this collapses both to `true`.\n *\n * @param backend - The database backend\n * @param graph - The current graph definition\n * @returns Whether a privileged migration/bootstrap is required.\n */\nexport async function requiresMigration<G extends GraphDef>(\n  backend: GraphBackend,\n  graph: G,\n): Promise<boolean> {\n  const diff = await getSchemaChanges(backend, graph);\n  if (diff === undefined) return true;\n  return diff.hasChanges;\n}\n\n/**\n * Reads the committed schema version for a graph in a single round-trip — no\n * schema reconcile, no diff, no materialization-marker reads.\n *\n * This is the cross-isolate invalidation probe for a cached reconciled schema:\n * compare the returned version against the one a verified open recorded\n * (`store.reconciledSchema.version`); when it has moved, another process\n * committed a schema change and the cached reconciliation must be refreshed via\n * `createVerifiedAdapterStore`. One read replaces the three-query verified open\n * on the steady-state (unchanged) path — the round-trip that saturated the\n * connection pool under fan-out.\n *\n * It reads the active schema *row* (via `backend.getActiveSchema`), so the\n * committed `schema_doc` is transferred and normalized even though only the\n * version is used. A version-only backend query would shrink the payload\n * further; it is a backward-compatible follow-up, not required for the\n * round-trip win above.\n *\n * Returns only the version; for the document it names, see\n * {@link getActiveSchema}.\n *\n * @param backend - The database backend\n * @param graphId - The graph ID\n * @returns The active committed version, or `undefined` if the schema has not\n *   been initialized for this graph.\n */\nexport async function getCommittedSchemaVersion(\n  backend: GraphBackend,\n  graphId: string,\n): Promise<number | undefined> {\n  const row = await backend.getActiveSchema(graphId);\n  return row?.version;\n}\n"]}