{"version":3,"sources":["../../src/graph-merge/canonical-props.ts","../../src/graph-merge/node-key.ts","../../src/graph-merge/errors.ts","../../src/graph-merge/temporal-identity-closure.ts","../../src/graph-merge/merge-identity.ts","../../src/graph-merge/state-diff.ts","../../src/graph-merge/types.ts","../../src/graph-merge/base-version.ts","../../src/graph-merge/working-copy.ts","../../src/graph-merge/branch.ts","../../src/graph-merge/evolution-target.ts","../../src/graph-merge/ingestion-branch.ts","../../src/graph-merge/adopted-transaction.ts","../../src/graph-merge/apply-callbacks.ts","../../src/graph-merge/blocking.ts","../../src/graph-merge/conflict-policy.ts","../../src/graph-merge/canonicalize.ts","../../src/graph-merge/union-find.ts","../../src/graph-merge/closures.ts","../../src/graph-merge/evidence.ts","../../src/graph-merge/similarity.ts","../../src/graph-merge/scoring.ts","../../src/graph-merge/clustering.ts","../../src/graph-merge/delete-modify.ts","../../src/graph-merge/valid-window.ts","../../src/graph-merge/edge-repoint.ts","../../src/graph-merge/options.ts","../../src/graph-merge/plan-schema.ts","../../src/graph-merge/plan-canonical.ts","../../src/graph-merge/plan-wire.ts","../../src/graph-merge/provenance-store.ts","../../src/graph-merge/sources.ts","../../src/graph-merge/staging.ts","../../src/graph-merge/type-reconcile.ts","../../src/graph-merge/write-fence.ts","../../src/graph-merge/merge.ts","../../src/graph-merge/candidate-write-set.ts","../../src/graph-merge/review-evidence.ts","../../src/graph-merge/review-baseline.ts","../../src/graph-merge/review-schema.ts","../../src/graph-merge/candidate-review.ts","../../src/graph-merge/durable-branch.ts","../../src/graph-merge/durable-merge.ts","../../src/graph-merge/durable-operation.ts","../../src/graph-merge/evolution-branch.ts"],"names":["sortedReplacer","TypeGraphError","TransactionConflictError","requireDefined","encodeTupleKey","identityAssertionSemanticKey","compareCodePoints","identityValidityWindowsOverlap","normalizeIdentityPair","sourceKey","storeBackend","storeRuntime","identityReferenceKey","compareStrings","IdentityContradictionError","NodeNotFoundError","canonicalizeDatabaseTimestamp","rowsById","getNodeRowsByIds","batchPointReadVerdict","getEdgeRowsByIds","getNodeKinds","getEdgeKinds","computeSchemaHash","serializeSchema","sha256Hex","schemaComponent","resolveLineage","ensureRevisionOrigin","recordedRevisionOriginsVerdict","readRevisionOrigin","storeCaptureEnabled","recordedRelationsLineage","encodeRecordedLineageRevision","createStoreWithSchema","snapshotExportContention","importGraphStream","exportGraphStream","importGraph","exportGraph","summarizeImportErrors","isBackendDerivedFrom","sharesSerializedTransactionResource","wrapWithManagedClose","createSqlSchema","createStore","generateId","ok","err","isErr","registerIngestionImportTarget","hasPendingRecordedGraphWrites","hasPendingWriteTransactionRevision","resolveWriteFencePlan","statementExecutionVerdict","ensureEngineSerializedWriterSlot","NODE_TEMPORAL_READ_NAMES","CURRENT_ONLY_READ_NAMES","EDGE_TEMPORAL_READ_NAMES","IDENTITY_READ_NAMES","readOwnProperty","computeUniqueKey","hasOwnKey","dedupeKey","createDataKeyedBag","value","META_EDGE_EQUIVALENT_TO","META_EDGE_SAME_AS","computeTransitiveClosure","isReachable","DEFAULT_HYBRID_WEIGHT","forced","byId","z","defineNode","defineInternalGraph","requireWriteFence","asCompiledStatementSql","requireFenceLockTables","ConfigurationError","sql","asCompiledRowsSql","branch","lockSchemaVersionForStoreWrite","lockRecordedGraphWrite","graphCommandCoordinationIsolation","identity","repoint","nodeProps","IdentityEndpointValidityError","runRetriedUnit","transactionBackend","readRecordedClock","requireLineage","validateEdgeEndpoints","forceRecordedGraphRevision","forceWriteTransactionRevision","advanceRevisionClock","resolveEvolvedTransactionStore","nonEmptyStringSchema","isCanonicalIsoDate","jsonObjectSchema","InterchangeIdentitySchema","getGraphDefinitionHash","assertJsonValue"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDO,SAAS,kBACd,KAAA,EACQ;AACR,EAAA,OAAO,IAAA,CAAK,SAAA,CAAU,KAAA,EAAOA,gCAAc,CAAA;AAC7C;AAaO,SAAS,kBAAkB,KAAA,EAA0B;AAC1D,EAAA,OAAO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AAC,CAAA;AAAA,EAC9D;AACA,EAAA,IAAI;AACF,IAAA,MAAM,cAAA,GAA0B,MAAM,QAAA,CAAS,UAAA,CAAW,cAAA,CAAe;AAAA,MACvE,YAAY,UAAA,CAAW,KAAA;AAAA,MACvB,gBAAgB,KAAA,CAAM;AAAA,KACvB,CAAA;AACD,IAAA,OAAO,OAAO,cAAA,KAAmB,SAAA,GAC7BD,oBAAA,CAAG,cAAc,CAAA,GACjBC,qBAAA;AAAA,MACE,IAAI,6BAAA;AAAA,QACF;AAAA;AACF,KACF;AAAA,EACN,SAAS,KAAA,EAAO;AACd,IAAA,OAAOA,qBAAA;AAAA,MACL,KAAA,YAAiB,qBAAA,GAAwB,KAAA,GACvC,IAAI,qBAAA;AAAA,QACF,CAAA,8CAAA,EAAiD,aAAA,CAAc,KAAK,CAAC,CAAA,CAAA;AAAA,QACrE,EAAE,OAAO,KAAA;AAAM;AACjB,KAEJ;AAAA,EACF;AACF;;;ACh3BA,eAAsB,kBAAA,CACpB,KAAA,EACA,IAAA,EACA,WAAA,EACA,OAAA,EACyE;AACzE,EAAA,IAAI;AACF,IAAA,MAAM,SAAA,GAAY,uBAAA,CAAwB,KAAA,EAAO,IAAI,CAAA;AACrD,IAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO,SAAA,EAAW,aAAa,OAAO,CAAA;AAC3D,IAAA,OAAO,MAAA;AAAA,EACT,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,KAAA,YAAiB,wBAAA,EAA0B,OAAOA,qBAAA,CAAI,KAAK,CAAA;AAC/D,IAAA,OAAOA,qBAAA;AAAA,MACL,IAAI,wBAAA;AAAA,QACF,2CAAA;AAAA,QACA,EAAE,KAAA,EAAO,KAAA,EAAO,SAAS,EAAE,UAAA,EAAY,mBAAkB;AAAE;AAC7D,KACF;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * The single canonical property serializer for the merge primitive.\n *\n * Hoisted to T2 (rather than living next to the clustering code) because three\n * separate phases must agree byte-for-byte on the serialized form of a property\n * bag:\n *\n *   - state-diff (T3) — to detect whether an inherited node's props changed,\n *   - clustering / property union (T8) — to compare member values,\n *   - edge repoint + dedupe (T9) — to key the `(from|type|to|propsKey)` tuple.\n *\n * {@link canonicalValueKey} is the SINGLE-VALUE sibling: the same recursive\n * key-sort over an arbitrary {@link JsonValue} (scalar / array / object), so the\n * conflict-resolution layer (T8 / `conflict-policy.ts`) decides value equality and\n * tie-breaks on the canonical form too — two branches that wrote a logically-equal\n * nested object with different key order must NOT register as a conflict.\n *\n * Determinism rules:\n *   - Object keys are sorted lexicographically at every nesting level, so two\n *     objects that differ only by key insertion order serialize identically.\n *   - Arrays preserve order (order is semantically meaningful in a list).\n *   - `undefined` keys are dropped (JSON has no `undefined`; an absent key and a\n *     key set to `undefined` are treated as the same absence).\n *   - All other JSON-representable values serialize via their natural form.\n *\n * IMPORTANT contract for callers: the input MUST be a PARSED plain object, never\n * a JSON string. Backend rows store `props` as a JSON string; callers MUST\n * `JSON.parse` first. Passing a string would serialize the string literal (with\n * its own incidental key order) rather than the canonical structure, so the\n * `propsKey` would NOT be stable across staged-vs-committed representations.\n */\n\nimport type { JsonValue } from \"./typegraph-internal\";\nimport { sortedReplacer } from \"./typegraph-internal\";\n\n/**\n * Produces a deterministic, recursively key-sorted JSON serialization of a\n * parsed property object.\n *\n * Delegates to the schema layer's {@link sortedReplacer} — the single canonical\n * JSON serializer in the codebase (also used by `computeSchemaHash` /\n * `computeSchemaDiff`) — so the merge primitive and the schema layer can never\n * drift on what \"canonical form\" means. The replacer sorts object keys at every\n * depth while preserving array order; `JSON.stringify` omits `undefined`-valued\n * keys, matching the \"an absent key and a key set to `undefined` are the same\n * absence\" rule in the module docs.\n *\n * @param props A PARSED plain object (NOT a JSON string). See module docs.\n * @returns A canonical JSON string suitable for equality comparison / dedupe\n *   keying. Equivalent objects (key order aside) yield identical strings;\n *   objects differing in any value yield differing strings.\n */\nexport function canonicalizeProps(\n  props: Readonly<Record<string, unknown>>,\n): string {\n  return JSON.stringify(props, sortedReplacer);\n}\n\n/**\n * Produces a deterministic, recursively key-sorted JSON serialization of a single\n * {@link JsonValue} — the per-value analogue of {@link canonicalizeProps}.\n *\n * Used by the conflict layer to compare candidate values, dedupe them, and\n * tie-break, so a nested object's incidental key order can never make two\n * logically-equal values look different (which would surface a spurious conflict).\n *\n * @param value Any parsed JSON value (scalar, array, or object). Not a JSON string.\n * @returns A canonical JSON string suitable for equality / dedupe / ordering.\n */\nexport function canonicalValueKey(value: JsonValue): string {\n  return JSON.stringify(value, sortedReplacer);\n}\n\n/**\n * A stable fingerprint of a committed edge's mergeable state — its endpoints,\n * liveness, and canonical props. The incremental lost-update guard captures this\n * for every target edge at plan time and re-derives it inside the commit\n * transaction; a mismatch means the committed edge drifted in the plan→commit\n * window, so applying the plan (built from the plan-time value) would silently\n * overwrite that change. Edges carry no `version` column, so this content\n * fingerprint is the node-`version` analogue for the edge half of the guard.\n *\n * @param edge Endpoints, liveness, and PARSED props (never a JSON string).\n * @returns A canonical string; equal iff the two edge states are mergeably equal.\n */\nexport function edgeStateSignature(\n  edge: Readonly<{\n    fromKind: string;\n    fromId: string;\n    toKind: string;\n    toId: string;\n    live: boolean;\n    props: Readonly<Record<string, unknown>>;\n  }>,\n): string {\n  return JSON.stringify([\n    edge.fromKind,\n    edge.fromId,\n    edge.toKind,\n    edge.toId,\n    edge.live,\n    canonicalizeProps(edge.props),\n  ]);\n}\n\n/**\n * Normalizes a stored row's `props` — a JSON string on SQLite, an\n * already-parsed object on Postgres (jsonb rows arrive driver-parsed) — into\n * the plain object that {@link canonicalizeProps} requires. Malformed JSON, a\n * non-object, or an array all collapse to `{}` — a parse error never escapes.\n * Backend-written rows hold valid JSON, but an external / legacy / truncated\n * `props` value must not crash a state diff or a base-version fingerprint.\n * Centralized so the diff and the fingerprint can never disagree on what a\n * malformed row parses to.\n */\nexport function parseRowProps(\n  props: string | Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> {\n  let parsed: unknown;\n  if (typeof props === \"string\") {\n    try {\n      parsed = JSON.parse(props);\n    } catch {\n      return {};\n    }\n  } else {\n    parsed = props;\n  }\n  if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n    return {};\n  }\n  return parsed as Record<string, unknown>;\n}\n","/**\n * The composite MERGE IDENTITY key for a node: the pair `(kind, id)`.\n *\n * TypeGraph node identity is the PAIR `(kind, id)` — a bare id string is NOT unique\n * on its own (a `Patient` and an `Encounter` may both carry the id \"x\" as two\n * DISTINCT committed nodes; ids are caller-supplied). Every place the merge pipeline\n * groups, clusters, de-dupes, repoints, retypes, or deletes BY NODE IDENTITY must\n * key on this pair — never the bare id — or two different-kind nodes that happen to\n * share an id string silently fuse into one cluster (wrong merge, dropped node,\n * incoherent commit) and the §6.4-A base guard is bypassed.\n *\n * Represented as a NUL-joined string (a branded {@link MergeKey}) so it doubles as a\n * `Map`/`Set` key and a deterministic ordering key. `kind` is a schema identifier\n * (NUL-free), so the FIRST NUL unambiguously delimits kind from id even when a\n * caller-supplied id itself contains a NUL byte. This matches the `(kind, id)`\n * separator the commit-time write guard already uses.\n *\n * {@link compareMergeKeys} orders by the bare id FIRST (kind only breaks a same-id\n * tie), so the merge's \"minimum-id survivor\" / id-sorted-members semantics are\n * preserved unchanged for the common single-kind cluster — the composite key changes\n * WHICH nodes share an identity, never the ordering among genuinely distinct ids.\n */\n\nimport type { NodeId, NodeType } from \"./typegraph-internal\";\n\n/** The `(kind, id)` separator: a NUL byte (0x00), absent from schema kind names. */\nconst SEPARATOR = String.fromCharCode(0);\n\n/** A node id in its untyped (`NodeType`-default) branded form. */\ntype AnyNodeId = NodeId<NodeType>;\n\n/**\n * A composite `(kind, id)` node-identity key. Branded so it cannot be confused with\n * a bare {@link NodeId} at the type level — the whole point is that the two are NOT\n * interchangeable as identities.\n */\nexport type MergeKey = string & { readonly __mergeKey: unique symbol };\n\n/** Builds the composite identity key for a `(kind, id)` pair. */\nexport function mergeKey(kind: string, id: string): MergeKey {\n  // `kindOf`/`idOf` split on the FIRST NUL, so a NUL in `kind` would alias distinct\n  // identities (`mergeKey(\"a\\0b\",\"c\") === mergeKey(\"a\",\"b\\0c\")`), silently fusing\n  // unrelated nodes into one cluster and bypassing the §6.4-A base guard this composite\n  // key exists to protect. Kinds are NUL-free schema identifiers; fail loud if not.\n  if (kind.includes(SEPARATOR)) {\n    throw new Error(\n      `Node kind ${JSON.stringify(kind)} contains a NUL byte, which collides the (kind, id) merge-identity separator.`,\n    );\n  }\n  return `${kind}${SEPARATOR}${id}` as MergeKey;\n}\n\n/** Builds the composite identity key for any object carrying a `kind` and `id`. */\nexport function mergeKeyOf(\n  node: Readonly<{ kind: string; id: string }>,\n): MergeKey {\n  return mergeKey(node.kind, node.id);\n}\n\n/** The kind component of a {@link MergeKey}. */\nexport function kindOf(key: MergeKey): string {\n  const separator = key.indexOf(SEPARATOR);\n  return separator === -1 ? key : key.slice(0, separator);\n}\n\n/** The bare node id component of a {@link MergeKey}. */\nexport function idOf(key: MergeKey): AnyNodeId {\n  const separator = key.indexOf(SEPARATOR);\n  return (separator === -1 ? key : key.slice(separator + 1)) as AnyNodeId;\n}\n\n/**\n * Deterministic comparator over two merge keys, BARE ID first and kind only as a\n * same-id tie-break. This keeps the merge's minimum-id survivor selection and\n * id-sorted member order identical to the pre-composite behaviour for any pair of\n * genuinely distinct ids (the overwhelmingly common case), so the re-key changes\n * identity grouping without perturbing deterministic ordering.\n */\nexport function compareMergeKeys(left: MergeKey, right: MergeKey): number {\n  const leftId = idOf(left);\n  const rightId = idOf(right);\n  if (leftId !== rightId) {\n    return leftId < rightId ? -1 : 1;\n  }\n  const leftKind = kindOf(left);\n  const rightKind = kindOf(right);\n  return (\n    leftKind < rightKind ? -1\n    : leftKind > rightKind ? 1\n    : 0\n  );\n}\n\nexport { compareStrings } from \"../utils/compare\";\n","import type { TypeGraphErrorOptions } from \"./typegraph-internal\";\nimport { TransactionConflictError, TypeGraphError } from \"./typegraph-internal\";\n\n/**\n * Error hierarchy for the graph-merge primitive.\n *\n * Every error extends the publicly-exported {@link TypeGraphError}, so consumers\n * can use the same `isTypeGraphError`/category machinery they already use for\n * TypeGraph itself. Each subclass carries a stable machine-readable `code`, a\n * fixed `ErrorCategory`, and a cause chain for debugging.\n */\n\n/**\n * Machine-readable error codes for the merge primitive. Stable identifiers so\n * callers can branch on `error.code` without string-matching messages.\n */\nexport const MERGE_ERROR_CODES = {\n  merge: \"GRAPH_MERGE_ERROR\",\n  invalidOptions: \"GRAPH_MERGE_INVALID_OPTIONS\",\n  branch: \"GRAPH_MERGE_BRANCH_ERROR\",\n  similarityUnavailable: \"GRAPH_MERGE_SIMILARITY_UNAVAILABLE\",\n  conflict: \"GRAPH_MERGE_CONFLICT\",\n  constraintConflict: \"GRAPH_MERGE_CONSTRAINT_CONFLICT\",\n  identityConflict: \"GRAPH_MERGE_IDENTITY_CONFLICT\",\n  baseVersionMismatch: \"GRAPH_MERGE_BASE_VERSION_MISMATCH\",\n  planCapability: \"GRAPH_MERGE_PLAN_CAPABILITY\",\n  planInvalid: \"GRAPH_MERGE_PLAN_INVALID\",\n  planVersionUnsupported: \"GRAPH_MERGE_PLAN_VERSION_UNSUPPORTED\",\n  planDigestMismatch: \"GRAPH_MERGE_PLAN_DIGEST_MISMATCH\",\n  planTargetMismatch: \"GRAPH_MERGE_PLAN_TARGET_MISMATCH\",\n  planSchemaMismatch: \"GRAPH_MERGE_PLAN_SCHEMA_MISMATCH\",\n  planOriginMismatch: \"GRAPH_MERGE_PLAN_ORIGIN_MISMATCH\",\n  planStale: \"GRAPH_MERGE_PLAN_STALE\",\n  planningStale: \"GRAPH_MERGE_PLANNING_STALE\",\n  candidateSource: \"GRAPH_MERGE_CANDIDATE_SOURCE\",\n  evidence: \"GRAPH_MERGE_EVIDENCE\",\n  candidateWriteSet: \"GRAPH_MERGE_CANDIDATE_WRITE_SET\",\n  review: \"GRAPH_MERGE_REVIEW\",\n  operation: \"GRAPH_MERGE_OPERATION\",\n  operationRequest: \"GRAPH_MERGE_OPERATION_REQUEST\",\n  operationConflict: \"GRAPH_MERGE_OPERATION_CONFLICT\",\n  operationUnsupported: \"GRAPH_MERGE_OPERATION_UNSUPPORTED\",\n  operationEvidence: \"GRAPH_MERGE_OPERATION_EVIDENCE\",\n  operationUndelivered: \"GRAPH_MERGE_OPERATION_UNDELIVERED\",\n} as const;\n\n/**\n * Options shared by every merge error. Mirrors the relevant subset of\n * TypeGraphError's options while making `cause`/`details`/`suggestion`\n * uniformly optional at the merge-error boundary.\n */\nexport type MergeErrorOptions = Readonly<{\n  details?: Record<string, unknown>;\n  suggestion?: string;\n  cause?: unknown;\n}>;\n\n/**\n * Builds a {@link TypeGraphErrorOptions} for a fixed category, threading only\n * the optional fields that are actually present. Omitting undefined keys (rather\n * than assigning `undefined`) keeps the result valid under\n * `exactOptionalPropertyTypes`.\n */\nfunction toTypeGraphErrorOptions(\n  category: TypeGraphErrorOptions[\"category\"],\n  options: MergeErrorOptions,\n): TypeGraphErrorOptions {\n  return {\n    category,\n    ...(options.details === undefined ? {} : { details: options.details }),\n    ...(options.suggestion === undefined ?\n      {}\n    : { suggestion: options.suggestion }),\n    ...(options.cause === undefined ? {} : { cause: options.cause }),\n  };\n}\n\n/**\n * Generic failure raised while computing or committing a merge. The catch-all\n * for the orchestrator (comparison-ceiling overruns, commit failures, etc.).\n */\nexport class MergeError extends TypeGraphError {\n  protected static readonly errorCategory: TypeGraphErrorOptions[\"category\"] =\n    \"system\";\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    const errorClass = new.target;\n    super(\n      message,\n      MERGE_ERROR_CODES.merge,\n      toTypeGraphErrorOptions(errorClass.errorCategory, options),\n    );\n    this.name = \"MergeError\";\n  }\n}\n\n/** Raised when caller-supplied merge options are invalid or unsupported. */\nexport class InvalidMergeOptionsError extends MergeError {\n  protected static override readonly errorCategory = \"user\";\n  override readonly code = MERGE_ERROR_CODES.invalidOptions;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"InvalidMergeOptionsError\";\n  }\n}\n\n/** Invalid, unsupported, or unavailable evidence for durable merge review. */\nexport class MergeReviewError extends MergeError {\n  protected static override readonly errorCategory = \"user\";\n  override readonly code = MERGE_ERROR_CODES.review;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"MergeReviewError\";\n  }\n}\n\n/**\n * Failure raised while creating a working-copy branch of a base store\n * (clone/export/import failures, backend construction failures).\n */\nexport class BranchError extends TypeGraphError {\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(\n      message,\n      MERGE_ERROR_CODES.branch,\n      toTypeGraphErrorOptions(\"system\", options),\n    );\n    this.name = \"BranchError\";\n  }\n}\n\n/**\n * Raised when a `vector`/`hybrid` similarity strategy is requested but no\n * {@link import(\"./types\").Embedder} was configured (`MergeOptions.embedder` is\n * absent). The `vector`/`hybrid` scorers compute cosine over real embeddings in\n * memory, so an embedder is mandatory for them; `fulltext`/`custom` need none.\n */\nexport class SimilarityUnavailableError extends MergeError {\n  override readonly code = MERGE_ERROR_CODES.similarityUnavailable;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, {\n      ...options,\n      suggestion:\n        options.suggestion ??\n        \"Pass MergeOptions.embedder (a local model), or use a fulltext/custom similarity strategy.\",\n    });\n    this.name = \"SimilarityUnavailableError\";\n  }\n}\n\n/**\n * Raised when a conflict cannot be resolved by the configured policy and the\n * caller has opted into hard-failing rather than flagging.\n */\nexport class MergeConflictError extends MergeError {\n  override readonly code = MERGE_ERROR_CODES.conflict;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"MergeConflictError\";\n  }\n}\n\n/** Details copied from the deterministic store constraint that refused commit. */\nexport type MergeConstraintConflictErrorDetails = Readonly<{\n  /** Stable code of the underlying store constraint error. */\n  constraintCode: string;\n  /** Class name of the underlying store constraint error. */\n  constraintErrorName: string;\n  /** Constraint-specific fields, also copied onto this details object. */\n  constraintDetails: Readonly<Record<string, unknown>>;\n  [key: string]: unknown;\n}>;\n\n/** Raised when a resolved merge would commit a graph that violates a constraint. */\nexport class MergeConstraintConflictError extends MergeError {\n  protected static override readonly errorCategory = \"constraint\";\n  override readonly code = MERGE_ERROR_CODES.constraintConflict;\n  declare readonly category: \"constraint\";\n  declare readonly cause: TypeGraphError;\n  declare readonly details: MergeConstraintConflictErrorDetails;\n\n  constructor(cause: TypeGraphError) {\n    super(`The resolved merge would violate ${cause.name}: ${cause.message}`, {\n      cause,\n      details: {\n        ...cause.details,\n        constraintCode: cause.code,\n        constraintErrorName: cause.name,\n        constraintDetails: cause.details,\n      },\n      suggestion:\n        cause.suggestion ??\n        \"Change the branch data or target state so the resolved graph satisfies its constraints, then retry the merge.\",\n    });\n    this.name = \"MergeConstraintConflictError\";\n  }\n}\n\n/**\n * Translates a merge commit's transaction-conflict exhaustion into a\n * {@link MergeError} the merge boundary's callers already know how to handle,\n * and deterministic store-constraint refusals into\n * {@link MergeConstraintConflictError}. Identity conflicts have their own\n * established merge error surface; infrastructure and stale-plan failures are\n * not category `constraint`.\n *\n * @internal\n */\nexport function translateMergeCommitError(error: unknown): unknown {\n  if (error instanceof MergeError) return error;\n  if (error instanceof TransactionConflictError) {\n    return new MergeError(\n      `Merge commit aborted by transaction conflicts (serialization failure or deadlock) on ${error.details.attempts} consecutive attempt(s); giving up.`,\n      {\n        cause: error,\n        details: { attempts: error.details.attempts },\n        suggestion:\n          \"Reduce concurrent writes to the merge target, or serialize merges against it.\",\n      },\n    );\n  }\n  if (!(error instanceof TypeGraphError)) return error;\n  if (error.category !== \"constraint\" || error.code.startsWith(\"IDENTITY_\")) {\n    return error;\n  }\n  return new MergeConstraintConflictError(error);\n}\n\n/** Raised when identity branches contain opposing or retract/reassert truth. */\nexport class IdentityMergeConflictError extends MergeError {\n  override readonly code = MERGE_ERROR_CODES.identityConflict;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"IdentityMergeConflictError\";\n  }\n}\n\n/**\n * Raised by the `merge()` precondition check when a branch's `base@V` token\n * does not match the merge target's current base version (the branch forked\n * from a divergent schema or content fingerprint).\n */\nexport class BaseVersionMismatchError extends MergeError {\n  override readonly code = MERGE_ERROR_CODES.baseVersionMismatch;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, {\n      ...options,\n      suggestion:\n        options.suggestion ??\n        \"Re-branch from the current target so the branch base matches before merging.\",\n    });\n    this.name = \"BaseVersionMismatchError\";\n  }\n}\n\n/** Raised when a target cannot provide the durable plan/apply guarantees. */\nexport class MergePlanCapabilityError extends MergeError {\n  protected static override readonly errorCategory = \"user\";\n  override readonly code = MERGE_ERROR_CODES.planCapability;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"MergePlanCapabilityError\";\n  }\n}\n\n/** Raised when a serialized plan is structurally or semantically malformed. */\nexport class InvalidMergePlanError extends MergeError {\n  protected static override readonly errorCategory = \"user\";\n  override readonly code: string = MERGE_ERROR_CODES.planInvalid;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"InvalidMergePlanError\";\n  }\n}\n\n/** Raised when a plan uses a wire format this library version cannot read. */\nexport class UnsupportedMergePlanVersionError extends InvalidMergePlanError {\n  override readonly code = MERGE_ERROR_CODES.planVersionUnsupported;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"UnsupportedMergePlanVersionError\";\n  }\n}\n\n/** Raised when a plan's canonical content no longer matches its digest. */\nexport class MergePlanDigestMismatchError extends InvalidMergePlanError {\n  override readonly code = MERGE_ERROR_CODES.planDigestMismatch;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"MergePlanDigestMismatchError\";\n  }\n}\n\n/** Raised when a plan names a different target graph. */\nexport class MergePlanTargetMismatchError extends InvalidMergePlanError {\n  override readonly code = MERGE_ERROR_CODES.planTargetMismatch;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"MergePlanTargetMismatchError\";\n  }\n}\n\n/** Raised when a plan was produced for another active schema. */\nexport class MergePlanSchemaMismatchError extends InvalidMergePlanError {\n  override readonly code = MERGE_ERROR_CODES.planSchemaMismatch;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"MergePlanSchemaMismatchError\";\n  }\n}\n\n/** Raised when a plan belongs to an independently-created revision clock. */\nexport class MergePlanOriginMismatchError extends InvalidMergePlanError {\n  override readonly code = MERGE_ERROR_CODES.planOriginMismatch;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"MergePlanOriginMismatchError\";\n  }\n}\n\n/** Raised when the target revision no longer equals the plan's fence. */\nexport class StaleMergePlanError extends MergeError {\n  override readonly code: string = MERGE_ERROR_CODES.planStale;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, {\n      ...options,\n      suggestion:\n        options.suggestion ??\n        \"Create a new merge plan against the target's current revision, review it, and apply that plan instead.\",\n    });\n    this.name = \"StaleMergePlanError\";\n  }\n}\n\n/** Raised when the target moved while a plan was being computed. */\nexport class MergePlanningStaleError extends StaleMergePlanError {\n  override readonly code = MERGE_ERROR_CODES.planningStale;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"MergePlanningStaleError\";\n  }\n}\n\n/** Raised when a built-in candidate source cannot produce attributed output. */\nexport class CandidateSourceError extends MergeError {\n  override readonly code = MERGE_ERROR_CODES.candidateSource;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"CandidateSourceError\";\n  }\n}\n\n/** Raised when a serialized candidate write set cannot be validated or staged. */\nexport class CandidateWriteSetError extends MergeError {\n  protected static override readonly errorCategory = \"user\";\n  override readonly code = MERGE_ERROR_CODES.candidateWriteSet;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"CandidateWriteSetError\";\n  }\n}\n\n/** Raised when match evidence is invalid or contains a non-finite score. */\nexport class MatchEvidenceError extends MergeError {\n  override readonly code = MERGE_ERROR_CODES.evidence;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"MatchEvidenceError\";\n  }\n}\n\n/**\n * Generic operational failure raised while orchestrating a durable-branch\n * operation, such as a strategy transport or host failure.\n */\nexport class DurableOperationError extends MergeError {\n  override readonly code: string = MERGE_ERROR_CODES.operation;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"DurableOperationError\";\n  }\n}\n\n/** Raised when a durable-operation request or descriptor is invalid. */\nexport class DurableOperationRequestError extends DurableOperationError {\n  protected static override readonly errorCategory = \"user\";\n  override readonly code = MERGE_ERROR_CODES.operationRequest;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"DurableOperationRequestError\";\n  }\n}\n\n/**\n * Raised when an idempotency key is reused with a different operation digest.\n * The previously committed operation is returned untouched; the new request is\n * refused before any graph mutation or evidence write.\n */\nexport class DurableOperationConflictError extends DurableOperationError {\n  protected static override readonly errorCategory = \"constraint\";\n  override readonly code = MERGE_ERROR_CODES.operationConflict;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"DurableOperationConflictError\";\n  }\n}\n\n/**\n * Raised when a host cannot provide the atomic mutation-plus-evidence\n * guarantee. It carries the dimensions the host cannot honor. The portable\n * fallback is refusal; TypeGraph never emulates atomicity with callbacks or\n * best effort.\n */\nexport class DurableOperationUnsupportedError extends DurableOperationError {\n  protected static override readonly errorCategory = \"user\";\n  override readonly code = MERGE_ERROR_CODES.operationUnsupported;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"DurableOperationUnsupportedError\";\n  }\n}\n\n/** Raised when a host returns malformed or request-inconsistent evidence. */\nexport class DurableOperationEvidenceError extends DurableOperationError {\n  override readonly code = MERGE_ERROR_CODES.operationEvidence;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"DurableOperationEvidenceError\";\n  }\n}\n\n/**\n * Raised when archive/destroy is fenced by undelivered operation evidence.\n *\n * Extends {@link BranchError} so the established `destroyDurableBranch` result\n * type already transports it: a strategy that refuses destruction while\n * undelivered evidence remains preserves that refusal to the caller instead of\n * having it flattened into a generic branch failure.\n */\nexport class DurableEvidenceUndeliveredError extends BranchError {\n  override readonly code = MERGE_ERROR_CODES.operationUndelivered;\n\n  constructor(message: string, options: MergeErrorOptions = {}) {\n    super(message, options);\n    this.name = \"DurableEvidenceUndeliveredError\";\n  }\n}\n\n/**\n * One-line human description of an unknown thrown value, for wrapping into\n * typed error messages.\n *\n * @internal\n */\nexport function describeCause(cause: unknown): string {\n  return cause instanceof Error ? cause.message : String(cause);\n}\n","import { requireDefined } from \"../utils/presence\";\nimport { IdentityMergeConflictError } from \"./errors\";\nimport type { PlanIdentityContext } from \"./merge-identity\";\nimport {\n  compareMergeKeys,\n  type MergeKey,\n  mergeKey,\n  mergeKeyOf,\n} from \"./node-key\";\nimport type { IdentityTransferAssertion } from \"./typegraph-internal\";\n\n/**\n * Offline temporal identity validation.\n *\n * Each half-open assertion window is stored in a segment tree. A depth-first\n * walk applies only the assertions visible throughout the current segment and\n * rolls those changes back on return. The disjoint-set therefore represents\n * exactly one temporal coordinate at every leaf without filtering the full\n * ledger or rebuilding every identity class for every boundary.\n *\n * `different` assertions live in component-adjacency sets. When a later\n * `same` union internalizes one, the union records the contradiction; this\n * avoids rescanning all active negative truth after every connectivity change.\n */\ntype IdentityReference = Readonly<{ kind: string; id: string }>;\n\ntype AssertionRange = Readonly<{\n  assertionIndex: number;\n  start: number;\n  end: number;\n}>;\n\ntype TemporalEvents = Readonly<{\n  references: number[];\n  sameAssertions: number[];\n  differentAssertions: number[];\n}>;\n\ntype ComponentState = Readonly<{\n  parent: number[];\n  sizes: number[];\n  kindFirstReference: Map<string, number>[];\n  differentAssertions: Set<number>[];\n  violatesOntology: boolean[];\n}>;\n\ntype KindFirstReferenceChange = Readonly<{\n  kind: string;\n  previousFirstReference: number | undefined;\n  nextFirstReference: number;\n}>;\n\ntype TemporalClosureState = Readonly<{\n  assertions: readonly IdentityTransferAssertion[];\n  context: PlanIdentityContext;\n  references: readonly IdentityReference[];\n  referenceIndexByKey: ReadonlyMap<MergeKey, number>;\n  activeReferences: boolean[];\n  activeReferencesById: Map<string, Set<number>>;\n  components: ComponentState;\n  contradictoryAssertions: Set<number>;\n  undo: (() => void)[];\n  disjointCache: Map<string, boolean>;\n  sharedIdViolationCount: { value: number };\n}>;\n\nfunction disjointCacheKey(left: string, right: string): string {\n  return left <= right ? `${left}\\u0000${right}` : `${right}\\u0000${left}`;\n}\n\nfunction areDisjoint(\n  state: TemporalClosureState,\n  left: string,\n  right: string,\n): boolean {\n  const key = disjointCacheKey(left, right);\n  const cached = state.disjointCache.get(key);\n  if (cached !== undefined) return cached;\n  const result = state.context.areDisjoint(left, right);\n  state.disjointCache.set(key, result);\n  return result;\n}\n\nfunction findRoot(components: ComponentState, index: number): number {\n  let root = index;\n  while (components.parent[root] !== root) {\n    root = requireDefined(components.parent[root]);\n  }\n  return root;\n}\n\nfunction componentKindsConflict(\n  state: TemporalClosureState,\n  leftKinds: ReadonlyMap<string, number>,\n  rightKinds: ReadonlyMap<string, number>,\n): boolean {\n  for (const left of leftKinds.keys()) {\n    for (const right of rightKinds.keys()) {\n      if (left !== right && areDisjoint(state, left, right)) return true;\n    }\n  }\n  return false;\n}\n\nfunction unionReferences(\n  state: TemporalClosureState,\n  leftIndex: number,\n  rightIndex: number,\n): void {\n  const { components } = state;\n  const leftRoot = findRoot(components, leftIndex);\n  const rightRoot = findRoot(components, rightIndex);\n  if (leftRoot === rightRoot) return;\n\n  const [parentRoot, childRoot] =\n    (\n      requireDefined(components.sizes[leftRoot]) >=\n      requireDefined(components.sizes[rightRoot])\n    ) ?\n      [leftRoot, rightRoot]\n    : [rightRoot, leftRoot];\n  const parentKinds = requireDefined(components.kindFirstReference[parentRoot]);\n  const childKinds = requireDefined(components.kindFirstReference[childRoot]);\n  const parentDifferent = requireDefined(\n    components.differentAssertions[parentRoot],\n  );\n  const childDifferent = requireDefined(\n    components.differentAssertions[childRoot],\n  );\n  const previousParentSize = requireDefined(components.sizes[parentRoot]);\n  const previousViolation = requireDefined(\n    components.violatesOntology[parentRoot],\n  );\n  const changedKinds: KindFirstReferenceChange[] = [...childKinds].flatMap(\n    ([kind, childFirstReference]) => {\n      const previousFirstReference = parentKinds.get(kind);\n      return (\n          previousFirstReference === undefined ||\n            childFirstReference < previousFirstReference\n        ) ?\n          [\n            {\n              kind,\n              previousFirstReference,\n              nextFirstReference: childFirstReference,\n            },\n          ]\n        : [];\n    },\n  );\n  const addedDifferent = [...childDifferent].filter(\n    (assertionIndex) => !parentDifferent.has(assertionIndex),\n  );\n  const addedContradictions: number[] = [];\n  const crossesDisjointKinds = componentKindsConflict(\n    state,\n    parentKinds,\n    childKinds,\n  );\n\n  components.parent[childRoot] = parentRoot;\n  components.sizes[parentRoot] =\n    previousParentSize + requireDefined(components.sizes[childRoot]);\n  for (const { kind, nextFirstReference } of changedKinds) {\n    parentKinds.set(kind, nextFirstReference);\n  }\n  for (const assertionIndex of addedDifferent) {\n    parentDifferent.add(assertionIndex);\n  }\n  components.violatesOntology[parentRoot] =\n    previousViolation ||\n    requireDefined(components.violatesOntology[childRoot]) ||\n    crossesDisjointKinds;\n\n  for (const assertionIndex of childDifferent) {\n    const assertion = requireDefined(state.assertions[assertionIndex]);\n    const aIndex = requireDefined(\n      state.referenceIndexByKey.get(mergeKeyOf(assertion.a)),\n    );\n    const bIndex = requireDefined(\n      state.referenceIndexByKey.get(mergeKeyOf(assertion.b)),\n    );\n    if (\n      findRoot(components, aIndex) === findRoot(components, bIndex) &&\n      !state.contradictoryAssertions.has(assertionIndex)\n    ) {\n      state.contradictoryAssertions.add(assertionIndex);\n      addedContradictions.push(assertionIndex);\n    }\n  }\n\n  state.undo.push(() => {\n    for (const assertionIndex of addedContradictions) {\n      state.contradictoryAssertions.delete(assertionIndex);\n    }\n    components.violatesOntology[parentRoot] = previousViolation;\n    for (const assertionIndex of addedDifferent) {\n      parentDifferent.delete(assertionIndex);\n    }\n    for (const { kind, previousFirstReference } of changedKinds) {\n      if (previousFirstReference === undefined) parentKinds.delete(kind);\n      else parentKinds.set(kind, previousFirstReference);\n    }\n    components.sizes[parentRoot] = previousParentSize;\n    components.parent[childRoot] = childRoot;\n  });\n}\n\nfunction activateReference(\n  state: TemporalClosureState,\n  referenceIndex: number,\n): void {\n  if (state.activeReferences[referenceIndex] === true) return;\n  const reference = requireDefined(state.references[referenceIndex]);\n  const peers = [...(state.activeReferencesById.get(reference.id) ?? [])];\n  let addedSharedIdViolations = 0;\n  for (const peerIndex of peers) {\n    const peer = requireDefined(state.references[peerIndex]);\n    if (areDisjoint(state, reference.kind, peer.kind)) {\n      addedSharedIdViolations += 1;\n    }\n  }\n  state.sharedIdViolationCount.value += addedSharedIdViolations;\n  state.activeReferences[referenceIndex] = true;\n  const activeForId =\n    state.activeReferencesById.get(reference.id) ?? new Set<number>();\n  activeForId.add(referenceIndex);\n  state.activeReferencesById.set(reference.id, activeForId);\n  state.undo.push(() => {\n    activeForId.delete(referenceIndex);\n    if (activeForId.size === 0) {\n      state.activeReferencesById.delete(reference.id);\n    }\n    state.activeReferences[referenceIndex] = false;\n    state.sharedIdViolationCount.value -= addedSharedIdViolations;\n  });\n\n  if (state.context.sameIdAcrossKinds === \"fold\") {\n    for (const peerIndex of peers) {\n      unionReferences(state, referenceIndex, peerIndex);\n    }\n  }\n}\n\nfunction addDifferentAssertion(\n  state: TemporalClosureState,\n  assertionIndex: number,\n): void {\n  const assertion = requireDefined(state.assertions[assertionIndex]);\n  const aIndex = requireDefined(\n    state.referenceIndexByKey.get(mergeKeyOf(assertion.a)),\n  );\n  const bIndex = requireDefined(\n    state.referenceIndexByKey.get(mergeKeyOf(assertion.b)),\n  );\n  const aRoot = findRoot(state.components, aIndex);\n  const bRoot = findRoot(state.components, bIndex);\n  if (aRoot === bRoot) {\n    state.contradictoryAssertions.add(assertionIndex);\n    state.undo.push(() => {\n      state.contradictoryAssertions.delete(assertionIndex);\n    });\n    return;\n  }\n\n  const aDifferent = requireDefined(\n    state.components.differentAssertions[aRoot],\n  );\n  const bDifferent = requireDefined(\n    state.components.differentAssertions[bRoot],\n  );\n  aDifferent.add(assertionIndex);\n  bDifferent.add(assertionIndex);\n  state.undo.push(() => {\n    aDifferent.delete(assertionIndex);\n    bDifferent.delete(assertionIndex);\n  });\n}\n\nfunction rollback(state: TemporalClosureState, snapshot: number): void {\n  while (state.undo.length > snapshot) {\n    requireDefined(state.undo.pop())();\n  }\n}\n\nfunction firstDisjointPair(\n  state: TemporalClosureState,\n  kinds: readonly string[],\n): readonly [string, string] | undefined {\n  for (const [index, left] of kinds.entries()) {\n    for (const right of kinds.slice(index + 1)) {\n      if (areDisjoint(state, left, right)) return [left, right];\n    }\n  }\n  return undefined;\n}\n\nfunction firstAssertionIndex(assertionIndexes: ReadonlySet<number>): number {\n  let first = Number.POSITIVE_INFINITY;\n  for (const assertionIndex of assertionIndexes) {\n    first = Math.min(first, assertionIndex);\n  }\n  return first;\n}\n\nfunction activeClassMembers(\n  state: TemporalClosureState,\n  root: number,\n): readonly IdentityReference[] {\n  return state.references\n    .filter(\n      (_reference, index) =>\n        state.activeReferences[index] === true &&\n        findRoot(state.components, index) === root,\n    )\n    .toSorted((left, right) =>\n      compareMergeKeys(\n        mergeKey(left.kind, left.id),\n        mergeKey(right.kind, right.id),\n      ),\n    );\n}\n\nfunction componentKindsInReferenceOrder(\n  state: TemporalClosureState,\n  root: number,\n): readonly string[] {\n  return [...requireDefined(state.components.kindFirstReference[root])]\n    .toSorted((left, right) => left[1] - right[1])\n    .map(([kind]) => kind);\n}\n\nfunction assertCoordinateConsistent(state: TemporalClosureState): void {\n  if (state.sharedIdViolationCount.value > 0) {\n    const activeById = new Map<string, IdentityReference[]>();\n    for (const [index, reference] of state.references.entries()) {\n      if (state.activeReferences[index] !== true) continue;\n      const references = activeById.get(reference.id) ?? [];\n      references.push(reference);\n      activeById.set(reference.id, references);\n    }\n    for (const [sharedId, references] of activeById) {\n      const disjointKinds = firstDisjointPair(state, [\n        ...new Set(references.map((reference) => reference.kind)),\n      ]);\n      if (disjointKinds === undefined) continue;\n      throw new IdentityMergeConflictError(\n        \"The merged graph would give one id to two ontology-disjoint kinds.\",\n        { details: { disjointKinds, sharedId } },\n      );\n    }\n  }\n\n  if (state.contradictoryAssertions.size > 0) {\n    const assertionIndex = firstAssertionIndex(state.contradictoryAssertions);\n    const assertion = requireDefined(state.assertions[assertionIndex]);\n    const root = findRoot(\n      state.components,\n      requireDefined(state.referenceIndexByKey.get(mergeKeyOf(assertion.a))),\n    );\n    throw new IdentityMergeConflictError(\n      \"The merged identity ledger would assert one pair of nodes is both the same and different.\",\n      {\n        details: {\n          assertion,\n          sameClass: activeClassMembers(state, root),\n        },\n      },\n    );\n  }\n\n  const checkedRoots = new Set<number>();\n  for (const [referenceIndex, active] of state.activeReferences.entries()) {\n    if (!active) continue;\n    const root = findRoot(state.components, referenceIndex);\n    if (checkedRoots.has(root)) continue;\n    checkedRoots.add(root);\n    if (!requireDefined(state.components.violatesOntology[root])) continue;\n    const sameClass = activeClassMembers(state, root);\n    const disjointKinds = firstDisjointPair(\n      state,\n      componentKindsInReferenceOrder(state, root),\n    );\n    if (disjointKinds === undefined) continue;\n    throw new IdentityMergeConflictError(\n      \"The merged identity ledger would join two ontology-disjoint kinds into one class.\",\n      { details: { disjointKinds, sameClass } },\n    );\n  }\n}\n\nfunction addRangeEvent(\n  events: readonly TemporalEvents[],\n  node: number,\n  left: number,\n  right: number,\n  start: number,\n  end: number,\n  add: (event: TemporalEvents) => void,\n): void {\n  if (start <= left && right <= end) {\n    add(requireDefined(events[node]));\n    return;\n  }\n  const middle = Math.floor((left + right) / 2);\n  if (start < middle) {\n    addRangeEvent(events, node * 2, left, middle, start, end, add);\n  }\n  if (middle < end) {\n    addRangeEvent(events, node * 2 + 1, middle, right, start, end, add);\n  }\n}\n\nfunction visitTemporalEvents(\n  events: readonly TemporalEvents[],\n  state: TemporalClosureState,\n  node: number,\n  left: number,\n  right: number,\n): void {\n  const snapshot = state.undo.length;\n  const event = requireDefined(events[node]);\n  for (const referenceIndex of event.references) {\n    activateReference(state, referenceIndex);\n  }\n  for (const assertionIndex of event.sameAssertions) {\n    const assertion = requireDefined(state.assertions[assertionIndex]);\n    unionReferences(\n      state,\n      requireDefined(state.referenceIndexByKey.get(mergeKeyOf(assertion.a))),\n      requireDefined(state.referenceIndexByKey.get(mergeKeyOf(assertion.b))),\n    );\n  }\n  for (const assertionIndex of event.differentAssertions) {\n    addDifferentAssertion(state, assertionIndex);\n  }\n\n  if (right - left === 1) {\n    assertCoordinateConsistent(state);\n  } else {\n    const middle = Math.floor((left + right) / 2);\n    visitTemporalEvents(events, state, node * 2, left, middle);\n    visitTemporalEvents(events, state, node * 2 + 1, middle, right);\n  }\n  rollback(state, snapshot);\n}\n\nfunction mergeRanges(\n  ranges: readonly Readonly<{ start: number; end: number }>[],\n): readonly Readonly<{ start: number; end: number }>[] {\n  const merged: { start: number; end: number }[] = [];\n  for (const range of ranges.toSorted(\n    (left, right) => left.start - right.start,\n  )) {\n    const previous = merged.at(-1);\n    if (previous === undefined || previous.end < range.start) {\n      merged.push({ ...range });\n    } else {\n      previous.end = Math.max(previous.end, range.end);\n    }\n  }\n  return merged;\n}\n\nexport function assertTemporalIdentityClosureConsistent(\n  assertions: readonly IdentityTransferAssertion[],\n  identityContext: PlanIdentityContext,\n  nodeUniverse: readonly IdentityReference[],\n): void {\n  const boundaries = new Set<string>();\n  for (const assertion of assertions) {\n    boundaries.add(assertion.validFrom);\n    if (assertion.validTo !== undefined) boundaries.add(assertion.validTo);\n  }\n  const sortedBoundaries = [...boundaries].toSorted();\n  const leafCount = Math.max(1, sortedBoundaries.length);\n  const boundaryIndex = new Map(\n    sortedBoundaries.map((boundary, index) => [boundary, index]),\n  );\n  const assertionRanges: AssertionRange[] = assertions.map(\n    (assertion, assertionIndex) => ({\n      assertionIndex,\n      start: requireDefined(boundaryIndex.get(assertion.validFrom)),\n      end:\n        assertion.validTo === undefined ?\n          leafCount\n        : requireDefined(boundaryIndex.get(assertion.validTo)),\n    }),\n  );\n\n  const references: IdentityReference[] = [];\n  const referenceIndexByKey = new Map<MergeKey, number>();\n  const addReference = (reference: IdentityReference): number => {\n    const key = mergeKey(reference.kind, reference.id);\n    const existing = referenceIndexByKey.get(key);\n    if (existing !== undefined) return existing;\n    const index = references.length;\n    references.push(reference);\n    referenceIndexByKey.set(key, index);\n    return index;\n  };\n  const alwaysActive = new Set(nodeUniverse.map((node) => addReference(node)));\n  const rangesByReference = new Map<\n    number,\n    Readonly<{ start: number; end: number }>[]\n  >();\n  for (const range of assertionRanges) {\n    if (range.start >= range.end) continue;\n    const assertion = requireDefined(assertions[range.assertionIndex]);\n    for (const endpoint of [assertion.a, assertion.b]) {\n      const referenceIndex = addReference(endpoint);\n      const ranges = rangesByReference.get(referenceIndex) ?? [];\n      ranges.push({ start: range.start, end: range.end });\n      rangesByReference.set(referenceIndex, ranges);\n    }\n  }\n\n  const events: TemporalEvents[] = Array.from(\n    { length: leafCount * 4 },\n    () => ({ references: [], sameAssertions: [], differentAssertions: [] }),\n  );\n  for (const [referenceIndex, ranges] of rangesByReference) {\n    if (alwaysActive.has(referenceIndex)) continue;\n    for (const range of mergeRanges(ranges)) {\n      addRangeEvent(events, 1, 0, leafCount, range.start, range.end, (event) =>\n        event.references.push(referenceIndex),\n      );\n    }\n  }\n  for (const range of assertionRanges) {\n    if (range.start >= range.end) continue;\n    const assertion = requireDefined(assertions[range.assertionIndex]);\n    addRangeEvent(events, 1, 0, leafCount, range.start, range.end, (event) =>\n      assertion.relation === \"same\" ?\n        event.sameAssertions.push(range.assertionIndex)\n      : event.differentAssertions.push(range.assertionIndex),\n    );\n  }\n\n  const state: TemporalClosureState = {\n    assertions,\n    context: identityContext,\n    references,\n    referenceIndexByKey,\n    activeReferences: references.map(() => false),\n    activeReferencesById: new Map(),\n    components: {\n      parent: references.map((_reference, index) => index),\n      sizes: references.map(() => 1),\n      kindFirstReference: references.map(\n        (reference, index) => new Map([[reference.kind, index]]),\n      ),\n      differentAssertions: references.map(() => new Set<number>()),\n      violatesOntology: references.map(() => false),\n    },\n    contradictoryAssertions: new Set(),\n    undo: [],\n    disjointCache: new Map(),\n    sharedIdViolationCount: { value: 0 },\n  };\n  // Universe nodes are present at every coordinate, so their activation and\n  // same-id folds form the rollback traversal's immutable baseline.\n  for (const referenceIndex of alwaysActive)\n    activateReference(state, referenceIndex);\n  state.undo.length = 0;\n  visitTemporalEvents(events, state, 1, 0, leafCount);\n}\n","/**\n * Identity semantics of graph merge, in one module: the plan-time derivation\n * of identity changes (dedupe, retraction truth validation, endpoint remap),\n * the plan-time contradiction simulation, and the commit-transaction guards\n * that prove the validated identity state still holds when the plan applies.\n *\n * The dependency is one-directional: `merge.ts` (the orchestrator) imports\n * from here, never the reverse. Functions that need plan data take\n * {@link IdentityPlanSlice} — a structural subset of `MergePlan` — so this\n * module never names the full plan type.\n *\n * COMMIT-GUARD LAYERING. Correctness rests on what runs INSIDE the commit\n * transaction: the by-id freshness check ({@link assertPlannedIdentityIdsFresh}\n * — ended rows included, which no ledger slice or class fingerprint can see),\n * the identity applier's own refusals, and — after the identity DML — the\n * post-write affected-class assertion\n * ({@link assertMergedIdentityClassesConsistent}), which re-derives the\n * touched identity classes from the state the merge just wrote and refuses a\n * contradiction there. All of them translate typed at the apply boundary\n * through {@link translateIdentityCommitError}.\n *\n * Every layer ABOVE that is diagnosability. The plan-time simulation\n * ({@link assertNoContradictoryIdentityClosure}) and the window fingerprints\n * (direct-peer arrivals, per-seed class/liveness fingerprints, the\n * negative-ledger fingerprint, and the simulation re-run inside\n * {@link assertIdentityPeersStable}) exist to refuse EARLY — before any write,\n * with a message naming exactly what drifted — rather than to make the commit\n * sound. Never add a NEW invariant as a fingerprint or a simulation arm alone:\n * make the applier or the post-write assertion enforce it against real state,\n * then simulate it for the error message if useful.\n *\n * Beneath all of it sits a layer that is not code at all: the derived identity\n * separation relation (`identity/separation.ts`) carries a CHECK constraint\n * that no plan, simulation, or applier can satisfy while a `different`\n * assertion sits inside one identity class. A plan that slips past every guard\n * above still aborts in the engine, and its\n * `IdentitySeparationViolationError` — an `IDENTITY_`-coded refusal — is\n * translated here like any other applier refusal.\n */\nimport { identityAssertionSemanticKey } from \"../identity/assertion-key\";\nimport {\n  identityReferenceKey,\n  normalizeIdentityPair,\n} from \"../identity/reference\";\nimport { identityValidityWindowsOverlap } from \"../identity/validity-window\";\nimport { encodeTupleKey } from \"../utils/tuple-key\";\nimport type { CanonicalEntity } from \"./canonicalize\";\nimport {\n  BaseVersionMismatchError,\n  describeCause,\n  IdentityMergeConflictError,\n  MergeError,\n} from \"./errors\";\nimport {\n  compareMergeKeys,\n  compareStrings,\n  idOf,\n  kindOf,\n  type MergeKey,\n  mergeKey,\n  mergeKeyOf,\n} from \"./node-key\";\nimport type { StagedIdentityAssertion, StagingSet } from \"./staging\";\nimport { assertTemporalIdentityClosureConsistent } from \"./temporal-identity-closure\";\nimport {\n  compareCodePoints,\n  type GraphBackend,\n  type GraphDef,\n  IdentityContradictionError,\n  type IdentityTransferAssertion,\n  NodeNotFoundError,\n  type Store,\n  storeBackend,\n  storeRuntime,\n  type TransactionBackend,\n  TypeGraphError,\n} from \"./typegraph-internal\";\nimport type { DroppedItem } from \"./types\";\n\n/**\n * The identity-relevant slice of a resolved merge plan: a STRUCTURAL subset of\n * `MergePlan` (which `merge.ts` defines), so the orchestrator can hand its\n * plan to every function here without this module importing the plan type.\n */\nexport type IdentityPlanSlice = Readonly<{\n  canonicalEntities: readonly CanonicalEntity[];\n  identityAssertions: readonly IdentityTransferAssertion[];\n  identityRetractions: readonly IdentityTransferAssertion[];\n  nodeDeletions: ReadonlyMap<MergeKey, string>;\n  retypeMap: ReadonlyMap<MergeKey, string>;\n  canonicalOf: ReadonlyMap<MergeKey, MergeKey>;\n}>;\n\n/**\n * The `(a.kind, a.id, b.kind, b.id)` endpoint tuple every identity key encoder\n * below is built from. One definition keeps their FIELD ORDER identical — the\n * keys are compared against each other's encodings, so a drifted order in one\n * encoder would silently stop matching rows the others key the same way.\n */\nfunction endpointTuple(\n  assertion: Readonly<{ a: IdentityEndpoint; b: IdentityEndpoint }>,\n): readonly string[] {\n  return [assertion.a.kind, assertion.a.id, assertion.b.kind, assertion.b.id];\n}\n\nfunction identityEndpointKey(assertion: IdentityTransferAssertion): string {\n  return encodeTupleKey(endpointTuple(assertion));\n}\n\nfunction identitySemanticKey(assertion: IdentityTransferAssertion): string {\n  return identityAssertionSemanticKey(\n    assertion.relation,\n    assertion.a,\n    assertion.b,\n  );\n}\n\nfunction identityDedupeKey(assertion: IdentityTransferAssertion): string {\n  const semantic = identitySemanticKey(assertion);\n  if (assertion.validTo === undefined) return semantic;\n  return encodeTupleKey([semantic, assertion.validFrom, assertion.validTo]);\n}\n\nfunction compareIdentitySurvivors(\n  left: IdentityTransferAssertion,\n  right: IdentityTransferAssertion,\n): number {\n  const byValidity = compareCodePoints(left.validFrom, right.validFrom);\n  return byValidity === 0 ? compareCodePoints(left.id, right.id) : byValidity;\n}\n\n/**\n * Reason recorded when two branches asserted the SAME semantic pair and the\n * survivor rule kept only one of the two assertion ids.\n */\nexport const DUPLICATE_IDENTITY_ASSERTION_DROP_REASON =\n  \"identity:duplicate-assertion\";\n\n/**\n * Reason recorded when node reconciliation collapsed both endpoints of a `same`\n * assertion onto one survivor, making the assertion vacuous.\n */\nexport const REDUNDANT_IDENTITY_ASSERTION_DROP_REASON =\n  \"identity:endpoints-collapsed\";\n\n/** Reason recorded when endpoint remapping leaves no shared validity window. */\nexport const EMPTY_REMAPPED_IDENTITY_WINDOW_DROP_REASON =\n  \"identity:empty-remapped-window\";\n\n/** The report entry for an identity assertion the merge did not apply. */\nfunction droppedIdentityAssertion(\n  assertion: IdentityTransferAssertion,\n  reason: string,\n): DroppedItem {\n  return { kind: \"identity\", id: assertion.id, reason };\n}\n\n/**\n * Keeps one CURRENT assertion per semantic pair, while retaining every\n * distinct bounded window. Exact bounded duplicates still choose one survivor\n * and report the loser. Survivors come back in window-aware key order.\n *\n * An id in `committedIds` (already committed on the target with the exact\n * staged truth) ALWAYS wins over an uncommitted challenger, regardless of the\n * {@link compareIdentitySurvivors} order: the applier is idempotent per\n * dedupe key, so the challenger would never be written — picking it would\n * report an id as applied that never lands while listing the target's own row\n * as dropped. Between two ids of equal committed status the comparator\n * decides.\n */\nfunction dedupeIdentityAssertions(\n  assertions: readonly IdentityTransferAssertion[],\n  committedIds: ReadonlySet<string>,\n): Readonly<{\n  survivors: readonly IdentityTransferAssertion[];\n  dropped: readonly DroppedItem[];\n}> {\n  const survivorBySemantic = new Map<string, IdentityTransferAssertion>();\n  const dropped: DroppedItem[] = [];\n  for (const assertion of assertions) {\n    const key = identityDedupeKey(assertion);\n    const previous = survivorBySemantic.get(key);\n    if (previous === undefined) {\n      survivorBySemantic.set(key, assertion);\n      continue;\n    }\n    const assertionCommitted = committedIds.has(assertion.id);\n    const previousCommitted = committedIds.has(previous.id);\n    const [survivor, loser] =\n      assertionCommitted === previousCommitted ?\n        compareIdentitySurvivors(assertion, previous) < 0 ?\n          ([assertion, previous] as const)\n        : ([previous, assertion] as const)\n      : assertionCommitted ? ([assertion, previous] as const)\n      : ([previous, assertion] as const);\n    survivorBySemantic.set(key, survivor);\n    // Two branches staging the IDENTICAL row (same id, same complete truth —\n    // e.g. both imported one interchange document) is ONE assertion, not a\n    // survivor and a loser: reporting the id as dropped while it is applied\n    // would make the report self-contradictory.\n    if (\n      loser.id === survivor.id &&\n      loser.validFrom === survivor.validFrom &&\n      (loser.validTo ?? undefined) === (survivor.validTo ?? undefined)\n    ) {\n      continue;\n    }\n    dropped.push(\n      droppedIdentityAssertion(loser, DUPLICATE_IDENTITY_ASSERTION_DROP_REASON),\n    );\n  }\n  return {\n    survivors: [...survivorBySemantic.values()].toSorted((left, right) =>\n      compareCodePoints(identityDedupeKey(left), identityDedupeKey(right)),\n    ),\n    dropped,\n  };\n}\n\nfunction assertNoOpposingIdentityRelations(\n  assertions: readonly IdentityTransferAssertion[],\n): void {\n  const byEndpoint = new Map<string, IdentityTransferAssertion[]>();\n  for (const assertion of assertions) {\n    const key = identityEndpointKey(assertion);\n    const group = byEndpoint.get(key) ?? [];\n    group.push(assertion);\n    byEndpoint.set(key, group);\n  }\n  for (const [endpoint, group] of byEndpoint) {\n    const same = group.filter((assertion) => assertion.relation === \"same\");\n    const different = group.filter(\n      (assertion) => assertion.relation === \"different\",\n    );\n    for (const sameAssertion of same) {\n      for (const differentAssertion of different) {\n        if (\n          !identityValidityWindowsOverlap(sameAssertion, differentAssertion)\n        ) {\n          continue;\n        }\n        throw new IdentityMergeConflictError(\n          \"Branches asserted opposing identity relations for one endpoint pair.\",\n          {\n            details: {\n              endpoint,\n              assertions: [sameAssertion, differentAssertion],\n            },\n          },\n        );\n      }\n    }\n  }\n}\n\n/**\n * Refuses the retract/reassert RACE: one branch retracts the assertion for a\n * semantic pair while a DIFFERENT branch re-asserts that pair under a new id\n * WITHOUT retracting it — the branches disagree about whether the old truth still\n * holds, and no rule can pick between \"the pair is not asserted\" and \"the pair is\n * asserted under a new id\".\n *\n * Two nearby shapes are NOT races and must merge cleanly:\n *\n *   - A single fork that retracts then re-asserts the same pair (a normal linear\n *     edit): its final state is simply \"old id retracted, new id asserted\".\n *   - CONVERGENT edits, where the re-asserting branch ALSO retracted the pair:\n *     every branch agrees the old assertion dies, and one went further by\n *     re-asserting. The merge applies both effects.\n *\n * Both hinge on which branch produced which change, so this consults the staged\n * (branch-tagged) retractions — grouping by semantic key alone would drop exactly\n * the provenance that separates a race from agreement.\n */\nfunction assertNoRetractReassertRace(staging: StagingSet): void {\n  const retractedBySemantic = new Map<string, StagedIdentityAssertion[]>();\n  for (const staged of staging.retractedIdentityAssertions) {\n    const key = identitySemanticKey(staged.assertion);\n    const retractions = retractedBySemantic.get(key) ?? [];\n    retractions.push(staged);\n    retractedBySemantic.set(key, retractions);\n  }\n  for (const staged of staging.newIdentityAssertions) {\n    const retractions =\n      retractedBySemantic.get(identitySemanticKey(staged.assertion)) ?? [];\n    const selfRetracted = retractions.some(\n      (retraction) => retraction.branchId === staged.branchId,\n    );\n    if (selfRetracted) {\n      continue;\n    }\n    const crossBranchRetraction = retractions.find(\n      (retraction) => retraction.assertion.id !== staged.assertion.id,\n    );\n    if (crossBranchRetraction !== undefined) {\n      throw new IdentityMergeConflictError(\n        \"Branches contain a retract/reassert race for one identity pair.\",\n        {\n          details: {\n            retractedAssertion: crossBranchRetraction.assertion,\n            retractedBy: crossBranchRetraction.branchId,\n            reassertedAssertion: staged.assertion,\n            reassertedBy: staged.branchId,\n          },\n        },\n      );\n    }\n  }\n}\n\n/**\n * Reason recorded when a branch retracted an assertion whose id identifies a\n * DIFFERENT complete truth on the target's current ledger. Ending that row\n * would delete truth the branch never saw, while the branch's actual intent —\n * \"the assertion I retracted no longer holds\" — is already satisfied by that\n * assertion's absence, so the retraction is skipped and reported instead.\n */\nexport const RETRACTION_TARGET_MISMATCH_DROP_REASON =\n  \"identity:retraction-target-mismatch\";\n\n/**\n * Reason recorded when EVERY branch that staged a retraction staged it as the\n * cascade of a node deletion the delete/modify resolution then OVERRULED.\n *\n * A node soft-delete ends every open assertion touching the node, so the\n * deleting branch's diff stages those endings as retractions — but it stages\n * them with their derived cause (the deleted node), not as bare retractions.\n * When the modification wins and the node survives, the cause is gone: applying\n * the ending would strip the resurrected node's identity truth, so it is\n * dropped (visibly) along with the deletion that caused it. A retraction any\n * branch made EXPLICITLY, or whose cause deletion survived, is never dropped\n * here.\n */\nexport const RETRACTION_DELETION_OVERRULED_DROP_REASON =\n  \"identity:deletion-overruled\";\n\n/** The empty stored-row map, for validating staged assertions intra-plan only. */\nexport const NO_STORED_ASSERTIONS: ReadonlyMap<string, LedgerAssertion> =\n  new Map();\n\n/** @internal Exported for deterministic phase-level verification. */\nexport function planIdentityChanges(\n  staging: StagingSet,\n  storedIdentityRowsById: ReadonlyMap<string, LedgerAssertion>,\n): Readonly<{\n  assertions: readonly IdentityTransferAssertion[];\n  retractions: readonly IdentityTransferAssertion[];\n  dropped: readonly DroppedItem[];\n}> {\n  assertNoOpposingIdentityRelations(\n    staging.newIdentityAssertions.map((staged) => staged.assertion),\n  );\n  assertNoRetractReassertRace(staging);\n  // One id, one truth — over the RAW staged assertions, BEFORE the semantic\n  // survivor dedupe: two branches staging one id for the same pair with\n  // different validFrom values collapse into one survivor under the semantic\n  // key (which excludes validity), so a later check would never see the\n  // collision — while the report would list the id as both applied and\n  // dropped.\n  assertOneIdOneTruth(\n    staging.newIdentityAssertions.map((staged) => staged.assertion),\n    NO_STORED_ASSERTIONS,\n  );\n\n  // Staged ids the target ALREADY holds with the exact staged truth. The\n  // survivor dedupe must prefer these: the applier is idempotent per semantic\n  // pair, so a freshly minted branch id can never displace the target's\n  // committed row — choosing it would report an id as applied that is never\n  // written while listing the target's own row as dropped.\n  const committedIds = new Set<string>(\n    staging.newIdentityAssertions\n      .map((staged) => staged.assertion)\n      .filter((assertion) => {\n        const stored = storedIdentityRowsById.get(assertion.id);\n        return (\n          stored !== undefined &&\n          assertionTruthKey(stored) === assertionTruthKey(assertion)\n        );\n      })\n      .map((assertion) => assertion.id),\n  );\n  const deduped = dedupeIdentityAssertions(\n    staging.newIdentityAssertions.map((staged) => staged.assertion),\n    committedIds,\n  );\n  const retractionById = new Map<string, IdentityTransferAssertion>();\n  for (const staged of staging.retractedIdentityAssertions) {\n    const previous = retractionById.get(staged.assertion.id);\n    if (\n      previous !== undefined &&\n      assertionIdentityKey(previous) !== assertionIdentityKey(staged.assertion)\n    ) {\n      throw new IdentityMergeConflictError(\n        \"One assertion id was staged for retraction with two different identity truths.\",\n        {\n          details: {\n            assertionId: staged.assertion.id,\n            first: previous,\n            second: staged.assertion,\n          },\n        },\n      );\n    }\n    retractionById.set(staged.assertion.id, staged.assertion);\n  }\n  const retractions: IdentityTransferAssertion[] = [];\n  const retractionDropped: DroppedItem[] = [];\n  for (const [assertionId, retraction] of retractionById) {\n    const stored = storedIdentityRowsById.get(assertionId);\n    if (\n      stored !== undefined &&\n      stored.validTo === undefined &&\n      assertionIdentityKey(stored) !== assertionIdentityKey(retraction)\n    ) {\n      retractionDropped.push({\n        kind: \"identity\",\n        id: assertionId,\n        reason: RETRACTION_TARGET_MISMATCH_DROP_REASON,\n      });\n      continue;\n    }\n    retractions.push(retraction);\n  }\n  // Defensive: one id planned as BOTH a new assertion and a retraction would\n  // reach the applier as retract-then-import of one id, which the import\n  // refuses generically (the freshly ended row fails its exact-match test).\n  // Unreachable through the supported staging paths today — the truth-aware\n  // diff and the retraction truth filter each break every construction we\n  // know — so refuse typed if a future path assembles it.\n  const survivingIds = new Set(\n    deduped.survivors.map((survivor) => survivor.id),\n  );\n  for (const retraction of retractions) {\n    if (survivingIds.has(retraction.id)) {\n      throw new IdentityMergeConflictError(\n        \"One assertion id was staged as both a new assertion and a retraction.\",\n        { details: { assertionId: retraction.id } },\n      );\n    }\n  }\n  return {\n    assertions: deduped.survivors,\n    retractions: retractions.toSorted((left, right) =>\n      compareCodePoints(left.id, right.id),\n    ),\n    dropped: [...deduped.dropped, ...retractionDropped],\n  };\n}\n\n/** A plain `(kind, id)` node reference — an identity assertion endpoint. */\ntype IdentityEndpoint = Readonly<{ kind: string; id: string }>;\n\n/**\n * Maps an endpoint onto the `(kind, id)` it will actually carry in the committed\n * target: first through the cluster canonical map (the SAME map edge repoint\n * uses), then through the ontology retype cascade, keyed EXACTLY as\n * {@link applyMergePlan} keys an edge endpoint — `mergeKey(kind, id)` of the\n * post-canonical endpoint, whose retype value is the survivor's reconciled kind.\n *\n * Both hops are required. Under `reconcileTypes: \"ontology\"` a cluster survivor\n * is written under its most-specific kind, so an assertion that still named the\n * pre-retype kind would reference a `(kind, id)` no live row carries and the\n * commit-time endpoint guard would reject it (or, worse, bind to a stale row of\n * the old kind).\n */\nfunction resolveIdentityEndpoint(\n  endpoint: IdentityEndpoint,\n  canonicalOf: ReadonlyMap<MergeKey, MergeKey>,\n  retypeMap: ReadonlyMap<MergeKey, string>,\n): IdentityEndpoint {\n  const key = mergeKeyOf(endpoint);\n  const canonical = canonicalOf.get(key) ?? key;\n  return {\n    kind: retypeMap.get(canonical) ?? kindOf(canonical),\n    id: idOf(canonical),\n  };\n}\n\n/**\n * Repoints every planned identity assertion's endpoints onto the identity they\n * will hold after the commit ({@link resolveIdentityEndpoint}), so an assertion\n * naming a branch node that reconciliation folded away — or retyped — references\n * the surviving row instead of a dangling `(kind, id)` (which the commit-time\n * `requireLiveEndpoints` guard would reject with a NodeNotFoundError, rolling back\n * the whole merge). After remapping it re-establishes the identity-pair invariants:\n * a `same` assertion whose endpoints collapse onto one survivor is redundant\n * and dropped (reported), while a collapsed `different` assertion is a typed\n * conflict; surviving endpoints are re-normalized into code-point order (the\n * import path rejects a non-normalized pair), and assertions that now share a\n * semantic key are re-deduped by the same survivor rule\n * ({@link compareIdentitySurvivors}) that {@link planIdentityChanges} applied\n * before the remap.\n */\nexport function remapIdentityAssertionEndpoints(\n  assertions: readonly IdentityTransferAssertion[],\n  canonicalOf: ReadonlyMap<MergeKey, MergeKey>,\n  retypeMap: ReadonlyMap<MergeKey, string>,\n  storedRowsById: ReadonlyMap<string, LedgerAssertion>,\n  endpointWindows: ReadonlyMap<\n    MergeKey,\n    Readonly<{ validFrom?: string; validTo?: string }>\n  > = new Map(),\n): Readonly<{\n  assertions: readonly IdentityTransferAssertion[];\n  dropped: readonly DroppedItem[];\n  warnings: readonly string[];\n}> {\n  const remapped: IdentityTransferAssertion[] = [];\n  const dropped: DroppedItem[] = [];\n  const narrowingWarningById = new Map<string, string>();\n  for (const assertion of assertions) {\n    const remappedA = resolveIdentityEndpoint(\n      assertion.a,\n      canonicalOf,\n      retypeMap,\n    );\n    const remappedB = resolveIdentityEndpoint(\n      assertion.b,\n      canonicalOf,\n      retypeMap,\n    );\n    if (mergeKeyOf(remappedA) === mergeKeyOf(remappedB)) {\n      if (assertion.relation === \"different\") {\n        throw new IdentityMergeConflictError(\n          \"Node reconciliation collapsed a different-identity assertion onto one survivor.\",\n          { details: { assertion, survivor: remappedA } },\n        );\n      }\n      dropped.push(\n        droppedIdentityAssertion(\n          assertion,\n          REDUNDANT_IDENTITY_ASSERTION_DROP_REASON,\n        ),\n      );\n      continue;\n    }\n    const [a, b] = normalizeIdentityPair(remappedA, remappedB);\n    const endpointWindowA = endpointWindows.get(mergeKeyOf(a));\n    const endpointWindowB = endpointWindows.get(mergeKeyOf(b));\n    const validFrom = [\n      assertion.validFrom,\n      endpointWindowA?.validFrom,\n      endpointWindowB?.validFrom,\n    ]\n      .filter((bound): bound is string => bound !== undefined)\n      .reduce((latest, bound) =>\n        compareCodePoints(latest, bound) < 0 ? bound : latest,\n      );\n    const validTo = [\n      assertion.validTo,\n      endpointWindowA?.validTo,\n      endpointWindowB?.validTo,\n    ]\n      .filter((bound): bound is string => bound !== undefined)\n      .reduce<string | undefined>(\n        (earliest, bound) =>\n          earliest === undefined || compareCodePoints(bound, earliest) < 0 ?\n            bound\n          : earliest,\n        undefined,\n      );\n    if (validTo !== undefined && compareCodePoints(validFrom, validTo) >= 0) {\n      dropped.push(\n        droppedIdentityAssertion(\n          assertion,\n          EMPTY_REMAPPED_IDENTITY_WINDOW_DROP_REASON,\n        ),\n      );\n      continue;\n    }\n    if (validFrom !== assertion.validFrom || validTo !== assertion.validTo) {\n      const originalUpper = assertion.validTo ?? \"open\";\n      const remappedUpper = validTo ?? \"open\";\n      narrowingWarningById.set(\n        assertion.id,\n        `Identity assertion ${JSON.stringify(assertion.id)} was narrowed from [${assertion.validFrom}, ${originalUpper}) to [${validFrom}, ${remappedUpper}) to fit its remapped endpoint windows.`,\n      );\n    }\n    const result = {\n      ...assertion,\n      a,\n      b,\n      validFrom,\n      ...(validTo === undefined ? {} : { validTo }),\n    };\n    // A COMMITTED row's endpoints must never be canonicalized away: the\n    // applier cannot rewrite a stored row, so a plan carrying its id with\n    // moved endpoints could only end as a false one-truth refusal or —\n    // worse, if the challenger won the dedupe — a report/ledger divergence.\n    // Refuse early with the specific cause instead.\n    const stored = storedRowsById.get(assertion.id);\n    if (\n      stored !== undefined &&\n      assertionTruthKey(stored) === assertionTruthKey(assertion) &&\n      assertionTruthKey(result) !== assertionTruthKey(assertion)\n    ) {\n      throw new IdentityMergeConflictError(\n        \"Node reconciliation moved the endpoints of an assertion already committed on the target; committed identity rows cannot be rewritten by a merge.\",\n        {\n          details: { assertionId: assertion.id, stored, remapped: result },\n          suggestion:\n            \"Exclude the colliding nodes from entity resolution, or manually retract the committed assertion and re-assert the canonical pair under a new id before merging.\",\n        },\n      );\n    }\n    remapped.push(result);\n  }\n  // Committed-id precedence must be RE-DERIVED post-remap: node\n  // reconciliation can collapse two previously distinct pairs onto one\n  // semantic key (a branch pair canonicalized onto a target pair), and the\n  // target's committed row — whose endpoints the remap leaves unchanged —\n  // still exactly matches its stored truth here. Without the recompute, the\n  // branch's unwritable challenger could win this second dedupe and recreate\n  // the applied-but-never-written report divergence.\n  const committedIds = new Set<string>(\n    remapped\n      .filter((assertion) => {\n        const stored = storedRowsById.get(assertion.id);\n        return (\n          stored !== undefined &&\n          assertionTruthKey(stored) === assertionTruthKey(assertion)\n        );\n      })\n      .map((assertion) => assertion.id),\n  );\n  const deduped = dedupeIdentityAssertions(remapped, committedIds);\n  // Node reconciliation can collapse previously distinct endpoint pairs onto\n  // the same canonical pair, so the pre-reconciliation check above is not\n  // sufficient on its own.\n  assertNoOpposingIdentityRelations(deduped.survivors);\n  return {\n    assertions: deduped.survivors,\n    dropped: [...dropped, ...deduped.dropped],\n    warnings: deduped.survivors.flatMap((assertion) => {\n      const warning = narrowingWarningById.get(assertion.id);\n      return warning === undefined ? [] : [warning];\n    }),\n  };\n}\n\n/**\n * Refuses an assertion that names a node the merge is about to DELETE.\n *\n * The commit soft-deletes nodes before applying the identity changes, which\n * detaches every assertion touching them, so an assertion naming a deleted\n * endpoint could only ever fail at commit time — rolling the whole merge back\n * behind a generic error. Detecting it here turns it into a deterministic,\n * plan-time {@link IdentityMergeConflictError}: one branch says the entity exists\n * and is (not) the same as another, a second says it is gone, and unlike the\n * delete/modify case there is no policy the caller can set to arbitrate.\n *\n * `nodeDeletions` is keyed by the deleted node's own kind, while the assertions\n * arrive post-retype, so a retyped identity is checked in BOTH forms.\n */\nexport function assertIdentityEndpointsNotDeleted(\n  assertions: readonly IdentityTransferAssertion[],\n  nodeDeletions: ReadonlyMap<MergeKey, string>,\n  retypeMap: ReadonlyMap<MergeKey, string>,\n): void {\n  const deletedIdentities = new Set<MergeKey>();\n  for (const key of nodeDeletions.keys()) {\n    deletedIdentities.add(key);\n    const retyped = retypeMap.get(key);\n    if (retyped !== undefined) {\n      deletedIdentities.add(mergeKey(retyped, idOf(key)));\n    }\n  }\n  for (const assertion of assertions) {\n    for (const endpoint of [assertion.a, assertion.b]) {\n      if (!deletedIdentities.has(mergeKeyOf(endpoint))) {\n        continue;\n      }\n      throw new IdentityMergeConflictError(\n        \"A branch asserted an identity relation over a node another branch deleted.\",\n        { details: { assertion, deletedEndpoint: endpoint } },\n      );\n    }\n  }\n}\n\n/**\n * Refuses — BEFORE any write — a merge whose committed ledger would claim two\n * nodes are BOTH the same and different, including through a chain of `same`\n * assertions no single branch ever wrote.\n *\n * This is the DIAGNOSABILITY layer, not the correctness one. It simulates the\n * post-merge ledger from reads taken before the commit, so it can name the\n * exact branch assertion and identity class at fault while nothing has been\n * written yet — but a target that moves between this simulation and the commit\n * makes its verdict stale. What the committed state is actually held to is\n * {@link assertMergedIdentityClassesConsistent}, which re-derives the affected\n * classes from the written state inside the commit transaction. Keep the two\n * in agreement: a simulation arm with no post-write counterpart is a message,\n * not a guarantee.\n *\n * {@link assertNoOpposingIdentityRelations} only sees a DIRECT collision (one\n * endpoint pair carrying both relations). The common shape is transitive: base\n * holds `same(p2, p3)`, one branch asserts `same(p1, p2)` and another asserts\n * `different(p1, p3)`. Nothing collides pairwise, so planning used to pass and the\n * identity import raised its own contradiction error inside the commit\n * transaction, where the orchestrator's catch-all rewrote it as a generic\n * `MergeError` — the documented `GRAPH_MERGE_IDENTITY_CONFLICT` code never fired.\n *\n * The check evaluates the ledger the merge would actually leave behind: the base's\n * CURRENT assertions minus the staged retractions, plus the already remapped and\n * deduped staged assertions. Base endpoints are put through the same\n * {@link resolveIdentityEndpoint} mapping, so an inherited assertion whose node\n * was folded or retyped is judged at its post-merge identity. The `same`\n * assertions are folded into equivalence classes and every `different` pair —\n * staged or inherited — is rejected when both of its endpoints land in one class.\n *\n * Two DERIVED relations join the explicit ledger in the simulation, because\n * canonicalization and retyping can manufacture contradictions no branch wrote:\n * under `sameIdAcrossKinds: \"fold\"` endpoints sharing an id across kinds are\n * implicitly the same (a remapped cross-kind `different` pair can land on one\n * id), and a retyped endpoint can pull a kind into a class that the ontology\n * declares disjoint with another member's kind. Both used to surface only at\n * commit time as a generic merge error.\n *\n * @internal Exported for deterministic phase-level verification.\n */\nexport function assertNoContradictoryIdentityClosure(\n  plannedAssertions: readonly IdentityTransferAssertion[],\n  retractions: readonly string[],\n  baseAssertions: readonly IdentityTransferAssertion[],\n  deletedNodes: ReadonlySet<MergeKey>,\n  canonicalOf: ReadonlyMap<MergeKey, MergeKey>,\n  retypeMap: ReadonlyMap<MergeKey, string>,\n  identityContext: PlanIdentityContext,\n  nodeUniverse: readonly Readonly<{ kind: string; id: string }>[],\n): void {\n  const retracted = new Set(retractions);\n  // Deleting a node ends its assertions, so a base assertion touching a\n  // plan-deleted endpoint must not conduct in the simulated post-merge\n  // ledger. The commit-guard re-runs filter their fresh ledger the same way\n  // BEFORE calling here; applying the rule inside the checker keeps all\n  // three call sites on one rule even when a retraction was dropped (e.g.\n  // target-truth mismatch) and the cascade id never reaches `retractions`.\n  const survivesDeletion = (\n    assertion: Readonly<{\n      a: Readonly<{ kind: string; id: string }>;\n      b: Readonly<{ kind: string; id: string }>;\n    }>,\n  ): boolean =>\n    !deletedNodes.has(mergeKey(assertion.a.kind, assertion.a.id)) &&\n    !deletedNodes.has(mergeKey(assertion.b.kind, assertion.b.id));\n  const mergedLedger: readonly IdentityTransferAssertion[] = [\n    ...plannedAssertions,\n    ...baseAssertions\n      .filter(\n        (assertion) =>\n          !retracted.has(assertion.id) && survivesDeletion(assertion),\n      )\n      .map((assertion) => ({\n        ...assertion,\n        a: resolveIdentityEndpoint(assertion.a, canonicalOf, retypeMap),\n        b: resolveIdentityEndpoint(assertion.b, canonicalOf, retypeMap),\n      })),\n  ];\n  assertTemporalIdentityClosureConsistent(\n    mergedLedger,\n    identityContext,\n    nodeUniverse,\n  );\n}\n\n/**\n * The identity semantics the plan-time contradiction simulation needs from the\n * target: whether same-id folding is on, and which kind pairs the ontology\n * declares disjoint.\n */\nexport type PlanIdentityContext = Readonly<{\n  sameIdAcrossKinds: \"fold\" | \"ignore\" | undefined;\n  areDisjoint: (left: string, right: string) => boolean;\n}>;\n\n/**\n * The plan-time same-id fold probe the incremental commit guard revalidates\n * inside the transaction (`IncrementalCommitGuard.identityPeerProbe`).\n */\nexport type IdentityPeerProbe = Readonly<{\n  /**\n   * The target's identity profile. The direct-peer window check below only\n   * applies under `\"fold\"` — a same-id row appearing under `\"ignore\"` never\n   * changes plan legality, so refusing on it would reject an unrelated\n   * target advance.\n   */\n  profile: \"fold\" | \"ignore\";\n  ids: readonly string[];\n  observed: ReadonlySet<MergeKey>;\n  /**\n   * The plan's node deletions, by composite key. Rows the plan removes are\n   * excluded from BOTH sides of every comparison — they are gone in the\n   * committed state, so treating them as present would falsely reject a\n   * legal delete-and-replace (and a still-live-at-tx-time row the plan\n   * deletes must not read as an \"appeared\" peer either).\n   */\n  plannedDeletions: ReadonlySet<MergeKey>;\n  /**\n   * Every `(kind, id)` the guarded universe contains — the seeds plus all\n   * snapshot class members. The negative-truth fingerprint below ranges\n   * over `different` assertions touching this set.\n   */\n  memberKeys: ReadonlySet<MergeKey>;\n  /**\n   * Deterministic fingerprint of the CURRENT `different` assertions\n   * touching the guarded universe at snapshot time. Negative truth changes\n   * plan legality without moving peers, liveness, or equivalence classes,\n   * so it needs its own drift signal.\n   */\n  differentFingerprint: string;\n  /**\n   * The plan-time structural identity class of every final fold seed,\n   * serialized to a comparable fingerprint per seed. The direct-peer set\n   * above covers planned ids that do not exist yet; this covers\n   * class-TRANSITIVE drift — a window row or assertion joining a seed's\n   * class through another member changes the class without changing the\n   * seed's direct same-id peers.\n   */\n  classFingerprints: ReadonlyMap<string, string>;\n  seeds: readonly Readonly<{ kind: string; id: string }>[];\n}>;\n\n/**\n * Narrows the plan-time fold probe to the ids the FINAL plan folds on: the\n * commit-ready canonical node identities (minus planned deletions) and the\n * remapped assertion endpoints. The observed peer set is filtered the same\n * way so the in-transaction comparison ranges over one universe.\n */\nexport async function buildIdentityPeerProbe<G extends GraphDef>(\n  target: Store<G>,\n  probedIds: readonly string[],\n  targetPeers: readonly Readonly<{ kind: string; id: string }>[],\n  plan: IdentityPlanSlice,\n  profile: \"fold\" | \"ignore\",\n): Promise<\n  Readonly<{\n    probe: IdentityPeerProbe;\n    snapshot: IdentityClassSnapshot;\n    ledger: readonly LedgerAssertion[];\n  }>\n> {\n  const finalIds = new Set([\n    ...plan.canonicalEntities\n      .filter(\n        (entity) =>\n          !plan.nodeDeletions.has(mergeKey(entity.kind, entity.canonicalId)),\n      )\n      .map((entity) => entity.canonicalId),\n    ...plan.identityAssertions.flatMap((assertion) => [\n      assertion.a.id,\n      assertion.b.id,\n    ]),\n  ]);\n  const plannedDeletions = new Set<MergeKey>(plan.nodeDeletions.keys());\n  const relevantPeers = targetPeers.filter(\n    (peer) =>\n      finalIds.has(peer.id) &&\n      !plannedDeletions.has(mergeKey(peer.kind, peer.id)),\n  );\n  // The fold seeds whose classes plan legality depends on: the commit-ready\n  // canonical nodes (final retyped kinds), the remapped assertion endpoints,\n  // and the live target peers anchoring them into existing classes.\n  const seedsByKey = new Map<string, Readonly<{ kind: string; id: string }>>();\n  const addSeed = (kind: string, id: string): void => {\n    seedsByKey.set(mergeKey(kind, id), { kind, id });\n  };\n  for (const entity of plan.canonicalEntities) {\n    const sourceKey = mergeKey(entity.kind, entity.canonicalId);\n    if (plan.nodeDeletions.has(sourceKey)) continue;\n    addSeed(plan.retypeMap.get(sourceKey) ?? entity.kind, entity.canonicalId);\n  }\n  for (const assertion of plan.identityAssertions) {\n    addSeed(assertion.a.kind, assertion.a.id);\n    addSeed(assertion.b.kind, assertion.b.id);\n  }\n  for (const peer of relevantPeers) addSeed(peer.kind, peer.id);\n  const seeds = [...seedsByKey.values()];\n  const liveKeys = new Set(\n    targetPeers\n      .map((peer) => mergeKey(peer.kind, peer.id))\n      .filter((key) => !plannedDeletions.has(key)),\n  );\n  const snapshot = await snapshotIdentityClasses(\n    target,\n    seeds,\n    liveKeys,\n    plannedDeletions,\n  );\n  const memberKeys = new Set<MergeKey>([\n    ...seeds.map((seed) => mergeKey(seed.kind, seed.id)),\n    ...snapshot.groups.flatMap((group) =>\n      group.map((member) => mergeKey(member.kind, member.id)),\n    ),\n  ]);\n  // Negative truth is invisible to peers, liveness, and class structure, so\n  // the CURRENT ledger touching the universe is read fresh here: the recheck\n  // validates the plan against it, and its `different` slice is fingerprinted\n  // for the in-transaction comparison.\n  const ledger = (\n    await relevantLedgerAssertions(target, memberKeys, storeBackend(target))\n  ).filter(\n    (assertion) =>\n      !plannedDeletions.has(mergeKey(assertion.a.kind, assertion.a.id)) &&\n      !plannedDeletions.has(mergeKey(assertion.b.kind, assertion.b.id)),\n  );\n  return {\n    probe: {\n      profile,\n      plannedDeletions,\n      ids: probedIds.filter((id) => finalIds.has(id)),\n      observed: new Set(\n        relevantPeers.map((peer) => mergeKey(peer.kind, peer.id)),\n      ),\n      memberKeys,\n      differentFingerprint: differentLedgerFingerprint(ledger),\n      classFingerprints: snapshot.fingerprints,\n      seeds,\n    },\n    snapshot,\n    ledger,\n  };\n}\n\ntype IdentityClassSnapshot = Readonly<{\n  /**\n   * One comparable fingerprint per seed: the seed's LIVENESS plus its sorted\n   * class member tuples, JSON-encoded — structural encoding because caller\n   * ids may contain any character, so a joined string is not injective, and\n   * the liveness bit because a live singleton and a deleted or missing one\n   * have identical (self-coalesced) classes.\n   */\n  fingerprints: ReadonlyMap<string, string>;\n  /** The raw class member groups, for revalidating the plan against them. */\n  groups: readonly (readonly Readonly<{ kind: string; id: string }>[])[];\n}>;\n\nasync function snapshotIdentityClasses<G extends GraphDef>(\n  target: Store<G>,\n  seeds: readonly Readonly<{ kind: string; id: string }>[],\n  liveKeys: ReadonlySet<MergeKey>,\n  plannedDeletions: ReadonlySet<MergeKey>,\n  txBackend?: TransactionBackend,\n): Promise<IdentityClassSnapshot> {\n  const classes = await storeRuntime(target).structuralIdentityClasses(\n    seeds,\n    txBackend,\n  );\n  const fingerprints = new Map<string, string>();\n  const groups: (readonly Readonly<{ kind: string; id: string }>[])[] = [];\n  for (const seed of seeds) {\n    const key = mergeKey(seed.kind, seed.id);\n    // Members the plan DELETES are excluded on both sides of the comparison — the\n    // committed state no longer contains them, so keeping them would reject\n    // a legal delete-and-replace.\n    const members = (classes.get(identityReferenceKey(seed)) ?? [seed]).filter(\n      (member) => !plannedDeletions.has(mergeKey(member.kind, member.id)),\n    );\n    groups.push(members);\n    fingerprints.set(key, encodeClassFingerprint(liveKeys.has(key), members));\n  }\n  return { fingerprints, groups };\n}\n\nexport type LedgerAssertion = Readonly<{\n  id: string;\n  relation: \"same\" | \"different\";\n  a: Readonly<{ kind: string; id: string }>;\n  b: Readonly<{ kind: string; id: string }>;\n  validFrom: string;\n  validTo?: string | undefined;\n}>;\n\n/**\n * The target's CURRENT assertions touching the guarded universe, read fresh\n * from `backend` (the tx backend inside the commit transaction).\n */\nasync function relevantLedgerAssertions<G extends GraphDef>(\n  target: Store<G>,\n  memberKeys: ReadonlySet<MergeKey>,\n  backend: GraphBackend | TransactionBackend,\n): Promise<readonly LedgerAssertion[]> {\n  const current = await storeRuntime(target).identityAssertionsAtTarget(\n    backend,\n    \"state\",\n  );\n  return current.filter(\n    (assertion) =>\n      memberKeys.has(mergeKey(assertion.a.kind, assertion.a.id)) ||\n      memberKeys.has(mergeKey(assertion.b.kind, assertion.b.id)),\n  );\n}\n\n/** Deterministic fingerprint of the `different` assertions in a ledger slice. */\n/** @internal Deterministic fingerprint for commit-guard verification. */\nexport function differentLedgerFingerprint(\n  assertions: readonly LedgerAssertion[],\n): string {\n  return JSON.stringify(\n    assertions\n      .filter((assertion) => assertion.relation === \"different\")\n      .map((assertion) => [assertion.id, ...endpointTuple(assertion)])\n      .toSorted((left, right) =>\n        compareStrings(encodeTupleKey(left), encodeTupleKey(right)),\n      ),\n  );\n}\n\n/**\n * @internal Exported for deterministic verification. Structural (JSON)\n * encoding of a seed's liveness plus its sorted class member tuples —\n * injective even when ids contain the separator characters a joined string\n * would collide on.\n */\nexport function encodeClassFingerprint(\n  live: boolean,\n  members: readonly Readonly<{ kind: string; id: string }>[],\n): string {\n  return JSON.stringify([\n    live,\n    members\n      .map((member) => [member.kind, member.id] as const)\n      .toSorted(([leftKind, leftId], [rightKind, rightId]) =>\n        compareMergeKeys(\n          mergeKey(leftKind, leftId),\n          mergeKey(rightKind, rightId),\n        ),\n      ),\n  ]);\n}\n\n/** The complete truth an assertion id identifies, as a comparable string. */\nexport function assertionTruthKey(assertion: LedgerAssertion): string {\n  return JSON.stringify([\n    assertion.relation,\n    ...endpointTuple(assertion),\n    assertion.validFrom,\n    assertion.validTo ?? null,\n  ]);\n}\n\n/**\n * The immutable identity of a ledger row — everything but `validTo`. Two\n * captures of ONE row always agree on this key (retraction only sets\n * `validTo`), so it is the right comparator for \"is the target's row the same\n * assertion the branch retracted\": the branch's staged copy carries its own end\n * timestamp while the target's current row carries none, which makes the\n * complete {@link assertionTruthKey} unusable for that question.\n */\nexport function assertionIdentityKey(assertion: LedgerAssertion): string {\n  return JSON.stringify([\n    assertion.relation,\n    ...endpointTuple(assertion),\n    assertion.validFrom,\n  ]);\n}\n\n/**\n * One assertion id identifies ONE complete truth — the invariant the import\n * coordinator enforces with `IDENTITY_IMPORT_ID_CONFLICT` inside the commit.\n * Validated here at plan time instead: intra-plan (two branches staging one\n * id for different truths) and against every stored row for those ids —\n * ended rows included, exactly the set the importer compares. An exact match\n * is fine (the importer skips it as already applied).\n */\nexport function assertOneIdOneTruth(\n  planned: readonly IdentityTransferAssertion[],\n  storedById: ReadonlyMap<string, LedgerAssertion>,\n): void {\n  const plannedById = new Map<string, IdentityTransferAssertion>();\n  for (const assertion of planned) {\n    const previous = plannedById.get(assertion.id);\n    if (\n      previous !== undefined &&\n      assertionTruthKey(previous) !== assertionTruthKey(assertion)\n    ) {\n      throw new IdentityMergeConflictError(\n        \"One assertion id was staged for two different identity truths.\",\n        {\n          details: {\n            assertionId: assertion.id,\n            first: previous,\n            second: assertion,\n          },\n        },\n      );\n    }\n    plannedById.set(assertion.id, assertion);\n    const stored = storedById.get(assertion.id);\n    if (\n      stored !== undefined &&\n      assertionTruthKey(stored) !== assertionTruthKey(assertion)\n    ) {\n      throw new IdentityMergeConflictError(\n        \"A staged assertion id already identifies different truth in the target ledger.\",\n        { details: { assertionId: assertion.id, staged: assertion, stored } },\n      );\n    }\n  }\n}\n\n/**\n * In-transaction freshness of every planned assertion and retraction id,\n * shared by BOTH commit modes. The plan validated each id against the target's\n * ledger as of planning; a row committed (or ended) in the plan→commit window\n * can claim a planned id — with endpoints entirely outside the guarded member\n * universe — without moving the legacy base@V token, which fingerprints\n * CURRENT assertions only. A planned NEW assertion refuses when its id\n * identifies any different complete truth (ended rows included, exactly the\n * set the applier compares); a planned RETRACTION refuses when the CURRENT row\n * its id ends is no longer the truth the branch retracted.\n */\nexport async function assertPlannedIdentityIdsFresh<G extends GraphDef>(\n  target: Store<G>,\n  txBackend: TransactionBackend,\n  plan: Pick<IdentityPlanSlice, \"identityAssertions\" | \"identityRetractions\">,\n): Promise<void> {\n  const plannedIds = [\n    ...plan.identityAssertions.map((assertion) => assertion.id),\n    ...plan.identityRetractions.map((retraction) => retraction.id),\n  ];\n  if (plannedIds.length === 0) return;\n  const storedById = await storeRuntime(target).identityAssertionRowsByIds(\n    plannedIds,\n    txBackend,\n  );\n  for (const assertion of plan.identityAssertions) {\n    const stored = storedById.get(assertion.id);\n    if (\n      stored !== undefined &&\n      assertionTruthKey(stored) !== assertionTruthKey(assertion)\n    ) {\n      throw new BaseVersionMismatchError(\n        \"The merge validated its assertion ids as of planning, but a row identifying different truth under a planned id was committed before the commit transaction.\",\n        {\n          details: { assertionId: assertion.id },\n          suggestion:\n            \"Retry the merge — the plan is recomputed from current state. A persistent refusal means the branch's assertion id conflicts with target truth and needs manual resolution.\",\n        },\n      );\n    }\n  }\n  for (const retraction of plan.identityRetractions) {\n    const stored = storedById.get(retraction.id);\n    if (\n      stored !== undefined &&\n      stored.validTo === undefined &&\n      assertionIdentityKey(stored) !== assertionIdentityKey(retraction)\n    ) {\n      throw new BaseVersionMismatchError(\n        \"The merge validated each planned retraction against the target row its id identified at planning, but that row's truth changed before the commit transaction.\",\n        {\n          details: { assertionId: retraction.id },\n          suggestion:\n            \"Retry the merge — the plan is recomputed from current state.\",\n        },\n      );\n    }\n  }\n}\n\n/**\n * The identity classes a commit can move, as the `(kind, id)` seeds the\n * post-write assertion expands through the closure. Three sources, all minus\n * the plan's node deletions (a deleted identity carries no class, and seeding\n * one would ask the assertion to reason about a row the commit removed):\n *\n *  - both endpoints of every planned assertion — the classes the commit\n *    MERGES, and the pairs it constrains;\n *  - both endpoints of every planned retraction — the classes it SPLITS,\n *    where the closure repair must have landed;\n *  - under `sameIdAcrossKinds: \"fold\"`, every node identity the commit writes,\n *    at the kind it is written under (the retype cascade's kind when the\n *    ontology reconciled one). A written row folds with every live row sharing\n *    its id, so a node write alone can move a class. Under `\"ignore\"` it\n *    cannot: folding is off and a node write creates no assertion, so a\n *    written identity that no planned assertion names stays a singleton.\n */\nexport function affectedIdentityClassSeeds(\n  plan: IdentityPlanSlice,\n  profile: \"fold\" | \"ignore\" | undefined,\n): readonly Readonly<{ kind: string; id: string }>[] {\n  const seedsByKey = new Map<\n    MergeKey,\n    Readonly<{ kind: string; id: string }>\n  >();\n  const addSeed = (kind: string, id: string): void => {\n    const key = mergeKey(kind, id);\n    if (plan.nodeDeletions.has(key)) return;\n    seedsByKey.set(key, { kind, id });\n  };\n  for (const assertion of [\n    ...plan.identityAssertions,\n    ...plan.identityRetractions,\n  ]) {\n    addSeed(assertion.a.kind, assertion.a.id);\n    addSeed(assertion.b.kind, assertion.b.id);\n  }\n  if (profile === \"fold\") {\n    for (const entity of plan.canonicalEntities) {\n      const sourceKey = mergeKey(entity.kind, entity.canonicalId);\n      if (plan.nodeDeletions.has(sourceKey)) continue;\n      addSeed(plan.retypeMap.get(sourceKey) ?? entity.kind, entity.canonicalId);\n    }\n  }\n  return [...seedsByKey.values()];\n}\n\n/**\n * The correctness-bearing identity guard: after the commit's identity DML, the\n * applier re-derives the affected identity classes FROM THE WRITTEN STATE and\n * refuses a contradiction, inside the commit transaction. Every earlier\n * identity guard reasons about a simulated post-merge universe assembled from\n * reads taken before the writes; this one reads the database the merge is\n * about to leave behind, so it holds whatever the plan assumed and however the\n * target moved underneath it. A refusal aborts the transaction, so the merge\n * is never partially applied.\n *\n * Shared by BOTH commit modes through {@link applyMergePlan}, and raised\n * inside the identity-applier boundary so\n * {@link translateIdentityCommitError} gives it the same typed conflict\n * surface as the applier's own refusals.\n */\nexport async function assertMergedIdentityClassesConsistent<G extends GraphDef>(\n  target: Store<G>,\n  txBackend: TransactionBackend,\n  plan: IdentityPlanSlice,\n): Promise<void> {\n  await storeRuntime(target).assertIdentityClassesConsistentAtTarget(\n    txBackend,\n    affectedIdentityClassSeeds(plan, target.graph.identity?.sameIdAcrossKinds),\n  );\n}\n\n/**\n * Codes the identity service raises for ENVIRONMENT problems — a missing\n * profile, a non-atomic backend, an undersized bind budget. These are not\n * statements about identity truth, so they pass through untranslated; every\n * other identity refusal escaping the commit IS a truth conflict.\n */\nconst IDENTITY_ENVIRONMENT_CODES: ReadonlySet<string> = new Set([\n  \"IDENTITY_MERGE_REQUIRES_PROFILE\",\n  \"IDENTITY_REQUIRES_ATOMIC_BACKEND\",\n  \"IDENTITY_REQUIRES_STATEMENT_EXECUTION\",\n  \"IDENTITY_BIND_BUDGET_TOO_SMALL\",\n  // Environment/corruption statements — translating one into \"re-plan against\n  // the current target\" would be advice that can never succeed. The applier\n  // reaches the last two through the current different-ness probe (see\n  // `identity/separation`), which refuses rather than guessing when the derived\n  // separation relation is missing or disagrees with the ledger.\n  \"IDENTITY_NOT_ENABLED\",\n  \"IDENTITY_STORAGE_MISSING\",\n  \"IDENTITY_SCHEMA_CONTRADICTION\",\n  \"IDENTITY_IMPORT_REQUIRES_PROFILE\",\n]);\n\n/**\n * The identity code carried by an applier refusal, wherever the applier put\n * it: the top-level error code, a `details.code` field (the coordinator's\n * `ConfigurationError`s), or a per-assertion `details.issues[].code` (the\n * transfer validator's `ValidationError`s report per-row issues, so the code\n * never reaches the top level).\n */\nfunction identityRefusalCode(error: TypeGraphError): string | undefined {\n  const detailCode = error.details[\"code\"];\n  if (typeof detailCode === \"string\" && detailCode.startsWith(\"IDENTITY_\")) {\n    return detailCode;\n  }\n  if (error.code.startsWith(\"IDENTITY_\")) return error.code;\n  const issues = error.details[\"issues\"];\n  if (Array.isArray(issues)) {\n    for (const issue of issues) {\n      const code = (issue as Readonly<Record<string, unknown>>)[\"code\"];\n      if (typeof code === \"string\" && code.startsWith(\"IDENTITY_\")) {\n        return code;\n      }\n    }\n  }\n  return undefined;\n}\n\n/**\n * The commit-phase completeness backstop for identity invariants. The planner\n * SIMULATES the identity applier's rules to refuse illegal plans early and\n * typed — but a simulation can lag the applier, and an invariant it does not\n * (yet) mirror would surface as the generic merge wrapper around the applier's\n * refusal. Translating every refusal that escapes an identity-owned commit\n * boundary (the identity applier, plus the node-window guard that protects\n * open assertions) into the typed conflict error (cause preserved) gives NEW\n * invariants a typed surface by construction instead of by hand-built\n * plan-time twins.\n *\n * A {@link NodeNotFoundError} is translated only at the identity-applier call,\n * where it can mean just one thing — an assertion endpoint the plan validated\n * vanished. Node writes invoke this translator only for their explicit\n * identity-window refusal. Typed {@link MergeError}s (the guards' own refusals)\n * and non-identity failures pass through unchanged.\n *\n * @internal Exported for isolated verification of the translation contract.\n */\nexport function translateIdentityCommitError(error: unknown): unknown {\n  if (error instanceof MergeError) return error;\n  if (!(error instanceof TypeGraphError)) return error;\n  const identityCode = identityRefusalCode(error);\n  const identityRefusal =\n    error instanceof IdentityContradictionError ||\n    error instanceof NodeNotFoundError ||\n    (identityCode !== undefined &&\n      !IDENTITY_ENVIRONMENT_CODES.has(identityCode));\n  if (!identityRefusal) return error;\n  return new IdentityMergeConflictError(\n    `The identity applier refused the resolved plan inside the commit transaction — identity truth on the target is incompatible with the plan. Cause: ${describeCause(error)}`,\n    {\n      cause: error,\n      details: { ...(identityCode === undefined ? {} : { identityCode }) },\n      suggestion:\n        \"Retry once — the plan is recomputed from current state. If the refusal persists, the branches' identity truth conflicts with the target and needs manual resolution (change the branch's assertion, or resolve the target's truth first).\",\n    },\n  );\n}\n\n/**\n * Fold-peer TOCTOU guard: proves the identity state the plan-time simulation\n * validated still holds inside the commit transaction — direct peers,\n * per-seed class/liveness fingerprints, the negative ledger, and finally the\n * FULL simulation re-run on transaction reads (drift that leaves every\n * fingerprint unchanged, like a redundant `same(a, b)` that becomes decisive\n * once the plan removes the pair's bridge, can only be caught by\n * re-deriving legality itself). Drift is refused as the same typed replan\n * error the other window guards raise.\n */\nexport async function assertIdentityPeersStable<G extends GraphDef>(\n  target: Store<G>,\n  txBackend: TransactionBackend,\n  probe: IdentityPeerProbe | undefined,\n  plan: IdentityPlanSlice,\n): Promise<void> {\n  if (probe === undefined) return;\n  const live = (\n    await storeRuntime(target).liveNodesSharingIds(probe.ids, txBackend)\n  ).filter((peer) => !probe.plannedDeletions.has(mergeKey(peer.kind, peer.id)));\n  // Under \"fold\" ANY new same-id peer changes the classes the plan folded\n  // on; under \"ignore\" only a peer of a kind DISJOINT with a seed sharing\n  // its id changes legality (the create-time disjoint-id constraint) — a\n  // benign same-id row is an unrelated target advance.\n  const seedKindsById = new Map<string, Set<string>>();\n  for (const seed of probe.seeds) {\n    const kinds = seedKindsById.get(seed.id) ?? new Set<string>();\n    kinds.add(seed.kind);\n    seedKindsById.set(seed.id, kinds);\n  }\n  const appeared = live\n    .filter(\n      (peer) =>\n        probe.profile === \"fold\" ||\n        [...(seedKindsById.get(peer.id) ?? [])].some((kind) =>\n          target.registry.areDisjoint(peer.kind, kind),\n        ),\n    )\n    .map((peer) => mergeKey(peer.kind, peer.id))\n    .filter((key) => !probe.observed.has(key))\n    .sort((left, right) => compareMergeKeys(left, right));\n  if (appeared.length > 0) {\n    throw new BaseVersionMismatchError(\n      `mergeIncremental() simulated identity folding against the target's live same-id peers as of planning, but ${appeared.length} committed row(s) sharing a planned node's id appeared before the commit transaction. Committing the plan could fold nodes into classes the plan never validated.`,\n      { details: { appeared } },\n    );\n  }\n  // Class-transitive drift: a window row or assertion can change a seed's\n  // identity class through ANOTHER member without touching the seed's direct\n  // same-id peers — and a seed can DISAPPEAR without changing its\n  // self-coalesced class, so liveness is part of the fingerprint.\n  const { fingerprints: liveFingerprints, groups: liveGroups } =\n    await snapshotIdentityClasses(\n      target,\n      probe.seeds,\n      new Set(live.map((peer) => mergeKey(peer.kind, peer.id))),\n      probe.plannedDeletions,\n      txBackend,\n    );\n  const drifted = [...probe.classFingerprints]\n    .filter(([key, fingerprint]) => liveFingerprints.get(key) !== fingerprint)\n    .map(([key]) => key)\n    .sort((left, right) => compareStrings(left, right));\n  if (drifted.length > 0) {\n    throw new BaseVersionMismatchError(\n      `mergeIncremental() validated identity against the classes visible at planning, but the identity class of ${drifted.length} node(s) the plan folds on changed before the commit transaction. Committing the plan could contradict identity truth it never validated.`,\n      { details: { drifted } },\n    );\n  }\n  // Negative truth: a `different` assertion committed (or retracted) in the\n  // window changes plan legality without moving any class or peer.\n  const ledger = (\n    await relevantLedgerAssertions(target, probe.memberKeys, txBackend)\n  ).filter(\n    (assertion) =>\n      !probe.plannedDeletions.has(mergeKey(assertion.a.kind, assertion.a.id)) &&\n      !probe.plannedDeletions.has(mergeKey(assertion.b.kind, assertion.b.id)),\n  );\n  if (differentLedgerFingerprint(ledger) !== probe.differentFingerprint) {\n    throw new BaseVersionMismatchError(\n      \"mergeIncremental() validated identity against the `different` assertions visible at planning, but that ledger changed before the commit transaction. Committing the plan could contradict identity truth it never validated.\",\n      { details: {} },\n    );\n  }\n\n  // The decisive backstop: re-run the identity simulation on TRANSACTION\n  // reads. Every fingerprint above can survive a window write that still\n  // changes post-plan legality — the canonical example is a `same(a, b)`\n  // added while a and b are already transitively connected (no class or\n  // ledger-slice fingerprint moves) that becomes the surviving link once the\n  // plan removes their bridge and asserts them different.\n  try {\n    assertNoContradictoryIdentityClosure(\n      plan.identityAssertions,\n      plan.identityRetractions.map((retraction) => retraction.id),\n      ledger,\n      probe.plannedDeletions,\n      plan.canonicalOf,\n      plan.retypeMap,\n      {\n        sameIdAcrossKinds: probe.profile,\n        areDisjoint: (left, right) => target.registry.areDisjoint(left, right),\n      },\n      [...probe.seeds, ...liveGroups.flat()],\n    );\n  } catch (error) {\n    if (!(error instanceof IdentityMergeConflictError)) throw error;\n    throw new BaseVersionMismatchError(\n      \"mergeIncremental() validated identity as of planning, but identity truth committed before the commit transaction invalidates the plan. Re-plan against the current target.\",\n      { details: { conflict: error.message } },\n    );\n  }\n}\n","import { requireDefined } from \"../utils/presence\";\n/**\n * State-diff engine: compute the per-fork delta (new / modified / deleted nodes\n * and edges) of a working copy against the IMMUTABLE original base store.\n *\n * Why backend-level enumeration (not `Store.find()`): the collection API\n * silently hides soft-deleted rows, so a node deleted in a fork would be\n * invisible and the diff could never report a deletion. We therefore go through\n * the backend with `excludeDeleted: false` and read the raw `NodeRow`/`EdgeRow`.\n *\n * Row representation contract (verified against `NodeRow`/`EdgeRow`):\n *   - `props` is a JSON string (SQLite) or a driver-parsed object (Postgres\n *     jsonb) — every comparison routes it through `parseRowProps` before\n *     `canonicalizeProps`, never feeding a raw string to the serializer (that\n *     would key on incidental string-literal order, not canonical structure).\n *   - `deleted_at` is a field, `undefined` for live rows. Liveness is\n *     `row.deleted_at === undefined`.\n *\n * Enumeration ordering: both nodes AND edges use KEYSET pagination\n * (`orderBy: \"id\"` + `after` cursor) over the unique `id`, a TOTAL order, so\n * paging can neither skip nor duplicate a row even when many rows share a\n * `created_at`. (Edges previously had only offset paging over the non-unique\n * `created_at`, which could skip a boundary row under a reordering query plan.)\n *\n * Concurrency: P0 assumes quiesced (non-concurrent) forks per design §10.\n * Concurrent-write enumeration is a P1 concern.\n */\nimport {\n  canonicalizeProps,\n  edgeStateSignature,\n  parseRowProps,\n} from \"./canonical-props\";\nimport { assertionIdentityKey, assertionTruthKey } from \"./merge-identity\";\nimport { compareStrings, type MergeKey, mergeKey } from \"./node-key\";\nimport type {\n  EdgeId,\n  EntityKey,\n  GraphBackend,\n  GraphDef,\n  IdentityTransferAssertion,\n  LineageDelta,\n  NodeId,\n  NodeType,\n  Store,\n  TransactionBackend,\n} from \"./typegraph-internal\";\nimport {\n  batchPointReadVerdict,\n  canonicalizeDatabaseTimestamp,\n  getEdgeKinds,\n  getEdgeRowsByIds,\n  getNodeKinds,\n  getNodeRowsByIds,\n} from \"./typegraph-internal\";\nimport { storeBackend, storeRuntime } from \"./typegraph-internal\";\n\n/**\n * Local structural mirror of TypeGraph's internal `NodeRow`. 0.29.0 does NOT\n * re-export `NodeRow`/`EdgeRow` from any public entrypoint, but `GraphBackend`\n * (public) returns rows of exactly this shape from `findNodesByKind`, so the\n * runtime values are structurally assignable. Keep this local mirror until using\n * the backend row type directly buys enough clarity to justify the coupling.\n */\nexport type NodeRow = Readonly<{\n  graph_id: string;\n  kind: string;\n  id: string;\n  props: string | Readonly<Record<string, unknown>>;\n  version: number;\n  valid_from: string | undefined;\n  valid_to: string | undefined;\n  created_at: string;\n  updated_at: string;\n  deleted_at: string | undefined;\n}>;\n\n/** Local structural mirror of TypeGraph's internal `EdgeRow`. See {@link NodeRow}. */\nexport type EdgeRow = Readonly<{\n  graph_id: string;\n  id: string;\n  kind: string;\n  from_kind: string;\n  from_id: string;\n  to_kind: string;\n  to_id: string;\n  props: string | Readonly<Record<string, unknown>>;\n  valid_from: string | undefined;\n  valid_to: string | undefined;\n  created_at: string;\n  updated_at: string;\n  deleted_at: string | undefined;\n}>;\n\n/**\n * Page size for keyset/offset enumeration. Large enough to keep round-trips low\n * on demo-scale graphs; the algorithm is correct for any positive value.\n */\nconst ENUMERATION_PAGE_SIZE = 1000;\n\n/**\n * A node that exists in both base and fork but whose canonicalized props differ.\n * Carries the parsed fork props so downstream phases (staging, conflict) avoid\n * re-parsing.\n */\nexport type ModifiedNode = Readonly<{\n  id: NodeId<NodeType>;\n  kind: string;\n  baseProps: Readonly<Record<string, unknown>>;\n  forkProps: Readonly<Record<string, unknown>>;\n  row: NodeRow;\n}>;\n\n/** A node present and live only on one side of the diff. */\nexport type ChangedNode = Readonly<{\n  id: NodeId<NodeType>;\n  kind: string;\n  props: Readonly<Record<string, unknown>>;\n  row: NodeRow;\n}>;\n\n/** Identifier of a node that the fork removed (live in base, gone in fork). */\nexport type DeletedNode = Readonly<{\n  id: NodeId<NodeType>;\n  kind: string;\n  /**\n   * The instant the fork soft-deleted the node, read from its own row, or\n   * `undefined` when the fork carries no row at all (a HARD delete, which\n   * removes the row rather than tombstoning it).\n   *\n   * Soft and hard deletion leave different evidence behind, and\n   * {@link RetractionCause} needs to tell them apart: only a hard delete\n   * removes the assertion rows outright, so only a hard delete can explain a\n   * retraction with no surviving fork row.\n   */\n  deletedAt: string | undefined;\n}>;\n\n/** A node reference naming the endpoint whose deletion cascaded. */\ntype CascadeCauseNode = Readonly<{ kind: string; id: string }>;\n\n/**\n * Why an assertion stopped being current in the fork.\n *\n * `cascade` is READ, not guessed: a node soft-delete ends every open assertion\n * touching that node and stamps the deleted node's `(kind, id)` onto each row\n * it ends (see `detachIdentityForNode`), so the row states its own cause. An\n * assertion the fork retracted explicitly carries no stamp — including the\n * same-branch retract-then-delete sequence, where the explicit retraction\n * closed the row before the delete ran, so the cascade never touched it, no\n * matter how close together the two acts fell.\n *\n * ONE case is genuinely undecidable and resolves to `cascade`, the conservative\n * side (a dropped ending keeps identity truth; a wrongly kept one destroys it):\n * a HARD delete physically removes every assertion row touching the node,\n * taking the stamp with it along with any earlier explicit retraction of the\n * same row — a hard delete is then the only thing that can have produced the\n * retraction.\n */\nexport type RetractionCause =\n  | Readonly<{ kind: \"explicit\" }>\n  | Readonly<{ kind: \"cascade\"; deletedNode: CascadeCauseNode }>;\n\n/** An assertion the fork stopped asserting, with the cause of its ending. */\ntype RetractedAssertion = Readonly<{\n  assertion: IdentityTransferAssertion;\n  cause: RetractionCause;\n}>;\n\n/** The `explicit` cause — a single shared value; the variant carries no data. */\nconst EXPLICIT_RETRACTION: RetractionCause = { kind: \"explicit\" };\n\n/** An edge present and live only on one side of the diff. */\nexport type ChangedEdge = Readonly<{\n  id: EdgeId;\n  kind: string;\n  fromId: NodeId<NodeType>;\n  toId: NodeId<NodeType>;\n  fromKind: string;\n  toKind: string;\n  props: Readonly<Record<string, unknown>>;\n  row: EdgeRow;\n}>;\n\n/** An edge present in both base and fork but whose canonicalized props differ. */\nexport type ModifiedEdge = Readonly<{\n  id: EdgeId;\n  kind: string;\n  fromId: NodeId<NodeType>;\n  toId: NodeId<NodeType>;\n  fromKind: string;\n  toKind: string;\n  baseProps: Readonly<Record<string, unknown>>;\n  forkProps: Readonly<Record<string, unknown>>;\n  row: EdgeRow;\n}>;\n\n/** Identifier of an edge the fork removed (live in base, gone in fork). */\nexport type DeletedEdge = Readonly<{\n  id: EdgeId;\n  kind: string;\n}>;\n\n/**\n * A row's valid-time window, normalized to canonical UTC instants.\n *\n * The raw `valid_from` / `valid_to` columns are TEXT whose formatting differs\n * per driver (postgres-js hands back `timestamptz` as its own raw rendering),\n * so comparing or ordering the stored strings would resolve differently on\n * SQLite and PostgreSQL. Every window the diff reports is canonicalized here\n * once, and every downstream comparison operates on this shape.\n */\nexport type ValidWindow = Readonly<{\n  validFrom: string | undefined;\n  validTo: string | undefined;\n}>;\n\n/**\n * An inherited node — live in BOTH base and fork — whose valid-time window the\n * fork changed. Independent of {@link ModifiedNode}: modification detection\n * compares props only, so a row can appear in one bucket, the other, or both.\n *\n * Keeping the two buckets separate is what makes an end-of-validity behave as a\n * sibling of deletion rather than as a modification: a window-only change never\n * enters delete/modify resolution, so a branch that ends a row another branch\n * deleted raises no conflict — the deletion simply absorbs the weaker claim.\n */\nexport type WindowedNode = Readonly<{\n  id: NodeId<NodeType>;\n  kind: string;\n  base: ValidWindow;\n  fork: ValidWindow;\n}>;\n\n/**\n * The edge analogue of {@link WindowedNode}. Carries the edge's endpoints and\n * parsed props too, because an inherited edge whose ONLY change is its window is\n * not otherwise staged — the repoint phase needs the full record to carry the\n * ending through to the commit.\n *\n * `baseProps` is the same record {@link ModifiedEdge} carries, and for the same\n * consumer: the repoint fold judges each contributor's property values against\n * its own base, so an untouched value never enters the union as an authored claim\n * (issue #408). A window-only fork's `props` happen to equal its `baseProps`,\n * which is exactly what makes such a copy contribute nothing — but that equality\n * is a fact about the fork, not something the fold should have to assume.\n */\nexport type WindowedEdge = Readonly<{\n  id: EdgeId;\n  kind: string;\n  fromId: NodeId<NodeType>;\n  toId: NodeId<NodeType>;\n  fromKind: string;\n  toKind: string;\n  props: Readonly<Record<string, unknown>>;\n  baseProps: Readonly<Record<string, unknown>>;\n  base: ValidWindow;\n  fork: ValidWindow;\n}>;\n\n/** Reads a row's window as canonical instants. */\nfunction validWindowOf(\n  row: Readonly<{\n    valid_from: string | undefined;\n    valid_to: string | undefined;\n  }>,\n): ValidWindow {\n  return {\n    validFrom: canonicalizeDatabaseTimestamp(row.valid_from),\n    validTo: canonicalizeDatabaseTimestamp(row.valid_to),\n  };\n}\n\n/** True when two canonicalized windows differ in either endpoint. */\nfunction windowsDiffer(left: ValidWindow, right: ValidWindow): boolean {\n  return left.validFrom !== right.validFrom || left.validTo !== right.validTo;\n}\n\n/**\n * The complete delta of a fork against the original base store.\n */\nexport type StateDiff = Readonly<{\n  nodes: Readonly<{\n    new: readonly ChangedNode[];\n    modified: readonly ModifiedNode[];\n    deleted: readonly DeletedNode[];\n    /** Inherited nodes whose valid-time window the fork changed. */\n    windowed: readonly WindowedNode[];\n  }>;\n  edges: Readonly<{\n    new: readonly ChangedEdge[];\n    modified: readonly ModifiedEdge[];\n    deleted: readonly DeletedEdge[];\n    /** Inherited edges whose valid-time window the fork changed. */\n    windowed: readonly WindowedEdge[];\n  }>;\n  /**\n   * Identity-ledger delta: assertions current in the fork but not the base\n   * (`new`), and assertions current in the base but no longer in the fork\n   * (`retracted`). An id current on BOTH sides with DIFFERENT complete truth\n   * (a hard-delete/recreate replacement) appears in both lists. Entries carry\n   * the ledger's own {@link IdentityTransferAssertion} shape — the same\n   * records the merge commit hands back to the identity import — so the diff\n   * never re-declares (and can never drift from) the assertion contract.\n   *\n   * Each retraction additionally carries its {@link RetractionCause}, so the\n   * merge planner can tie a cascade ending's fate to the deletion that caused\n   * it instead of inferring intent from branch-level provenance.\n   */\n  identity: Readonly<{\n    new: readonly IdentityTransferAssertion[];\n    retracted: readonly RetractedAssertion[];\n  }>;\n  /**\n   * `(kind, id) -> version` for every fork-store node observed during this diff\n   * (live and soft-deleted). Captured from the same enumeration the diff reads,\n   * so it is the fork's exact observed state — the incremental merge uses the\n   * target branch's map as the plan-time baseline for its commit-time\n   * lost-update guard (see assertInheritedTargetUnchanged in merge.ts).\n   */\n  forkNodeVersions: ReadonlyMap<MergeKey, number>;\n  /**\n   * `(kind, id) -> {@link edgeStateSignature}` for every fork-store edge observed\n   * during this diff (live and soft-deleted). The edge-half analogue of\n   * {@link forkNodeVersions}: edges carry no `version` column, so the guard\n   * fingerprints their mergeable content (endpoints, liveness, canonical props)\n   * instead. The incremental merge uses the target branch's map as the plan-time\n   * baseline for the commit-time lost-update guard.\n   */\n  forkEdgeSignatures: ReadonlyMap<MergeKey, string>;\n}>;\n\n/**\n * Enumerates EVERY node of `kind` for `graphId` (live and soft-deleted) via\n * keyset pagination on `id`. Returns rows ascending in the BACKEND's own id\n * ordering — byte order on SQLite/PGlite, the database collation on server\n * Postgres. That order is deterministic and pagination-consistent (the cursor\n * comparison uses the same collation as ORDER BY), but it is NOT guaranteed to\n * equal JS code-unit order for mixed-case ids; consumers needing a canonical\n * cross-backend order sort in JS (as `stateDiff` and the base@V fingerprint\n * do).\n */\nexport async function enumerateAllNodes(\n  backend: GraphBackend | TransactionBackend,\n  graphId: string,\n  kind: string,\n): Promise<readonly NodeRow[]> {\n  const collected: NodeRow[] = [];\n  let after: string | undefined;\n  for (;;) {\n    const page: readonly NodeRow[] = await backend.findNodesByKind({\n      graphId,\n      kind,\n      excludeDeleted: false,\n      orderBy: \"id\",\n      limit: ENUMERATION_PAGE_SIZE,\n      ...(after === undefined ? {} : { after }),\n    });\n    for (const row of page) {\n      collected.push(row);\n    }\n    if (page.length < ENUMERATION_PAGE_SIZE) {\n      break;\n    }\n    after = requireDefined(page.at(-1)).id;\n  }\n  return collected;\n}\n\n/**\n * Enumerates EVERY edge of `kind` for `graphId` (live and soft-deleted) via\n * keyset pagination on the unique `id` (a TOTAL order), so paging can neither\n * skip nor duplicate a row regardless of how many edges share a `created_at`.\n * Returns rows ascending in the backend's own id ordering (see\n * {@link enumerateAllNodes} for the collation caveat). Mirrors\n * {@link enumerateAllNodes}.\n */\nexport async function enumerateAllEdges(\n  backend: GraphBackend | TransactionBackend,\n  graphId: string,\n  kind: string,\n): Promise<readonly EdgeRow[]> {\n  const collected: EdgeRow[] = [];\n  let after: string | undefined;\n  for (;;) {\n    const page: readonly EdgeRow[] = await backend.findEdgesByKind({\n      graphId,\n      kind,\n      excludeDeleted: false,\n      orderBy: \"id\",\n      limit: ENUMERATION_PAGE_SIZE,\n      ...(after === undefined ? {} : { after }),\n    });\n    for (const row of page) {\n      collected.push(row);\n    }\n    if (page.length < ENUMERATION_PAGE_SIZE) {\n      break;\n    }\n    after = requireDefined(page.at(-1)).id;\n  }\n  return collected;\n}\n\n/**\n * The ids of one `kind`'s entries in a lineage delta's mixed-kind key list —\n * the per-kind slice {@link fetchNodesByIds}/{@link fetchEdgesByIds} fetch,\n * mirroring how {@link enumerateAllNodes}/{@link enumerateAllEdges} are\n * themselves scoped to one kind at a time.\n */\nfunction idsForKind(keys: readonly EntityKey[], kind: string): string[] {\n  return keys.filter((key) => key.kind === kind).map((key) => key.id);\n}\n\n/**\n * Narrows an already-fetched row set down to the given ids — used when a\n * FULL enumeration was already required for {@link StateDiff.forkNodeVersions}\n * / {@link StateDiff.forkEdgeSignatures} (`captureForkState`), so pruning the\n * fork side for diffing costs a filter, not a second read.\n */\nfunction filterRowsByIds<T extends Readonly<{ id: string }>>(\n  rows: readonly T[],\n  ids: readonly string[],\n): readonly T[] {\n  if (ids.length === 0) return [];\n  const idSet = new Set(ids);\n  return rows.filter((row) => idSet.has(row.id));\n}\n\n/**\n * Fetches exactly the requested node ids for `kind` — live and tombstoned\n * alike, since {@link getNodeRowsByIds}'s underlying `getNodes`/`getNode`\n * reads carry no `deleted_at` filter, matching {@link enumerateAllNodes}'s\n * own `excludeDeleted: false` contract. The pruned counterpart to\n * {@link enumerateAllNodes}, used only when a caller supplies a `pruneTo`\n * delta to {@link diffAgainstBase}.\n */\nasync function fetchNodesByIds(\n  backend: GraphBackend,\n  graphId: string,\n  kind: string,\n  ids: readonly string[],\n): Promise<readonly NodeRow[]> {\n  if (ids.length === 0) return [];\n  const rowsById = await getNodeRowsByIds(\n    backend,\n    batchPointReadVerdict(backend),\n    graphId,\n    kind,\n    ids,\n  );\n  return [...rowsById.values()];\n}\n\n/**\n * The edge analogue of {@link fetchNodesByIds}, with one difference:\n * `getEdgeRowsByIds` fetches by id ALONE — the edge backend surface\n * (`getEdge`/`getEdges`) carries no `kind` parameter, unlike the node path,\n * where `kind` is threaded straight into the query. A row is therefore\n * filtered to `kind` here, in this function, rather than at the backend: an\n * id a fork hard-deleted under one edge kind and later recreated under a\n * different kind resolves, by id alone, to the CURRENT row's kind, and that\n * row must be excluded from every OTHER kind's pruned fetch — exactly as\n * {@link enumerateAllEdges}'s own `findEdgesByKind` call already excludes it\n * by construction.\n */\nasync function fetchEdgesByIds(\n  backend: GraphBackend,\n  graphId: string,\n  kind: string,\n  ids: readonly string[],\n): Promise<readonly EdgeRow[]> {\n  if (ids.length === 0) return [];\n  const rowsById = await getEdgeRowsByIds(\n    backend,\n    batchPointReadVerdict(backend),\n    graphId,\n    ids,\n  );\n  return [...rowsById.values()].filter((row) => row.kind === kind);\n}\n\n/** True when the row is live (not soft-deleted). */\nfunction isLive(row: Readonly<{ deleted_at: string | undefined }>): boolean {\n  return row.deleted_at === undefined;\n}\n\n/** Indexes rows by id for O(1) base-vs-fork lookup. */\nfunction indexById<T extends Readonly<{ id: string }>>(\n  rows: readonly T[],\n): ReadonlyMap<string, T> {\n  const index = new Map<string, T>();\n  for (const row of rows) {\n    index.set(row.id, row);\n  }\n  return index;\n}\n\n/**\n * Diffs the node sets of one kind. `new` = absent-in-base, live-in-fork;\n * `deleted` = live-in-base, absent-or-soft-deleted-in-fork; `modified` =\n * live in both with differing canonicalized props.\n */\nfunction diffNodeKind(\n  kind: string,\n  baseRows: readonly NodeRow[],\n  forkRows: readonly NodeRow[],\n): Readonly<{\n  new: ChangedNode[];\n  modified: ModifiedNode[];\n  deleted: DeletedNode[];\n  windowed: WindowedNode[];\n}> {\n  const baseIndex = indexById(baseRows);\n  const forkIndex = indexById(forkRows);\n\n  const created: ChangedNode[] = [];\n  const modified: ModifiedNode[] = [];\n  const deleted: DeletedNode[] = [];\n  const windowed: WindowedNode[] = [];\n\n  for (const forkRow of forkRows) {\n    if (!isLive(forkRow)) {\n      continue;\n    }\n    const baseRow = baseIndex.get(forkRow.id);\n    const forkProps = parseRowProps(forkRow.props);\n    if (baseRow === undefined || !isLive(baseRow)) {\n      created.push({\n        id: forkRow.id as NodeId<NodeType>,\n        kind,\n        props: forkProps,\n        row: forkRow,\n      });\n      continue;\n    }\n    const baseProps = parseRowProps(baseRow.props);\n    if (canonicalizeProps(baseProps) !== canonicalizeProps(forkProps)) {\n      modified.push({\n        id: forkRow.id as NodeId<NodeType>,\n        kind,\n        baseProps,\n        forkProps,\n        row: forkRow,\n      });\n    }\n    const baseWindow = validWindowOf(baseRow);\n    const forkWindow = validWindowOf(forkRow);\n    if (windowsDiffer(baseWindow, forkWindow)) {\n      windowed.push({\n        id: forkRow.id as NodeId<NodeType>,\n        kind,\n        base: baseWindow,\n        fork: forkWindow,\n      });\n    }\n  }\n\n  for (const baseRow of baseRows) {\n    if (!isLive(baseRow)) {\n      continue;\n    }\n    const forkRow = forkIndex.get(baseRow.id);\n    if (forkRow === undefined || !isLive(forkRow)) {\n      deleted.push({\n        id: baseRow.id as NodeId<NodeType>,\n        kind,\n        deletedAt:\n          forkRow === undefined ? undefined : (\n            canonicalizeDatabaseTimestamp(forkRow.deleted_at)\n          ),\n      });\n    }\n  }\n\n  return { new: created, modified, deleted, windowed };\n}\n\n/**\n * Diffs the edge sets of one kind. Same liveness/modification rules as nodes,\n * carrying endpoint ids/kinds for the downstream repoint phase.\n */\nfunction diffEdgeKind(\n  kind: string,\n  baseRows: readonly EdgeRow[],\n  forkRows: readonly EdgeRow[],\n): Readonly<{\n  new: ChangedEdge[];\n  modified: ModifiedEdge[];\n  deleted: DeletedEdge[];\n  windowed: WindowedEdge[];\n}> {\n  const baseIndex = indexById(baseRows);\n  const forkIndex = indexById(forkRows);\n\n  const created: ChangedEdge[] = [];\n  const modified: ModifiedEdge[] = [];\n  const deleted: DeletedEdge[] = [];\n  const windowed: WindowedEdge[] = [];\n\n  for (const forkRow of forkRows) {\n    if (!isLive(forkRow)) {\n      continue;\n    }\n    const baseRow = baseIndex.get(forkRow.id);\n    const forkProps = parseRowProps(forkRow.props);\n    if (baseRow === undefined || !isLive(baseRow)) {\n      created.push({\n        id: forkRow.id as EdgeId,\n        kind,\n        fromId: forkRow.from_id as NodeId<NodeType>,\n        toId: forkRow.to_id as NodeId<NodeType>,\n        fromKind: forkRow.from_kind,\n        toKind: forkRow.to_kind,\n        props: forkProps,\n        row: forkRow,\n      });\n      continue;\n    }\n    const baseProps = parseRowProps(baseRow.props);\n    if (canonicalizeProps(baseProps) !== canonicalizeProps(forkProps)) {\n      modified.push({\n        id: forkRow.id as EdgeId,\n        kind,\n        fromId: forkRow.from_id as NodeId<NodeType>,\n        toId: forkRow.to_id as NodeId<NodeType>,\n        fromKind: forkRow.from_kind,\n        toKind: forkRow.to_kind,\n        baseProps,\n        forkProps,\n        row: forkRow,\n      });\n    }\n    const baseWindow = validWindowOf(baseRow);\n    const forkWindow = validWindowOf(forkRow);\n    if (windowsDiffer(baseWindow, forkWindow)) {\n      windowed.push({\n        id: forkRow.id as EdgeId,\n        kind,\n        fromId: forkRow.from_id as NodeId<NodeType>,\n        toId: forkRow.to_id as NodeId<NodeType>,\n        fromKind: forkRow.from_kind,\n        toKind: forkRow.to_kind,\n        props: forkProps,\n        baseProps,\n        base: baseWindow,\n        fork: forkWindow,\n      });\n    }\n  }\n\n  for (const baseRow of baseRows) {\n    if (!isLive(baseRow)) {\n      continue;\n    }\n    const forkRow = forkIndex.get(baseRow.id);\n    if (forkRow === undefined || !isLive(forkRow)) {\n      deleted.push({ id: baseRow.id as EdgeId, kind });\n    }\n  }\n\n  return { new: created, modified, deleted, windowed };\n}\n\n/**\n * Classifies ONE retracted assertion against this fork's node deletions.\n *\n * The rule is the one documented on {@link RetractionCause}:\n *\n *   - the fork's row carries an `endedBy` stamp naming a node this fork\n *     deleted — that deletion's cascade ended it, `cascade`;\n *   - the fork has NO row for the id, and an endpoint was HARD-deleted (the\n *     only deletion that removes assertion rows) — nothing else can have ended\n *     it, `cascade`. Evaluated endpoint-first in `(a, b)` order so a retraction\n *     whose both endpoints were hard-deleted names a deterministic cause;\n *   - anything else the fork did to the assertion was its own act, `explicit`.\n *\n * A stamp naming a node the fork later RESURRECTED is deliberately `explicit`:\n * the merge ties a cascade's fate to a staged deletion, and this fork staged\n * none for that node, so its ending stands on its own.\n *\n * @param forkAssertion The fork's own row for this id, or `undefined` when the\n *   fork has no row for it at all (hard-deleted, or replaced under the same id).\n */\nfunction classifyRetraction(\n  assertion: IdentityTransferAssertion,\n  deletedByKey: ReadonlyMap<MergeKey, DeletedNode>,\n  forkAssertion: IdentityTransferAssertion | undefined,\n): RetractionCause {\n  if (forkAssertion !== undefined) {\n    const stamp = forkAssertion.endedBy;\n    if (\n      stamp !== undefined &&\n      deletedByKey.has(mergeKey(stamp.kind, stamp.id))\n    ) {\n      return { kind: \"cascade\", deletedNode: { ...stamp } };\n    }\n    return EXPLICIT_RETRACTION;\n  }\n  for (const endpoint of [assertion.a, assertion.b]) {\n    const deletion = deletedByKey.get(mergeKey(endpoint.kind, endpoint.id));\n    if (deletion !== undefined && deletion.deletedAt === undefined) {\n      return {\n        kind: \"cascade\",\n        deletedNode: { kind: deletion.kind, id: deletion.id },\n      };\n    }\n  }\n  return EXPLICIT_RETRACTION;\n}\n\n/**\n * Classifies every retraction in one fork.\n *\n * The fork's archival row owns the authored retraction boundary. Preserve that\n * complete ended truth in the plan whenever the row still identifies the base\n * assertion; a hard delete can remove the row entirely, in which case the node\n * deletion itself owns the commit-time cascade.\n */\nfunction classifyRetractions(\n  retracted: readonly IdentityTransferAssertion[],\n  deletedNodes: readonly DeletedNode[],\n  forkRowsById: ReadonlyMap<string, IdentityTransferAssertion>,\n): readonly RetractedAssertion[] {\n  if (retracted.length === 0) return [];\n  const deletedByKey = new Map<MergeKey, DeletedNode>(\n    deletedNodes.map((deletion) => [\n      mergeKey(deletion.kind, deletion.id),\n      deletion,\n    ]),\n  );\n  return retracted.map((assertion) => {\n    const forkAssertion = forkRowsById.get(assertion.id);\n    const endedAssertion =\n      (\n        forkAssertion?.validTo !== undefined &&\n        assertionIdentityKey(forkAssertion) === assertionIdentityKey(assertion)\n      ) ?\n        forkAssertion\n      : assertion;\n    return {\n      assertion: endedAssertion,\n      cause: classifyRetraction(assertion, deletedByKey, forkAssertion),\n    };\n  });\n}\n\n/** Stable id-ascending comparator over any `{ id: string }`. */\nfunction byId<T extends Readonly<{ id: string }>>(left: T, right: T): number {\n  return compareStrings(left.id, right.id);\n}\n\n/**\n * Computes the full {@link StateDiff} of `forkStore` against `baseStore`.\n *\n * Both stores MUST share the same graph definition (the fork is a clone of the\n * base). The diff is keyed by id and sorted by `(kind, id)` so its shape is a\n * pure function of the stores' content, independent of enumeration order. No\n * branch tag is attached here — provenance tagging happens in T7 (staging).\n *\n * @param captureForkState Whether to populate {@link StateDiff.forkNodeVersions}\n *   / {@link StateDiff.forkEdgeSignatures}. `stageBranches` only ever keeps these\n *   maps for the one branch matching `captureTargetStateFor`, and computing the\n *   edge signatures (canonicalizing props + stringifying every edge) is real\n *   work — so callers that don't need them for this branch can skip it. Defaults\n *   to `true` so direct callers (e.g. tests) get the full diff without having to\n *   know this parameter exists.\n * @param pruneTo A lineage delta bounding which rows changed on EITHER side\n *   since this branch forked (see `staging.ts`'s `stageBranches`, which\n *   computes the union of the fork's and the base's own `changesSince`). When\n *   it is `{ kind: \"keys\" }`, both sides are read by ID SET instead of full\n *   kind enumeration — a key absent from the delta is guaranteed identical on\n *   both sides (see the property test asserting this), so restricting reads\n *   to the union is lossless. `undefined` or `{ kind: \"unbounded\" }` runs the\n *   full enumeration, exactly as when this parameter is omitted. When\n *   `captureForkState` is also true, the fork side is still enumerated IN\n *   FULL for {@link StateDiff.forkNodeVersions} / {@link StateDiff.forkEdgeSignatures}\n *   (the lost-update guard needs the whole store); pruning then narrows only\n *   which of those already-fetched rows are diffed, at no extra read.\n */\nexport async function diffAgainstBase<G extends GraphDef>(\n  baseStore: Store<G>,\n  forkStore: Store<G>,\n  captureForkState = true,\n  pruneTo?: LineageDelta,\n): Promise<StateDiff> {\n  const prunedKeys = pruneTo?.kind === \"keys\" ? pruneTo : undefined;\n  const graph = baseStore.graph;\n  const nodeKinds = getNodeKinds(graph);\n  const edgeKinds = getEdgeKinds(graph);\n  const [baseIdentity, forkIdentity] = await Promise.all([\n    storeRuntime(baseStore).readCurrentIdentityAssertions(\"archival\"),\n    storeRuntime(forkStore).readCurrentIdentityAssertions(\"archival\"),\n  ]);\n  const baseIdentityById = new Map(\n    baseIdentity.map((assertion) => [assertion.id, assertion]),\n  );\n  const forkIdentityById = new Map(\n    forkIdentity.map((assertion) => [assertion.id, assertion]),\n  );\n\n  const newNodes: ChangedNode[] = [];\n  const modifiedNodes: ModifiedNode[] = [];\n  const deletedNodes: DeletedNode[] = [];\n  const windowedNodes: WindowedNode[] = [];\n  // Version snapshot of the fork store as observed by THIS diff's enumeration\n  // (the same read the plan resolves against), keyed by merge identity.\n  const forkNodeVersions = new Map<MergeKey, number>();\n\n  for (const kind of nodeKinds) {\n    const nodeIds =\n      prunedKeys === undefined ? [] : idsForKind(prunedKeys.nodes, kind);\n    const baseRows =\n      prunedKeys === undefined ?\n        await enumerateAllNodes(\n          storeBackend(baseStore),\n          baseStore.graphId,\n          kind,\n        )\n      : await fetchNodesByIds(\n          storeBackend(baseStore),\n          baseStore.graphId,\n          kind,\n          nodeIds,\n        );\n    const forkRowsFetched =\n      captureForkState || prunedKeys === undefined ?\n        await enumerateAllNodes(\n          storeBackend(forkStore),\n          forkStore.graphId,\n          kind,\n        )\n      : await fetchNodesByIds(\n          storeBackend(forkStore),\n          forkStore.graphId,\n          kind,\n          nodeIds,\n        );\n    if (captureForkState) {\n      for (const row of forkRowsFetched) {\n        forkNodeVersions.set(mergeKey(kind, row.id), row.version);\n      }\n    }\n    // When a full fetch above was forced by `captureForkState` while pruning\n    // is active, the rows fed to `diffNodeKind` are narrowed to the pruned\n    // set here — no second read, just a filter over what was already fetched.\n    const forkRows =\n      prunedKeys === undefined || !captureForkState ?\n        forkRowsFetched\n      : filterRowsByIds(forkRowsFetched, nodeIds);\n    const delta = diffNodeKind(kind, baseRows, forkRows);\n    for (const entry of delta.new) {\n      newNodes.push(entry);\n    }\n    for (const entry of delta.modified) {\n      modifiedNodes.push(entry);\n    }\n    for (const entry of delta.deleted) {\n      deletedNodes.push(entry);\n    }\n    for (const entry of delta.windowed) {\n      windowedNodes.push(entry);\n    }\n  }\n\n  const newEdges: ChangedEdge[] = [];\n  const modifiedEdges: ModifiedEdge[] = [];\n  const deletedEdges: DeletedEdge[] = [];\n  const windowedEdges: WindowedEdge[] = [];\n  // Content fingerprint of the fork store's edges as observed by THIS diff's\n  // enumeration — the edge-half baseline for the commit-time lost-update guard\n  // (edges have no version, so we key on mergeable content instead).\n  const forkEdgeSignatures = new Map<MergeKey, string>();\n\n  for (const kind of edgeKinds) {\n    const edgeIds =\n      prunedKeys === undefined ? [] : idsForKind(prunedKeys.edges, kind);\n    const baseRows =\n      prunedKeys === undefined ?\n        await enumerateAllEdges(\n          storeBackend(baseStore),\n          baseStore.graphId,\n          kind,\n        )\n      : await fetchEdgesByIds(\n          storeBackend(baseStore),\n          baseStore.graphId,\n          kind,\n          edgeIds,\n        );\n    const forkRowsFetched =\n      captureForkState || prunedKeys === undefined ?\n        await enumerateAllEdges(\n          storeBackend(forkStore),\n          forkStore.graphId,\n          kind,\n        )\n      : await fetchEdgesByIds(\n          storeBackend(forkStore),\n          forkStore.graphId,\n          kind,\n          edgeIds,\n        );\n    const forkRows =\n      prunedKeys === undefined || !captureForkState ?\n        forkRowsFetched\n      : filterRowsByIds(forkRowsFetched, edgeIds);\n    if (captureForkState) {\n      for (const row of forkRowsFetched) {\n        forkEdgeSignatures.set(\n          mergeKey(kind, row.id),\n          edgeStateSignature({\n            fromKind: row.from_kind,\n            fromId: row.from_id,\n            toKind: row.to_kind,\n            toId: row.to_id,\n            live: isLive(row),\n            props: parseRowProps(row.props),\n          }),\n        );\n      }\n    }\n    const delta = diffEdgeKind(kind, baseRows, forkRows);\n    for (const entry of delta.new) {\n      newEdges.push(entry);\n    }\n    for (const entry of delta.modified) {\n      modifiedEdges.push(entry);\n    }\n    for (const entry of delta.deleted) {\n      deletedEdges.push(entry);\n    }\n    for (const entry of delta.windowed) {\n      windowedEdges.push(entry);\n    }\n  }\n\n  // Ids present on BOTH sides are compared by COMPLETE truth, not presence: a\n  // fork can hard-delete an assertion's endpoint (physically removing the row),\n  // recreate it, and legally import the same id for different truth. Presence-\n  // only comparison would diff that replacement as empty and the merge would\n  // silently keep the base truth. A shared id with changed truth surfaces as\n  // BOTH retracted (the base row) and new (the fork row), so planning sees the\n  // replacement and can refuse unsupported id reuse as a typed conflict.\n  const retractedAssertions = baseIdentity\n    .filter((assertion) => {\n      const fork = forkIdentityById.get(assertion.id);\n      return (\n        fork === undefined ||\n        assertionTruthKey(fork) !== assertionTruthKey(assertion)\n      );\n    })\n    .toSorted((left, right) => compareStrings(left.id, right.id));\n  const classifiedRetractions = classifyRetractions(\n    retractedAssertions,\n    deletedNodes,\n    forkIdentityById,\n  );\n\n  return {\n    nodes: {\n      new: newNodes.sort((left, right) => byId(left, right)),\n      modified: modifiedNodes.sort((left, right) => byId(left, right)),\n      deleted: deletedNodes.sort((left, right) => byId(left, right)),\n      windowed: windowedNodes.sort((left, right) => byId(left, right)),\n    },\n    edges: {\n      new: newEdges.sort((left, right) => byId(left, right)),\n      modified: modifiedEdges.sort((left, right) => byId(left, right)),\n      deleted: deletedEdges.sort((left, right) => byId(left, right)),\n      windowed: windowedEdges.sort((left, right) => byId(left, right)),\n    },\n    identity: {\n      // Ids present on BOTH sides are compared by COMPLETE truth, not\n      // presence: a fork can hard-delete an assertion's endpoint (physically\n      // removing the row), recreate it, and legally import the same id for\n      // different truth. Presence-only comparison would diff that replacement\n      // as empty and the merge would silently keep the base truth. A shared\n      // id with changed truth surfaces as BOTH retracted (the base row) and\n      // new (the fork row), so planning sees the replacement and can refuse\n      // unsupported id reuse as a typed conflict.\n      new: forkIdentity\n        .filter((assertion) => {\n          const base = baseIdentityById.get(assertion.id);\n          return (\n            base === undefined ||\n            (assertionIdentityKey(base) !== assertionIdentityKey(assertion) &&\n              assertionTruthKey(base) !== assertionTruthKey(assertion))\n          );\n        })\n        .toSorted((left, right) => compareStrings(left.id, right.id)),\n      retracted: classifiedRetractions,\n    },\n    forkNodeVersions,\n    forkEdgeSignatures,\n  };\n}\n","/**\n * Core type model for the graph-merge primitive.\n *\n * Finalized against TypeGraph's real generic machinery: the design's illustrative\n * `Node<G, K>` / `NodeId<NodeKinds<G>>` collapse onto TypeGraph's public\n * `Node` / `Edge` / `NodeId<NodeType>` / `EdgeId` (which are themselves branded\n * over `NodeType` / `EdgeType`). The merge surface is parameterized over\n * `G extends GraphDef` so `Store<G>` and `GraphBranch<G>` thread the caller's\n * concrete graph definition end-to-end.\n *\n * This module is pure type declarations plus the two branding helpers — no\n * runtime merge logic.\n */\n\nimport type { IngestionImportTarget } from \"../interchange/ingestion-import-target\";\nimport type { CandidateDiagnostics, MatchEvidence } from \"./evidence\";\nimport type {\n  EdgeId,\n  EngineRevision,\n  GetNodeType,\n  GraphDef,\n  IdentityAssertionWriteFacade,\n  JsonValue,\n  Node,\n  NodeId,\n  NodeKinds,\n  NodeType,\n  Store,\n} from \"./typegraph-internal\";\n\n/**\n * Opaque identifier for a branch (working copy) of a base store. Branded so a\n * raw string cannot be passed where a deliberately-minted branch id is required.\n */\nexport type BranchId = string & Readonly<{ readonly __brand: \"BranchId\" }>;\n\n/**\n * Opaque token identifying the immutable `base@V` a branch was forked from.\n * Combines a schema hash with a staleness component. Branded so it cannot be\n * confused with an arbitrary string. The second component is a\n * durable revision anchor for stores with revision tracking enabled and a\n * compatibility content fingerprint otherwise.\n */\nexport type BaseVersion = string &\n  Readonly<{ readonly __brand: \"BaseVersion\" }>;\n\n/**\n * Mints a {@link BranchId} from a raw string. Centralizes the brand cast so the\n * unsafe assertion lives in exactly one place.\n */\nexport function asBranchId(value: string): BranchId {\n  return value as BranchId;\n}\n\n/**\n * Mints a {@link BaseVersion} from a raw string. Centralizes the brand cast so\n * the unsafe assertion lives in exactly one place.\n */\nexport function asBaseVersion(value: string): BaseVersion {\n  return value as BaseVersion;\n}\n\n/**\n * A working-copy handle for one branch: its id, the `base@V` it forked from, and\n * a {@link Store} over the branch's own backend.\n */\nexport type GraphBranch<G extends GraphDef> = Readonly<{\n  id: BranchId;\n  base: BaseVersion;\n  store: Store<G>;\n  /**\n   * The branch store's committed schema row `(version, hash)` captured AT\n   * FORK. The merge requires the branch's CURRENT committed schema to still\n   * equal this anchor: any schema operation on the branch after forking —\n   * including a round-trip that restores the original document hash —\n   * advances the version and is refused, so its row side effects can never\n   * be projected into a merge as bare data changes. `undefined` inside the\n   * tuple-less field means the clone committed no schema row (unmanaged\n   * stores); absent entirely on hand-built branch objects, where the merge\n   * falls back to comparing the branch's hash against the fork source's.\n   */\n  schemaAnchor?: Readonly<{ version: number; hash: string }> | undefined;\n  /**\n   * Releases the branch's working-copy backend — the composed close a\n   * {@link WorkingCopyStrategy} built (e.g. a forked working copy's\n   * connection AND its host-level fork, see `forkedWorkingCopyStrategy`).\n   * Idempotent the same way {@link IngestionBranch.close} is: both coalesce\n   * concurrent calls onto one release of the working copy's backend and make\n   * a completed release final, so a backend whose own `close` is not\n   * idempotent is still released exactly once; a release that FAILED is\n   * retried by the next call rather than cached. `branch()` sets this; a\n   * hand-built `GraphBranch` (the merge primitive's own committed-target\n   * stand-in, `tests/`-only fixtures) must supply one too — a no-op when the object does not own a disposable\n   * backend at all.\n   */\n  close: () => Promise<void>;\n  /**\n   * The engine revision the working copy's `lineage` source reported right\n   * after `branch()` cloned it, before any write — the baseline `state-diff.ts`'s\n   * `diffAgainstBase` and `staging.ts`'s `stageBranches` measure this branch's\n   * OWN changes against when pruning the merge diff (see `LineageDelta`). The\n   * key is PRESENT only when a lineage source answered at fork time; it is\n   * ABSENT both when the working copy resolved no `lineage` at all (no backend\n   * `lineage`, no `history: true` capture) and on a hand-built branch object —\n   * either way, the merge always diffs this branch in full.\n   */\n  forkRevision?: EngineRevision | undefined;\n}>;\n\ndeclare const INGESTION_BRANCH_BRAND: unique symbol;\n\n/**\n * Node collections exposed by an {@link IngestionBranch}. They retain normal\n * validation, reads, and staging writes, but omit APIs that claim a declared\n * uniqueness constraint exists on the relaxed physical working copy.\n */\nexport type IngestionNodeCollections<G extends GraphDef> = Readonly<{\n  [K in keyof Store<G>[\"nodes\"]]-?: Pick<\n    Store<G>[\"nodes\"][K],\n    | \"create\"\n    | \"getById\"\n    | \"getByIds\"\n    | \"update\"\n    | \"updateWhere\"\n    | \"delete\"\n    | \"hardDelete\"\n    | \"find\"\n    | \"count\"\n    | \"createFromRecord\"\n    | \"upsertById\"\n    | \"upsertByIdFromRecord\"\n    | \"bulkCreate\"\n    | \"bulkUpsertById\"\n    | \"bulkInsert\"\n    | \"bulkDelete\"\n    | \"bulkFindByIndex\"\n  >;\n}>;\n\n/**\n * Opaque handle for an untrusted ingestion working copy.\n *\n * The ordinary {@link Store} is intentionally absent: callers may stage and\n * inspect graph data through the typed collections, then pass this handle to\n * merge planning, but cannot access schema evolution, transactions, or runtime\n * internals. `close()` releases the private working-copy backend.\n */\nexport type IngestionBranch<G extends GraphDef> = IngestionImportTarget<G> &\n  Readonly<{\n    [INGESTION_BRANCH_BRAND]: true;\n    id: BranchId;\n    base: BaseVersion;\n    nodes: IngestionNodeCollections<G>;\n    edges: Store<G>[\"edges\"];\n    close: () => Promise<void>;\n  }> &\n  (\"identity\" extends keyof Store<G> ?\n    Readonly<{ identity: IdentityAssertionWriteFacade<G> }>\n  : Readonly<Record<never, never>>);\n\n/** A normal branch or an opaque ingestion branch accepted by merge entrypoints. */\nexport type MergeBranch<G extends GraphDef> =\n  GraphBranch<G> | IngestionBranch<G>;\n\n/**\n * Options for {@link GraphBranch} creation. `id` is optional — when omitted a\n * fresh id is generated.\n */\nexport type BranchOptions = Readonly<{\n  id?: BranchId;\n}>;\n\n/**\n * Turns text into an embedding vector. Injected via {@link MergeOptions.embedder}\n * and used by the `vector` / `hybrid` similarity strategies to score candidate\n * pairs by cosine IN MEMORY — the staged candidate nodes are unindexed in the\n * working copy, so a backend ANN index cannot score them pairwise (see\n * `scorePair`). Exact in-memory cosine over real model vectors is both the right\n * scale for bounded candidate dedup and deterministic, which the merge contract\n * requires.\n *\n * Batched and async: given N texts it returns N vectors in the SAME order, each a\n * fixed-dimension `Float32Array` (every vector a given embedder returns shares one\n * length — the model's embedding dimension). The function MUST be deterministic —\n * the same text always yields the same vector — because the whole merge is\n * order-independent and reproducible. Vectors need NOT be pre-normalized; cosine\n * scoring normalizes internally.\n *\n * The concrete local model lives in the CONSUMER (the harness ships an\n * all-MiniLM-L6-v2 embedder); this package depends only on the function shape, so\n * it stays model-agnostic and lean inside the TypeGraph core package.\n */\nexport type Embedder = (\n  texts: readonly string[],\n) => Promise<readonly Float32Array[]>;\n\n/**\n * Pluggable per-kind similarity strategy (design §8).\n *\n * - `vector` / `hybrid` score candidate pairs by cosine over an injected\n *   {@link Embedder} ({@link MergeOptions.embedder}), computed in memory; they\n *   fail with `SimilarityUnavailableError` when no embedder is configured.\n * - `fulltext` and `custom` run with ZERO embeddings — the cross-DB-safe\n *   default. `fulltext` uses an in-memory Sørensen–Dice trigram scorer (T6).\n *\n * The generic mirrors the design's `SimilarityStrategy<G, K>`: `K` constrains the\n * `custom` score function's node arguments to the resolved kind.\n */\nexport type SimilarityStrategy<\n  G extends GraphDef = GraphDef,\n  K extends NodeType = NodeType,\n> =\n  | Readonly<{\n      kind: \"hybrid\";\n      fields: readonly string[];\n      weights?: Readonly<{ vector?: number; fulltext?: number }>;\n      // Phantom binding to the caller's graph, matching the design's\n      // `SimilarityStrategy<G, K>` two-parameter shape. Never set at runtime.\n      readonly __graph?: G;\n    }>\n  | Readonly<{ kind: \"vector\"; field: string; readonly __graph?: G }>\n  | Readonly<{\n      kind: \"fulltext\";\n      fields: readonly string[];\n      readonly __graph?: G;\n    }>\n  | Readonly<{\n      kind: \"custom\";\n      score: (a: Node<K>, b: Node<K>) => number;\n      readonly __graph?: G;\n    }>;\n\n/**\n * Per-kind entity-resolution configuration.\n */\nexport type ResolveConfig<\n  G extends GraphDef = GraphDef,\n  K extends NodeType = NodeType,\n> = Readonly<{\n  /**\n   * Cheap exact-equality blocking key, evaluated before similarity to bound the\n   * O(n²) candidate comparisons. Returning `undefined` places the node in the\n   * shared `\"unblocked\"` bucket (compared all-vs-all within its kind).\n   *\n   * STAGED-vs-staged only: it is an arbitrary JS function, so it cannot be queried\n   * against the committed base. To recall committed entities by a block key\n   * (new-vs-base, the `baseKey` source §6.2), declare the key as a TypeGraph node\n   * index and name it via {@link ResolveConfig.blockIndex} instead.\n   */\n  block?: (node: Node<K>) => string | undefined;\n  /**\n   * Name of a declared TypeGraph node index (`defineNodeIndex`) whose key is this\n   * kind's NEW-vs-BASE block key (design §6.2). When set and the new-vs-base scope is\n   * driven, the `baseKey` source issues an indexed `bulkFindByIndex` lookup of\n   * committed nodes sharing each staged node's index key and proposes them as scored\n   * candidate pairs (a shared block key is a candidate, not a definitional match).\n   *\n   * The index keys on real fields (a field-set + scope + optional partial-`where`), so\n   * only a FIELD-SET block key migrates here; a transform key (`slice`/`soundex`/…)\n   * stays on the staged-only {@link block}. Unused on the public snapshot `merge()`\n   * path. An undeclared name surfaces a typed error at lookup time.\n   */\n  blockIndex?: string;\n  /**\n   * Bounded coarse candidate generation for the NO-KEY case (design §6.2, the\n   * `keyless` source). A node whose {@link block} returns `undefined` (and has no\n   * unique signature) lands in the shared `\"unblocked\"` bucket, which is otherwise\n   * compared ALL-vs-all — an O(n²) cliff that `maxComparisonsPerKind` then truncates\n   * to id-only. Set `keyless` to bound that bucket by single-pass SORTED-NEIGHBOURHOOD\n   * instead: the unblocked nodes are sorted by their similarity-field text (tie-broken\n   * by id) and each is proposed only against its next `window` neighbours — O(n·window),\n   * deterministic. Unset preserves today's all-vs-all behaviour. Only the `\"unblocked\"`\n   * bucket is affected; keyed `block()` buckets are unchanged.\n   */\n  keyless?: Readonly<{\n    /** Forward-neighbour window: each unblocked node is paired with its next `window`\n     * neighbours in the sort. Must be a positive integer. Larger → more recall, more\n     * comparisons (→ all-vs-all as `window` ≥ bucket size). */\n    window: number;\n  }>;\n  /** Similarity strategy (design §8). */\n  similarity: SimilarityStrategy<G, K>;\n  /** Candidate-merge threshold in `[0, 1]`. */\n  threshold: number;\n}>;\n\n/**\n * A resolved cluster of node ids that the merge collapses into one canonical\n * survivor.\n */\nexport type ResolvedCluster = Readonly<{\n  members: readonly NodeId<NodeType>[];\n}>;\n\n/**\n * Policy for resolving conflicting property values across cluster members.\n *\n * - `\"flag\"` keeps the canonical's value and records a {@link PropertyConflict}\n *   without auto-resolving.\n * - `\"lastWriteWins\"` picks by the stable branch/logical total order — NEVER\n *   wall-clock arrival.\n * - `\"provenanceWeighted\"` picks by per-branch trust weight.\n * - A function delegates the decision, returning the surviving {@link JsonValue}.\n */\nexport type PropertyConflictPolicy<G extends GraphDef = GraphDef> =\n  | \"flag\"\n  | \"lastWriteWins\"\n  | \"provenanceWeighted\"\n  | ((conflict: PropertyConflict<G>) => JsonValue);\n\n/**\n * Policy for resolving an inherited node that is deleted by one branch and\n * modified by another (design §6.2).\n *\n * - `\"deleteWins\"` — the node is finally DELETED; the modification is discarded.\n * - `\"modifyWins\"` — the node is RESURRECTED; the modification survives.\n * - `\"flag\"` (default) — the **modification SURVIVES in the merged output** (as\n *   with `\"modifyWins\"`) AND an **unresolved {@link DeleteModifyConflict} is\n *   recorded** in `report.deleteModifyConflicts` for human review. `\"flag\"` is\n *   therefore NOT neutral — it keeps data and surfaces the disagreement, on the\n *   posture that a merge must never silently destroy the only branch still\n *   carrying data. Choose `\"deleteWins\"` to honor the delete by default instead.\n */\nexport type DeleteModifyPolicy = \"deleteWins\" | \"modifyWins\" | \"flag\";\n\n/**\n * Behavior when `maxComparisonsPerKind` is exceeded for a kind.\n *\n * - `\"error\"` fails the merge with a typed error (default).\n * - `\"mergeByIdOnly\"` skips similarity for that kind, emits no candidate edges,\n *   and records a report warning.\n */\nexport type ComparisonCeilingPolicy = \"error\" | \"mergeByIdOnly\";\n\n/**\n * Opt-in retention policy for candidate-level scoring diagnostics. The limit is\n * a deterministic global ceiling over the canonically ordered scored pairs;\n * planning still evaluates candidates according to the normal comparison\n * ceiling, then retains at most this many accepted/rejected decisions.\n */\nexport type CandidateDiagnosticsOptions = Readonly<{\n  limit: number;\n}>;\n\n/**\n * Ontology type-reconciliation mode. `\"off\"` is a no-op (default); `\"ontology\"`\n * collapses compatible types to the most-specific via the public subClassOf\n * closure (T2a / T10).\n */\nexport type ReconcileTypesMode = \"ontology\" | \"off\";\n\n/**\n * Map of node kind name → its {@link ResolveConfig}. Keys are constrained to the\n * graph's node kinds (`keyof G[\"nodes\"]`), so a typo or a kind that does not\n * belong to the graph is a COMPILE error rather than a silently-ignored config\n * (which would let those nodes merge by id only without warning). Each kind's\n * config is bound to that kind's concrete `NodeType`, so `block(node)` and the\n * `custom` scorer see the right node shape. All keys are optional: kinds omitted\n * from this map merge by ID only (new fork nodes added as-is, no fuzzy\n * resolution). For the default unparameterized `GraphDef` the keys widen back to\n * `string`.\n */\nexport type ResolveMap<G extends GraphDef = GraphDef> = Readonly<\n  Partial<{\n    [K in NodeKinds<G>]: ResolveConfig<G, GetNodeType<G, K>>;\n  }>\n>;\n\n/**\n * Caller-facing options for {@link merge}. All fields are optional with frozen\n * defaults applied by `normalizeMergeOptions` (see `options.ts`).\n */\nexport type MergeOptions<G extends GraphDef = GraphDef> = Readonly<{\n  /** Per-kind entity resolution. Omitted kinds merge by ID only. */\n  resolve?: ResolveMap<G>;\n  /** Reconcile differing types across forks. Default `\"off\"`. */\n  reconcileTypes?: ReconcileTypesMode;\n  /** Property-conflict policy for staged-vs-staged disagreements. Default `\"flag\"`. */\n  onPropertyConflict?: PropertyConflictPolicy<G>;\n  /**\n   * Property-conflict policy for BASE↔branch disagreements in a new-vs-base merge\n   * (§6.4-C). DISTINCT from {@link onPropertyConflict} and DOES NOT inherit it:\n   * `onPropertyConflict` can be `\"lastWriteWins\"` / `\"provenanceWeighted\"` / a\n   * function, any of which would let a fuzzy branch match silently OVERWRITE\n   * committed data. Default `\"flag\"` keeps the committed base value (and records the\n   * conflict). Mirrors how `onDeleteModifyConflict` is kept separate. Only consulted\n   * when a cluster contains a base member; the staged path never uses it.\n   */\n  onBasePropertyConflict?: PropertyConflictPolicy<G>;\n  /** Delete/modify-conflict policy. Default `\"flag\"`. */\n  onDeleteModifyConflict?: DeleteModifyPolicy;\n  /** Comparison-ceiling behavior. Default `\"error\"`. */\n  onComparisonCeiling?: ComparisonCeilingPolicy;\n  /**\n   * Deterministic survivor selection within a cluster. Default: the member with\n   * the lexicographically-minimal node id.\n   */\n  canonical?: (cluster: ResolvedCluster) => NodeId<NodeType>;\n  /** Populate the report-only provenance index. Default `true`. */\n  provenance?: boolean;\n  /**\n   * Persist provenance ON-GRAPH: after the commit, upsert one `{branch, sourceId}`\n   * row per contribution into a sidecar provenance graph on the target's backend\n   * (queryable via `openProvenanceStore` / `readProvenance`). Default `false`\n   * (report-only). Best-effort and post-commit — a persistence failure surfaces as\n   * a {@link MergeReport.warnings} entry, never a failed merge.\n   */\n  persistProvenance?: boolean;\n  /**\n   * Local embedder for `vector` / `hybrid` similarity (in-memory cosine over the\n   * staged candidate pairs). Required ONLY when a kind's resolve strategy is\n   * `vector` or `hybrid`; `fulltext` / `custom` ignore it. A vector/hybrid\n   * strategy with no embedder configured fails with a typed\n   * {@link import(\"./errors\").SimilarityUnavailableError}.\n   */\n  embedder?: Embedder;\n  /** Merge receiver. Default: the base `store`, written transactionally. */\n  target?: Store<G>;\n  /** Safety ceiling on candidate comparisons per kind. Default: unbounded. */\n  maxComparisonsPerKind?: number;\n  /**\n   * Retain bounded accepted/rejected scored-pair diagnostics. Omitted by\n   * default so ordinary plans and reports contain only decisive evidence.\n   */\n  candidateDiagnostics?: CandidateDiagnosticsOptions;\n  /**\n   * Optional single-link diameter guard. When set, clusters whose pairwise\n   * distance exceeds it are split by the deterministic drop-weakest rule (T8).\n   */\n  clusterMaxDiameter?: number;\n  /**\n   * Explicit stable branch order used by `lastWriteWins` / tie-breaking. When\n   * omitted, branch ids sorted lexicographically are used. NEVER wall-clock.\n   */\n  branchOrder?: readonly BranchId[];\n  /**\n   * Per-branch trust weights consulted ONLY by the `\"provenanceWeighted\"`\n   * property-conflict policy ({@link onPropertyConflict} /\n   * {@link onBasePropertyConflict}): when branches disagree on a property value,\n   * the value contributed by the highest-weight branch wins. Ties fall back to\n   * {@link branchOrder} (then canonical value order); branches absent from the map\n   * default to weight `0`. Ignored by every other policy. Keyed by\n   * {@link BranchId}, like {@link branchOrder}. A non-empty map is required when\n   * either property-conflict policy is `\"provenanceWeighted\"`; otherwise option\n   * validation refuses the merge rather than silently changing policy.\n   */\n  provenanceWeights?: ReadonlyMap<BranchId, number>;\n}>;\n\n/**\n * Object-form arguments for {@link mergeIncremental} (§6.6). The two same-typed\n * stores are NAMED so `forkPoint` (the frozen ancestor the branches forked from, the\n * diff reference) and `target` (the live committed graph that base lookups and the\n * commit land on) cannot be swapped. The target is deliberately absent from the\n * options type because the named `target` argument is authoritative.\n */\nexport type MergeIncrementalArgs<G extends GraphDef = GraphDef> = Readonly<{\n  forkPoint: Store<G>;\n  target: Store<G>;\n  branches: readonly MergeBranch<G>[];\n  options?: Omit<MergeOptions<G>, \"target\">;\n}>;\n\n/**\n * Records that a set of fork node ids resolved to a single canonical survivor.\n */\nexport type EntityResolution = Readonly<{\n  canonicalId: NodeId<NodeType>;\n  memberIds: readonly NodeId<NodeType>[];\n  kind: string;\n  branchOrigins: readonly BranchId[];\n  /** Deterministic minimal accepted-edge witness for this resolution. */\n  decisiveEdges: readonly MatchEvidence[];\n}>;\n\n/**\n * One candidate value contributing to a property conflict, tagged by its origin\n * branch.\n */\nexport type ConflictingValue = Readonly<{\n  branchId: BranchId;\n  value: JsonValue;\n}>;\n\n/**\n * A property whose value differed across cluster members (or across the two\n * collapsed edges for an edge conflict). `resolution` records the value the\n * policy selected.\n */\nexport type PropertyConflict<G extends GraphDef = GraphDef> = Readonly<{\n  entityId: NodeId<NodeType> | EdgeId;\n  kind: string;\n  property: string;\n  values: readonly ConflictingValue[];\n  resolution: JsonValue;\n  // `G` keeps the public conflict type parameterized by the caller's graph\n  // (matching the design's `PropertyConflict<G>`); it carries no runtime field.\n  readonly __graph?: G;\n}>;\n\n/**\n * An inherited node OR edge deleted by one branch and modified by another, with\n * the resolution the {@link DeleteModifyPolicy} produced. `entityId` is a\n * {@link NodeId} for a node conflict and an {@link EdgeId} for an edge conflict.\n */\nexport type DeleteModifyConflict = Readonly<{\n  entityId: NodeId<NodeType> | EdgeId;\n  kind: string;\n  deletedBy: BranchId;\n  modifiedBy: BranchId;\n  resolution: DeleteModifyPolicy;\n}>;\n\n/**\n * Records that a cluster's mixed member kinds were collapsed to a single\n * canonical (most-specific) type via ontology reconciliation.\n */\nexport type TypeReconciliation = Readonly<{\n  entityId: NodeId<NodeType>;\n  fromTypes: readonly string[];\n  toType: string;\n  /** Accepted ontology-retype witness, when emitted by graph merge. */\n  decisiveEdges?: readonly MatchEvidence[];\n}>;\n\n/**\n * An item omitted from the merged result (e.g. an edge whose endpoint was\n * deleted, an incompatible-typed cluster member, or an identity assertion that\n * lost the survivor rule to an equivalent assertion from another branch).\n *\n * Discriminated on `kind` so each variant keeps its own id type: node and edge\n * ids are branded, while an identity assertion is named by the ledger's plain\n * assertion id (it is not a graph entity and carries no brand).\n */\nexport type DroppedItem =\n  | Readonly<{ kind: \"node\"; id: NodeId<NodeType>; reason: string }>\n  | Readonly<{ kind: \"edge\"; id: EdgeId; reason: string }>\n  | Readonly<{ kind: \"identity\"; id: string; reason: string }>;\n\n/**\n * The {@link ValidityEndResolution.precedence} of an entry the INCREMENTAL TARGET\n * decided rather than the merge: the destination had already moved this row's end\n * before the merge ran, so every branch claim was discarded and no write was staged.\n */\nexport const VALIDITY_END_TARGET_PRECEDENCE = \"target\" as const;\n\n/**\n * One inherited row whose end-of-validity the merge RESOLVED: the explicit set or\n * clear that stands and every branch that claimed a change for the row (including\n * the ones whose claim lost arbitration).\n *\n * `id` is bare because `entity` + `kind` already disambiguate it — a node and an\n * edge, or two kinds, that share an id string are distinct entries.\n */\nexport type ValidityEndResolution = Readonly<{\n  entity: \"node\" | \"edge\";\n  kind: string;\n  id: string;\n  /** Every branch that claimed a change, sorted; length > 1 means arbitration. */\n  claimedBy: readonly BranchId[];\n  /**\n   * Present only as {@link VALIDITY_END_TARGET_PRECEDENCE}, marking an entry the\n   * merge did NOT decide: the incremental target had already changed this end, so\n   * the set/clear fields describe the target's own committed state, every claim in\n   * `claimedBy` was discarded, and nothing was written or credited for the row.\n   *\n   * ABSENT means the merge decided the change — `validTo` or `clearValidTo` names\n   * what it wrote and `claimedBy` names the claims it arbitrated between. A consumer\n   * that ignores the field therefore keeps reading the entries it always read.\n   */\n  precedence?: typeof VALIDITY_END_TARGET_PRECEDENCE;\n}> &\n  (\n    | Readonly<{\n        /** The canonical instant the merge set, or the target already held. */\n        validTo: string;\n        clearValidTo?: never;\n      }>\n    | Readonly<{\n        /** Marks a resolution that reopened the row by clearing its upper bound. */\n        clearValidTo: true;\n        validTo?: never;\n      }>\n  );\n\n/**\n * A `(kind, id)` node identity as surfaced in the merge report. Node identity is the\n * PAIR, never the bare id (a `Doctor` and a `SpecialistDoctor` can share an id string),\n * so report shapes that name nodes carry both halves.\n */\ntype ReportNodeIdentity = Readonly<{\n  kind: string;\n  id: NodeId<NodeType>;\n}>;\n\n/**\n * An AMBIGUOUS new-vs-base match (design §6.4-A): a connected component that\n * bridged ≥2 distinct committed base entities (directly, `baseA ~ new ~ baseB`, or\n * through staged hops, `baseA ~ new1 ~ new2 ~ baseB`). `baseIds` are the committed\n * entities the component spanned; `memberIds` are all of its members. Both are full\n * `(kind, id)` identities — the guard keys on the composite identity, so a component\n * spanning two SAME-id/different-kind bases stays distinguishable in the report. The\n * base↔base collapse is ALWAYS REFUSED — the component is split so the committed\n * entities stay separate. Reported regardless of how the component split. (A\n * deliberate-collapse trust path is deferred until committed-entity re-keying + edge\n * repoint exist; §6.4-C.)\n */\nexport type BaseAmbiguity = Readonly<{\n  baseIds: readonly ReportNodeIdentity[];\n  memberIds: readonly ReportNodeIdentity[];\n}>;\n\n/**\n * The contribution one branch made to the merged result. Returned by\n * {@link ProvenanceIndex.byBranch}. EXPLICITLY in-memory / report-only for P0 —\n * no on-graph prop tagging (deferred to the AgentFS phase).\n */\nexport type BranchProvenance = Readonly<{\n  nodeIds: readonly NodeId<NodeType>[];\n  edgeIds: readonly EdgeId[];\n}>;\n\n/**\n * Report-only, in-memory provenance index. `byBranch` answers \"which\n * nodes/edges did this branch contribute to the merged result?\".\n */\nexport type ProvenanceIndex = Readonly<{\n  byBranch: (branchId: BranchId) => BranchProvenance;\n}>;\n\n/**\n * One `{branch, sourceId}` → canonical contribution — the unit of provenance.\n *\n * The in-memory {@link ProvenanceIndex} collapses these to `branch → {canonical\n * ids}`; the full record (which keeps the contributing `sourceId` and kind) is what\n * `persistProvenance` writes to the sidecar provenance graph. `sourceId` is the\n * fork-local id the contribution had in its branch BEFORE the merge collapsed it to\n * `canonicalId` (equal to `canonicalId` for an in-place modification).\n */\nexport type ProvenanceRecord = Readonly<{\n  role: \"node\" | \"edge\";\n  canonicalId: string;\n  canonicalKind: string;\n  branchId: BranchId;\n  sourceId: string;\n}>;\n\n/**\n * What the merge actually wrote to the target: node and edge counts plus the\n * identity-ledger effects. `identity.asserted` counts rows the applier\n * CREATED — planned assertions the target already held (idempotent exact or\n * semantic-pair matches, the normal incremental case) are excluded — and\n * `identity.retracted` counts rows the applier ENDED, excluding already-ended\n * or unknown ids. Assertions dropped by the survivor rule are enumerated in\n * {@link MergeReport.dropped} rather than counted here.\n */\nexport type MergedCounts = Readonly<{\n  nodes: number;\n  edges: number;\n  identity: Readonly<{ asserted: number; retracted: number }>;\n}>;\n\n/**\n * The full result of a {@link merge}: counts, every resolution/conflict/\n * reconciliation/drop, and the report-only provenance index.\n */\nexport type MergeReport<G extends GraphDef = GraphDef> = Readonly<{\n  merged: MergedCounts;\n  resolutions: readonly EntityResolution[];\n  conflicts: readonly PropertyConflict<G>[];\n  deleteModifyConflicts: readonly DeleteModifyConflict[];\n  typeReconciliations: readonly TypeReconciliation[];\n  dropped: readonly DroppedItem[];\n  /**\n   * Every inherited row whose END-OF-VALIDITY the merge resolved, with the end\n   * update that stands and the branches that claimed it. A set carries `validTo`;\n   * a reopening carries `clearValidTo: true`.\n   *\n   * Reported because the resolution is silent by design: two branches ending the\n   * same row at different instants are not in conflict (an ending is a monotone\n   * claim, like a deletion), so the earliest end is taken without a\n   * `PropertyConflict`. This list is how a caller sees that arbitration happened.\n   * It includes the rows where the arbitration discarded EVERY claim because the\n   * incremental target had already moved the end — those carry\n   * `precedence: \"target\"` and staged no write. Window deltas the commit CANNOT\n   * apply appear in {@link MergeReport.dropped} instead, with reason\n   * `\"window-not-applicable\"`.\n   */\n  validityEnds: readonly ValidityEndResolution[];\n  /**\n   * Ambiguous new-vs-base matches (§6.4-A): components that bridged ≥2 committed\n   * base entities. Empty on the staged-vs-staged snapshot path.\n   */\n  baseAmbiguities: readonly BaseAmbiguity[];\n  provenance: ProvenanceIndex;\n  /**\n   * Non-fatal advisories from the merge — comparison-ceiling skips and, when\n   * `persistProvenance` is set, a best-effort provenance-persistence failure (the\n   * graph still committed). Empty on a clean merge.\n   */\n  warnings: readonly string[];\n  /** Bounded accepted/rejected scored-pair diagnostics when explicitly enabled. */\n  candidateDiagnostics?: CandidateDiagnostics;\n  /**\n   * Present only when `persistProvenance` ran and SUCCEEDED: the sidecar provenance\n   * graph id and how many `{branch, sourceId}` rows were upserted. Absent when\n   * persistence was off or failed (a failure adds a {@link MergeReport.warnings}).\n   */\n  provenancePersisted?: Readonly<{ graphId: string; count: number }>;\n}>;\n","/**\n * `base@V` stamping.\n *\n * A {@link BaseVersion} is the immutable token a branch is forked from. It must\n * change whenever either the schema OR the live content of the base store\n * changes, so that `merge()`'s precondition check (T11) can reject a branch that\n * forked from a divergent base.\n *\n * The token is two stable components joined by a separator:\n *\n *   1. A **schema hash** — `computeSchemaHash(serializeSchema(graph, version))`.\n *      This is content-addressed (the public `computeSchemaHash` deliberately\n *      excludes the version number and `generatedAt`, so it is stable across\n *      re-saves of the same schema).\n *   2. An anchor, chosen by ONE precedence every caller of\n *      {@link computeBaseVersion} shares:\n *      a. A **revision anchor** when the Store has `revisionTracking` (or\n *         `history`) enabled — a durable random per-graph origin plus the\n *         monotonic revision clock. This is O(1) to read and changes after\n *         every successful Store write; the origin prevents independent\n *         stores with coincident timestamps from sharing an anchor.\n *      b. Otherwise, an **engine anchor** when `resolveLineage(store)` yields\n *         a `lineage` (necessarily the BACKEND's own — a store with no\n *         revision tracking never captures history, so the recorded-relations\n *         lineage is unreachable here; see `store/recorded-capture/lineage.ts`).\n *         The anchor pairs the SAME durable per-graph revision-origin nonce\n *         the revision anchor uses (ensured here too, at mint time, on this\n *         store's backend) with the engine's opaque whole-database revision\n *         — origin-namespaced for the identical reason the revision anchor\n *         is: two independent databases whose engines both happen to report\n *         the same revision string (a fresh counter starting at \"r1\") would\n *         otherwise mint indistinguishable engine anchors, making a branch\n *         forked from one database look mergeable into the other. Both\n *         reads are O(1). It is engine-wide rather than per-graph, which is\n *         why re-validating it (see\n *         `graph-merge/merge.ts`'s `assertTargetUnchanged` and\n *         `assertForkPointUnchanged`) cannot stop at a raw inequality: a\n *         revision bump from a commit to an UNRELATED graph on the same\n *         engine must not fail this graph's merge, so a mismatch is only\n *         a real divergence once `lineage.changesSince` confirms this\n *         graph's own rows moved. `LineageDelta` names only node and edge\n *         keys, not identity assertions: an engine-anchored store that\n *         changes ONLY its current identity assertions between plan and\n *         commit — no node or edge row touched — mints an empty delta and\n *         is tolerated as unchanged. The content-fingerprint fallback below\n *         does not share this gap (its fingerprint folds identity\n *         assertions in directly), and revision-anchored stores do not\n *         either (any Store write, identity-only included, advances the\n *         shared revision clock the anchor reads). Closing it would mean\n *         teaching `LineageDelta` a THIRD dimension, or re-checking\n *         identity assertions on the side the way `assertTargetUnchanged`\n *         already re-checks the schema half — neither is done today.\n *      c. Otherwise, the compatibility fallback: a **content fingerprint**, a\n *         SHA-256 digest (truncated to a fixed-width hex string) of every\n *         LIVE node and edge over the base store (`id`, `updated_at`, the\n *         bitemporal `valid_from`/`valid_to`, and canonicalized `props`;\n *         edges also carry their endpoint ids), sorted by id, so two stores\n *         with identical live content fingerprint identically regardless of\n *         row enumeration order or insertion order. Props AND validity are\n *         folded in so the token changes on a content or validity edit even\n *         when `updated_at` ties at millisecond granularity. Current\n *         identity assertions are folded in too (see\n *         `computeContentComponent`), which is exactly what the engine\n *         anchor above does not do. Hashing keeps the token fixed-width\n *         instead of growing linearly with store size.\n *\n * The token MUST be computed off the ORIGINAL base store, never off a clone:\n * `exportGraph`/`importGraph` regenerate `created_at`/`updated_at`, so a clone's\n * fingerprint would not match its source. (See the working-copy fidelity note in\n * T4.)\n *\n * `computeBaseVersion` is async because schema hashing, revision reads, and the\n * compatibility live-content enumeration go through async TypeGraph internals.\n * The design's synchronous illustrative signature does not survive contact with\n * the real store surface.\n */\n\nimport type { SqlSchema } from \"../query/compiler/schema\";\nimport { canonicalizeProps, parseRowProps } from \"./canonical-props\";\nimport { compareStrings } from \"./node-key\";\nimport { enumerateAllEdges, enumerateAllNodes } from \"./state-diff\";\nimport type {\n  EngineRevision,\n  GraphBackend,\n  GraphDef,\n  IdentityTransferAssertion,\n  LineageDelta,\n  Store,\n  TransactionBackend,\n} from \"./typegraph-internal\";\nimport { getEdgeKinds, getNodeKinds, sha256Hex } from \"./typegraph-internal\";\nimport {\n  encodeRecordedLineageRevision,\n  ensureRevisionOrigin,\n  readRevisionOrigin,\n  recordedRelationsLineage,\n  recordedRevisionOriginsVerdict,\n  resolveLineage,\n  storeBackend,\n  storeCaptureEnabled,\n  storeRuntime,\n} from \"./typegraph-internal\";\nimport { computeSchemaHash, serializeSchema } from \"./typegraph-internal\";\nimport type { BaseVersion } from \"./types\";\nimport { asBaseVersion } from \"./types\";\n\n/**\n * Separator between the schema-hash and revision-or-content token components.\n * The schema hash contains no NUL byte, so one NUL unambiguously delimits the\n * two components.\n */\nconst TOKEN_SEPARATOR = \"\\0\";\n\n/** Separates the schema hash from the monotonic active schema version. */\nconst SCHEMA_VERSION_TAG = \"#s\";\nconst REVISION_COMPONENT_PREFIX = \"revision:\";\nconst REVISION_COMPONENT_SEPARATOR = \":\";\nconst INITIAL_REVISION = \"initial\";\n\n/**\n * Marks the engine-anchor component form — see the module doc's anchor\n * precedence. Distinct from {@link REVISION_COMPONENT_PREFIX}: a token never\n * carries both, and {@link hasRevisionAnchor} stays true only for the\n * TypeGraph-owned form.\n */\nconst ENGINE_COMPONENT_PREFIX = \"engine:\";\n\n/**\n * Falls back to schema version `1` when the backend has not recorded an active\n * schema version. `serializeSchema` only uses the version for the serialized\n * doc; the hash deliberately excludes it, so the exact value never affects the\n * resulting `BaseVersion`.\n */\nconst FALLBACK_SCHEMA_VERSION = 1;\n\n/**\n * Reads the active schema version from the backend, defaulting when absent. The\n * value is informational for `serializeSchema`; `computeSchemaHash` excludes the\n * version, so this never destabilizes the token.\n *\n * Exported so a caller re-validating the schema half of an already-computed\n * token — `merge.ts`'s `assertTargetUnchanged`, which needs a FRESH read\n * through the pinned transaction backend rather than `computeSchemaComponent`'s\n * root-backend read — shares this one reader instead of re-spelling the\n * `getActiveSchema` fallback. Takes the narrow read surface both a\n * `GraphBackend` and a `TransactionBackend` satisfy.\n */\nexport async function readActiveSchemaVersion(\n  backend: Pick<GraphBackend, \"getActiveSchema\">,\n  graphId: string,\n): Promise<number> {\n  const active = await backend.getActiveSchema(graphId);\n  return active?.version ?? FALLBACK_SCHEMA_VERSION;\n}\n\n/**\n * Computes the schema-hash component of the base version token — the SCHEMA half of\n * `base@V`, independent of live content. Exported so `mergeIncremental()` can assert\n * `forkPoint` and `target` share a schema (the hard half of its precondition) without\n * re-parsing the token separator or recomputing the content fingerprint (§6.6).\n */\nexport async function computeSchemaComponent<G extends GraphDef>(\n  store: Store<G>,\n): Promise<string> {\n  const version = await readActiveSchemaVersion(\n    storeBackend(store),\n    store.graphId,\n  );\n  return computeSchemaHash(serializeSchema(store.graph, version));\n}\n\n/**\n * Stable TOTAL comparator over `{ kind, id }` digest entries. Keyed on `(kind, id)`\n * because the node primary key is `(graph_id, kind, id)` — two nodes of different\n * kinds may legitimately share an `id` (e.g. `Person:x` and `Company:x`), so an\n * id-only comparator is non-total and would leave same-id/different-kind entries at\n * the mercy of sort stability. `(kind, id)` makes the digest order fully canonical.\n */\nfunction byDigestEntry(\n  left: Readonly<{ kind: string; id: string }>,\n  right: Readonly<{ kind: string; id: string }>,\n): number {\n  const byKind = compareStrings(left.kind, right.kind);\n  return byKind === 0 ? compareStrings(left.id, right.id) : byKind;\n}\n\n/**\n * Number of SHA-256 bytes retained for the content fingerprint. 16 bytes (128\n * bits) makes an accidental collision — which would let a divergent base pass\n * the merge precondition — negligible, while keeping the token fixed-width\n * regardless of store size.\n */\nconst CONTENT_FINGERPRINT_BYTES = 16;\n\n/**\n * Builds the deterministic content fingerprint over the base store's LIVE rows.\n *\n * Each live node contributes `(id, updatedAt, validFrom, validTo, props)` and\n * each live edge contributes `(id, updatedAt, validFrom, validTo, endpoints,\n * props)`; both lists are sorted by id before serialization so the fingerprint is\n * independent of enumeration order. Props are canonicalized so the token changes\n * whenever live content changes even when two writes land on the same millisecond\n * `updated_at` (timestamp granularity must never be the sole change signal). The\n * bitemporal `valid_from`/`valid_to` are folded in for the same reason — they are\n * user-mutable row content, so a validity-only edit that leaves `updated_at`\n * unchanged must still move the token. Soft-deleted rows are intentionally\n * excluded — the fingerprint describes the live base a branch forks from.\n *\n * Takes the backend rather than a `Store` so the SAME fingerprint can be\n * re-computed inside a commit transaction (via the tx-scoped backend) for the\n * in-transaction `base@V` re-validation — the reads then observe the\n * transaction's snapshot, not whatever a concurrent writer has since committed.\n *\n * `identityAssertions` is REQUIRED (never defaulted): a caller that forgot to\n * read the ledger would silently mint a pre-identity token, so an identity-only\n * divergence would pass the `base@V` precondition. Pass an empty array only when\n * the store genuinely holds no current assertions.\n */\nexport async function computeContentComponent<G extends GraphDef>(\n  backend: GraphBackend | TransactionBackend,\n  graphId: string,\n  graph: G,\n  identityAssertions: readonly IdentityTransferAssertion[],\n): Promise<string> {\n  const nodeKinds = getNodeKinds(graph);\n  const edgeKinds = getEdgeKinds(graph);\n\n  const nodeDigest: Readonly<{\n    id: string;\n    kind: string;\n    updatedAt: string;\n    validFrom: string | undefined;\n    validTo: string | undefined;\n    props: string;\n  }>[] = [];\n  for (const kind of nodeKinds) {\n    const rows = await enumerateAllNodes(backend, graphId, kind);\n    for (const row of rows) {\n      if (row.deleted_at === undefined) {\n        nodeDigest.push({\n          id: row.id,\n          kind: row.kind,\n          updatedAt: row.updated_at,\n          validFrom: row.valid_from,\n          validTo: row.valid_to,\n          props: canonicalizeProps(parseRowProps(row.props)),\n        });\n      }\n    }\n  }\n\n  const edgeDigest: Readonly<{\n    id: string;\n    kind: string;\n    fromId: string;\n    toId: string;\n    updatedAt: string;\n    validFrom: string | undefined;\n    validTo: string | undefined;\n    props: string;\n  }>[] = [];\n  for (const kind of edgeKinds) {\n    const rows = await enumerateAllEdges(backend, graphId, kind);\n    for (const row of rows) {\n      if (row.deleted_at === undefined) {\n        edgeDigest.push({\n          id: row.id,\n          kind: row.kind,\n          fromId: row.from_id,\n          toId: row.to_id,\n          updatedAt: row.updated_at,\n          validFrom: row.valid_from,\n          validTo: row.valid_to,\n          props: canonicalizeProps(parseRowProps(row.props)),\n        });\n      }\n    }\n  }\n\n  // Omit the `identity` key entirely when the assertion list is empty, mirroring\n  // the serializer's omit-when-empty convention (schema/serializer.ts). This keeps\n  // the content token byte-identical to the pre-identity shape for identity-disabled\n  // graphs and stores that carry identity config but zero live assertions — so a\n  // pre-upgrade branch does not spuriously fail the base@V precondition.\n  return sha256Hex(\n    canonicalizeProps({\n      nodes: nodeDigest.sort((left, right) => byDigestEntry(left, right)),\n      edges: edgeDigest.sort((left, right) => byDigestEntry(left, right)),\n      ...(identityAssertions.length === 0 ?\n        {}\n      : { identity: identityAssertions }),\n    }),\n    CONTENT_FINGERPRINT_BYTES,\n  );\n}\n\n/**\n * Computes the immutable `base@V` token for a store. Combines the schema hash\n * with a durable revision anchor when tracking is enabled, otherwise with the\n * compatibility live-content fingerprint.\n *\n * MUST be called on the ORIGINAL base store, not a clone (clones regenerate\n * timestamps and would fingerprint differently when the compatibility path is\n * in use).\n */\nexport async function computeBaseVersion<G extends GraphDef>(\n  store: Store<G>,\n): Promise<BaseVersion> {\n  if (store.revisionTrackingEnabled) {\n    const [schemaComponent, origin, revision, activeVersion] =\n      await Promise.all([\n        computeSchemaComponent(store),\n        store.revisionOriginNow(),\n        store.revisionNow(),\n        readActiveSchemaVersion(storeBackend(store), store.graphId),\n      ]);\n    // The document hash is deliberately version-blind, and the revision\n    // clock does not advance on schema commits — so a schema ROUND-TRIP\n    // (migrate away and back) would otherwise restore the exact token while\n    // its preflights mutated identity rows. The active schema version is\n    // monotonic, so baking it into the schema half fences the round-trip.\n    // The legacy branch below needs no equivalent: its content fingerprint\n    // covers the mutated rows directly.\n    return asBaseVersion(\n      `${schemaComponent}${SCHEMA_VERSION_TAG}${activeVersion}${TOKEN_SEPARATOR}${revisionComponent(origin, revision)}`,\n    );\n  }\n  // Tracking is off, so `resolveLineage` can only ever answer with the\n  // BACKEND's own `lineage` (the recorded-relations lineage requires\n  // `storeCaptureEnabled`, which implies tracking — see the module doc's\n  // anchor precedence). A store with no lineage at all falls through to the\n  // compatibility content fingerprint below.\n  const lineage = resolveLineage(store);\n  if (lineage !== undefined) {\n    // The session is the root backend `store` holds: this runs strictly\n    // outside any transaction, so the root backend is the only session\n    // available, and it is the same object `resolveLineage(store)` just\n    // resolved `lineage` off of.\n    const backend = storeBackend(store);\n    const [schemaComponent, activeVersion, origin, revision] =\n      await Promise.all([\n        computeSchemaComponent(store),\n        readActiveSchemaVersion(backend, store.graphId),\n        // The SAME `typegraph_revision_origins` row the TypeGraph revision\n        // anchor above binds to — ensured here too, on the store's own\n        // graph, so an engine-anchored store (no TypeGraph revision\n        // tracking) still gets a durable per-graph namespace to distinguish\n        // it from an unrelated database whose engine coincidentally reports\n        // the same revision. See `engineComponent`'s own doc.\n        ensureRevisionOrigin(\n          backend,\n          recordedRevisionOriginsVerdict(backend),\n          store.revisionSchema,\n          store.graphId,\n        ),\n        lineage.revision(backend),\n      ]);\n    // Same schema-half shape as the revision-anchor branch, and for the same\n    // reason: nothing here guarantees an engine's revision is blind to a\n    // schema-only round-trip, so the active version stays folded in.\n    //\n    // Unlike the content-fingerprint fallback below, this anchor carries no\n    // identity-assertion signal at all: `LineageDelta` names only node and\n    // edge keys (see the module doc's precedence entry b), so a commit that\n    // changes only the graph's current identity assertions is invisible to\n    // `lineage.changesSince` and the engine-anchor re-validation guards in\n    // `graph-merge/merge.ts` tolerate it as unchanged.\n    return asBaseVersion(\n      `${schemaComponent}${SCHEMA_VERSION_TAG}${activeVersion}${TOKEN_SEPARATOR}${engineComponent(origin, revision)}`,\n    );\n  }\n  const [schemaComponent, contentComponent] = await Promise.all([\n    computeSchemaComponent(store),\n    computeStoreContentComponent(store),\n  ]);\n  return asBaseVersion(\n    `${schemaComponent}${TOKEN_SEPARATOR}${contentComponent}`,\n  );\n}\n\n/**\n * The content component of a live {@link Store}: reads the store's current\n * identity assertions, then fingerprints its live rows alongside them.\n *\n * Exists so {@link computeBaseVersion} can run the schema half and the content\n * half CONCURRENTLY. The identity read must precede the fingerprint (it is an\n * input to it), but that ordering is internal to this half and must not serialize\n * the independent schema hash behind it.\n */\nasync function computeStoreContentComponent<G extends GraphDef>(\n  store: Store<G>,\n): Promise<string> {\n  const identityAssertions =\n    await storeRuntime(store).readCurrentIdentityAssertions(\"state\");\n  return computeContentComponent(\n    storeBackend(store),\n    store.graphId,\n    store.graph,\n    identityAssertions,\n  );\n}\n\n/**\n * THE one grammar for an origin-namespaced anchor component: `<prefix>`\n * followed by the durable per-graph origin nonce, the separator, and the\n * revision — shared by both anchor forms that carry an origin (the\n * TypeGraph revision anchor and the engine anchor) so there is exactly one\n * place that encodes and decodes `<origin><sep><revision>`, never two\n * hand-spelled copies drifting apart. The origin itself is a `generateId()`\n * nonce (URL-safe nanoid alphabet), which never contains\n * {@link REVISION_COMPONENT_SEPARATOR}, so the FIRST separator in the\n * encoded string unambiguously ends the origin even when the revision that\n * follows contains separators of its own (a `RecordedInstant` does).\n */\nfunction encodeAnchorComponent(\n  prefix: string,\n  origin: string,\n  revision: string,\n): string {\n  return `${prefix}${origin}${REVISION_COMPONENT_SEPARATOR}${revision}`;\n}\n\nfunction decodeAnchorComponent(\n  prefix: string,\n  component: string,\n): Readonly<{ origin: string; revision: string }> | undefined {\n  if (!component.startsWith(prefix)) return undefined;\n  const encoded = component.slice(prefix.length);\n  const separator = encoded.indexOf(REVISION_COMPONENT_SEPARATOR);\n  if (separator <= 0 || separator === encoded.length - 1) return undefined;\n  return {\n    origin: encoded.slice(0, separator),\n    revision: encoded.slice(separator + 1),\n  };\n}\n\nfunction revisionComponent(\n  origin: string,\n  revision: string | undefined,\n): string {\n  return encodeAnchorComponent(\n    REVISION_COMPONENT_PREFIX,\n    origin,\n    revision ?? INITIAL_REVISION,\n  );\n}\n\n/**\n * Builds the engine-anchor component: the store's durable per-graph revision\n * origin (the SAME `typegraph_revision_origins` row the TypeGraph revision\n * anchor uses, ensured at mint time by {@link computeBaseVersion}) alongside\n * the engine's own opaque revision. Without the origin, two independent\n * databases whose engines both happen to report the same revision string\n * (a fresh counter starting at \"r1\", for instance) would mint identical\n * engine anchors for unrelated graphs — see the module doc's clear()-epoch\n * and cross-database notes.\n */\nfunction engineComponent(origin: string, revision: EngineRevision): string {\n  return encodeAnchorComponent(ENGINE_COMPONENT_PREFIX, origin, revision);\n}\n\n/** True when a base token uses the O(1) durable revision-anchor component. */\nexport function hasRevisionAnchor(version: BaseVersion): boolean {\n  return contentComponentOf(version).startsWith(REVISION_COMPONENT_PREFIX);\n}\n\nfunction engineAnchorParts(\n  version: BaseVersion,\n): Readonly<{ origin: string; revision: EngineRevision }> | undefined {\n  const parts = decodeAnchorComponent(\n    ENGINE_COMPONENT_PREFIX,\n    contentComponentOf(version),\n  );\n  return parts === undefined ? undefined : (\n      { origin: parts.origin, revision: parts.revision as EngineRevision }\n    );\n}\n\n/**\n * Extracts the engine revision from an engine-anchored base token, or\n * `undefined` for any other anchor form. The ONE parser for this component,\n * paired with {@link engineComponent}: `graph-merge/merge.ts`'s\n * `assertTargetUnchanged` and `assertForkPointUnchanged` both call this\n * rather than re-spelling the `\"engine:\"` prefix.\n */\nexport function engineAnchorOf(\n  version: BaseVersion,\n): EngineRevision | undefined {\n  return engineAnchorParts(version)?.revision;\n}\n\n/**\n * Extracts the durable store-specific origin namespace from an\n * engine-anchored base token, the engine-anchor counterpart of\n * {@link revisionOriginOf}. `undefined` for any other anchor form.\n */\nexport function engineAnchorOriginOf(version: BaseVersion): string | undefined {\n  return engineAnchorParts(version)?.origin;\n}\n\n/**\n * Extracts the durable revision from a revision-anchored base token. Undefined\n * represents the stable initial state before the first tracked write.\n */\nexport function revisionAnchorOf(version: BaseVersion): string | undefined {\n  const revision = revisionPartsOf(version)?.revision;\n  return revision === undefined || revision === INITIAL_REVISION ?\n      undefined\n    : revision;\n}\n\n/**\n * Extracts the durable store-specific namespace from a revision-anchored base\n * token. Undefined denotes a legacy timestamp-only anchor, which must never\n * be treated as equivalent to a current store's namespaced revision.\n */\nexport function revisionOriginOf(version: BaseVersion): string | undefined {\n  return revisionPartsOf(version)?.origin;\n}\n\n/**\n * THE one owner of the origin-match decision for EITHER origin-namespaced\n * anchor form: `expectedVersion`'s origin component — the revision anchor's\n * when it carries one, else the engine anchor's — against the LIVE origin\n * row {@link readRevisionOrigin} reads off `backend` for `graphId`. A token\n * only ever carries one anchor form, so exactly one of the two extractors\n * below answers. `merge.ts`'s `assertTargetUnchanged` (re-validating either\n * anchor form inside the commit transaction) and this module's own\n * `lineageDeltaSinceAnchor` (deciding whether a `base` of either\n * origin-namespaced form can trust a `changesSince` read) both need exactly\n * this comparison; extracted here so neither re-spells it. Returns the two\n * values actually compared alongside the verdict, so a caller that refuses\n * on a mismatch embeds both in its own error `details` without a second\n * read.\n */\nexport async function revisionOriginMatch(\n  backend: Pick<GraphBackend, \"execute\">,\n  schema: SqlSchema,\n  graphId: string,\n  expectedVersion: BaseVersion,\n): Promise<\n  Readonly<{\n    expectedOrigin: string | undefined;\n    liveOrigin: string | undefined;\n    matches: boolean;\n  }>\n> {\n  const expectedOrigin =\n    revisionOriginOf(expectedVersion) ?? engineAnchorOriginOf(expectedVersion);\n  const liveOrigin = await readRevisionOrigin(backend, schema, graphId);\n  return { expectedOrigin, liveOrigin, matches: liveOrigin === expectedOrigin };\n}\n\nfunction revisionPartsOf(\n  version: BaseVersion,\n): Readonly<{ origin: string; revision: string }> | undefined {\n  return decodeAnchorComponent(\n    REVISION_COMPONENT_PREFIX,\n    contentComponentOf(version),\n  );\n}\n\n/**\n * Extracts the second component from a `base@V` token. The schema component\n * contains no NUL byte, so the substring after the separator is exactly the\n * durable revision or compatibility content fingerprint.\n *\n * Used by both revision-token parsing and legacy in-transaction content\n * re-validation. The schema component is a pure function of the in-memory\n * graph definition, so only the second component needs runtime checking.\n */\nexport function contentComponentOf(version: BaseVersion): string {\n  const separatorIndex = (version as string).indexOf(TOKEN_SEPARATOR);\n  return separatorIndex === -1 ? version : (\n      (version as string).slice(separatorIndex + 1)\n    );\n}\n\n/**\n * Extracts the schema-hash component (including the schema-version tag when\n * present) from a `base@V` token — the substring BEFORE the separator, the\n * complement of {@link contentComponentOf}. A caller that must tell a schema\n * change from an anchor-only change — `assertForkPointUnchanged`'s\n * empty-delta acceptance for an engine anchor — compares this independently\n * of the full token rather than assuming a whole-token mismatch is always a\n * real divergence.\n */\nexport function schemaComponentOf(version: BaseVersion): string {\n  const separatorIndex = (version as string).indexOf(TOKEN_SEPARATOR);\n  return separatorIndex === -1 ? \"\" : (\n      (version as string).slice(0, separatorIndex)\n    );\n}\n\n/**\n * Extracts the monotonic active schema version baked into a revision- or\n * engine-anchored token's schema half, or `undefined` for a legacy\n * content-fallback token (which carries no {@link SCHEMA_VERSION_TAG} at\n * all — its content fingerprint covers a schema round-trip's mutated rows\n * directly, see the module doc). The document hash never contains `#s`\n * (hex digits only), so the tag position is unambiguous.\n *\n * Pairs with {@link readActiveSchemaVersion}: a caller re-validating the\n * schema half of an already-computed engine-anchored token — `merge.ts`'s\n * `assertTargetUnchanged`, which has no whole-token recomputation to lean\n * on the way `assertForkPointUnchanged` does — compares this parsed value\n * against a fresh `readActiveSchemaVersion` read instead of re-deriving the\n * split.\n */\nexport function schemaActiveVersionOf(\n  version: BaseVersion,\n): number | undefined {\n  const component = schemaComponentOf(version);\n  const tagIndex = component.indexOf(SCHEMA_VERSION_TAG);\n  if (tagIndex === -1) return undefined;\n  const parsed = Number(component.slice(tagIndex + SCHEMA_VERSION_TAG.length));\n  return Number.isFinite(parsed) ? parsed : undefined;\n}\n\n/**\n * What changed on `baseStore` after `base` was minted — the BASE-side half of\n * the pruned diff's safety argument (see `state-diff.ts`'s `diffAgainstBase`\n * and `staging.ts`'s `stageBranches`): a key absent from EITHER side's delta\n * is guaranteed identical to what the fork cloned from it, so restricting\n * enumeration to the union of both deltas is lossless. `undefined` means this\n * anchor form has no lineage `baseStore` can consult for it right now, and\n * the caller must fall back to the full diff for this side.\n *\n * Mirrors `merge.ts`'s `assertTargetUnchanged`, NOT `resolveLineage`: a\n * TypeGraph revision anchor is answered directly through the recorded\n * relations, the same way `assertTargetUnchanged` re-reads the clock\n * directly rather than going through `resolveLineage` — that selection is\n * for a store with NO TypeGraph revision anchor at all, which a\n * revision-anchored `base` can never be (see the module doc's precedence).\n * An engine anchor is answered through `resolveLineage(baseStore)` — this is\n * a PLANNING-time call, strictly outside any commit transaction, unlike\n * `assertTargetUnchanged`'s own engine branch, which reads the pinned\n * transaction handle's `lineage` instead (see that function's doc comment).\n *\n * The revision-anchor branch re-checks `assertTargetUnchanged`'s FIRST guard\n * before trusting the numeric revision at all: `revisionOriginOf(base)`\n * against `baseStore`'s LIVE origin row. This early check is no longer the\n * ONLY thing standing between a numerically coincidental anchor and\n * `changesSince` — the bundled `EngineRevision` `recordedRelationsLineage`\n * mints also embeds this same origin, and `changesSince` re-verifies it on\n * whatever session it is given (see that module's own doc, \"Token identity\n * is scoped to one graph, not one physical store\") — but it stays: it is\n * the cheap early exit that avoids a wasted `changesSince` round trip when\n * the branch clearly forked from an unrelated store, and it is what lets\n * this function reuse `originMatch.liveOrigin` below rather than reading\n * the origin a second time. `encodeRecordedLineageRevision` re-derives the\n * SAME bundled grammar `revision()` mints from the token's already-parsed\n * origin and revision components, rather than asking `recordedRelationsLineage`\n * for a fresh reading — `base`'s revision anchor is a specific PAST\n * revision, not \"now\".\n *\n * A revision-anchored `base` minted before `baseStore` ever advanced its\n * clock parses to `revisionAnchorOf(base) === undefined` (the \"initial\"\n * sentinel) even though {@link hasRevisionAnchor} is true for it; this\n * function returns `undefined` for that case too (falls back to the full\n * diff) rather than resolving a genesis token, which costs nothing in\n * practice — a store forked before its first tracked write has no rows to\n * enumerate on the base side either.\n */\nexport async function lineageDeltaSinceAnchor<G extends GraphDef>(\n  baseStore: Store<G>,\n  base: BaseVersion,\n): Promise<LineageDelta | undefined> {\n  const revisionAnchor = revisionAnchorOf(base);\n  if (revisionAnchor !== undefined) {\n    // `recordedRelationsLineage` below reads TypeGraph's own recorded\n    // relations directly, so this gate is `storeCaptureEnabled`, not the\n    // public `historyEnabled` getter — a revision anchor is a TypeGraph-\n    // owned token to begin with, but an engine-native store's `history:\n    // true` must still fall back to the full diff here rather than reading\n    // relations the engine never populates.\n    if (!storeCaptureEnabled(baseStore)) return undefined;\n    const originMatch = await revisionOriginMatch(\n      storeBackend(baseStore),\n      baseStore.revisionSchema,\n      baseStore.graphId,\n      base,\n    );\n    if (!originMatch.matches || originMatch.liveOrigin === undefined) {\n      return undefined;\n    }\n    return recordedRelationsLineage(baseStore).changesSince(\n      storeBackend(baseStore),\n      encodeRecordedLineageRevision(originMatch.liveOrigin, revisionAnchor),\n      baseStore.graphId,\n    );\n  }\n  const engineAnchor = engineAnchorOf(base);\n  if (engineAnchor === undefined) return undefined;\n  // Same origin re-check as the revision-anchor branch above, and for the\n  // same reason: the engine anchor's numeric-looking revision is meaningless\n  // against a `baseStore` whose own origin row does not match the one\n  // `base` was minted with — see `revisionOriginMatch`'s doc.\n  const engineOriginMatch = await revisionOriginMatch(\n    storeBackend(baseStore),\n    baseStore.revisionSchema,\n    baseStore.graphId,\n    base,\n  );\n  if (!engineOriginMatch.matches) return undefined;\n  const lineage = resolveLineage(baseStore);\n  if (lineage === undefined) return undefined;\n  // PLANNING-time call, strictly outside any commit transaction: the root\n  // backend `baseStore` holds is the only session available, and the same\n  // object `resolveLineage(baseStore)` resolved `lineage` off of.\n  return lineage.changesSince(\n    storeBackend(baseStore),\n    engineAnchor,\n    baseStore.graphId,\n  );\n}\n","/**\n * Pluggable working-copy strategy: how `branch()` produces an isolated,\n * independently-mutable copy of a base store.\n *\n * The P0 default is a faithful CLONE via streamed public interchange\n * ({@link cloneWorkingCopyStrategy}): `exportGraphStream` the base, then\n * `importGraphStream` into a fresh store on a caller-provided backend. IDs are\n * preserved by interchange, so the diff engine (T3) can key on stable ids across\n * base and fork. This leverages public entrypoints only, needs zero schema\n * changes, and behaves identically across SQLite and Postgres.\n *\n * INTERCHANGE FIDELITY LIMITATION (verified, design §13.x): the interchange\n * `meta` schema has no `deletedAt` field, so a base row that is already\n * soft-deleted would round-trip into the clone as LIVE (its tombstone lost). A\n * resurrected row would then read as a spurious `new` node in the fork's diff —\n * the base row is non-live, so `diffNodeKind` takes its `!isLive(base)` branch and\n * reports the (live, clone-resurrected) row as an addition — silently re-creating a\n * deleted node on commit. We therefore export with `includeDeleted: false`: the\n * clone carries only the base's LIVE state, exactly what `branch()` needs. The\n * merge state-diff is still computed against the ORIGINAL base store (live rows\n * only) as the immutable reference, never against the clone (clones regenerate\n * `created_at`/`updated_at`, which would otherwise destabilize `base@V`).\n *\n * `includeTemporal: true` carries `validFrom`/`validTo` through unchanged,\n * preserving the base's exact valid-time window on the clone: create-time\n * paths default an omitted `validFrom` to the row's own creation instant\n * (see #240) — except for a BORN-ENDED row, whose stated `validTo` at or before\n * the write instant leaves it with no lower bound at all (see #407) — and\n * export/import round-trip a still-open-left `valid_from` (a born-ended row, or\n * one that predates the #240 fix) as an explicit `null` rather than silently\n * dropping it — see `InterchangeNodeSchema.validFrom`'s doc.\n * Without either half of this, the clone's re-import would re-stamp the\n * affected base rows to the CLONE's creation instant instead — narrowing\n * their validity window and making `asOf` reads on the fork diverge from\n * identical reads on the base for any instant between the row's real\n * creation and the clone.\n *\n * Undeclared properties are the same class of stored live state.\n * `validateStore()` treats them as healthy semi-structured data. The clone\n * therefore imports with `onUnknownProperty: \"allow\"` — interchange's\n * fidelity-preserving strategy — so those keys survive the round trip.\n * `\"error\"` would refuse to branch a graph analysis already reports as clean.\n * `\"strip\"` would drop the keys on the fork, and the merge diff against the\n * original base would invent deletions the caller never made.\n *\n * Logical-namespace (copy-on-write within one backend, no full data copy) is a\n * future strategy slot — see the `WorkingCopyStrategy` interface — deferred past\n * P0.\n *\n * A second bundled strategy, {@link forkedWorkingCopyStrategy}, targets a\n * fork-capable host instead: the working copy is a database-level fork (a file\n * copy, a `CREATE DATABASE ... TEMPLATE`, a hosting product's branch call)\n * rather than a streamed-interchange replay, so none of the fidelity\n * limitations above apply to it — see its own doc comment.\n */\n\nimport { computeBaseVersion } from \"./base-version\";\nimport { BranchError } from \"./errors\";\nimport type {\n  GraphBackend,\n  GraphDef,\n  ResolvedSqlTableNames,\n  Store,\n  StoreOptions,\n} from \"./typegraph-internal\";\nimport {\n  createSqlSchema,\n  createStore,\n  createStoreWithSchema,\n  exportGraph,\n  exportGraphStream,\n  importGraph,\n  importGraphStream,\n  isBackendDerivedFrom,\n  sharesSerializedTransactionResource,\n  snapshotExportContention,\n  storeBackend,\n  summarizeImportErrors,\n  wrapWithManagedClose,\n} from \"./typegraph-internal\";\nimport type { BaseVersion } from \"./types\";\n\n/**\n * Batch size for the clone's `importGraphStream` pass. Large enough to keep\n * round-trips low on demo-scale graphs; correctness is independent of the value.\n */\nconst CLONE_IMPORT_BATCH_SIZE = 1000;\n\n/**\n * How `branch()` materializes a working copy of a base store.\n *\n * `create` receives the live base store and the {@link BaseVersion} `branch()`\n * already stamped off it, and returns a fresh, independently mutable\n * {@link Store} over the SAME graph definition, seeded with the base's current\n * state. Mutating the returned store MUST NOT affect the base.\n *\n * `base` is a convenience for a strategy that needs to re-validate the\n * working copy against the exact token the branch records: {@link forkedWorkingCopyStrategy}\n * fences the fork against it instead of recomputing the base's own version a\n * second time. A strategy that has no such check (the clone strategy, which\n * builds its working copy directly from `baseStore` rather than from an\n * independent copy) can ignore the parameter.\n *\n * The single method is the only extension point: alternative strategies\n * (e.g. a future logical-namespace copy-on-write within one backend) implement\n * the same contract.\n */\nexport type WorkingCopyStrategy<G extends GraphDef> = Readonly<{\n  create: (baseStore: Store<G>, base: BaseVersion) => Promise<Store<G>>;\n}>;\n\n/**\n * Factory for a caller-provided backend. `branch()` stays backend-agnostic by\n * delegating backend construction to the caller: the clone strategy calls this\n * once per `create()` to obtain the fresh backend that backs the working copy.\n *\n * Returning a promise lets async backends (e.g. PGlite, which boots an\n * in-process Postgres engine) be constructed lazily at branch time.\n *\n * The returned backend MUST be EMPTY (no rows for the base graph): the clone\n * seeds it from the base via `importGraphStream` with `onConflict: \"error\"`, so a\n * pre-existing row is surfaced as a {@link BranchError} rather than silently\n * skipped (which would leave the working copy diverging from the base).\n * When the source store uses `revisionTracking`, the backend must also satisfy\n * that option's transactional revision-clock requirements because the clone\n * preserves the source's branchability contract.\n */\nexport type MakeBackend = () => Promise<GraphBackend>;\n\n/**\n * Proves that a host-created working copy was taken from the exact `base@V`\n * TypeGraph stamped before asking the host to fork it.\n *\n * This is the single owner of the post-fork equality decision. Host-native fork\n * calls are allowed to race with a write to the source branch; trusting the\n * requested base token would then relabel a newer or older snapshot as the\n * requested one. Ephemeral host forks call this after opening the created store\n * and refuse before handing the working copy to a caller.\n */\nasync function assertWorkingCopyMatchesBase<G extends GraphDef>(\n  workingCopy: Store<G>,\n  base: BaseVersion,\n): Promise<void> {\n  const workingCopyVersion = await computeBaseVersion(workingCopy);\n  if (workingCopyVersion === base) return;\n  throw new BranchError(\n    \"Working copy does not match its base: computeBaseVersion disagrees \" +\n      \"between the host-created store and the base store it was forked \" +\n      \"from. The host may have forked a different revision or the source \" +\n      \"may have advanced while the fork was being allocated.\",\n    { details: { workingCopyVersion, baseVersion: base } },\n  );\n}\n\n/**\n * The P0 default working-copy strategy: faithful clone via streamed interchange.\n *\n * On each `create(baseStore)`:\n *   1. `exportGraphStream(baseStore, { includeMeta: true, includeTemporal: true,\n *      includeDeleted: false })` — `includeMeta: true` carries\n *      `created_at`/`updated_at`; `includeTemporal: true` carries\n *      `validFrom`/`validTo` so the clone's valid-time window matches the base's\n *      exactly (see the fidelity note above); `includeDeleted: false` keeps the\n *      clone to LIVE rows only. Shipping soft-deleted rows is unsafe: the meta\n *      schema has no `deletedAt`, so they would import as live and resurrect on\n *      the fork's diff (see the fidelity note above). `branch()` only needs the\n *      base's live state.\n *   2. Create a fresh store over the caller-provided backend with the SAME graph\n *      definition via `createStoreWithSchema`.\n *   3. `importGraphStream(freshStore, data, { onConflict: \"error\",\n *      onUnknownProperty: \"allow\", ... })` — ids are preserved so the diff\n *      engine can key on them. `onConflict: \"error\"` requires the backend to be\n *      EMPTY: a pre-existing row is a contract violation that must surface\n *      loudly, never be silently skipped (a skipped row would leave the clone\n *      diverging from the base, so the fork's diff would report phantom\n *      modifications/deletions). `onUnknownProperty: \"allow\"` carries undeclared\n *      properties through (see the fidelity note above). A streamed chunk that\n *      reports per-row errors throws (default `onStreamChunkError: \"abort\"`); a\n *      materialized import returns `{ success, errors }`. Either failure fails\n *      the branch.\n *\n * The backend `makeBackend()` returns is opened here, so any failure AFTER it is\n * created closes it before rethrowing — only the success path hands the backend\n * (via the returned store) to the caller, who then owns its lifecycle.\n *\n * @param makeBackend - Constructs the fresh, EMPTY backend the working copy is\n *   built on.\n */\nexport function cloneWorkingCopyStrategy<G extends GraphDef>(\n  makeBackend: MakeBackend,\n): WorkingCopyStrategy<G> {\n  return cloneWorkingCopyWithGraphStrategy(\n    makeBackend,\n    (baseStore) => baseStore.graph,\n  );\n}\n\n/**\n * Working-copy strategy used by {@link ingestionBranch}. The clone is backed by\n * a mechanically-derived graph that omits node uniqueness declarations while\n * preserving every other graph contract, including lookup indexes.\n *\n * This strategy is deliberately not part of the public barrel. The opaque\n * ingestion handle is the only supported owner of a relaxed working copy.\n */\nexport function cloneIngestionWorkingCopyStrategy<G extends GraphDef>(\n  makeBackend: MakeBackend,\n): WorkingCopyStrategy<G> {\n  return cloneWorkingCopyWithGraphStrategy(makeBackend, (baseStore) =>\n    graphWithoutNodeUniqueness(baseStore.graph),\n  );\n}\n\nfunction cloneWorkingCopyWithGraphStrategy<G extends GraphDef>(\n  makeBackend: MakeBackend,\n  graphForClone: (baseStore: Store<G>) => G,\n): WorkingCopyStrategy<G> {\n  return {\n    create: async (baseStore: Store<G>): Promise<Store<G>> => {\n      const backend = await makeBackend();\n      try {\n        const [freshStore] = await createStoreWithSchema(\n          graphForClone(baseStore),\n          backend,\n          {\n            // Keep descendants branchable with the same O(1) anchor contract,\n            // but do not copy recorded-time history into the disposable fork.\n            //\n            // Deliberately narrower than Store.workingCopyOptions (the full\n            // set a fork inherits, see forkStoreOptions): the clone's backend\n            // is a FRESH, empty database, not a physical copy of the base's,\n            // so a `schema` naming the base's tables would misdirect writes\n            // on an unrelated backend, and an external `recordedRead`\n            // binding would point at a relation the clone never populates.\n            // Hooks, `coalesceUnchangedUpserts`, `autoRefreshStatistics` and\n            // `queryDefaults` carry no such physical assumption, but the\n            // clone strategy is used for host-agnostic P0 branching where the\n            // caller's `makeBackend` factory — not the base's own\n            // configuration — owns the fresh store's behavior; only the\n            // branchability contract (`revisionTracking`) is load-bearing\n            // enough to thread through unconditionally.\n            revisionTracking: baseStore.revisionTrackingEnabled,\n          },\n        );\n        const exportOptions = {\n          includeMeta: true,\n          includeTemporal: true,\n          includeDeleted: false,\n          batchSize: CLONE_IMPORT_BATCH_SIZE,\n        } as const;\n        const importOptions = {\n          onConflict: \"error\",\n          onUnknownProperty: \"allow\",\n          validateReferences: true,\n          batchSize: CLONE_IMPORT_BATCH_SIZE,\n        } as const;\n        // When the fresh backend writes through the connection the base's\n        // snapshot export would hold, streaming is exactly what the import\n        // guard refuses — so ask that guard's own predicate, and materialize\n        // the export instead of streaming it when it says so.\n        const result =\n          (\n            snapshotExportContention(\n              storeBackend(baseStore),\n              storeBackend(freshStore),\n            ) === undefined\n          ) ?\n            await importGraphStream(\n              freshStore,\n              exportGraphStream(baseStore, exportOptions),\n              importOptions,\n            )\n          : await importGraph(\n              freshStore,\n              await exportGraph(baseStore, exportOptions),\n              importOptions,\n            );\n        if (!result.success) {\n          throw new BranchError(\n            `Clone import failed: the working copy could not be seeded from the base store. ${summarizeImportErrors(result.errors)}`,\n            { details: { errors: result.errors } },\n          );\n        }\n        return freshStore;\n      } catch (error) {\n        // The backend was opened above; close it on any failure so its\n        // connection / file handle / in-process engine cannot leak. A close\n        // failure must not mask the original error.\n        try {\n          await backend.close();\n        } catch {\n          // Intentionally ignored — surface the original branch failure.\n        }\n        throw error;\n      }\n    },\n  };\n}\n\n/**\n * A host-level handle to a forked database, produced by\n * {@link ForkedWorkingCopyOptions.fork} and released by its own `dispose`.\n *\n * `dispose` is OPTIONAL: some hosts have nothing left to release beyond the\n * connection `connect` opens on the fork (already composed into the returned\n * working copy's backend — see {@link forkedWorkingCopyStrategy}), while others\n * (a temporary file, a database created for this fork alone) need an explicit\n * teardown.\n */\nexport type ForkHandle = Readonly<{\n  dispose?: () => Promise<void>;\n}>;\n\n/**\n * Configuration for {@link forkedWorkingCopyStrategy}.\n */\nexport type ForkedWorkingCopyOptions<\n  G extends GraphDef,\n  TFork extends ForkHandle,\n> = Readonly<{\n  /**\n   * Produces a host-level fork of the database `baseStore` is on — the\n   * caller's own fork API call (a file copy, a `CREATE DATABASE ... TEMPLATE`,\n   * a hosting product's branch-database call). The fork MUST be the base at\n   * the instant it is taken: `create()` asserts this by comparing\n   * `computeBaseVersion` between the fork and the base and refuses otherwise\n   * (see {@link forkedWorkingCopyStrategy}). That comparison proves base-token\n   * equality (schema plus a revision anchor, or a live-content fingerprint) —\n   * see `computeBaseVersion`'s own doc comment for exactly what it does and\n   * does not cover — not a byte-for-byte audit of the fork; the FORK\n   * MECHANISM is what is trusted for physical fidelity.\n   */\n  fork: (baseStore: Store<G>) => Promise<TFork>;\n  /**\n   * Opens a backend on the fork `fork` produced. The returned backend MUST be\n   * an INDEPENDENT connection, never the base's own backend or one that\n   * shares its connection: `create()` refuses before wrapping when the\n   * connected backend is `===` the base's backend, is derived from it (or it\n   * from the connected backend) through `deriveBackend`, or shares its\n   * serialized transaction resource (two wrappers over the same underlying\n   * connection) — see {@link forkedWorkingCopyStrategy}'s aliasing check. This\n   * catches a `connect` that mistakenly hands back a cached factory's\n   * existing backend; it CANNOT catch a fresh backend built over the base's\n   * own connection pool when that pool audits as independent (a default-size\n   * `pg.Pool`, for example) — a pooled checkout is genuinely a different\n   * connection from the pool's perspective, so nothing here can tell it apart\n   * from a real fork's connection short of the caller's own knowledge of\n   * their topology.\n   *\n   * The returned backend's own table bindings (`backend.tableNames`) MUST\n   * also agree with the base's resolved SQL schema (`baseStore.revisionSchema`\n   * — the same schema the fork's store resolves to via\n   * {@link forkStoreOptions}). A fork is the SAME physical database as the\n   * base, so this is normally automatic (a backend factory bound to the\n   * base's custom names, if any, opens correctly on the fork too); `create()`\n   * still checks it and refuses with a {@link BranchError}, closing the\n   * backend first, when the two disagree — a backend bound to the wrong table\n   * names reads and writes through tables the fork's rows were never written\n   * to.\n   */\n  connect: (fork: TFork) => Promise<GraphBackend>;\n}>;\n\n/**\n * Store options for a forked working copy: the base's WHOLE option set —\n * hooks, upsert coalescing, the SQL schema, the auto-refresh-statistics\n * threshold, query defaults, and an externally-bound recorded-read relation,\n * read once through {@link Store.workingCopyOptions} — plus `history`/\n * `revisionTracking`, decided the same way {@link cloneWorkingCopyStrategy}\n * decides `revisionTracking`: read off `baseStore`'s own public getters.\n *\n * A fork is the SAME physical database as the base, so every one of those\n * inherited options is safe to carry over unchanged: custom table names in\n * `schema` name relations that physically exist in the fork; an external\n * `recordedRead` binding points at a relation the fork carries too (unlike a\n * clone's fresh, empty backend, which would need that relation populated\n * from scratch); hooks and the behavioral flags are pure JavaScript-side\n * configuration with no dependency on which physical database they run\n * against. A fork's recorded-time relations are already physically present\n * on the copied database (unlike a clone's, which streamed interchange\n * cannot carry), so `history: true` is threaded through here where the clone\n * strategy deliberately withholds it (see its own fidelity note).\n *\n * `recordedRead` is split out before the `history` branch below: `history:\n * true` and an external `recordedRead` binding are mutually exclusive at\n * Store construction (the constructor throws `ConfigurationError` for that\n * combination), so a base with `historyEnabled` never carries one to inherit\n * — there is nothing to drop, only an invariant to preserve.\n */\nfunction forkStoreOptions<G extends GraphDef>(\n  baseStore: Store<G>,\n): StoreOptions {\n  const { recordedRead, ...inherited } = baseStore.workingCopyOptions;\n  if (baseStore.historyEnabled) {\n    return { ...inherited, history: true };\n  }\n  return {\n    ...inherited,\n    revisionTracking: baseStore.revisionTrackingEnabled,\n    ...(recordedRead === undefined ? {} : { recordedRead }),\n  };\n}\n\n/**\n * Whether two resolved table-name sets name the exact same physical tables,\n * field by field.\n */\nfunction resolvedTableNamesEqual(\n  a: ResolvedSqlTableNames,\n  b: ResolvedSqlTableNames,\n): boolean {\n  const keys = new Set([...Object.keys(a), ...Object.keys(b)]) as Set<\n    keyof ResolvedSqlTableNames\n  >;\n  return [...keys].every((key) => a[key] === b[key]);\n}\n\n/**\n * Whether `connectedBackend` aliases `baseStore`'s own backend rather than\n * naming an independent connection to the fork — the ONE decision every arm\n * of {@link forkedWorkingCopyStrategy}'s aliasing refusal reduces to; nothing\n * else in this module re-derives it.\n *\n * Three ways two backend objects can turn out to be the SAME underlying\n * connection even though `connect()` believes it opened a fresh one:\n *\n *   - Object identity: `connect()` returned the base's own backend outright\n *     (e.g. a cached factory keyed by database name that returns the base's\n *     backend for any fork of that database).\n *   - Derivation lineage, in EITHER direction, through `deriveBackend`\n *     (`isBackendDerivedFrom`): a decorator built from the base's backend, or\n *     the base's backend built from what `connect()` returned.\n *   - A shared serialized transaction resource\n *     (`sharesSerializedTransactionResource`): two independently-constructed\n *     wrapper objects whose statements land on the SAME underlying\n *     connection — two `createSqliteBackend` calls over one `Database`\n *     handle, for example. `src/backend/transaction-resource.ts` is the\n *     existing owner of \"two wrappers on one connection\"; this reuses it\n *     rather than re-deriving it.\n *\n * Deliberately NOT exhaustive — see {@link ForkedWorkingCopyOptions.connect}'s\n * doc comment for the one aliasing shape none of these three arms can see: a\n * fresh backend built over the base's own connection POOL, when that pool\n * audits as independent (the normal case for a default-size `pg.Pool`). A\n * pooled checkout genuinely is a different connection from the pool's own\n * perspective, so there is nothing here to detect.\n */\nfunction forkAliasesBase<G extends GraphDef>(\n  connectedBackend: GraphBackend,\n  baseStore: Store<G>,\n): boolean {\n  const baseBackend = storeBackend(baseStore);\n  return (\n    connectedBackend === baseBackend ||\n    isBackendDerivedFrom(connectedBackend, baseBackend) ||\n    isBackendDerivedFrom(baseBackend, connectedBackend) ||\n    sharesSerializedTransactionResource(connectedBackend, baseBackend)\n  );\n}\n\n/**\n * The branch handle's `close`: releases the working copy's backend once,\n * however many times and however concurrently it is called. The\n * `GraphBackend` contract does not require an idempotent `close`, so the\n * handle coalesces concurrent calls onto the in-flight release and treats a\n * completed release as final, rather than relying on the backend (a forked\n * working copy's composed close, or a caller-built backend from\n * `MakeBackend`) tolerating a second release.\n *\n * A FAILED release is not final: the in-flight promise is dropped on\n * rejection so the next call attempts the cleanup again — a composed close\n * retries the teardown phases that did not complete, and caching the\n * rejection would hide that retry and leave a host-level fork orphaned\n * after a transient failure.\n */\nexport function coalescedWorkingCopyClose<G extends GraphDef>(\n  store: Store<G>,\n): () => Promise<void> {\n  let closed = false;\n  let inFlight: Promise<void> | undefined;\n  return async () => {\n    if (closed) return;\n    inFlight ??= storeBackend(store)\n      .close()\n      .then(() => {\n        closed = true;\n      })\n      .finally(() => {\n        inFlight = undefined;\n      });\n    await inFlight;\n  };\n}\n\n/**\n * Working-copy strategy for a fork-capable host: `fork(baseStore)` asks the\n * host to produce a complete, independent copy of the underlying database —\n * not a public-interchange replay — and `connect(fork)` opens a backend on\n * that copy.\n *\n * Unlike {@link cloneWorkingCopyStrategy}, the working copy is never built\n * through `exportGraphStream`/`importGraphStream`, so none of that strategy's\n * interchange-fidelity limitations apply here: soft-deleted rows keep their\n * tombstones, `created_at`/`updated_at` and the `version` column carry over\n * unchanged, and — when the base has `history` enabled — the recorded\n * relations the fork physically carries answer `asOfRecorded` for instants\n * before the fork, which a clone cannot (streamed interchange never carries\n * recorded history).\n *\n * `create(baseStore, base)`:\n *   1. `fork(baseStore)` — the host-level fork call.\n *   2. `connect(fork)` — opens a backend on the fork. A failure here disposes\n *      the fork before rethrowing (mirroring the clone strategy's\n *      own-failure cleanup); a dispose failure never masks the original\n *      error.\n *   3. The connected backend is checked for ALIASING the base's own backend\n *      by `forkAliasesBase` — object identity with the base's backend,\n *      derivation lineage in either direction (`isBackendDerivedFrom`), or a\n *      shared serialized transaction resource\n *      (`sharesSerializedTransactionResource`, `transaction-resource.ts`'s\n *      existing owner of \"two wrappers on one connection\"). Without this, a\n *      `connect()` that hands back the base's own backend (a cached factory\n *      keyed by database name, say) would pass every later fence — the\n *      table-name check, the base@V check both trivially agree with\n *      themselves — while every fork write actually mutates the base and\n *      closing the \"fork\" actually closes the base. An alias refuses BEFORE\n *      wrapping: only the fork is disposed (never the connected backend — it\n *      is the base's) before `create()` throws a {@link BranchError} naming\n *      `connect()`.\n *   4. The connected backend's `close` is composed with the fork's `dispose`\n *      through `wrapWithManagedClose` (a `deriveBackend` overlay, never a\n *      spread), so the caller's single `close()` on the resulting store's\n *      backend releases both the connection and the fork.\n *   5. `baseStore.revisionSchema` — the base's own resolved SQL schema getter\n *      (an explicit `schema` option, or `backend.tableNames` otherwise; never\n *      re-derived by hand here) — is compared, table by table, against\n *      `createSqlSchema(connectedBackend.tableNames)`. A fork is the same\n *      physical database as the base, so a backend bound to different table\n *      names — typically the defaults, when `connect()` did not reconstruct\n *      the base's custom bindings — would read and write through tables the\n *      fork's rows were never written to. A mismatch closes the backend\n *      (releasing both the connection and the fork) before refusing with a\n *      {@link BranchError}.\n *   6. A fresh `Store` is attached with `createStore` — a zero-DDL attach,\n *      since the fork already carries the base's schema and rows — using\n *      {@link forkStoreOptions}.\n *   7. `computeBaseVersion(forkStore)` is compared against `base` — the\n *      token `branch()` already stamped off the ORIGINAL base store, passed\n *      in rather than recomputed here: comparing against the caller's own\n *      token (instead of a second, independently computed one) means an\n *      untracked base's content fingerprint is computed exactly once per\n *      branch. Equality here proves base-token equality — schema plus a\n *      revision anchor, or a live-content fingerprint — at the instant the\n *      fork was taken; it is NOT a byte-for-byte physical audit (see\n *      {@link ForkedWorkingCopyOptions.fork}'s doc comment for what the\n *      fingerprint deliberately omits and why that is the fork mechanism's\n *      contract, not this assertion's). A mismatch closes the backend\n *      (releasing both the connection and the fork, mirroring step 5's\n *      composition) before refusing with a {@link BranchError}.\n *\n * @param options - `{ fork, connect }` — see {@link ForkedWorkingCopyOptions}.\n */\nexport function forkedWorkingCopyStrategy<\n  G extends GraphDef,\n  TFork extends ForkHandle,\n>(options: ForkedWorkingCopyOptions<G, TFork>): WorkingCopyStrategy<G> {\n  return {\n    create: async (\n      baseStore: Store<G>,\n      base: BaseVersion,\n    ): Promise<Store<G>> => {\n      const fork = await options.fork(baseStore);\n      let connectedBackend: GraphBackend;\n      try {\n        connectedBackend = await options.connect(fork);\n      } catch (error) {\n        try {\n          await fork.dispose?.();\n        } catch {\n          // Intentionally ignored — surface the original connect failure.\n        }\n        throw error;\n      }\n      if (forkAliasesBase(connectedBackend, baseStore)) {\n        // The connected backend IS the base's own backend (or shares its\n        // connection) — never close it here, the base still owns it and\n        // still needs it. Only the fork itself (the host-level handle,\n        // never a connection) is released.\n        try {\n          await fork.dispose?.();\n        } catch {\n          // Intentionally ignored — surface the aliasing refusal below.\n        }\n        throw new BranchError(\n          \"Fork backend aliases its base: connect() returned the base \" +\n            \"store's own backend instead of an independent connection to \" +\n            \"the fork — directly (the same backend object), through \" +\n            \"backend derivation, or through a connection the two backends \" +\n            \"share. Writing to this working copy would mutate the base, \" +\n            \"and closing it would close the base's own backend.\",\n        );\n      }\n      const backend = wrapWithManagedClose(connectedBackend, async () => {\n        await fork.dispose?.();\n      });\n      try {\n        const forkOptions = forkStoreOptions(baseStore);\n        // baseStore.revisionSchema is the SAME resolved-schema getter every\n        // other consumer of a store's table names reads (an explicit\n        // `schema` option, or backend.tableNames otherwise) — never a\n        // hand-rolled fallback. Comparing forkOptions.schema directly\n        // against a bare `createSqlSchema()` default would compare DEFAULTS\n        // against the fork's real table names whenever a base's custom\n        // names come only from its backend factory, with no explicit\n        // `schema` option (see tests/custom-table-names.test.ts).\n        const inheritedTables = baseStore.revisionSchema.tables;\n        const connectedTables = createSqlSchema(\n          connectedBackend.tableNames,\n        ).tables;\n        if (!resolvedTableNamesEqual(inheritedTables, connectedTables)) {\n          throw new BranchError(\n            \"Fork backend does not bind the base's table names: connect() \" +\n              \"returned a backend whose own table bindings disagree with \" +\n              \"the SQL schema this fork inherits from its base. A fork is \" +\n              \"the SAME physical database as the base, so a backend bound \" +\n              \"to different (often just the default) table names reads and \" +\n              \"writes through tables the fork's rows were never written to.\",\n            { details: { inheritedTables, connectedTables } },\n          );\n        }\n        const forkStore = createStore(baseStore.graph, backend, forkOptions);\n        await assertWorkingCopyMatchesBase(forkStore, base);\n        return forkStore;\n      } catch (error) {\n        try {\n          await backend.close();\n        } catch {\n          // Intentionally ignored — surface the original branch failure.\n        }\n        throw error;\n      }\n    },\n  };\n}\n\n/**\n * Derives the honest persisted schema for an ingestion working copy.\n *\n * The graph's node and edge types are unchanged, so retaining `G` is sound for\n * collection inputs and outputs. Only the registrations' node uniqueness slice\n * is removed. Extension documents are rewritten too: they are the durable\n * source used to reconstruct extension kinds on reload, so leaving their\n * declarations intact would silently restore uniqueness after a restart.\n *\n * What \"node uniqueness is deferred\" means at the level the store enforces it:\n * a row's reservations are whatever\n * {@link file://../store/claims/node-claims.ts nodeClaimEntries} says its kind\n * owes, and `unique` is the ONLY input to that list's uniqueness family. So\n * removing it removes exactly the uniqueness claim entries and nothing else —\n * the disjointness entries the same list carries come from the registry's\n * declared pairs, which this derivation does not touch, and they stay enforced\n * on the clone during staging. `tests/graph-merge/ingestion-branch.test.ts`\n * asserts that split through `nodeClaimEntries` itself rather than restating it.\n */\nfunction graphWithoutNodeUniqueness<G extends GraphDef>(graph: G): G {\n  const nodes = Object.fromEntries(\n    Object.entries(graph.nodes).map(([name, registration]) => {\n      const { unique: _omitted, ...withoutUnique } = registration;\n      return [name, Object.freeze(withoutUnique)] as const;\n    }),\n  );\n  const extension =\n    graph.extension?.nodes === undefined ?\n      graph.extension\n    : Object.freeze({\n        ...graph.extension,\n        nodes: Object.freeze(\n          Object.fromEntries(\n            Object.entries(graph.extension.nodes).map(([name, node]) => {\n              const { unique: _omitted, ...withoutUnique } = node;\n              return [name, Object.freeze(withoutUnique)] as const;\n            }),\n          ),\n        ),\n      });\n\n  // `G`'s data types are unchanged. Its registration-level constraint-name\n  // phantom is intentionally retained so branch nodes remain assignable to the\n  // canonical graph's merge types; the ingestion handle omits constraint lookup\n  // methods whose declarations no longer exist physically.\n  return Object.freeze({\n    ...graph,\n    nodes: Object.freeze(nodes),\n    extension,\n  });\n}\n","/**\n * `branch()` — fork an isolated, independently-mutable working copy of a base\n * store (design §7.1).\n *\n * A branch is a {@link GraphBranch}: a fresh {@link BranchId}, the immutable\n * `base@V` token the copy forked from (computed off the ORIGINAL base store via\n * {@link computeBaseVersion}, never off the clone), a {@link Store} over the\n * branch's own backend seeded with the base's live state, and — when the\n * working copy resolves a `lineage` source — the fork-time engine revision\n * (`forkRevision`) that anchors this branch's half of the pruned merge diff.\n *\n * The copy mechanism is pluggable behind {@link WorkingCopyStrategy}. The P0\n * default is the faithful streamed-interchange clone\n * ({@link cloneWorkingCopyStrategy}),\n * which keeps this primitive backend-agnostic: the caller supplies a\n * `makeBackend` factory, and `branch()` never names a concrete backend.\n */\n\nimport { computeBaseVersion } from \"./base-version\";\nimport { BranchError } from \"./errors\";\nimport type { Result } from \"./result\";\nimport { err, ok } from \"./result\";\nimport type { EngineRevision, GraphDef } from \"./typegraph-internal\";\nimport { generateId, resolveLineage, storeBackend } from \"./typegraph-internal\";\nimport type { BranchOptions, GraphBranch } from \"./types\";\nimport { asBranchId } from \"./types\";\nimport type { MakeBackend, WorkingCopyStrategy } from \"./working-copy\";\nimport {\n  cloneWorkingCopyStrategy,\n  coalescedWorkingCopyClose,\n} from \"./working-copy\";\n\n/**\n * Creates an isolated working-copy branch of `baseStore`.\n *\n * Stamps the `base@V` token off the original base store, mints (or accepts) a\n * {@link BranchId}, and materializes the working copy via the resolved strategy.\n * The default strategy is a faithful clone over a fresh backend produced by\n * `makeBackend`; pass an explicit `strategy` to override (e.g. a future\n * logical-namespace copy-on-write).\n *\n * Returns a {@link Result}: success yields the {@link GraphBranch}; any failure\n * (base-version stamping, backend construction, streamed interchange) is wrapped in a\n * {@link BranchError} with the underlying cause attached. Errors are returned,\n * never thrown — this is internal-logic surface (the caller converts to a thrown\n * error at the framework boundary).\n *\n * @param baseStore - The store to fork. Remains untouched.\n * @param makeBackend - Factory for the working copy's backend (keeps the\n *   primitive backend-agnostic). Used only by the default clone strategy; ignored\n *   when an explicit `strategy` is supplied.\n * @param options - Optional `{ id }` to set an explicit branch id.\n * @param strategy - Optional working-copy strategy override.\n */\nexport async function branch<G extends GraphDef>(\n  baseStore: GraphBranch<G>[\"store\"],\n  makeBackend: MakeBackend,\n  options?: BranchOptions,\n  strategy?: WorkingCopyStrategy<G>,\n): Promise<Result<GraphBranch<G>, BranchError>> {\n  try {\n    const base = await computeBaseVersion(baseStore);\n    const id = options?.id ?? asBranchId(generateId());\n    const workingCopyStrategy =\n      strategy ?? cloneWorkingCopyStrategy<G>(makeBackend);\n    const store = await workingCopyStrategy.create(baseStore, base);\n    // Ownership of the working copy's BACKEND transferred here: the strategy\n    // closes it only on its own failures, and \"only the success path hands the\n    // backend to the caller, who then owns its lifecycle\" (see\n    // `cloneWorkingCopyStrategy`). Everything after this line therefore runs\n    // inside `captureBranchForkState`, which closes it before failing — a\n    // `branch()` that returned `err(...)` from here would drop the only handle to a live\n    // engine (a PGlite instance, a file handle, a connection pool).\n    const { schemaAnchor, forkRevision } = await captureBranchForkState(store);\n    return ok({\n      id,\n      base,\n      store,\n      close: coalescedWorkingCopyClose(store),\n      ...(schemaAnchor === undefined ?\n        { schemaAnchor: undefined }\n      : { schemaAnchor }),\n      ...(forkRevision === undefined ? {} : { forkRevision }),\n    });\n  } catch (error) {\n    return err(\n      new BranchError(\"Failed to create working-copy branch of base store\", {\n        cause: error,\n      }),\n    );\n  }\n}\n\n/**\n * Captures the clone's fork-time state: the committed schema row (the\n * merge-time drift anchor — version participates so a schema ROUND-TRIP\n * (migrate away and back, restoring the document hash while its preflights\n * mutated rows) is still detected) and, when the working copy resolves a\n * `lineage` source, the engine revision it reports right after the clone\n * completes and before any write — the baseline the pruned diff (see\n * `state-diff.ts`'s `diffAgainstBase` and `staging.ts`'s `stageBranches`)\n * measures the fork's OWN changes against. `resolveLineage` runs on the\n * WORKING COPY here, never the original `baseStore`: the fork's delta is\n * \"what this clone itself has done since it was made,\" a question only the\n * clone's own lineage can answer. `undefined` when the working copy resolves\n * no lineage at all (no backend `lineage`, and no `history: true` capture) —\n * `stageBranches` then has no fork-side delta to prune with and diffs this\n * branch in full.\n *\n * Closes the working copy's backend if either read fails. `branch()` reports\n * every failure as a returned `err(...)` rather than a throw, so the caller\n * never receives the store and has no handle to close: without this, a\n * backend whose `getActiveSchema` or `lineage.revision()` rejects would leak\n * the engine the strategy just opened. A close failure must not mask the\n * original error.\n */\nasync function captureBranchForkState<G extends GraphDef>(\n  store: GraphBranch<G>[\"store\"],\n): Promise<BranchForkState> {\n  try {\n    return await readBranchForkState(store);\n  } catch (error) {\n    try {\n      await storeBackend(store).close();\n    } catch {\n      // Intentionally ignored — surface the original failure.\n    }\n    throw error;\n  }\n}\n\n/**\n * The fork-time state `captureBranchForkState` reads: the committed schema row\n * (the merge-time drift anchor) and, when the working copy resolves a `lineage`\n * source, the engine revision it reports before any write.\n */\nexport type BranchForkState = Readonly<{\n  schemaAnchor: Readonly<{ version: number; hash: string }> | undefined;\n  forkRevision: EngineRevision | undefined;\n}>;\n\n/**\n * Reads the fork-time state WITHOUT closing the working copy's backend on\n * failure. The caller that owns the store is responsible for releasing it —\n * `branch()` uses {@link captureBranchForkState}, which closes on failure as\n * its own contract; the durable path owns the allocation outright and must\n * both close the store AND abort the persistent working copy, so it reads\n * through this seam and performs that cleanup itself rather than having a\n * close happen behind its back (see `durable-branch.ts`'s `abandonAllocation`).\n */\nexport async function readBranchForkState<G extends GraphDef>(\n  store: GraphBranch<G>[\"store\"],\n): Promise<BranchForkState> {\n  const schemaRow = await storeBackend(store).getActiveSchema(store.graphId);\n  const schemaAnchor =\n    schemaRow === undefined ? undefined : (\n      { version: schemaRow.version, hash: schemaRow.schema_hash }\n    );\n  const lineage = resolveLineage(store);\n  // The session is the working copy's own root backend — the same object\n  // `resolveLineage(store)` just resolved `lineage` off of, and the only\n  // session available this far outside any transaction.\n  const forkRevision =\n    lineage === undefined ? undefined : (\n      await lineage.revision(storeBackend(store))\n    );\n  return { schemaAnchor, forkRevision };\n}\n","import type { GraphDef } from \"../core/define-graph\";\nimport type { EvolutionPlan } from \"../schema/evolution-plan\";\nimport { storeRuntime } from \"../store/runtime-port\";\nimport type { Store } from \"../store/store\";\nimport { MergePlanCapabilityError } from \"./errors\";\n\n/**\n * Constructs the plan-owned view of the graph that an evolution will produce.\n *\n * This is the single bridge from a module-issued evolution plan to merge\n * planning. It validates both plan ownership and graph identity through the\n * Store runtime before any branch is created or candidate data is staged.\n */\nexport function evolutionPlanningTarget<G extends GraphDef>(\n  store: Store<G>,\n  plan: EvolutionPlan,\n): Store<G> {\n  const planningTarget = storeRuntime(store).evolutionPlanningTarget;\n  if (planningTarget === undefined) {\n    throw new MergePlanCapabilityError(\n      \"This Store cannot construct a resulting-schema merge planning view.\",\n      { details: { capability: \"evolutionPlanningTarget\" } },\n    );\n  }\n  return planningTarget(plan);\n}\n","/**\n * Constraint-aware working copies for untrusted ingestion.\n *\n * An ingestion branch persists a mechanically-derived schema with node\n * uniqueness declarations removed. That lets aliases reach merge planning,\n * where canonical candidate generation and final resolved-write validation use\n * the canonical graph's constraints. Every other working-copy constraint stays\n * active during staging.\n */\n\nimport { registerIngestionImportTarget } from \"../interchange/ingestion-import-target\";\nimport { branch } from \"./branch\";\nimport { BranchError } from \"./errors\";\nimport type { Result } from \"./result\";\nimport { err, isErr, ok } from \"./result\";\nimport type {\n  GraphDef,\n  IdentityAssertionWriteFacade,\n  IdentityFacade,\n} from \"./typegraph-internal\";\nimport type {\n  BranchOptions,\n  GraphBranch,\n  IngestionBranch,\n  MergeBranch,\n} from \"./types\";\nimport type { MakeBackend } from \"./working-copy\";\nimport {\n  cloneIngestionWorkingCopyStrategy,\n  coalescedWorkingCopyClose,\n} from \"./working-copy\";\n\nconst PRIVATE_BRANCHES = new WeakMap<object, unknown>();\n\n/** Restricts a full identity facade to the assertions accepted during ingestion. */\nfunction createIngestionIdentityFacade<G extends GraphDef>(\n  identity: IdentityFacade<G>,\n): IdentityAssertionWriteFacade<G> {\n  return Object.freeze({\n    assertSame(a, b, window) {\n      return identity.assertSame(a, b, window);\n    },\n    assertDifferent(a, b, window) {\n      return identity.assertDifferent(a, b, window);\n    },\n    bulkAssertSame(pairs) {\n      return identity.bulkAssertSame(pairs);\n    },\n    bulkAssertDifferent(pairs) {\n      return identity.bulkAssertDifferent(pairs);\n    },\n  });\n}\n\n/**\n * Creates an isolated ingestion branch whose node uniqueness constraints are\n * deferred until the resolved merge write set is applied.\n *\n * The returned handle deliberately exposes no ordinary Store. Its typed node\n * and edge collections are sufficient to stage and inspect incoming data, and\n * merge entrypoints accept the handle directly. Call `close()` when the working\n * copy is no longer needed.\n */\nexport async function ingestionBranch<G extends GraphDef>(\n  baseStore: GraphBranch<G>[\"store\"],\n  makeBackend: MakeBackend,\n  options?: BranchOptions,\n): Promise<Result<IngestionBranch<G>, BranchError>> {\n  try {\n    const created = await branch(\n      baseStore,\n      makeBackend,\n      options,\n      cloneIngestionWorkingCopyStrategy<G>(makeBackend),\n    );\n    if (isErr(created)) {\n      return err(\n        new BranchError(\"Failed to create constraint-aware ingestion branch\", {\n          cause: created.error,\n        }),\n      );\n    }\n    const privateBranch = created.data;\n    const { base, id, store } = privateBranch;\n    const identityAccess =\n      store.graph.identity === undefined ?\n        {}\n      : {\n          identity: createIngestionIdentityFacade(\n            (store as typeof store & Readonly<{ identity: IdentityFacade<G> }>)\n              .identity,\n          ),\n        };\n    const handle = Object.freeze({\n      id,\n      base,\n      nodes: store.nodes,\n      edges: store.edges,\n      ...identityAccess,\n      close: coalescedWorkingCopyClose(store),\n    }) as unknown as IngestionBranch<G>;\n    PRIVATE_BRANCHES.set(handle, privateBranch);\n    registerIngestionImportTarget(handle, store);\n    return ok(handle);\n  } catch (error) {\n    return err(\n      new BranchError(\"Failed to create constraint-aware ingestion branch\", {\n        cause: error,\n      }),\n    );\n  }\n}\n\n/** Resolves an opaque ingestion handle to its private planner-facing branch. */\nfunction unwrapMergeBranch<G extends GraphDef>(\n  input: MergeBranch<G>,\n): GraphBranch<G> {\n  const privateBranch = PRIVATE_BRANCHES.get(input);\n  if (privateBranch !== undefined) {\n    return privateBranch as GraphBranch<G>;\n  }\n  return input as GraphBranch<G>;\n}\n\n/** Resolves all public branch inputs once at a merge entrypoint boundary. */\nexport function unwrapMergeBranches<G extends GraphDef>(\n  inputs: readonly MergeBranch<G>[],\n): readonly GraphBranch<G>[] {\n  return inputs.map((input) => unwrapMergeBranch(input));\n}\n","import { statementExecutionVerdict } from \"../backend/capabilities/resolve\";\nimport { resolveWriteFencePlan } from \"../backend/capabilities/write-fence\";\nimport type { TransactionBackend } from \"../backend/types\";\nimport type { GraphDef } from \"../core/define-graph\";\nimport {\n  ensureEngineSerializedWriterSlot,\n  hasPendingWriteTransactionRevision,\n} from \"../store/operations/write-transaction\";\nimport { hasPendingRecordedGraphWrites } from \"../store/recorded-capture\";\nimport { storeBackend } from \"../store/runtime-port\";\nimport type { Store } from \"../store/store\";\nimport { MergePlanCapabilityError } from \"./errors\";\n\n/** A plan's durable revision cannot fence changes still awaiting capture flush. */\nexport async function assertMergeTransactionPristine<G extends GraphDef>(\n  target: Store<G>,\n  txBackend: TransactionBackend,\n): Promise<void> {\n  if (\n    hasPendingRecordedGraphWrites(txBackend, target.graphId) ||\n    hasPendingWriteTransactionRevision(txBackend)\n  ) {\n    throw new MergePlanCapabilityError(\n      \"Apply the merge plan before writing to its target graph in this transaction.\",\n      { details: { capability: \"mergeTransactionPristine\" } },\n    );\n  }\n  if (resolveWriteFencePlan(txBackend).kind !== \"engine-serialized\") return;\n  const statements = statementExecutionVerdict(storeBackend(target));\n  if (!statements.supported) {\n    throw new MergePlanCapabilityError(\n      \"Adopted merge application requires transaction-scoped statement execution to acquire the engine writer slot.\",\n      { details: { capability: \"mergeTransactionWriterSlot\" } },\n    );\n  }\n  await ensureEngineSerializedWriterSlot(\n    txBackend,\n    target.revisionSchema,\n    statements,\n  );\n}\n","import type { GraphDef, GraphIdentityConfig } from \"../core/define-graph\";\nimport type { IdentityFacade } from \"../identity/types\";\nimport {\n  CURRENT_ONLY_READ_NAMES,\n  EDGE_TEMPORAL_READ_NAMES,\n  IDENTITY_READ_NAMES,\n  NODE_TEMPORAL_READ_NAMES,\n} from \"../store/collection-surface\";\nimport type { TransactionContext } from \"../store/types\";\nimport { requireDefined } from \"../utils/presence\";\nimport { InvalidMergeOptionsError } from \"./errors\";\nimport type { MergedCounts } from \"./types\";\n\nconst NODE_READ_NAMES = [\n  ...NODE_TEMPORAL_READ_NAMES,\n  ...CURRENT_ONLY_READ_NAMES,\n] as const;\n\n/** Transaction-bound reads available before applying a fenced merge plan. */\nexport type MergePlanReadContext<G extends GraphDef> = Readonly<{\n  nodes: Readonly<{\n    [K in keyof TransactionContext<G>[\"nodes\"]]: Pick<\n      TransactionContext<G>[\"nodes\"][K],\n      (typeof NODE_READ_NAMES)[number]\n    >;\n  }>;\n  edges: Readonly<{\n    [K in keyof TransactionContext<G>[\"edges\"]]: Pick<\n      TransactionContext<G>[\"edges\"][K],\n      (typeof EDGE_TEMPORAL_READ_NAMES)[number]\n    >;\n  }>;\n}> &\n  (G[\"identity\"] extends GraphIdentityConfig ?\n    Readonly<{\n      identity: Pick<IdentityFacade<G>, (typeof IDENTITY_READ_NAMES)[number]>;\n    }>\n  : Readonly<Record<never, never>>);\n\n/** Plan effects inside an uncommitted transaction; excludes callback writes. */\nexport type MergePlanApplied = Readonly<{ merged: MergedCounts }>;\n\n/**\n * Work composed with merge application in its own protected transaction. Both\n * callbacks may be replayed up to three times on a transaction conflict:\n * await all work, use only the supplied context, perform no external effects.\n * See {@link file://../backend/capabilities/retried-unit.ts runRetriedUnit}\n * for the full replay contract this binds to. Throw/reject to abort;\n * returning a value (including a Result) is refused.\n */\nexport type MergePlanApplyOptions<G extends GraphDef> = Readonly<{\n  /** Runs after the target fence is checked, before plan writes. Reads only. */\n  beforeApply?: (reads: MergePlanReadContext<G>) => Promise<void>;\n  /** Runs after plan writes, before capture flush and commit. */\n  afterApply?: (\n    tx: TransactionContext<G>,\n    applied: MergePlanApplied,\n  ) => Promise<void>;\n}>;\n\nfunction pickReadMethods<T, K extends keyof T>(\n  source: T,\n  names: readonly K[],\n): Pick<T, K> {\n  return Object.fromEntries(names.map((name) => [name, source[name]])) as Pick<\n    T,\n    K\n  >;\n}\n\n/**\n * Project actual read-only objects. Enumerate registered kinds: transaction\n * collection proxies instantiate lazily and do not enumerate their own keys.\n */\nexport function mergePlanReadContext<G extends GraphDef>(\n  tx: TransactionContext<G>,\n  graph: G,\n): MergePlanReadContext<G> {\n  return {\n    nodes: Object.fromEntries(\n      Object.keys(graph.nodes).map((kind) => [\n        kind,\n        pickReadMethods(requireDefined(tx.nodes[kind]), NODE_READ_NAMES),\n      ]),\n    ),\n    edges: Object.fromEntries(\n      Object.keys(graph.edges).map((kind) => [\n        kind,\n        pickReadMethods(\n          requireDefined(tx.edges[kind]),\n          EDGE_TEMPORAL_READ_NAMES,\n        ),\n      ]),\n    ),\n    ...(\"identity\" in tx ?\n      {\n        identity: pickReadMethods(tx.identity, IDENTITY_READ_NAMES),\n      }\n    : {}),\n  } as MergePlanReadContext<G>;\n}\n\n/** JavaScript callers must not accidentally commit by returning an Err. */\nexport function assertMergeCallbackResult(\n  result: unknown,\n  callback: keyof MergePlanApplyOptions<GraphDef>,\n): void {\n  if (result !== undefined) {\n    throw new InvalidMergeOptionsError(\n      `${callback} must resolve without a return value; throw or reject to abort merge application.`,\n      { cause: result, details: { callback } },\n    );\n  }\n}\n","import { readOwnProperty } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\n/**\n * Per-kind blocking (design §9 phase 2): bucket a kind's NEW nodes by a cheap\n * exact-equality key so candidate-gen (T6) only compares pairs that could\n * plausibly be the same entity, bounding the otherwise-O(n²) work.\n *\n * A node is placed into a bucket for EACH key it produces, so it can belong to\n * MULTIPLE buckets — two key sources combined as a UNION (not a composite key):\n *\n *   1. The caller's `ResolveConfig.block(node)` — an application-defined cheap\n *      pre-filter (e.g. a Patient's `birthDate`) → its ONE block bucket.\n *   2. The kind's declared `unique` constraints, read from the PUBLIC\n *      `store.introspect().kinds[k].unique` → ONE bucket per constraint the node\n *      fully satisfies. A unique constraint is an exact-match short-circuit: two\n *      nodes sharing all of a constraint's field values are definitionally the\n *      same entity, so they co-bucket THERE regardless of their block keys or any\n *      OTHER constraint.\n *\n * Composing the two sources into a single key (the old behavior) was a bug: a\n * differing `block()` key — or a differing EARLIER constraint — split two nodes\n * that share a unique value into separate buckets, so candidate-gen never compared\n * them and a real duplicate survived the merge. The UNION fixes this: a shared\n * unique value always co-buckets, independent of `block()`.\n *\n * candidate-gen compares pairs within each bucket and DEDUPS pairs across buckets,\n * so a node in several buckets is compared against the UNION of its bucket-mates,\n * each pair scored exactly once.\n *\n * Determinism is load-bearing — candidate-gen order must never leak into merge\n * results — so bucket keys are emitted sorted lexicographically, each bucket's\n * member list is sorted by `node.id`, and each unique signature is built in the\n * constraint's declared field order.\n *\n * A node that produces NO key (no `block()`, no satisfied constraint) lands in the\n * shared {@link UNBLOCKED_BUCKET_KEY} bucket, compared all-vs-all within its kind.\n * This is the safe (no false-negative) fallback: blocking only ever prunes pairs\n * that are guaranteed non-matches.\n *\n * This module is a PURE function over its inputs (the introspection snapshot is\n * read synchronously by the caller and passed in); it performs no I/O.\n */\nimport { compareStrings } from \"./node-key\";\nimport type { Node, NodeType, UniqueIntrospection } from \"./typegraph-internal\";\nimport { computeUniqueKey } from \"./typegraph-internal\";\nimport type { ResolveConfig } from \"./types\";\n\n/**\n * Bucket key for nodes that produced no blocking key from either `block()` or a\n * unique constraint. Members of this bucket are compared all-vs-all within their\n * kind by candidate-gen.\n */\nexport const UNBLOCKED_BUCKET_KEY = \"unblocked\";\n\n/**\n * Separator joining the parts of a bucket key (its prefix, and a unique\n * signature's constraint name + field values). Chosen as a control character so it\n * cannot collide with ordinary stringified property values.\n */\nconst KEY_PART_SEPARATOR = \"\\0\";\n\n/**\n * Prefix marking a `block()`-key bucket, so a `block()` value can never be confused\n * with a unique-constraint value that happens to stringify the same.\n */\nconst BLOCK_KEY_PREFIX = \"b\";\n\n/** Prefix marking a unique-constraint bucket. See {@link BLOCK_KEY_PREFIX}. */\nconst UNIQUE_KEY_PREFIX = \"u\";\n\n/**\n * True when a bucket key denotes a UNIQUE-constraint bucket (vs. a `block()` or the\n * unblocked bucket). candidate-gen FORCE-MERGES every pair in such a bucket: a\n * shared unique value is definitionally the same entity (the exact-match\n * short-circuit), so the pair is a GUARANTEED merge candidate regardless of the\n * similarity threshold — differing properties are then reported as conflicts\n * normally. This also keeps the merged graph from violating its own uniqueness:\n * two unmerged same-unique rows could never commit.\n */\nexport function isUniqueBucketKey(key: string): boolean {\n  return key.startsWith(`${UNIQUE_KEY_PREFIX}${KEY_PART_SEPARATOR}`);\n}\n\n/**\n * Returns the declared constraint name encoded in a unique bucket key. This is\n * the single decoder for the private bucket-key format, so candidate evidence\n * never has to parse an implementation detail or retain the compared value.\n */\nexport function uniqueConstraintNameForBucket(key: string): string | undefined {\n  if (!isUniqueBucketKey(key)) {\n    return undefined;\n  }\n  const constraintStart = UNIQUE_KEY_PREFIX.length + KEY_PART_SEPARATOR.length;\n  const constraintEnd = key.indexOf(KEY_PART_SEPARATOR, constraintStart);\n  return constraintEnd === -1 ? undefined : (\n      key.slice(constraintStart, constraintEnd)\n    );\n}\n\n/**\n * Builds the exact-match signature for one unique constraint from a node's\n * field values, or `undefined` when ANY of the constraint's fields is `null` /\n * `undefined` (a partial key cannot establish exact-match equality, and — since\n * the introspection snapshot does not expose a constraint's `where` predicate —\n * skipping absent values keeps a partial unique constraint from silently\n * over-merging two distinct rows that the database would treat as a non-match;\n * a genuine non-partial null collision still surfaces loudly at commit).\n *\n * The signature delegates to {@link computeUniqueKey} — the SAME key the store\n * enforces uniqueness with — so a blocking bucket co-buckets EXACTLY the values\n * the commit-time uniqueness check treats as equal. Hand-rolling a separate\n * canonical encoding here drifted from enforcement: it distinguished the number\n * `1` from the string `\"1\"` (which `computeUniqueKey` collapses, so the merge\n * aborted with a `UniquenessError`) and key-sorted object values (which\n * `computeUniqueKey` does not, so distinct rows were silently over-merged).\n */\nfunction constraintSignature(\n  node: Node<NodeType>,\n  constraint: UniqueIntrospection,\n): string | undefined {\n  const props = node as unknown as Record<string, unknown>;\n  for (const field of constraint.fields) {\n    // Own-key read: a constraint over a prototype-named field (\"toString\")\n    // must see an absent value as absent here, exactly as computeUniqueKey\n    // below does — a raw read would mint a signature for a value the\n    // commit-time uniqueness check treats as missing.\n    const value = readOwnProperty(props, field);\n    if (value === undefined || value === null) {\n      return undefined;\n    }\n  }\n  return `${constraint.name}${KEY_PART_SEPARATOR}${computeUniqueKey(\n    props,\n    constraint.fields,\n    constraint.collation,\n  )}`;\n}\n\n/**\n * Computes the SET of bucket keys a node belongs to: its `block()` key bucket (if\n * `block()` returned a key) PLUS one bucket per unique constraint the node fully\n * satisfies. Because a shared unique value gets its OWN bucket — never intersected\n * with the block key or other constraints — two nodes sharing it always co-bucket.\n * Returns `[UNBLOCKED_BUCKET_KEY]` when the node produces no key at all.\n *\n * Each unique signature already embeds its constraint name, so distinct constraints\n * yield distinct keys; the `b`/`u` prefixes keep block and unique keyspaces\n * disjoint. No constraint ordering is needed — each is an independent bucket.\n */\nfunction bucketKeysFor(\n  node: Node<NodeType>,\n  block: ResolveConfig[\"block\"],\n  constraints: readonly UniqueIntrospection[],\n): readonly string[] {\n  const keys: string[] = [];\n\n  const blockKey = block?.(node);\n  if (blockKey !== undefined) {\n    keys.push(`${BLOCK_KEY_PREFIX}${KEY_PART_SEPARATOR}${blockKey}`);\n  }\n\n  for (const constraint of constraints) {\n    const signature = constraintSignature(node, constraint);\n    if (signature !== undefined) {\n      keys.push(`${UNIQUE_KEY_PREFIX}${KEY_PART_SEPARATOR}${signature}`);\n    }\n  }\n\n  return keys.length === 0 ? [UNBLOCKED_BUCKET_KEY] : keys;\n}\n\n/**\n * Buckets a kind's NEW nodes by their blocking key(s). A node may land in MORE\n * THAN ONE bucket — its `block()` bucket plus a bucket for each unique constraint\n * it satisfies — so two nodes sharing any blocking key co-bucket and are compared.\n *\n * @param newNodes The kind's new (fork-introduced) nodes. All nodes SHOULD be of\n *   one kind; the caller invokes `blockNodes` once per resolved kind.\n * @param resolveConfig The kind's resolution config; its optional `block`\n *   function supplies the application blocking key.\n * @param uniqueConstraints The kind's `unique` constraints from\n *   `store.introspect().kinds[k].unique`. Pass an empty array when blocking\n *   should rely on `block()` alone.\n * @returns A map from bucket key → that bucket's nodes. Iteration order of the\n *   returned map is the lexicographic order of bucket keys, and each bucket's\n *   node list is sorted by `node.id`, so the result is a pure, order-independent\n *   function of the input node SET. A node may appear in several buckets;\n *   candidate-gen dedups pairs so each is scored once.\n */\nexport function blockNodes<K extends NodeType>(\n  newNodes: readonly Node<K>[],\n  resolveConfig: Pick<ResolveConfig, \"block\">,\n  uniqueConstraints: readonly UniqueIntrospection[] = [],\n): Map<string, Node<K>[]> {\n  const buckets = new Map<string, Node<K>[]>();\n\n  for (const node of newNodes) {\n    for (const key of bucketKeysFor(\n      node,\n      resolveConfig.block,\n      uniqueConstraints,\n    )) {\n      const bucket = buckets.get(key);\n      if (bucket === undefined) {\n        buckets.set(key, [node]);\n      } else {\n        bucket.push(node);\n      }\n    }\n  }\n\n  const sortedKeys = [...buckets.keys()].sort((left, right) =>\n    compareStrings(left, right),\n  );\n  const ordered = new Map<string, Node<K>[]>();\n  for (const key of sortedKeys) {\n    const members = [...requireDefined(buckets.get(key))].sort((left, right) =>\n      compareStrings(left.id, right.id),\n    );\n    ordered.set(key, members);\n  }\n  return ordered;\n}\n","import { hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\n/**\n * The centralized property-conflict resolution rule (design §6.4 rule 4 / §7.3,\n * T8). Shared by canonical node-property union (T8 / `canonicalize.ts`) and edge\n * property-collision resolution (T9), so the determinism contract lives in\n * exactly one place.\n *\n * DETERMINISM CONTRACT — the single most important invariant of the merge:\n *   Conflict resolution NEVER consults wall-clock arrival time. When a value\n *   must be chosen among differing per-branch candidates, the choice is made on\n *   a STABLE branch total order — either the caller-supplied\n *   `MergeOptions.branchOrder`, or branch ids sorted lexicographically — captured\n *   ONCE before any resolution runs. Two merges of the same branch set in any\n *   order therefore resolve every conflict identically.\n */\nimport { canonicalValueKey } from \"./canonical-props\";\nimport { compareStrings } from \"./node-key\";\nimport type {\n  EdgeId,\n  GraphDef,\n  JsonValue,\n  NodeId,\n  NodeType,\n} from \"./typegraph-internal\";\nimport type {\n  BranchId,\n  ConflictingValue,\n  PropertyConflict,\n  PropertyConflictPolicy,\n} from \"./types\";\n\n/**\n * The candidate values for one conflicted property, each tagged with the branch\n * that contributed it. Built by the union phases (node/edge) before delegating\n * to {@link resolveConflictValue}.\n */\ntype ConflictInput = Readonly<{\n  /** The property name in conflict. */\n  property: string;\n  /** Every distinct contributing `(branchId, value)`, one per source. */\n  values: readonly ConflictingValue[];\n  /** The canonical survivor's own value — kept under the `\"flag\"` policy. */\n  canonicalValue: JsonValue;\n}>;\n\n/**\n * Per-branch trust weights for the `\"provenanceWeighted\"` policy. Branches absent\n * from the map default to weight `0`. Ties are broken by the stable branch order.\n */\nexport type ProvenanceWeights = ReadonlyMap<BranchId, number>;\n\n/**\n * The captured, immutable resolution context. The stable branch order is passed\n * separately as a precomputed `branchRank` (built once via {@link buildBranchRank}\n * and shared across every conflict), so this context carries only the policy and\n * the optional `\"provenanceWeighted\"` weights.\n *\n * BRANCH ORDER IS A PRIORITY ORDER: the branch appearing EARLIER in\n * `MergeOptions.branchOrder` (lower rank) has higher precedence. `\"lastWriteWins\"`\n * therefore picks the value of the HIGHEST-PRIORITY branch (lowest rank / first\n * in the order) — the \"winning write\" is defined by the stable order, NOT by\n * wall-clock arrival. There is no wall-clock anywhere in this module.\n */\nexport type ResolutionContext<G extends GraphDef = GraphDef> = Readonly<{\n  policy: PropertyConflictPolicy<G>;\n  weights?: ProvenanceWeights;\n}>;\n\n/**\n * The outcome of resolving one property conflict: the surviving value and\n * whether the values actually differed (so callers know whether to record a\n * {@link PropertyConflict}).\n */\ntype ConflictResolution = Readonly<{\n  value: JsonValue;\n  conflicted: boolean;\n}>;\n\n/**\n * Builds the rank lookup for a stable branch order. Branch ids not present in\n * the supplied order are appended in lexicographic order after the explicit\n * ones, so an incomplete `branchOrder` is still total and deterministic.\n */\nexport function buildBranchRank(\n  branchOrder: readonly BranchId[],\n  allBranchIds: readonly BranchId[],\n): ReadonlyMap<BranchId, number> {\n  const rank = new Map<BranchId, number>();\n  let next = 0;\n  for (const branchId of branchOrder) {\n    if (!rank.has(branchId)) {\n      rank.set(branchId, next);\n      next += 1;\n    }\n  }\n  const remaining = allBranchIds\n    .filter((branchId) => !rank.has(branchId))\n    .sort((left, right) => compareStrings(left, right));\n  for (const branchId of remaining) {\n    if (!rank.has(branchId)) {\n      rank.set(branchId, next);\n      next += 1;\n    }\n  }\n  return rank;\n}\n\n/**\n * Returns the value contributed by the HIGHEST-PRIORITY branch — the one with\n * the lowest rank (earliest in the stable branch order). Ties (two contributions\n * sharing a rank, e.g. when the same branch staged two values) are broken by the\n * canonical serialization of the value, so the choice is fully deterministic.\n */\nfunction pickByPriority(\n  values: readonly ConflictingValue[],\n  branchRank: ReadonlyMap<BranchId, number>,\n): JsonValue {\n  let chosen = requireDefined(values[0]);\n  let chosenRank = branchRank.get(chosen.branchId) ?? Number.MAX_SAFE_INTEGER;\n  for (const candidate of values.slice(1)) {\n    const candidateRank =\n      branchRank.get(candidate.branchId) ?? Number.MAX_SAFE_INTEGER;\n    if (candidateRank < chosenRank) {\n      chosen = candidate;\n      chosenRank = candidateRank;\n    } else if (\n      candidateRank === chosenRank &&\n      canonicalValueKey(candidate.value) < canonicalValueKey(chosen.value)\n    ) {\n      chosen = candidate;\n    }\n  }\n  return chosen.value;\n}\n\n/**\n * Picks the value contributed by the highest-weight branch under\n * `\"provenanceWeighted\"`. Ties on weight fall back to the stable branch order\n * (highest-priority / lowest rank wins), then to canonical value order — never\n * wall-clock.\n */\nfunction pickByWeight(\n  values: readonly ConflictingValue[],\n  weights: ProvenanceWeights,\n  branchRank: ReadonlyMap<BranchId, number>,\n): JsonValue {\n  let chosen = requireDefined(values[0]);\n  let chosenWeight = weights.get(chosen.branchId) ?? 0;\n  let chosenRank = branchRank.get(chosen.branchId) ?? Number.MAX_SAFE_INTEGER;\n  for (const candidate of values.slice(1)) {\n    const candidateWeight = weights.get(candidate.branchId) ?? 0;\n    const candidateRank =\n      branchRank.get(candidate.branchId) ?? Number.MAX_SAFE_INTEGER;\n    if (candidateWeight > chosenWeight) {\n      chosen = candidate;\n      chosenWeight = candidateWeight;\n      chosenRank = candidateRank;\n      continue;\n    }\n    if (candidateWeight === chosenWeight) {\n      if (candidateRank < chosenRank) {\n        chosen = candidate;\n        chosenRank = candidateRank;\n      } else if (\n        candidateRank === chosenRank &&\n        canonicalValueKey(candidate.value) < canonicalValueKey(chosen.value)\n      ) {\n        chosen = candidate;\n      }\n    }\n  }\n  return chosen.value;\n}\n\n/**\n * Returns whether every contributing value is deeply equal (so there is no real\n * conflict). Compares the {@link canonicalValueKey} (recursively key-sorted) form\n * so two branches that wrote a logically-equal object with different key order do\n * NOT register as a conflict.\n */\nfunction allValuesEqual(values: readonly ConflictingValue[]): boolean {\n  if (values.length <= 1) {\n    return true;\n  }\n  const first = canonicalValueKey(requireDefined(values[0]).value);\n  return values.every(\n    (candidate) => canonicalValueKey(candidate.value) === first,\n  );\n}\n\n/**\n * A single `(branchId, props)` contribution to a property union — a cluster\n * member (node) or a collision-group member (edge's staged record). The union\n * phases differ in their surrounding base/survivor logic but agree on HOW to\n * gather a property's candidate values, so they share {@link collectConflictingValues}.\n */\ntype Contribution = Readonly<{\n  branchId: BranchId;\n  props: Readonly<Record<string, JsonValue>>;\n}>;\n\n/**\n * Collects the distinct `(branchId, value)` contributions for one property across\n * a set of contributions, in stable `(branchId, canonical-value)` order. Distinct\n * on `(branchId, value)`: two contributions from the same branch carrying the same\n * value collapse to one entry, but the same branch contributing two different\n * values is preserved (so an intra-branch contradiction stays visible).\n *\n * Shared by the node property union (T8) and the edge property union (T9) so the\n * determinism-critical dedupe + sort is defined exactly once and node/edge conflict\n * records are shaped identically.\n */\nexport function collectConflictingValues(\n  property: string,\n  contributions: readonly Contribution[],\n): readonly ConflictingValue[] {\n  const seen = new Set<string>();\n  const values: ConflictingValue[] = [];\n  for (const { branchId, props } of contributions) {\n    if (!hasOwnKey(props, property)) {\n      continue;\n    }\n    const value = props[property] as JsonValue;\n    const dedupeKey = `${branchId}\\0${canonicalValueKey(value)}`;\n    if (seen.has(dedupeKey)) {\n      continue;\n    }\n    seen.add(dedupeKey);\n    values.push({ branchId, value });\n  }\n  return [...values].sort((left, right) => {\n    const byBranch = compareStrings(left.branchId, right.branchId);\n    return byBranch === 0 ?\n        compareStrings(\n          canonicalValueKey(left.value),\n          canonicalValueKey(right.value),\n        )\n      : byBranch;\n  });\n}\n\n/**\n * Resolves one property conflict under the captured {@link ResolutionContext}.\n *\n * - If all contributing values are equal → that value, `conflicted: false`.\n * - `\"flag\"` → keep the canonical's value, `conflicted: true` (caller records a\n *   {@link PropertyConflict}; no auto-resolution).\n * - `\"lastWriteWins\"` → the value of the HIGHEST-PRIORITY branch (earliest in the\n *   stable order / lowest rank). NEVER wall-clock.\n * - `\"provenanceWeighted\"` → the value of the highest-weight branch (ties →\n *   highest-priority branch → canonical value order).\n * - function policy → the value returned by the delegate.\n *\n * @param input The conflicted property, its tagged candidate values, and the\n *   canonical survivor's own value.\n * @param context The captured policy + stable branch order + optional weights.\n * @param makeConflict Builds the {@link PropertyConflict}-shaped record passed to\n *   a function policy. Kept as a callback so this module needs no knowledge of\n *   the node-vs-edge entity shape.\n * @returns The surviving value and whether the values genuinely differed.\n */\nfunction resolveConflictValue<G extends GraphDef = GraphDef>(\n  input: ConflictInput,\n  context: ResolutionContext<G>,\n  branchRank: ReadonlyMap<BranchId, number>,\n  makeConflict: (\n    resolution: JsonValue,\n  ) => Parameters<\n    Extract<PropertyConflictPolicy<G>, (...args: never[]) => unknown>\n  >[0],\n): ConflictResolution {\n  if (allValuesEqual(input.values)) {\n    return {\n      value: input.values[0]?.value ?? input.canonicalValue,\n      conflicted: false,\n    };\n  }\n\n  const { policy } = context;\n\n  if (policy === \"flag\") {\n    return { value: input.canonicalValue, conflicted: true };\n  }\n  if (policy === \"lastWriteWins\") {\n    return {\n      value: pickByPriority(input.values, branchRank),\n      conflicted: true,\n    };\n  }\n  if (policy === \"provenanceWeighted\") {\n    const weights = context.weights ?? new Map<BranchId, number>();\n    return {\n      value: pickByWeight(input.values, weights, branchRank),\n      conflicted: true,\n    };\n  }\n  // Function policy: delegate, but first resolve a stable provisional value so\n  // the conflict record handed to the delegate is itself deterministic.\n  const provisional = pickByPriority(input.values, branchRank);\n  const resolved = policy(makeConflict(provisional));\n  return { value: resolved, conflicted: true };\n}\n\n/**\n * The resolve-and-record tail every property union shares (node cluster union T8,\n * edge collision union T9, inherited 3-way merge T8a): resolve the conflict, then —\n * if the values genuinely differed — build the public {@link PropertyConflict}. The\n * SINGLE place the conflict record is shaped, so the value the function policy sees\n * and the value recorded can never drift.\n *\n * `values` is the FULL contributing set the policy resolves over; `reportedValues`\n * is the PUBLIC subset (synthetic sentinels excluded) recorded on the conflict.\n */\nexport function resolvePropertyUnion<G extends GraphDef = GraphDef>(\n  input: Readonly<{\n    entityId: NodeId<NodeType> | EdgeId;\n    kind: string;\n    property: string;\n    values: readonly ConflictingValue[];\n    reportedValues: readonly ConflictingValue[];\n    canonicalValue: JsonValue;\n  }>,\n  context: ResolutionContext<G>,\n  branchRank: ReadonlyMap<BranchId, number>,\n): Readonly<{ value: JsonValue; conflict: PropertyConflict<G> | undefined }> {\n  const makeRecord = (resolution: JsonValue): PropertyConflict<G> => ({\n    entityId: input.entityId,\n    kind: input.kind,\n    property: input.property,\n    values: input.reportedValues,\n    resolution,\n  });\n  const resolved = resolveConflictValue(\n    {\n      property: input.property,\n      values: input.values,\n      canonicalValue: input.canonicalValue,\n    },\n    context,\n    branchRank,\n    (resolution) => makeRecord(resolution),\n  );\n  return {\n    value: resolved.value,\n    conflict: resolved.conflicted ? makeRecord(resolved.value) : undefined,\n  };\n}\n","import { createDataKeyedBag, hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\n/**\n * Canonical survivor selection + commutative property union (design §6.4 rule 3\n * & rule 4 / §7.3, T8).\n *\n * Given a {@link ClusterResult} (member ids) and the per-member, per-branch\n * property contributions, this module:\n *\n *   1. Picks the CANONICAL survivor — by default the member with the\n *      lexicographically-minimal node id (`MergeOptions.canonical` overrides).\n *      Because `generateId()` is nanoid (random, NOT time-prefixed), min-id is\n *      independent of creation order — the canonical choice cannot leak the\n *      order nodes were created or branches were merged in.\n *   2. UNIONS properties across all members: per property, collect every\n *      `(branchId, value)`; if all agree → that value; if they differ → defer to\n *      the conflict policy on a STABLE non-wall-clock branch order (T8 /\n *      `conflict-policy.ts`), recording a {@link PropertyConflict}.\n *\n * The result is a pure function of the (unordered) member set + the captured\n * branch order, so shuffling members or branches yields an identical resolution.\n */\nimport type { ClusterResult } from \"./clustering\";\nimport type { ProvenanceWeights, ResolutionContext } from \"./conflict-policy\";\nimport {\n  collectConflictingValues,\n  resolvePropertyUnion,\n} from \"./conflict-policy\";\nimport { compareMergeKeys, compareStrings, idOf, mergeKeyOf } from \"./node-key\";\nimport type {\n  GraphDef,\n  JsonValue,\n  NodeId,\n  NodeType,\n} from \"./typegraph-internal\";\nimport type {\n  BranchId,\n  ConflictingValue,\n  EntityResolution,\n  PropertyConflict,\n  PropertyConflictPolicy,\n  ResolvedCluster,\n} from \"./types\";\nimport { asBranchId } from \"./types\";\n\n/**\n * Reserved provenance \"branch\" for a BASE contribution (§6.4-D). A committed base\n * member has no real branch; this BranchId-shaped sentinel is the key its\n * contributions carry through the value union and the provenance records, so those\n * paths tolerate a base member without a separate code path. It is NOT a real branch\n * id — it is EXCLUDED from the public {@link EntityResolution.branchOrigins} (which\n * lists only real contributing branches), and callers must never mint a branch with\n * this reserved value (rejected at the merge boundary; kept NUL-free so it round-trips\n * through `persistProvenance` on every backend).\n */\nexport const BASE_PROVENANCE_BRANCH: BranchId =\n  asBranchId(\"__committed_base__\");\n\n/**\n * Reserved branch id for the live incremental target staged as a synthetic\n * branch. Lives beside {@link BASE_PROVENANCE_BRANCH} so survivor selection\n * can recognize target-contributed members.\n */\nexport const COMMITTED_TARGET_BRANCH: BranchId = asBranchId(\n  \"__committed_target__\",\n);\n\n/** A node id in its untyped (`NodeType`-default) branded form. */\ntype AnyNodeId = NodeId<NodeType>;\n\n/**\n * Where a {@link ClusterMember}'s contribution originated: a branch's STAGED diff,\n * or a committed BASE node a base source pulled into the cluster (design §6.4-C).\n * The mandatory `branchId` cannot represent a base member, so this discriminator is\n * what lets the reconciler tell the two apart — it enforces base-id-wins (§6.4-C: a\n * base member is the canonical survivor, see {@link pickClusterSurvivor}) and tags\n * base provenance with {@link BASE_PROVENANCE_BRANCH} (§6.4-D). The new-vs-base\n * sources (`baseUnique`) emit `\"base\"` members; the public snapshot `merge()` path\n * stays staged-only, so every member there is `\"staged\"`.\n */\ntype MemberOrigin = \"staged\" | \"base\";\n\n/**\n * One member of a cluster, with the parsed props the contributing branch staged\n * for it. A node that appears in several branches contributes several\n * {@link ClusterMember} entries (one per branch), so property differences across\n * branches surface as conflicts.\n */\nexport type ClusterMember = Readonly<{\n  origin: MemberOrigin;\n  id: AnyNodeId;\n  kind: string;\n  branchId: BranchId;\n  props: Readonly<Record<string, JsonValue>>;\n  // The row's valid-time window. null explicitly preserves an open-left start.\n  // A `validTo` on a staged member means the\n  // branch authored the node as ALREADY ENDED — the commit must not resurrect\n  // it as current.\n  validFrom?: string | null;\n  validTo?: string;\n}>;\n\n/**\n * The fully-resolved canonical entity for one cluster: the survivor id, the\n * unioned property bag, the {@link EntityResolution} record, and any\n * {@link PropertyConflict}s the union surfaced.\n */\nexport type CanonicalEntity = Readonly<{\n  canonicalId: AnyNodeId;\n  kind: string;\n  props: Readonly<Record<string, JsonValue>>;\n  resolution: EntityResolution;\n  conflicts: readonly PropertyConflict[];\n  // The SURVIVOR's staged valid-time window, when the survivor is a staged\n  // member (absent for base-member survivors, whose committed window stays\n  // untouched). Carried to the commit upsert so a branch-authored window —\n  // including a deliberately ENDED one on a resurrection — survives the\n  // merge instead of being reset to merge time.\n  validFrom?: string | null;\n  validTo?: string;\n  // The effective survivor window, including committed base survivors whose\n  // window is intentionally not copied into the upsert fields above. Identity\n  // assertions remapped onto this survivor are intersected with this window.\n  endpointValidFrom?: string;\n  endpointValidTo?: string;\n}>;\n\n/**\n * Bare-id reference selector over a PUBLIC {@link ResolvedCluster}: the member with\n * the lexicographically-minimal node id, or the caller's override. It is NOT the\n * live survivor selector — the merge path selects survivors via\n * {@link pickClusterSurvivor}, which is cross-kind-aware (composite `(kind, id)`\n * keys), enforces base-id-wins, and is where the {@link MergeOptions.canonical} hook\n * is actually consulted. Kept as the documented bare-id default a `canonical` hook\n * mirrors; do not wire new phases onto this helper.\n */\nexport function pickCanonical(\n  cluster: ResolvedCluster,\n  override?: (cluster: ResolvedCluster) => AnyNodeId,\n): AnyNodeId {\n  if (override !== undefined) {\n    return override(cluster);\n  }\n  return requireDefined(\n    [...cluster.members].sort((left, right) => compareStrings(left, right))[0],\n  );\n}\n\n/**\n * Selects a cluster's canonical survivor MEMBER, enforcing BASE-ID-WINS (§6.4-C)\n * UPSTREAM of the `MergeOptions.canonical` hook. Returning the member (not just its\n * id) carries the survivor's KIND alongside its id, so the canonical entity's kind is\n * the survivor's own kind — never a different-kind member that merely shares the id\n * string (the cross-kind identity hazard).\n *\n *   - if the cluster contains a BASE member, the committed base identity is the\n *     survivor and the hook is BYPASSED — the committed identity (and everything\n *     pointing at it) must stay stable, so this is a commit-correctness invariant,\n *     not a survivor preference. By §6.4-A a merged cluster holds ≤1 base member; the\n *     min base `(id, kind)` is taken defensively so selection is deterministic even\n *     before that guard lands.\n *   - otherwise the cluster is pure staged-vs-staged and the hook (mapped over the\n *     bare-id view of the cluster) or the min-`(id, kind)` default applies.\n */\nfunction pickClusterSurvivor(\n  members: readonly ClusterMember[],\n  cluster: ClusterResult,\n  canonicalOverride?: (cluster: ResolvedCluster) => AnyNodeId,\n  preferKind?: (kinds: readonly string[]) => string | undefined,\n): ClusterMember {\n  const byKey = (left: ClusterMember, right: ClusterMember): number =>\n    compareMergeKeys(mergeKeyOf(left), mergeKeyOf(right));\n\n  // base-id-wins (§6.4-C): the committed identity is the survivor outright. By the\n  // staged-only ontology-retype rule, a base member never shares an id with a\n  // different-kind member, so no cross-kind kind choice arises here.\n  const baseMembers = members\n    .filter((member) => member.origin === \"base\")\n    .sort(byKey);\n  if (baseMembers.length > 0) {\n    return requireDefined(baseMembers[0]);\n  }\n\n  // The survivor's bare id: the override's pick (mapped over the bare-id view of the\n  // cluster) when it names a real member, else the minimum identity's id.\n  let canonicalId: AnyNodeId | undefined;\n  if (canonicalOverride !== undefined) {\n    const chosen = canonicalOverride({ members: cluster.members.map(idOf) });\n    if (members.some((member) => member.id === chosen)) {\n      canonicalId = chosen;\n    }\n  }\n  if (canonicalId === undefined) {\n    const minIdentity = [...cluster.members].sort((left, right) =>\n      compareMergeKeys(left, right),\n    )[0];\n    canonicalId =\n      minIdentity === undefined ?\n        requireDefined(members[0]).id\n      : idOf(minIdentity);\n  }\n\n  // Among the members AT that id, choose the KIND. An ontology-retype cluster carries\n  // several subtype-compatible kinds under one id; `preferKind` selects the\n  // MOST-SPECIFIC one, BYPASSING the bare-id hook (which cannot tell `Doctor:x` from\n  // `SpecialistDoctor:x`). Otherwise the id has a single kind and the min `(id, kind)`\n  // member is taken.\n  const membersAtId = members.filter((member) => member.id === canonicalId);\n  if (membersAtId.length === 0) {\n    return requireDefined([...members].sort(byKey)[0]);\n  }\n  const kinds = [...new Set(membersAtId.map((member) => member.kind))];\n  const chosenKind =\n    preferKind !== undefined && kinds.length > 1 ?\n      preferKind(kinds)\n    : undefined;\n  return (\n    (chosenKind === undefined ? undefined : (\n      membersAtId.find((member) => member.kind === chosenKind)\n    )) ?? requireDefined([...membersAtId].sort(byKey)[0])\n  );\n}\n\nfunction findPreferredMember(\n  members: readonly ClusterMember[],\n  property: string,\n  preferredBranchId: BranchId | undefined,\n): ClusterMember | undefined {\n  if (preferredBranchId === undefined) {\n    return undefined;\n  }\n  return members.find(\n    (member) =>\n      member.branchId === preferredBranchId &&\n      hasOwnKey(member.props, property),\n  );\n}\n\nfunction memberPropertyValue(\n  member: ClusterMember,\n  property: string,\n): JsonValue | undefined {\n  if (!hasOwnKey(member.props, property)) {\n    return undefined;\n  }\n  return member.props[property];\n}\n\nfunction pickCanonicalPropertyValue(\n  canonicalMember: ClusterMember,\n  members: readonly ClusterMember[],\n  property: string,\n  values: readonly ConflictingValue[],\n  preferredBranchId: BranchId | undefined,\n): JsonValue {\n  const preferredMember = findPreferredMember(\n    members,\n    property,\n    preferredBranchId,\n  );\n  const preferredValue =\n    preferredMember === undefined ? undefined : (\n      memberPropertyValue(preferredMember, property)\n    );\n  if (preferredValue !== undefined) {\n    return preferredValue;\n  }\n\n  const canonicalValue = memberPropertyValue(canonicalMember, property);\n  return canonicalValue === undefined ?\n      requireDefined(values[0]).value\n    : canonicalValue;\n}\n\n/**\n * Unions the properties of a cluster's members into a single canonical property\n * bag, resolving any per-property disagreement via the conflict policy on a\n * stable branch order. Returns the merged props plus a {@link PropertyConflict}\n * for every property that genuinely differed.\n *\n * @param canonicalId The survivor id (from {@link pickClusterSurvivor}); the entity id\n *   on every recorded conflict.\n * @param kind The canonical entity's kind, recorded on each conflict.\n * @param members Every `(branchId, props)` contribution for this cluster.\n * @param context The captured policy + stable branch order + optional weights.\n * @param branchRank The branch rank lookup (built once, shared across clusters).\n */\nfunction unionProperties(\n  canonicalMember: ClusterMember,\n  members: readonly ClusterMember[],\n  context: ResolutionContext<GraphDef>,\n  baseContext: ResolutionContext<GraphDef>,\n  branchRank: ReadonlyMap<BranchId, number>,\n  preferredBranchId?: BranchId,\n): Readonly<{\n  props: Record<string, JsonValue>;\n  conflicts: PropertyConflict[];\n}> {\n  const canonicalId = canonicalMember.id;\n  const kind = canonicalMember.kind;\n  const hasBaseMember = members.some((member) => member.origin === \"base\");\n\n  const propertyNames = new Set<string>();\n  for (const member of members) {\n    for (const name of Object.keys(member.props)) {\n      propertyNames.add(name);\n    }\n  }\n\n  const props = createDataKeyedBag<JsonValue>();\n  const conflicts: PropertyConflict[] = [];\n\n  for (const property of [...propertyNames].sort((left, right) =>\n    compareStrings(left, right),\n  )) {\n    const values = collectConflictingValues(property, members);\n    if (values.length === 0) {\n      continue;\n    }\n    const canonicalValue = pickCanonicalPropertyValue(\n      canonicalMember,\n      members,\n      property,\n      values,\n      preferredBranchId,\n    );\n\n    // A disagreement that involves a committed BASE value is governed by the\n    // SEPARATE onBasePropertyConflict policy (§6.4-C) — it must not inherit the\n    // staged policy, which could let a branch overwrite committed data. Because\n    // base-id-wins makes the base member canonical, `canonicalValue` is already the\n    // committed value, so `\"flag\"` keeps it. A property the base lacks is a pure\n    // gap-fill / staged-vs-staged conflict and uses the staged policy.\n    const baseInvolved =\n      hasBaseMember &&\n      members.some(\n        (member) =>\n          member.origin === \"base\" && hasOwnKey(member.props, property),\n      );\n\n    // Resolution math sees the FULL contributions (including the base value, so the\n    // disagreement is detected and base-id-wins resolves it). But the reserved\n    // {@link BASE_PROVENANCE_BRANCH} sentinel is NOT a real branch, so it is excluded\n    // from the PUBLIC conflict's `values` — exactly as it is from `branchOrigins`. The\n    // committed value the base contributed still surfaces as the conflict `resolution`.\n    const reportedValues = values.filter(\n      (value) =>\n        value.branchId !== BASE_PROVENANCE_BRANCH &&\n        value.branchId !== preferredBranchId,\n    );\n    const { value, conflict } = resolvePropertyUnion(\n      {\n        entityId: canonicalId,\n        kind,\n        property,\n        values,\n        reportedValues,\n        canonicalValue,\n      },\n      baseInvolved ? baseContext : context,\n      branchRank,\n    );\n    props[property] = value;\n    if (conflict !== undefined) {\n      conflicts.push(conflict);\n    }\n  }\n\n  return { props, conflicts };\n}\n\n/**\n * Resolves a single cluster into its {@link CanonicalEntity}: picks the survivor,\n * unions properties under the conflict policy, and assembles the\n * {@link EntityResolution} record.\n *\n * @param cluster The cluster's member ids (id-sorted from T8 clustering).\n * @param members The per-branch property contributions for those member ids.\n * @param policy The staged-vs-staged property-conflict policy.\n * @param branchRank The captured stable branch rank (built once).\n * @param weights Optional per-branch trust weights for `\"provenanceWeighted\"`.\n * @param canonicalOverride Optional `MergeOptions.canonical` survivor selector.\n * @param basePolicy The SEPARATE base↔branch policy (§6.4-C, `onBasePropertyConflict`)\n *   governing conflicts that involve a committed base value. Defaults to `\"flag\"`\n *   (keep committed value) — it never inherits `policy`.\n */\nexport function canonicalizeCluster(\n  cluster: ClusterResult,\n  members: readonly ClusterMember[],\n  policy: PropertyConflictPolicy,\n  branchRank: ReadonlyMap<BranchId, number>,\n  weights?: ProvenanceWeights,\n  canonicalOverride?: (cluster: ResolvedCluster) => AnyNodeId,\n  basePolicy: PropertyConflictPolicy = \"flag\",\n  preferKind?: (kinds: readonly string[]) => string | undefined,\n  preferredBranchId?: BranchId,\n): CanonicalEntity {\n  const survivor = pickClusterSurvivor(\n    members,\n    cluster,\n    canonicalOverride,\n    preferKind,\n  );\n  const canonicalId = survivor.id;\n  const kind = survivor.kind;\n\n  const context: ResolutionContext<GraphDef> = {\n    policy,\n    ...(weights === undefined ? {} : { weights }),\n  };\n  const baseContext: ResolutionContext<GraphDef> = {\n    policy: basePolicy,\n    ...(weights === undefined ? {} : { weights }),\n  };\n\n  const { props, conflicts } = unionProperties(\n    survivor,\n    members,\n    context,\n    baseContext,\n    branchRank,\n    preferredBranchId,\n  );\n\n  // The public resolution reports the DISTINCT bare member ids; the cluster carries\n  // composite `(kind, id)` keys, so project each to its id and dedup (an ontology\n  // retype puts several kinds under one id, which collapses to a single member id).\n  const memberIds = [\n    ...new Set(cluster.members.map((member) => idOf(member))),\n  ].sort((left, right) => compareStrings(left, right));\n  // `branchOrigins` lists the REAL contributing branches; the reserved\n  // {@link BASE_PROVENANCE_BRANCH} sentinel a base member carries is NOT a branch, so\n  // it is excluded from this public field (it still flows through the value union and\n  // the provenance records, which is where a base contribution is tracked).\n  const branchOrigins = [\n    ...new Set(\n      members\n        .map((member) => member.branchId)\n        .filter(\n          (branchId) =>\n            branchId !== BASE_PROVENANCE_BRANCH &&\n            branchId !== preferredBranchId,\n        ),\n    ),\n  ].sort((left, right) => compareStrings(left, right));\n\n  const resolution: EntityResolution = {\n    canonicalId,\n    memberIds,\n    kind,\n    branchOrigins,\n    // The merge orchestrator replaces this with the witness selected from the\n    // post-guard surviving edge set. Canonicalization never re-derives evidence.\n    decisiveEdges: [],\n  };\n\n  // Window precedence mirrors committed-first assertion precedence: when the\n  // live incremental target itself contributed a member for the surviving\n  // identity, the target's committed window wins — a user branch's staged\n  // window must not end (or re-window) a row the target already holds.\n  // Otherwise the survivor member's own staged window rides.\n  const windowSource =\n    members.find(\n      (member) =>\n        member.branchId === COMMITTED_TARGET_BRANCH &&\n        member.kind === kind &&\n        member.id === canonicalId,\n    ) ?? survivor;\n  return {\n    canonicalId,\n    kind,\n    props,\n    resolution,\n    conflicts,\n    ...(windowSource.validFrom === undefined ?\n      {}\n    : { validFrom: windowSource.validFrom }),\n    ...(windowSource.validTo === undefined ?\n      {}\n    : { validTo: windowSource.validTo }),\n    ...(typeof windowSource.validFrom === \"string\" ?\n      { endpointValidFrom: windowSource.validFrom }\n    : {}),\n    ...(windowSource.validTo === undefined ?\n      {}\n    : { endpointValidTo: windowSource.validTo }),\n  };\n}\n","import { requireDefined } from \"../utils/presence\";\n/**\n * A deterministic disjoint-set forest (union-find), shared by every merge phase\n * that folds a set of items into equivalence classes — ontology equivalence\n * (`closures.ts`), candidate clustering (`clustering.ts`), and cross-kind identity\n * grouping (`sources.ts`).\n *\n * Determinism is the load-bearing property: path compression keeps `find` flat,\n * and the union rule makes the chosen representative a pure function of the union\n * SET, not the union order — the item that compares LEAST (by the `compare`\n * supplied at construction) always becomes the root. Two runs that union the same\n * pairs in any order therefore produce identical roots, which is what lets the\n * merge's partitions be order-independent. Callers that only need the partition\n * (and re-sort each group) may pass any total order; callers that expose the\n * representative (e.g. an equivalence-class canonical) pass the comparator whose\n * minimum they want as the representative.\n */\nexport class UnionFind<T> {\n  private readonly parent = new Map<T, T>();\n\n  constructor(private readonly compare: (left: T, right: T) => number) {}\n\n  /** Adds `value` as its own singleton set if it is not already present. */\n  add(value: T): void {\n    if (!this.parent.has(value)) {\n      this.parent.set(value, value);\n    }\n  }\n\n  /** Returns the representative of `value`'s set, compressing the path to it. */\n  find(value: T): T {\n    this.add(value);\n    let root = value;\n    while (this.parent.get(root) !== root) {\n      root = requireDefined(this.parent.get(root));\n    }\n    // Path compression: point every node on the walk straight at the root.\n    let cursor = value;\n    while (cursor !== root) {\n      const next = requireDefined(this.parent.get(cursor));\n      this.parent.set(cursor, root);\n      cursor = next;\n    }\n    return root;\n  }\n\n  /** Merges the sets of `left` and `right`; the `compare`-minimal root wins. */\n  union(left: T, right: T): void {\n    const leftRoot = this.find(left);\n    const rightRoot = this.find(right);\n    if (leftRoot === rightRoot) {\n      return;\n    }\n    if (this.compare(leftRoot, rightRoot) <= 0) {\n      this.parent.set(rightRoot, leftRoot);\n    } else {\n      this.parent.set(leftRoot, rightRoot);\n    }\n  }\n\n  /** Every value seen by {@link add}/{@link find}/{@link union}, insertion order. */\n  members(): readonly T[] {\n    return [...this.parent.keys()];\n  }\n}\n","/**\n * Ontology subclass-closure glue over TypeGraph's PUBLIC closure utilities.\n *\n * TypeGraph 0.29.0 exports `computeTransitiveClosure` / `invertClosure` /\n * `isReachable` from the package root, and `store.introspect().ontology` exposes\n * the declared meta-edges as `{ metaEdge, from, to, origin }` records. This\n * module is therefore THIN GLUE: it projects the introspected ontology onto the\n * `[child, parent]` relation pairs the public closure builder expects, folds in\n * type-level equivalence classes (`equivalentTo` and its deprecated `sameAs`\n * alias), and exposes the {@link isReachable}\n * accessor reconcileTypes (T10) consumes. There is deliberately NO local Warshall\n * reimplementation — the transitive work is done entirely by the public\n * `computeTransitiveClosure`.\n *\n * Direction convention (verified against `store.introspect()` at runtime):\n * `subClassOf(Child, Parent)` introspects as `{ metaEdge: \"subClassOf\",\n * from: \"Child\", to: \"Parent\" }`. So `from` is the more-specific (child) type\n * and `to` is the more-general (parent) type, matching the `[child, parent]`\n * relation pairs `computeTransitiveClosure` consumes, where `isReachable(closure,\n * child, ancestor)` answers \"is `child` a (transitive) subclass of `ancestor`?\".\n */\nimport { compareStrings } from \"./node-key\";\nimport type { OntologyIntrospection } from \"./typegraph-internal\";\nimport {\n  computeTransitiveClosure,\n  isReachable as isReachablePublic,\n  META_EDGE_EQUIVALENT_TO,\n  META_EDGE_SAME_AS,\n} from \"./typegraph-internal\";\nimport { UnionFind } from \"./union-find\";\n\n/**\n * The meta-edge name identifying a subclass relation in `introspect().ontology`.\n */\nexport const SUB_CLASS_OF_META_EDGE = \"subClassOf\";\n\n/**\n * The meta-edge names identifying a type-level equivalence relation in\n * `introspect().ontology`. These edges are folded into symmetric equivalence\n * classes so that equivalent types share each other's ancestors and descendants.\n *\n * `sameAs` is the deprecated alias of `equivalentTo` and MUST be treated\n * identically here: `introspect()` reports the declared meta-edge name verbatim,\n * and both the kind registry (`kind-registry.ts`) and ontology validation collapse\n * the two into one case. Recognizing only `equivalentTo` would silently give a\n * `sameAs` ontology a different type-reconciliation outcome from an otherwise\n * identical `equivalentTo` one.\n */\nconst EQUIVALENCE_META_EDGES: ReadonlySet<string> = new Set([\n  META_EDGE_EQUIVALENT_TO,\n  META_EDGE_SAME_AS,\n]);\n\n/**\n * An immutable subclass closure plus the equivalence-class canonicalization used\n * to fold `equivalentTo` relations.\n *\n * - `closure` maps each (canonicalized) child type to the set of all its\n *   (canonicalized) transitive ancestors, as produced by the public\n *   `computeTransitiveClosure`.\n * - `canonicalOf` maps every type seen in the ontology to its equivalence-class\n *   representative (the lexicographically-smallest member). Types not involved\n *   in any `equivalentTo` relation map to themselves.\n */\nexport type SubClassClosure = Readonly<{\n  closure: ReadonlyMap<string, ReadonlySet<string>>;\n  canonicalOf: ReadonlyMap<string, string>;\n}>;\n\n/**\n * Builds the subclass closure from an introspected ontology.\n *\n * Steps:\n *   1. Fold every equivalence relation ({@link EQUIVALENCE_META_EDGES}) into a\n *      union-find so equivalent types collapse to a single deterministic\n *      representative.\n *   2. Project every `subClassOf` relation onto a `[childRep, parentRep]` pair\n *      (each endpoint canonicalized to its equivalence representative). Self\n *      loops introduced by equivalence are dropped — a type is never its own\n *      strict subclass.\n *   3. Hand the relation pairs to the PUBLIC `computeTransitiveClosure`. No local\n *      transitive-closure logic exists here.\n *\n * @param ontology The `store.introspect().ontology` array.\n * @returns A `SubClassClosure` queryable via `isReachable` (which canonicalizes\n *   its inputs through the equivalence map).\n */\nexport function buildSubClassClosure(\n  ontology: readonly OntologyIntrospection[],\n): SubClassClosure {\n  // Union by lexicographically-smaller representative, so each equivalence class's\n  // canonical is its lex-min member, independent of relation insertion order.\n  const unionFind = new UnionFind<string>(compareStrings);\n\n  for (const relation of ontology) {\n    unionFind.add(relation.from);\n    unionFind.add(relation.to);\n    if (EQUIVALENCE_META_EDGES.has(relation.metaEdge)) {\n      unionFind.union(relation.from, relation.to);\n    }\n  }\n\n  const canonicalOf = new Map<string, string>();\n  for (const value of unionFind.members()) {\n    canonicalOf.set(value, unionFind.find(value));\n  }\n\n  const relationKeys = new Set<string>();\n  const relations: (readonly [string, string])[] = [];\n  for (const relation of ontology) {\n    if (relation.metaEdge !== SUB_CLASS_OF_META_EDGE) {\n      continue;\n    }\n    const child = canonicalOf.get(relation.from) ?? relation.from;\n    const parent = canonicalOf.get(relation.to) ?? relation.to;\n    if (child === parent) {\n      continue;\n    }\n    const key = `${child}\\0${parent}`;\n    if (relationKeys.has(key)) {\n      continue;\n    }\n    relationKeys.add(key);\n    relations.push([child, parent]);\n  }\n\n  return {\n    closure: computeTransitiveClosure(relations),\n    canonicalOf,\n  };\n}\n\n/**\n * Resolves a type name to its equivalence-class representative, falling back to\n * the name itself when the type was never seen in the ontology.\n */\nfunction canonicalType(closure: SubClassClosure, type: string): string {\n  return closure.canonicalOf.get(type) ?? type;\n}\n\n/**\n * Reports whether `from` is a (transitive) subclass of `to`.\n *\n * Both arguments are canonicalized through the equivalence map first, then the\n * PUBLIC `isReachable` is consulted. Equivalent-but-distinct types (e.g.\n * `equivalentTo(Physician, Doctor)`) are treated as mutually reachable. A type\n * is NOT considered a subclass of itself (the relation is strict / irreflexive),\n * matching the public closure's non-reflexive semantics.\n *\n * @param closure The closure produced by `buildSubClassClosure`.\n * @param from The candidate descendant (more-specific) type.\n * @param to The candidate ancestor (more-general) type.\n */\nexport function isReachable(\n  closure: SubClassClosure,\n  from: string,\n  to: string,\n): boolean {\n  const fromRep = canonicalType(closure, from);\n  const toRep = canonicalType(closure, to);\n  if (fromRep === toRep) {\n    // Distinct names that fold to the same equivalence class are mutually\n    // reachable; identical names are NOT (strict subclass relation).\n    return from !== to;\n  }\n  return isReachablePublic(closure.closure, fromRep, toRep);\n}\n","import { canonicalValueKey } from \"./canonical-props\";\nimport type { MergeKey } from \"./node-key\";\nimport {\n  compareMergeKeys,\n  compareStrings,\n  idOf,\n  kindOf,\n  mergeKey,\n} from \"./node-key\";\nimport type { JsonValue, NodeId, NodeType } from \"./typegraph-internal\";\nimport type { SimilarityStrategy } from \"./types\";\n\n/** A complete graph-merge node identity. */\nexport type EntityRef = Readonly<{\n  kind: string;\n  id: NodeId<NodeType>;\n}>;\n\n/** Structured attribution for one candidate-recall path. */\nexport type MatchSource =\n  | Readonly<{ kind: \"block\"; sourceId: string }>\n  | Readonly<{\n      kind: \"unique\";\n      sourceId: string;\n      constraintName: string;\n    }>\n  | Readonly<{\n      kind: \"baseUnique\";\n      sourceId: string;\n      constraintName: string;\n    }>\n  | Readonly<{\n      kind: \"baseIndex\";\n      sourceId: string;\n      indexName: string;\n    }>\n  | Readonly<{ kind: \"keyless\"; sourceId: string }>\n  | Readonly<{ kind: \"retype\"; sourceId: string }>\n  | Readonly<{\n      kind: \"custom\";\n      sourceId: string;\n      metadata?: JsonValue | undefined;\n    }>;\n\n/** JSON-safe description of the strategy that actually scored a pair. */\nexport type MatchStrategy =\n  | Readonly<{ kind: \"fulltext\"; fields: readonly string[] }>\n  | Readonly<{ kind: \"vector\"; fields: readonly string[] }>\n  | Readonly<{\n      kind: \"hybrid\";\n      fields: readonly string[];\n      weights: Readonly<{ vector: number; fulltext: number }>;\n    }>\n  | Readonly<{ kind: \"custom\" }>;\n\n/** Serializable explanation for one accepted identity edge. */\nexport type MatchEvidence =\n  | Readonly<{\n      a: EntityRef;\n      b: EntityRef;\n      sources: readonly MatchSource[];\n      decision: \"definitional\";\n    }>\n  | Readonly<{\n      a: EntityRef;\n      b: EntityRef;\n      sources: readonly MatchSource[];\n      decision: \"scored\";\n      strategy: MatchStrategy;\n      score: number;\n      threshold: number;\n    }>;\n\n/** One opt-in scorer observation, retained independently of cluster membership. */\nexport type CandidateDiagnostic =\n  | Readonly<{\n      evidence: Extract<MatchEvidence, Readonly<{ decision: \"scored\" }>>;\n      scoreDecision: \"accepted\" | \"rejected\";\n      reason?: \"noComparableValues\";\n      clusterDisposition?:\n        | \"retained\"\n        | Readonly<{\n            kind: \"excluded\";\n            reason: \"diameter\" | \"baseAmbiguity\";\n          }>;\n    }>\n  | Readonly<{\n      evidence: Extract<MatchEvidence, Readonly<{ decision: \"definitional\" }>>;\n      scoreDecision: \"accepted\";\n      clusterDisposition: Readonly<{\n        kind: \"excluded\";\n        reason: \"diameter\" | \"baseAmbiguity\";\n      }>;\n    }>;\n\n/** Bounded public diagnostic collection assembled by the merge planner. */\nexport type CandidateDiagnostics = Readonly<{\n  entries: readonly CandidateDiagnostic[];\n  total: number;\n  limit: number;\n  truncated: boolean;\n}>;\n\n/** Converts an internal composite key into its public JSON-safe identity. */\nexport function entityRef(key: MergeKey): EntityRef {\n  return { kind: kindOf(key), id: idOf(key) };\n}\n\nconst SOURCE_KIND_ORDER: Readonly<Record<MatchSource[\"kind\"], number>> = {\n  block: 0,\n  unique: 1,\n  baseUnique: 2,\n  baseIndex: 3,\n  keyless: 4,\n  retype: 5,\n  custom: 6,\n};\n\n/** Canonical JSON key for source deduplication and ordering. */\nfunction sourceKey(source: MatchSource): string {\n  switch (source.kind) {\n    case \"block\":\n    case \"keyless\":\n    case \"retype\": {\n      return JSON.stringify([SOURCE_KIND_ORDER[source.kind], source.sourceId]);\n    }\n    case \"unique\":\n    case \"baseUnique\": {\n      return JSON.stringify([\n        SOURCE_KIND_ORDER[source.kind],\n        source.sourceId,\n        source.constraintName,\n      ]);\n    }\n    case \"baseIndex\": {\n      return JSON.stringify([\n        SOURCE_KIND_ORDER[source.kind],\n        source.sourceId,\n        source.indexName,\n      ]);\n    }\n    case \"custom\": {\n      return JSON.stringify([\n        SOURCE_KIND_ORDER.custom,\n        source.sourceId,\n        source.metadata === undefined ? \"\" : canonicalValueKey(source.metadata),\n      ]);\n    }\n    default: {\n      const exhaustive: never = source;\n      return exhaustive;\n    }\n  }\n}\n\n/** Total order shared by evidence producers and wire validation. */\nexport function compareMatchSources(\n  left: MatchSource,\n  right: MatchSource,\n): number {\n  return compareStrings(sourceKey(left), sourceKey(right));\n}\n\n/** Canonical endpoint order shared by evidence producers and wire validation. */\nexport function compareEntityRefs(\n  left: Readonly<{ kind: string; id: string }>,\n  right: Readonly<{ kind: string; id: string }>,\n): number {\n  return compareMergeKeys(\n    mergeKey(left.kind, left.id),\n    mergeKey(right.kind, right.id),\n  );\n}\n\n/** Stable, duplicate-free union of every attribution for an endpoint pair. */\nexport function normalizeMatchSources(\n  sources: readonly MatchSource[],\n): readonly MatchSource[] {\n  const byKey = new Map<string, MatchSource>();\n  for (const source of sources) {\n    byKey.set(sourceKey(source), source);\n  }\n  return [...byKey]\n    .sort(([, left], [, right]) => compareMatchSources(left, right))\n    .map(([, source]) => source);\n}\n\nconst DEFAULT_HYBRID_WEIGHT = 0.5;\n\n/** Builds the effective, function-free strategy descriptor used in evidence. */\nexport function describeMatchStrategy(\n  strategy: SimilarityStrategy,\n): MatchStrategy {\n  switch (strategy.kind) {\n    case \"fulltext\": {\n      return { kind: \"fulltext\", fields: [...strategy.fields] };\n    }\n    case \"vector\": {\n      return { kind: \"vector\", fields: [strategy.field] };\n    }\n    case \"hybrid\": {\n      const vector = strategy.weights?.vector ?? DEFAULT_HYBRID_WEIGHT;\n      const fulltext = strategy.weights?.fulltext ?? DEFAULT_HYBRID_WEIGHT;\n      const total = vector + fulltext;\n      const weights =\n        total === 0 ?\n          { vector: DEFAULT_HYBRID_WEIGHT, fulltext: DEFAULT_HYBRID_WEIGHT }\n        : { vector: vector / total, fulltext: fulltext / total };\n      return { kind: \"hybrid\", fields: [...strategy.fields], weights };\n    }\n    case \"custom\": {\n      return { kind: \"custom\" };\n    }\n    default: {\n      const exhaustive: never = strategy;\n      return exhaustive;\n    }\n  }\n}\n\n/** Total order for evidence and diagnostic serialization. */\nexport function compareMatchEvidence(\n  left: MatchEvidence,\n  right: MatchEvidence,\n): number {\n  const byA = compareEntityRefs(left.a, right.a);\n  if (byA !== 0) return byA;\n  return compareEntityRefs(left.b, right.b);\n}\n","import { readOwnProperty } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\n/**\n * Pluggable, symmetric candidate-pair similarity scoring (design §8, T6).\n *\n * Four strategy kinds, two of which are the ZERO-EMBEDDING P0 default:\n *\n *   - `custom`   — the caller's own `score(a, b)` function, clamped to `[0, 1]`.\n *   - `fulltext` — an IN-MEMORY Sørensen–Dice trigram coefficient over the\n *                  configured `fields` of the two staged nodes. No embeddings,\n *                  no DB round-trips, identical across every backend. This is\n *                  the portable scorer the FHIR demo runs on.\n *   - `vector` / `hybrid` — REAL embeddings scored IN MEMORY. An injected\n *                  {@link import(\"./types\").Embedder} (precomputed by `merge()`\n *                  into `ctx.embeddings`, a text→vector lookup) turns each node's\n *                  configured field text into a vector; the pair is scored by\n *                  cosine. `vector` is pure cosine over one field; `hybrid` blends\n *                  cosine with the Dice trigram by `weights` (default 0.5 / 0.5).\n *                  Staged candidate rows are unindexed, so a backend ANN index\n *                  cannot score them pairwise — exact in-memory cosine is the right\n *                  tool at candidate-dedup scale AND is deterministic (the merge\n *                  contract). With NO embedder configured (`ctx.embeddings`\n *                  absent), scoring fails with a typed\n *                  {@link SimilarityUnavailableError}.\n *\n * IMPORTANT: this module never touches `store.search.fulltext`. Staged candidate\n * nodes are unindexed in the working copy, so the DB fulltext index cannot score\n * them; the in-memory Dice scorer is the only correct option for staged\n * candidate generation. `store.search.fulltext` is reserved for the T11 parity\n * probe.\n *\n * Symmetry is a load-bearing invariant: clustering treats candidate edges as\n * undirected, so `scorePair(a, b)` MUST equal `scorePair(b, a)`. The Dice\n * coefficient is symmetric by construction; the `custom` branch documents the\n * requirement and the caller is responsible for honoring it.\n */\nimport { canonicalValueKey } from \"./canonical-props\";\nimport {\n  MatchEvidenceError,\n  type MergeError,\n  SimilarityUnavailableError,\n} from \"./errors\";\nimport type { MergeKey } from \"./node-key\";\nimport type { Result } from \"./result\";\nimport { err, ok } from \"./result\";\nimport type {\n  GraphBackend,\n  JsonValue,\n  Node,\n  NodeType,\n} from \"./typegraph-internal\";\nimport type { SimilarityStrategy } from \"./types\";\n\n/**\n * Ambient context a scorer needs beyond the two nodes.\n *\n * - `backend` is carried for diagnostics (the dialect in error details).\n * - `embeddings` is the precomputed text→vector lookup `merge()` builds by running\n *   the injected {@link import(\"./types\").Embedder} over every staged field text of\n *   the `vector`/`hybrid` kinds. Its PRESENCE means an embedder was configured;\n *   its ABSENCE makes a `vector`/`hybrid` strategy fail with\n *   {@link SimilarityUnavailableError}. `fulltext`/`custom` never read it.\n */\nexport type SimilarityContext = Readonly<{\n  backend: GraphBackend;\n  embeddings?: ReadonlyMap<string, Float32Array>;\n}>;\n\n/** Lower bound of the similarity codomain. */\nconst MIN_SCORE = 0;\n\n/** Upper bound of the similarity codomain. */\nconst MAX_SCORE = 1;\n\n/**\n * Sub-threshold sentinel returned by {@link scorePrepared} for a pair with NO\n * comparable text (one side has no value in the scoring field). It is BELOW\n * {@link MIN_SCORE}, and the kind's `threshold` is validated to `[0, 1]`, so a\n * textless pair can never clear ANY threshold — including `threshold: 0`, where\n * a `MIN_SCORE` (0) return would otherwise pass `score >= threshold` and merge two\n * distinct entities that share no evidence. The standalone {@link scorePair}\n * surfaces this as `MIN_SCORE` to keep its `[0, 1]` contract; only candidate-gen\n * (via {@link createPairScorer} + the threshold gate) treats it as \"never a match\".\n */\nconst NO_EVIDENCE_SCORE = -1;\n\n/** Trigram window length for the Sørensen–Dice coefficient. */\nconst TRIGRAM_LENGTH = 3;\n\n/**\n * Padding character framing a normalized string before trigram extraction, so\n * leading/trailing characters are weighted like interior ones and very short\n * strings still produce trigrams. A space is conventional and cannot appear in a\n * trigram alongside itself for non-trivial inputs.\n */\nconst TRIGRAM_PAD = \" \";\n\n/**\n * Clamps a finite number into the `[0, 1]` similarity codomain. Custom scorers\n * are checked for finiteness before reaching this helper; built-in strategies\n * only produce finite values.\n */\nfunction clampScore(value: number): number {\n  if (Number.isNaN(value)) {\n    return MIN_SCORE;\n  }\n  if (value < MIN_SCORE) {\n    return MIN_SCORE;\n  }\n  if (value > MAX_SCORE) {\n    return MAX_SCORE;\n  }\n  return value;\n}\n\n/**\n * Reads a single schema field off a node. `Node<N>` spreads its schema\n * properties at the top level (e.g. `node.name`, not `node.props.name`), so a\n * field is indexed directly on the node.\n *\n * Own-key read: `fields` is an unvalidated `readonly string[]` off the caller's\n * `similarity` config, so it may name a field the node does not carry. A raw\n * read would answer such a field named after an `Object.prototype` member\n * (\"toString\") with the inherited function, which {@link stringifyFieldValue}\n * renders identically for EVERY node — collapsing distinct entities into one\n * cluster at similarity 1.0. Absent must read absent, exactly as\n * `constraintSignature` in `blocking.ts` reads it.\n */\nfunction readField(node: Node<NodeType>, field: string): unknown {\n  return readOwnProperty(node, field);\n}\n\n/**\n * Concatenates a node's configured `fields` into a single lowercase comparison\n * string. Non-string field values are coerced via `String(...)`; absent /\n * `undefined` fields contribute nothing. Fields are joined with a space so two\n * adjacent fields cannot fuse into a spurious cross-field trigram.\n *\n * Exported so `merge()`'s embedding precompute keys the text→vector lookup by the\n * EXACT same text `scorePair` looks up — there is a single source of truth for \"the\n * text of a node under a strategy's fields\", so the precompute and the scorer can\n * never disagree on what to embed.\n */\nexport function fieldText(\n  node: Node<NodeType>,\n  fields: readonly string[],\n): string {\n  const parts: string[] = [];\n  for (const field of fields) {\n    const value = readField(node, field);\n    if (value === undefined || value === null) {\n      continue;\n    }\n    parts.push(stringifyFieldValue(value));\n  }\n  return parts.join(TRIGRAM_PAD).toLowerCase();\n}\n\nfunction stringifyFieldValue(value: unknown): string {\n  if (typeof value === \"string\") {\n    return value;\n  }\n  if (\n    typeof value === \"number\" ||\n    typeof value === \"boolean\" ||\n    typeof value === \"bigint\"\n  ) {\n    return String(value);\n  }\n  // Objects/arrays: canonical (recursively key-sorted) JSON so two\n  // logically-equal values written with different key order yield the same\n  // comparison text — matching canonicalValueKey used everywhere else.\n  return canonicalValueKey(value as JsonValue);\n}\n\n/**\n * Extracts the trigram MULTISET of a normalized string as a count map. A\n * multiset (not a set) is required so repeated trigrams contribute their full\n * multiplicity to the Dice intersection, matching the standard Sørensen–Dice\n * formulation `2·|A∩B| / (|A|+|B|)` over bags.\n */\nfunction trigramMultiset(text: string): Map<string, number> {\n  const counts = new Map<string, number>();\n  if (text.length === 0) {\n    return counts;\n  }\n  const padded = `${TRIGRAM_PAD}${text}${TRIGRAM_PAD}`;\n  for (let index = 0; index + TRIGRAM_LENGTH <= padded.length; index += 1) {\n    const gram = padded.slice(index, index + TRIGRAM_LENGTH);\n    counts.set(gram, (counts.get(gram) ?? 0) + 1);\n  }\n  return counts;\n}\n\n/** Total cardinality (with multiplicity) of a trigram multiset. */\nfunction multisetSize(counts: Map<string, number>): number {\n  let total = 0;\n  for (const count of counts.values()) {\n    total += count;\n  }\n  return total;\n}\n\n/**\n * Multiset intersection cardinality: for every shared trigram, the lesser of\n * the two multiplicities.\n */\nfunction multisetIntersectionSize(\n  left: Map<string, number>,\n  right: Map<string, number>,\n): number {\n  let shared = 0;\n  for (const [gram, leftCount] of left) {\n    const rightCount = right.get(gram);\n    if (rightCount !== undefined) {\n      shared += Math.min(leftCount, rightCount);\n    }\n  }\n  return shared;\n}\n\n/**\n * Computes the symmetric Sørensen–Dice trigram coefficient of two raw strings:\n * lowercase, pad, extract trigram multisets, then `2·|A∩B| / (|A|+|B|)`.\n *\n * Edge cases:\n *   - Two empty strings score {@link MAX_SCORE} (vacuously identical).\n *   - One empty and one non-empty score {@link MIN_SCORE}.\n *\n * Exported so the determinism / acceptance tests can assert the metric directly.\n */\n/**\n * Sørensen–Dice coefficient over two PRECOMPUTED trigram multisets — the metric\n * core, with the same empty-input rules as {@link diceTrigramSimilarity}. The\n * candidate scorer prepares each node's multiset ONCE and calls this directly, so\n * a node's trigrams are built once rather than rebuilt for every pair it joins.\n */\nfunction diceFromMultisets(\n  left: Map<string, number>,\n  right: Map<string, number>,\n): number {\n  const leftSize = multisetSize(left);\n  const rightSize = multisetSize(right);\n  if (leftSize === 0 && rightSize === 0) {\n    return MAX_SCORE;\n  }\n  if (leftSize === 0 || rightSize === 0) {\n    return MIN_SCORE;\n  }\n  const shared = multisetIntersectionSize(left, right);\n  return (2 * shared) / (leftSize + rightSize);\n}\n\nexport function diceTrigramSimilarity(left: string, right: string): number {\n  return diceFromMultisets(\n    trigramMultiset(left.toLowerCase()),\n    trigramMultiset(right.toLowerCase()),\n  );\n}\n\n/**\n * The field(s) whose text a `vector`/`hybrid` strategy embeds, or `undefined` for\n * the zero-embedding strategies (`fulltext`/`custom`). `merge()`'s precompute uses\n * this to decide which staged texts to embed; `scorePair` uses the SAME selection\n * implicitly via {@link fieldText}, so the embedded text and the looked-up text\n * match exactly.\n */\nexport function embeddingFields(\n  strategy: SimilarityStrategy,\n): readonly string[] | undefined {\n  switch (strategy.kind) {\n    case \"vector\": {\n      return [strategy.field];\n    }\n    case \"hybrid\": {\n      return strategy.fields;\n    }\n    case \"fulltext\":\n    case \"custom\": {\n      return undefined;\n    }\n    default: {\n      const exhaustive: never = strategy;\n      throw new Error(\n        `Unhandled similarity strategy: ${JSON.stringify(exhaustive)}`,\n      );\n    }\n  }\n}\n\n/**\n * Cosine similarity of two equal-length vectors, in `[-1, 1]`. Computed in a fixed\n * index order so it is deterministic. Returns {@link MIN_SCORE} for a dimension\n * mismatch or a zero-magnitude vector (no comparable direction → no evidence),\n * never `NaN`. `scorePair` clamps the result into the `[0, 1]` similarity codomain.\n *\n */\nfunction cosineSimilarity(left: Float32Array, right: Float32Array): number {\n  if (left.length !== right.length || left.length === 0) {\n    return MIN_SCORE;\n  }\n  let dot = 0;\n  let leftMagnitude = 0;\n  let rightMagnitude = 0;\n  for (let index = 0; index < left.length; index += 1) {\n    const leftComponent = requireDefined(left[index]);\n    const rightComponent = requireDefined(right[index]);\n    dot += leftComponent * rightComponent;\n    leftMagnitude += leftComponent * leftComponent;\n    rightMagnitude += rightComponent * rightComponent;\n  }\n  if (leftMagnitude === 0 || rightMagnitude === 0) {\n    return MIN_SCORE;\n  }\n  return dot / (Math.sqrt(leftMagnitude) * Math.sqrt(rightMagnitude));\n}\n\n/**\n * Cosine of the two field texts' precomputed vectors. A text whose vector is\n * absent from the lookup (only possible if the precompute and scorer disagreed —\n * they cannot, since both go through {@link fieldText}) scores {@link MIN_SCORE}\n * defensively rather than throwing.\n */\nfunction cosineFromLookup(\n  embeddings: ReadonlyMap<string, Float32Array>,\n  leftText: string,\n  rightText: string,\n): number {\n  const leftVector = embeddings.get(leftText);\n  const rightVector = embeddings.get(rightText);\n  if (leftVector === undefined || rightVector === undefined) {\n    return MIN_SCORE;\n  }\n  return cosineSimilarity(leftVector, rightVector);\n}\n\n/** Default hybrid blend: equal weight to the vector and fulltext components. */\nconst DEFAULT_HYBRID_WEIGHT = 0.5;\n\n/**\n * Coerces a raw weight into the non-negative finite domain. A non-finite value\n * (`NaN`/`±Infinity`) contributes `0` rather than poisoning the whole blend —\n * `Math.max(0, NaN)` is `NaN`, which would survive the `total === 0` guard and\n * collapse every hybrid score to 0. Valid weights are rejected earlier at the\n * options boundary (`normalizeMergeOptions`); this is the defensive backstop.\n */\nfunction nonNegativeFinite(value: number): number {\n  return Number.isFinite(value) ? Math.max(0, value) : 0;\n}\n\n/**\n * Normalizes a hybrid strategy's `weights` so the vector and fulltext components\n * sum to 1, defaulting either omitted side to {@link DEFAULT_HYBRID_WEIGHT}. A\n * degenerate `{0, 0}` (or negative / non-finite) total falls back to an even\n * 0.5/0.5 split so the blend can never divide by zero, invert, or produce `NaN`.\n */\nfunction normalizeHybridWeights(\n  weights: Readonly<{ vector?: number; fulltext?: number }> | undefined,\n): Readonly<{ vector: number; fulltext: number }> {\n  const vector = nonNegativeFinite(weights?.vector ?? DEFAULT_HYBRID_WEIGHT);\n  const fulltext = nonNegativeFinite(\n    weights?.fulltext ?? DEFAULT_HYBRID_WEIGHT,\n  );\n  const total = vector + fulltext;\n  if (total === 0) {\n    return { vector: DEFAULT_HYBRID_WEIGHT, fulltext: DEFAULT_HYBRID_WEIGHT };\n  }\n  return { vector: vector / total, fulltext: fulltext / total };\n}\n\n/**\n * Builds the {@link SimilarityUnavailableError} for a `vector`/`hybrid` strategy\n * requested with no configured embedder.\n */\nfunction embedderUnavailable(\n  kind: \"vector\" | \"hybrid\",\n  ctx: SimilarityContext,\n): SimilarityUnavailableError {\n  return new SimilarityUnavailableError(\n    `Similarity strategy \"${kind}\" requires a configured embedder (MergeOptions.embedder); none was provided.`,\n    { details: { strategy: kind, dialect: ctx.backend.dialect } },\n  );\n}\n\n/**\n * The field(s) a strategy reads off a node to form its comparison text: the\n * embedded field(s) for `vector`/`hybrid`, the configured `fields` for `fulltext`,\n * and none for `custom` (which scores the node objects directly).\n */\nfunction scoringFields(strategy: SimilarityStrategy): readonly string[] {\n  switch (strategy.kind) {\n    case \"fulltext\":\n    case \"hybrid\": {\n      return strategy.fields;\n    }\n    case \"vector\": {\n      return [strategy.field];\n    }\n    case \"custom\": {\n      return [];\n    }\n    default: {\n      const exhaustive: never = strategy;\n      throw new Error(\n        `Unhandled similarity strategy: ${JSON.stringify(exhaustive)}`,\n      );\n    }\n  }\n}\n\n/**\n * A node's per-strategy comparison inputs, computed ONCE and reused across every\n * pair the node joins: its lowercase {@link fieldText} (looked up in the embedding\n * map for `vector`/`hybrid`) and, for the trigram strategies, its trigram multiset.\n * The original `node` is retained for the `custom` strategy, which scores nodes\n * directly. {@link createPairScorer} memoizes one of these per node.\n */\ntype PreparedNode<K extends NodeType = NodeType> = Readonly<{\n  node: Node<K>;\n  text: string;\n  grams: Map<string, number>;\n}>;\n\n/** Empty trigram multiset shared by strategies that never consult grams. */\nconst NO_GRAMS: Map<string, number> = new Map<string, number>();\n\n/** Computes a node's {@link PreparedNode} for a strategy (trigrams only when used). */\nfunction prepareNode<K extends NodeType>(\n  node: Node<K>,\n  strategy: SimilarityStrategy,\n): PreparedNode<K> {\n  const text = fieldText(node, scoringFields(strategy));\n  const grams =\n    strategy.kind === \"fulltext\" || strategy.kind === \"hybrid\" ?\n      trigramMultiset(text)\n    : NO_GRAMS;\n  return { node, text, grams };\n}\n\n/**\n * Scores a candidate pair from its two {@link PreparedNode}s under a\n * {@link SimilarityStrategy}, returning a value in `[0, 1]` (guaranteed symmetric\n * for the built-in strategies). This is the single match-decision switch;\n * {@link scorePair} and {@link createPairScorer} both feed it prepared nodes.\n *\n * @returns `ok(score)` on success, or `err(SimilarityUnavailableError)` when a\n *   `vector`/`hybrid` strategy is requested with no configured embedder.\n */\nfunction scorePrepared<K extends NodeType>(\n  left: PreparedNode<K>,\n  right: PreparedNode<K>,\n  strategy: SimilarityStrategy,\n  ctx: SimilarityContext,\n): Result<number, MergeError> {\n  switch (strategy.kind) {\n    case \"custom\": {\n      // The caller owns symmetry here. A non-finite result cannot be represented\n      // faithfully in JSON evidence, so refuse it instead of silently converting\n      // NaN to zero or Infinity to a perfect match.\n      let raw: number;\n      try {\n        raw = strategy.score(left.node, right.node);\n      } catch (error) {\n        return err(\n          new MatchEvidenceError(\"Custom similarity scorer failed.\", {\n            details: {\n              kind: left.node.kind,\n              sourceId: \"similarity:custom\",\n              operation: \"score\",\n            },\n            cause: error,\n          }),\n        );\n      }\n      if (!Number.isFinite(raw)) {\n        return err(\n          new MatchEvidenceError(\n            \"Custom similarity scorer returned a non-finite score.\",\n            {\n              details: {\n                kind: left.node.kind,\n                sourceId: \"similarity:custom\",\n                operation: \"score\",\n                score: String(raw),\n              },\n            },\n          ),\n        );\n      }\n      return ok(clampScore(raw));\n    }\n    case \"fulltext\": {\n      // A node with NO text in the configured fields offers no evidence of a\n      // match. Comparing two such nodes must NOT collapse two distinct entities,\n      // NOT even at threshold 0 — so it returns the sub-threshold\n      // {@link NO_EVIDENCE_SCORE}, never the vacuous diceTrigramSimilarity(\"\",\"\")\n      // === 1. The metric itself keeps empty==empty==1 for direct callers / the\n      // acceptance tests; this guard is candidate-gen's policy.\n      if (left.text.length === 0 || right.text.length === 0) {\n        return ok(NO_EVIDENCE_SCORE);\n      }\n      return ok(clampScore(diceFromMultisets(left.grams, right.grams)));\n    }\n    case \"vector\": {\n      // Presence of `ctx.embeddings` == an embedder was configured. Absent → the\n      // caller asked for vector similarity without supplying MergeOptions.embedder.\n      if (ctx.embeddings === undefined) {\n        return err(embedderUnavailable(\"vector\", ctx));\n      }\n      // A node with no text in the field offers no evidence of a match —\n      // NO_EVIDENCE_SCORE, not the cosine of two zero/absent vectors (mirrors the\n      // fulltext guard, and excludes the pair even at threshold 0).\n      if (left.text.length === 0 || right.text.length === 0) {\n        return ok(NO_EVIDENCE_SCORE);\n      }\n      const cosine = cosineFromLookup(ctx.embeddings, left.text, right.text);\n      return ok(clampScore(cosine));\n    }\n    case \"hybrid\": {\n      if (ctx.embeddings === undefined) {\n        return err(embedderUnavailable(\"hybrid\", ctx));\n      }\n      if (left.text.length === 0 || right.text.length === 0) {\n        return ok(NO_EVIDENCE_SCORE);\n      }\n      // Blend exact in-memory cosine (semantic/spelling proximity) with the Dice\n      // trigram (literal character overlap) by the normalized weights. Both\n      // components are symmetric, so the blend is too.\n      const vectorScore = clampScore(\n        cosineFromLookup(ctx.embeddings, left.text, right.text),\n      );\n      const fulltextScore = diceFromMultisets(left.grams, right.grams);\n      const weights = normalizeHybridWeights(strategy.weights);\n      return ok(\n        clampScore(\n          weights.vector * vectorScore + weights.fulltext * fulltextScore,\n        ),\n      );\n    }\n    default: {\n      // Exhaustiveness guard: a new strategy kind must add a branch above, or\n      // this assignment fails to compile.\n      const exhaustive: never = strategy;\n      throw new Error(\n        `Unhandled similarity strategy: ${JSON.stringify(exhaustive)}`,\n      );\n    }\n  }\n}\n\n/**\n * Scores a candidate pair under a {@link SimilarityStrategy}, returning a value\n * in `[0, 1]` (guaranteed symmetric for the built-in strategies). A single-pair\n * convenience over {@link scorePrepared}; the candidate loop uses\n * {@link createPairScorer} instead so per-node work is not repeated across pairs.\n *\n * @param a   First staged node.\n * @param b   Second staged node.\n * @param strategy The per-kind similarity strategy from the kind's `ResolveConfig`.\n * @param ctx Ambient context (the backend, for vector-capability gating).\n * @returns `ok(score)` on success, or `err(SimilarityUnavailableError)` when a\n *   `vector`/`hybrid` strategy is requested with no configured embedder.\n */\nexport function scorePair<K extends NodeType>(\n  a: Node<K>,\n  b: Node<K>,\n  strategy: SimilarityStrategy,\n  ctx: SimilarityContext,\n): Result<number, MergeError> {\n  const result = scorePrepared(\n    prepareNode(a, strategy),\n    prepareNode(b, strategy),\n    strategy,\n    ctx,\n  );\n  // The standalone scorer's contract is a [0, 1] score; the internal\n  // NO_EVIDENCE_SCORE sentinel (a textless pair) surfaces here as MIN_SCORE. Only\n  // candidate-gen needs the sub-threshold value to exclude the pair at threshold 0.\n  if (result.success && result.data === NO_EVIDENCE_SCORE) {\n    return ok(MIN_SCORE);\n  }\n  return result;\n}\n\n/**\n * Builds a memoized pair scorer for one kind. Each node's {@link PreparedNode} is\n * computed once, keyed by its `(kind, id)` {@link MergeKey}, so a node appearing in\n * m candidate pairs has its text + trigram multiset built once, not m times — the\n * per-bucket cost drops from O(pairs · text) trigram builds to O(nodes · text).\n * Pair-for-pair equivalent to {@link scorePair}.\n */\nexport function createPairScorer<K extends NodeType>(\n  strategy: SimilarityStrategy,\n  ctx: SimilarityContext,\n): (\n  a: MergeKey,\n  left: Node<K>,\n  b: MergeKey,\n  right: Node<K>,\n) => Result<number, MergeError> {\n  const prepared = new Map<MergeKey, PreparedNode<K>>();\n  const prepare = (key: MergeKey, node: Node<K>): PreparedNode<K> => {\n    const cached = prepared.get(key);\n    if (cached !== undefined) {\n      return cached;\n    }\n    const fresh = prepareNode(node, strategy);\n    prepared.set(key, fresh);\n    return fresh;\n  };\n  return (a, left, b, right) =>\n    scorePrepared(prepare(a, left), prepare(b, right), strategy, ctx);\n}\n","/**\n * The shared SCORING stage (design §4, the single match-decision point).\n *\n * Candidate generation is three layers — sources → scoring → reconciler (§4).\n * This module is the MIDDLE layer: it turns the candidate PROPOSALS every source\n * emits into the {@link CandidateEdge} set the reconciler consumes, applying the\n * EXACT same scorer + threshold regardless of which source proposed a pair. A\n * source proposes (recall); scoring disposes (the match decision).\n *\n * Two proposal kinds enter:\n *\n *   - {@link CandidatePair}s — unscored `(a, b)` node pairs from any source. They\n *     are deduped by canonical `(a, b)` and each scored EXACTLY ONCE by\n *     {@link scorePair}; only pairs clearing the kind's threshold become edges.\n *   - FORCED {@link CandidateEdge}s — DEFINITIONAL matches (a shared unique value)\n *     that BYPASS scoring entirely, emitted at {@link FORCED_MATCH_SCORE}. A forced\n *     pair is never also fuzzy-scored: forced `(a, b)` keys are reserved first, so\n *     a fuzzy pair proposing the same endpoints is dropped before scoring.\n *\n * This was previously fused into `candidate-gen.ts`'s `generateCandidates` (which\n * scored AND thresholded inline); naming scoring as its own stage is what makes\n * \"the scorer — not a source — decides matches\" concrete (§4). `generateCandidates`\n * now composes the bucket sources over this stage.\n *\n * Determinism: the emitted edge set is a pure function of the proposal SETS — pairs\n * are deduped by canonical `(a, b)`, scored by the symmetric {@link scorePair}, and\n * the final list is sorted by `(a, b)`, so neither the order proposals arrive in\n * nor the directionality of a pair affects the result.\n *\n * The {@link ComparisonCeilingPolicy} bounds only the FUZZY scoring work (the\n * embedder step for vector/hybrid); FORCED edges are definitional, not\n * similarity-based, so they are emitted regardless of the ceiling:\n *\n *   - `\"error\"`         — exceeding the ceiling fails with a typed {@link MergeError}.\n *   - `\"mergeByIdOnly\"` — fuzzy similarity is SKIPPED for the kind (no\n *                         threshold-scored edges), FORCED edges are still emitted,\n *                         and a {@link CandidateWarning} is recorded.\n */\n\nimport { MatchEvidenceError, MergeError } from \"./errors\";\nimport type {\n  CandidateDiagnostic,\n  MatchEvidence,\n  MatchSource,\n} from \"./evidence\";\nimport {\n  describeMatchStrategy,\n  entityRef,\n  normalizeMatchSources,\n} from \"./evidence\";\nimport { compareMergeKeys, type MergeKey } from \"./node-key\";\nimport type { Result } from \"./result\";\nimport { err, isErr, ok } from \"./result\";\nimport type { SimilarityContext } from \"./similarity\";\nimport { createPairScorer } from \"./similarity\";\nimport type { Node, NodeType } from \"./typegraph-internal\";\nimport type { ComparisonCeilingPolicy, ResolveConfig } from \"./types\";\n\n/**\n * An undirected candidate-merge edge between two nodes that should merge.\n * Endpoints are stored in ascending id order (`a < b`) so the edge has a single\n * canonical representation. Fuzzy edges carry their similarity score; FORCED\n * (definitional) edges carry {@link FORCED_MATCH_SCORE}.\n */\nexport type CandidateEdge = Readonly<{\n  a: MergeKey;\n  b: MergeKey;\n  /** Internal drop-weakest rank. Definitional 1 is never copied to evidence. */\n  score: number;\n  evidence: MatchEvidence;\n}>;\n\n/**\n * A non-fatal advisory raised during scoring — currently only the\n * `\"mergeByIdOnly\"` comparison-ceiling skip. Surfaced in the merge report.\n */\ntype CandidateWarning = Readonly<{\n  kind: \"comparisonCeiling\";\n  comparisons: number;\n  limit: number;\n  message: string;\n}>;\n\n/**\n * The scoring result for one kind: the emitted edges plus any advisories.\n * Returned inside a {@link Result} so the `vector`/`hybrid` guard and the\n * `\"error\"` ceiling path can fail without throwing.\n */\nexport type CandidateGenResult = Readonly<{\n  edges: readonly CandidateEdge[];\n  warnings: readonly CandidateWarning[];\n  diagnostics: readonly CandidateDiagnostic[];\n  diagnosticsTotal: number;\n}>;\n\n/**\n * An unscored candidate pair a source proposes for scoring: the canonical\n * endpoint ids `(a, b)` (`a < b`) plus the two node objects the scorer reads\n * fields off of. `left`/`right` carry the nodes whose ids are `a`/`b`\n * respectively, but {@link scorePair} is symmetric so their roles are\n * interchangeable for scoring.\n */\nexport type CandidatePair<K extends NodeType = NodeType> = Readonly<{\n  a: MergeKey;\n  b: MergeKey;\n  left: Node<K>;\n  right: Node<K>;\n  sources: readonly MatchSource[];\n}>;\n\n/**\n * The proposals the scoring stage consumes for one kind: the fuzzy pairs to score\n * and the forced (definitional) edges to pass through unscored.\n */\nexport type ScoringInput<K extends NodeType = NodeType> = Readonly<{\n  pairs: readonly CandidatePair<K>[];\n  forcedEdges: readonly CandidateEdge[];\n}>;\n\n/**\n * Score for a FORCED (definitional, unique-match) edge — the maximum, so the pair\n * always clears any threshold and is never the weakest edge a diameter guard would\n * drop. Sources that emit forced edges stamp this score; scoring passes it through.\n */\nexport const FORCED_MATCH_SCORE = 1;\n\n/**\n * Stable `(a, b)` ascending comparator over {@link CandidateEdge}. Endpoints are\n * `(kind, id)` MergeKeys, so ordering uses the SAME id-first {@link compareMergeKeys}\n * the clustering stage uses — never raw kind-first string order. The SINGLE shared\n * definition: clustering and `merge()`'s candidate generation import this instead of\n * re-deriving it, so every stage orders the edge set identically by construction.\n */\nexport function compareCandidateEdges(\n  left: CandidateEdge,\n  right: CandidateEdge,\n): number {\n  const byA = compareMergeKeys(left.a, right.a);\n  return byA === 0 ? compareMergeKeys(left.b, right.b) : byA;\n}\n\n/** The canonical dedup key for a pair / edge's ordered endpoints. */\nfunction endpointKey(a: MergeKey, b: MergeKey): string {\n  return JSON.stringify([a, b]);\n}\n\nfunction withSources(\n  edge: CandidateEdge,\n  sources: readonly MatchSource[],\n): CandidateEdge {\n  return {\n    ...edge,\n    evidence: {\n      ...edge.evidence,\n      sources: normalizeMatchSources([...edge.evidence.sources, ...sources]),\n    },\n  };\n}\n\n/**\n * Scores the proposed candidates for a single kind into a {@link CandidateEdge}\n * set, applying the kind's threshold and the comparison-ceiling policy.\n *\n * FORCED endpoint keys are reserved FIRST, so a fuzzy pair proposing the same\n * `(a, b)` is dropped before scoring — a forced (definitional) match is never also\n * fuzzy-scored. The remaining fuzzy pairs are deduped by canonical `(a, b)` and\n * scored exactly once; only those clearing `threshold` become edges. The combined\n * forced + passing-fuzzy edge list is sorted by `(a, b)`.\n *\n * @param input The fuzzy pairs + forced edges every source proposed for the kind.\n * @param resolveConfig The kind's resolution config (similarity strategy + threshold).\n * @param ctx Ambient context (the backend, for vector-capability gating).\n * @param ceilingPolicy Behavior when `maxComparisonsPerKind` is exceeded.\n * @param maxComparisonsPerKind Optional per-kind FUZZY-comparison ceiling.\n *   `undefined` means unbounded. Forced edges are never bounded by it.\n * @returns `ok({ edges, warnings })`, or `err(...)` when the `\"error\"` ceiling\n *   fires or a `vector`/`hybrid` guard trips.\n */\nexport function scoreCandidates<K extends NodeType>(\n  input: ScoringInput<K>,\n  resolveConfig: ResolveConfig,\n  ctx: SimilarityContext,\n  ceilingPolicy: ComparisonCeilingPolicy,\n  maxComparisonsPerKind?: number,\n  diagnosticLimit = 0,\n): Result<CandidateGenResult, MergeError> {\n  const { similarity, threshold } = resolveConfig;\n\n  // Reserve forced endpoint keys FIRST so a fuzzy pair proposing the same pair is\n  // dropped — a definitional match is never also fuzzy-scored (the old Phase-1\n  // before Phase-2 dedup, now source-agnostic).\n  const forcedByKey = new Map<string, CandidateEdge>();\n  for (const edge of input.forcedEdges) {\n    const key = endpointKey(edge.a, edge.b);\n    const previous = forcedByKey.get(key);\n    forcedByKey.set(\n      key,\n      previous === undefined ? edge : (\n        withSources(previous, edge.evidence.sources)\n      ),\n    );\n  }\n\n  const fuzzyByKey = new Map<string, CandidatePair<K>>();\n  for (const pair of input.pairs) {\n    const key = endpointKey(pair.a, pair.b);\n    const forced = forcedByKey.get(key);\n    if (forced !== undefined) {\n      forcedByKey.set(key, withSources(forced, pair.sources));\n      continue;\n    }\n    const previous = fuzzyByKey.get(key);\n    fuzzyByKey.set(\n      key,\n      previous === undefined ? pair : (\n        {\n          ...previous,\n          sources: normalizeMatchSources([\n            ...previous.sources,\n            ...pair.sources,\n          ]),\n        }\n      ),\n    );\n  }\n  const forced = [...forcedByKey.values()];\n  const fuzzy = [...fuzzyByKey.values()].sort((left, right) => {\n    const byA = compareMergeKeys(left.a, right.a);\n    return byA === 0 ? compareMergeKeys(left.b, right.b) : byA;\n  });\n\n  if (\n    maxComparisonsPerKind !== undefined &&\n    fuzzy.length > maxComparisonsPerKind\n  ) {\n    if (ceilingPolicy === \"error\") {\n      return err(\n        new MergeError(\n          `Comparison ceiling exceeded: ${fuzzy.length} candidate pairs > maxComparisonsPerKind ${maxComparisonsPerKind}.`,\n          {\n            details: {\n              comparisons: fuzzy.length,\n              limit: maxComparisonsPerKind,\n            },\n            suggestion:\n              'Tighten the kind\\'s block() to shrink buckets, or set onComparisonCeiling: \"mergeByIdOnly\".',\n          },\n        ),\n      );\n    }\n    // \"mergeByIdOnly\": skip FUZZY similarity for this kind, but KEEP the forced\n    // edges — those are definitional, not similarity-based.\n    return ok({\n      edges: [...forced].sort((left, right) =>\n        compareCandidateEdges(left, right),\n      ),\n      warnings: [\n        {\n          kind: \"comparisonCeiling\",\n          comparisons: fuzzy.length,\n          limit: maxComparisonsPerKind,\n          message: `Skipped similarity for this kind: ${fuzzy.length} candidate pairs exceeded maxComparisonsPerKind ${maxComparisonsPerKind}; nodes will merge by id and exact unique match only.`,\n        },\n      ],\n      diagnostics: [],\n      diagnosticsTotal: 0,\n    });\n  }\n\n  // One memoized scorer per kind so each node's text + trigram multiset is built\n  // once, not once per pair it joins (the within-bucket pair count is ~O(n²)).\n  const scorer = createPairScorer<K>(similarity, ctx);\n  const edges: CandidateEdge[] = [...forced];\n  const diagnostics: CandidateDiagnostic[] = [];\n  let diagnosticsTotal = 0;\n  for (const { left, right, a, b, sources } of fuzzy) {\n    const scored = scorer(a, left, b, right);\n    if (isErr(scored)) {\n      if (\n        similarity.kind === \"custom\" &&\n        scored.error instanceof MatchEvidenceError\n      ) {\n        return err(\n          new MatchEvidenceError(scored.error.message, {\n            cause: scored.error,\n            details: {\n              kind: left.kind,\n              operation: \"score\",\n              sourceIds: normalizeMatchSources(sources).map(\n                (source) => source.sourceId,\n              ),\n              endpoints: [entityRef(a), entityRef(b)],\n            },\n          }),\n        );\n      }\n      return err(scored.error);\n    }\n    if (!Number.isFinite(scored.data)) {\n      return err(\n        new MatchEvidenceError(\n          \"Similarity scorer returned a non-finite score.\",\n          {\n            details: {\n              kind: left.kind,\n              operation: \"score\",\n              sourceIds: normalizeMatchSources(sources).map(\n                (source) => source.sourceId,\n              ),\n              score: String(scored.data),\n            },\n          },\n        ),\n      );\n    }\n    const noComparableValues = scored.data < 0;\n    const publicScore = noComparableValues ? 0 : scored.data;\n    const accepted = !noComparableValues && scored.data >= threshold;\n    diagnosticsTotal += 1;\n    const retainsDiagnostic = diagnostics.length < diagnosticLimit;\n    if (accepted || retainsDiagnostic) {\n      const evidence: Extract<\n        MatchEvidence,\n        Readonly<{ decision: \"scored\" }>\n      > = {\n        a: entityRef(a),\n        b: entityRef(b),\n        sources: normalizeMatchSources(sources),\n        decision: \"scored\",\n        strategy: describeMatchStrategy(similarity),\n        score: publicScore,\n        threshold,\n      };\n      if (accepted) edges.push({ a, b, score: scored.data, evidence });\n      if (!retainsDiagnostic) continue;\n      diagnostics.push({\n        evidence,\n        scoreDecision: accepted ? \"accepted\" : \"rejected\",\n        ...(noComparableValues ?\n          { reason: \"noComparableValues\" as const }\n        : {}),\n      });\n    }\n  }\n\n  return ok({\n    edges: edges.sort((left, right) => compareCandidateEdges(left, right)),\n    warnings: [],\n    diagnostics,\n    diagnosticsTotal,\n  });\n}\n","import { requireDefined } from \"../utils/presence\";\n/**\n * Connected-components clustering over the candidate-edge graph (design §6.4\n * rule 2, T8).\n *\n * Two staged nodes are merged into the same cluster iff they are connected\n * (transitively) by a chain of candidate-merge edges. This is the SINGLE-LINK\n * rule: A~B and B~C cluster {A,B,C} even when A≁C directly, because each hop\n * cleared the similarity threshold. The frozen v1 default is single-link with NO\n * guard; the optional diameter guard (below) is the only deviation.\n *\n * Determinism:\n *   - The component assignment is computed via union-find over the candidate\n *     edge SET (a pure function of the edges, never their arrival order). We\n *     additionally order edge consumption by `(a, b)` and union with a\n *     min-id-as-root tie-break, so even the internal forest is identical across\n *     shuffled inputs — not merely the resulting partition.\n *   - Every cluster's `members` array is sorted by node id, and the cluster list\n *     is sorted by each cluster's minimum member id. So the output is fully\n *     canonical regardless of the order edges or seed node ids are supplied in.\n *\n * Diameter guard (optional, design §6.4 / T8):\n *   When `clusterMaxDiameter` is set, a formed component must satisfy a single\n *   bound: the maximum pairwise graph distance (in candidate-edge hops) between\n *   any two members must not exceed the guard. A component that violates the\n *   bound is split by the deterministic DROP-WEAKEST single-link rule: remove the\n *   lowest-scoring candidate edge (ties broken by `(a, b)` id order) and\n *   recompute components on the survivors, repeating until every sub-component\n *   satisfies the bound. This is the frozen v1 behavior — no correlation\n *   clustering in P0.\n */\nimport type { CandidateEdge } from \"./candidate-gen\";\nimport type { MatchEvidence } from \"./evidence\";\nimport { compareMergeKeys, type MergeKey } from \"./node-key\";\nimport { compareCandidateEdges } from \"./scoring\";\nimport { UnionFind } from \"./union-find\";\n\n/**\n * The node IDENTITY the cluster graph is built over: the composite `(kind, id)`\n * {@link MergeKey}, NOT a bare node id. Two different-kind nodes that share an id\n * string are DISTINCT identities here, so single-link clustering never fuses them\n * into one component (the base guard would otherwise be silently bypassed).\n */\ntype AnyNodeId = MergeKey;\n\n/**\n * A resolved cluster of node identities that the merge collapses into one canonical\n * survivor. `members` is always sorted (by id, then kind) and never empty.\n */\nexport type ClusterResult = Readonly<{\n  members: readonly AnyNodeId[];\n}>;\n\n/**\n * Builds connected components from a candidate-edge set plus an explicit seed\n * set of all node ids in scope. Seed ids with no incident edge become singleton\n * components, so the result partitions the ENTIRE node set, not just edge\n * endpoints.\n */\nfunction buildComponents(\n  edges: readonly CandidateEdge[],\n  nodeIds: readonly AnyNodeId[],\n  edgesSorted = false,\n): ClusterResult[] {\n  const forest = new UnionFind<AnyNodeId>(compareMergeKeys);\n  const seed = new Set<AnyNodeId>(nodeIds);\n  for (const id of nodeIds) {\n    forest.add(id);\n  }\n  // Consume edges in canonical order so the forest is identical across shuffles.\n  // An edge whose endpoint is NOT in the seed set is out of scope and skipped, so\n  // the partition is a function of exactly the supplied node set — a candidate\n  // edge can never inject a phantom member never passed in `nodeIds`.\n  // `edgesSorted` lets a caller that already holds the edges in canonical order\n  // (the drop-weakest loop) skip the redundant re-sort on every iteration.\n  const orderedEdges =\n    edgesSorted ? edges : (\n      [...edges].sort((left, right) => compareCandidateEdges(left, right))\n    );\n  for (const edge of orderedEdges) {\n    if (!seed.has(edge.a) || !seed.has(edge.b)) {\n      continue;\n    }\n    forest.union(edge.a, edge.b);\n  }\n\n  const byRoot = new Map<AnyNodeId, AnyNodeId[]>();\n  for (const id of forest.members()) {\n    const root = forest.find(id);\n    const bucket = byRoot.get(root);\n    if (bucket === undefined) {\n      byRoot.set(root, [id]);\n    } else {\n      bucket.push(id);\n    }\n  }\n\n  const clusters: ClusterResult[] = [];\n  for (const members of byRoot.values()) {\n    clusters.push({\n      members: [...members].sort((left, right) =>\n        compareMergeKeys(left, right),\n      ),\n    });\n  }\n  // Order clusters by their (sorted) first member, which is the minimum id.\n  clusters.sort((left, right) =>\n    compareMergeKeys(\n      requireDefined(left.members[0]),\n      requireDefined(right.members[0]),\n    ),\n  );\n  return clusters;\n}\n\n/**\n * Builds the undirected adjacency (member id → set of neighbor ids) for one\n * component's members, restricted to candidate edges whose BOTH endpoints are in\n * the component.\n */\nfunction adjacencyOf(\n  members: readonly AnyNodeId[],\n  edges: readonly CandidateEdge[],\n): Map<AnyNodeId, Set<AnyNodeId>> {\n  const memberSet = new Set(members);\n  const adjacency = new Map<AnyNodeId, Set<AnyNodeId>>();\n  for (const id of members) {\n    adjacency.set(id, new Set());\n  }\n  for (const edge of edges) {\n    if (memberSet.has(edge.a) && memberSet.has(edge.b)) {\n      requireDefined(adjacency.get(edge.a)).add(edge.b);\n      requireDefined(adjacency.get(edge.b)).add(edge.a);\n    }\n  }\n  return adjacency;\n}\n\n/**\n * Whether one component's pairwise graph diameter (in candidate-edge hops) EXCEEDS\n * `maxDiameter`. Runs a BFS from each member but EARLY-EXITS the moment it reaches\n * a node beyond `maxDiameter` (or finds the component disconnected), so a check\n * costs `O(members + edges-within-the-bound)` rather than the full all-pairs\n * `O(V·(V+E))` exact diameter — the guard only needs the threshold answer, never\n * the exact value. Equivalent to `componentDiameter(...) > maxDiameter`.\n */\nfunction exceedsDiameter(\n  members: readonly AnyNodeId[],\n  edges: readonly CandidateEdge[],\n  maxDiameter: number,\n): boolean {\n  if (members.length <= 1) {\n    return false;\n  }\n  const adjacency = adjacencyOf(members, edges);\n  for (const source of members) {\n    const distance = new Map<AnyNodeId, number>([[source, 0]]);\n    const queue: AnyNodeId[] = [source];\n    let head = 0;\n    while (head < queue.length) {\n      const current = requireDefined(queue[head]);\n      head += 1;\n      const currentDistance = requireDefined(distance.get(current));\n      for (const neighbor of requireDefined(adjacency.get(current))) {\n        if (!distance.has(neighbor)) {\n          const neighborDistance = currentDistance + 1;\n          if (neighborDistance > maxDiameter) {\n            return true; // a pair already exceeds the bound — stop early\n          }\n          distance.set(neighbor, neighborDistance);\n          queue.push(neighbor);\n        }\n      }\n    }\n    if (distance.size < members.length) {\n      return true; // disconnected from `source` → diameter is infinite\n    }\n  }\n  return false;\n}\n\n/**\n * The candidate edges internal to a single component (both endpoints inside it),\n * in canonical `(a, b)` order.\n */\nfunction internalEdges(\n  members: readonly AnyNodeId[],\n  edges: readonly CandidateEdge[],\n): CandidateEdge[] {\n  const memberSet = new Set(members);\n  return edges\n    .filter((edge) => memberSet.has(edge.a) && memberSet.has(edge.b))\n    .sort((left, right) => compareCandidateEdges(left, right));\n}\n\n/**\n * The single weakest edge of a set: lowest score, ties broken by `(a, b)` id\n * order. The deterministic edge the drop-weakest splits remove first.\n */\nfunction weakestEdge(edges: readonly CandidateEdge[]): CandidateEdge {\n  return edges.reduce((current, candidate) => {\n    if (candidate.score !== current.score) {\n      return candidate.score < current.score ? candidate : current;\n    }\n    return compareCandidateEdges(candidate, current) < 0 ? candidate : current;\n  });\n}\n\n/**\n * The shared DROP-WEAKEST splitter (design §6.4 / §6.4-A). Repeatedly removes the\n * lowest-scoring internal candidate edge (ties broken by `(a, b)` id order) and\n * recomputes components until NO sub-component is still `isOffending`, then returns\n * the satisfying sub-components. `isOffending` receives the current surviving edge\n * set so a predicate like the diameter check can measure against it.\n *\n * The degenerate \"still offending but no internal edge left to drop\" case — only\n * reachable if a future caller passes a ≥2-member component with no internal edge —\n * degrades EVERY such offending component to singletons (keeping every satisfying\n * sibling intact), so the partition is never silently truncated. It first exhausts the\n * splittable offending components (those with an edge to drop), so an edgeless\n * offending sibling can never leave another offending component unsplit.\n */\ntype SplitResult = Readonly<{\n  clusters: readonly ClusterResult[];\n  survivingEdges: readonly CandidateEdge[];\n  removedEdges: readonly CandidateEdge[];\n}>;\n\nfunction splitUntil(\n  members: readonly AnyNodeId[],\n  edges: readonly CandidateEdge[],\n  isOffending: (\n    members: readonly AnyNodeId[],\n    surviving: readonly CandidateEdge[],\n  ) => boolean,\n): SplitResult {\n  // `surviving` starts in canonical `(a, b)` order and `.filter` preserves it, so\n  // every iteration can pass it to `buildComponents` pre-sorted.\n  let surviving = internalEdges(members, edges);\n  const removedEdges: CandidateEdge[] = [];\n\n  for (;;) {\n    const components = buildComponents(surviving, members, true);\n    const offending = components.filter((component) =>\n      isOffending(component.members, surviving),\n    );\n    if (offending.length === 0) {\n      return { clusters: components, survivingEdges: surviving, removedEdges };\n    }\n    // Prefer to keep dropping the weakest edge of an offending component that still has\n    // one; only when EVERY offending component is edgeless do we degrade them all.\n    // Scan lazily — stop at the first offending component that still has an internal\n    // edge instead of materializing internalEdges for every offending component.\n    let splittable: CandidateEdge[] | undefined;\n    for (const component of offending) {\n      const componentEdges = internalEdges(component.members, surviving);\n      if (componentEdges.length > 0) {\n        splittable = componentEdges;\n        break;\n      }\n    }\n    if (splittable === undefined) {\n      const offendingSet = new Set(offending);\n      return {\n        clusters: components.flatMap((component) =>\n          offendingSet.has(component) ?\n            component.members.map((id) => ({ members: [id] }))\n          : [component],\n        ),\n        survivingEdges: surviving,\n        removedEdges,\n      };\n    }\n    const weakest = weakestEdge(splittable);\n    removedEdges.push(weakest);\n    surviving = surviving.filter((edge) => edge !== weakest);\n  }\n}\n\n/**\n * Splits a single over-diameter component by the deterministic DROP-WEAKEST\n * single-link rule until every resulting sub-component satisfies `maxDiameter`.\n */\nfunction splitByDropWeakest(\n  members: readonly AnyNodeId[],\n  edges: readonly CandidateEdge[],\n  maxDiameter: number,\n): SplitResult {\n  return splitUntil(members, edges, (componentMembers, surviving) =>\n    exceedsDiameter(componentMembers, surviving, maxDiameter),\n  );\n}\n\n/**\n * Computes the connected components of the candidate-edge graph over `nodeIds`,\n * applying the optional single-link diameter guard.\n *\n * @param candidateEdges Undirected candidate-merge edges (from T6). Order does\n *   not affect the result.\n * @param nodeIds Every node id in scope. Ids with no incident candidate edge\n *   become singleton clusters, so the output partitions the full set.\n * @returns Clusters with id-sorted members, sorted by minimum member id. Pure\n *   over the input edge/node SETS.\n *\n * The diameter guard is deliberately NOT applied here: {@link enforceBaseGuard}\n * (§6.4-A) must run on these RAW components FIRST, and only then may a caller run\n * {@link enforceDiameter}. Folding the diameter split back in would let it sever a\n * base↔base bridge before base multiplicity is detected.\n */\nexport function connectedComponents(\n  candidateEdges: readonly CandidateEdge[],\n  nodeIds: readonly AnyNodeId[],\n): readonly ClusterResult[] {\n  return buildComponents(candidateEdges, nodeIds);\n}\n\n/**\n * Applies the single-link DIAMETER guard to already-formed clusters: any cluster\n * whose pairwise diameter exceeds `clusterMaxDiameter` is split by the deterministic\n * drop-weakest rule. Separated from {@link connectedComponents} so the base guard\n * (§6.4-A) can run on the RAW pre-diameter components FIRST — a diameter split must\n * never sever a base↔base bridge before base-multiplicity is detected.\n */\nexport function enforceDiameter(\n  clusters: readonly ClusterResult[],\n  candidateEdges: readonly CandidateEdge[],\n  clusterMaxDiameter: number,\n): readonly ClusterResult[] {\n  return enforceDiameterWithEdges(clusters, candidateEdges, clusterMaxDiameter)\n    .clusters;\n}\n\nexport type ExcludedCandidateEdge = Readonly<{\n  edge: CandidateEdge;\n  reason: \"diameter\" | \"baseAmbiguity\";\n}>;\n\nexport type GuardedClusters = Readonly<{\n  clusters: readonly ClusterResult[];\n  survivingEdges: readonly CandidateEdge[];\n  excludedEdges: readonly ExcludedCandidateEdge[];\n}>;\n\n/** Diameter guard variant that preserves the exact post-split edge graph. */\nexport function enforceDiameterWithEdges(\n  clusters: readonly ClusterResult[],\n  candidateEdges: readonly CandidateEdge[],\n  clusterMaxDiameter: number,\n): GuardedClusters {\n  const guarded: ClusterResult[] = [];\n  let survivingEdges = [...candidateEdges];\n  const excludedEdges: ExcludedCandidateEdge[] = [];\n  for (const component of clusters) {\n    if (\n      exceedsDiameter(component.members, candidateEdges, clusterMaxDiameter)\n    ) {\n      const split = splitByDropWeakest(\n        component.members,\n        survivingEdges,\n        clusterMaxDiameter,\n      );\n      guarded.push(...split.clusters);\n      const memberSet = new Set(component.members);\n      survivingEdges = [\n        ...survivingEdges.filter(\n          (edge) => !(memberSet.has(edge.a) && memberSet.has(edge.b)),\n        ),\n        ...split.survivingEdges,\n      ].sort((left, right) => compareCandidateEdges(left, right));\n      excludedEdges.push(\n        ...split.removedEdges.map((edge) => ({\n          edge,\n          reason: \"diameter\" as const,\n        })),\n      );\n    } else {\n      guarded.push(component);\n    }\n  }\n  guarded.sort((left, right) =>\n    compareMergeKeys(\n      requireDefined(left.members[0]),\n      requireDefined(right.members[0]),\n    ),\n  );\n  return { clusters: guarded, survivingEdges, excludedEdges };\n}\n\n/** Count of a component's members that are committed BASE nodes. */\nfunction countBaseMembers(\n  members: readonly AnyNodeId[],\n  baseIds: ReadonlySet<AnyNodeId>,\n): number {\n  let count = 0;\n  for (const id of members) {\n    if (baseIds.has(id)) {\n      count += 1;\n    }\n  }\n  return count;\n}\n\n/**\n * Splits a component holding ≥2 base members by the deterministic DROP-WEAKEST rule\n * until NO surviving sub-component holds two base members. This is CONTAINMENT, not\n * resolution: it removes the lowest-scoring BRIDGING edges (forced new↔base edges,\n * at max score, are dropped last), so the distinct committed entities land in\n * separate clusters and BOTH survive — it never \"picks\" which base wins (§6.4-A).\n */\nfunction splitByBaseMultiplicity(\n  members: readonly AnyNodeId[],\n  edges: readonly CandidateEdge[],\n  baseIds: ReadonlySet<AnyNodeId>,\n): SplitResult {\n  return splitUntil(\n    members,\n    edges,\n    (componentMembers) => countBaseMembers(componentMembers, baseIds) >= 2,\n  );\n}\n\n/**\n * A connected component that spanned ≥2 distinct committed base entities — an\n * AMBIGUOUS match (§6.4-A). Reported regardless of how the component was split:\n * any component that EVER bridged two base identities is an ambiguity event.\n */\nexport type BaseMultiplicityEvent = Readonly<{\n  baseIds: readonly AnyNodeId[];\n  memberIds: readonly AnyNodeId[];\n}>;\n\n/**\n * Component-level BASE GUARD (§6.4-A). Single-link clustering is transitive, so two\n * committed entities fuse whenever ANY chain links them (`baseA ~ new ~ baseB`, or\n * through staged hops `baseA ~ new1 ~ new2 ~ baseB` where no single new node spans\n * both). A node-level guard misses the chain case; this guard is COMPONENT-level.\n *\n * MUST run on the RAW connected components, BEFORE any diameter split — otherwise a\n * diameter guard could sever a base↔base bridge into single-base pieces and the\n * ambiguity would go unreported (§6.4-A: reported regardless of how it split).\n *\n * Any component containing ≥2 distinct base members is an ambiguous match and is\n * reported as a {@link BaseMultiplicityEvent}. The committed entities are ALWAYS kept\n * SEPARATE — the base↔base collapse is REFUSED by splitting the component\n * (drop-weakest, containment only) until no sub-component holds two base members.\n * Splitting never downgrades the event from ambiguous, and never silently picks which\n * base wins. (A deliberate-collapse trust path is deferred until committed-entity\n * re-keying + edge repoint exist; §6.4-C.)\n *\n * A no-op fast path when there are no base members (the public snapshot path).\n *\n * @returns the guarded clusters (id-sorted members, sorted by min member id) and\n *   one event per component that spanned ≥2 base entities.\n */\nexport function enforceBaseGuard(\n  clusters: readonly ClusterResult[],\n  candidateEdges: readonly CandidateEdge[],\n  baseIds: ReadonlySet<AnyNodeId>,\n): Readonly<{\n  clusters: readonly ClusterResult[];\n  events: readonly BaseMultiplicityEvent[];\n  survivingEdges: readonly CandidateEdge[];\n  excludedEdges: readonly ExcludedCandidateEdge[];\n}> {\n  if (baseIds.size === 0) {\n    return {\n      clusters,\n      events: [],\n      survivingEdges: [...candidateEdges].sort((left, right) =>\n        compareCandidateEdges(left, right),\n      ),\n      excludedEdges: [],\n    };\n  }\n\n  const result: ClusterResult[] = [];\n  const events: BaseMultiplicityEvent[] = [];\n  let survivingEdges = [...candidateEdges];\n  const excludedEdges: ExcludedCandidateEdge[] = [];\n  for (const cluster of clusters) {\n    const clusterBaseIds = cluster.members.filter((id) => baseIds.has(id));\n    if (clusterBaseIds.length < 2) {\n      result.push(cluster);\n      continue;\n    }\n    events.push({\n      baseIds: [...clusterBaseIds].sort((left, right) =>\n        compareMergeKeys(left, right),\n      ),\n      memberIds: [...cluster.members].sort((left, right) =>\n        compareMergeKeys(left, right),\n      ),\n    });\n    // Always REFUSE the base↔base collapse: split for containment so both committed\n    // entities survive separately (§6.4-A). A deliberate collapse is deferred (§6.4-C).\n    const split = splitByBaseMultiplicity(\n      cluster.members,\n      survivingEdges,\n      baseIds,\n    );\n    result.push(...split.clusters);\n    const memberSet = new Set(cluster.members);\n    survivingEdges = [\n      ...survivingEdges.filter(\n        (edge) => !(memberSet.has(edge.a) && memberSet.has(edge.b)),\n      ),\n      ...split.survivingEdges,\n    ].sort((left, right) => compareCandidateEdges(left, right));\n    excludedEdges.push(\n      ...split.removedEdges.map((edge) => ({\n        edge,\n        reason: \"baseAmbiguity\" as const,\n      })),\n    );\n  }\n  result.sort((left, right) =>\n    compareMergeKeys(\n      requireDefined(left.members[0]),\n      requireDefined(right.members[0]),\n    ),\n  );\n  return { clusters: result, events, survivingEdges, excludedEdges };\n}\n\n/**\n * Selects a deterministic minimal connectivity witness for a final cluster.\n * Canonical Kruskal selection over the post-guard edge set yields N-1 evidence\n * edges for every connected N-member cluster and can never cite a removed edge.\n */\nexport function decisiveEdgesForCluster(\n  cluster: ClusterResult,\n  survivingEdges: readonly CandidateEdge[],\n): readonly MatchEvidence[] {\n  const members = new Set(cluster.members);\n  const forest = new UnionFind<AnyNodeId>(compareMergeKeys);\n  for (const member of cluster.members) forest.add(member);\n\n  const decisive: MatchEvidence[] = [];\n  for (const edge of internalEdges(cluster.members, survivingEdges)) {\n    if (!members.has(edge.a) || !members.has(edge.b)) continue;\n    if (forest.find(edge.a) === forest.find(edge.b)) continue;\n    forest.union(edge.a, edge.b);\n    decisive.push(edge.evidence);\n  }\n  return decisive;\n}\n","import { createDataKeyedBag, hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\n/**\n * Node-level delete/modify conflict resolution (design §6.2, T8a).\n *\n * The §6.2 case the draft omitted: an INHERITED node that one fork DELETES while\n * another fork MODIFIES is neither a pure deletion nor a pure modification — it\n * is a delete/modify conflict whose outcome is governed by the\n * {@link DeleteModifyPolicy} (`\"deleteWins\"` | `\"modifyWins\"` | `\"flag\"`) and\n * surfaced in the {@link MergeReport}.\n *\n * This module is a PURE decision function over the staging set (T7) plus the\n * captured stable branch order (T8). It runs BEFORE clustering/canonicalize feed\n * the surviving modifications into the property union, and BEFORE edge repoint\n * (T9), to which it hands the authoritative FINAL LIVENESS of every inherited\n * endpoint:\n *\n *   - a node finally deleted (`\"deleteWins\"`) → it is in {@link nodeDeletions};\n *     T9 drops every edge touching it.\n *   - a node kept/resurrected (`\"modifyWins\"` / `\"flag\"`, or never deleted) →\n *     its modifications are in {@link survivingModifications}; T9 keeps its edges.\n *\n * DETERMINISM CONTRACT (inherited from the merge-wide invariant):\n *   The keep-vs-delete decision is a function ONLY of the policy and the\n *   (unordered) set of contributing branches — it NEVER consults wall-clock\n *   arrival. The captured `branchRank` is used solely to TIE-BREAK which\n *   modification survives under `\"modifyWins\"` / `\"flag\"` (and which branch ids\n *   are recorded as `deletedBy` / `modifiedBy`), so two merges of the same branch\n *   set in any order resolve every delete/modify conflict identically.\n */\nimport { canonicalValueKey } from \"./canonical-props\";\nimport type { ProvenanceWeights, ResolutionContext } from \"./conflict-policy\";\nimport {\n  collectConflictingValues,\n  resolvePropertyUnion,\n} from \"./conflict-policy\";\nimport { compareStrings, type MergeKey, mergeKey } from \"./node-key\";\nimport type {\n  StagedModifiedEdge,\n  StagedModifiedNode,\n  StagingSet,\n} from \"./staging\";\nimport type { DeletedEdge } from \"./state-diff\";\nimport type {\n  EdgeId,\n  GraphDef,\n  JsonValue,\n  NodeId,\n  NodeType,\n} from \"./typegraph-internal\";\nimport type {\n  BranchId,\n  DeleteModifyConflict,\n  DeleteModifyPolicy,\n  DroppedItem,\n  PropertyConflict,\n  PropertyConflictPolicy,\n} from \"./types\";\n\n/** A node id in its untyped (`NodeType`-default) branded form. */\ntype AnyNodeId = NodeId<NodeType>;\n/** The `(kind, id)` of a node the delete/modify resolution finally deletes. */\ntype DeletedNodeRef = Readonly<{ id: AnyNodeId; kind: string }>;\ntype BranchTagged = Readonly<{ branchId: BranchId }>;\n\n/** Reason recorded on a {@link DroppedItem} for a finally-deleted node. */\nexport const DELETED_NODE_DROP_REASON = \"delete-modify:deleteWins\" as const;\n\n/**\n * The outcome of delete/modify resolution over the whole staging set.\n *\n * - `survivingModifications`: every staged inherited-node modification that the\n *   merge will still apply — i.e. all modifications NOT overridden by a\n *   `\"deleteWins\"` resolution. A node modified by several branches contributes\n *   several entries here (one per branch), so T8's property union still sees the\n *   full cross-branch disagreement.\n * - `nodeDeletions`: the AUTHORITATIVE set of inherited nodes that are finally\n *   deleted — pure deletions (no branch modified them) plus delete/modify\n *   conflicts resolved `\"deleteWins\"`. T9 reads this as the endpoint liveness.\n *   Entries are the surviving deletion's `(kind, id)` only: a staged deletion\n *   additionally records WHEN its branch removed the node, which is per-branch\n *   evidence rather than a merge outcome.\n * - `conflicts`: one {@link DeleteModifyConflict} per inherited node that was\n *   both deleted and modified.\n * - `dropped`: a `{ kind: \"node\" }` {@link DroppedItem} for every finally-deleted\n *   node, so the report can enumerate exactly what left the merged graph.\n */\nexport type DeleteModifyResolution = Readonly<{\n  survivingModifications: readonly StagedModifiedNode[];\n  nodeDeletions: readonly DeletedNodeRef[];\n  conflicts: readonly DeleteModifyConflict[];\n  dropped: readonly DroppedItem[];\n}>;\n\n/**\n * Picks the HIGHEST-PRIORITY branch from a set — the one with the lowest\n * `branchRank` (earliest in the captured stable order). Ties on rank fall back to\n * lexicographic branch-id order, so the choice is total and deterministic. Used\n * to record `deletedBy` / `modifiedBy` and to select which modification survives.\n */\nfunction pickHighestPriorityBranch(\n  branchIds: readonly BranchId[],\n  branchRank: ReadonlyMap<BranchId, number>,\n): BranchId {\n  let chosen = requireDefined(branchIds[0]);\n  let chosenRank = branchRank.get(chosen) ?? Number.MAX_SAFE_INTEGER;\n  for (const candidate of branchIds.slice(1)) {\n    const candidateRank = branchRank.get(candidate) ?? Number.MAX_SAFE_INTEGER;\n    if (\n      candidateRank < chosenRank ||\n      (candidateRank === chosenRank && compareStrings(candidate, chosen) < 0)\n    ) {\n      chosen = candidate;\n      chosenRank = candidateRank;\n    }\n  }\n  return chosen;\n}\n\nfunction effectiveDeleteModifyPolicy(\n  policy: DeleteModifyPolicy,\n  deletions: readonly BranchTagged[],\n  modifications: readonly BranchTagged[],\n  preferredBranchId: BranchId | undefined,\n): DeleteModifyPolicy {\n  if (\n    preferredBranchId !== undefined &&\n    deletions.some((deletion) => deletion.branchId === preferredBranchId)\n  ) {\n    return \"deleteWins\";\n  }\n  if (\n    policy === \"deleteWins\" &&\n    preferredBranchId !== undefined &&\n    modifications.some(\n      (modification) => modification.branchId === preferredBranchId,\n    )\n  ) {\n    return \"modifyWins\";\n  }\n  return policy;\n}\n\n/**\n * Groups staged items by the `(kind, id)` IDENTITY of the entity `entityOf` extracts\n * (a node or an edge), preserving the per-identity arrays so callers can inspect every\n * contributing branch. Keying on the composite identity (not bare id) keeps an\n * inherited `Patient` and an inherited `Encounter` that share an id string from being\n * reconciled/deleted as if they were one entity.\n */\nfunction groupByEntity<T>(\n  items: readonly T[],\n  entityOf: (item: T) => Readonly<{ id: string; kind: string }>,\n): ReadonlyMap<MergeKey, readonly T[]> {\n  const grouped = new Map<MergeKey, T[]>();\n  for (const item of items) {\n    const entity = entityOf(item);\n    const key = mergeKey(entity.kind, entity.id);\n    const bucket = grouped.get(key);\n    if (bucket === undefined) {\n      grouped.set(key, [item]);\n    } else {\n      bucket.push(item);\n    }\n  }\n  return grouped;\n}\n\n/**\n * The shared node/edge DELETE-MODIFY resolver — the single control flow behind\n * {@link resolveDeleteModify} (nodes) and {@link resolveEdgeDeleteModify} (edges).\n * `modifiedEntity`/`deletedEntity` extract each staged item's `(id, kind)` (its\n * `.node` or `.edge`), and `dropDeleted` builds the {@link DroppedItem} for a\n * finally-deleted entity — a factory rather than a `\"node\" | \"edge\"` tag because\n * `DroppedItem` is discriminated on `kind`, so only the caller can pair the right\n * discriminant with its own id type. Everything else — conflict detection, policy\n * application, pure-deletion/pure-modification passthrough, and the canonical\n * output sort — is identical for both.\n */\nfunction resolveDeleteModifyOver<\n  ModifiedItem extends BranchTagged,\n  DeletedItem extends BranchTagged,\n  Id extends AnyNodeId | EdgeId,\n>(\n  modified: readonly ModifiedItem[],\n  deleted: readonly DeletedItem[],\n  modifiedEntity: (item: ModifiedItem) => Readonly<{ id: Id; kind: string }>,\n  deletedEntity: (item: DeletedItem) => Readonly<{ id: Id; kind: string }>,\n  dropDeleted: (id: Id) => DroppedItem,\n  policy: DeleteModifyPolicy,\n  branchRank: ReadonlyMap<BranchId, number>,\n  preferredBranchId: BranchId | undefined,\n): Readonly<{\n  survivingModifications: readonly ModifiedItem[];\n  deletions: readonly Readonly<{ id: Id; kind: string }>[];\n  conflicts: readonly DeleteModifyConflict[];\n  dropped: readonly DroppedItem[];\n}> {\n  const modifiedByKey = groupByEntity(modified, modifiedEntity);\n  const deletedByKey = groupByEntity(deleted, deletedEntity);\n\n  const survivingModifications: ModifiedItem[] = [];\n  const deletions: Readonly<{ id: Id; kind: string }>[] = [];\n  const conflicts: DeleteModifyConflict[] = [];\n  const dropped: DroppedItem[] = [];\n\n  const conflictedKeys = new Set<MergeKey>();\n  for (const key of deletedByKey.keys()) {\n    if (modifiedByKey.has(key)) {\n      conflictedKeys.add(key);\n    }\n  }\n\n  for (const [key, modifications] of modifiedByKey) {\n    if (!conflictedKeys.has(key)) {\n      for (const modification of modifications) {\n        survivingModifications.push(modification);\n      }\n      continue;\n    }\n\n    const deletionsForKey = requireDefined(deletedByKey.get(key));\n    const { id, kind } = modifiedEntity(requireDefined(modifications[0]));\n    const deletedBy = pickHighestPriorityBranch(\n      deletionsForKey.map((deletion) => deletion.branchId),\n      branchRank,\n    );\n    const modifiedBy = pickHighestPriorityBranch(\n      modifications.map((modification) => modification.branchId),\n      branchRank,\n    );\n    const effectivePolicy = effectiveDeleteModifyPolicy(\n      policy,\n      deletionsForKey,\n      modifications,\n      preferredBranchId,\n    );\n\n    conflicts.push({\n      entityId: id,\n      kind,\n      deletedBy,\n      modifiedBy,\n      resolution: effectivePolicy,\n    });\n\n    if (effectivePolicy === \"deleteWins\") {\n      deletions.push({ id, kind });\n      dropped.push(dropDeleted(id));\n      continue;\n    }\n\n    // \"modifyWins\" and \"flag\" both KEEP the modification (resurrect the entity);\n    // \"flag\" additionally leaves the recorded conflict unresolved for review.\n    for (const modification of modifications) {\n      survivingModifications.push(modification);\n    }\n  }\n\n  for (const [key, deletionsForKey] of deletedByKey) {\n    if (conflictedKeys.has(key)) {\n      continue;\n    }\n    const { id, kind } = deletedEntity(requireDefined(deletionsForKey[0]));\n    deletions.push({ id, kind });\n  }\n\n  return {\n    survivingModifications: [...survivingModifications].sort((left, right) => {\n      const byId = compareStrings(\n        modifiedEntity(left).id,\n        modifiedEntity(right).id,\n      );\n      return byId === 0 ? compareStrings(left.branchId, right.branchId) : byId;\n    }),\n    deletions: [...deletions].sort((left, right) =>\n      compareStrings(left.id, right.id),\n    ),\n    conflicts: [...conflicts].sort((left, right) =>\n      compareStrings(left.entityId, right.entityId),\n    ),\n    dropped: [...dropped].sort((left, right) =>\n      compareStrings(left.id, right.id),\n    ),\n  };\n}\n\n/**\n * The shared node/edge MODIFICATION reconciler — the single control flow behind\n * {@link reconcileModifications} (nodes) and {@link reconcileEdgeModifications}\n * (edges). Groups by `(kind, id)`, 3-way merges every multi-branch modification via\n * {@link threeWayMergeProps}, and rebuilds ONE surviving record per id via `rebuild`\n * (carrying the highest-priority contributor's branch + the merged props).\n */\nfunction reconcileOver<Item extends BranchTagged>(\n  survivingModifications: readonly Item[],\n  entityOf: (item: Item) => Readonly<{\n    id: AnyNodeId | EdgeId;\n    kind: string;\n    baseProps: Readonly<Record<string, unknown>>;\n    forkProps: Readonly<Record<string, unknown>>;\n  }>,\n  rebuild: (\n    representative: Item,\n    chosenBranch: BranchId,\n    mergedProps: Record<string, JsonValue>,\n  ) => Item,\n  policy: PropertyConflictPolicy,\n  branchRank: ReadonlyMap<BranchId, number>,\n  weights: ProvenanceWeights | undefined,\n  preferredBranchId: BranchId | undefined,\n): Readonly<{\n  survivingModifications: readonly Item[];\n  conflicts: readonly PropertyConflict[];\n}> {\n  const context: ResolutionContext<GraphDef> = {\n    policy,\n    ...(weights === undefined ? {} : { weights }),\n  };\n\n  const grouped = groupByEntity(survivingModifications, entityOf);\n  const out: Item[] = [];\n  const conflicts: PropertyConflict[] = [];\n\n  for (const modifications of grouped.values()) {\n    if (modifications.length === 1) {\n      out.push(requireDefined(modifications[0]));\n      continue;\n    }\n    const first = entityOf(requireDefined(modifications[0]));\n    const { props, conflicts: propertyConflicts } = threeWayMergeProps(\n      first.id,\n      first.kind,\n      first.baseProps as Readonly<Record<string, JsonValue>>,\n      modifications.map((modification) => ({\n        branchId: modification.branchId,\n        forkProps: entityOf(modification).forkProps as Readonly<\n          Record<string, JsonValue>\n        >,\n      })),\n      context,\n      branchRank,\n      preferredBranchId,\n    );\n    const chosenBranch = pickHighestPriorityBranch(\n      modifications.map((modification) => modification.branchId),\n      branchRank,\n    );\n    const representative =\n      modifications.find(\n        (modification) => modification.branchId === chosenBranch,\n      ) ?? requireDefined(modifications[0]);\n    out.push(rebuild(representative, chosenBranch, props));\n    for (const conflict of propertyConflicts) {\n      conflicts.push(conflict);\n    }\n  }\n\n  return {\n    survivingModifications: [...out].sort((left, right) => {\n      const byId = compareStrings(entityOf(left).id, entityOf(right).id);\n      return byId === 0 ? compareStrings(left.branchId, right.branchId) : byId;\n    }),\n    conflicts: conflicts.sort((left, right) =>\n      compareStrings(\n        `${left.entityId}|${left.property}`,\n        `${right.entityId}|${right.property}`,\n      ),\n    ),\n  };\n}\n\n/**\n * Resolves every inherited node that is simultaneously DELETED by one or more\n * branches and MODIFIED by one or more (other) branches, per the\n * {@link DeleteModifyPolicy}:\n *\n *   - `\"deleteWins\"` → the node is finally deleted (its modifications are\n *     discarded). A {@link DeleteModifyConflict} with `resolution: \"deleteWins\"`\n *     is recorded and a `{ kind: \"node\" }` {@link DroppedItem} is emitted.\n *   - `\"modifyWins\"` → the node is RESURRECTED: its modifications survive (the\n *     deletion is ignored). A conflict with `resolution: \"modifyWins\"` is\n *     recorded; the node is NOT deleted.\n *   - `\"flag\"` → the modifications survive (as with `\"modifyWins\"`) but the\n *     conflict is recorded UNRESOLVED (`resolution: \"flag\"`) for human review.\n *\n * Pure deletions (no branch modified the node) pass straight through to\n * {@link nodeDeletions}; pure modifications (no branch deleted the node) pass\n * straight through to {@link survivingModifications}. Both unconflicted paths\n * carry NO {@link DeleteModifyConflict}.\n *\n * The result is order-independent: the keep-vs-delete decision depends only on\n * the policy and the contributing branch SET; `branchRank` is consulted solely to\n * tie-break which modification survives and which branch ids are recorded.\n *\n * @param staging The provenance-tagged union staging set (T7).\n * @param policy The delete/modify-conflict policy.\n * @param branchRank The captured stable branch rank (built once via\n *   `buildBranchRank`, shared across phases). Used ONLY for deterministic\n *   tie-breaking — never for the keep-vs-delete decision itself.\n */\nexport function resolveDeleteModify(\n  staging: StagingSet,\n  policy: DeleteModifyPolicy,\n  branchRank: ReadonlyMap<BranchId, number>,\n  preferredBranchId?: BranchId,\n): DeleteModifyResolution {\n  const resolved = resolveDeleteModifyOver(\n    staging.modifiedNodes,\n    staging.deletedNodes,\n    (item) => item.node,\n    (item) => item.node,\n    (id) => ({ kind: \"node\", id, reason: DELETED_NODE_DROP_REASON }),\n    policy,\n    branchRank,\n    preferredBranchId,\n  );\n  return {\n    survivingModifications: resolved.survivingModifications,\n    nodeDeletions: resolved.deletions,\n    conflicts: resolved.conflicts,\n    dropped: resolved.dropped,\n  };\n}\n\n/**\n * The outcome of reconciling the surviving inherited modifications: ONE merged\n * record per node id (carrying the 3-way-merged props the commit applies) plus\n * every {@link PropertyConflict} that a multi-branch modification surfaced.\n */\nexport type ModificationReconciliation = Readonly<{\n  survivingModifications: readonly StagedModifiedNode[];\n  conflicts: readonly PropertyConflict[];\n}>;\n\n/** A single branch's full fork props for an inherited entity (node or edge). */\ntype ForkContribution = Readonly<{\n  branchId: BranchId;\n  forkProps: Readonly<Record<string, JsonValue>>;\n}>;\n\n/**\n * 3-WAY merges one inherited entity (node OR edge) modified by 2+ branches against\n * the SHARED base.\n *\n * Per property: a branch whose fork value equals base contributed no change; a\n * property exactly one branch changed takes that change; a property multiple\n * branches changed to DIFFERING values is a genuine conflict, resolved by the\n * captured policy on the stable `branchRank` and recorded as a\n * {@link PropertyConflict}. Property DELETIONS (a base key absent from a fork) are\n * treated conservatively as \"unchanged\" so an unrelated branch's edit is never\n * lost. `baseProps` is identical across the contributions (same base, same id).\n *\n * Shared by node modification reconciliation ({@link reconcileModifications}) and\n * edge modification reconciliation ({@link reconcileEdgeModifications}), so both\n * apply identical base-aware semantics — without this, disjoint edits to the same\n * entity by different branches would false-conflict and one edit could be lost.\n */\nfunction threeWayMergeProps(\n  entityId: AnyNodeId | EdgeId,\n  kind: string,\n  baseProps: Readonly<Record<string, JsonValue>>,\n  contributions: readonly ForkContribution[],\n  context: ResolutionContext<GraphDef>,\n  branchRank: ReadonlyMap<BranchId, number>,\n  preferredBranchId?: BranchId,\n): Readonly<{\n  props: Record<string, JsonValue>;\n  conflicts: PropertyConflict[];\n}> {\n  const merged = createDataKeyedBag<JsonValue>();\n  const conflicts: PropertyConflict[] = [];\n\n  // Every property the base OR any fork carries. Base keys are included so a key\n  // that EVERY fork dropped is still seen here (a fork's `forkProps` is its full\n  // bag, so a missing base key is an intentional deletion, not an omission).\n  const propertyNames = new Set<string>(Object.keys(baseProps));\n  for (const contribution of contributions) {\n    for (const name of Object.keys(contribution.forkProps)) {\n      propertyNames.add(name);\n    }\n  }\n\n  for (const property of [...propertyNames].sort(compareStrings)) {\n    const baseHas = hasOwnKey(baseProps, property);\n    const baseKey =\n      baseHas ?\n        canonicalValueKey(requireDefined(baseProps[property]))\n      : undefined;\n\n    // Contributions from branches that actually CHANGED this property (present and\n    // differing from base). Reuse the shared collector so the distinct-(branch,value)\n    // dedupe + ordering match the node/edge property unions exactly — one definition\n    // of conflict gathering, with the canonical NUL-separated dedupe key.\n    const changed = contributions\n      .filter((contribution) => {\n        if (!hasOwnKey(contribution.forkProps, property)) {\n          return false; // absent — a deletion (handled below), never a change\n        }\n        const value = contribution.forkProps[property] as JsonValue;\n        return !baseHas || canonicalValueKey(value) !== baseKey;\n      })\n      .map((contribution) => ({\n        branchId: contribution.branchId,\n        props: contribution.forkProps,\n      }));\n    const values = collectConflictingValues(property, changed);\n\n    if (values.length === 0) {\n      // No fork CHANGED the value. A fork's `forkProps` is its FULL bag, so a base\n      // property a fork OMITS was DELETED by it; honor that deletion by leaving the\n      // key out of `merged`. Otherwise every fork kept the base value, so it stands.\n      const deletedByFork =\n        baseHas &&\n        contributions.some(\n          (contribution) => !hasOwnKey(contribution.forkProps, property),\n        );\n      if (baseHas && !deletedByFork) {\n        merged[property] = requireDefined(baseProps[property]);\n      }\n      continue;\n    }\n\n    const distinctValues = new Set(\n      values.map((candidate) => canonicalValueKey(candidate.value)),\n    );\n    if (distinctValues.size === 1) {\n      merged[property] = requireDefined(values[0]).value; // a single, agreed-upon change\n      continue;\n    }\n\n    const preferredValue = values.find(\n      (value) => value.branchId === preferredBranchId,\n    )?.value;\n    const canonicalValue =\n      preferredValue ??\n      (baseHas ?\n        requireDefined(baseProps[property])\n      : requireDefined(values[0]).value);\n    const reportedValues =\n      preferredBranchId === undefined ? values : (\n        values.filter((value) => value.branchId !== preferredBranchId)\n      );\n    const { value, conflict } = resolvePropertyUnion(\n      { entityId, kind, property, values, reportedValues, canonicalValue },\n      context,\n      branchRank,\n    );\n    merged[property] = value;\n    if (conflict !== undefined) {\n      conflicts.push(conflict);\n    }\n  }\n\n  return { props: merged, conflicts };\n}\n\n/**\n * Reconciles the post-delete/modify surviving modifications into the records the\n * commit applies. An inherited node modified by a SINGLE branch passes through\n * unchanged; a node modified by TWO OR MORE branches is 3-way merged against the\n * base ({@link mergeModifiedProps}) into one record carrying the merged props,\n * surfacing any genuine cross-branch disagreement as a {@link PropertyConflict}.\n *\n * Without this, each per-branch modification was committed by id in turn, so the\n * lexicographically-largest branchId silently overwrote the others with NO\n * conflict recorded and the configured `onPropertyConflict` / `branchOrder`\n * bypassed (the §6.2 gap). The synthetic record's `branchId` is the highest\n * -priority contributor — cosmetic, since the commit reads only `node.id` / kind /\n * `forkProps`, and provenance for every contributing branch is recorded upstream.\n *\n * Order-independent: groups by id (the staging input is already `(id, branchId)`\n * sorted), merges per the stable `branchRank`, and sorts both outputs by stable\n * keys, so shuffling the branch set yields an identical result.\n *\n * @param survivingModifications The surviving modifications from\n *   {@link resolveDeleteModify} (one entry per `(id, branch)`).\n * @param policy The property-conflict policy (shared with the cluster union, T8).\n * @param branchRank The captured stable branch rank.\n * @param weights Optional per-branch weights for `\"provenanceWeighted\"`.\n */\nexport function reconcileModifications(\n  survivingModifications: readonly StagedModifiedNode[],\n  policy: PropertyConflictPolicy,\n  branchRank: ReadonlyMap<BranchId, number>,\n  weights?: ProvenanceWeights,\n  preferredBranchId?: BranchId,\n): ModificationReconciliation {\n  return reconcileOver(\n    survivingModifications,\n    (item) => item.node,\n    (representative, chosenBranch, mergedProps) => ({\n      branchId: chosenBranch,\n      node: { ...representative.node, forkProps: mergedProps },\n    }),\n    policy,\n    branchRank,\n    weights,\n    preferredBranchId,\n  );\n}\n\n// ============================================================\n// Inherited EDGE delete/modify resolution (the edge analogue of the node path\n// above). Edges carry fixed endpoints, so a \"modified\" edge only changes props;\n// the delete/modify and 3-way merge logic is otherwise identical to nodes, and\n// reuses the same {@link pickHighestPriorityBranch} + {@link threeWayMergeProps}\n// cores so node and edge behavior can never drift.\n// ============================================================\n\n/**\n * The outcome of delete/modify resolution over the staged inherited EDGES.\n * Mirrors {@link DeleteModifyResolution}: `edgeDeletions` is the authoritative set\n * of finally-deleted inherited edges (pure deletions plus `\"deleteWins\"` conflict\n * resolutions); `survivingModifications` is every modification the merge still\n * applies; `conflicts`/`dropped` mirror the node fields.\n */\nexport type EdgeDeleteModifyResolution = Readonly<{\n  survivingModifications: readonly StagedModifiedEdge[];\n  edgeDeletions: readonly DeletedEdge[];\n  conflicts: readonly DeleteModifyConflict[];\n  dropped: readonly DroppedItem[];\n}>;\n\n/**\n * Resolves every inherited EDGE simultaneously deleted by one+ branches and\n * modified by one+ (other) branches, per the {@link DeleteModifyPolicy} — the\n * edge analogue of {@link resolveDeleteModify}. Pure deletions flow to\n * `edgeDeletions`; pure modifications flow to `survivingModifications`. Without\n * this, inherited edge deletions were staged but never applied, so a branch's\n * edge deletion was silently dropped and the edge stayed live. Shares\n * {@link resolveDeleteModifyOver} with the node path so the two can never drift.\n */\nexport function resolveEdgeDeleteModify(\n  staging: StagingSet,\n  policy: DeleteModifyPolicy,\n  branchRank: ReadonlyMap<BranchId, number>,\n  preferredBranchId?: BranchId,\n): EdgeDeleteModifyResolution {\n  const resolved = resolveDeleteModifyOver(\n    staging.modifiedEdges,\n    staging.deletedEdges,\n    (item) => item.edge,\n    (item) => item.edge,\n    (id) => ({ kind: \"edge\", id, reason: DELETED_NODE_DROP_REASON }),\n    policy,\n    branchRank,\n    preferredBranchId,\n  );\n  return {\n    survivingModifications: resolved.survivingModifications,\n    edgeDeletions: resolved.deletions,\n    conflicts: resolved.conflicts,\n    dropped: resolved.dropped,\n  };\n}\n\n/**\n * The edge analogue of {@link reconcileModifications}: ONE merged record per edge\n * id, carrying the 3-way-merged props the commit applies, plus every\n * {@link PropertyConflict} a multi-branch edge modification surfaced. Edge\n * endpoints are immutable, so only props are merged; the representative's\n * endpoints/kind are kept.\n */\nexport function reconcileEdgeModifications(\n  survivingModifications: readonly StagedModifiedEdge[],\n  policy: PropertyConflictPolicy,\n  branchRank: ReadonlyMap<BranchId, number>,\n  weights?: ProvenanceWeights,\n  preferredBranchId?: BranchId,\n): Readonly<{\n  survivingModifications: readonly StagedModifiedEdge[];\n  conflicts: readonly PropertyConflict[];\n}> {\n  return reconcileOver(\n    survivingModifications,\n    (item) => item.edge,\n    (representative, chosenBranch, mergedProps) => ({\n      branchId: chosenBranch,\n      edge: { ...representative.edge, forkProps: mergedProps },\n    }),\n    policy,\n    branchRank,\n    weights,\n    preferredBranchId,\n  );\n}\n","/**\n * Valid-time window reconciliation for INHERITED rows (issue #369).\n *\n * A branch can end an inherited row's validity — `update(id, {}, { validTo })`\n * is an ordinary write — and until now the merge discarded that statement\n * silently. This module resolves those endings and hands the commit the one\n * instant it must write.\n *\n * WHAT IS RECONCILED, AND WHY ONLY THAT\n *\n * On a row that is live in both the base and the fork, `validTo` is the only\n * window field a branch can author AND the commit can apply:\n *\n * | observed delta            | reachable how                     | applicable? |\n * | ------------------------- | --------------------------------- | ----------- |\n * | `validTo` set / moved     | `update(id, {}, { validTo })`     | yes         |\n * | `validTo` cleared to none | `update(id, {}, { clearValidTo: true })` | yes |\n * | `validFrom` changed       | soft-delete + resurrect in a fork | no          |\n *\n * The update SQL writes `valid_from` only under `clearDeleted` (the\n * resurrection path), so a changed lower bound still cannot be applied to a\n * live inherited row. Reconciling a value the commit then drops would make the\n * merge report a change that did not happen, so that delta is REPORTED\n * ({@link WINDOW_NOT_APPLICABLE_DROP_REASON}) rather than staged.\n *\n * THE RESOLUTION RULE\n *\n * An end-of-validity is a monotone claim (\"this stopped being true\") — the same\n * shape as a deletion — so it is resolved by a fixed least-claim rule rather\n * than by `onPropertyConflict`:\n *\n *   1. no branch changed it        → keep base, write nothing;\n *   2. exactly one branch changed  → that value, INCLUDING an extension to a\n *                                    later instant (a blind `min` against base\n *                                    would make extension impossible), or clear;\n *   3. several branches changed    → the preferred (incremental target) branch's\n *                                    value if it is one of them, else the\n *                                    EARLIEST end; an end beats a concurrent\n *                                    clear as the stronger monotone claim, and\n *                                    unanimous clears reopen the row.\n *\n * `min` over the set claims plus the all-clear check is commutative and\n * associative, so determinism holds without consulting `branchRank` at all, and\n * rule 3's preference is the same\n * committed-target precedence `canonicalizeCluster` applies to identity\n * survivors: a user branch never re-windows a row the target itself windowed.\n * Nothing here can raise a new conflict, so no previously-succeeding merge\n * starts failing.\n *\n * Rule 3's preferred half is reached by NOT ACTING: the preferred branch is the\n * committed target itself, so its own end is already the stored one. Resolving\n * to it would write the row back at itself and report an end the merge never\n * decided, which is why a target that moved the end takes this row out of the\n * WRITES entirely.\n *\n * It does not take it out of the REPORT (issue #409). Discarding a claim is an\n * arbitration outcome, and the merge report's honesty principle is that every\n * observable-but-unapplied delta is visible: the claim that merely LOST the\n * least-claim rule already appears in `ValidityEndResolution.claimedBy`, so a claim\n * target precedence threw away must not be less visible than that. Such a row gets a\n * resolution naming the TARGET's own instant, its discarded claimants, and\n * `precedence: {@link VALIDITY_END_TARGET_PRECEDENCE}` — the discriminator that keeps\n * \"the merge wrote this end\" and \"the target already held this end\" distinguishable.\n * A row NO branch claimed produces no entry at all: there was nothing to discard.\n *\n * DELETION ABSORBS AN ENDING\n *\n * A window-only change is not a \"modification\" (it is staged in its own bucket),\n * so it never reaches delete/modify resolution. A row one branch deleted and\n * another merely re-windowed is therefore deleted, with no `DeleteModifyConflict`\n * — deleting and ending are both \"no longer true\", and the stronger statement\n * wins. The callers pass the finally-deleted identity sets so the ending is\n * dropped with the row.\n *\n * WHO GETS PROVENANCE CREDIT\n *\n * An ending is authored state, so the branch that authored it contributed to the\n * committed row and must appear in the merge's provenance — even when the ending\n * is its ONLY change to that row (issue #402). This module is the authority on\n * that: it decided which claim was committed, so it also emits the credit\n * ({@link ValidWindowResolution.nodeCredits} / `edgeCredits`), rather than leaving\n * the commit to re-derive it from staging and lose the claim that won.\n *\n * Credit goes to exactly the branches whose claim IS the resolved end — the `min`\n * winner and anyone who tied with it. Provenance records contribution to\n * COMMITTED state, and a branch whose later end lost the least-claim rule\n * contributed none of it; its claim is still visible in the report\n * (`ValidityEndResolution.claimedBy` names every claimant, winning or not), which\n * is where \"who asked for what\" belongs. The alternative — crediting every\n * claimant — would make provenance answer \"who spoke about this row\" instead, a\n * different question that the report already answers.\n *\n * By the same rule a target-precedence row credits NOBODY: the merge committed none\n * of that end, so its resolution is report-only and mints no credit.\n */\nimport { requireDefined } from \"../utils/presence\";\nimport {\n  compareMergeKeys,\n  compareStrings,\n  type MergeKey,\n  mergeKey,\n} from \"./node-key\";\nimport type { StagedWindowedEdge, StagedWindowedNode } from \"./staging\";\nimport type { ValidWindow } from \"./state-diff\";\nimport type { EdgeId, NodeId, NodeType } from \"./typegraph-internal\";\nimport type { BranchId, DroppedItem, ValidityEndResolution } from \"./types\";\nimport { VALIDITY_END_TARGET_PRECEDENCE } from \"./types\";\n\n/** A node id in its untyped (`NodeType`-default) branded form. */\ntype AnyNodeId = NodeId<NodeType>;\n\n/**\n * Reason recorded on a {@link DroppedItem} for a window delta the commit cannot\n * apply to a live inherited row — a fork `validFrom` divergence, or a `validTo`\n * cleared back to none. Reported rather than silently ignored.\n */\nexport const WINDOW_NOT_APPLICABLE_DROP_REASON =\n  \"window-not-applicable\" as const;\n\n/**\n * The outcome of window reconciliation over the whole staging set: the end each\n * inherited identity must be written with, plus both report channels.\n */\nexport type ValidWindowResolution = Readonly<{\n  /** `(kind, id) -> validTo change` for every inherited NODE to re-window. */\n  nodeEnds: ReadonlyMap<MergeKey, ValidToChange>;\n  /** `(kind, id) -> validTo change` for every inherited EDGE to re-window. */\n  edgeEnds: ReadonlyMap<MergeKey, ValidToChange>;\n  /**\n   * `(kind, id) -> the branches that AUTHORED the resolved node end`: the\n   * claimants whose claim equals {@link ValidWindowResolution.nodeEnds}, sorted\n   * and deduped. The provenance credit for a window change, keyed identically to\n   * `nodeEnds` so the two are read together. Never empty for an identity present\n   * in `nodeEnds` — an end exists only because some branch claimed it.\n   */\n  nodeCredits: ReadonlyMap<MergeKey, readonly BranchId[]>;\n  /** The edge half of {@link ValidWindowResolution.nodeCredits}. */\n  edgeCredits: ReadonlyMap<MergeKey, readonly BranchId[]>;\n  /**\n   * Every row whose upper-bound change this phase RESOLVED, nodes then edges — a\n   * superset of the changes above: a row target precedence decided appears here (marked\n   * {@link VALIDITY_END_TARGET_PRECEDENCE}) with no entry in `nodeEnds`/`edgeEnds`\n   * and none in the credits.\n   */\n  resolutions: readonly ValidityEndResolution[];\n  dropped: readonly DroppedItem[];\n}>;\n\n/** An explicit upper-bound change; absence from a plan means preserve. */\nexport type ValidToChange =\n  Readonly<{ kind: \"set\"; validTo: string }> | Readonly<{ kind: \"clear\" }>;\n\n/** One branch's claim about a row's upper validity bound. */\nexport type EndClaim = Readonly<{\n  branchId: BranchId;\n  change: ValidToChange;\n}>;\n\n/**\n * The least claim in a set: the earliest instant any branch claimed, or\n * `undefined` for an empty set. Canonical ISO 8601 UTC is fixed-width, so its\n * lexicographic order IS chronological order (see `isCanonicalIsoDate`) — every\n * window the diff reports is canonicalized, which is also what keeps the choice\n * identical on SQLite and PostgreSQL despite their different raw timestamp text.\n *\n * Order-independent: `min` over a set is commutative and associative.\n */\nfunction earliestEnd(claims: readonly EndClaim[]): string | undefined {\n  let earliest: string | undefined;\n  for (const claim of claims) {\n    if (claim.change.kind !== \"set\") continue;\n    if (\n      earliest === undefined ||\n      compareStrings(claim.change.validTo, earliest) < 0\n    ) {\n      earliest = claim.change.validTo;\n    }\n  }\n  return earliest;\n}\n\n/**\n * Applies rule 3 to a set of end claims: the preferred branch's claim if it made\n * one, else {@link earliestEnd}. Order-independent — the preferred branch's claims\n * are selected as a SET and reduced by the same `min`, so a fold set holding several\n * preferred rows (distinct edges the repoint collapsed) cannot resolve on which of\n * them the caller happened to list first.\n *\n * Only the edge FOLD needs this form. The inherited-row reconciler never sees a\n * preferred claim (the committed target's own end is already stored, so it is\n * taken out of the resolution rather than resolved to) and calls\n * {@link earliestEnd} directly.\n */\nexport function resolveEndClaims(\n  claims: readonly EndClaim[],\n  preferredBranchId: BranchId | undefined,\n): ValidToChange | undefined {\n  const preferred = claims.filter(\n    (claim) => claim.branchId === preferredBranchId,\n  );\n  const candidates = preferred.length > 0 ? preferred : claims;\n  const earliest = earliestEnd(candidates);\n  return (\n    earliest === undefined ?\n      candidates.some((claim) => claim.change.kind === \"clear\") ?\n        { kind: \"clear\" }\n      : undefined\n    : { kind: \"set\", validTo: earliest }\n  );\n}\n\n/** The claiming branches of a resolved end, deduped and sorted. */\nfunction claimingBranches(claims: readonly EndClaim[]): readonly BranchId[] {\n  return [...new Set(claims.map((claim) => claim.branchId))].sort(\n    (left, right) => compareStrings(left, right),\n  );\n}\n\n/** Whether two explicit upper-bound changes request the same stored state. */\nfunction sameValidToChange(left: ValidToChange, right: ValidToChange): boolean {\n  if (left.kind !== right.kind) return false;\n  if (left.kind === \"clear\") return true;\n  return right.kind === \"set\" && left.validTo === right.validTo;\n}\n\n/**\n * Splits ONE branch's observed window delta into the part the commit can apply\n * (a set, move, or authored clear of `validTo`) and the part it cannot. A moved\n * lower bound proves delete+resurrect occurred. Its implicit ended-to-open\n * transition is part of that indivisible resurrection artifact, not an authored\n * clear, so it stays entirely in `window-not-applicable`; an explicit new end\n * remains independently applicable.\n */\nfunction classifyDelta(\n  base: ValidWindow,\n  fork: ValidWindow,\n): Readonly<{\n  applicableEnd: ValidToChange | undefined;\n  unapplicable: boolean;\n}> {\n  const lowerBoundMoved = fork.validFrom !== base.validFrom;\n  const endCleared = fork.validTo === undefined && base.validTo !== undefined;\n  return {\n    applicableEnd:\n      fork.validTo !== undefined && fork.validTo !== base.validTo ?\n        { kind: \"set\", validTo: fork.validTo }\n      : endCleared && !lowerBoundMoved ? { kind: \"clear\" }\n      : undefined,\n    unapplicable: lowerBoundMoved,\n  };\n}\n\n/** A staged window delta reduced to the fields reconciliation needs. */\ntype WindowDelta = Readonly<{\n  branchId: BranchId;\n  kind: string;\n  id: string;\n  base: ValidWindow;\n  fork: ValidWindow;\n}>;\n\n/**\n * Reconciles one entity population (nodes or edges), skipping identities the\n * merge finally deletes — deletion absorbs an ending, with no conflict recorded.\n *\n * `ends` and `credits` cover only the rows the commit must WRITE; `resolutions`\n * additionally reports the rows target precedence decided, so a discarded claim is\n * visible without being staged.\n */\nfunction resolvePopulation(\n  entity: \"node\" | \"edge\",\n  deltas: readonly WindowDelta[],\n  deletions: ReadonlySet<MergeKey>,\n  preferredBranchId: BranchId | undefined,\n  dropItem: (id: string) => DroppedItem,\n): Readonly<{\n  ends: ReadonlyMap<MergeKey, ValidToChange>;\n  credits: ReadonlyMap<MergeKey, readonly BranchId[]>;\n  resolutions: readonly ValidityEndResolution[];\n  dropped: readonly DroppedItem[];\n}> {\n  const byIdentity = new Map<MergeKey, WindowDelta[]>();\n  for (const delta of deltas) {\n    const identity = mergeKey(delta.kind, delta.id);\n    if (deletions.has(identity)) {\n      continue;\n    }\n    const bucket = byIdentity.get(identity);\n    if (bucket === undefined) {\n      byIdentity.set(identity, [delta]);\n    } else {\n      bucket.push(delta);\n    }\n  }\n\n  const ends = new Map<MergeKey, ValidToChange>();\n  const credits = new Map<MergeKey, readonly BranchId[]>();\n  const resolutions: ValidityEndResolution[] = [];\n  const dropped: DroppedItem[] = [];\n\n  for (const [identity, group] of byIdentity) {\n    const claims: EndClaim[] = [];\n    let reportedUnapplicable = false;\n    let targetEnd: ValidToChange | undefined;\n    for (const delta of group) {\n      const { applicableEnd, unapplicable } = classifyDelta(\n        delta.base,\n        delta.fork,\n      );\n      // The preferred branch IS the committed incremental target: its delta\n      // describes the DESTINATION's own row, not a claim staged against it. A\n      // target that already moved this end leaves the merge nothing to apply —\n      // that is rule 3's committed-target precedence, reached without writing\n      // the row back at itself. The instant is kept rather than a flag, because\n      // the report has to name the end that actually stands (a group holds at\n      // most one delta per branch, so the `??=` records that one delta's end).\n      // A target-side unapplicable delta is likewise not something the merge\n      // failed to carry: it is where the merge writes.\n      if (delta.branchId === preferredBranchId) {\n        targetEnd ??= applicableEnd;\n        continue;\n      }\n      if (applicableEnd !== undefined) {\n        claims.push({ branchId: delta.branchId, change: applicableEnd });\n      }\n      // One entry per ROW, not per contributing branch: the report names what\n      // the merge could not apply to that row, and a second branch diverging the\n      // same way adds no information a caller can act on.\n      if (unapplicable && !reportedUnapplicable) {\n        reportedUnapplicable = true;\n        dropped.push(dropItem(delta.id));\n      }\n    }\n    const first = requireDefined(group[0]);\n    if (targetEnd !== undefined) {\n      // Target precedence: the committed target already moved this end, so the\n      // merge applies nothing and every branch claim is discarded. Say so\n      // (issue #409) — a claim the merge observed and did not apply is exactly what\n      // the report exists to make visible, and the least-claim LOSER is already\n      // visible in `claimedBy`, so a discarded claim must not be less visible than\n      // an out-arbitrated one. The entry names the target's own instant and is\n      // marked so a consumer can tell it from an end the merge decided. No end is\n      // staged and no credit is minted: nothing here was committed by a branch.\n      if (claims.length > 0) {\n        resolutions.push({\n          entity,\n          kind: first.kind,\n          id: first.id,\n          ...(targetEnd.kind === \"set\" ?\n            { validTo: targetEnd.validTo }\n          : { clearValidTo: true as const }),\n          claimedBy: claimingBranches(claims),\n          precedence: VALIDITY_END_TARGET_PRECEDENCE,\n        });\n      }\n      continue;\n    }\n    const resolved = resolveEndClaims(claims, undefined);\n    if (resolved === undefined) {\n      continue;\n    }\n    ends.set(identity, resolved);\n    // The AUTHORS of the committed end: every branch whose claim is the resolved\n    // instant, including the ones that tied with it. A later claim lost the\n    // least-claim rule and put nothing into the committed row, so it earns no\n    // credit — it stays visible as a claimant in the resolution below.\n    credits.set(\n      identity,\n      claimingBranches(\n        claims.filter((claim) => sameValidToChange(claim.change, resolved)),\n      ),\n    );\n    resolutions.push({\n      entity,\n      kind: first.kind,\n      id: first.id,\n      ...(resolved.kind === \"set\" ?\n        { validTo: resolved.validTo }\n      : { clearValidTo: true as const }),\n      claimedBy: claimingBranches(claims),\n    });\n  }\n\n  // Ordered by the composite `(kind, id)` identity, never a joined string: a\n  // caller-supplied id may contain any character, so a separator-joined key\n  // would not be a total order and the output would depend on insertion order.\n  return {\n    ends,\n    credits,\n    resolutions: resolutions.sort((left, right) =>\n      compareMergeKeys(\n        mergeKey(left.kind, left.id),\n        mergeKey(right.kind, right.id),\n      ),\n    ),\n    dropped: dropped.sort((left, right) => compareStrings(left.id, right.id)),\n  };\n}\n\n/**\n * Reconciles every staged inherited window delta into the ends the commit writes.\n *\n * Order-independent: deltas are grouped by `(kind, id)`, resolved by the fixed\n * least-claim rule, and both report channels are sorted by stable keys — so\n * shuffling the branch set yields an identical result.\n *\n * @param staging The provenance-tagged union staging set (T7).\n * @param nodeDeletions The AUTHORITATIVE finally-deleted node identities.\n * @param edgeDeletions The AUTHORITATIVE finally-deleted edge identities.\n * @param preferredBranchId The incremental merge's committed-target branch, whose\n *   own end already stands and so takes its row out of the ENDS the commit writes\n *   (rule 3's preferred half) while still reporting the claims it discarded.\n *   Absent on the snapshot path.\n */\nexport function resolveValidWindows(\n  staging: Readonly<{\n    windowedNodes: readonly StagedWindowedNode[];\n    windowedEdges: readonly StagedWindowedEdge[];\n  }>,\n  nodeDeletions: ReadonlySet<MergeKey>,\n  edgeDeletions: ReadonlySet<MergeKey>,\n  preferredBranchId?: BranchId,\n): ValidWindowResolution {\n  const nodes = resolvePopulation(\n    \"node\",\n    staging.windowedNodes.map((staged) => ({\n      branchId: staged.branchId,\n      kind: staged.node.kind,\n      id: staged.node.id,\n      base: staged.node.base,\n      fork: staged.node.fork,\n    })),\n    nodeDeletions,\n    preferredBranchId,\n    (id) => ({\n      kind: \"node\",\n      id: id as AnyNodeId,\n      reason: WINDOW_NOT_APPLICABLE_DROP_REASON,\n    }),\n  );\n  const edges = resolvePopulation(\n    \"edge\",\n    staging.windowedEdges.map((staged) => ({\n      branchId: staged.branchId,\n      kind: staged.edge.kind,\n      id: staged.edge.id,\n      base: staged.edge.base,\n      fork: staged.edge.fork,\n    })),\n    edgeDeletions,\n    preferredBranchId,\n    (id) => ({\n      kind: \"edge\",\n      id: id as EdgeId,\n      reason: WINDOW_NOT_APPLICABLE_DROP_REASON,\n    }),\n  );\n\n  return {\n    nodeEnds: nodes.ends,\n    edgeEnds: edges.ends,\n    nodeCredits: nodes.credits,\n    edgeCredits: edges.credits,\n    resolutions: [...nodes.resolutions, ...edges.resolutions],\n    dropped: [...nodes.dropped, ...edges.dropped],\n  };\n}\n","import { createDataKeyedBag, hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\n/**\n * Edge repoint to canonical + set-dedupe cascade (design §6.3 / §6.4 rule 5, T9).\n *\n * After clustering (T8) collapses fork nodes into canonical survivors and\n * delete/modify resolution (T8a) fixes the FINAL LIVENESS of every endpoint, the\n * inherited and new edges of the merge must be:\n *\n *   1. REPOINTED — each endpoint mapped to its cluster's canonical id. An edge\n *      `x → a` where `{a, b}` collapsed to canonical `c*` becomes `x → c*`.\n *   2. DROPPED — any edge whose (repointed) `from` or `to` is a finally-deleted\n *      node (per T8a, NOT resurrected) is removed, recorded as a\n *      {@link DroppedItem} with reason {@link ENDPOINT_DELETED_DROP_REASON}.\n *   3. DEDUPED — repointing can make two distinct edges identical. Edges brought\n *      together THAT WAY are collapsed as a pure SET operation keyed by\n *      `(fromCanonical | type | toCanonical | propsKey)`, where `propsKey` is the\n *      T2 canonical serializer over PARSED props. So `x → a` and `x → b` (both\n *      repointed to `x → c*`) with equal props yield a SINGLE `x → c*`.\n *   4. RECONCILED — when two such edges collapse to the same `(from, type, to)`\n *      but carry DIFFERING props, the per-property disagreement is resolved by the\n *      shared T8 conflict policy ({@link resolvePropertyUnion}) on the captured,\n *      non-wall-clock branch order, recording an edge-level {@link PropertyConflict}\n *      whose `entityId` is the surviving edge's id. Only the members that AUTHORED a\n *      property — changed it from their own base — compete for it, so an untouched\n *      inherited value never outvotes a real edit (issue #408; see\n *      {@link authoredProperty}).\n *\n * SCOPE OF THE FOLD (issue #393). Steps 3 and 4 apply ONLY to a collision the\n * repointing INDUCED. The store is a MULTIGRAPH: nothing enforces uniqueness on\n * `(from, type, to)`, `create()` makes a parallel edge, and\n * `getOrCreateByEndpoints()` is the opt-in set-semantics accessor. Folding edges\n * that ALREADY named the same endpoints would therefore destroy authored\n * multigraph intent and break branch-effect commutativity — a merge must produce\n * what the operation would have produced applied directly to the target, and\n * `create(x, y, props)` on the target yields a parallel edge.\n *\n * So the fold groups by PRE-REPOINT endpoint pair ({@link foldSets}): one row per\n * pair collapses into a single set — that is the `x → a` / `x → b` case above —\n * and every further row a pair authored commits as its own parallel row. A group\n * that MIXES the two folds only across the pairs: a repointed `x → b` joining two\n * parallel `x → a` rows collapses into the lower-id one of them and the other\n * still commits, because repointing said nothing about the rows already there.\n *\n * What makes two staged edges one ROW is their EDGE ID, not equal props:\n * re-staging one INHERITED row from several branches is the same row (it folds, so\n * concurrent property edits still reconcile into one write), while a\n * branch-CREATED row carries a fresh id and is a new parallel edge even when its\n * props happen to coincide with an inherited one's. Consequently a window claim\n * lands on the row its author touched.\n *\n * SURVIVOR OF A FOLD (issue #395). A fold REWRITES the row it keeps and never\n * deletes the rows that folded into it, so which member survives is a matter of\n * commit correctness rather than taste: a survivor the target does not already hold\n * would leave every committed member of the set live BESIDE its own replacement,\n * carrying the props it had before the merge and never receiving the edit staged for\n * it. So an INHERITED member wins survivorship whenever the set holds one — the edge\n * analog of the node path's base-id-wins (design §6.4-C) — and only a set that is\n * entirely branch-created falls back to the minimum edge id (see\n * {@link pickSurvivor}). This is why {@link StagedEdge} carries its\n * {@link StagedEdgeOrigin}.\n *\n * Determinism: the dedupe is a pure function of the (unordered) staged-edge SET.\n * Group membership derives only from the staged endpoints and {@link canonicalOf} —\n * never from id sort order. Within a folded group the survivor is chosen by origin\n * and edge id alone, property resolution uses only the captured `branchRank`, and\n * the output is sorted by dedupe key with the edge id as the final tiebreaker\n * (parallel edges can share every other component) — so shuffling the input edges\n * yields an identical result. Clusters are computed once upstream (T8) and passed in\n * as {@link canonicalOf}; this module never re-clusters.\n */\nimport { canonicalizeProps, canonicalValueKey } from \"./canonical-props\";\nimport type { ClusterResult } from \"./clustering\";\nimport type { ProvenanceWeights, ResolutionContext } from \"./conflict-policy\";\nimport {\n  collectConflictingValues,\n  resolvePropertyUnion,\n} from \"./conflict-policy\";\nimport {\n  compareStrings,\n  idOf,\n  kindOf,\n  type MergeKey,\n  mergeKey,\n} from \"./node-key\";\nimport type {\n  EdgeId,\n  GraphDef,\n  JsonValue,\n  NodeId,\n  NodeType,\n  ValidityEndMutation,\n} from \"./typegraph-internal\";\nimport type {\n  BranchId,\n  PropertyConflict,\n  PropertyConflictPolicy,\n} from \"./types\";\nimport { resolveEndClaims } from \"./valid-window\";\n\n/** A node id in its untyped (`NodeType`-default) branded form. */\ntype AnyNodeId = NodeId<NodeType>;\n\n/** Reason recorded on a {@link DroppedItem} for an edge to a deleted endpoint. */\nexport const ENDPOINT_DELETED_DROP_REASON = \"edge:endpoint-deleted\" as const;\n\n/**\n * A `{ kind: \"edge\" }` dropped item. Mirrors the public {@link DroppedItem} but is\n * narrowed to edges so this module's output is precisely typed. Structurally\n * assignable to {@link DroppedItem}.\n */\ntype DroppedEdge = Readonly<{\n  kind: \"edge\";\n  id: EdgeId;\n  reason: string;\n}>;\n\n/** {@link StagedEdgeOrigin} of a row the merge base already holds. */\nexport const INHERITED_EDGE_ORIGIN = \"inherited\" as const;\n\n/** {@link StagedEdgeOrigin} of a row a branch created after the fork point. */\nexport const BRANCH_CREATED_EDGE_ORIGIN = \"branch-created\" as const;\n\n/**\n * Whether a staged edge's ROW already existed at the fork point its branch diffed\n * against, or was created after it. It is the diff BUCKET the staging phase (T7) put the\n * edge in — a modified or re-windowed inherited edge is {@link INHERITED_EDGE_ORIGIN}, a\n * new fork edge is {@link BRANCH_CREATED_EDGE_ORIGIN} — threaded through as data because\n * nothing about an edge id reveals its origin (ids are opaque and may be caller-chosen,\n * so re-deriving one from the id is not possible, not merely unwise).\n *\n * Survivor selection is the consumer: an inherited row is one the merge target already\n * holds, so a fold must land on it (see {@link pickSurvivor}). Note this is not a\n * liveness dichotomy — an incremental target's OWN new edge is\n * {@link BRANCH_CREATED_EDGE_ORIGIN} while being a live committed row of the target too,\n * which is why the order between the two is a decision {@link pickSurvivor} has to make\n * rather than a tautology.\n */\ntype StagedEdgeOrigin =\n  typeof INHERITED_EDGE_ORIGIN | typeof BRANCH_CREATED_EDGE_ORIGIN;\n\n/**\n * One staged edge fed into the repoint phase: a new fork edge or a surviving\n * inherited edge. Carries the parsed props (NOT a JSON string) so the dedupe key\n * and the conflict union both operate on the canonical structure, the\n * {@link BranchId} that contributed it so edge-property conflicts resolve on the\n * same stable branch order as node-property conflicts, and its\n * {@link StagedEdgeOrigin} so a fold survives onto a row the target already holds.\n *\n * The orchestrator (T11) builds these from `StagedNewEdge` / surviving\n * `StagedModifiedEdge` items (T7); this module needs no knowledge of the diff\n * shape beyond these fields.\n */\nexport type StagedEdge = Readonly<{\n  id: EdgeId;\n  kind: string;\n  origin: StagedEdgeOrigin;\n  fromId: AnyNodeId;\n  toId: AnyNodeId;\n  fromKind: string;\n  toKind: string;\n  props: Readonly<Record<string, JsonValue>>;\n  /**\n   * The props the MERGE BASE holds for this row — present on an INHERITED edge,\n   * absent on a branch-created one (nothing preceded it).\n   *\n   * The property union compares each member's {@link StagedEdge.props} against it\n   * so only the properties a member actually AUTHORED compete (issue #408, and the\n   * edge analog of the node path's 3-way merge). Without a base, a staged copy of\n   * an inherited row contributes its whole fork bag, so an untouched base value\n   * enters the union as a first-class claim and can outvote a real edit under any\n   * rank-based policy — see {@link authoredProperty}.\n   */\n  baseProps?: Readonly<Record<string, JsonValue>>;\n  branchId: BranchId;\n  /**\n   * The valid-time window the commit must write. A NEW edge carries the branch's\n   * authored window; an INHERITED edge carries `validTo` only, and only when the\n   * merge reconciled an end-of-validity for it (an unreconciled inherited window\n   * is absent, so the committed row's own window stays untouched).\n   *\n   * Windows take no part in the dedupe key or the conflict union. `validFrom`\n   * rides along with whichever edge survives a fold; `validTo` is instead\n   * resolved across the folded set (see {@link repointEdges}), because an end is\n   * a monotone claim that must not be lost to the survivor pick.\n   */\n  validFrom?: string | null;\n}> &\n  ValidityEndMutation;\n\n/**\n * A surviving merged edge after repoint + dedupe. `id` is the canonical survivor\n * of its fold set (its inherited member, else its minimum contributing edge id — see\n * {@link pickSurvivor}); `mergedIds` is every staged edge id that collapsed into it\n * (always includes `id`), which is how the commit phase (T11) records each contributing\n * branch's provenance against the row that actually persists. Nothing ENDS a folded-away\n * row — that is precisely why `id` is a commit-correctness choice and not a preference\n * (see the module header's survivor rule).\n */\nexport type MergedEdge = Readonly<{\n  id: EdgeId;\n  kind: string;\n  fromId: AnyNodeId;\n  toId: AnyNodeId;\n  fromKind: string;\n  toKind: string;\n  props: Readonly<Record<string, JsonValue>>;\n  mergedIds: readonly EdgeId[];\n  /** The survivor's {@link StagedEdge} window, if it carried one. */\n  validFrom?: string | null;\n}> &\n  ValidityEndMutation;\n\n/**\n * The outcome of the repoint + dedupe cascade: the surviving merged edges, every\n * edge dropped for a deleted endpoint, and every edge-level property conflict the\n * dedupe surfaced.\n */\nexport type EdgeRepointResult<G extends GraphDef = GraphDef> = Readonly<{\n  edges: readonly MergedEdge[];\n  dropped: readonly DroppedEdge[];\n  conflicts: readonly PropertyConflict<G>[];\n}>;\n\n/**\n * Builds the endpoint → canonical map from the resolved clusters. Every member of\n * a cluster maps to that cluster's canonical id; ids absent from the map (cluster\n * singletons / nodes never compared) are treated as their own canonical by the\n * `?? id` fallback at lookup time, so the map need only carry the rewrites.\n *\n * @param clusters Resolved clusters (T8). Each must be non-empty.\n * @param canonicalOf A `cluster → canonicalId` selector returning the cluster's\n *   canonical survivor (as chosen by T8 `pickClusterSurvivor`), threaded so this\n *   module reuses the merge-wide canonical choice rather than re-deriving it.\n */\nexport function buildCanonicalMap(\n  clusters: readonly ClusterResult[],\n  canonicalOf: (cluster: ClusterResult) => MergeKey,\n): ReadonlyMap<MergeKey, MergeKey> {\n  const map = new Map<MergeKey, MergeKey>();\n  for (const cluster of clusters) {\n    const canonical = canonicalOf(cluster);\n    for (const member of cluster.members) {\n      map.set(member, canonical);\n    }\n  }\n  return map;\n}\n\n/**\n * Resolves an endpoint IDENTITY (`(kind, id)` key) to its cluster canonical,\n * defaulting to itself. Keying on the composite identity is what stops an edge from\n * a `Patient` and an edge from an `Encounter` that share an endpoint id from being\n * repointed onto the same survivor.\n */\nfunction repoint(\n  key: MergeKey,\n  canonicalOf: ReadonlyMap<MergeKey, MergeKey>,\n): MergeKey {\n  return canonicalOf.get(key) ?? key;\n}\n\n/**\n * The dedupe key for a repointed edge: a JSON-encoded `[from', type, to',\n * propsKey]` tuple. The `propsKey` is the T2 canonical serializer over the PARSED\n * props, so two edges that agree on endpoints, type, AND every property collapse to\n * one regardless of property key order. JSON-encoding the tuple (rather than\n * concatenating with a literal separator) keeps the key unambiguous even when an\n * edge `type` — a user-defined schema string — or a caller-supplied endpoint id\n * contains the separator character.\n */\nfunction dedupeKey(\n  fromKey: MergeKey,\n  type: string,\n  toKey: MergeKey,\n  props: Readonly<Record<string, JsonValue>>,\n): string {\n  return JSON.stringify([fromKey, type, toKey, canonicalizeProps(props)]);\n}\n\n/**\n * The key identifying a collision GROUP — edges sharing `(from', type, to')`\n * regardless of props. Edges in the same group but with differing props are the\n * ones whose properties must be reconciled by the conflict policy. JSON-encoded\n * (see {@link dedupeKey}) so a `|`-bearing type/id can never fuse two distinct\n * groups.\n */\nfunction groupKey(fromKey: MergeKey, type: string, toKey: MergeKey): string {\n  return JSON.stringify([fromKey, type, toKey]);\n}\n\n/**\n * The PRE-repoint endpoint identity pair of a staged edge — the relationship the\n * author named. {@link foldSets} partitions a collision group by it: distinct pairs\n * are distinct relationships that repointing collapsed (so they fold), one pair is\n * ordinary multigraph multiplicity (so it does not). Direction-sensitive, so the\n * reversed intra-cluster pair `a → b` / `b → a` reads as two source pairs and still\n * folds once `{a, b}` collapse. JSON-encoded (see {@link dedupeKey}) so a\n * separator-bearing id cannot fuse pairs.\n */\nfunction sourcePairKey(fromKey: MergeKey, toKey: MergeKey): string {\n  return JSON.stringify([fromKey, toKey]);\n}\n\n/**\n * A repointed staged edge plus both endpoints already mapped to their canonical\n * IDENTITY key (`(kind, id)`). The composite keys carry the canonical node's kind, so\n * the surviving edge's bare `fromId`/`toId` and `fromKind`/`toKind` are read off\n * `idOf`/`kindOf` of these keys — never the (possibly different-kind) staged endpoint.\n * `sourcePair` and `dedupeKey` are computed during the single repoint pass so the\n * fold partition and the props-identity check never recanonicalize props.\n */\ntype RepointedEdge = Readonly<{\n  staged: StagedEdge;\n  fromKey: MergeKey;\n  toKey: MergeKey;\n  sourcePair: string;\n  dedupeKey: string;\n}>;\n\n/**\n * Groups a collision group's members into ROWS: one row per edge id, holding every\n * staged copy of it. Two branches that both staged one inherited edge contribute two\n * members of the SAME row — the id is what makes them the same row.\n */\nfunction rowsById(\n  groupEdges: readonly RepointedEdge[],\n): ReadonlyMap<EdgeId, readonly RepointedEdge[]> {\n  const rows = new Map<EdgeId, RepointedEdge[]>();\n  for (const edge of groupEdges) {\n    const row = rows.get(edge.staged.id);\n    if (row === undefined) {\n      rows.set(edge.staged.id, [edge]);\n    } else {\n      row.push(edge);\n    }\n  }\n  return rows;\n}\n\n/**\n * The pre-repoint relationship of each ROW: the minimal {@link sourcePairKey} its\n * members named. A row normally names exactly one pair; the minimum keeps the choice\n * total (and order-independent) for the chosen-id case where two branches staged the\n * same edge id from different endpoints, which is still ONE row and so must land in\n * exactly one fold set.\n */\nfunction sourcePairByRow(\n  rows: ReadonlyMap<EdgeId, readonly RepointedEdge[]>,\n): ReadonlyMap<EdgeId, string> {\n  const pairs = new Map<EdgeId, string>();\n  for (const [id, members] of rows) {\n    const sorted = members\n      .map((member) => member.sourcePair)\n      .sort((left, right) => compareStrings(left, right));\n    pairs.set(id, requireDefined(sorted[0]));\n  }\n  return pairs;\n}\n\n/**\n * Partitions one `(from', type, to')` collision group into the member sets that each\n * commit as a SINGLE row.\n *\n * Two staged edges are the same ROW when they share an edge id; two rows are the same\n * pre-repoint RELATIONSHIP when they named the same `(from, to)` pair before\n * repointing. Repointing can collapse distinct relationships onto one identity, and\n * that is the collision the §6.3 set-collapse exists for — so ONE row per pre-repoint\n * pair (its minimum-id row: which of a pair's rows REPRESENTS it needs only to be\n * total and order-independent, since every row a pair authored commits either way)\n * folds into a single set. Whether that set then lands on a committed row is\n * {@link pickSurvivor}'s decision, not this partition's. Every FURTHER row a pair\n * authored is ordinary multigraph multiplicity and\n * commits as its own parallel row: nothing enforces uniqueness on `(from, type, to)`,\n * so a merge that collapsed them would destroy multiplicity the branch author's\n * operation would have produced applied straight to the target.\n *\n * The two ends of that rule are the cases the module exists to get right:\n *   - `x → a` and `x → b` both landing on `x → c*` are two pairs of one row each, so\n *     they fold to one edge as before;\n *   - two parallel `x → y` edges are one pair of two rows, so neither is folded away.\n *\n * A group that mixes them folds only ACROSS the pairs: a repointed `x → b` joining two\n * parallel `x → a` rows collapses into the lower-id one of them and the other still\n * commits, because repointing said nothing about the rows that were already there.\n *\n * Determinism: the partition derives only from the staged ids and their pre-repoint\n * pairs — never from input order — and the sets are emitted in id order.\n */\nfunction foldSets(\n  groupEdges: readonly RepointedEdge[],\n): readonly (readonly RepointedEdge[])[] {\n  const rows = rowsById(groupEdges);\n  const sourcePairs = sourcePairByRow(rows);\n  const representatives = new Map<string, EdgeId>();\n  for (const [id, pair] of sourcePairs) {\n    const representative = representatives.get(pair);\n    if (\n      representative === undefined ||\n      compareStrings(id, representative) < 0\n    ) {\n      representatives.set(pair, id);\n    }\n  }\n\n  const collapsed: RepointedEdge[] = [];\n  const parallel: (readonly RepointedEdge[])[] = [];\n  for (const id of [...rows.keys()].sort((left, right) =>\n    compareStrings(left, right),\n  )) {\n    const members = requireDefined(rows.get(id));\n    const pair = requireDefined(sourcePairs.get(id));\n    if (representatives.get(pair) === id) {\n      collapsed.push(...members);\n    } else {\n      parallel.push(members);\n    }\n  }\n  return [collapsed, ...parallel];\n}\n\n/**\n * Orders two members of one fold set for the survivor pick: by edge id, then toward\n * the preferred branch, then by branch id.\n *\n * Members that tie on the edge id are the SAME ROW staged by several branches (two\n * branches creating one caller-chosen id), so the row that survives is settled either\n * way and the remaining choice is only WHICH branch's staged copy of it the fold reads\n * its kind, window and survivor prop values from. It goes to the preferred branch,\n * agreeing with {@link pickSurvivor}'s candidate preference — which is where a\n * preferred-branch copy is normally selected, so this clause only ever breaks a tie\n * INSIDE a candidate class. The branch id then makes the order total, so the pick cannot\n * depend on which copy the caller listed first.\n */\nfunction compareMembers(\n  left: RepointedEdge,\n  right: RepointedEdge,\n  preferredBranchId: BranchId | undefined,\n): number {\n  const byId = compareStrings(left.staged.id, right.staged.id);\n  if (byId !== 0) {\n    return byId;\n  }\n  const leftPreferred = left.staged.branchId === preferredBranchId;\n  const rightPreferred = right.staged.branchId === preferredBranchId;\n  if (leftPreferred !== rightPreferred) {\n    return leftPreferred ? -1 : 1;\n  }\n  return compareStrings(left.staged.branchId, right.staged.branchId);\n}\n\n/**\n * Picks the canonical survivor edge of a fold set, enforcing INHERITED-WINS (issue\n * #395) — the edge analog of the node path's base-id-wins (§6.4-C,\n * `pickClusterSurvivor`), and a commit-correctness invariant for the same reason.\n *\n *   - an INHERITED member wins outright (the minimum-id one, for the rare set the\n *     repoint built from several committed rows). A fold rewrites its survivor and\n *     ends none of the rows folded into it, so a survivor the target does not hold\n *     would leave the committed row live beside the new one that was meant to replace\n *     it, with the edit staged for that committed row never written. Writing onto the\n *     row the target already holds is what makes that outcome unreachable, so this\n *     outranks the preferred-branch pick below: the incremental target's own new row\n *     is equally live, but preferring it is precisely what let a committed row lose.\n *   - otherwise every member is branch-created, nothing committed can be stranded,\n *     and the minimum edge id survives — restricted to the preferred (incremental\n *     target) branch's members when the set has any, so an incremental merge still\n *     writes onto the target's row rather than beside it.\n *\n * Order-independent: origin and edge id are intrinsic to the staged set, and\n * {@link compareMembers} is total. (`generateId()` is nanoid — random, not\n * time-prefixed — so min-id never leaks creation order.)\n */\nfunction pickSurvivor(\n  edges: readonly RepointedEdge[],\n  preferredBranchId?: BranchId,\n): RepointedEdge {\n  const inherited = edges.filter(\n    (edge) => edge.staged.origin === INHERITED_EDGE_ORIGIN,\n  );\n  const preferred =\n    preferredBranchId === undefined ?\n      []\n    : edges.filter((edge) => edge.staged.branchId === preferredBranchId);\n  const candidates =\n    inherited.length > 0 ? inherited\n    : preferred.length > 0 ? preferred\n    : edges;\n  return requireDefined(\n    [...candidates].sort((left, right) =>\n      compareMembers(left, right, preferredBranchId),\n    )[0],\n  );\n}\n\n/**\n * Whether one fold member AUTHORED a value for `property` — it carries the\n * property AND its value differs from the one that member's own merge base holds.\n * A BRANCH-CREATED member has no base, so everything it carries is authored.\n *\n * This is the changed-props filter of {@link unionEdgeProps} (issue #408), the edge\n * analog of the node path's 3-way merge (`threeWayMergeProps`): a staged copy of an\n * inherited row contributes its FULL fork bag, so without it an UNTOUCHED base\n * value competes as a first-class claim and can outvote a real edit under any\n * rank-based policy — which branch's label happened to ride on the untouched copy\n * would then decide the committed value.\n *\n * The window-only carrier is the case that makes it observable: that staged copy\n * exists only to give an end-of-validity a row to ride on, its props ARE the base's,\n * and the branch labelling it is merely whichever sorted first. It authors no\n * property at all, and so contributes no claim and raises no conflict.\n */\nfunction authoredProperty(edge: RepointedEdge, property: string): boolean {\n  const { props, baseProps } = edge.staged;\n  if (!hasOwnKey(props, property)) {\n    return false;\n  }\n  if (baseProps === undefined || !hasOwnKey(baseProps, property)) {\n    return true;\n  }\n  return (\n    canonicalValueKey(props[property] as JsonValue) !==\n    canonicalValueKey(baseProps[property] as JsonValue)\n  );\n}\n\n/**\n * The value a fold set carries for a property NO member authored — used for a key the\n * survivor's own bag lacks, so filtering out unauthored CLAIMS never erases the row's\n * content. Every carrier holds its own row's base value here (that is what unauthored\n * means), so which one is taken is a choice between untouched inherited values.\n *\n * Taken from the minimum staged EDGE ID, never from the branch label riding on it.\n * Which branch a staged copy of an inherited row belongs to is arbitrary — for a\n * window-only carrier it is merely whichever branch sorted first in staging — so\n * choosing by label would reinstate, for exactly these keys, the label sensitivity the\n * authored-claims filter removes (issue #408). The edge id is the fold's ordering\n * authority everywhere else ({@link pickSurvivor}, `mergedIds`), and the canonical\n * value breaks a tie between two staged copies of ONE row so the order stays total.\n *\n * @param edges The fold set. At least one member must carry `property`.\n */\nfunction unauthoredValue(\n  property: string,\n  edges: readonly RepointedEdge[],\n): JsonValue {\n  const carriers = edges\n    .filter((edge) => hasOwnKey(edge.staged.props, property))\n    .sort((left, right) => {\n      const byId = compareStrings(left.staged.id, right.staged.id);\n      return byId === 0 ?\n          compareStrings(\n            canonicalValueKey(left.staged.props[property] as JsonValue),\n            canonicalValueKey(right.staged.props[property] as JsonValue),\n          )\n        : byId;\n    });\n  return requireDefined(carriers[0]).staged.props[property] as JsonValue;\n}\n\n/**\n * Unions the props of one fold set's edges, resolving any per-property\n * disagreement via the shared T8 conflict policy. Returns the surviving prop bag\n * plus an edge-level {@link PropertyConflict} for every property that genuinely\n * differed (its `entityId` is the surviving edge id).\n *\n * Only the members that AUTHORED a property compete for it ({@link\n * authoredProperty}). A property no member changed is not contested at all, so the\n * value the survivor already holds stands and no conflict is recorded; a property\n * two members changed differently is a genuine disagreement and resolves — and is\n * reported — exactly as before, over their real values alone.\n */\nfunction unionEdgeProps(\n  survivorId: EdgeId,\n  kind: string,\n  survivor: RepointedEdge,\n  edges: readonly RepointedEdge[],\n  context: ResolutionContext<GraphDef>,\n  branchRank: ReadonlyMap<BranchId, number>,\n  preferredBranchId?: BranchId,\n): Readonly<{\n  props: Record<string, JsonValue>;\n  conflicts: PropertyConflict[];\n}> {\n  const propertyNames = new Set<string>();\n  for (const edge of edges) {\n    for (const name of Object.keys(edge.staged.props)) {\n      propertyNames.add(name);\n    }\n  }\n\n  const props = createDataKeyedBag<JsonValue>();\n  const conflicts: PropertyConflict[] = [];\n\n  for (const property of [...propertyNames].sort((left, right) =>\n    compareStrings(left, right),\n  )) {\n    // The staged record of an authoring edge IS a `(branchId, props)` contribution,\n    // so the shared node/edge collector consumes it directly.\n    const claimants = edges\n      .filter((edge) => authoredProperty(edge, property))\n      .map((edge) => edge.staged);\n    const values = collectConflictingValues(property, claimants);\n    if (values.length === 0) {\n      // No member of the set authored this property, so nothing competes for it:\n      // the value the survivor already holds stands, and no conflict is possible.\n      // Filtering claims must not shrink the row, so a key only a NON-survivor\n      // carries keeps a value too — see {@link unauthoredValue}.\n      props[property] =\n        hasOwnKey(survivor.staged.props, property) ?\n          (survivor.staged.props[property] as JsonValue)\n        : unauthoredValue(property, edges);\n      continue;\n    }\n    const survivorValue =\n      hasOwnKey(survivor.staged.props, property) ?\n        (survivor.staged.props[property] as JsonValue)\n      : requireDefined(values[0]).value;\n    const canonicalValue: JsonValue =\n      values.find((value) => value.branchId === preferredBranchId)?.value ??\n      survivorValue;\n    const reportedValues =\n      preferredBranchId === undefined ? values : (\n        values.filter((value) => value.branchId !== preferredBranchId)\n      );\n\n    const { value, conflict } = resolvePropertyUnion(\n      {\n        entityId: survivorId,\n        kind,\n        property,\n        values,\n        reportedValues,\n        canonicalValue,\n      },\n      context,\n      branchRank,\n    );\n    props[property] = value;\n    if (conflict !== undefined) {\n      conflicts.push(conflict);\n    }\n  }\n\n  return { props, conflicts };\n}\n\n/**\n * Folds one set of staged edges (a {@link foldSets} partition) onto the single row the\n * commit will write, resolving props and the valid-time window across its members.\n *\n * @param foldSet Non-empty. Every member shares the same repointed `(from, type, to)`.\n */\nfunction foldEdgeSet(\n  foldSet: readonly RepointedEdge[],\n  context: ResolutionContext<GraphDef>,\n  branchRank: ReadonlyMap<BranchId, number>,\n  preferredBranchId?: BranchId,\n): Readonly<{ edge: MergedEdge; conflicts: readonly PropertyConflict[] }> {\n  const survivor = pickSurvivor(foldSet, preferredBranchId);\n  const survivorId = survivor.staged.id;\n  const mergedIds = foldSet\n    .map((edge) => edge.staged.id)\n    .sort((left, right) => compareStrings(left, right));\n\n  // Endpoint ids AND kinds come from the canonical IDENTITY keys, so a repointed\n  // edge always names the canonical node's own kind (the commit then applies any\n  // retype cascade), never a staged endpoint that merely shared the id string.\n  const fromId = idOf(survivor.fromKey);\n  const fromKind = kindOf(survivor.fromKey);\n  const toId = idOf(survivor.toKey);\n  const toKind = kindOf(survivor.toKey);\n  // The survivor's lower bound rides along unchanged — a `validFrom` is the\n  // branch's authored start for the row we commit. An INHERITED survivor carries\n  // none (its start is already committed and a merge never restates it), so a\n  // branch-created member's authored start does not migrate onto the committed row\n  // the fold lands on; only its END does, below.\n  //\n  // The END is folded across the set. When repoint/dedupe collapses several\n  // DISTINCT edges into one survivor, an end claimed by a non-survivor would\n  // otherwise be discarded by the survivor pick — a silent window loss — so the\n  // earliest claimed end wins, the same least-claim rule the inherited-window\n  // reconciler uses.\n  //\n  // A survivor from the PREFERRED branch keeps its own end verbatim when it\n  // HAS one: that member is the live incremental target's row — or, when the\n  // target also staged the inherited survivor, the end already reconciled FOR\n  // that row — and a user branch never re-windows what the target already\n  // holds, so neither is the fold's to move. When the survivor has none\n  // there is no target window to protect, so the fold still resolves across\n  // the set — otherwise a preferred survivor would silently swallow the\n  // only end any branch claimed.\n  const preferredSurvivorEnd =\n    survivor.staged.branchId === preferredBranchId ?\n      typeof survivor.staged.validTo === \"string\" ?\n        { kind: \"set\" as const, validTo: survivor.staged.validTo }\n      : survivor.staged.clearValidTo === true ? { kind: \"clear\" as const }\n      : undefined\n    : undefined;\n  const foldedEnd =\n    preferredSurvivorEnd ??\n    resolveEndClaims(\n      foldSet\n        .filter(\n          (edge) =>\n            edge.staged.validTo !== undefined ||\n            edge.staged.clearValidTo === true,\n        )\n        .map((edge) => ({\n          branchId: edge.staged.branchId,\n          change:\n            typeof edge.staged.validTo === \"string\" ?\n              { kind: \"set\" as const, validTo: edge.staged.validTo }\n            : { kind: \"clear\" as const },\n        })),\n      preferredBranchId,\n    );\n  const window = {\n    ...(survivor.staged.validFrom === undefined ?\n      {}\n    : { validFrom: survivor.staged.validFrom }),\n    ...(foldedEnd?.kind === \"set\" ? { validTo: foldedEnd.validTo }\n    : foldedEnd?.kind === \"clear\" ? { clearValidTo: true as const }\n    : {}),\n  };\n\n  const contentKeys = new Set(foldSet.map((edge) => edge.dedupeKey));\n  if (contentKeys.size === 1) {\n    // Exact-equal collapse: every member shares identical props, so no\n    // conflict is possible — keep the survivor's props verbatim.\n    return {\n      edge: {\n        id: survivorId,\n        kind: survivor.staged.kind,\n        fromId,\n        toId,\n        fromKind,\n        toKind,\n        props: survivor.staged.props,\n        mergedIds,\n        ...window,\n      },\n      conflicts: [],\n    };\n  }\n\n  const { props, conflicts } = unionEdgeProps(\n    survivorId,\n    survivor.staged.kind,\n    survivor,\n    foldSet,\n    context,\n    branchRank,\n    preferredBranchId,\n  );\n  return {\n    edge: {\n      id: survivorId,\n      kind: survivor.staged.kind,\n      fromId,\n      toId,\n      fromKind,\n      toKind,\n      props,\n      mergedIds,\n      ...window,\n    },\n    conflicts,\n  };\n}\n\n/**\n * Repoints every staged edge onto its cluster canonical, drops edges whose\n * (repointed) endpoints are finally deleted, and dedupes the survivors that\n * repointing brought together as a pure set operation keyed by\n * `(from' | type | to' | propsKey)`.\n *\n * Within each folded set — one row per PRE-REPOINT endpoint pair of a group sharing\n * `(from', type, to')`:\n *   - identical props collapse silently to one edge,\n *   - DIFFERING props are reconciled by `policy` on the captured `branchRank`,\n *     recording one edge-level {@link PropertyConflict} per disagreeing property.\n *\n * The parallel rows a pair authored beyond that one are NOT folded together: the store\n * is a multigraph, so each of them commits as its own row (see {@link foldSets} and the\n * module header for the full rule and why identity, not props equality, decides it).\n *\n * The surviving edge of every folded set is its INHERITED member — the row the target\n * already holds, so the fold writes onto it instead of beside it — falling back to the\n * lexicographically-minimal contributing edge id for a set that is entirely\n * branch-created ({@link pickSurvivor}). Its `mergedIds` lists every collapsed edge id.\n * Output is sorted by the full dedupe key plus the edge id, so the result is a pure\n * function of the unordered input set.\n *\n * @param stagedEdges The new + surviving-inherited edges to merge. Order does not\n *   affect the result. Props MUST already be parsed objects.\n * @param canonicalOf The endpoint → canonical map (from {@link buildCanonicalMap}).\n *   Endpoints absent from it map to themselves.\n * @param deletedNodeIds The AUTHORITATIVE finally-deleted node id set (T8a). Any\n *   edge whose repointed `from`/`to` is in this set is dropped.\n * @param policy The property-conflict policy (shared with node union, T8).\n * @param branchRank The captured stable branch rank (built once via\n *   `buildBranchRank`). Used only for deterministic conflict resolution — never\n *   wall-clock.\n * @param weights Optional per-branch weights for the `\"provenanceWeighted\"` policy.\n */\nexport function repointEdges<G extends GraphDef = GraphDef>(\n  stagedEdges: readonly StagedEdge[],\n  canonicalOf: ReadonlyMap<MergeKey, MergeKey>,\n  deletedNodeIds: ReadonlySet<MergeKey>,\n  policy: PropertyConflictPolicy<G>,\n  branchRank: ReadonlyMap<BranchId, number>,\n  weights?: ProvenanceWeights,\n  preferredBranchId?: BranchId,\n): EdgeRepointResult<G> {\n  const dropped: DroppedEdge[] = [];\n  // Per `(from', type, to')` group → its members. Insertion order is irrelevant:\n  // Phase 2 partitions the group, re-derives each survivor, and sorts the output\n  // explicitly, so the bucket carries membership only.\n  const liveByGroup = new Map<string, RepointedEdge[]>();\n\n  // Phase 1: repoint endpoints (by their `(kind, id)` identity, so a cross-kind id\n  // collision can never repoint two unrelated edges onto one survivor), drop edges to\n  // deleted nodes, and bucket the survivors by their post-repoint endpoint group.\n  for (const staged of stagedEdges) {\n    const sourceFromKey = mergeKey(staged.fromKind, staged.fromId);\n    const sourceToKey = mergeKey(staged.toKind, staged.toId);\n    const fromKey = repoint(sourceFromKey, canonicalOf);\n    const toKey = repoint(sourceToKey, canonicalOf);\n\n    if (deletedNodeIds.has(fromKey) || deletedNodeIds.has(toKey)) {\n      dropped.push({\n        kind: \"edge\",\n        id: staged.id,\n        reason: ENDPOINT_DELETED_DROP_REASON,\n      });\n      continue;\n    }\n\n    const repointed: RepointedEdge = {\n      staged,\n      fromKey,\n      toKey,\n      sourcePair: sourcePairKey(sourceFromKey, sourceToKey),\n      dedupeKey: dedupeKey(fromKey, staged.kind, toKey, staged.props),\n    };\n    const group = groupKey(fromKey, staged.kind, toKey);\n    const bucket = liveByGroup.get(group);\n    if (bucket === undefined) {\n      liveByGroup.set(group, [repointed]);\n    } else {\n      bucket.push(repointed);\n    }\n  }\n\n  // Phase 2: partition every `(from', type, to')` group into the sets that commit as\n  // one row ({@link foldSets} — one row per pre-repoint endpoint pair collapses,\n  // further parallel rows commit on their own) and fold each set onto its survivor.\n  // A set whose members share one dedupe key is an exact-equal collapse (no conflict\n  // is possible); several dedupe keys means props differ, so the union runs the\n  // conflict policy.\n  const context: ResolutionContext<GraphDef> = {\n    policy: policy as PropertyConflictPolicy<GraphDef>,\n    ...(weights === undefined ? {} : { weights }),\n  };\n\n  const merged: MergedEdge[] = [];\n  const conflicts: PropertyConflict<G>[] = [];\n\n  const sortedGroups = [...liveByGroup.keys()].sort((left, right) =>\n    compareStrings(left, right),\n  );\n\n  for (const group of sortedGroups) {\n    const groupEdges = requireDefined(liveByGroup.get(group));\n    for (const foldSet of foldSets(groupEdges)) {\n      const folded = foldEdgeSet(\n        foldSet,\n        context,\n        branchRank,\n        preferredBranchId,\n      );\n      merged.push(folded.edge);\n      for (const conflict of folded.conflicts) {\n        conflicts.push(conflict as PropertyConflict<G>);\n      }\n    }\n  }\n\n  // Sort on a PRECOMPUTED key per edge (Schwartzian) so `canonicalizeProps` +\n  // serialization run once per edge, not twice on every comparison. The edge id is\n  // the final component: parallel edges on one endpoint pair can agree on every\n  // other one, and a non-total key would leave their order dependent on the stable\n  // sort's view of input order.\n  const sortedEdges = merged\n    .map((edge) => ({\n      edge,\n      sortKey: JSON.stringify([\n        dedupeKey(\n          mergeKey(edge.fromKind, edge.fromId),\n          edge.kind,\n          mergeKey(edge.toKind, edge.toId),\n          edge.props,\n        ),\n        edge.id,\n      ]),\n    }))\n    .sort((left, right) => compareStrings(left.sortKey, right.sortKey))\n    .map(({ edge }) => edge);\n\n  return {\n    edges: sortedEdges,\n    dropped: dropped.sort((left, right) => compareStrings(left.id, right.id)),\n    conflicts: conflicts.sort((left, right) =>\n      compareStrings(\n        `${left.entityId}|${left.property}`,\n        `${right.entityId}|${right.property}`,\n      ),\n    ),\n  };\n}\n","/**\n * Validation + default-application for {@link MergeOptions}.\n *\n * The zod schema validates the scalar / enum surface (thresholds, ceilings,\n * enums) and applies the frozen P0 defaults. Function- and store-valued fields\n * (`canonical`, a function `onPropertyConflict`, `target`, per-kind `block` /\n * `custom.score`, `branchOrder`) are not meaningfully validatable by zod, so they\n * are threaded through unchanged after the scalar surface validates.\n *\n * `normalizeMergeOptions` is the single entry point: it returns a\n * {@link NormalizedMergeOptions} with every default resolved, so downstream\n * phases never branch on `undefined`.\n */\n\nimport { z } from \"zod\";\n\nimport { createDataKeyedBag } from \"../utils/object\";\nimport type { GraphDef } from \"./typegraph-internal\";\nimport type {\n  BranchId,\n  CandidateDiagnosticsOptions,\n  ComparisonCeilingPolicy,\n  DeleteModifyPolicy,\n  Embedder,\n  MergeOptions,\n  PropertyConflictPolicy,\n  ReconcileTypesMode,\n  ResolveConfig,\n  ResolvedCluster,\n  ResolveMap,\n} from \"./types\";\n\n/**\n * Frozen P0 defaults. Exported so tests and downstream phases assert against the\n * same constants rather than re-typing literals.\n */\nexport const MERGE_OPTION_DEFAULTS = {\n  reconcileTypes: \"off\",\n  onPropertyConflict: \"flag\",\n  onBasePropertyConflict: \"flag\",\n  onDeleteModifyConflict: \"flag\",\n  onComparisonCeiling: \"error\",\n  provenance: true,\n  persistProvenance: false,\n} as const satisfies Readonly<{\n  reconcileTypes: ReconcileTypesMode;\n  onPropertyConflict: \"flag\";\n  onBasePropertyConflict: \"flag\";\n  onDeleteModifyConflict: DeleteModifyPolicy;\n  onComparisonCeiling: ComparisonCeilingPolicy;\n  provenance: boolean;\n  persistProvenance: boolean;\n}>;\n\n/**\n * zod schema for the STRING arm of `onPropertyConflict`. The field is a union of\n * this enum and a function; the function arm is not validatable by zod, but the\n * string arm is — and validating it here keeps `onPropertyConflict` consistent with\n * every other enum option, so a bad string fails with a clean option error rather\n * than an opaque `TypeError` deep inside conflict resolution.\n */\nconst propertyConflictPolicySchema = z.enum([\n  \"flag\",\n  \"lastWriteWins\",\n  \"provenanceWeighted\",\n]);\n\n/** zod schema for a single resolve config's scalar surface (the threshold). */\nconst resolveConfigScalarSchema = z.object({\n  threshold: z\n    .number()\n    .min(0, { message: \"threshold must be >= 0\" })\n    .max(1, { message: \"threshold must be <= 1\" }),\n});\n\n/**\n * zod schema for the scalar / enum surface of {@link MergeOptions}. Function- and\n * store-valued fields are deliberately omitted (validated structurally by the\n * type system, not at runtime) and re-attached after parsing.\n */\nconst mergeOptionsScalarSchema = z.object({\n  reconcileTypes: z\n    .enum([\"ontology\", \"off\"])\n    .default(MERGE_OPTION_DEFAULTS.reconcileTypes),\n  onDeleteModifyConflict: z\n    .enum([\"deleteWins\", \"modifyWins\", \"flag\"])\n    .default(MERGE_OPTION_DEFAULTS.onDeleteModifyConflict),\n  onComparisonCeiling: z\n    .enum([\"error\", \"mergeByIdOnly\"])\n    .default(MERGE_OPTION_DEFAULTS.onComparisonCeiling),\n  provenance: z.boolean().default(MERGE_OPTION_DEFAULTS.provenance),\n  persistProvenance: z\n    .boolean()\n    .default(MERGE_OPTION_DEFAULTS.persistProvenance),\n  maxComparisonsPerKind: z\n    .number()\n    .int({ message: \"maxComparisonsPerKind must be an integer\" })\n    .min(0, { message: \"maxComparisonsPerKind must be >= 0\" })\n    .optional(),\n  clusterMaxDiameter: z\n    .number()\n    .positive({ message: \"clusterMaxDiameter must be positive\" })\n    .optional(),\n  candidateDiagnostics: z\n    .object({\n      limit: z\n        .number()\n        .int({ message: \"candidateDiagnostics.limit must be an integer\" })\n        .min(0, { message: \"candidateDiagnostics.limit must be >= 0\" }),\n    })\n    .strict()\n    .optional(),\n});\n\n/**\n * Fully-normalized merge options: every default resolved, the (validated)\n * pass-through fields attached. Downstream phases consume this, never the raw\n * {@link MergeOptions}.\n */\nexport type NormalizedMergeOptions<G extends GraphDef = GraphDef> = Readonly<{\n  // Internal kind-agnostic view: the public {@link ResolveMap} is keyed per-kind,\n  // but downstream phases index it by a runtime kind STRING, so the normalized\n  // form widens to a plain record. Unknown keys were already validated away.\n  resolve: Readonly<Record<string, ResolveConfig<G>>>;\n  reconcileTypes: ReconcileTypesMode;\n  onPropertyConflict: PropertyConflictPolicy<G>;\n  onBasePropertyConflict: PropertyConflictPolicy<G>;\n  onDeleteModifyConflict: DeleteModifyPolicy;\n  onComparisonCeiling: ComparisonCeilingPolicy;\n  provenance: boolean;\n  persistProvenance: boolean;\n  canonical?: (\n    cluster: ResolvedCluster,\n  ) => ReturnType<NonNullable<MergeOptions<G>[\"canonical\"]>>;\n  embedder?: Embedder;\n  target?: MergeOptions<G>[\"target\"];\n  maxComparisonsPerKind?: number;\n  clusterMaxDiameter?: number;\n  candidateDiagnostics?: CandidateDiagnosticsOptions;\n  branchOrder?: readonly BranchId[];\n  provenanceWeights?: ReadonlyMap<BranchId, number>;\n}>;\n\n/**\n * Validates the STRING arm of a property-conflict policy (the function arm is not\n * validatable by zod), throwing a clean option error for an unknown enum value.\n * Shared by `onPropertyConflict` and the separate `onBasePropertyConflict`.\n */\nfunction validatePropertyConflictPolicy<G extends GraphDef>(\n  policy: PropertyConflictPolicy<G>,\n  label: string,\n): PropertyConflictPolicy<G> {\n  if (\n    typeof policy === \"string\" &&\n    !propertyConflictPolicySchema.safeParse(policy).success\n  ) {\n    throw new Error(\n      `Invalid ${label} \"${policy}\": expected \"flag\", \"lastWriteWins\", \"provenanceWeighted\", or a function.`,\n    );\n  }\n  return policy;\n}\n\n/**\n * Validates each per-kind resolve config's threshold, leaving the strategy and\n * `block` function untouched. Returns the same map shape (resolve configs are\n * passed through; only their scalar surface is validated).\n */\nfunction validateResolveMap<G extends GraphDef>(\n  resolve: ResolveMap<G> | undefined,\n): Readonly<Record<string, ResolveConfig<G>>> {\n  if (resolve === undefined) {\n    return {};\n  }\n  // The public ResolveMap binds each kind's config to that kind's NodeType;\n  // validation only reads the kind-agnostic scalar surface, so widen to a plain\n  // record (the per-kind block/similarity types are sound at every call site).\n  const configs = resolve as unknown as Readonly<\n    Record<string, ResolveConfig<G>>\n  >;\n  // Data-keyed: node kind names supplied by the caller's resolve map.\n  const validated = createDataKeyedBag<ResolveConfig<G>>();\n  for (const [kind, config] of Object.entries(configs)) {\n    const parsed = resolveConfigScalarSchema.safeParse({\n      threshold: config.threshold,\n    });\n    if (!parsed.success) {\n      throw new Error(\n        `Invalid resolve config for kind \"${kind}\": ${parsed.error.message}`,\n      );\n    }\n    if (\n      config.keyless !== undefined &&\n      (!Number.isInteger(config.keyless.window) || config.keyless.window < 1)\n    ) {\n      throw new Error(\n        `Invalid resolve config for kind \"${kind}\": keyless.window must be a positive integer, got ${config.keyless.window}.`,\n      );\n    }\n    const strategy = config.similarity;\n    if (strategy.kind === \"hybrid\") {\n      for (const component of [\"vector\", \"fulltext\"] as const) {\n        const weight = strategy.weights?.[component];\n        if (weight !== undefined && (!Number.isFinite(weight) || weight < 0)) {\n          throw new Error(\n            `Invalid resolve config for kind \"${kind}\": similarity.weights.${component} must be a finite number >= 0, got ${String(weight)}.`,\n          );\n        }\n      }\n    }\n    validated[kind] = config;\n  }\n  // Spread at the boundary: this becomes `NormalizedMergeOptions.resolve`,\n  // returned from the exported `normalizeMergeOptions`.\n  return { ...validated };\n}\n\n/**\n * Validates the optional `\"provenanceWeighted\"` trust weights: every weight must\n * be a finite number `>= 0`, since a NaN / negative weight would corrupt the\n * highest-weight pick. Returns the same map.\n */\nfunction validateProvenanceWeights(\n  weights: ReadonlyMap<BranchId, number>,\n): ReadonlyMap<BranchId, number> {\n  for (const [branchId, weight] of weights) {\n    if (!Number.isFinite(weight) || weight < 0) {\n      throw new Error(\n        `Invalid provenanceWeights for branch \"${branchId}\": weight must be a finite number >= 0, got ${String(weight)}.`,\n      );\n    }\n  }\n  return weights;\n}\n\n/**\n * Validates and normalizes {@link MergeOptions}, applying every P0 default.\n *\n * Throws (not a `Result`) on invalid scalar input — option validation is a\n * caller-boundary concern, surfaced as a thrown error per project conventions;\n * `merge()` converts it back to a typed `MergeError` at its own boundary.\n *\n * @throws if a threshold is outside `[0, 1]`, `maxComparisonsPerKind` is\n *   negative/non-integer, or `clusterMaxDiameter` is non-positive.\n */\nexport function normalizeMergeOptions<G extends GraphDef>(\n  options: MergeOptions<G> = {},\n): NormalizedMergeOptions<G> {\n  const scalar = mergeOptionsScalarSchema.parse({\n    reconcileTypes: options.reconcileTypes,\n    onDeleteModifyConflict: options.onDeleteModifyConflict,\n    onComparisonCeiling: options.onComparisonCeiling,\n    provenance: options.provenance,\n    persistProvenance: options.persistProvenance,\n    ...(options.maxComparisonsPerKind === undefined ?\n      {}\n    : { maxComparisonsPerKind: options.maxComparisonsPerKind }),\n    ...(options.clusterMaxDiameter === undefined ?\n      {}\n    : { clusterMaxDiameter: options.clusterMaxDiameter }),\n    ...(options.candidateDiagnostics === undefined ?\n      {}\n    : { candidateDiagnostics: options.candidateDiagnostics }),\n  });\n\n  const onPropertyConflict = validatePropertyConflictPolicy(\n    options.onPropertyConflict ?? MERGE_OPTION_DEFAULTS.onPropertyConflict,\n    \"onPropertyConflict\",\n  );\n  // DELIBERATELY does not fall back to `onPropertyConflict` — base↔branch conflicts\n  // must not silently inherit a staged policy that could overwrite committed data.\n  const onBasePropertyConflict = validatePropertyConflictPolicy(\n    options.onBasePropertyConflict ??\n      MERGE_OPTION_DEFAULTS.onBasePropertyConflict,\n    \"onBasePropertyConflict\",\n  );\n\n  const provenanceWeights =\n    options.provenanceWeights === undefined ?\n      undefined\n    : validateProvenanceWeights(options.provenanceWeights);\n\n  // \"provenanceWeighted\" without weights would silently degrade to a\n  // stable-branch-order (lastWriteWins) resolution and quietly commit a\n  // different graph. Fail loudly instead so the misconfiguration is visible.\n  const usesProvenanceWeighting =\n    onPropertyConflict === \"provenanceWeighted\" ||\n    onBasePropertyConflict === \"provenanceWeighted\";\n  if (\n    usesProvenanceWeighting &&\n    (provenanceWeights === undefined || provenanceWeights.size === 0)\n  ) {\n    throw new Error(\n      'A \"provenanceWeighted\" property-conflict policy requires a non-empty provenanceWeights map.',\n    );\n  }\n\n  return {\n    resolve: validateResolveMap(options.resolve),\n    reconcileTypes: scalar.reconcileTypes,\n    onPropertyConflict,\n    onBasePropertyConflict,\n    onDeleteModifyConflict: scalar.onDeleteModifyConflict,\n    onComparisonCeiling: scalar.onComparisonCeiling,\n    provenance: scalar.provenance,\n    persistProvenance: scalar.persistProvenance,\n    ...(options.canonical === undefined ?\n      {}\n    : { canonical: options.canonical }),\n    ...(options.embedder === undefined ? {} : { embedder: options.embedder }),\n    ...(options.target === undefined ? {} : { target: options.target }),\n    ...(scalar.maxComparisonsPerKind === undefined ?\n      {}\n    : { maxComparisonsPerKind: scalar.maxComparisonsPerKind }),\n    ...(scalar.clusterMaxDiameter === undefined ?\n      {}\n    : { clusterMaxDiameter: scalar.clusterMaxDiameter }),\n    ...(scalar.candidateDiagnostics === undefined ?\n      {}\n    : { candidateDiagnostics: scalar.candidateDiagnostics }),\n    ...(options.branchOrder === undefined ?\n      {}\n    : { branchOrder: options.branchOrder }),\n    ...(provenanceWeights === undefined ? {} : { provenanceWeights }),\n  };\n}\n","import { z } from \"zod\";\n\nimport { compareEntityRefs, compareMatchSources } from \"./evidence\";\nimport type { JsonValue } from \"./typegraph-internal\";\n\nexport const MERGE_PLAN_FORMAT_VERSION = 1 as const;\nexport const MERGE_PLAN_DIGEST_ALGORITHM = \"sha256\" as const;\n\nexport type MergePlanEntityRef = Readonly<{ kind: string; id: string }>;\n\nexport type MergePlanSchemaFence = Readonly<{\n  managed: boolean;\n  version: number;\n  hash: string;\n}>;\n\nexport type MergePlanRevisionFence = Readonly<{\n  origin: string;\n  revision: string | null;\n}>;\n\nexport type MergePlanTargetFence = Readonly<{\n  graphId: string;\n  schema: MergePlanSchemaFence;\n  revision: MergePlanRevisionFence;\n}>;\n\nexport type MergePlanBranchAnchor = Readonly<{\n  branchId: string;\n  baseVersion: string;\n}>;\n\nexport type MergePlanAnchors =\n  | Readonly<{\n      kind: \"snapshot\";\n      base: Readonly<{ graphId: string; baseVersion: string }>;\n      branches: readonly MergePlanBranchAnchor[];\n    }>\n  | Readonly<{\n      kind: \"incremental\";\n      forkPoint: Readonly<{\n        graphId: string;\n        baseVersion: string;\n        schema: MergePlanSchemaFence;\n      }>;\n      branches: readonly MergePlanBranchAnchor[];\n    }>;\n\nexport type MergePlanNodeDelete = MergePlanEntityRef;\n\nexport type MergePlanNodeUpsert = Readonly<{\n  kind: string;\n  id: string;\n  setProps: Readonly<Record<string, JsonValue>>;\n  unsetProps: readonly string[];\n  validFrom?: string | null | undefined;\n  validTo?: string | undefined;\n}>;\n\nexport type MergePlanEdgeDelete = MergePlanEntityRef;\n\nexport type MergePlanEdgeUpsert = Readonly<{\n  kind: string;\n  id: string;\n  from: MergePlanEntityRef;\n  to: MergePlanEntityRef;\n  setProps: Readonly<Record<string, JsonValue>>;\n  unsetProps: readonly string[];\n  validFrom?: string | null | undefined;\n  validTo?: string | undefined;\n}>;\n\nexport type MergePlanIdentityAssertion = Readonly<{\n  id: string;\n  relation: \"same\" | \"different\";\n  a: MergePlanEntityRef;\n  b: MergePlanEntityRef;\n  validFrom: string;\n  validTo?: string | undefined;\n  endedBy?: MergePlanEntityRef | undefined;\n}>;\n\nexport type MergePlanWrites = Readonly<{\n  nodeDeletes: readonly MergePlanNodeDelete[];\n  nodeUpserts: readonly MergePlanNodeUpsert[];\n  edgeDeletes: readonly MergePlanEdgeDelete[];\n  edgeUpserts: readonly MergePlanEdgeUpsert[];\n  identityAssertions: readonly MergePlanIdentityAssertion[];\n  identityRetractions: readonly MergePlanIdentityAssertion[];\n}>;\n\nexport type MergePlanProposedSummary = Readonly<{\n  nodes: Readonly<{ upserts: number; deletions: number }>;\n  edges: Readonly<{ upserts: number; deletions: number }>;\n  identity: Readonly<{ assertions: number; retractions: number }>;\n}>;\n\nexport type MergePlanCanonicalMapping = Readonly<{\n  member: MergePlanEntityRef;\n  canonical: MergePlanEntityRef;\n}>;\n\nexport type MergePlanRetype = Readonly<{\n  entity: MergePlanEntityRef;\n  toKind: string;\n}>;\n\nexport type MergePlanGuards = Readonly<{\n  canonicalMappings: readonly MergePlanCanonicalMapping[];\n  retypes: readonly MergePlanRetype[];\n  deletedNodes: readonly MergePlanEntityRef[];\n  incremental?: Readonly<{\n    tombstoneResurrection: \"refuse\";\n    lossyUpdates: \"refuse\";\n    edgeIdentity: \"preserve\";\n  }>;\n}>;\n\nexport type MergePlanMatchSource =\n  | Readonly<{ kind: \"block\"; sourceId: string }>\n  | Readonly<{\n      kind: \"unique\";\n      sourceId: string;\n      constraintName: string;\n    }>\n  | Readonly<{\n      kind: \"baseUnique\";\n      sourceId: string;\n      constraintName: string;\n    }>\n  | Readonly<{\n      kind: \"baseIndex\";\n      sourceId: string;\n      indexName: string;\n    }>\n  | Readonly<{ kind: \"keyless\"; sourceId: string }>\n  | Readonly<{ kind: \"retype\"; sourceId: string }>\n  | Readonly<{\n      kind: \"custom\";\n      sourceId: string;\n      metadata?: JsonValue | undefined;\n    }>;\n\nexport type MergePlanSimilarityStrategy =\n  | Readonly<{ kind: \"fulltext\" | \"vector\"; fields: readonly string[] }>\n  | Readonly<{\n      kind: \"hybrid\";\n      fields: readonly string[];\n      weights: Readonly<{ vector: number; fulltext: number }>;\n    }>\n  | Readonly<{ kind: \"custom\" }>;\n\nexport type MergePlanMatchEvidence =\n  | Readonly<{\n      a: MergePlanEntityRef;\n      b: MergePlanEntityRef;\n      sources: readonly MergePlanMatchSource[];\n      decision: \"definitional\";\n    }>\n  | Readonly<{\n      a: MergePlanEntityRef;\n      b: MergePlanEntityRef;\n      sources: readonly MergePlanMatchSource[];\n      decision: \"scored\";\n      strategy: MergePlanSimilarityStrategy;\n      score: number;\n      threshold: number;\n    }>;\n\nexport type MergePlanEntityResolution = Readonly<{\n  canonicalId: string;\n  memberIds: readonly string[];\n  kind: string;\n  branchOrigins: readonly string[];\n  decisiveEdges: readonly MergePlanMatchEvidence[];\n}>;\n\nexport type MergePlanCandidateDiagnostic = Readonly<{\n  evidence: MergePlanMatchEvidence;\n  scoreDecision: \"accepted\" | \"rejected\";\n  reason?: \"noComparableValues\" | undefined;\n  clusterDisposition?:\n    | \"retained\"\n    | Readonly<{\n        kind: \"excluded\";\n        reason: \"diameter\" | \"baseAmbiguity\";\n      }>\n    | undefined;\n}>;\n\nexport type MergePlanDiagnostics = Readonly<{\n  entries: readonly MergePlanCandidateDiagnostic[];\n  total: number;\n  limit: number;\n  truncated: boolean;\n}>;\n\nexport type MergePlanTypeReconciliation = Readonly<{\n  entityId: string;\n  fromTypes: readonly string[];\n  toType: string;\n  decisiveEdges?: readonly MergePlanMatchEvidence[] | undefined;\n}>;\n\nexport type MergePlanReview = Readonly<{\n  resolutions: readonly MergePlanEntityResolution[];\n  conflicts: readonly JsonValue[];\n  deleteModifyConflicts: readonly JsonValue[];\n  typeReconciliations: readonly MergePlanTypeReconciliation[];\n  dropped: readonly JsonValue[];\n  validityEnds: readonly JsonValue[];\n  baseAmbiguities: readonly JsonValue[];\n  provenanceRecords: readonly JsonValue[];\n  warnings: readonly string[];\n  diagnostics?: MergePlanDiagnostics | undefined;\n}>;\n\nexport type MergePlanProvenanceOptions = Readonly<{\n  includeInReport: boolean;\n  persist: boolean;\n}>;\n\nexport type MergePlanDigest = Readonly<{\n  algorithm: typeof MERGE_PLAN_DIGEST_ALGORITHM;\n  value: string;\n}>;\n\nexport type MergePlanArtifactV1 = Readonly<{\n  formatVersion: typeof MERGE_PLAN_FORMAT_VERSION;\n  digest: MergePlanDigest;\n  mode: \"snapshot\" | \"incremental\";\n  target: MergePlanTargetFence;\n  anchors: MergePlanAnchors;\n  proposed: MergePlanProposedSummary;\n  writes: MergePlanWrites;\n  guards: MergePlanGuards;\n  review: MergePlanReview;\n  provenance: MergePlanProvenanceOptions;\n}>;\n\n/** Current public merge-plan artifact type. */\nexport type MergePlanArtifact = MergePlanArtifactV1;\n\nexport type MergePlanArtifactV1Input = Omit<MergePlanArtifactV1, \"digest\">;\n\nconst nonEmptyStringSchema = z.string().min(1);\n// Zod 4's number schema rejects NaN and infinities by default.\nconst finiteNumberSchema = z.number();\nconst nonNegativeIntegerSchema = finiteNumberSchema.int().nonnegative();\nconst jsonObjectSchema = z.record(z.string(), z.json());\n\nconst mergePlanEntityRefSchema = z\n  .object({ kind: nonEmptyStringSchema, id: nonEmptyStringSchema })\n  .strict();\n\nconst mergePlanSchemaFenceSchema = z\n  .object({\n    managed: z.boolean(),\n    version: nonNegativeIntegerSchema,\n    hash: nonEmptyStringSchema,\n  })\n  .strict();\n\nconst mergePlanRevisionFenceSchema = z\n  .object({\n    origin: nonEmptyStringSchema,\n    revision: nonEmptyStringSchema.nullable(),\n  })\n  .strict();\n\nconst mergePlanTargetFenceSchema = z\n  .object({\n    graphId: nonEmptyStringSchema,\n    schema: mergePlanSchemaFenceSchema,\n    revision: mergePlanRevisionFenceSchema,\n  })\n  .strict();\n\nconst branchAnchorSchema = z\n  .object({\n    branchId: nonEmptyStringSchema,\n    baseVersion: nonEmptyStringSchema,\n  })\n  .strict();\n\nconst snapshotAnchorsSchema = z\n  .object({\n    kind: z.literal(\"snapshot\"),\n    base: z\n      .object({\n        graphId: nonEmptyStringSchema,\n        baseVersion: nonEmptyStringSchema,\n      })\n      .strict(),\n    branches: z.array(branchAnchorSchema),\n  })\n  .strict();\n\nconst incrementalAnchorsSchema = z\n  .object({\n    kind: z.literal(\"incremental\"),\n    forkPoint: z\n      .object({\n        graphId: nonEmptyStringSchema,\n        baseVersion: nonEmptyStringSchema,\n        schema: mergePlanSchemaFenceSchema,\n      })\n      .strict(),\n    branches: z.array(branchAnchorSchema),\n  })\n  .strict();\n\nconst mergePlanAnchorsSchema = z.discriminatedUnion(\"kind\", [\n  snapshotAnchorsSchema,\n  incrementalAnchorsSchema,\n]);\n\nconst nodeUpsertSchema = z\n  .object({\n    kind: nonEmptyStringSchema,\n    id: nonEmptyStringSchema,\n    setProps: jsonObjectSchema,\n    unsetProps: z.array(nonEmptyStringSchema),\n    validFrom: nonEmptyStringSchema.nullable().optional(),\n    validTo: nonEmptyStringSchema.optional(),\n  })\n  .strict();\n\nconst edgeUpsertSchema = z\n  .object({\n    kind: nonEmptyStringSchema,\n    id: nonEmptyStringSchema,\n    from: mergePlanEntityRefSchema,\n    to: mergePlanEntityRefSchema,\n    setProps: jsonObjectSchema,\n    unsetProps: z.array(nonEmptyStringSchema),\n    validFrom: nonEmptyStringSchema.nullable().optional(),\n    validTo: nonEmptyStringSchema.optional(),\n  })\n  .strict();\n\nconst mergePlanIdentityAssertionSchema = z\n  .object({\n    id: nonEmptyStringSchema,\n    relation: z.enum([\"same\", \"different\"]),\n    a: mergePlanEntityRefSchema,\n    b: mergePlanEntityRefSchema,\n    validFrom: nonEmptyStringSchema,\n    validTo: nonEmptyStringSchema.optional(),\n    endedBy: mergePlanEntityRefSchema.optional(),\n  })\n  .strict();\n\nconst mergePlanWritesSchema = z\n  .object({\n    nodeDeletes: z.array(mergePlanEntityRefSchema),\n    nodeUpserts: z.array(nodeUpsertSchema),\n    edgeDeletes: z.array(mergePlanEntityRefSchema),\n    edgeUpserts: z.array(edgeUpsertSchema),\n    identityAssertions: z.array(mergePlanIdentityAssertionSchema),\n    identityRetractions: z.array(mergePlanIdentityAssertionSchema),\n  })\n  .strict();\n\nconst proposedRoleSchema = z\n  .object({\n    upserts: nonNegativeIntegerSchema,\n    deletions: nonNegativeIntegerSchema,\n  })\n  .strict();\n\nconst mergePlanProposedSummarySchema = z\n  .object({\n    nodes: proposedRoleSchema,\n    edges: proposedRoleSchema,\n    identity: z\n      .object({\n        assertions: nonNegativeIntegerSchema,\n        retractions: nonNegativeIntegerSchema,\n      })\n      .strict(),\n  })\n  .strict();\n\nconst mergePlanGuardsSchema = z\n  .object({\n    canonicalMappings: z.array(\n      z\n        .object({\n          member: mergePlanEntityRefSchema,\n          canonical: mergePlanEntityRefSchema,\n        })\n        .strict(),\n    ),\n    retypes: z.array(\n      z\n        .object({\n          entity: mergePlanEntityRefSchema,\n          toKind: nonEmptyStringSchema,\n        })\n        .strict(),\n    ),\n    deletedNodes: z.array(mergePlanEntityRefSchema),\n    incremental: z\n      .object({\n        tombstoneResurrection: z.literal(\"refuse\"),\n        lossyUpdates: z.literal(\"refuse\"),\n        edgeIdentity: z.literal(\"preserve\"),\n      })\n      .strict()\n      .optional(),\n  })\n  .strict();\n\nconst matchSourceSchema = z.discriminatedUnion(\"kind\", [\n  z\n    .object({ kind: z.literal(\"block\"), sourceId: nonEmptyStringSchema })\n    .strict(),\n  z\n    .object({\n      kind: z.literal(\"unique\"),\n      sourceId: nonEmptyStringSchema,\n      constraintName: nonEmptyStringSchema,\n    })\n    .strict(),\n  z\n    .object({\n      kind: z.literal(\"baseUnique\"),\n      sourceId: nonEmptyStringSchema,\n      constraintName: nonEmptyStringSchema,\n    })\n    .strict(),\n  z\n    .object({\n      kind: z.literal(\"baseIndex\"),\n      sourceId: nonEmptyStringSchema,\n      indexName: nonEmptyStringSchema,\n    })\n    .strict(),\n  z\n    .object({ kind: z.literal(\"keyless\"), sourceId: nonEmptyStringSchema })\n    .strict(),\n  z\n    .object({ kind: z.literal(\"retype\"), sourceId: nonEmptyStringSchema })\n    .strict(),\n  z\n    .object({\n      kind: z.literal(\"custom\"),\n      sourceId: nonEmptyStringSchema,\n      metadata: z.json().optional(),\n    })\n    .strict(),\n]);\n\nconst similarityStrategySchema = z.discriminatedUnion(\"kind\", [\n  z\n    .object({\n      kind: z.literal(\"fulltext\"),\n      fields: z.array(nonEmptyStringSchema),\n    })\n    .strict(),\n  z\n    .object({\n      kind: z.literal(\"vector\"),\n      fields: z.array(nonEmptyStringSchema),\n    })\n    .strict(),\n  z\n    .object({\n      kind: z.literal(\"hybrid\"),\n      fields: z.array(nonEmptyStringSchema),\n      weights: z\n        .object({ vector: finiteNumberSchema, fulltext: finiteNumberSchema })\n        .strict(),\n    })\n    .strict(),\n  z.object({ kind: z.literal(\"custom\") }).strict(),\n]);\n\nconst definitionalEvidenceSchema = z\n  .object({\n    a: mergePlanEntityRefSchema,\n    b: mergePlanEntityRefSchema,\n    sources: z.array(matchSourceSchema),\n    decision: z.literal(\"definitional\"),\n  })\n  .strict();\n\nconst scoredEvidenceSchema = z\n  .object({\n    a: mergePlanEntityRefSchema,\n    b: mergePlanEntityRefSchema,\n    sources: z.array(matchSourceSchema),\n    decision: z.literal(\"scored\"),\n    strategy: similarityStrategySchema,\n    score: finiteNumberSchema,\n    threshold: finiteNumberSchema,\n  })\n  .strict();\n\nconst mergePlanMatchEvidenceSchema = z.discriminatedUnion(\"decision\", [\n  definitionalEvidenceSchema,\n  scoredEvidenceSchema,\n]);\n\nconst entityResolutionSchema = z\n  .object({\n    canonicalId: nonEmptyStringSchema,\n    memberIds: z.array(nonEmptyStringSchema),\n    kind: nonEmptyStringSchema,\n    branchOrigins: z.array(nonEmptyStringSchema),\n    decisiveEdges: z.array(mergePlanMatchEvidenceSchema),\n  })\n  .strict();\n\nconst diagnosticsSchema = z\n  .object({\n    entries: z.array(\n      z\n        .object({\n          evidence: mergePlanMatchEvidenceSchema,\n          scoreDecision: z.enum([\"accepted\", \"rejected\"]),\n          reason: z.literal(\"noComparableValues\").optional(),\n          clusterDisposition: z\n            .union([\n              z.literal(\"retained\"),\n              z\n                .object({\n                  kind: z.literal(\"excluded\"),\n                  reason: z.enum([\"diameter\", \"baseAmbiguity\"]),\n                })\n                .strict(),\n            ])\n            .optional(),\n        })\n        .strict(),\n    ),\n    total: nonNegativeIntegerSchema,\n    limit: nonNegativeIntegerSchema,\n    truncated: z.boolean(),\n  })\n  .strict();\n\nconst mergePlanReviewSchema = z\n  .object({\n    resolutions: z.array(entityResolutionSchema),\n    conflicts: z.array(\n      z\n        .object({\n          entityId: nonEmptyStringSchema,\n          kind: nonEmptyStringSchema,\n          property: nonEmptyStringSchema,\n          values: z.array(\n            z\n              .object({ branchId: nonEmptyStringSchema, value: z.json() })\n              .strict(),\n          ),\n          resolution: z.json(),\n        })\n        .strict(),\n    ),\n    deleteModifyConflicts: z.array(\n      z\n        .object({\n          entityId: nonEmptyStringSchema,\n          kind: nonEmptyStringSchema,\n          deletedBy: nonEmptyStringSchema,\n          modifiedBy: nonEmptyStringSchema,\n          resolution: z.enum([\"deleteWins\", \"modifyWins\", \"flag\"]),\n        })\n        .strict(),\n    ),\n    typeReconciliations: z.array(\n      z\n        .object({\n          entityId: nonEmptyStringSchema,\n          fromTypes: z.array(nonEmptyStringSchema),\n          toType: nonEmptyStringSchema,\n          decisiveEdges: z.array(mergePlanMatchEvidenceSchema).optional(),\n        })\n        .strict(),\n    ),\n    dropped: z.array(\n      z.discriminatedUnion(\"kind\", [\n        z\n          .object({\n            kind: z.literal(\"node\"),\n            id: nonEmptyStringSchema,\n            reason: nonEmptyStringSchema,\n          })\n          .strict(),\n        z\n          .object({\n            kind: z.literal(\"edge\"),\n            id: nonEmptyStringSchema,\n            reason: nonEmptyStringSchema,\n          })\n          .strict(),\n        z\n          .object({\n            kind: z.literal(\"identity\"),\n            id: nonEmptyStringSchema,\n            reason: nonEmptyStringSchema,\n          })\n          .strict(),\n      ]),\n    ),\n    validityEnds: z.array(\n      z\n        .object({\n          entity: z.enum([\"node\", \"edge\"]),\n          kind: nonEmptyStringSchema,\n          id: nonEmptyStringSchema,\n          validTo: nonEmptyStringSchema,\n          claimedBy: z.array(nonEmptyStringSchema),\n          precedence: z.literal(\"target\").optional(),\n        })\n        .strict(),\n    ),\n    baseAmbiguities: z.array(\n      z\n        .object({\n          baseIds: z.array(mergePlanEntityRefSchema),\n          memberIds: z.array(mergePlanEntityRefSchema),\n        })\n        .strict(),\n    ),\n    provenanceRecords: z.array(\n      z\n        .object({\n          role: z.enum([\"node\", \"edge\"]),\n          canonicalId: nonEmptyStringSchema,\n          canonicalKind: nonEmptyStringSchema,\n          branchId: nonEmptyStringSchema,\n          sourceId: nonEmptyStringSchema,\n        })\n        .strict(),\n    ),\n    warnings: z.array(z.string()),\n    diagnostics: diagnosticsSchema.optional(),\n  })\n  .strict();\n\nconst mergePlanDigestSchema = z\n  .object({\n    algorithm: z.literal(MERGE_PLAN_DIGEST_ALGORITHM),\n    value: z.string().regex(/^[\\da-f]{64}$/),\n  })\n  .strict();\n\nconst mergePlanArtifactV1BaseSchema = z\n  .object({\n    formatVersion: z.literal(MERGE_PLAN_FORMAT_VERSION),\n    digest: mergePlanDigestSchema,\n    mode: z.enum([\"snapshot\", \"incremental\"]),\n    target: mergePlanTargetFenceSchema,\n    anchors: mergePlanAnchorsSchema,\n    proposed: mergePlanProposedSummarySchema,\n    writes: mergePlanWritesSchema,\n    guards: mergePlanGuardsSchema,\n    review: mergePlanReviewSchema,\n    provenance: z\n      .object({ includeInReport: z.boolean(), persist: z.boolean() })\n      .strict(),\n  })\n  .strict();\n\nconst mergePlanArtifactV1InputBaseSchema = mergePlanArtifactV1BaseSchema.omit({\n  digest: true,\n});\ntype ParsedMergePlanArtifactV1Input = z.infer<\n  typeof mergePlanArtifactV1InputBaseSchema\n>;\n\nfunction addSemanticIssues(\n  artifact: ParsedMergePlanArtifactV1Input,\n  ctx: z.RefinementCtx,\n): void {\n  if (artifact.mode !== artifact.anchors.kind) {\n    ctx.addIssue({\n      code: \"custom\",\n      path: [\"anchors\", \"kind\"],\n      message: `Expected ${artifact.mode} anchors for a ${artifact.mode} plan.`,\n    });\n  }\n  if (\n    (artifact.mode === \"incremental\") !==\n    (artifact.guards.incremental !== undefined)\n  ) {\n    ctx.addIssue({\n      code: \"custom\",\n      path: [\"guards\", \"incremental\"],\n      message:\n        \"Incremental write guards must be present exactly for incremental plans.\",\n    });\n  }\n\n  const expectedCounts = {\n    nodeUpserts: artifact.writes.nodeUpserts.length,\n    nodeDeletions: artifact.writes.nodeDeletes.length,\n    edgeUpserts: artifact.writes.edgeUpserts.length,\n    edgeDeletions: artifact.writes.edgeDeletes.length,\n    assertions: artifact.writes.identityAssertions.length,\n    retractions: artifact.writes.identityRetractions.length,\n  };\n  const receivedCounts = {\n    nodeUpserts: artifact.proposed.nodes.upserts,\n    nodeDeletions: artifact.proposed.nodes.deletions,\n    edgeUpserts: artifact.proposed.edges.upserts,\n    edgeDeletions: artifact.proposed.edges.deletions,\n    assertions: artifact.proposed.identity.assertions,\n    retractions: artifact.proposed.identity.retractions,\n  };\n  if (JSON.stringify(expectedCounts) !== JSON.stringify(receivedCounts)) {\n    ctx.addIssue({\n      code: \"custom\",\n      path: [\"proposed\"],\n      message: \"Proposed counts must equal the resolved write-set counts.\",\n    });\n  }\n\n  addOperationIssues(\n    artifact.writes.nodeDeletes,\n    artifact.writes.nodeUpserts,\n    \"node\",\n    ctx,\n  );\n  addOperationIssues(\n    artifact.writes.edgeDeletes,\n    artifact.writes.edgeUpserts,\n    \"edge\",\n    ctx,\n  );\n  for (const [index, upsert] of artifact.writes.nodeUpserts.entries()) {\n    addPropertyPatchIssues(upsert, [\"writes\", \"nodeUpserts\", index], ctx);\n  }\n  for (const [index, upsert] of artifact.writes.edgeUpserts.entries()) {\n    addPropertyPatchIssues(upsert, [\"writes\", \"edgeUpserts\", index], ctx);\n  }\n\n  const canonicalByMember = new Map<string, string>();\n  let invalidCanonicalMappings = false;\n  for (const mapping of artifact.guards.canonicalMappings) {\n    const member = entityKey(mapping.member);\n    const canonical = entityKey(mapping.canonical);\n    if (canonicalByMember.has(member)) invalidCanonicalMappings = true;\n    canonicalByMember.set(member, canonical);\n  }\n  for (const canonical of canonicalByMember.values()) {\n    if (canonicalByMember.get(canonical) !== canonical) {\n      invalidCanonicalMappings = true;\n    }\n  }\n  if (invalidCanonicalMappings) {\n    ctx.addIssue({\n      code: \"custom\",\n      path: [\"guards\", \"canonicalMappings\"],\n      message:\n        \"Canonical mappings must name each member once and include a self-mapped canonical root.\",\n    });\n  }\n\n  const diagnostics = artifact.review.diagnostics;\n  if (diagnostics !== undefined) {\n    const expectedRetained = Math.min(diagnostics.total, diagnostics.limit);\n    if (\n      diagnostics.entries.length !== expectedRetained ||\n      diagnostics.truncated !== diagnostics.total > diagnostics.entries.length\n    ) {\n      ctx.addIssue({\n        code: \"custom\",\n        path: [\"review\", \"diagnostics\"],\n        message:\n          \"Diagnostic retention and truncation metadata must exactly match total and limit.\",\n      });\n    }\n    for (const [index, diagnostic] of diagnostics.entries.entries()) {\n      addEvidenceIssues(\n        diagnostic.evidence,\n        [\"review\", \"diagnostics\", \"entries\", index, \"evidence\"],\n        ctx,\n      );\n      const accepted =\n        diagnostic.evidence.decision === \"definitional\" ||\n        (diagnostic.evidence.score >= diagnostic.evidence.threshold &&\n          diagnostic.reason === undefined);\n      if (\n        diagnostic.scoreDecision !== (accepted ? \"accepted\" : \"rejected\") ||\n        (diagnostic.evidence.decision === \"scored\" &&\n          diagnostic.reason === \"noComparableValues\" &&\n          diagnostic.evidence.score !== 0) ||\n        (diagnostic.evidence.decision === \"definitional\" &&\n          (diagnostic.reason !== undefined ||\n            typeof diagnostic.clusterDisposition !== \"object\")) ||\n        (diagnostic.scoreDecision === \"rejected\" &&\n          diagnostic.clusterDisposition !== undefined)\n      ) {\n        ctx.addIssue({\n          code: \"custom\",\n          path: [\"review\", \"diagnostics\", \"entries\", index],\n          message:\n            \"Diagnostic decision, reason, and cluster disposition must agree with its score evidence.\",\n        });\n      }\n    }\n  }\n\n  for (const [index, resolution] of artifact.review.resolutions.entries()) {\n    addResolutionEvidenceIssues(artifact, resolution, index, ctx);\n  }\n  for (const [\n    reconciliationIndex,\n    reconciliation,\n  ] of artifact.review.typeReconciliations.entries()) {\n    for (const [edgeIndex, evidence] of (\n      reconciliation.decisiveEdges ?? []\n    ).entries()) {\n      addEvidenceIssues(\n        evidence,\n        [\n          \"review\",\n          \"typeReconciliations\",\n          reconciliationIndex,\n          \"decisiveEdges\",\n          edgeIndex,\n        ],\n        ctx,\n      );\n    }\n  }\n}\n\nfunction addResolutionEvidenceIssues(\n  artifact: ParsedMergePlanArtifactV1Input,\n  resolution: ParsedMergePlanArtifactV1Input[\"review\"][\"resolutions\"][number],\n  resolutionIndex: number,\n  ctx: z.RefinementCtx,\n): void {\n  const retypedKinds = new Map(\n    artifact.guards.retypes.map((retype) => [\n      entityKey(retype.entity),\n      retype.toKind,\n    ]),\n  );\n  const clusterMembers = artifact.guards.canonicalMappings\n    .filter((mapping) => {\n      const canonicalKind =\n        retypedKinds.get(entityKey(mapping.canonical)) ??\n        mapping.canonical.kind;\n      return (\n        mapping.canonical.id === resolution.canonicalId &&\n        canonicalKind === resolution.kind\n      );\n    })\n    .map((mapping) => mapping.member);\n  const uniqueMembers = new Map(\n    clusterMembers.map((member) => [entityKey(member), member]),\n  );\n  const memberIds = new Set(\n    [...uniqueMembers.values()].map((member) => member.id),\n  );\n  const declaredMemberIds = new Set(resolution.memberIds);\n  if (\n    uniqueMembers.size < 2 ||\n    declaredMemberIds.size !== resolution.memberIds.length ||\n    memberIds.size !== declaredMemberIds.size ||\n    [...memberIds].some((id) => !declaredMemberIds.has(id)) ||\n    resolution.decisiveEdges.length !== uniqueMembers.size - 1\n  ) {\n    ctx.addIssue({\n      code: \"custom\",\n      path: [\"review\", \"resolutions\", resolutionIndex],\n      message:\n        \"A resolution must name its complete guarded cluster and carry exactly N-1 decisive edges.\",\n    });\n    return;\n  }\n\n  const parent = new Map([...uniqueMembers.keys()].map((key) => [key, key]));\n  const find = (key: string): string => {\n    const next = parent.get(key);\n    if (next === undefined || next === key) return key;\n    const root = find(next);\n    parent.set(key, root);\n    return root;\n  };\n  let invalidTree = false;\n  for (const [edgeIndex, evidence] of resolution.decisiveEdges.entries()) {\n    addEvidenceIssues(\n      evidence,\n      [\"review\", \"resolutions\", resolutionIndex, \"decisiveEdges\", edgeIndex],\n      ctx,\n    );\n    const a = entityKey(evidence.a);\n    const b = entityKey(evidence.b);\n    if (!uniqueMembers.has(a) || !uniqueMembers.has(b)) {\n      invalidTree = true;\n      continue;\n    }\n    const rootA = find(a);\n    const rootB = find(b);\n    if (rootA === rootB) invalidTree = true;\n    else parent.set(rootB, rootA);\n  }\n  if (\n    invalidTree ||\n    new Set([...uniqueMembers.keys()].map((key) => find(key))).size !== 1\n  ) {\n    ctx.addIssue({\n      code: \"custom\",\n      path: [\"review\", \"resolutions\", resolutionIndex, \"decisiveEdges\"],\n      message:\n        \"Decisive edges must be an acyclic connected witness over the guarded cluster.\",\n    });\n  }\n}\n\nfunction addEvidenceIssues(\n  evidence: ParsedMergePlanArtifactV1Input[\"review\"][\"resolutions\"][number][\"decisiveEdges\"][number],\n  path: readonly (string | number)[],\n  ctx: z.RefinementCtx,\n): void {\n  const sourcesCanonical = evidence.sources.every((source, index) => {\n    const previous = evidence.sources[index - 1];\n    return previous === undefined || compareMatchSources(previous, source) < 0;\n  });\n  const invalidStrategy =\n    evidence.decision === \"scored\" &&\n    ((evidence.strategy.kind === \"vector\" &&\n      evidence.strategy.fields.length !== 1) ||\n      (evidence.strategy.kind === \"hybrid\" &&\n        (evidence.strategy.weights.vector < 0 ||\n          evidence.strategy.weights.vector > 1 ||\n          evidence.strategy.weights.fulltext < 0 ||\n          evidence.strategy.weights.fulltext > 1 ||\n          Math.abs(\n            evidence.strategy.weights.vector +\n              evidence.strategy.weights.fulltext -\n              1,\n          ) > Number.EPSILON)));\n  if (\n    compareEntityRefs(evidence.a, evidence.b) >= 0 ||\n    evidence.sources.length === 0 ||\n    !sourcesCanonical ||\n    (evidence.decision === \"scored\" &&\n      (evidence.score < 0 ||\n        evidence.score > 1 ||\n        evidence.threshold < 0 ||\n        evidence.threshold > 1)) ||\n    invalidStrategy\n  ) {\n    ctx.addIssue({\n      code: \"custom\",\n      path: [...path],\n      message:\n        \"Evidence endpoints and sources must be canonical, and scored values must be within [0, 1].\",\n    });\n  }\n}\n\nfunction addOperationIssues(\n  deletions: readonly MergePlanEntityRef[],\n  upserts: readonly MergePlanEntityRef[],\n  role: \"node\" | \"edge\",\n  ctx: z.RefinementCtx,\n): void {\n  const deletionKeys = deletions.map((entry) => entityKey(entry));\n  const upsertKeys = upserts.map((entry) => entityKey(entry));\n  if (\n    new Set(deletionKeys).size !== deletionKeys.length ||\n    new Set(upsertKeys).size !== upsertKeys.length\n  ) {\n    ctx.addIssue({\n      code: \"custom\",\n      path: [\"writes\"],\n      message: `The ${role} write set must not contain duplicate identities.`,\n    });\n  }\n  const deleted = new Set(deletionKeys);\n  if (upsertKeys.some((key) => deleted.has(key))) {\n    ctx.addIssue({\n      code: \"custom\",\n      path: [\"writes\"],\n      message: `The same ${role} identity cannot be both deleted and upserted.`,\n    });\n  }\n}\n\nfunction addPropertyPatchIssues(\n  patch: Readonly<{\n    setProps: Readonly<Record<string, JsonValue>>;\n    unsetProps: readonly string[];\n  }>,\n  path: readonly (string | number)[],\n  ctx: z.RefinementCtx,\n): void {\n  const unset = new Set(patch.unsetProps);\n  if (\n    unset.size !== patch.unsetProps.length ||\n    Object.keys(patch.setProps).some((key) => unset.has(key))\n  ) {\n    ctx.addIssue({\n      code: \"custom\",\n      path: [...path],\n      message:\n        \"unsetProps must be duplicate-free and disjoint from setProps keys.\",\n    });\n  }\n}\n\nfunction entityKey(entity: MergePlanEntityRef): string {\n  return JSON.stringify([entity.kind, entity.id]);\n}\n\nexport const mergePlanArtifactV1InputSchema =\n  mergePlanArtifactV1InputBaseSchema.superRefine((artifact, ctx) =>\n    addSemanticIssues(artifact, ctx),\n  );\n\nexport const mergePlanArtifactV1Schema =\n  mergePlanArtifactV1BaseSchema.superRefine((artifact, ctx) =>\n    addSemanticIssues(artifact, ctx),\n  );\n","import { sortedReplacer } from \"../schema/canonical\";\nimport { sha256Hex } from \"../utils/hash\";\nimport {\n  MERGE_PLAN_DIGEST_ALGORITHM,\n  type MergePlanArtifactV1,\n  type MergePlanArtifactV1Input,\n} from \"./plan-schema\";\n\n/** Returns the recursively key-sorted JSON representation used for plan identity. */\nexport function canonicalMergePlanJson(\n  artifact: MergePlanArtifactV1 | MergePlanArtifactV1Input,\n): string {\n  const digestless = \"digest\" in artifact ? omitDigest(artifact) : artifact;\n  return JSON.stringify(digestless, sortedReplacer);\n}\n\n/** Computes the full 256-bit digest of every plan field except `digest` itself. */\nexport async function computeMergePlanDigest(\n  artifact: MergePlanArtifactV1 | MergePlanArtifactV1Input,\n): Promise<string> {\n  return sha256Hex(canonicalMergePlanJson(artifact), 32);\n}\n\n/** Adds the canonical digest to an otherwise complete V1 artifact. */\nexport async function finalizeMergePlanArtifact(\n  artifact: MergePlanArtifactV1Input,\n): Promise<MergePlanArtifactV1> {\n  const finalized: MergePlanArtifactV1 = {\n    ...artifact,\n    digest: {\n      algorithm: MERGE_PLAN_DIGEST_ALGORITHM,\n      value: await computeMergePlanDigest(artifact),\n    },\n  };\n  const canonical: unknown = JSON.parse(\n    JSON.stringify(finalized, sortedReplacer),\n  );\n  return canonical as MergePlanArtifactV1;\n}\n\nfunction omitDigest(artifact: MergePlanArtifactV1): MergePlanArtifactV1Input {\n  const { digest: _digest, ...digestless } = artifact;\n  return digestless;\n}\n","import type { z } from \"zod\";\n\nimport {\n  computeMergePlanDigest,\n  finalizeMergePlanArtifact,\n} from \"./plan-canonical\";\nimport {\n  MERGE_PLAN_FORMAT_VERSION,\n  type MergePlanArtifactV1,\n  type MergePlanArtifactV1Input,\n  mergePlanArtifactV1InputSchema,\n  mergePlanArtifactV1Schema,\n} from \"./plan-schema\";\n\ntype MergePlanParseFailure =\n  | Readonly<{ kind: \"unsupported-version\"; received: unknown }>\n  | Readonly<{ kind: \"malformed\"; issues: z.core.$ZodIssue[] }>;\n\nexport type MergePlanParseResult =\n  | Readonly<{ success: true; artifact: MergePlanArtifactV1 }>\n  | Readonly<{ success: false; error: MergePlanParseFailure }>;\n\nexport type MergePlanDigestResult =\n  | Readonly<{ valid: true }>\n  | Readonly<{ valid: false; expected: string; received: string }>;\n\nexport type MergePlanValidationResult =\n  | Readonly<{ success: true; artifact: MergePlanArtifactV1 }>\n  | Readonly<{\n      success: false;\n      error:\n        | MergePlanParseFailure\n        | Readonly<{\n            kind: \"digest-mismatch\";\n            expected: string;\n            received: string;\n          }>;\n    }>;\n\n/** Parses an untrusted value without conflating an unknown version with bad V1 data. */\nexport function parseMergePlanArtifact(input: unknown): MergePlanParseResult {\n  const version = readFormatVersion(input);\n  if (version !== MERGE_PLAN_FORMAT_VERSION) {\n    return {\n      success: false,\n      error: { kind: \"unsupported-version\", received: version },\n    };\n  }\n  const parsed = mergePlanArtifactV1Schema.safeParse(input);\n  if (!parsed.success) {\n    return {\n      success: false,\n      error: { kind: \"malformed\", issues: parsed.error.issues },\n    };\n  }\n  return {\n    success: true,\n    artifact: parsed.data as unknown as MergePlanArtifactV1,\n  };\n}\n\n/** Verifies the digest on a structurally valid artifact. */\nexport async function verifyMergePlanDigest(\n  artifact: MergePlanArtifactV1,\n): Promise<MergePlanDigestResult> {\n  const expected = await computeMergePlanDigest(artifact);\n  const received = artifact.digest.value;\n  return expected === received ?\n      { valid: true }\n    : { valid: false, expected, received };\n}\n\n/** Performs the complete pure wire-boundary validation used before target checks. */\nexport async function validateMergePlanArtifact(\n  input: unknown,\n): Promise<MergePlanValidationResult> {\n  const parsed = parseMergePlanArtifact(input);\n  if (!parsed.success) return parsed;\n  const digest = await verifyMergePlanDigest(parsed.artifact);\n  if (!digest.valid) {\n    return {\n      success: false,\n      error: {\n        kind: \"digest-mismatch\",\n        expected: digest.expected,\n        received: digest.received,\n      },\n    };\n  }\n  return parsed;\n}\n\n/** Constructs and hashes a V1 wire artifact. */\nexport async function constructMergePlanArtifact(\n  input: MergePlanArtifactV1Input,\n): Promise<MergePlanArtifactV1> {\n  const validatedInput = mergePlanArtifactV1InputSchema.parse(input);\n  return finalizeMergePlanArtifact(\n    validatedInput as unknown as MergePlanArtifactV1Input,\n  );\n}\n\nfunction readFormatVersion(input: unknown): unknown {\n  if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n    return undefined;\n  }\n  return Reflect.get(input, \"formatVersion\") as unknown;\n}\n\nexport type {\n  MergePlanArtifactV1,\n  MergePlanArtifactV1Input,\n} from \"./plan-schema\";\n","/**\n * Sidecar provenance graph — durable, queryable `{branch, sourceId}` → canonical\n * tagging for a merge (open-item #5: \"on-graph provenance persistence\").\n *\n * The merge's in-memory {@link import(\"./types\").ProvenanceIndex}\n * (`report.provenance.byBranch`) evaporates after the call. This module persists the\n * same contributions as TYPED nodes in a SIDECAR graph on the SAME backend as the\n * merge target — a separate graph (its own `graphId`-namespaced tables), so the\n * user's domain schema is untouched. It is a faithful prototype of a future\n * first-class TypeGraph `annotations` primitive (see `docs/design/annotations.md`).\n *\n * Persistence is POST-COMMIT and best-effort, by design: the merge's commit path is\n * unchanged and stays on the same public store/backend contracts. Provenance is derived and\n * re-runnable, and the node ids are DETERMINISTIC (a hash of `{targetGraphId, role,\n * canonicalKind, canonicalId, branchId, sourceId}`), so re-merging the same forks UPSERTS rather\n * than duplicating. Atomic-in-the-merge-transaction is a possible upgrade later\n * (TypeGraph's cross-store `withTransaction`), deliberately deferred for v1.\n *\n * OWNERSHIP OF THE SIDECAR GRAPH ID. {@link openProvenanceStore} is the only\n * gateway, and the OWNERSHIP MARKER — not the schema shape — is the boundary.\n * One invariant states the whole rule: no write of any kind ever lands on a graph\n * id this module has not ALREADY marked as its own, and an open that refuses\n * writes nothing at all.\n *\n * {@link inspectSidecarGraphId} decides what may be done with an id:\n *\n *   - a VALID live owner marker for this target: OWNED — open it, registering (or\n *     migrating) the sidecar schema if that write has not landed yet;\n *   - ANY other `ProvenanceOwner`-kind row — tombstoned, schema-invalid, claiming a\n *     different target, or stored under a different id: foreign occupancy, refused\n *     with `corrupt-ownership-marker`. A marker this module cannot verify is never\n *     overwritten or resurrected;\n *   - unregistered id: FREE, and claimable, ONLY when it carries no row in ANY\n *     per-graph table — nodes and edges, but equally recorded-time history, the\n *     revision clock and origins, identity assertions and their derived\n *     closure/separation, fulltext, and unique keys. A schema-less application\n *     graph (plain `createStore`, which registers no schema row) is still an\n *     application graph, so any pre-existing row refuses;\n *   - the CURRENT sidecar schema with NO marker: refused\n *     (`unowned-exact-schema-graph`) whatever its contents — empty and\n *     provenance-shaped included (see below);\n *   - pre-marker (legacy) schema: upgraded when every `Provenance` row verifies as\n *     one this module wrote for THIS target, refused otherwise;\n *   - anything else: refused with `GRAPH_MERGE_PROVENANCE_ID_COLLISION` and a\n *     remediation naming the state that was actually found.\n *\n * MARKER-FIRST ORDERING. Claiming the id is the FIRST write of an open, and it\n * happens BEFORE the sidecar schema is registered. That is possible because the\n * marker is a plain node row in the shared nodes table, which needs no per-graph\n * schema DDL — the same way a schema-less `createStore` graph writes rows. The\n * claim ({@link claimSidecarOwnership}) re-verifies the id and inserts the marker\n * as ONE fenced unit (`backend.schemaWriteTransaction`). What that fence is worth\n * differs by engine and by state, so be precise about it:\n *\n *   - SQLite: `BEGIN IMMEDIATE` owns the single writer slot, so it serializes the\n *     claim against EVERY other writer, whatever the id's state;\n *   - PostgreSQL: a per-graph `pg_advisory_xact_lock` plus `SELECT ... FOR UPDATE`\n *     on the graph's ACTIVE SCHEMA ROW. On the marker-first free-id path there is\n *     no such row yet, so the `FOR UPDATE` locks nothing and the advisory lock is\n *     the whole fence: it serializes this claim against other claims and against\n *     schema commits (which take the same lock), which is what makes two racing\n *     openers safe. The row lock earns its keep on the schema-BEARING states — the\n *     legacy upgrade, and any schema-managed Store write, which takes that row\n *     `FOR SHARE`. Writers that take NEITHER — raw, schema-less ones — are\n *     excluded by the claim's own relation lock (see below).\n *\n * So a competing writer of those classes either commits first — and this claim\n * then SEES its row and refuses, having written nothing — or waits until the claim\n * has committed, by which time the id is visibly owned and a later application\n * write makes that application the intruder in a marked graph rather than making\n * this module the colonizer of an application's graph. Only after the marker\n * commits does `createStoreWithSchema` register the schema.\n *\n * WHY AN UNMARKED CURRENT-SCHEMA ID IS NEVER ADOPTED. Contents cannot establish\n * ownership: an application may legitimately define these exact kinds at the\n * conventional sidecar id, and one that is empty (or holds rows that happen to\n * recompute) is indistinguishable from a sidecar of ours. Adopting it used to be\n * defended by the claim's fence, but the fence only orders the claim against\n * writers that contend for it — an application Store already open on that id keeps\n * writing afterwards, and once the marker exists no later open re-litigates\n * contents. Marker-first removes the question: the current schema without a marker\n * is a state this module cannot produce except by crashing between the marker\n * commit and the schema commit, which leaves the marker, not the schema. It is\n * therefore refused unconditionally, and — because 0.46 is unreleased — no\n * legitimate fleet state carries the current sidecar schema without a marker.\n *\n * RESUMABILITY. Creation is still two separately committed writes, but in the safe\n * order: the marker, then the schema. A crash between them leaves\n * marker-without-schema, and a valid live marker for this target IS the proof of\n * ownership, so that state resumes by registering the schema. The legacy upgrade\n * has the same window: the marker is claimed inside the fence that verified every\n * pre-marker row, and the migration to the current schema runs afterwards.\n *\n * NO RESIDUE. A refused open leaves the occupant byte-identical: no schema row, no\n * marker, no provenance row. The unfenced preflight is a read-only classification —\n * it decides whether a fence must be opened at all (an already-owned sidecar needs\n * no claim), never whether a write is allowed; every decision that admits a write\n * is re-taken inside the fence.\n *\n * THE UNFENCED-WRITER WINDOW, AND HOW IT IS CLOSED. One writer class takes\n * neither the advisory lock nor the schema row: a schema-LESS raw `createStore`\n * writer, or a direct `backend.insertNode`/`insertEdge` call. At PostgreSQL's read\n * committed its insert could commit between the claim's fenced re-inspection and\n * the claim's commit, and the claim would mark a graph id it saw empty and an\n * application saw as its own. That window is CLOSED, not accepted: the claim takes\n * `LOCK TABLE <nodes>, <edges> IN SHARE ROW EXCLUSIVE MODE` inside the fence and\n * before the re-inspection, which drains in-flight row writers and holds new ones\n * off until the marker commits. {@link drainUnfencedRowWriters} states the mode\n * choice, the deadlock analysis, and the cost — every node/edge write on the\n * database waits for the duration of a claim, which happens only when a sidecar is\n * created, upgraded, or resumed. SQLite needs no such lock: `BEGIN IMMEDIATE` owns\n * the single writer slot.\n *\n * What remains is narrower and is stated as a residual rather than closed: a\n * writer that inserts ONLY into a secondary per-graph relation — identity\n * assertions, the revision clock, recorded history — under this id, with no node\n * or edge row in the same transaction and no schema of its own. No TypeGraph write\n * path does that: those relations are written either atomically with the node or\n * edge row that produced them (drained by the table lock), or by a schema-managed\n * or identity-enabled store, which must first register a schema for this id\n * through the same per-graph advisory lock this claim holds. Reaching it means an\n * application writing TypeGraph's internal tables by hand. If it were reached, the\n * failure is a visible NAMESPACE COLLISION — an application's rows and this\n * module's marker under one graph id — not corruption: no row is overwritten, no\n * row is lost, and both sides read their own rows back unchanged. It is also the\n * accepted marker-boundary semantics one instant early: an application writing\n * into the sidecar AFTER the claim commits is already documented as \"the\n * application is the intruder in a marked graph\".\n *\n * The claim needs a transactional schema fence. A backend that exposes none is\n * refused with `GRAPH_MERGE_PROVENANCE_CLAIM_UNFENCED` rather than claiming the id\n * with a check-then-write that a concurrent writer can slip through. Opening an\n * ALREADY-owned sidecar needs no claim, so read-only use of an existing sidecar\n * stays available on such a backend.\n */\n\nimport { z } from \"zod\";\n\nimport { encodeTupleKey } from \"../utils/tuple-key\";\nimport { parseRowProps } from \"./canonical-props\";\nimport { compareStrings } from \"./node-key\";\nimport type {\n  GraphBackend,\n  GraphDef,\n  Node,\n  NodeRow,\n  Store,\n} from \"./typegraph-internal\";\nimport {\n  asCompiledRowsSql,\n  asCompiledStatementSql,\n  computeSchemaHash,\n  ConfigurationError,\n  createSqlSchema,\n  createStoreWithSchema,\n  defineInternalGraph,\n  defineNode,\n  requireFenceLockTables,\n  requireWriteFence,\n  resolveWriteFencePlan,\n  serializeSchema,\n  sha256Hex,\n  sql,\n  storeBackend,\n} from \"./typegraph-internal\";\nimport { asBranchId, type BranchId, type ProvenanceRecord } from \"./types\";\n\n/** The node kind holding one persisted contribution. */\nconst PROVENANCE_KIND = \"Provenance\";\n\n/** The node kind holding the durable ownership marker. */\nconst PROVENANCE_OWNER_KIND = \"ProvenanceOwner\";\n\n/** The Provenance node: one row per `{branch, sourceId}` → canonical contribution. */\nconst Provenance = defineNode(PROVENANCE_KIND, {\n  schema: z.object({\n    targetGraphId: z.string(),\n    role: z.enum([\"node\", \"edge\"]),\n    canonicalId: z.string(),\n    canonicalKind: z.string(),\n    branchId: z.string(),\n    sourceId: z.string(),\n  }),\n});\n\nconst PROVENANCE_OWNER = \"@nicia-ai/typegraph/merge-provenance\";\nconst PROVENANCE_OWNER_VERSION = 1;\nconst PROVENANCE_OWNER_ID = \"merge-provenance-owner\";\n\n/**\n * Durable ownership claim for the sidecar graph id.\n *\n * Schema equality cannot establish ownership: an application is allowed to\n * define the same `Provenance` kind at the conventional sidecar id. The marker\n * row is therefore required independently of the schema hash on every sidecar\n * created by this version.\n */\nconst ProvenanceOwner = defineNode(PROVENANCE_OWNER_KIND, {\n  schema: z.object({\n    owner: z.literal(PROVENANCE_OWNER),\n    version: z.literal(PROVENANCE_OWNER_VERSION),\n    targetGraphId: z.string(),\n  }),\n});\n\n/**\n * Derives the sidecar graph id for a target graph. Suffixing the target's own id\n * keeps each target graph's provenance in its own `graphId`-namespaced tables on a\n * shared backend, while a single `Provenance` schema serves all of them.\n */\nexport function provenanceGraphId(targetGraphId: string): string {\n  return `${targetGraphId}::merge-provenance`;\n}\n\n/** Builds the sidecar provenance graph definition for a target graph. */\nfunction buildOwnedProvenanceGraph(targetGraphId: string) {\n  return defineInternalGraph({\n    id: provenanceGraphId(targetGraphId),\n    nodes: {\n      Provenance: { type: Provenance },\n      ProvenanceOwner: { type: ProvenanceOwner },\n    },\n    edges: {},\n  });\n}\n\n/** The schema written by releases before durable sidecar ownership markers. */\nfunction buildProvenanceGraph(targetGraphId: string) {\n  return defineInternalGraph({\n    id: provenanceGraphId(targetGraphId),\n    nodes: { Provenance: { type: Provenance } },\n    edges: {},\n  });\n}\n\n/**\n * Public view of the sidecar graph. The ownership kind is deliberately hidden:\n * it is framework metadata, not provenance data or an application collection.\n */\nexport type ProvenanceGraph = ReturnType<typeof buildProvenanceGraph>;\n\n/** A persisted provenance node (the queryable record). */\nexport type ProvenanceNode = Node<typeof Provenance>;\n\n/**\n * Opens the provenance store for a target — OPENING OR CREATING, never merely\n * reading. On a free graph id this claims the ownership marker and registers the\n * sidecar schema; on an occupied one it throws. There is no read-only entry\n * point: a tool that wants to inspect an existing sidecar without creating one\n * must decide for itself (e.g. by checking `backend.getActiveSchema` for\n * {@link provenanceGraphId}) before calling this.\n *\n * Pass the target Store in ordinary application code; callers that do not have\n * its GraphDef may instead pass the backend and target graph id.\n *\n * Idempotent in the sense that matters for the persist/query path: repeated calls\n * converge on one sidecar and write no second marker. It shares the backend with\n * the target, so the caller must NOT close it separately — closing the shared\n * backend is the target owner's job.\n */\nexport function openProvenanceStore<G extends GraphDef>(\n  target: Store<G>,\n): Promise<Store<ProvenanceGraph>>;\n/**\n * Opens (or creates — see above) a provenance store without a target GraphDef,\n * for callers that hold only the backend and the target's graph id.\n */\nexport function openProvenanceStore(\n  backend: GraphBackend,\n  targetGraphId: string,\n): Promise<Store<ProvenanceGraph>>;\nexport async function openProvenanceStore<G extends GraphDef>(\n  ...args:\n    | readonly [target: Store<G>]\n    | readonly [backend: GraphBackend, targetGraphId: string]\n): Promise<Store<ProvenanceGraph>> {\n  const [backend, targetGraphId] =\n    args.length === 1 ? [storeBackend(args[0]), args[0].graphId] : args;\n  const graph = buildOwnedProvenanceGraph(targetGraphId);\n  // Preflight, unfenced and read-only: it decides whether a CLAIM is needed at\n  // all (an already-owned sidecar needs none, so read-only use stays available\n  // on a backend with no schema fence) and refuses early. It authorizes no\n  // write — the claim below re-takes the decision inside its fence.\n  const preflight = await inspectSidecarGraphId(backend, graph, targetGraphId);\n  if (preflight.state === \"refuse\") {\n    throw provenanceGraphIdCollision(graph.id, targetGraphId, preflight.reason);\n  }\n  if (preflight.state !== \"owned\") {\n    // Marker-first: the ownership row is this open's FIRST write, so a lost race\n    // refuses before anything — not even a schema-version row — has been written\n    // to the occupant.\n    const claim = await claimSidecarOwnership(backend, graph, targetGraphId);\n    if (claim.state === \"refuse\") {\n      throw provenanceGraphIdCollision(graph.id, targetGraphId, claim.reason);\n    }\n  }\n  // Reached only once the marker owns the id: registering the sidecar schema (or\n  // migrating a pre-marker one) now writes into a graph this module has claimed.\n  const [store] = await createStoreWithSchema(graph, backend);\n  return store as unknown as Store<ProvenanceGraph>;\n}\n\n/**\n * Re-verifies the sidecar id and writes the ownership marker as ONE fenced unit,\n * so no writer can occupy the id between the two — and, being the open's first\n * write, so a claim that loses the race leaves the occupant untouched.\n *\n * `backend.schemaWriteTransaction` is the fence: the same per-graph lock a schema\n * commit holds (SQLite `BEGIN IMMEDIATE`; PostgreSQL `pg_advisory_xact_lock` plus\n * `SELECT ... FOR UPDATE` on the graph's active schema row, which every\n * schema-managed Store write takes `FOR SHARE`). It BLOCKS a competing writer\n * rather than aborting on a serialization failure, so no retry loop is needed.\n *\n * The marker is written with the backend's `insertNode` primitive rather than\n * `store.nodes.ProvenanceOwner.upsertById`: a Store write opens its own\n * transaction and cannot join this one. An INSERT is also the only write this\n * claim is ever allowed to make — the marker is claimed only when the id holds no\n * `ProvenanceOwner` row at all, so an unverifiable marker can never be overwritten\n * or resurrected. `ProvenanceOwner` declares no unique field, embedding, or\n * fulltext projection, so the row a Store write would produce is this row — and,\n * being a plain row in the shared nodes table, it needs no registered schema for\n * the graph id, which is what lets the claim run BEFORE the schema commit.\n */\nasync function claimSidecarOwnership(\n  backend: GraphBackend,\n  graph: ReturnType<typeof buildOwnedProvenanceGraph>,\n  targetGraphId: string,\n): Promise<SidecarDisposition> {\n  const fence = backend.schemaWriteTransaction;\n  if (fence === undefined) {\n    throw provenanceClaimUnfenced(graph.id, targetGraphId);\n  }\n  return fence(graph.id, async (tx) => {\n    // Before the re-inspection, not after it: the drain is only worth anything\n    // if no row can land between the read it authorizes and this transaction's\n    // commit.\n    await drainUnfencedRowWriters(tx);\n    const verdict = await inspectSidecarGraphId(tx, graph, targetGraphId);\n    // `owned`: a concurrent opener claimed the id first. Nothing to write, and\n    // its marker is the same durable claim this one would have made.\n    if (verdict.state === \"refuse\" || verdict.state === \"owned\") return verdict;\n    await tx.insertNode({\n      graphId: graph.id,\n      kind: PROVENANCE_OWNER_KIND,\n      id: PROVENANCE_OWNER_ID,\n      props: {\n        owner: PROVENANCE_OWNER,\n        version: PROVENANCE_OWNER_VERSION,\n        targetGraphId,\n      },\n    });\n    return verdict;\n  });\n}\n\n/**\n * The claim's own port: the fenced transaction, plus the two members the drain\n * needs beyond the inspection reads.\n */\ntype SidecarClaimPort = SidecarInspectionPort &\n  Readonly<{\n    capabilities: GraphBackend[\"capabilities\"];\n    dialect: GraphBackend[\"dialect\"];\n    executeStatement: NonNullable<GraphBackend[\"executeStatement\"]>;\n  }>;\n\n/**\n * Drains — and holds off — the writers the per-graph fence cannot reach, so the\n * claim's re-inspection reads a state no one can change until it commits.\n *\n * The fence excludes every writer that takes the per-graph advisory lock (other\n * claims, schema commits) or the active schema row (`FOR SHARE` on every\n * schema-managed Store write). One class takes neither: a schema-LESS raw\n * `createStore` writer, or a direct `backend.insertNode`/`insertEdge` call. At\n * PostgreSQL's read committed its INSERT can commit between the re-inspection's\n * statement snapshot and this transaction's commit, and the claim would then\n * mark a graph id it saw empty and an application saw as its own.\n *\n * A relation lock is the expressible exclusion for \"no row may appear\", and this\n * module takes it — the same advisory-then-relation ordering the contribution\n * teardown uses, and the same reasoning as the identity enablement snapshot's\n * `LOCK TABLE ... IN SHARE MODE`: a verdict computed from the absence of rows is\n * only sound if nothing can add one while it is acted on.\n *\n * `SHARE ROW EXCLUSIVE` is the minimal mode that works here, and the mode choice\n * is load-bearing:\n *\n *   - it conflicts with `ROW EXCLUSIVE`, so it excludes every INSERT/UPDATE/DELETE\n *     on these two tables (for EVERY graph — the tables are shared);\n *   - it is SELF-exclusive, which plain `SHARE` is not. `SHARE` would let two\n *     concurrent claims (different sidecar ids, different advisory locks) both\n *     acquire it and then both request `ROW EXCLUSIVE` for their own marker\n *     INSERT — each blocked by the other's `SHARE`. That is a textbook\n *     lock-upgrade deadlock, and PostgreSQL would resolve it by aborting one\n *     claim. Under this mode the second claim waits at the lock, holding nothing\n *     the first needs;\n *   - it still admits readers (`ACCESS SHARE`) and row-level lockers\n *     (`ROW SHARE`), which `EXCLUSIVE` would block for no benefit here.\n *\n * COST, stated plainly, because it is real: while this transaction runs, every\n * node and edge write on the whole database waits. The bound is what makes it\n * acceptable — the lock is taken ONLY inside the claim, so only when a sidecar is\n * created, upgraded from the pre-marker schema, or resumed after a crash; never\n * on the common path, where an already-owned sidecar opens without a fence at\n * all. Its duration is the re-inspection's probes plus one INSERT, with no user\n * code and no I/O of the caller's inside it.\n *\n * DEADLOCK ANALYSIS, by writer class — the wait graph stays acyclic in each:\n *\n *   - a raw, schema-less writer takes `ROW EXCLUSIVE` here and nothing else, so\n *     the wait is one-directional (this claim waits for it; it never waits for\n *     anything this claim holds);\n *   - a schema-MANAGED writer also takes the graph's active schema row\n *     `FOR SHARE`, which this fence holds `FOR UPDATE` — but it takes that row\n *     lock FIRST, as the opening statement of its write transaction\n *     (`lockSchemaVersionForStoreWrite`, run before any row write precisely so a\n *     rolled-back savepoint cannot drop the fence). It therefore can never be\n *     holding `ROW EXCLUSIVE` on these tables while waiting on the schema row,\n *     which is the only shape that would close a cycle;\n *   - a fence holder for ANOTHER graph id can hold `ROW EXCLUSIVE` here while\n *     this claim waits, but it never requests another graph's advisory lock;\n *   - another CLAIM is excluded by this mode's self-exclusivity before it holds\n *     anything (see above), which is the case a plain `SHARE` would deadlock.\n *\n * SQLITE takes no lock: `BEGIN IMMEDIATE` — which every fence transaction here is\n * opened with — already owns the engine's single writer slot, so the drain is\n * complete before the callback runs. Unlike the identity path, this fence is\n * always one TypeGraph opened itself, never one adopted from a caller's\n * `DEFERRED` transaction, so that premise holds unconditionally.\n *\n * Resolves a {@link resolveWriteFencePlan}: the `lock` arm takes the relation\n * lock below (needs `drain: \"table-lock\"`), and the `engine-serialized` arm\n * is the SQLite writer-slot case this doc already describes.\n */\nasync function drainUnfencedRowWriters(tx: SidecarClaimPort): Promise<void> {\n  const plan = resolveWriteFencePlan(tx);\n  const fence = requireWriteFence(\n    plan,\n    \"graph-merge provenance fence\",\n    \"drain\",\n  );\n  switch (fence.kind) {\n    case \"lock\":\n    case \"row\": {\n      if (fence.drain !== \"table-lock\") {\n        // `drain: \"quiescent\"`: the declaration already excludes concurrent\n        // writers by some other means, so this site takes no statement.\n        return;\n      }\n      // Built fresh from `tx.tableNames` — always the live-relation schema,\n      // never a recorded-read view — so `schema.tables.nodes/.edges` (the\n      // physical names `lockTables` needs) name the same relations\n      // `schema.nodesTable/.edgesTable` would.\n      const schema = createSqlSchema(tx.tableNames);\n      await tx.executeStatement(\n        asCompiledStatementSql(\n          requireFenceLockTables(fence, \"drainUnfencedRowWriters\")(\n            [schema.tables.nodes, schema.tables.edges],\n            \"share-row-exclusive\",\n          ),\n        ),\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\n/**\n * The distinguishable states a refusal can name. Callers branch on the stable\n * `GRAPH_MERGE_PROVENANCE_ID_COLLISION` code; the reason (and the remediation\n * derived from it) says WHICH occupant was found, because \"rename the colliding\n * application graph\" is wrong advice for a sidecar this module itself wrote.\n */\ntype SidecarRefusalReason =\n  | \"application-graph\"\n  | \"corrupt-ownership-marker\"\n  | \"empty-legacy-sidecar\"\n  | \"unupgradeable-legacy-sidecar\"\n  | \"unowned-exact-schema-graph\";\n\n/**\n * What {@link openProvenanceStore} may do with the sidecar graph id. `create`\n * (a completely free id) and `upgrade` (a pre-marker sidecar whose every row\n * verifies) are the two states a claim may write the marker in; `owned` needs no\n * claim, and `refuse` permits no write at all.\n */\ntype SidecarDisposition =\n  | Readonly<{ state: \"create\" }>\n  | Readonly<{ state: \"owned\" }>\n  | Readonly<{ state: \"upgrade\" }>\n  | Readonly<{ state: \"refuse\"; reason: SidecarRefusalReason }>;\n\n/** Rows this module could have written, keyed by what they mean for ownership. */\ntype SidecarContents =\n  \"empty\" | \"provenance\" | \"unrecognized-provenance\" | \"foreign-rows\";\n\n/**\n * The reads every sidecar probe needs, and nothing else. Satisfied by both a\n * top-level {@link GraphBackend} and a transaction-scoped backend, so the SAME\n * inspection runs as the unfenced preflight and again inside the claim's fence —\n * two callers of one decision rather than two decisions that can disagree.\n *\n * `tableExists` is the one member only the fenced port has, and it exists so the\n * two callers can run that one decision the same way: a secondary relation a\n * database has never materialized must be skipped, and inside a PostgreSQL\n * transaction a failed statement aborts the whole transaction, so the fenced\n * caller cannot learn that by attempting the read. See\n * {@link hasRowsInSecondaryTable}.\n */\ntype SidecarInspectionPort = Readonly<\n  Pick<\n    GraphBackend,\n    \"getActiveSchema\" | \"findNodesByKind\" | \"execute\" | \"tableNames\"\n  > &\n    Readonly<{\n      tableExists?: (tableName: string) => Promise<boolean>;\n    }>\n>;\n\n/**\n * Decides — WITHOUT writing anything — whether the sidecar graph id is this\n * module's to open. The module doc states the rule this implements.\n */\nasync function inspectSidecarGraphId(\n  port: SidecarInspectionPort,\n  graph: ReturnType<typeof buildOwnedProvenanceGraph>,\n  targetGraphId: string,\n): Promise<SidecarDisposition> {\n  const activeSchema = await port.getActiveSchema(graph.id);\n  // An unregistered graph id is NOT evidence of a free namespace: a store booted\n  // with plain `createStore` writes rows and registers no schema row. Only an id\n  // with no schema row AND no durable row of any kind is free.\n  if (\n    activeSchema === undefined &&\n    !(await hasRowsUnderGraphId(port, graph.id, \"any\"))\n  ) {\n    return { state: \"create\" };\n  }\n\n  // The id holds something. The ownership marker is the only evidence that can\n  // say it is OURS, and it is consulted the same way on every schema state.\n  const marker = await inspectOwnerMarker(port, graph.id, targetGraphId);\n  if (marker === \"foreign\") {\n    return { state: \"refuse\", reason: \"corrupt-ownership-marker\" };\n  }\n  if (marker === \"ours\") {\n    // A verified marker is the durable claim; the contents are not re-litigated.\n    // Rows an application later wrote INTO our sidecar do not revoke ownership,\n    // and refusing over them would brick a working sidecar.\n    return { state: \"owned\" };\n  }\n\n  if (activeSchema === undefined) {\n    return { state: \"refuse\", reason: \"application-graph\" };\n  }\n\n  const ownedHash = await computeSchemaHash(\n    serializeSchema(graph, activeSchema.version),\n  );\n  if (activeSchema.schema_hash === ownedHash) {\n    // The current sidecar schema with no marker. This module writes the marker\n    // FIRST, so it cannot have produced this state: whatever registered the\n    // schema, it was not an interrupted creation of ours. Contents are not\n    // consulted — empty or provenance-shaped, they are not evidence of\n    // authorship, and adopting on them is exactly how an application graph gets\n    // colonized.\n    return { state: \"refuse\", reason: \"unowned-exact-schema-graph\" };\n  }\n\n  const legacyHash = await computeSchemaHash(\n    serializeSchema(buildProvenanceGraph(targetGraphId), activeSchema.version),\n  );\n  if (activeSchema.schema_hash !== legacyHash) {\n    return { state: \"refuse\", reason: \"application-graph\" };\n  }\n  return LEGACY_SCHEMA_DISPOSITION[\n    await inspectSidecarContents(port, graph.id, targetGraphId)\n  ];\n}\n\n/**\n * Contents → disposition for a graph id carrying the PRE-MARKER (legacy) schema —\n * the ONE state whose contents may establish ownership, because a pre-marker\n * release could not have written a marker beside them. `empty` still refuses: an\n * empty legacy sidecar carries no evidence at all that this module wrote it, so\n * it cannot be told apart from an application graph of the same shape.\n */\nconst LEGACY_SCHEMA_DISPOSITION: Readonly<\n  Record<SidecarContents, SidecarDisposition>\n> = {\n  provenance: { state: \"upgrade\" },\n  empty: { state: \"refuse\", reason: \"empty-legacy-sidecar\" },\n  \"unrecognized-provenance\": {\n    state: \"refuse\",\n    reason: \"unupgradeable-legacy-sidecar\",\n  },\n  \"foreign-rows\": { state: \"refuse\", reason: \"application-graph\" },\n};\n\n/** The refusal message and remediation for each distinguishable state. */\nconst SIDECAR_REFUSALS: Readonly<\n  Record<\n    SidecarRefusalReason,\n    Readonly<{\n      describe: (graphId: string, targetGraphId: string) => string;\n      suggestion: (graphId: string) => string;\n    }>\n  >\n> = {\n  \"application-graph\": {\n    describe: (graphId) =>\n      `Graph id \"${graphId}\" is already used by an application graph and cannot host merge provenance.`,\n    suggestion: () =>\n      \"Rename the colliding application graph before enabling persisted merge provenance for this target.\",\n  },\n  \"corrupt-ownership-marker\": {\n    describe: (graphId, targetGraphId) =>\n      `Graph id \"${graphId}\" holds a \"${PROVENANCE_OWNER_KIND}\" row that is not a valid ownership claim for target \"${targetGraphId}\" — it is soft-deleted, does not validate against the marker schema, names a different target, or sits under a different row id.`,\n    suggestion: (graphId) =>\n      `Do not re-run: an unverifiable marker is never overwritten or resurrected, because it may be an application's row. Inspect the \"${PROVENANCE_OWNER_KIND}\" rows under graph id \"${graphId}\" and hard-delete the invalid one, or drop that graph id entirely — persisted provenance is derived, so re-running the merge rebuilds it.`,\n  },\n  \"empty-legacy-sidecar\": {\n    describe: (graphId) =>\n      `Graph id \"${graphId}\" holds an EMPTY provenance sidecar from a release that wrote no ownership marker, which cannot be told apart from an application graph of the same shape.`,\n    suggestion: (graphId) =>\n      `Drop graph id \"${graphId}\" — it holds no provenance records, so nothing is lost — and re-run the merge to create an owned sidecar.`,\n  },\n  \"unupgradeable-legacy-sidecar\": {\n    describe: (graphId, targetGraphId) =>\n      `Graph id \"${graphId}\" holds a pre-marker provenance sidecar whose rows do not verify as provenance for target \"${targetGraphId}\", so it cannot be upgraded to an owned sidecar.`,\n    suggestion: (graphId) =>\n      `Export anything you still need from graph id \"${graphId}\", then drop it: provenance is derived, and re-running the merge rebuilds an owned sidecar.`,\n  },\n  \"unowned-exact-schema-graph\": {\n    describe: (graphId) =>\n      `Graph id \"${graphId}\" carries the merge-provenance schema but no ownership marker, so this library did not create it.`,\n    suggestion: (graphId) =>\n      `Drop graph id \"${graphId}\" (or rename the graph that occupies it) and re-run the merge: a sidecar this library owns writes its \"${PROVENANCE_OWNER}\" marker row BEFORE the schema, so a marker-less one carrying this schema was written either by an application — which is never adopted — or by a crash of an unreleased build between those two writes. Persisted provenance is derived, so re-running the merge rebuilds it.`,\n  },\n};\n\nfunction provenanceGraphIdCollision(\n  graphId: string,\n  targetGraphId: string,\n  reason: SidecarRefusalReason,\n): ConfigurationError {\n  const refusal = SIDECAR_REFUSALS[reason];\n  return new ConfigurationError(\n    refusal.describe(graphId, targetGraphId),\n    {\n      code: \"GRAPH_MERGE_PROVENANCE_ID_COLLISION\",\n      reason,\n      graphId,\n      targetGraphId,\n    },\n    { suggestion: refusal.suggestion(graphId) },\n  );\n}\n\n/**\n * Refused when the ownership claim cannot be made atomic. Not a collision: the\n * id may well be free — the backend simply cannot hold the contents check and\n * the marker write together, and a check-then-write a concurrent application\n * writer can slip through is not an ownership claim.\n */\nfunction provenanceClaimUnfenced(\n  graphId: string,\n  targetGraphId: string,\n): ConfigurationError {\n  return new ConfigurationError(\n    `Claiming graph id \"${graphId}\" for merge provenance requires a transactional schema fence, which this backend does not provide.`,\n    {\n      code: \"GRAPH_MERGE_PROVENANCE_CLAIM_UNFENCED\",\n      graphId,\n      targetGraphId,\n    },\n    {\n      suggestion:\n        \"Use a backend that implements schemaWriteTransaction (both bundled Drizzle backends do when transactions are enabled); without it the sidecar's emptiness check and its ownership write cannot be committed as one unit. An ALREADY-owned sidecar opens without a claim.\",\n    },\n  );\n}\n\n/**\n * THE ownership predicate: whether one `ProvenanceOwner`-kind row is the marker\n * this module wrote for THIS target. Every consumer of \"is the marker ours?\" calls\n * this one function, so the marker probe and the foreign-occupancy classification\n * cannot drift into disagreeing.\n *\n * Exactly one row state qualifies: live (never soft-deleted), stored under the\n * canonical marker id, and validating against {@link ProvenanceOwner} — whose\n * `owner` and `version` are `z.literal`s, so the parse itself pins them — for this\n * target graph id. Every other `ProvenanceOwner`-kind row is FOREIGN, including a\n * tombstone: resurrecting one would overwrite a row this module cannot prove it\n * wrote.\n */\nfunction isOwnedMarkerRow(row: NodeRow, targetGraphId: string): boolean {\n  if (row.id !== PROVENANCE_OWNER_ID) return false;\n  if (row.deleted_at !== undefined) return false;\n  const parsed = ProvenanceOwner.schema.safeParse(parseRowProps(row.props));\n  return parsed.success && parsed.data.targetGraphId === targetGraphId;\n}\n\n/**\n * What the graph id's `ProvenanceOwner`-kind rows say about ownership.\n *\n * `absent` means there is NO such row at all — the only state in which the marker\n * may be claimed. `foreign` means at least one row exists that\n * {@link isOwnedMarkerRow} rejects, which is occupancy by something this module\n * did not write and must not modify.\n */\ntype OwnerMarkerState = \"ours\" | \"absent\" | \"foreign\";\n\nasync function inspectOwnerMarker(\n  port: SidecarInspectionPort,\n  graphId: string,\n  targetGraphId: string,\n): Promise<OwnerMarkerState> {\n  let ours = false;\n  for await (const row of readRowsOfKind(\n    port,\n    graphId,\n    PROVENANCE_OWNER_KIND,\n  )) {\n    if (!isOwnedMarkerRow(row, targetGraphId)) return \"foreign\";\n    ours = true;\n  }\n  return ours ? \"ours\" : \"absent\";\n}\n\n/** Rows read per page while classifying a graph id's durable contents. */\nconst SIDECAR_PAGE_SIZE = 500;\n\n/**\n * Every durable row of `kind` under `graphId`, tombstones included. Soft-deleted\n * and out-of-window rows MUST be visible: a row this module cannot account for is\n * occupancy whether or not it is currently live.\n */\nasync function* readRowsOfKind(\n  port: SidecarInspectionPort,\n  graphId: string,\n  kind: string,\n): AsyncGenerator<NodeRow> {\n  let after: string | undefined;\n  for (;;) {\n    const rows = await port.findNodesByKind({\n      graphId,\n      kind,\n      temporalMode: \"includeTombstones\",\n      excludeDeleted: false,\n      orderBy: \"id\",\n      ...(after === undefined ? {} : { after }),\n      limit: SIDECAR_PAGE_SIZE,\n    });\n    for (const row of rows) {\n      yield row;\n    }\n    if (rows.length < SIDECAR_PAGE_SIZE) return;\n    after = rows.at(-1)?.id;\n    if (after === undefined) return;\n  }\n}\n\n/** One probe row: the SELECT projects a constant, so only its presence matters. */\ntype SidecarProbeRow = Readonly<{ present: number }>;\n\n/**\n * Cheapest existence probe a backend offers for \"does this graph id hold rows?\":\n * one `LIMIT 1` lookup per per-graph row table, on the same `graph_id` prefix\n * every read path uses, short-circuiting at the first hit. Tombstoned rows COUNT\n * — a soft-deleted application row still means the id belongs to that\n * application.\n *\n * EVERY per-graph table is probed, not just nodes and edges. A graph id whose\n * only durable rows are recorded-time history, a revision clock or origin,\n * identity assertions and their derived closure/separation, fulltext, or unique\n * keys is an id an application has used — claiming it because the two entity\n * tables happen to be empty is the same colonization refusing a stray node row\n * exists to prevent.\n *\n * `scope: \"foreign\"` narrows only the NODE table, to rows this module could not\n * have written: node rows of any other kind. Every other table is occupancy in\n * both scopes — a sidecar declares no edges, tracks no revisions, asserts no\n * identities, and projects no fulltext or unique keys, so a row in any of them\n * is not ours whatever the schema says. `ProvenanceOwner` rows are NOT excused\n * either: the marker probe has already classified every one of them, so a row\n * this raw probe can see and `findNodesByKind` cannot is unaccounted-for\n * occupancy and must refuse. It cannot be expressed through `findNodesByKind`,\n * which needs the kinds of a graph whose schema — by construction, in the case\n * that matters — was never registered.\n *\n * The reachable set is exactly the tables the backend names through its\n * `tableNames` port. The schema-version table and the materialization-marker\n * tables are NOT addressable through it, so they are not probed; the active\n * schema row is covered by `getActiveSchema` in {@link inspectSidecarGraphId}.\n */\nasync function hasRowsUnderGraphId(\n  port: SidecarInspectionPort,\n  graphId: string,\n  scope: \"any\" | \"foreign\",\n): Promise<boolean> {\n  const schema = createSqlSchema(port.tableNames);\n  const kindFilter =\n    scope === \"any\" ? sql.empty() : sql` AND kind <> ${PROVENANCE_KIND}`;\n  // The entity tables first: every backend has them, so a failure here is a real\n  // failure and propagates, and they are where an occupant is likeliest to be.\n  if (await hasRowsInTable(port, schema.tables.nodes, graphId, kindFilter)) {\n    return true;\n  }\n  if (await hasRowsInTable(port, schema.tables.edges, graphId, sql.empty())) {\n    return true;\n  }\n  for (const tableName of secondaryRowTableNames(schema.tables)) {\n    if (await hasRowsInSecondaryTable(port, tableName, graphId)) return true;\n  }\n  return false;\n}\n\n/**\n * The per-graph row tables beyond nodes and edges, deduplicated because a\n * backend may map two logical relations onto one physical name.\n *\n * This list is the probe's completeness claim: it is every member of the\n * backend's resolved table names that carries a `graph_id` column.\n */\nfunction secondaryRowTableNames(\n  tables: ReturnType<typeof createSqlSchema>[\"tables\"],\n): readonly string[] {\n  return [\n    ...new Set([\n      tables.recordedNodes,\n      tables.recordedEdges,\n      tables.recordedClock,\n      tables.revisionOrigins,\n      tables.identityAssertions,\n      tables.recordedIdentityAssertions,\n      tables.identityClosure,\n      tables.identitySeparation,\n      tables.fulltext,\n      tables.uniques,\n      tables.edgeClaims,\n    ]),\n  ];\n}\n\n/** One `LIMIT 1` existence lookup for one graph id in one table. */\nasync function hasRowsInTable(\n  port: SidecarInspectionPort,\n  tableName: string,\n  graphId: string,\n  filter: ReturnType<typeof sql.empty>,\n): Promise<boolean> {\n  const rows = await port.execute<SidecarProbeRow>(\n    asCompiledRowsSql(\n      sql`SELECT 1 AS present FROM ${sql.identifier(tableName)} WHERE graph_id = ${graphId}${filter} LIMIT 1`,\n    ),\n  );\n  return rows.length > 0;\n}\n\n/**\n * The same lookup for a relation the database may never have materialized —\n * identity storage, for instance, is created when identity is first enabled, so\n * a database from an earlier release can be missing it entirely.\n *\n * A missing table holds no rows for ANY graph id, so skipping it is exact rather\n * than lenient. Proving it is missing is where the two ports differ: the fenced\n * caller MUST ask the catalog first, because on PostgreSQL a failed statement\n * aborts the enclosing transaction and would take the claim's marker write down\n * with it; the unfenced preflight runs each probe as its own statement, so it can\n * simply let the failure answer the question. Only this narrow \"does the relation\n * exist\" question is answered that way — the entity-table probes above are strict,\n * and they run first, so a broken connection or an unreadable database fails there\n * instead of being mistaken for a free id.\n */\nasync function hasRowsInSecondaryTable(\n  port: SidecarInspectionPort,\n  tableName: string,\n  graphId: string,\n): Promise<boolean> {\n  const tableExists = port.tableExists;\n  if (tableExists !== undefined) {\n    return (\n      (await tableExists(tableName)) &&\n      (await hasRowsInTable(port, tableName, graphId, sql.empty()))\n    );\n  }\n  try {\n    return await hasRowsInTable(port, tableName, graphId, sql.empty());\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Classifies a sidecar-shaped graph id by its actual durable contents.\n *\n * `provenance` is claimed only when every row is a live, valid contribution for\n * THIS target stored under its recomputed deterministic id, and the id holds no\n * other row. It is the sole admission path that reasons from CONTENTS rather than\n * from the marker, and it exists only for pre-marker sidecars, whose release could\n * not have written a marker beside them.\n */\nasync function inspectSidecarContents(\n  port: SidecarInspectionPort,\n  graphId: string,\n  targetGraphId: string,\n): Promise<SidecarContents> {\n  if (await hasRowsUnderGraphId(port, graphId, \"foreign\")) {\n    return \"foreign-rows\";\n  }\n\n  let rowCount = 0;\n  for await (const row of readRowsOfKind(port, graphId, PROVENANCE_KIND)) {\n    if (!(await isOwnedProvenanceRow(row, targetGraphId))) {\n      return \"unrecognized-provenance\";\n    }\n    rowCount += 1;\n  }\n  return rowCount > 0 ? \"provenance\" : \"empty\";\n}\n\n/**\n * Whether one `Provenance` row is a contribution this module wrote for THIS\n * target: live, valid against the schema, and stored under the deterministic id\n * its own props hash to. The recomputed id is what makes this a proof of\n * authorship rather than a shape check — an application row with plausible props\n * under an id of its own choosing fails it.\n */\nasync function isOwnedProvenanceRow(\n  row: NodeRow,\n  targetGraphId: string,\n): Promise<boolean> {\n  if (row.deleted_at !== undefined) return false;\n  const parsed = Provenance.schema.safeParse(parseRowProps(row.props));\n  if (!parsed.success || parsed.data.targetGraphId !== targetGraphId) {\n    return false;\n  }\n  const expectedId = await provenanceNodeId(targetGraphId, {\n    role: parsed.data.role,\n    canonicalId: parsed.data.canonicalId,\n    canonicalKind: parsed.data.canonicalKind,\n    branchId: asBranchId(parsed.data.branchId),\n    sourceId: parsed.data.sourceId,\n  });\n  return row.id === expectedId;\n}\n\n/** Separator used by provenance ids written before tuple escaping was added. */\nconst ID_SEPARATOR = \"\\0\";\n\n/** Bytes of the SHA-256 digest kept (128 bits — collision-safe for provenance). */\nconst ID_DIGEST_BYTES = 16;\n\n/**\n * The tuple that IDENTIFIES a contribution: everything {@link provenanceNodeId}\n * hashes except the target graph id, which is fixed for one merge. Two records\n * agreeing on it are one sidecar row by definition, so a caller that collapses on\n * this key collapses exactly what the row identity would have collapsed —\n * `canonicalKind` is part of it because two same-id canonicals of different kinds\n * are different entities under the `(kind, id)` identity model.\n */\nexport function contributionKey(record: ProvenanceRecord): string {\n  return encodeProvenanceTuple([\n    record.role,\n    record.canonicalKind,\n    record.canonicalId,\n    record.branchId,\n    record.sourceId,\n  ]);\n}\n\n/**\n * Preserves existing provenance ids for ordinary values while making the full\n * string domain injective. JSON tuple output never contains a literal NUL, so\n * it cannot collide with the legacy form, which has one between every field.\n */\nfunction encodeProvenanceTuple(values: readonly string[]): string {\n  return values.some((value) => value.includes(ID_SEPARATOR)) ?\n      encodeTupleKey(values)\n    : values.join(ID_SEPARATOR);\n}\n\n/**\n * Deterministic provenance node id: a hash of the contribution tuple, so\n * re-persisting the same contribution UPSERTS the same row (idempotent re-runs).\n *\n * Uses the shared {@link sha256Hex} (Web Crypto) instead of `node:crypto` so the\n * `graph-merge` entry point stays importable on every runtime the library\n * targets (Cloudflare Workers, Deno, browsers) — `base-version.ts` already hashes\n * its content fingerprint the same way.\n */\nexport async function provenanceNodeId(\n  targetGraphId: string,\n  record: ProvenanceRecord,\n): Promise<string> {\n  const tuple = encodeProvenanceTuple([\n    targetGraphId,\n    record.role,\n    record.canonicalKind,\n    record.canonicalId,\n    record.branchId,\n    record.sourceId,\n  ]);\n  const digest = await sha256Hex(tuple, ID_DIGEST_BYTES);\n  return `prov_${digest}`;\n}\n\n/**\n * Upserts one `Provenance` node per record into the sidecar store, keyed by the\n * deterministic id (re-running the same merge is a no-op upsert, never a\n * duplicate). Returns the row count written. The caller wraps this for best-effort\n * behavior — a failure here must not fail an already-committed merge.\n *\n * Records that hash to the SAME id are collapsed before the batch: the id is the\n * contribution's identity, so they are one row by definition — and a single\n * `bulkUpsertById` batch cannot create the same id twice. Collapsing here is what\n * makes the returned number the rows actually written for ANY caller, whatever\n * shape its record list arrived in.\n */\nexport async function persistProvenanceRecords(\n  store: Store<ProvenanceGraph>,\n  targetGraphId: string,\n  records: readonly ProvenanceRecord[],\n): Promise<number> {\n  if (records.length === 0) {\n    return 0;\n  }\n  const identified = await Promise.all(\n    records.map(async (record) => ({\n      id: await provenanceNodeId(targetGraphId, record),\n      props: {\n        targetGraphId,\n        role: record.role,\n        canonicalId: record.canonicalId,\n        canonicalKind: record.canonicalKind,\n        branchId: record.branchId,\n        sourceId: record.sourceId,\n      },\n    })),\n  );\n  const itemsById = new Map<string, (typeof identified)[number]>();\n  for (const item of identified) {\n    itemsById.set(item.id, item);\n  }\n  const items = [...itemsById.values()];\n  await store.nodes.Provenance.bulkUpsertById(items);\n  return items.length;\n}\n\n/** Filter for {@link readProvenance}. Each field, when set, narrows the result. */\nexport type ProvenanceQuery = Readonly<{\n  branchId?: BranchId | string;\n  canonicalId?: string;\n  role?: \"node\" | \"edge\";\n}>;\n\n/**\n * Reads persisted provenance back, filtered and stably ordered. The sidecar is a\n * normal typed graph, so this is a thin ergonomic wrapper over\n * `store.nodes.Provenance.find()` (filtered in memory — provenance volumes are\n * modest; a query-builder `where` is the scale path). Answers \"which canonical\n * entities did branch X contribute to?\" and \"who contributed canonical Y?\".\n */\nexport async function readProvenance(\n  store: Store<ProvenanceGraph>,\n  query: ProvenanceQuery = {},\n): Promise<readonly ProvenanceNode[]> {\n  const all = await store.nodes.Provenance.find();\n  return all\n    .filter(\n      (node) =>\n        (query.branchId === undefined || node.branchId === query.branchId) &&\n        (query.canonicalId === undefined ||\n          node.canonicalId === query.canonicalId) &&\n        (query.role === undefined || node.role === query.role),\n    )\n    .sort((left, right) => compareStrings(left.id, right.id));\n}\n","import { createDataKeyedBag } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\n/**\n * Candidate SOURCES (design §4 / §6.1) — the RECALL layer of candidate generation.\n *\n * Candidate generation is three layers — sources → scoring → reconciler (§4). This\n * module is the FIRST layer: each source PROPOSES candidates and decides nothing\n * about a fuzzy match. A source emits three things:\n *\n *   - `pairs`       — unscored `(a, b)` node pairs handed to the shared scoring\n *                     stage (`scoring.ts`), which makes every fuzzy match decision.\n *   - `forcedEdges` — DEFINITIONAL matches (a shared unique value) that bypass\n *                     scoring at {@link FORCED_MATCH_SCORE}.\n *   - `baseMembers` — committed base nodes the source pulled into scope, so the\n *                     reconciler can seed + canonicalize a base endpoint without\n *                     re-querying the backend. EMPTY for staged-only sources.\n *\n * Two sources ship here — today's two blocking strategies (`blocking.ts`),\n * refactored behind the source interface:\n *\n *   - {@link exactKeySource} (`exactKey`, §6.1) — the `block(node) => string`\n *     bucket: same-bucket node pairs become fuzzy `pairs`. Staged-vs-staged.\n *   - {@link uniqueSource} (`unique`, §6.1) — the unique-constraint signature\n *     buckets: every same-signature pair is a FORCED edge (a shared unique value\n *     is definitionally the same entity). Staged-vs-staged.\n *\n * Both read the SAME pre-computed `blockNodes` map off the scope (the UNION of the\n * `block()` key and the per-constraint signatures, `blocking.ts`), filtering it by\n * {@link isUniqueBucketKey}: `exactKey` owns the non-unique buckets, `unique` owns\n * the unique buckets. Sharing one blocked map (vs. re-blocking per source) keeps the\n * source split byte-identical to the old fused `generateCandidates` — a node with a\n * unique signature but no `block()` key lands ONLY in its unique bucket, never the\n * all-vs-all `unblocked` bucket.\n *\n * Determinism: the extraction visits buckets in sorted-key order over id-sorted\n * members and enumerates `i < j`, so proposals are emitted in a canonical order;\n * the scoring stage additionally dedups + sorts, so neither source's emission order\n * leaks into the merge result.\n */\nimport {\n  isUniqueBucketKey,\n  UNBLOCKED_BUCKET_KEY,\n  uniqueConstraintNameForBucket,\n} from \"./blocking\";\nimport { CandidateSourceError } from \"./errors\";\nimport { entityRef, type MatchSource } from \"./evidence\";\nimport {\n  compareMergeKeys,\n  compareStrings,\n  idOf,\n  kindOf,\n  type MergeKey,\n  mergeKey,\n  mergeKeyOf,\n} from \"./node-key\";\nimport type { CandidateEdge, CandidatePair } from \"./scoring\";\nimport { FORCED_MATCH_SCORE } from \"./scoring\";\nimport { fieldText } from \"./similarity\";\nimport type {\n  GraphDef,\n  JsonValue,\n  Node,\n  NodeId,\n  NodeType,\n  UniqueIntrospection,\n} from \"./typegraph-internal\";\nimport type { ResolveConfig } from \"./types\";\nimport { UnionFind } from \"./union-find\";\n\n/**\n * A committed BASE node a source pulled into the cluster universe (design §4\n * member contribution / §6.4-D). It carries the same `(id, kind, props)` a staged\n * member does, plus a reserved `\"base\"` origin so the reconciler can enforce\n * base-id-wins (§6.4-C) and tag provenance with the base sentinel (§6.4-D). EMPTY\n * for staged-only sources (`exactKey`, `unique`).\n */\nexport type BaseMember = Readonly<{\n  id: NodeId<NodeType>;\n  kind: string;\n  props: Readonly<Record<string, JsonValue>>;\n  origin: \"base\";\n  validFrom?: string;\n  validTo?: string;\n}>;\n\n/**\n * What a candidate source emits for one kind: fuzzy `pairs` to score, FORCED\n * (definitional) edges to pass through unscored, and the committed `baseMembers`\n * it pulled into scope.\n */\ntype SourceResult = Readonly<{\n  pairs: readonly CandidatePair[];\n  forcedEdges: readonly CandidateEdge[];\n  baseMembers: readonly BaseMember[];\n}>;\n\n/**\n * The minimal node-collection surface a base-querying source needs: the public\n * `bulkFindByConstraint` (typegraph 0.29.0). It computes each item's constraint key\n * from its props, returns the live committed match per item in INPUT ORDER\n * (`undefined` for misses, soft-deleted excluded), and is indexed by the `uniques`\n * table PK — so graph-merge never reconstructs constraint keys itself. A runtime,\n * kind-string-keyed view (like the commit's `TxNodes`) so a source can dispatch on\n * a kind string without threading the caller's concrete `Store<G>` generic.\n */\nexport type BaseNodeLookup = Readonly<{\n  bulkFindByConstraint: (\n    constraintName: string,\n    items: readonly Readonly<{ props: Record<string, unknown> }>[],\n  ) => Promise<readonly (Node<NodeType> | undefined)[]>;\n  /**\n   * The non-unique sibling (typegraph 0.30): for each item, the live committed nodes\n   * sharing its declared-INDEX key (computed from props), returned per item in input\n   * order, each inner array id-sorted, soft-deleted excluded. `limitPerInput` bounds\n   * per-item fan-out (id-ordered, so the cap is deterministic). Candidate retrieval —\n   * NOT a uniqueness/identity guarantee — so `baseKey` emits scored pairs, not forced\n   * edges.\n   */\n  bulkFindByIndex: (\n    indexName: string,\n    items: readonly Readonly<{ props: Record<string, unknown> }>[],\n    options?: Readonly<{ limitPerInput?: number }>,\n  ) => Promise<readonly (readonly Node<NodeType>[])[]>;\n}>;\n\n/** Runtime, kind-string-keyed view of a store's node collections for base lookups. */\nexport type BaseLookupStore = Readonly<{\n  nodes: Readonly<Record<string, BaseNodeLookup>>;\n}>;\n\n/**\n * The per-kind input a source generates over. `blocks` is the UNION `blockNodes`\n * result (`block()` key + per-constraint signatures) the staged sources read.\n *\n * The remaining fields are present only when a BASE-querying source (`baseUnique` /\n * `baseKey`, §6.2) is driven: the kind's materialized staged new `nodes` (the lookup\n * items), its `uniqueConstraints` (for `baseUnique`), the declared `blockIndex` name\n * (for `baseKey`, when the kind configured one), and the committed `store` to query\n * against. Staged-only sources (`exactKey`, `unique`) ignore them, so the public\n * `merge()` candidate path leaves them unset.\n */\nexport type SourceScope = Readonly<{\n  kind: string;\n  blocks: ReadonlyMap<string, readonly Node<NodeType>[]>;\n  nodes?: readonly Node<NodeType>[];\n  uniqueConstraints?: readonly UniqueIntrospection[];\n  blockIndex?: string;\n  /** When set, `exactKey` bounds the no-key (`\"unblocked\"`) bucket by sorted-\n   * neighbourhood instead of all-vs-all (the `keyless` source, §6.2). */\n  keyless?: KeylessConfig;\n  store?: BaseLookupStore;\n}>;\n\n/**\n * A candidate source (design §4): proposes pairs (recall) + definitional forced\n * edges, and supplies the base members it pulled into scope. The `id` attributes\n * a source in reports and pins its determinism level (§7).\n */\nexport type CandidateSource = Readonly<{\n  readonly id: string;\n  generate(scope: SourceScope): Promise<SourceResult>;\n}>;\n\n/**\n * Orders a pair's two node IDENTITY keys (`(kind, id)`, not bare id) so the smaller\n * is `a`, with the matching node objects in `left`/`right`. Keying on the composite\n * identity is what keeps a `Patient` and an `Encounter` that share an id string from\n * being proposed as the same endpoint. Guarantees every proposal has a single\n * canonical `(a, b)` representation regardless of enumeration order.\n */\nfunction orderEndpoints<K extends NodeType>(\n  left: Node<K>,\n  right: Node<K>,\n  sources: readonly MatchSource[],\n): CandidatePair<K> {\n  const leftKey = mergeKeyOf(left);\n  const rightKey = mergeKeyOf(right);\n  return compareMergeKeys(leftKey, rightKey) <= 0 ?\n      { a: leftKey, b: rightKey, left, right, sources }\n    : { a: rightKey, b: leftKey, left: right, right: left, sources };\n}\n\n/** Sorts a bucket's members by ascending node id (defensive — blocking already does). */\nfunction sortMembersById<K extends NodeType>(\n  members: readonly Node<K>[],\n): readonly Node<K>[] {\n  return [...members].sort((left, right) => compareStrings(left.id, right.id));\n}\n\n/** Visits the blocked buckets in sorted-key order. */\nfunction sortedBucketKeys(\n  blocks: ReadonlyMap<string, readonly Node<NodeType>[]>,\n): readonly string[] {\n  return [...blocks.keys()].sort((left, right) => compareStrings(left, right));\n}\n\n/** The system fields a {@link Node} carries alongside its schema props. */\nconst NODE_SYSTEM_FIELDS: ReadonlySet<string> = new Set([\"id\", \"kind\", \"meta\"]);\n\n/**\n * Extracts a node's schema PROPS from its spread runtime shape (`Node` spreads its\n * schema fields at the top level alongside `id` / `kind` / `meta`). Used to build a\n * base lookup's props from a staged node and a {@link BaseMember}'s props from the\n * returned committed node — without a second fetch or any knowledge of the schema.\n */\nfunction nodeProps(node: Node<NodeType>): Record<string, JsonValue> {\n  // Data-keyed: schema property names spread onto the public node.\n  const props = createDataKeyedBag<JsonValue>();\n  for (const [key, value] of Object.entries(\n    node as unknown as Record<string, unknown>,\n  )) {\n    if (!NODE_SYSTEM_FIELDS.has(key)) {\n      props[key] = value as JsonValue;\n    }\n  }\n  return props;\n}\n\n/**\n * The bounded coarse source for the NO-KEY case (design §6.2, `keyless`): which\n * unblocked nodes to compare, and how far. `window` is the forward-neighbour count;\n * `sortFields` is the kind's similarity text fields, so the SORTED-NEIGHBOURHOOD sort\n * groups lexically-similar values adjacently (the same text the scorer reads).\n */\nexport type KeylessConfig = Readonly<{\n  window: number;\n  sortFields: readonly string[];\n}>;\n\n/**\n * Builds the {@link KeylessConfig} for a kind's resolve config (its `keyless.window`\n * plus the similarity text fields the sorted-neighbourhood pass sorts on), or\n * `undefined` when `keyless` is unset. The sort fields are the kind's similarity text\n * (so adjacency tracks the scorer's text); `custom` similarity exposes none → sort by\n * id only (bounded but semantically weak — a no-key custom kind wants `stagedVector`,\n * deferred §8).\n *\n * Shared by `merge()`'s source path AND the back-compat `generateCandidates()` helper,\n * so both honour `ResolveConfig.keyless` identically rather than the helper silently\n * ignoring it.\n */\nexport function keylessConfigFor<G extends GraphDef, K extends NodeType>(\n  resolveConfig: ResolveConfig<G, K>,\n): KeylessConfig | undefined {\n  if (resolveConfig.keyless === undefined) {\n    return undefined;\n  }\n  const strategy = resolveConfig.similarity;\n  const sortFields =\n    strategy.kind === \"fulltext\" || strategy.kind === \"hybrid\" ? strategy.fields\n    : strategy.kind === \"vector\" ? [strategy.field]\n    : [];\n  return { window: resolveConfig.keyless.window, sortFields };\n}\n\n/**\n * Single-pass SORTED-NEIGHBOURHOOD pairs over one bucket's members: sort by the\n * similarity-field text (tie-broken by id — a total order, so the output is a pure\n * function of the member SET), then propose each node only against its next `window`\n * neighbours. O(n·window) instead of O(n²); `window ≥ n-1` degenerates to all-vs-all.\n */\nfunction windowedPairs(\n  members: readonly Node<NodeType>[],\n  config: KeylessConfig,\n): readonly CandidatePair[] {\n  const keyed = members.map((node) => ({\n    node,\n    key: fieldText(node, config.sortFields),\n  }));\n  keyed.sort((left, right) =>\n    left.key === right.key ?\n      compareStrings(left.node.id, right.node.id)\n    : compareStrings(left.key, right.key),\n  );\n  const pairs: CandidatePair[] = [];\n  for (let index = 0; index < keyed.length; index += 1) {\n    const last = Math.min(index + config.window, keyed.length - 1);\n    for (let index_ = index + 1; index_ <= last; index_ += 1) {\n      pairs.push(\n        orderEndpoints(\n          requireDefined(keyed[index]).node,\n          requireDefined(keyed[index_]).node,\n          [{ kind: \"keyless\", sourceId: \"keyless\" }],\n        ),\n      );\n    }\n  }\n  return pairs;\n}\n\n/**\n * Extracts the FUZZY candidate pairs from the NON-unique (block / unblocked)\n * buckets: every `i < j` pair of a bucket's id-sorted members, in sorted-key\n * order. Cross-bucket duplicates are left for the scoring stage to dedup.\n *\n * When `keyless` is set, the shared `\"unblocked\"` (no-key) bucket is bounded by\n * single-pass sorted-neighbourhood ({@link windowedPairs}) instead of all-vs-all —\n * closing the O(n²) cliff (design §6.2). Keyed `block()` buckets are unaffected\n * (they are already bounded by the key). Unset preserves all-vs-all for every bucket.\n */\nexport function pairsFromBlocks(\n  blocks: ReadonlyMap<string, readonly Node<NodeType>[]>,\n  keyless?: KeylessConfig,\n): readonly CandidatePair[] {\n  const pairs: CandidatePair[] = [];\n  for (const bucketKey of sortedBucketKeys(blocks)) {\n    if (isUniqueBucketKey(bucketKey)) {\n      continue;\n    }\n    const members = sortMembersById(blocks.get(bucketKey) ?? []);\n    if (bucketKey === UNBLOCKED_BUCKET_KEY) {\n      if (keyless !== undefined) {\n        pairs.push(...windowedPairs(members, keyless));\n        continue;\n      }\n      for (let index = 0; index < members.length; index += 1) {\n        for (let index_ = index + 1; index_ < members.length; index_ += 1) {\n          pairs.push(\n            orderEndpoints(\n              requireDefined(members[index]),\n              requireDefined(members[index_]),\n              [{ kind: \"keyless\", sourceId: \"keyless\" }],\n            ),\n          );\n        }\n      }\n      continue;\n    }\n    for (let index = 0; index < members.length; index += 1) {\n      for (let index_ = index + 1; index_ < members.length; index_ += 1) {\n        pairs.push(\n          orderEndpoints(\n            requireDefined(members[index]),\n            requireDefined(members[index_]),\n            [{ kind: \"block\", sourceId: \"exactKey\" }],\n          ),\n        );\n      }\n    }\n  }\n  return pairs;\n}\n\n/**\n * Extracts the FORCED (definitional) edges from the UNIQUE-constraint buckets:\n * every `i < j` pair of a bucket's id-sorted members, at {@link FORCED_MATCH_SCORE}.\n * Cross-bucket / cross-constraint duplicates are left for the scoring stage to dedup.\n */\nexport function forcedEdgesFromBlocks(\n  blocks: ReadonlyMap<string, readonly Node<NodeType>[]>,\n): readonly CandidateEdge[] {\n  const edges: CandidateEdge[] = [];\n  for (const bucketKey of sortedBucketKeys(blocks)) {\n    if (!isUniqueBucketKey(bucketKey)) {\n      continue;\n    }\n    const members = sortMembersById(blocks.get(bucketKey) ?? []);\n    const constraintName = uniqueConstraintNameForBucket(bucketKey);\n    if (constraintName === undefined) {\n      throw new CandidateSourceError(\n        \"Unique candidate bucket has no constraint name.\",\n        {\n          details: {\n            operation: \"candidateEvidence\",\n            sourceId: \"unique\",\n            kind: members[0]?.kind ?? \"unknown\",\n          },\n        },\n      );\n    }\n    for (let index = 0; index < members.length; index += 1) {\n      for (let index_ = index + 1; index_ < members.length; index_ += 1) {\n        const { a, b } = orderEndpoints(\n          requireDefined(members[index]),\n          requireDefined(members[index_]),\n          [],\n        );\n        edges.push({\n          a,\n          b,\n          score: FORCED_MATCH_SCORE,\n          evidence: {\n            a: entityRef(a),\n            b: entityRef(b),\n            sources: [{ kind: \"unique\", sourceId: \"unique\", constraintName }],\n            decision: \"definitional\",\n          },\n        });\n      }\n    }\n  }\n  return edges;\n}\n\n/**\n * Ontology RETYPE candidate edges (the cross-kind STAGED source, §6.4 / T10).\n *\n * Node identity is strictly `(kind, id)`, so a `Patient` and an `Encounter` that\n * share an id string are DISTINCT and never fuse. But under `reconcileTypes:\n * \"ontology\"`, two STAGED-NEW nodes that share a bare id AND carry subtype-compatible\n * kinds are \"the same entity at a refined type\" (one branch staged `Doctor:x`,\n * another `SpecialistDoctor:x`). This source forces those distinct identities into one\n * cluster so the reconciler can collapse it to the most-specific kind. The same-id\n * identities are PARTITIONED into maximal subtype-comparable groups first, so an\n * unrelated kind sharing the id (`Encounter:x` beside `Doctor:x` / `SpecialistDoctor:x`)\n * is split into its own group and does NOT suppress the valid retype; a group only\n * fuses when its kinds still collapse to a single most-specific kind.\n *\n * `isRetypeCompatible` MUST be the same most-specific-common-kind test the reconciler\n * uses ({@link import(\"./type-reconcile\").mostSpecificCommonKind}), so a kind set\n * fuses here iff the reconciler would later collapse it. The caller passes STAGED\n * identities only; committed-base members stay outside this staged retype source.\n *\n * Deterministic: ids are visited in sorted order, the identities at each id are sorted\n * + deduped, and a star of forced edges from the minimum identity makes the fusion\n * transitive (the scoring stage dedups the forced set).\n */\nexport function ontologyRetypeEdges(\n  stagedIdentities: Iterable<MergeKey>,\n  isRetypeCompatible: (kinds: readonly string[]) => boolean,\n): readonly CandidateEdge[] {\n  const identitiesById = new Map<string, MergeKey[]>();\n  for (const identity of stagedIdentities) {\n    const id = idOf(identity);\n    const bucket = identitiesById.get(id);\n    if (bucket === undefined) {\n      identitiesById.set(id, [identity]);\n    } else {\n      bucket.push(identity);\n    }\n  }\n\n  const edges: CandidateEdge[] = [];\n  for (const id of [...identitiesById.keys()].sort(compareStrings)) {\n    const identities = [...new Set(identitiesById.get(id))].sort(\n      compareMergeKeys,\n    );\n    if (identities.length < 2) {\n      continue; // a single kind at this id — nothing cross-kind to reconcile.\n    }\n    // Partition the same-id identities into maximal subtype-comparable GROUPS, so an\n    // UNRELATED kind sharing the id (e.g. an `Encounter:x` next to a `Doctor:x` /\n    // `SpecialistDoctor:x` refinement) does not suppress the valid retype: two\n    // identities join a group when their kinds are pairwise retype-compatible, and the\n    // relation is unioned transitively.\n    const group = unionByCompatibility(identities, isRetypeCompatible);\n    for (const members of groupsOf(identities, group)) {\n      // Only fuse a group that still collapses to ONE most-specific kind (a single\n      // minimum). Incompatible siblings linked only through a shared subtype do not —\n      // fusing them would force the reconciler to flag the cluster and pick a kind.\n      if (\n        members.length < 2 ||\n        !isRetypeCompatible(members.map((identity) => kindOf(identity)))\n      ) {\n        continue;\n      }\n      for (let index = 1; index < members.length; index += 1) {\n        edges.push({\n          a: requireDefined(members[0]),\n          b: requireDefined(members[index]),\n          score: FORCED_MATCH_SCORE,\n          evidence: {\n            a: entityRef(requireDefined(members[0])),\n            b: entityRef(requireDefined(members[index])),\n            sources: [{ kind: \"retype\", sourceId: \"retype\" }],\n            decision: \"definitional\",\n          },\n        });\n      }\n    }\n  }\n  return edges;\n}\n\n/**\n * Union-find over a same-id identity set: `identity → group representative`, where two\n * identities share a representative iff their kinds are (transitively) pairwise\n * {@link isRetypeCompatible}. Pure over the identity SET (the representative chosen is\n * irrelevant — only the partition matters, and callers re-sort each group).\n */\nfunction unionByCompatibility(\n  identities: readonly MergeKey[],\n  isRetypeCompatible: (kinds: readonly string[]) => boolean,\n): ReadonlyMap<MergeKey, MergeKey> {\n  // Partition only — the representative chosen is irrelevant (callers re-sort each\n  // group), so any total order works; `compareMergeKeys` keeps it deterministic.\n  const forest = new UnionFind<MergeKey>(compareMergeKeys);\n  for (const identity of identities) {\n    forest.add(identity);\n  }\n  for (let index = 0; index < identities.length; index += 1) {\n    for (let index_ = index + 1; index_ < identities.length; index_ += 1) {\n      if (\n        isRetypeCompatible([\n          kindOf(requireDefined(identities[index])),\n          kindOf(requireDefined(identities[index_])),\n        ])\n      ) {\n        forest.union(\n          requireDefined(identities[index]),\n          requireDefined(identities[index_]),\n        );\n      }\n    }\n  }\n  return new Map(\n    identities.map((identity) => [identity, forest.find(identity)]),\n  );\n}\n\n/** Buckets identities by their union-find representative, each group id-sorted. */\nfunction groupsOf(\n  identities: readonly MergeKey[],\n  representativeOf: ReadonlyMap<MergeKey, MergeKey>,\n): readonly (readonly MergeKey[])[] {\n  const byRoot = new Map<MergeKey, MergeKey[]>();\n  for (const identity of identities) {\n    const root = requireDefined(representativeOf.get(identity));\n    const bucket = byRoot.get(root);\n    if (bucket === undefined) {\n      byRoot.set(root, [identity]);\n    } else {\n      bucket.push(identity);\n    }\n  }\n  return [...byRoot.values()].map((group) => [...group].sort(compareMergeKeys));\n}\n\n/**\n * `exactKey` source (§6.1) — today's `block(node) => string` bucketing. Same-bucket\n * node pairs become fuzzy `pairs` for the scoring stage to decide. Staged-vs-staged,\n * fully deterministic, no base members.\n *\n * Also hosts the `keyless` source (§6.2): when `scope.keyless` is set, the no-key\n * (`\"unblocked\"`) bucket is bounded by sorted-neighbourhood rather than all-vs-all.\n * It rides `exactKey` rather than a parallel source because both operate on the same\n * staged blocked map and would otherwise double-emit the unblocked bucket.\n */\nexport const exactKeySource: CandidateSource = {\n  id: \"exactKey\",\n  generate(scope) {\n    return Promise.resolve({\n      pairs: pairsFromBlocks(scope.blocks, scope.keyless),\n      forcedEdges: [],\n      baseMembers: [],\n    });\n  },\n};\n\n/**\n * `unique` source (§6.1) — today's unique-constraint short-circuit. Every pair\n * sharing a unique signature is a FORCED edge: a shared unique value is\n * definitionally the same entity, so it merges regardless of similarity (differing\n * properties are reported as conflicts downstream, and the merged graph never\n * violates its own uniqueness). Staged-vs-staged, fully deterministic, no base\n * members.\n */\nexport const uniqueSource: CandidateSource = {\n  id: \"unique\",\n  generate(scope) {\n    return Promise.resolve({\n      pairs: [],\n      forcedEdges: forcedEdgesFromBlocks(scope.blocks),\n      baseMembers: [],\n    });\n  },\n};\n\n/**\n * `baseUnique` source (§6.2) — the first NEW-vs-BASE source. For each declared\n * unique constraint, it issues ONE batched `bulkFindByConstraint` over the staged\n * new nodes against the committed base store (TypeGraph's own constraint API,\n * indexed by the `uniques` PK; key computed from props, soft-deleted excluded). Each\n * hit is a DEFINITIONAL match — a staged node sharing a committed node's unique\n * value is the same entity — so it emits:\n *\n *   - a FORCED edge between the staged node and the committed base node, and\n *   - a {@link BaseMember} built from the returned committed node (no second fetch),\n *     so the reconciler can seed + canonicalize the base endpoint (§4).\n *\n * Grouped by `(kind, constraint)` — one batched call per constraint — so each\n * constraint's own `fields` / `where` / `scope` / `collation` semantics are honoured\n * by construction; graph-merge never rebuilds keys. Deterministic: constraints are\n * visited in sorted name order, base members are deduped by id and id-sorted, and\n * the scoring stage dedups + sorts the forced edges.\n *\n * NOT part of {@link CANDIDATE_SOURCES}: the public `merge()` snapshot path stays\n * staged-vs-staged. This source is driven only by the synthetic new-vs-base scope\n * (later slice steps), which supplies the `nodes` / `uniqueConstraints` / `store`\n * the staged sources omit.\n */\nexport const baseUniqueSource: CandidateSource = {\n  id: \"baseUnique\",\n  async generate(scope) {\n    const { kind, nodes, uniqueConstraints, store } = scope;\n    if (\n      nodes === undefined ||\n      uniqueConstraints === undefined ||\n      store === undefined\n    ) {\n      throw new CandidateSourceError(\n        \"baseUniqueSource requires nodes, uniqueConstraints, and store in the source scope.\",\n        {\n          details: {\n            kind,\n            source: \"baseUnique\",\n            sourceId: \"baseUnique\",\n            operation: \"generate\",\n          },\n        },\n      );\n    }\n\n    const collection = store.nodes[kind];\n    if (collection === undefined || nodes.length === 0) {\n      return { pairs: [], forcedEdges: [], baseMembers: [] };\n    }\n\n    const forcedEdges: CandidateEdge[] = [];\n    const baseMembers = new Map<string, BaseMember>();\n\n    // The lookup items are the SAME for every constraint (one props bag per staged\n    // node), so build them ONCE rather than per constraint, and fire the independent\n    // per-constraint lookups concurrently. Results are consumed in sorted-constraint\n    // order below, so the dedup-by-id keeps determinism despite the parallel I/O.\n    const constraints = [...uniqueConstraints].sort((left, right) =>\n      compareStrings(left.name, right.name),\n    );\n    const items = nodes.map((node) => ({ props: nodeProps(node) }));\n    // `bulkFindByConstraint` re-validates each item's FULL props against the kind's\n    // CREATE schema to compute the constraint key, so a non-idempotent create schema\n    // (a transform/default/coercion) — or a staged node that otherwise fails the\n    // schema — throws a typegraph error. Surface it as a typed MergeError carrying the\n    // kind + constraint, rather than letting an opaque throw be masked as the generic\n    // \"Merge failed while staging or committing\" wrapper downstream.\n    const matchesByConstraint = await Promise.all(\n      constraints.map(async (constraint) => {\n        try {\n          return await collection.bulkFindByConstraint(constraint.name, items);\n        } catch (error) {\n          throw new CandidateSourceError(\n            `baseUniqueSource: new-vs-base lookup for constraint \"${constraint.name}\" on kind \"${kind}\" failed — a staged node's props could not be validated against the kind's schema for constraint-key computation.`,\n            {\n              details: {\n                kind,\n                sourceId: \"baseUnique\",\n                operation: \"lookupConstraint\",\n                constraint: constraint.name,\n              },\n              cause: error,\n            },\n          );\n        }\n      }),\n    );\n    for (const [constraintIndex, matches] of matchesByConstraint.entries()) {\n      const constraint = requireDefined(constraints[constraintIndex]);\n      for (const [index, node] of nodes.entries()) {\n        const base = matches[index];\n        if (base === undefined) {\n          continue;\n        }\n        const stagedNode = node;\n        const stagedKey = mergeKey(stagedNode.kind, stagedNode.id);\n        const baseKey = mergeKey(base.kind, base.id);\n        // ALWAYS pull the committed node in as a base member, so the reconciler seeds +\n        // canonicalizes it and enforces base-id-wins (§6.4-C) — including for a\n        // same-(kind,id) re-discovery, where the committed value must still win over a\n        // divergent staged prop. (Dropping the base member here is what made a same-id\n        // re-add ERROR in the stale-overwrite guard instead of resolving onto the base.)\n        if (!baseMembers.has(baseKey)) {\n          baseMembers.set(baseKey, {\n            origin: \"base\",\n            id: base.id,\n            kind: base.kind,\n            props: nodeProps(base),\n            ...(base.meta.validFrom === undefined ?\n              {}\n            : { validFrom: base.meta.validFrom }),\n            ...(base.meta.validTo === undefined ?\n              {}\n            : { validTo: base.meta.validTo }),\n          });\n        }\n        // A same-(kind,id) re-discovery is already ONE identity (the base member lands\n        // in the staged node's own cluster by key), so it needs no linking edge — a\n        // self-loop would be a degenerate no-op. Skip ONLY the forced edge, not the\n        // base member above.\n        if (stagedKey === baseKey) {\n          continue;\n        }\n        const { a, b } =\n          compareMergeKeys(stagedKey, baseKey) <= 0 ?\n            { a: stagedKey, b: baseKey }\n          : { a: baseKey, b: stagedKey };\n        forcedEdges.push({\n          a,\n          b,\n          score: FORCED_MATCH_SCORE,\n          evidence: {\n            a: entityRef(a),\n            b: entityRef(b),\n            sources: [\n              {\n                kind: \"baseUnique\",\n                sourceId: \"baseUnique\",\n                constraintName: constraint.name,\n              },\n            ],\n            decision: \"definitional\",\n          },\n        });\n      }\n    }\n\n    return {\n      pairs: [],\n      forcedEdges,\n      baseMembers: [...baseMembers.values()].sort((left, right) =>\n        compareStrings(left.id, right.id),\n      ),\n    };\n  },\n};\n\n/**\n * `baseKey` source (§6.2, descriptor-backed block key) — the second NEW-vs-BASE\n * source. For the kind's declared block INDEX (named by `ResolveConfig.blockIndex`,\n * threaded onto the scope), it issues ONE batched `bulkFindByIndex` over the staged\n * new nodes against the committed base store (typegraph 0.30's non-unique index\n * lookup; key computed from props, soft-deleted excluded, fan-out bounded by\n * `limitPerInput`). Unlike {@link baseUniqueSource}, a shared block key is NOT\n * definitional — it is a candidate — so each new↔base hit emits:\n *\n *   - a {@link CandidatePair} (staged ↔ base) handed to the shared scoring stage (it\n *     becomes an edge only if it clears the kind's threshold), and\n *   - a {@link BaseMember} built from the returned committed node (no second fetch).\n *\n * A same-(kind, id) hit needs no pair — the base member joins the staged node's own\n * cluster by key — so only its base member is emitted. graph-merge never reconstructs\n * the index key (typegraph owns `fields`/`scope`/`where`/collation), mirroring\n * `baseUnique`. Deterministic: typegraph returns matches per item in input order,\n * id-sorted; base members are deduped by id and id-sorted; the scoring stage dedups +\n * sorts the pairs. Field-set index keys only — a transform block key stays on the\n * staged-only opaque `block()` (§6.2).\n *\n * NOT part of {@link CANDIDATE_SOURCES}: the public `merge()` snapshot path stays\n * staged-vs-staged; this source runs only under the synthetic new-vs-base scope.\n */\nexport const baseKeySource: CandidateSource = {\n  id: \"baseKey\",\n  async generate(scope) {\n    const { kind, nodes, blockIndex, store } = scope;\n    // No declared block index for this kind → baseKey contributes nothing (a kind opts\n    // into new-vs-base block-key recall by declaring an index + setting blockIndex).\n    if (blockIndex === undefined) {\n      return { pairs: [], forcedEdges: [], baseMembers: [] };\n    }\n    if (nodes === undefined || store === undefined) {\n      throw new CandidateSourceError(\n        \"baseKeySource requires nodes and store in the source scope.\",\n        {\n          details: {\n            kind,\n            source: \"baseKey\",\n            sourceId: \"baseKey\",\n            operation: \"generate\",\n          },\n        },\n      );\n    }\n\n    const collection = store.nodes[kind];\n    if (collection === undefined || nodes.length === 0) {\n      return { pairs: [], forcedEdges: [], baseMembers: [] };\n    }\n\n    const items = nodes.map((node) => ({ props: nodeProps(node) }));\n    // Like `bulkFindByConstraint`, an unknown index name / type-incompatible field\n    // throws a typegraph error; surface it as a typed MergeError carrying the index +\n    // kind rather than letting it be masked as the generic \"Merge failed\" wrapper.\n    let matchesByNode: readonly (readonly Node<NodeType>[])[];\n    try {\n      matchesByNode = await collection.bulkFindByIndex(blockIndex, items);\n    } catch (error) {\n      throw new CandidateSourceError(\n        `baseKeySource: new-vs-base lookup on index \"${blockIndex}\" for kind \"${kind}\" failed — the index is undeclared or a staged node's props are incompatible with its indexed fields.`,\n        {\n          details: {\n            kind,\n            sourceId: \"baseKey\",\n            operation: \"lookupIndex\",\n            index: blockIndex,\n          },\n          cause: error,\n        },\n      );\n    }\n\n    const pairs: CandidatePair[] = [];\n    const baseMembers = new Map<string, BaseMember>();\n    for (const [index, node] of nodes.entries()) {\n      const stagedNode = node;\n      const stagedKey = mergeKey(stagedNode.kind, stagedNode.id);\n      for (const base of matchesByNode[index] ?? []) {\n        const baseKey = mergeKey(base.kind, base.id);\n        if (!baseMembers.has(baseKey)) {\n          baseMembers.set(baseKey, {\n            origin: \"base\",\n            id: base.id,\n            kind: base.kind,\n            props: nodeProps(base),\n            ...(base.meta.validFrom === undefined ?\n              {}\n            : { validFrom: base.meta.validFrom }),\n            ...(base.meta.validTo === undefined ?\n              {}\n            : { validTo: base.meta.validTo }),\n          });\n        }\n        // A same-(kind, id) re-discovery is already ONE identity; the base member lands\n        // in the staged node's own cluster by key, so it needs no candidate pair.\n        if (stagedKey === baseKey) {\n          continue;\n        }\n        pairs.push(\n          orderEndpoints(stagedNode, base, [\n            { kind: \"baseIndex\", sourceId: \"baseKey\", indexName: blockIndex },\n          ]),\n        );\n      }\n    }\n\n    return {\n      pairs,\n      forcedEdges: [],\n      baseMembers: [...baseMembers.values()].sort((left, right) =>\n        compareStrings(left.id, right.id),\n      ),\n    };\n  },\n};\n\n/**\n * The STAGED candidate sources the public `merge()` drives, in a fixed order (§6.1\n * \"phase: now\"). The scoring stage dedups + sorts the union, so this order does not\n * affect the merge result; it is fixed only for stable report attribution. The\n * new-vs-base {@link baseUniqueSource} / {@link baseKeySource} are deliberately NOT\n * here — they run only under the synthetic new-vs-base scope so the public snapshot\n * path stays staged-vs-staged.\n */\nexport const CANDIDATE_SOURCES: readonly CandidateSource[] = [\n  exactKeySource,\n  uniqueSource,\n];\n","import { requireDefined } from \"../utils/presence\";\n/**\n * Staging (design §6.4 rule 1, T7): run the state-diff (T3) for EVERY branch,\n * tag each diff item with its origin {@link BranchId}, and assemble the UNION\n * of all branches' diffs into a single {@link StagingSet}.\n *\n * Why union (not incremental):\n *   Downstream candidate-generation (T6) and clustering (T8) must be\n *   order-independent — shuffling the branch order MUST yield an identical\n *   merge. If staging folded branches one-at-a-time into a mutating cumulative\n *   state, the result could depend on fold order. Instead we COLLECT every\n *   branch's tagged items into flat arrays, then GROUP and SORT once at the end,\n *   so the {@link StagingSet} is a pure function of the unordered branch SET.\n *\n * Provenance tagging:\n *   Every staged item carries the {@link BranchId} of the branch whose diff\n *   produced it. An inherited node modified differently by two branches appears\n *   once per branch (each tagged), which is exactly what the conflict-detection\n *   phases (T8 / T8a) need. A new node introduced by one branch appears once,\n *   tagged by that branch.\n *\n * Determinism:\n *   - New nodes/edges are grouped by kind; the per-kind arrays are sorted by\n *     `(id, branchId)`.\n *   - Flat collections (modified / deleted) are sorted by `(kind, id, branchId)`.\n *   - Bucket maps iterate in lexicographic kind order.\n *   The `(…, branchId)` tail breaks ties when the same id is contributed by more\n *   than one branch, so the ordering is total and stable.\n *\n * Pruning:\n *   Each branch's diff is bounded, when possible, by {@link branchPruneTo} — a\n *   lineage delta naming exactly the rows that changed on either side since\n *   the branch forked (see `state-diff.ts`'s `diffAgainstBase`). This changes\n *   which rows are READ, never the result: a row absent from the delta is\n *   guaranteed unchanged on both sides, so the staged `StagingSet` is\n *   identical to what a full enumeration would have produced.\n */\nimport { lineageDeltaSinceAnchor } from \"./base-version\";\nimport { compareStrings, type MergeKey, mergeKey } from \"./node-key\";\nimport type {\n  ChangedEdge,\n  ChangedNode,\n  DeletedEdge,\n  DeletedNode,\n  ModifiedEdge,\n  ModifiedNode,\n  RetractionCause,\n  WindowedEdge,\n  WindowedNode,\n} from \"./state-diff\";\nimport { diffAgainstBase } from \"./state-diff\";\nimport type {\n  EntityKey,\n  GraphDef,\n  IdentityTransferAssertion,\n  LineageDelta,\n  Store,\n} from \"./typegraph-internal\";\nimport {\n  resolveLineage,\n  storeBackend,\n  storeRuntime,\n} from \"./typegraph-internal\";\nimport type { BranchId, GraphBranch } from \"./types\";\n\n/** A new fork node tagged with the branch that introduced it. */\nexport type StagedNewNode = Readonly<{\n  branchId: BranchId;\n  node: ChangedNode;\n}>;\n\n/** A modified inherited node tagged with the branch that modified it. */\nexport type StagedModifiedNode = Readonly<{\n  branchId: BranchId;\n  node: ModifiedNode;\n}>;\n\n/** A deleted inherited node tagged with the branch that deleted it. */\ntype StagedDeletedNode = Readonly<{\n  branchId: BranchId;\n  node: DeletedNode;\n}>;\n\n/** An inherited node whose valid-time window one branch changed. */\nexport type StagedWindowedNode = Readonly<{\n  branchId: BranchId;\n  node: WindowedNode;\n}>;\n\n/** A new fork edge tagged with the branch that introduced it. */\nexport type StagedNewEdge = Readonly<{\n  branchId: BranchId;\n  edge: ChangedEdge;\n}>;\n\n/** A modified inherited edge tagged with the branch that modified it. */\nexport type StagedModifiedEdge = Readonly<{\n  branchId: BranchId;\n  edge: ModifiedEdge;\n}>;\n\n/** A deleted inherited edge tagged with the branch that deleted it. */\ntype StagedDeletedEdge = Readonly<{\n  branchId: BranchId;\n  edge: DeletedEdge;\n}>;\n\n/** An inherited edge whose valid-time window one branch changed. */\nexport type StagedWindowedEdge = Readonly<{\n  branchId: BranchId;\n  edge: WindowedEdge;\n}>;\n\nexport type StagedIdentityAssertion = Readonly<{\n  branchId: BranchId;\n  assertion: IdentityTransferAssertion;\n}>;\n\n/**\n * A retracted assertion tagged with the branch that stopped asserting it AND\n * with WHY it stopped ({@link RetractionCause}).\n *\n * A `cascade` entry is the staged form of \"branch X's deletion of node N ended\n * this assertion\" — its fate belongs to that deletion, so delete/modify\n * resolution decides it: applied when the deletion survives, dropped with the\n * deletion when it is overruled. An `explicit` entry is the branch's own intent\n * and outlives any deletion decision.\n */\nexport type StagedRetraction = StagedIdentityAssertion &\n  Readonly<{ cause: RetractionCause }>;\n\n/**\n * The provenance-tagged union of every branch's state-diff against the base.\n *\n * New items are bucketed by kind so downstream blocking/candidate-gen (T5/T6)\n * can iterate one kind at a time. Modified and deleted items are kept as flat,\n * fully-sorted arrays — conflict detection (T8/T8a) groups them by id itself.\n */\nexport type StagingSet = Readonly<{\n  /** New fork nodes, bucketed by kind. Map iterates in lexicographic kind order. */\n  newNodesByKind: ReadonlyMap<string, readonly StagedNewNode[]>;\n  /** Modified inherited nodes (one entry per (id, branch) modification). */\n  modifiedNodes: readonly StagedModifiedNode[];\n  /** Deleted inherited nodes (one entry per (id, branch) deletion). */\n  deletedNodes: readonly StagedDeletedNode[];\n  /**\n   * Inherited nodes whose valid-time window a branch changed (one entry per\n   * (id, branch) change). Disjoint from {@link StagingSet.modifiedNodes} in\n   * MEANING, not in membership: a branch that edits props AND moves the end\n   * appears in both, and a window-only change appears here alone — which is\n   * exactly what keeps it out of delete/modify resolution.\n   */\n  windowedNodes: readonly StagedWindowedNode[];\n  /** New fork edges, bucketed by kind. Map iterates in lexicographic kind order. */\n  newEdgesByKind: ReadonlyMap<string, readonly StagedNewEdge[]>;\n  /** Modified inherited edges (one entry per (id, branch) modification). */\n  modifiedEdges: readonly StagedModifiedEdge[];\n  /** Deleted inherited edges (one entry per (id, branch) deletion). */\n  deletedEdges: readonly StagedDeletedEdge[];\n  /** The edge analogue of {@link StagingSet.windowedNodes}. */\n  windowedEdges: readonly StagedWindowedEdge[];\n  newIdentityAssertions: readonly StagedIdentityAssertion[];\n  retractedIdentityAssertions: readonly StagedRetraction[];\n  /**\n   * Every assertion CURRENT in the base store at staging time — the inherited\n   * truth the branches forked from. Untagged (it belongs to no branch). The\n   * planner needs it because a merge can only decide whether the branches'\n   * assertions contradict each other by evaluating them against the assertions\n   * that survive the merge unchanged: a staged `different` pair can contradict a\n   * `same` pair no branch touched (see the contradiction check in `merge.ts`).\n   */\n  baseIdentityAssertions: readonly IdentityTransferAssertion[];\n  /**\n   * `(kind, id) -> version` for the nodes of the branch named by\n   * `stageBranches`' `captureTargetStateFor` argument, observed by that\n   * branch's diff enumeration. Empty when no branch was requested. The\n   * incremental merge captures the committed target branch here to use as the\n   * plan-time baseline for its commit-time lost-update guard.\n   */\n  targetNodeVersions: ReadonlyMap<MergeKey, number>;\n  /**\n   * `(kind, id) -> edge content signature` for the edges of the same captured\n   * branch. The edge-half analogue of {@link targetNodeVersions} (edges carry no\n   * version, so the guard fingerprints their content). Empty when no branch was\n   * requested.\n   */\n  targetEdgeSignatures: ReadonlyMap<MergeKey, string>;\n}>;\n\n/**\n * Total order over `(id, branchId)`. Used for the new-node/new-edge per-kind\n * buckets, where every member already shares a kind so kind need not be keyed.\n */\nfunction compareByIdThenBranch(\n  left: Readonly<{ id: string; branchId: BranchId }>,\n  right: Readonly<{ id: string; branchId: BranchId }>,\n): number {\n  const byId = compareStrings(left.id, right.id);\n  return byId === 0 ? compareStrings(left.branchId, right.branchId) : byId;\n}\n\n/**\n * Total order over `(kind, id, branchId)`. Used for the flat modified/deleted\n * collections, which mix kinds.\n */\nfunction compareByKindIdBranch(\n  left: Readonly<{ kind: string; id: string; branchId: BranchId }>,\n  right: Readonly<{ kind: string; id: string; branchId: BranchId }>,\n): number {\n  const byKind = compareStrings(left.kind, right.kind);\n  if (byKind !== 0) {\n    return byKind;\n  }\n  const byId = compareStrings(left.id, right.id);\n  return byId === 0 ? compareStrings(left.branchId, right.branchId) : byId;\n}\n\n/**\n * Groups items carrying a `kind` into a kind-keyed map whose iteration order is\n * lexicographic by kind and whose per-kind lists are sorted by `(id, branchId)`.\n */\nfunction groupByKind<\n  T extends Readonly<{ kind: string; id: string; branchId: BranchId }>,\n>(items: readonly T[]): ReadonlyMap<string, readonly T[]> {\n  const buckets = new Map<string, T[]>();\n  for (const item of items) {\n    const bucket = buckets.get(item.kind);\n    if (bucket === undefined) {\n      buckets.set(item.kind, [item]);\n    } else {\n      bucket.push(item);\n    }\n  }\n  const ordered = new Map<string, readonly T[]>();\n  for (const kind of [...buckets.keys()].sort((left, right) =>\n    compareStrings(left, right),\n  )) {\n    ordered.set(\n      kind,\n      [...requireDefined(buckets.get(kind))].sort((left, right) =>\n        compareByIdThenBranch(left, right),\n      ),\n    );\n  }\n  return ordered;\n}\n\n/**\n * Deduplicates a lineage delta's mixed-kind key list by `(kind, id)` — the\n * fork's and the base's own `changesSince` results can both name the same\n * row (e.g. one the fork inherited unmodified but the base itself later\n * changed), and a duplicate id costs an extra bind in the pruned batch read\n * `diffAgainstBase` issues for it.\n */\nfunction dedupeEntityKeys(keys: readonly EntityKey[]): EntityKey[] {\n  const byMergeKey = new Map<MergeKey, EntityKey>();\n  for (const key of keys) {\n    byMergeKey.set(mergeKey(key.kind, key.id), key);\n  }\n  return [...byMergeKey.values()];\n}\n\n/**\n * THE one owner of per-branch pruning: the union of what changed on the\n * FORK since it was branched (`branch.forkRevision`, resolved through the\n * fork's own lineage) and what changed on the BASE since the branch's `base`\n * anchor was minted (`lineageDeltaSinceAnchor`, resolved through the base's\n * own lineage for whichever anchor form `base` carries). A key absent from\n * BOTH deltas never moved on either side since the fork point, so restricting\n * `diffAgainstBase`'s reads to this union cannot miss a change — see the\n * property test in `tests/property/lineage-pruned-diff.test.ts`, which is the\n * load-bearing proof that the pruned diff deep-equals the full one.\n *\n * `undefined` — no pruning; `diffAgainstBase` runs its full enumeration —\n * whenever EITHER side cannot supply a bounded delta: the branch was not\n * produced by `branch()` (no `forkRevision`, e.g. `mergeIncremental`'s\n * hand-built committed-target branch), the fork's own store resolves no\n * `lineage` at diff time, the fork's `changesSince` answers `unbounded`, the\n * base-side counterpart of any of those, or either `changesSince` call\n * itself REJECTING (a transient engine error, an unhealthy connection).\n * Pruning is a pure optimization over the full diff, never a precondition\n * for one: a rejection here must fall back to the full comparison rather\n * than fail a merge the full diff would otherwise have completed, so both\n * lineage calls below run through {@link safeLineageDelta}.\n */\nexport async function branchPruneTo<G extends GraphDef>(\n  baseStore: Store<G>,\n  branch: GraphBranch<G>,\n): Promise<LineageDelta | undefined> {\n  if (branch.forkRevision === undefined) return undefined;\n  const forkLineage = resolveLineage(branch.store);\n  if (forkLineage === undefined) return undefined;\n  const forkRevision = branch.forkRevision;\n  // The session is the fork's own root backend — the same object\n  // `resolveLineage(branch.store)` just resolved `lineage` off of, and the\n  // only session available this far outside any transaction.\n  const forkDelta = await safeLineageDelta(() =>\n    forkLineage.changesSince(\n      storeBackend(branch.store),\n      forkRevision,\n      branch.store.graphId,\n    ),\n  );\n  if (forkDelta?.kind !== \"keys\") return undefined;\n  const baseDelta = await safeLineageDelta(() =>\n    lineageDeltaSinceAnchor(baseStore, branch.base),\n  );\n  if (baseDelta?.kind !== \"keys\") return undefined;\n  return {\n    kind: \"keys\",\n    nodes: dedupeEntityKeys([...forkDelta.nodes, ...baseDelta.nodes]),\n    edges: dedupeEntityKeys([...forkDelta.edges, ...baseDelta.edges]),\n  };\n}\n\n/**\n * Runs one lineage delta call, treating a REJECTION the same as an\n * `undefined`/`unbounded` answer: {@link branchPruneTo}'s own doc comment is\n * the \"one owner\" of why a rejection must fall back to the full diff rather\n * than propagate and fail a merge the full diff would have completed.\n */\nasync function safeLineageDelta(\n  fetch: () => Promise<LineageDelta | undefined>,\n): Promise<LineageDelta | undefined> {\n  try {\n    return await fetch();\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Stages the UNION of all branches' diffs against the base, provenance-tagged.\n *\n * Each branch is diffed against `baseStore` (the immutable reference — NEVER a\n * clone, per the Interchange `deletedAt` fidelity limitation), and every diff\n * item is tagged with that branch's id. All branches' tagged items are then\n * collected into flat arrays and grouped/sorted ONCE, so the result is a pure\n * function of the unordered branch set: passing the branches in any order yields\n * a structurally identical {@link StagingSet}.\n *\n * @param baseStore The immutable base store every branch is diffed against.\n * @param branches The branches to stage. Order does not affect the result.\n * @returns The provenance-tagged union staging set.\n */\nexport async function stageBranches<G extends GraphDef>(\n  baseStore: Store<G>,\n  branches: readonly GraphBranch<G>[],\n  captureTargetStateFor?: BranchId,\n): Promise<StagingSet> {\n  const newNodes: (StagedNewNode & { kind: string; id: string })[] = [];\n  const modifiedNodes: (StagedModifiedNode & { kind: string; id: string })[] =\n    [];\n  const deletedNodes: (StagedDeletedNode & { kind: string; id: string })[] = [];\n  const newEdges: (StagedNewEdge & { kind: string; id: string })[] = [];\n  const modifiedEdges: (StagedModifiedEdge & { kind: string; id: string })[] =\n    [];\n  const deletedEdges: (StagedDeletedEdge & { kind: string; id: string })[] = [];\n  const windowedNodes: (StagedWindowedNode & { kind: string; id: string })[] =\n    [];\n  const windowedEdges: (StagedWindowedEdge & { kind: string; id: string })[] =\n    [];\n  const newIdentityAssertions: StagedIdentityAssertion[] = [];\n  const retractedIdentityAssertions: StagedRetraction[] = [];\n\n  const baseIdentityAssertions =\n    await storeRuntime(baseStore).readCurrentIdentityAssertions(\"state\");\n\n  let targetNodeVersions: ReadonlyMap<MergeKey, number> = new Map();\n  let targetEdgeSignatures: ReadonlyMap<MergeKey, string> = new Map();\n  for (const branch of branches) {\n    const branchId = branch.id;\n    const pruneTo = await branchPruneTo(baseStore, branch);\n    const diff = await diffAgainstBase(\n      baseStore,\n      branch.store,\n      branchId === captureTargetStateFor,\n      pruneTo,\n    );\n    if (branchId === captureTargetStateFor) {\n      targetNodeVersions = diff.forkNodeVersions;\n      targetEdgeSignatures = diff.forkEdgeSignatures;\n    }\n\n    for (const node of diff.nodes.new) {\n      newNodes.push({ branchId, node, kind: node.kind, id: node.id });\n    }\n    for (const node of diff.nodes.modified) {\n      modifiedNodes.push({ branchId, node, kind: node.kind, id: node.id });\n    }\n    for (const node of diff.nodes.deleted) {\n      deletedNodes.push({ branchId, node, kind: node.kind, id: node.id });\n    }\n    for (const edge of diff.edges.new) {\n      newEdges.push({ branchId, edge, kind: edge.kind, id: edge.id });\n    }\n    for (const edge of diff.edges.modified) {\n      modifiedEdges.push({ branchId, edge, kind: edge.kind, id: edge.id });\n    }\n    for (const edge of diff.edges.deleted) {\n      deletedEdges.push({ branchId, edge, kind: edge.kind, id: edge.id });\n    }\n    for (const node of diff.nodes.windowed) {\n      windowedNodes.push({ branchId, node, kind: node.kind, id: node.id });\n    }\n    for (const edge of diff.edges.windowed) {\n      windowedEdges.push({ branchId, edge, kind: edge.kind, id: edge.id });\n    }\n    for (const assertion of diff.identity.new) {\n      newIdentityAssertions.push({ branchId, assertion });\n    }\n    for (const retraction of diff.identity.retracted) {\n      retractedIdentityAssertions.push({\n        branchId,\n        assertion: retraction.assertion,\n        cause: retraction.cause,\n      });\n    }\n  }\n\n  return {\n    newNodesByKind: groupByKind(newNodes),\n    modifiedNodes: [...modifiedNodes].sort((left, right) =>\n      compareByKindIdBranch(left, right),\n    ),\n    deletedNodes: [...deletedNodes].sort((left, right) =>\n      compareByKindIdBranch(left, right),\n    ),\n    newEdgesByKind: groupByKind(newEdges),\n    modifiedEdges: [...modifiedEdges].sort((left, right) =>\n      compareByKindIdBranch(left, right),\n    ),\n    deletedEdges: [...deletedEdges].sort((left, right) =>\n      compareByKindIdBranch(left, right),\n    ),\n    windowedNodes: [...windowedNodes].sort((left, right) =>\n      compareByKindIdBranch(left, right),\n    ),\n    windowedEdges: [...windowedEdges].sort((left, right) =>\n      compareByKindIdBranch(left, right),\n    ),\n    newIdentityAssertions: newIdentityAssertions.toSorted((left, right) => {\n      const byId = compareStrings(left.assertion.id, right.assertion.id);\n      return byId === 0 ? compareStrings(left.branchId, right.branchId) : byId;\n    }),\n    retractedIdentityAssertions: retractedIdentityAssertions.toSorted(\n      (left, right) => {\n        const byId = compareStrings(left.assertion.id, right.assertion.id);\n        return byId === 0 ?\n            compareStrings(left.branchId, right.branchId)\n          : byId;\n      },\n    ),\n    baseIdentityAssertions: baseIdentityAssertions.toSorted((left, right) =>\n      compareStrings(left.id, right.id),\n    ),\n    targetNodeVersions,\n    targetEdgeSignatures,\n  };\n}\n","import { requireDefined } from \"../utils/presence\";\n/**\n * Opt-in ontology type reconciliation (design §6 / §7, T10).\n *\n * When entity resolution (T8) collapses fork nodes into one cluster, those nodes\n * may carry DIFFERING `node.kind` values across branches — e.g. one branch staged\n * a `Doctor` while another staged the more-specific `SpecialistDoctor` for what is\n * really the same person. With `reconcileTypes: \"ontology\"` enabled, this module\n * uses the PUBLIC-closure glue (T2a, `closures.ts`) to decide whether those kinds\n * are subClassOf-compatible and, if so, collapses the cluster to the\n * MOST-SPECIFIC common type, recording a {@link TypeReconciliation}. Genuinely\n * incompatible kinds (siblings, disjoint trees) are FLAGGED — never silently\n * collapsed — and surfaced as a {@link DroppedItem}.\n *\n * MOST-SPECIFIC = the unique minimum of the subclass partial order restricted to\n * the cluster's distinct kinds: the kind `T` such that every OTHER kind in the\n * cluster is a (transitive) ancestor of `T` (`isReachable(closure, T, other)`),\n * or is EQUIVALENT to `T` (mutual reachability, from folded `equivalentTo`\n * relations). If several mutually-equivalent kinds tie for the minimum, the\n * lexicographically-smallest representative is chosen so the outcome is\n * deterministic. If no single minimum exists, the kinds are incompatible.\n *\n * This module is a PURE decision function — no I/O, no store access. The\n * orchestrator (T11) builds the {@link ReconcileClusterInput}s from the resolved\n * clusters + the staged nodes' kinds, then applies the returned\n * {@link TypeReconcileResult.retypeMap} to the canonical node's `kind` and to the\n * repointed edges' `fromKind` / `toKind` annotations while keeping endpoint ids\n * stable (the cascade described in step 2). `mode: \"off\"` is a guaranteed no-op.\n */\nimport type { SubClassClosure } from \"./closures\";\nimport { isReachable } from \"./closures\";\nimport { compareStrings, idOf, type MergeKey } from \"./node-key\";\nimport type {\n  DroppedItem,\n  ReconcileTypesMode,\n  TypeReconciliation,\n} from \"./types\";\n\n/**\n * Reason recorded on a {@link DroppedItem} when a cluster's mixed kinds are\n * neither subClassOf-comparable nor equivalent and therefore CANNOT be collapsed.\n * The cluster is left untouched (its members keep their original kinds); this\n * record only flags the incompatibility for the {@link MergeReport}.\n */\nexport const INCOMPATIBLE_TYPES_FLAG_REASON =\n  \"type-reconcile:incompatible-kinds\" as const;\n\n/**\n * One resolved cluster fed into type reconciliation: the canonical survivor id\n * (from T8 `pickClusterSurvivor`) and the DISTINCT kinds present across the cluster's\n * members. Single-kind clusters (one distinct kind) are no-ops and may be omitted\n * by the caller, but are handled defensively here too.\n */\nexport type ReconcileClusterInput = Readonly<{\n  /** The canonical survivor IDENTITY (`(kind, id)`), so the retype keys on the same\n   * composite identity the commit looks it up by — never a bare id shared across\n   * kinds. */\n  canonicalId: MergeKey;\n  /** The distinct member kinds in the cluster. Order does not affect the result. */\n  memberKinds: readonly string[];\n}>;\n\n/**\n * The outcome of reconciling every cluster's kinds.\n *\n * - `reconciliations`: one {@link TypeReconciliation} per multi-kind cluster that\n *   collapsed to a single most-specific type.\n * - `retypeMap`: `canonicalId → toType` for exactly those reconciled clusters, so\n *   the commit (T11) can cascade the retype onto the canonical node and the\n *   repointed edges' endpoint-kind annotations.\n * - `dropped`: one `{ kind: \"node\" }` {@link DroppedItem} per cluster whose kinds\n *   were incompatible (flagged, NOT collapsed) — its `id` is the canonical id and\n *   its `reason` is {@link INCOMPATIBLE_TYPES_FLAG_REASON}.\n */\nexport type TypeReconcileResult = Readonly<{\n  reconciliations: readonly TypeReconciliation[];\n  /** `canonical (kind, id) → toType` for each reconciled cluster, keyed by the\n   * composite identity so the commit cascade resolves a retype unambiguously even\n   * when an id is shared across kinds. */\n  retypeMap: ReadonlyMap<MergeKey, string>;\n  dropped: readonly DroppedItem[];\n}>;\n\n/** Distinct, lexicographically-sorted kinds — the canonical kind set. */\nfunction distinctKinds(kinds: readonly string[]): readonly string[] {\n  return [...new Set(kinds)].sort((left, right) => compareStrings(left, right));\n}\n\n/**\n * Reports whether two kinds are EQUIVALENT under the closure — distinct names\n * that fold to the same `equivalentTo` class, hence mutually reachable. (A kind is\n * not equivalent to itself here; identical names are handled by the caller.)\n */\nfunction areEquivalent(\n  closure: SubClassClosure,\n  left: string,\n  right: string,\n): boolean {\n  return (\n    left !== right &&\n    isReachable(closure, left, right) &&\n    isReachable(closure, right, left)\n  );\n}\n\n/**\n * Reports whether `candidate` is \"at or below\" `other` in the subclass order:\n * either it is a (transitive) subclass of `other`, or the two are equivalent. This\n * is the predicate the most-specific kind must satisfy against every OTHER kind in\n * the cluster.\n */\nfunction isAtOrBelow(\n  closure: SubClassClosure,\n  candidate: string,\n  other: string,\n): boolean {\n  if (candidate === other) {\n    return true;\n  }\n  return (\n    isReachable(closure, candidate, other) ||\n    areEquivalent(closure, candidate, other)\n  );\n}\n\n/**\n * Finds the MOST-SPECIFIC common kind among `kinds`, or `undefined` if the kinds\n * are incompatible (no single minimum of the subclass order).\n *\n * A kind qualifies as the minimum when every OTHER kind is at-or-above it\n * ({@link isAtOrBelow}). Several mutually-equivalent kinds can all qualify; the\n * lexicographically-smallest qualifier is returned so the choice is deterministic.\n * Siblings (e.g. two leaves under a shared parent) and disjoint trees yield no\n * qualifier → `undefined` (incompatible).\n */\nexport function mostSpecificCommonKind(\n  closure: SubClassClosure,\n  kinds: readonly string[],\n): string | undefined {\n  const qualifiers = kinds.filter((candidate) =>\n    kinds.every((other) => isAtOrBelow(closure, candidate, other)),\n  );\n  if (qualifiers.length === 0) {\n    return undefined;\n  }\n  return requireDefined(\n    [...qualifiers].sort((left, right) => compareStrings(left, right))[0],\n  );\n}\n\n/**\n * Reconciles the differing kinds of each resolved cluster against the subClassOf\n * closure.\n *\n * For `mode: \"off\"` (the default) this is a guaranteed no-op: it returns zero\n * reconciliations, an empty retype map, and zero dropped items, regardless of the\n * clusters.\n *\n * For `mode: \"ontology\"`, each cluster with more than one distinct kind is\n * reconciled:\n *\n *   - a single MOST-SPECIFIC common kind exists → the cluster collapses to it; a\n *     {@link TypeReconciliation} is recorded (`fromTypes` = the distinct kinds,\n *     `toType` = the chosen kind) and `canonicalId → toType` is added to\n *     `retypeMap`. When the most-specific kind already equals the cluster's full\n *     (single-element-after-collapse) intent — i.e. all kinds were equivalent and\n *     fold to the same chosen representative — the reconciliation is still\n *     recorded so the cascade can normalize the canonical node's kind.\n *   - no single most-specific kind (siblings / disjoint trees) → the cluster is\n *     FLAGGED incompatible: a `{ kind: \"node\" }` {@link DroppedItem} with reason\n *     {@link INCOMPATIBLE_TYPES_FLAG_REASON} is recorded and the cluster is NOT\n *     collapsed (no retype entry).\n *\n * Single-kind clusters never appear in the output. All output collections are\n * sorted by stable keys (`canonicalId`) so the result is a pure function of the\n * unordered cluster set.\n *\n * @param clusters The resolved clusters with their distinct member kinds.\n * @param closure The subClassOf closure from {@link buildSubClassClosure} (T2a).\n * @param mode `\"off\"` (no-op) or `\"ontology\"` (reconcile).\n */\nexport function reconcileTypes(\n  clusters: readonly ReconcileClusterInput[],\n  closure: SubClassClosure,\n  mode: ReconcileTypesMode,\n): TypeReconcileResult {\n  if (mode === \"off\") {\n    return {\n      reconciliations: [],\n      retypeMap: new Map<MergeKey, string>(),\n      dropped: [],\n    };\n  }\n\n  const reconciliations: TypeReconciliation[] = [];\n  const retypeMap = new Map<MergeKey, string>();\n  const dropped: DroppedItem[] = [];\n\n  for (const cluster of clusters) {\n    const kinds = distinctKinds(cluster.memberKinds);\n    if (kinds.length <= 1) {\n      continue;\n    }\n\n    // The PUBLIC report fields (`entityId`, dropped `id`) carry the bare node id;\n    // the internal retype keys on the full `(kind, id)` identity.\n    const entityId = idOf(cluster.canonicalId);\n    const toType = mostSpecificCommonKind(closure, kinds);\n    if (toType === undefined) {\n      dropped.push({\n        kind: \"node\",\n        id: entityId,\n        reason: INCOMPATIBLE_TYPES_FLAG_REASON,\n      });\n      continue;\n    }\n\n    reconciliations.push({\n      entityId,\n      fromTypes: kinds,\n      toType,\n    });\n    retypeMap.set(cluster.canonicalId, toType);\n  }\n\n  return {\n    reconciliations: reconciliations.sort((left, right) =>\n      compareStrings(left.entityId, right.entityId),\n    ),\n    retypeMap,\n    dropped: dropped.sort((left, right) => compareStrings(left.id, right.id)),\n  };\n}\n","import { resolveWriteFencePlan } from \"../backend/capabilities/write-fence\";\nimport { graphCommandCoordinationIsolation } from \"../backend/command-contract\";\nimport { type TransactionBackend } from \"../backend/types\";\nimport { TypeGraphError } from \"../errors\";\nimport { lockSchemaVersionForStoreWrite } from \"../store/operations/write-transaction\";\nimport { lockRecordedGraphWrite } from \"../store/recorded-capture\";\nimport { MergePlanCapabilityError } from \"./errors\";\n\n/** Acquires merge fences in the Store's canonical schema-first order. */\nexport async function lockMergeTargetWrite(\n  txBackend: TransactionBackend,\n  input: Readonly<{\n    graphId: string;\n    schemaVersion: number | undefined;\n    staleSchemaError: (cause: unknown) => TypeGraphError;\n  }> &\n    (\n      | Readonly<{ graphLock: \"required\"; requireFreshSnapshot?: boolean }>\n      | Readonly<{ graphLock: \"not-required\"; requireFreshSnapshot?: never }>\n    ),\n): Promise<void> {\n  try {\n    await lockSchemaVersionForStoreWrite(\n      { graphId: input.graphId, schemaVersion: input.schemaVersion },\n      txBackend,\n    );\n  } catch (error) {\n    if (\n      !(error instanceof TypeGraphError) ||\n      error.code !== \"STALE_SCHEMA_VERSION\"\n    ) {\n      throw error;\n    }\n    throw input.staleSchemaError(error);\n  }\n  if (input.graphLock === \"required\") {\n    const lock = await lockRecordedGraphWrite(txBackend, input.graphId);\n    // Serialized engines already own the writer slot. An advisory-lock token\n    // carries the isolation observed by the lock statement on this session.\n    if (\n      input.requireFreshSnapshot &&\n      resolveWriteFencePlan(txBackend).kind !== \"engine-serialized\"\n    ) {\n      const isolation =\n        lock.coordination === undefined ?\n          undefined\n        : graphCommandCoordinationIsolation(\n            txBackend.commands,\n            input.graphId,\n            lock.coordination,\n          );\n      if (isolation !== \"read_committed\") {\n        throw new MergePlanCapabilityError(\n          \"Composed merge application requires observed read-committed isolation so reads observe the target after acquiring its graph lock.\",\n          { details: { capability: \"mergeCallbackIsolation\", isolation } },\n        );\n      }\n    }\n  }\n}\n","import { validateEdgeEndpoints } from \"../constraints\";\nimport { IdentityEndpointValidityError } from \"../errors\";\nimport type { EvolutionPlan } from \"../schema/evolution-plan\";\nimport { resolveEvolvedTransactionStore } from \"../store/runtime-port\";\nimport type { TransactionContext } from \"../store/types\";\nimport { createDataKeyedBag, hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\nimport { assertMergeTransactionPristine } from \"./adopted-transaction\";\nimport {\n  assertMergeCallbackResult,\n  type MergePlanApplyOptions,\n  mergePlanReadContext,\n} from \"./apply-callbacks\";\n/**\n * `merge()` orchestrator (design §7.2, T11).\n *\n * Composes every phase built in T3–T10 into one DB-agnostic primitive:\n *\n *   1. PRECONDITION — compute the target's `base@V` and reject any branch whose\n *      `base` token does not match it (`BaseVersionMismatchError`). A branch\n *      forked from a divergent schema or base revision cannot be merged\n *      safely (design §5.2 / §13.6).\n *   2. STAGE — `stageBranches` (T7): the provenance-tagged UNION of every\n *      branch's state-diff against the immutable base.\n *   3. CANDIDATE-GEN — per resolved kind: build node-shaped objects from the\n *      staged NEW nodes, `blockNodes` (T5, folding in unique constraints from\n *      `introspect()`), `generateCandidates` (T6, fulltext Dice + custom; vector/\n *      hybrid guarded). Kinds NOT in `options.resolve` merge by id only.\n *   4. CLUSTER — `connectedComponents` (T8) over the accumulated candidate edges\n *      and every staged new-node id, with the optional diameter guard.\n *   5. CANONICALIZE — `canonicalizeCluster` (T8): min-id survivor + commutative\n *      property union under the stable, non-wall-clock conflict policy.\n *   6. DELETE/MODIFY — `resolveDeleteModify` (T8a): the authoritative final\n *      liveness of every inherited node + the delete/modify conflicts.\n *   7. TYPE-RECONCILE — `reconcileTypes` (T10) over the public-closure glue when\n *      `reconcileTypes: \"ontology\"`; otherwise a no-op.\n *   8. EDGE REPOINT — `repointEdges` (T9): repoint every staged edge onto its\n *      cluster canonical, drop edges to finally-deleted endpoints, dedupe + union\n *      edge props under the same conflict policy.\n *   9. COMMIT — apply everything to `target` (default = base store) in a single\n *      `store.transaction` when the backend is transactional, else non-atomically\n *      with a report warning (out of the P0 acceptance path — SQLite + Postgres\n *      are both transactional).\n *  10. REPORT — assemble the {@link MergeReport} with merged counts, every\n *      resolution / conflict / reconciliation / drop, and the in-memory\n *      {@link ProvenanceIndex}. With `persistProvenance`, ALSO upsert the\n *      `{branch, sourceId}` records to a sidecar provenance graph (post-commit,\n *      best-effort — a failure surfaces as a report warning, never a failed merge).\n *\n * DETERMINISM: every phase is order-independent (pure functions over the\n * unordered branch / staged sets, with a branch order captured ONCE for\n * conflict resolution), so shuffling `branches` yields a deep-equal report and an\n * identical committed graph. T12 proves this with a fast-check shuffle property.\n */\nimport {\n  computeBaseVersion,\n  computeContentComponent,\n  computeSchemaComponent,\n  contentComponentOf,\n  engineAnchorOf,\n  engineAnchorOriginOf,\n  hasRevisionAnchor,\n  readActiveSchemaVersion,\n  revisionAnchorOf,\n  revisionOriginMatch,\n  schemaActiveVersionOf,\n  schemaComponentOf,\n} from \"./base-version\";\nimport { blockNodes } from \"./blocking\";\nimport { canonicalizeProps, edgeStateSignature } from \"./canonical-props\";\nimport type { CanonicalEntity, ClusterMember } from \"./canonicalize\";\nimport {\n  BASE_PROVENANCE_BRANCH,\n  canonicalizeCluster,\n  COMMITTED_TARGET_BRANCH,\n} from \"./canonicalize\";\nimport { buildSubClassClosure } from \"./closures\";\nimport type { ClusterResult } from \"./clustering\";\nimport {\n  connectedComponents,\n  decisiveEdgesForCluster,\n  enforceBaseGuard,\n  enforceDiameterWithEdges,\n} from \"./clustering\";\nimport type { ProvenanceWeights } from \"./conflict-policy\";\nimport { buildBranchRank } from \"./conflict-policy\";\nimport {\n  reconcileEdgeModifications,\n  reconcileModifications,\n  resolveDeleteModify,\n  resolveEdgeDeleteModify,\n} from \"./delete-modify\";\nimport type { MergedEdge, StagedEdge } from \"./edge-repoint\";\nimport {\n  BRANCH_CREATED_EDGE_ORIGIN,\n  buildCanonicalMap,\n  INHERITED_EDGE_ORIGIN,\n  repointEdges,\n} from \"./edge-repoint\";\nimport {\n  BaseVersionMismatchError,\n  describeCause,\n  InvalidMergeOptionsError,\n  InvalidMergePlanError,\n  MergeError,\n  MergePlanCapabilityError,\n  MergePlanDigestMismatchError,\n  MergePlanningStaleError,\n  MergePlanOriginMismatchError,\n  MergePlanSchemaMismatchError,\n  MergePlanTargetMismatchError,\n  StaleMergePlanError,\n  translateMergeCommitError,\n  UnsupportedMergePlanVersionError,\n} from \"./errors\";\nimport type { CandidateDiagnostic, CandidateDiagnostics } from \"./evidence\";\nimport { compareMatchEvidence } from \"./evidence\";\nimport { evolutionPlanningTarget } from \"./evolution-target\";\nimport { unwrapMergeBranches } from \"./ingestion-branch\";\nimport {\n  assertIdentityEndpointsNotDeleted,\n  assertIdentityPeersStable,\n  assertMergedIdentityClassesConsistent,\n  assertNoContradictoryIdentityClosure,\n  assertOneIdOneTruth,\n  assertPlannedIdentityIdsFresh,\n  buildIdentityPeerProbe,\n  type IdentityPeerProbe,\n  type LedgerAssertion,\n  NO_STORED_ASSERTIONS,\n  planIdentityChanges,\n  type PlanIdentityContext,\n  remapIdentityAssertionEndpoints,\n  RETRACTION_DELETION_OVERRULED_DROP_REASON,\n  translateIdentityCommitError,\n} from \"./merge-identity\";\nimport {\n  compareMergeKeys,\n  compareStrings,\n  idOf,\n  kindOf,\n  type MergeKey,\n  mergeKey,\n  mergeKeyOf,\n} from \"./node-key\";\nimport type { NormalizedMergeOptions } from \"./options\";\nimport { normalizeMergeOptions } from \"./options\";\nimport type {\n  MergePlanAnchors,\n  MergePlanArtifact,\n  MergePlanArtifactV1,\n  MergePlanArtifactV1Input,\n  MergePlanEdgeUpsert,\n  MergePlanEntityRef,\n  MergePlanNodeUpsert,\n  MergePlanTargetFence,\n} from \"./plan-schema\";\nimport {\n  constructMergePlanArtifact,\n  validateMergePlanArtifact,\n} from \"./plan-wire\";\nimport type { ProvenanceGraph } from \"./provenance-store\";\nimport {\n  contributionKey,\n  openProvenanceStore,\n  persistProvenanceRecords,\n  provenanceGraphId,\n} from \"./provenance-store\";\nimport type { Result } from \"./result\";\nimport { err, isErr, ok } from \"./result\";\nimport type { CandidateEdge, CandidatePair } from \"./scoring\";\nimport { compareCandidateEdges, scoreCandidates } from \"./scoring\";\nimport type { SimilarityContext } from \"./similarity\";\nimport { embeddingFields, fieldText } from \"./similarity\";\nimport type { BaseLookupStore, BaseMember, SourceScope } from \"./sources\";\nimport {\n  baseKeySource,\n  baseUniqueSource,\n  CANDIDATE_SOURCES,\n  keylessConfigFor,\n  ontologyRetypeEdges,\n} from \"./sources\";\nimport type {\n  StagedModifiedEdge,\n  StagedModifiedNode,\n  StagedNewEdge,\n  StagedNewNode,\n  StagedRetraction,\n  StagingSet,\n} from \"./staging\";\nimport { stageBranches } from \"./staging\";\nimport type { ModifiedNode } from \"./state-diff\";\nimport type { ReconcileClusterInput } from \"./type-reconcile\";\nimport { mostSpecificCommonKind, reconcileTypes } from \"./type-reconcile\";\nimport type {\n  Edge,\n  EdgeId,\n  EngineRevision,\n  EntityKey,\n  GraphDef,\n  IdentityTransferAssertion,\n  JsonValue,\n  LineageDelta,\n  LineageMembers,\n  LineageSession,\n  Node,\n  NodeId,\n  NodeType,\n  Store,\n  TransactionBackend,\n  TransactionOptions,\n  UniqueIntrospection,\n  ValidityEndMutation,\n} from \"./typegraph-internal\";\nimport {\n  advanceRevisionClock,\n  forceRecordedGraphRevision,\n  forceWriteTransactionRevision,\n  readRecordedClock,\n  readRevisionOrigin,\n  requireLineage,\n  resolveLineage,\n  runRetriedUnit,\n  storeBackend,\n  storeCaptureEnabled,\n  storeRuntime,\n  transactionBackend,\n  TypeGraphError,\n} from \"./typegraph-internal\";\nimport type {\n  BaseAmbiguity,\n  BaseVersion,\n  BranchId,\n  BranchProvenance,\n  DeleteModifyConflict,\n  DroppedItem,\n  Embedder,\n  EntityResolution,\n  GraphBranch,\n  MergeBranch,\n  MergedCounts,\n  MergeIncrementalArgs as MergeIncrementalArguments,\n  MergeOptions,\n  MergeReport,\n  PropertyConflict,\n  PropertyConflictPolicy,\n  ProvenanceIndex,\n  ProvenanceRecord,\n  SimilarityStrategy,\n  TypeReconciliation,\n  ValidityEndResolution,\n} from \"./types\";\nimport type { ValidToChange } from \"./valid-window\";\nimport { resolveValidWindows } from \"./valid-window\";\nimport { lockMergeTargetWrite } from \"./write-fence\";\n\n/** A node id in its untyped (`NodeType`-default) branded form. */\ntype AnyNodeId = NodeId<NodeType>;\n\n/** Reserved synthetic branch id for the live target in `mergeIncremental()`. */\n\n/**\n * Materializes a {@link Node}-shaped object from a staged new node's parsed\n * props. The blocking (T5) and similarity (T6) phases read schema fields directly\n * off the node (`node.name`), so the props must be spread at the top level with\n * `kind`/`id` alongside — exactly the runtime shape `Node<NodeType>` carries.\n */\nfunction asNode(staged: StagedNewNode): Node<NodeType> {\n  return {\n    kind: staged.node.kind,\n    id: staged.node.id,\n    ...staged.node.props,\n  } as unknown as Node<NodeType>;\n}\n\n/**\n * Collects, per kind, every staged new node tagged by branch, in deterministic\n * `(id, branchId)` order. The staging set already buckets new nodes by kind in\n * lexicographic order; this re-sorts each bucket defensively so candidate-gen is\n * correct for any caller.\n */\nfunction newNodesByKind(\n  staging: StagingSet,\n): ReadonlyMap<string, readonly StagedNewNode[]> {\n  const ordered = new Map<string, readonly StagedNewNode[]>();\n  for (const [kind, items] of staging.newNodesByKind) {\n    ordered.set(\n      kind,\n      [...items].sort((left, right) => {\n        const byId = compareStrings(left.node.id, right.node.id);\n        return byId === 0 ?\n            compareStrings(left.branchId, right.branchId)\n          : byId;\n      }),\n    );\n  }\n  return ordered;\n}\n\n/**\n * Looks up a kind's declared unique constraints from the store introspection, so\n * blocking can short-circuit exact-match duplicates. Returns an empty array for a\n * kind with no constraints (or an unknown kind).\n */\nfunction uniqueConstraintsFor(\n  introspectionKinds: ReadonlyMap<string, readonly UniqueIntrospection[]>,\n  kind: string,\n): readonly UniqueIntrospection[] {\n  return introspectionKinds.get(kind) ?? [];\n}\n\n/**\n * Precomputes the text→vector lookup the `vector`/`hybrid` scorers read.\n *\n * Runs the injected {@link Embedder} ONCE over the deduplicated, non-empty field\n * texts of every staged new node belonging to a `vector`/`hybrid` kind, in sorted\n * order. Embedding is per-text independent and the lookup is keyed by text, so the\n * map — and therefore every pairwise cosine — is a pure function of the staged node\n * SET, independent of branch/arrival order (the determinism contract). The text of\n * each node is taken via the SAME {@link fieldText} the scorer uses, so the\n * embedded key and the looked-up key always match.\n *\n * Returns an EMPTY map when no kind needs embeddings (or every text is empty). The\n * caller passes the map (vs. `undefined`) to {@link SimilarityContext} only when an\n * embedder was configured — that presence is what lets `scorePair` distinguish\n * \"embedder configured\" from \"vector/hybrid requested with no embedder\".\n *\n * This covers only STAGED node texts. COMMITTED base nodes pulled into staged↔base\n * candidate pairs by the base sources are not known until candidate generation\n * runs, so their texts are embedded there via {@link embedMissingPairTexts}.\n */\nasync function precomputeEmbeddings<G extends GraphDef>(\n  byKind: ReadonlyMap<string, readonly StagedNewNode[]>,\n  resolve: NormalizedMergeOptions<G>[\"resolve\"],\n  embedder: Embedder,\n): Promise<ReadonlyMap<string, Float32Array>> {\n  const texts = new Set<string>();\n  for (const [kind, items] of byKind) {\n    const config = resolve[kind];\n    if (config === undefined) {\n      continue;\n    }\n    const fields = embeddingFields(config.similarity);\n    if (fields === undefined) {\n      continue;\n    }\n    for (const staged of items) {\n      const text = fieldText(asNode(staged), fields);\n      if (text.length > 0) {\n        texts.add(text);\n      }\n    }\n  }\n\n  if (texts.size === 0) {\n    return new Map<string, Float32Array>();\n  }\n  return embedSortedTexts(texts, embedder);\n}\n\n/**\n * Runs the injected {@link Embedder} over `texts` in sorted order and returns the\n * text→vector lookup. Sorting here is what makes every embedding call a pure\n * function of the text SET rather than of arrival order (the determinism\n * contract), and the one-vector-per-text contract is enforced loudly — a short\n * or long batch would otherwise silently mis-key the lookup.\n */\nasync function embedSortedTexts(\n  texts: ReadonlySet<string>,\n  embedder: Embedder,\n): Promise<ReadonlyMap<string, Float32Array>> {\n  const orderedTexts = [...texts].sort((left, right) =>\n    compareStrings(left, right),\n  );\n  const vectors = await embedder(orderedTexts);\n  if (vectors.length !== orderedTexts.length) {\n    throw new MergeError(\n      `Embedder returned ${vectors.length} vectors for ${orderedTexts.length} texts; expected exactly one per text.`,\n      {\n        details: { texts: orderedTexts.length, vectors: vectors.length },\n        suggestion:\n          \"Ensure MergeOptions.embedder returns one vector per input text, in order.\",\n      },\n    );\n  }\n  const lookup = new Map<string, Float32Array>();\n  for (const [index, text] of orderedTexts.entries()) {\n    lookup.set(text, requireDefined(vectors[index]));\n  }\n  return lookup;\n}\n\n/**\n * Ensures every text scored for a `vector`/`hybrid` kind is in the embeddings\n * lookup. {@link precomputeEmbeddings} embeds only STAGED node texts; the base\n * sources (`baseKeySource`/`baseUniqueSource`) pull COMMITTED nodes into\n * staged↔base candidate pairs whose texts were never embedded — without this they\n * would score MIN_SCORE and a staged node would commit as a DUPLICATE instead of\n * merging onto its committed entity. Embeds any pair-endpoint text missing from\n * `base` and returns the augmented map (the original when nothing is missing).\n * Keyed by text and embedded in sorted order, so the result stays a pure function\n * of the node set (the determinism contract). Non-embedding strategies\n * (`fulltext`/`custom`) return `base` unchanged.\n */\nasync function embedMissingPairTexts(\n  base: ReadonlyMap<string, Float32Array> | undefined,\n  pairs: readonly CandidatePair[],\n  strategy: SimilarityStrategy,\n  embedder: Embedder,\n): Promise<ReadonlyMap<string, Float32Array>> {\n  const existing = base ?? new Map<string, Float32Array>();\n  const fields = embeddingFields(strategy);\n  if (fields === undefined) {\n    return existing;\n  }\n  const missing = new Set<string>();\n  for (const pair of pairs) {\n    for (const node of [pair.left, pair.right]) {\n      const text = fieldText(node, fields);\n      if (text.length > 0 && !existing.has(text)) {\n        missing.add(text);\n      }\n    }\n  }\n  if (missing.size === 0) {\n    return existing;\n  }\n  return new Map([...existing, ...(await embedSortedTexts(missing, embedder))]);\n}\n\n/**\n * Runs candidate generation for every kind that has a {@link ResolveConfig} by\n * driving the candidate SOURCES (`sources.ts`) over the shared SCORING stage\n * (`scoring.ts`, §4): per kind, each source proposes pairs + forced edges off the\n * scope, and the scoring stage turns them into the kind's candidate edges.\n * Accumulates edges + any base members across kinds and records comparison-ceiling\n * warnings. Kinds NOT in `resolve` (or with no staged new nodes) contribute no\n * candidate edges — they merge by id only.\n *\n * `useBaseSources` selects the resolution DIRECTION. The public snapshot `merge()`\n * passes `false` — only the staged sources (`exactKey`, `unique`) run, so no\n * committed node is pulled into scope (`baseMembers` is empty) and the path stays\n * staged-vs-staged. The synthetic new-vs-base scope passes `true`, adding\n * {@link baseUniqueSource} (which queries `target`) so a staged node re-discovering\n * a committed entity surfaces as a forced new↔base edge + a base member.\n *\n * Returns `err` when a kind's `onComparisonCeiling: \"error\"` ceiling trips or a\n * `vector`/`hybrid` strategy hits the no-embedder guard.\n */\nasync function generateAllCandidates<G extends GraphDef>(\n  target: Store<G>,\n  staging: StagingSet,\n  options: NormalizedMergeOptions<G>,\n  introspectionKinds: ReadonlyMap<string, readonly UniqueIntrospection[]>,\n  ctx: SimilarityContext,\n  useBaseSources: boolean,\n  embedder: Embedder | undefined,\n): Promise<\n  Result<\n    Readonly<{\n      edges: readonly CandidateEdge[];\n      warnings: readonly string[];\n      baseMembers: readonly BaseMember[];\n      diagnostics: readonly CandidateDiagnostic[];\n      diagnosticsTotal: number;\n    }>,\n    MergeError\n  >\n> {\n  const allEdges: CandidateEdge[] = [];\n  const warnings: string[] = [];\n  const baseMembers: BaseMember[] = [];\n  const diagnostics: CandidateDiagnostic[] = [];\n  let diagnosticsTotal = 0;\n  const byKind = newNodesByKind(staging);\n  const sources =\n    useBaseSources ?\n      [...CANDIDATE_SOURCES, baseUniqueSource, baseKeySource]\n    : CANDIDATE_SOURCES;\n  // Base sources resolve staged nodes against the COMMITTED graph — the merge\n  // TARGET, where prior runs' canonicals live — NOT the (possibly older) diff\n  // reference. They coincide under the public snapshot path (target defaults to\n  // store); they differ under the synthetic new-vs-base scope.\n  const baseStore = target as unknown as BaseLookupStore;\n\n  // Each kind's candidate generation is independent (results are concatenated, then\n  // globally re-sorted below), so run them concurrently — under the base-source path\n  // each kind's `bulkFindByConstraint` round-trip would otherwise serialise.\n  const perKind = await Promise.all(\n    [...byKind].map(\n      async ([kind, items]): Promise<\n        Result<\n          Readonly<{\n            edges: readonly CandidateEdge[];\n            warnings: readonly string[];\n            baseMembers: readonly BaseMember[];\n            diagnostics: readonly CandidateDiagnostic[];\n            diagnosticsTotal: number;\n          }>,\n          MergeError\n        >\n      > => {\n        const resolveConfig = options.resolve[kind];\n        if (resolveConfig === undefined) {\n          // No resolution config for this kind: merge by id only (no candidate\n          // edges, so every new node stays a singleton cluster).\n          return ok({\n            edges: [],\n            warnings: [],\n            baseMembers: [],\n            diagnostics: [],\n            diagnosticsTotal: 0,\n          });\n        }\n\n        const nodes = items.map((staged) => asNode(staged));\n        const uniqueConstraints = uniqueConstraintsFor(\n          introspectionKinds,\n          kind,\n        );\n        const blocks = blockNodes(nodes, resolveConfig, uniqueConstraints);\n        const keylessConfig = keylessConfigFor(resolveConfig);\n        const scope: SourceScope = {\n          kind,\n          blocks,\n          nodes,\n          uniqueConstraints,\n          store: baseStore,\n          ...(resolveConfig.blockIndex === undefined ?\n            {}\n          : { blockIndex: resolveConfig.blockIndex }),\n          ...(keylessConfig === undefined ? {} : { keyless: keylessConfig }),\n        };\n\n        const pairs: CandidatePair[] = [];\n        const forcedEdges: CandidateEdge[] = [];\n        const kindBaseMembers: BaseMember[] = [];\n        for (const source of sources) {\n          const produced = await source.generate(scope);\n          pairs.push(...produced.pairs);\n          forcedEdges.push(...produced.forcedEdges);\n          kindBaseMembers.push(...produced.baseMembers);\n        }\n\n        // Base sources pull committed nodes into staged↔base pairs whose texts\n        // were not in the staged-only precompute; embed them now so vector/hybrid\n        // scoring can actually find them (otherwise the pair scores MIN_SCORE and\n        // the staged node duplicates instead of merging onto the committed entity).\n        const kindCtx =\n          embedder === undefined ? ctx : (\n            {\n              ...ctx,\n              embeddings: await embedMissingPairTexts(\n                ctx.embeddings,\n                pairs,\n                resolveConfig.similarity,\n                embedder,\n              ),\n            }\n          );\n\n        const scored = scoreCandidates(\n          { pairs, forcedEdges },\n          resolveConfig,\n          kindCtx,\n          options.onComparisonCeiling,\n          options.maxComparisonsPerKind,\n          options.candidateDiagnostics?.limit ?? 0,\n        );\n        if (isErr(scored)) {\n          return err(scored.error);\n        }\n        return ok({\n          edges: scored.data.edges,\n          warnings: scored.data.warnings.map(\n            (warning) => `[${kind}] ${warning.message}`,\n          ),\n          baseMembers: kindBaseMembers,\n          diagnostics: scored.data.diagnostics,\n          diagnosticsTotal: scored.data.diagnosticsTotal,\n        });\n      },\n    ),\n  );\n\n  for (const result of perKind) {\n    if (isErr(result)) {\n      return err(result.error);\n    }\n    allEdges.push(...result.data.edges);\n    warnings.push(...result.data.warnings);\n    baseMembers.push(...result.data.baseMembers);\n    if (options.candidateDiagnostics !== undefined) {\n      diagnostics.push(...result.data.diagnostics);\n      diagnostics.sort((left, right) =>\n        compareMatchEvidence(left.evidence, right.evidence),\n      );\n      diagnostics.splice(options.candidateDiagnostics.limit);\n    }\n    diagnosticsTotal += result.data.diagnosticsTotal;\n  }\n\n  return ok({\n    // The ONE shared `(a, b)` edge comparator (id-first `(kind, id)` order), so this\n    // stage emits edges in exactly the order clustering consumes them.\n    edges: allEdges.sort((left, right) => compareCandidateEdges(left, right)),\n    warnings,\n    // Total order over the composite `(kind, id)` identity (two same-id/different-kind\n    // base members would tie under a bare-id compare).\n    baseMembers: baseMembers.sort((left, right) =>\n      compareMergeKeys(mergeKeyOf(left), mergeKeyOf(right)),\n    ),\n    diagnostics,\n    diagnosticsTotal,\n  });\n}\n\n/**\n * Builds, per cluster, the {@link ClusterMember} contributions. A staged new node\n * contributes one member per branch that staged it (so a cross-branch property\n * disagreement surfaces as a conflict in the union, T8); a committed BASE node the\n * cluster pulled in contributes one `origin: \"base\"` member, carrying the reserved\n * {@link BASE_PROVENANCE_BRANCH} so it gap-fills the property union and survivor\n * selection can enforce base-id-wins (§6.4-C).\n */\nfunction clusterMembersFor(\n  cluster: ClusterResult,\n  newNodesById: ReadonlyMap<MergeKey, readonly StagedNewNode[]>,\n  baseMembersById: ReadonlyMap<MergeKey, BaseMember>,\n): readonly ClusterMember[] {\n  const members: ClusterMember[] = [];\n  for (const key of cluster.members) {\n    for (const staged of newNodesById.get(key) ?? []) {\n      members.push({\n        origin: \"staged\",\n        id: staged.node.id,\n        kind: staged.node.kind,\n        branchId: staged.branchId,\n        props: staged.node.props as Readonly<Record<string, JsonValue>>,\n        validFrom: staged.node.row.valid_from ?? null,\n        ...(staged.node.row.valid_to === undefined ?\n          {}\n        : { validTo: staged.node.row.valid_to }),\n      });\n    }\n    const base = baseMembersById.get(key);\n    if (base !== undefined) {\n      members.push({\n        origin: \"base\",\n        id: base.id,\n        kind: base.kind,\n        branchId: BASE_PROVENANCE_BRANCH,\n        props: base.props,\n        ...(base.validFrom === undefined ? {} : { validFrom: base.validFrom }),\n        ...(base.validTo === undefined ? {} : { validTo: base.validTo }),\n      });\n    }\n  }\n  return members;\n}\n\n/**\n * Indexes the staged new nodes by id (preserving the per-id branch list), so\n * clustering / canonicalization can pull every branch's contribution for a node.\n */\nfunction indexNewNodesById(\n  staging: StagingSet,\n): ReadonlyMap<MergeKey, readonly StagedNewNode[]> {\n  const index = new Map<MergeKey, StagedNewNode[]>();\n  for (const items of staging.newNodesByKind.values()) {\n    for (const staged of items) {\n      const key = mergeKeyOf(staged.node);\n      const bucket = index.get(key);\n      if (bucket === undefined) {\n        index.set(key, [staged]);\n      } else {\n        bucket.push(staged);\n      }\n    }\n  }\n  return index;\n}\n\n/**\n * Flattens the staged NEW edges plus the surviving inherited MODIFIED edges into\n * the {@link StagedEdge} shape the repoint phase (T9) consumes (parsed props +\n * branch tag). Inherited edges that were not modified by any branch are unchanged\n * in the base and need no re-commit, so only modified inherited edges are folded\n * in here alongside the new edges.\n *\n * The modified inherited edges are the RECONCILED ones (one per id, 3-way merged\n * against base by {@link reconcileEdgeModifications}) — NOT the raw per-branch\n * `staging.modifiedEdges`. That reconciler is the authority on a row several\n * branches modified: it survived delete/modify resolution, merged the props, and\n * already recorded any {@link PropertyConflict} the disagreement raised. Staging\n * each branch's copy separately would put the same row through a second\n * arbitration in the repoint fold and report the same conflict twice.\n *\n * Every inherited edge is staged WITH the base props it was diffed against, which is\n * what lets the fold's property union tell an authored value from an untouched one\n * (issue #408). A branch-created edge carries none — nothing preceded it.\n *\n * Each edge's diff bucket is carried through as its staged ORIGIN\n * ({@link INHERITED_EDGE_ORIGIN} / {@link BRANCH_CREATED_EDGE_ORIGIN}): the modified\n * and re-windowed buckets hold rows the base already has, the new bucket holds rows a\n * branch created. This is the ONLY place that distinction is known — the repoint phase\n * needs it to fold onto a row the target holds, and an edge id says nothing about\n * where the row came from.\n *\n * `windowOnlyCarried` names the identities staged ONLY to carry an ending. Their\n * `branchId` is a write vehicle rather than a contribution (see the loop below),\n * which the provenance fold must know so it does not credit it.\n */\nfunction buildStagedEdges(\n  staging: StagingSet,\n  modifiedEdges: readonly StagedModifiedEdge[],\n  edgeValidityEnds: ReadonlyMap<MergeKey, ValidToChange>,\n  edgeDeletions: ReadonlyMap<MergeKey, string>,\n): Readonly<{\n  edges: readonly StagedEdge[];\n  windowOnlyCarried: ReadonlySet<MergeKey>;\n}> {\n  const staged: StagedEdge[] = [];\n  const stagedIdentities = new Set<MergeKey>();\n  const windowOnlyCarried = new Set<MergeKey>();\n  for (const items of staging.newEdgesByKind.values()) {\n    for (const item of items) {\n      staged.push(toStagedEdge(item.branchId, item));\n    }\n  }\n  for (const item of modifiedEdges) {\n    const identity = mergeKeyOf(item.edge);\n    stagedIdentities.add(identity);\n    const validToChange = edgeValidityEnds.get(identity);\n    staged.push({\n      id: item.edge.id,\n      kind: item.edge.kind,\n      origin: INHERITED_EDGE_ORIGIN,\n      fromId: item.edge.fromId,\n      toId: item.edge.toId,\n      fromKind: item.edge.fromKind,\n      toKind: item.edge.toKind,\n      props: item.edge.forkProps as Readonly<Record<string, JsonValue>>,\n      baseProps: item.edge.baseProps as Readonly<Record<string, JsonValue>>,\n      branchId: item.branchId,\n      ...(validToChange?.kind === \"set\" ? { validTo: validToChange.validTo }\n      : validToChange?.kind === \"clear\" ? { clearValidTo: true as const }\n      : {}),\n    });\n  }\n  // An inherited edge whose ONLY change is its end-of-validity is in neither the\n  // new nor the modified bucket, so it must be staged here or the ending would\n  // have nothing to ride on. Its props are the fork's, which equal the base's by\n  // construction — the write carries the window and leaves the row's content\n  // alone. Finally-deleted edges are excluded: deletion absorbs the ending.\n  //\n  // WHICH branch's copy carries it is arbitrary — the first in the staging order,\n  // `(kind, id, branch)` — and stays that way. The copy is staged WITH the base it\n  // was diffed against, so the repoint fold's property union sees that it authored\n  // nothing and it contributes no claim under any label (issue #408); the carrier's\n  // `branchId` is then a write vehicle only. It is still recorded as window-only\n  // carried, because provenance reads the staged copies too and the ending's author\n  // is credited from the resolution rather than from whoever carried the row.\n  for (const item of staging.windowedEdges) {\n    const identity = mergeKeyOf(item.edge);\n    const validToChange = edgeValidityEnds.get(identity);\n    if (\n      validToChange === undefined ||\n      stagedIdentities.has(identity) ||\n      edgeDeletions.has(identity)\n    ) {\n      continue;\n    }\n    stagedIdentities.add(identity);\n    windowOnlyCarried.add(identity);\n    staged.push({\n      id: item.edge.id,\n      kind: item.edge.kind,\n      origin: INHERITED_EDGE_ORIGIN,\n      fromId: item.edge.fromId,\n      toId: item.edge.toId,\n      fromKind: item.edge.fromKind,\n      toKind: item.edge.toKind,\n      props: item.edge.props as Readonly<Record<string, JsonValue>>,\n      baseProps: item.edge.baseProps as Readonly<Record<string, JsonValue>>,\n      branchId: item.branchId,\n      ...(validToChange.kind === \"set\" ?\n        { validTo: validToChange.validTo }\n      : { clearValidTo: true as const }),\n    });\n  }\n  return { edges: staged, windowOnlyCarried };\n}\n\n/**\n * Projects a {@link StagedNewEdge} onto the repoint-phase {@link StagedEdge}.\n *\n * A new edge's valid-time window travels with it, exactly as a staged new\n * node's does: without it a branch edge authored over an ENDED window would\n * commit as CURRENT at merge time, leaving a live edge between endpoints that\n * are themselves no longer valid.\n */\nfunction toStagedEdge(branchId: BranchId, item: StagedNewEdge): StagedEdge {\n  return {\n    id: item.edge.id,\n    kind: item.edge.kind,\n    origin: BRANCH_CREATED_EDGE_ORIGIN,\n    fromId: item.edge.fromId,\n    toId: item.edge.toId,\n    fromKind: item.edge.fromKind,\n    toKind: item.edge.toKind,\n    props: item.edge.props as Readonly<Record<string, JsonValue>>,\n    branchId,\n    validFrom: item.edge.row.valid_from ?? null,\n    ...(item.edge.row.valid_to === undefined ?\n      {}\n    : { validTo: item.edge.row.valid_to }),\n  };\n}\n\n/**\n * Builds the report-only, in-memory provenance index from the full record list.\n * `byBranch(id)` answers which merged node / edge ids that branch contributed to:\n * a node id when the branch staged a new node that survived into a cluster's\n * canonical (or a surviving modification), an edge id when the branch staged an\n * edge that survived the repoint/dedupe. Collapses the records — which ALSO carry\n * each contribution's `sourceId` for the persisted sidecar — to deduped, sorted id\n * sets per branch (the unchanged report-only shape).\n */\nfunction buildProvenanceIndex(\n  records: readonly ProvenanceRecord[],\n): ProvenanceIndex {\n  const byBranch = new Map<\n    BranchId,\n    Readonly<{ nodeIds: Set<AnyNodeId>; edgeIds: Set<string> }>\n  >();\n  for (const record of records) {\n    let entry = byBranch.get(record.branchId);\n    if (entry === undefined) {\n      entry = { nodeIds: new Set(), edgeIds: new Set() };\n      byBranch.set(record.branchId, entry);\n    }\n    if (record.role === \"node\") {\n      entry.nodeIds.add(record.canonicalId as AnyNodeId);\n    } else {\n      entry.edgeIds.add(record.canonicalId);\n    }\n  }\n\n  const frozen = new Map<BranchId, BranchProvenance>();\n  for (const [branchId, sets] of byBranch) {\n    frozen.set(branchId, {\n      nodeIds: [...sets.nodeIds].sort((left, right) =>\n        compareStrings(left, right),\n      ),\n      edgeIds: [...sets.edgeIds]\n        .sort((left, right) => compareStrings(left, right))\n        .map((id) => id as Edge[\"id\"]),\n    });\n  }\n  return {\n    byBranch: (branchId: BranchId): BranchProvenance =>\n      frozen.get(branchId) ?? { nodeIds: [], edgeIds: [] },\n  };\n}\n\n/**\n * Empty per-branch trust weights used by policies that do not consult weights.\n * Option validation requires a non-empty map whenever `\"provenanceWeighted\"`\n * is selected, so this value is never a silent fallback for that policy.\n */\nconst EMPTY_WEIGHTS: ProvenanceWeights = new Map<BranchId, number>();\n\n/**\n * The fully-resolved (pre-commit) merge plan: everything the commit applies plus\n * everything the report records. Separated from the commit so the commit body is\n * a thin, mechanical application of an already-decided plan.\n *\n * Exported so the commit path can be unit-tested in isolation (e.g. proving that a\n * canonical entity whose id is an already-committed base node UPDATES that row and\n * repoints edges onto it, rather than inserting a duplicate — §6.2).\n */\nexport type MergePlan<G extends GraphDef> = Readonly<{\n  canonicalEntities: readonly CanonicalEntity[];\n  survivingModifications: readonly StagedModifiedNode[];\n  nodeDeletions: ReadonlyMap<MergeKey, string>;\n  edgeDeletions: ReadonlyMap<MergeKey, string>;\n  mergedEdges: readonly MergedEdge[];\n  // Base props of every inherited edge a fork MODIFIED, keyed by edge id. The\n  // commit drops props a fork removed (a base key absent from the merged edge's\n  // props) via {@link commitModificationProps} — edges, like nodes, are written\n  // with PATCH semantics, so a removed key would otherwise survive. New edges\n  // (never inherited) are absent from this map and need no deletion handling.\n  inheritedEdgeBaseProps: ReadonlyMap<\n    EdgeId,\n    Readonly<Record<string, unknown>>\n  >;\n  retypeMap: ReadonlyMap<MergeKey, string>;\n  // The REAL member->survivor canonical map the commit repoints edges and\n  // assertion endpoints with, carried on the plan so every closure re-run\n  // judges endpoints at their post-merge identity. Never reconstruct this\n  // from `resolutions` — those record only multi-bare-id clusters, keyed by\n  // the survivor's kind, so a reconstruction drops pure ontology-retype\n  // clusters and mis-keys mixed-kind members.\n  canonicalOf: ReadonlyMap<MergeKey, MergeKey>;\n  /**\n   * `(kind, id) -> validTo` for every inherited NODE whose end-of-validity the\n   * merge itself decided — a branch's ending that differs from the base's, on a\n   * row the committed target did not already re-window. Keyed on the PRE-retype\n   * identity, exactly as the modification fold is. An identity absent here has\n   * no reconciled ending, and the commit passes no window for it at all — never\n   * the base value re-asserted, and never the target's own value written back at\n   * itself, which is what lets an unchanged window coalesce.\n   */\n  nodeValidityEnds: ReadonlyMap<MergeKey, ValidToChange>;\n  /** The edge half of {@link nodeValidityEnds}, consumed by the repoint phase. */\n  edgeValidityEnds: ReadonlyMap<MergeKey, ValidToChange>;\n  validityEnds: readonly ValidityEndResolution[];\n  resolutions: readonly EntityResolution[];\n  propertyConflicts: readonly PropertyConflict<G>[];\n  deleteModifyConflicts: readonly DeleteModifyConflict[];\n  typeReconciliations: readonly TypeReconciliation[];\n  dropped: readonly DroppedItem[];\n  baseAmbiguities: readonly BaseAmbiguity[];\n  provenanceRecords: readonly ProvenanceRecord[];\n  warnings: readonly string[];\n  candidateDiagnostics?: CandidateDiagnostics;\n  identityAssertions: readonly IdentityTransferAssertion[];\n  // Complete expected rows, never bare ids: a retraction ends whatever CURRENT\n  // row carries its id, so it is only legal against the exact truth the branch\n  // retracted. The plan therefore carries the full staged assertion, and both\n  // validation layers (the plan-time filter and the in-transaction freshness\n  // guard) compare it to the target's row before the id is ended.\n  identityRetractions: readonly IdentityTransferAssertion[];\n}>;\n\n/**\n * Resolves the entire merge into a {@link MergePlan} WITHOUT touching the target.\n * Pure composition of the T3–T10 phases over the staged union; every step is\n * order-independent given the captured `branchRank`.\n */\nfunction buildInternalMergePlan<G extends GraphDef>(\n  staging: StagingSet,\n  candidateEdges: readonly CandidateEdge[],\n  candidateWarnings: readonly string[],\n  candidateDiagnostics: readonly CandidateDiagnostic[],\n  candidateDiagnosticsTotal: number,\n  baseMembers: readonly BaseMember[],\n  options: NormalizedMergeOptions<G>,\n  branchRank: ReadonlyMap<BranchId, number>,\n  subClassClosure: ReturnType<typeof buildSubClassClosure>,\n  identityContext: PlanIdentityContext,\n  storedIdentityRowsById: ReadonlyMap<string, LedgerAssertion>,\n  targetPeers: readonly Readonly<{ kind: string; id: string }>[],\n  preferredBranchId?: BranchId,\n): MergePlan<G> {\n  const identity = planIdentityChanges(staging, storedIdentityRowsById);\n  const provenanceRecords: ProvenanceRecord[] = [];\n  // The contributions already recorded, keyed by `contributionKey` — the sidecar\n  // row's own identity, so a repeat is the same row written twice and never new\n  // information. Several phases legitimately observe the SAME contribution: an\n  // inherited edge is credited once when its modification survives delete/modify\n  // and again when the repoint folds it, and a fold set's `mergedIds` lists one\n  // entry per staged COPY, so a row staged by several branches re-offers each of\n  // its branches once per copy. Repeats inflate `provenancePersisted.count` and,\n  // because `bulkUpsertById` cannot create the same id twice in one batch, fail the\n  // whole best-effort persist. Collapsing at this single funnel keeps the record\n  // list, the in-memory index and the reported count all speaking about DISTINCT\n  // contributions.\n  const recordedContributions = new Set<string>();\n  // Per-branch trust weights for the `\"provenanceWeighted\"` policy, or empty when\n  // the caller supplied none (then the policy falls back to the stable branch order).\n  const weights = options.provenanceWeights ?? EMPTY_WEIGHTS;\n  // Records a branch's contribution of a CANONICAL node id (`role: \"node\"`) or a\n  // SURVIVING edge id (`role: \"edge\"`), keeping its source.\n  const recordProvenance = (\n    role: ProvenanceRecord[\"role\"],\n    branchId: BranchId,\n    canonicalId: string,\n    canonicalKind: string,\n    sourceId: string,\n  ): void => {\n    if (branchId === preferredBranchId) {\n      return;\n    }\n    const record: ProvenanceRecord = {\n      role,\n      canonicalId,\n      canonicalKind,\n      branchId,\n      sourceId,\n    };\n    const key = contributionKey(record);\n    if (recordedContributions.has(key)) {\n      return;\n    }\n    recordedContributions.add(key);\n    provenanceRecords.push(record);\n  };\n\n  // (4) cluster over every staged new-node id + every base member id (so a forced\n  // new↔base edge is not dropped as out-of-scope, clustering.ts:134) + the\n  // candidate edges. Base members come only from base sources, so this set is\n  // exactly the staged universe under the public snapshot path.\n  const newNodesById = indexNewNodesById(staging);\n  // A base member only belongs in the cluster universe if it actually PARTICIPATES:\n  // it got an ACCEPTED candidate edge to a staged node (a forced `baseUnique` edge, or a\n  // `baseKey`/fuzzy pair that cleared the threshold), or it shares a key with a staged\n  // node (a same-(kind, id) rediscovery, which joins by key without an edge). A `baseKey`\n  // hit whose fuzzy pair was REJECTED below threshold would otherwise be seeded as a\n  // singleton cluster and re-committed — rewriting an unrelated committed row, inflating\n  // `merged.nodes`, and recording spurious provenance under the base sentinel. Drop those\n  // orphans here, now that scoring has decided which pairs survived.\n  const acceptedEndpointKeys = new Set<MergeKey>();\n  for (const edge of candidateEdges) {\n    acceptedEndpointKeys.add(edge.a);\n    acceptedEndpointKeys.add(edge.b);\n  }\n  const baseMembersById = new Map<MergeKey, BaseMember>();\n  for (const member of baseMembers) {\n    const key = mergeKeyOf(member);\n    if (acceptedEndpointKeys.has(key) || newNodesById.has(key)) {\n      baseMembersById.set(key, member);\n    }\n  }\n  const newNodeIds = [...newNodesById.keys(), ...baseMembersById.keys()];\n\n  // (3b) ONTOLOGY RETYPE edges (T10 input): identity stays strictly `(kind, id)`, but\n  // under `reconcileTypes: \"ontology\"` two STAGED-new nodes sharing a bare id with\n  // subtype-compatible kinds are the same entity at a refined type, so they are forced\n  // into one cluster for the reconciler to collapse. Same most-specific-common-kind\n  // test the reconciler uses (so a set fuses here iff it would collapse later);\n  // staged-only (base members excluded — a committed-base retype is an inherited\n  // mutation v1 refuses); `\"off\"` emits nothing, leaving identity strictly `(kind,id)`.\n  const isOntology = options.reconcileTypes === \"ontology\";\n  const preferKind =\n    isOntology ?\n      (kinds: readonly string[]): string | undefined =>\n        mostSpecificCommonKind(subClassClosure, kinds)\n    : undefined;\n  const clusterEdges =\n    isOntology ?\n      [\n        ...candidateEdges,\n        ...ontologyRetypeEdges(\n          newNodesById.keys(),\n          (kinds) =>\n            mostSpecificCommonKind(subClassClosure, kinds) !== undefined,\n        ),\n      ]\n    : candidateEdges;\n\n  // (4) component-level BASE GUARD (§6.4-A) runs on the RAW components, BEFORE the\n  // diameter split — so a diameter guard can never sever a base↔base bridge into\n  // single-base pieces and leave the ambiguity unreported. The committed entities are\n  // always kept separate (the collapse is refused; a deliberate collapse is deferred,\n  // §6.4-C), then the optional diameter guard splits the base-contained clusters.\n  const baseIds = new Set<MergeKey>(baseMembersById.keys());\n  const guard = enforceBaseGuard(\n    connectedComponents(clusterEdges, newNodeIds),\n    clusterEdges,\n    baseIds,\n  );\n  const diameterGuard =\n    options.clusterMaxDiameter === undefined ?\n      {\n        clusters: guard.clusters,\n        survivingEdges: guard.survivingEdges,\n        excludedEdges: [],\n      }\n    : enforceDiameterWithEdges(\n        guard.clusters,\n        clusterEdges,\n        options.clusterMaxDiameter,\n      );\n  const clusters = diameterGuard.clusters;\n  const baseSurvivingEdges = new Set(guard.survivingEdges);\n  const survivingEdges = diameterGuard.survivingEdges.filter((edge) =>\n    baseSurvivingEdges.has(edge),\n  );\n  const excludedByEndpoints = new Map<string, \"diameter\" | \"baseAmbiguity\">();\n  for (const excluded of [\n    ...guard.excludedEdges,\n    ...diameterGuard.excludedEdges,\n  ]) {\n    excludedByEndpoints.set(\n      JSON.stringify([excluded.edge.a, excluded.edge.b]),\n      excluded.reason,\n    );\n  }\n  const diagnosticsWithDisposition: CandidateDiagnostic[] =\n    candidateDiagnostics.map((diagnostic): CandidateDiagnostic => {\n      if (diagnostic.evidence.decision === \"definitional\") return diagnostic;\n      if (diagnostic.scoreDecision === \"rejected\") return diagnostic;\n      const a = mergeKey(diagnostic.evidence.a.kind, diagnostic.evidence.a.id);\n      const b = mergeKey(diagnostic.evidence.b.kind, diagnostic.evidence.b.id);\n      const reason = excludedByEndpoints.get(JSON.stringify([a, b]));\n      return {\n        ...diagnostic,\n        clusterDisposition:\n          reason === undefined ?\n            (\"retained\" as const)\n          : ({ kind: \"excluded\" as const, reason } as const),\n      } as CandidateDiagnostic;\n    });\n  const definitionalExclusions: CandidateDiagnostic[] = [\n    ...guard.excludedEdges,\n    ...diameterGuard.excludedEdges,\n  ]\n    .filter((excluded) => excluded.edge.evidence.decision === \"definitional\")\n    .map((excluded) => ({\n      evidence: excluded.edge.evidence as Extract<\n        CandidateEdge[\"evidence\"],\n        Readonly<{ decision: \"definitional\" }>\n      >,\n      scoreDecision: \"accepted\" as const,\n      clusterDisposition: {\n        kind: \"excluded\" as const,\n        reason: excluded.reason,\n      },\n    }));\n  const retainedDiagnostics = [\n    ...diagnosticsWithDisposition,\n    ...definitionalExclusions,\n  ].sort((left, right) => compareMatchEvidence(left.evidence, right.evidence));\n  // The guard keys on composite `(kind, id)` identities; the public BaseAmbiguity\n  // carries them in full, so a component spanning two same-id/different-kind committed\n  // entities stays distinguishable in the report.\n  const baseAmbiguities: BaseAmbiguity[] = guard.events.map((event) => ({\n    baseIds: event.baseIds.map((key) => ({ kind: kindOf(key), id: idOf(key) })),\n    memberIds: event.memberIds.map((key) => ({\n      kind: kindOf(key),\n      id: idOf(key),\n    })),\n  }));\n\n  // (5) canonicalize each cluster: min-id survivor + commutative prop union.\n  const canonicalEntities: CanonicalEntity[] = [];\n  const resolutions: EntityResolution[] = [];\n  const clusterByCanonicalIdentity = new Map<MergeKey, ClusterResult>();\n  const propertyConflicts: PropertyConflict<G>[] = [];\n  // (7-input) the distinct member kinds per cluster, collected here so a committed\n  // BASE member's kind is part of type reconciliation — a base↔staged kind divergence\n  // (e.g. base `Doctor` vs staged `SpecialistDoctor`) must be reconciled/flagged, not\n  // dropped because base members live outside `newNodesById`.\n  const reconcileInputs: ReconcileClusterInput[] = [];\n  for (const cluster of clusters) {\n    const members = clusterMembersFor(cluster, newNodesById, baseMembersById);\n    if (members.length === 0) {\n      continue;\n    }\n    const entity = canonicalizeCluster(\n      cluster,\n      members,\n      options.onPropertyConflict as PropertyConflictPolicy,\n      branchRank,\n      weights,\n      options.canonical,\n      options.onBasePropertyConflict as PropertyConflictPolicy,\n      preferKind,\n      preferredBranchId,\n    );\n    canonicalEntities.push(entity);\n    clusterByCanonicalIdentity.set(\n      mergeKey(entity.kind, entity.canonicalId),\n      cluster,\n    );\n    reconcileInputs.push({\n      canonicalId: mergeKey(entity.kind, entity.canonicalId),\n      memberKinds: members.map((member) => member.kind),\n    });\n    // An EntityResolution records an actual MERGE — two or more distinct fork node\n    // IDS collapsing into one canonical. Counted by distinct BARE id (not composite\n    // identity): an ontology-retype cluster is several `(kind, id)` identities at ONE\n    // id, which is a type reconciliation (recorded separately), not an id merge. A\n    // singleton cluster records no resolution.\n    const distinctMergedIds = new Set(\n      cluster.members.map((member) => idOf(member)),\n    );\n    if (distinctMergedIds.size > 1) {\n      resolutions.push({\n        ...entity.resolution,\n        decisiveEdges: decisiveEdgesForCluster(cluster, survivingEdges),\n      });\n    }\n    // Conflicts are recorded REGARDLESS of distinct-id count: two branches can\n    // stage a new node under the SAME id with differing props, producing a genuine\n    // cross-branch conflict inside a single-id cluster. `entity.conflicts` is\n    // already gated by `resolved.conflicted`, so an agreeing single-member cluster\n    // contributes none — but a real disagreement must not be silently auto-resolved\n    // without a report entry.\n    for (const conflict of entity.conflicts) {\n      propertyConflicts.push(conflict as PropertyConflict<G>);\n    }\n    for (const member of members) {\n      recordProvenance(\n        \"node\",\n        member.branchId,\n        entity.canonicalId,\n        entity.kind,\n        member.id,\n      );\n    }\n  }\n\n  // (6) delete/modify resolution → authoritative final endpoint liveness.\n  const deleteModify = resolveDeleteModify(\n    staging,\n    options.onDeleteModifyConflict,\n    branchRank,\n    preferredBranchId,\n  );\n  const nodeDeletions = new Map<MergeKey, string>();\n  for (const deletion of deleteModify.nodeDeletions) {\n    nodeDeletions.set(mergeKey(deletion.kind, deletion.id), deletion.kind);\n  }\n  // A node soft-delete CASCADES: it ends every open assertion touching the\n  // node, at the node's own deletion instant. The diff derives that cause and\n  // stages the ending as a `cascade` retraction naming the deleted node\n  // (StagedRetraction.cause); every other ending is the branch's own act and is\n  // staged `explicit`.\n  //\n  // A cascade's fate therefore belongs to the deletion that caused it. When the\n  // delete/modify resolution OVERRULES that deletion (\"flag\"/\"modifyWins\" keep\n  // the modification), applying the ending anyway would let the losing\n  // deletion's side effect outlive the decision and strip the resurrected\n  // node's identity truth — so the ending is dropped with its cause, visibly.\n  // A retraction survives as soon as ONE branch staged it explicitly, or one\n  // cause deletion survived: those are intents the deletion decision does not\n  // speak to.\n  const anyDeletionOverruled = staging.deletedNodes.some(\n    (deletion) =>\n      !nodeDeletions.has(mergeKey(deletion.node.kind, deletion.node.id)),\n  );\n  const stagedRetractionsById = new Map<string, StagedRetraction[]>();\n  for (const staged of staging.retractedIdentityAssertions) {\n    const contributions = stagedRetractionsById.get(staged.assertion.id) ?? [];\n    contributions.push(staged);\n    stagedRetractionsById.set(staged.assertion.id, contributions);\n  }\n  const overruledRetractionDrops: DroppedItem[] = [];\n  const survivingRetractions =\n    anyDeletionOverruled ?\n      identity.retractions.filter((retraction) => {\n        const contributions = stagedRetractionsById.get(retraction.id) ?? [];\n        const everyContributionOverruled =\n          contributions.length > 0 &&\n          contributions.every(\n            (staged) =>\n              staged.cause.kind === \"cascade\" &&\n              !nodeDeletions.has(\n                mergeKey(\n                  staged.cause.deletedNode.kind,\n                  staged.cause.deletedNode.id,\n                ),\n              ),\n          );\n        if (!everyContributionOverruled) return true;\n        overruledRetractionDrops.push({\n          kind: \"identity\",\n          id: retraction.id,\n          reason: RETRACTION_DELETION_OVERRULED_DROP_REASON,\n        });\n        return false;\n      })\n    : identity.retractions;\n  for (const modification of deleteModify.survivingModifications) {\n    recordProvenance(\n      \"node\",\n      modification.branchId,\n      modification.node.id,\n      modification.node.kind,\n      modification.node.id,\n    );\n  }\n\n  // Reconcile inherited nodes modified by 2+ branches into one merged record per\n  // id (3-way against base), surfacing genuine disagreements as PropertyConflicts\n  // instead of silently letting the last-committed branch win. Provenance above\n  // already credited every contributing branch.\n  const reconciledModifications = reconcileModifications(\n    deleteModify.survivingModifications,\n    options.onPropertyConflict as PropertyConflictPolicy,\n    branchRank,\n    weights,\n    preferredBranchId,\n  );\n  for (const conflict of reconciledModifications.conflicts) {\n    propertyConflicts.push(conflict as PropertyConflict<G>);\n  }\n\n  // (6-edge) the EDGE analogue of node delete/modify + reconcile. Inherited edge\n  // deletions are applied (previously staged but never committed, so the edge\n  // stayed live), and edges modified by 2+ branches are 3-way merged against base\n  // so disjoint edits do not false-conflict (previously each branch's full fork\n  // props were unioned, dropping a branch's independent edit). Provenance credits\n  // every modifying branch (mirrors the node push), before reconcile collapses\n  // them to one record per id.\n  const edgeDeleteModify = resolveEdgeDeleteModify(\n    staging,\n    options.onDeleteModifyConflict,\n    branchRank,\n    preferredBranchId,\n  );\n  const edgeDeletions = new Map<MergeKey, string>();\n  for (const deletion of edgeDeleteModify.edgeDeletions) {\n    edgeDeletions.set(mergeKey(deletion.kind, deletion.id), deletion.kind);\n  }\n  for (const modification of edgeDeleteModify.survivingModifications) {\n    recordProvenance(\n      \"edge\",\n      modification.branchId,\n      modification.edge.id,\n      modification.edge.kind,\n      modification.edge.id,\n    );\n  }\n  const reconciledEdgeModifications = reconcileEdgeModifications(\n    edgeDeleteModify.survivingModifications,\n    options.onPropertyConflict as PropertyConflictPolicy,\n    branchRank,\n    weights,\n    preferredBranchId,\n  );\n  for (const conflict of reconciledEdgeModifications.conflicts) {\n    propertyConflicts.push(conflict as PropertyConflict<G>);\n  }\n\n  // (6-window) reconcile the inherited valid-time windows the branches moved.\n  // Runs AFTER both delete/modify resolutions because a finally-deleted row\n  // absorbs its own ending: deleting and ending are both \"no longer true\", and\n  // the stronger statement wins without recording a conflict.\n  const validWindows = resolveValidWindows(\n    staging,\n    new Set(nodeDeletions.keys()),\n    new Set(edgeDeletions.keys()),\n    preferredBranchId,\n  );\n\n  // (6-window provenance) credit the branches that AUTHORED a committed node\n  // ending. Ending a row is authored state, but a branch whose only change to a\n  // node is its window is neither a cluster member nor a surviving modification,\n  // and the write that carries the ending names no branch — so without this the\n  // branch whose claim the commit applied is absent from the provenance sidecar\n  // entirely (issue #402). The credit comes from the resolution because only the\n  // resolution knows whose claim won; a claim that LOST the least-claim rule is\n  // not in `nodeCredits` and is not credited, since provenance records\n  // contribution to COMMITTED state.\n  //\n  // Edges take the same credit through `stagedEdgeBranches` below, where the\n  // repoint's surviving edge id is known.\n  //\n  // A branch that edited the node's props AND moved its window is already\n  // credited with this exact record by the modification loop above; re-recording\n  // it would count one sidecar row twice. A record whose `sourceId` differs from\n  // its canonical is a DIFFERENT contribution (a fork id folded into a survivor)\n  // and never stands in for the in-place one.\n  const creditedNodeIdentities = new Map<MergeKey, Set<BranchId>>();\n  for (const record of provenanceRecords) {\n    if (record.role !== \"node\" || record.sourceId !== record.canonicalId) {\n      continue;\n    }\n    const identity = mergeKey(record.canonicalKind, record.canonicalId);\n    const credited =\n      creditedNodeIdentities.get(identity) ?? new Set<BranchId>();\n    credited.add(record.branchId);\n    creditedNodeIdentities.set(identity, credited);\n  }\n  for (const [identity, branchIds] of validWindows.nodeCredits) {\n    for (const branchId of branchIds) {\n      if (creditedNodeIdentities.get(identity)?.has(branchId) === true) {\n        continue;\n      }\n      const id = idOf(identity);\n      recordProvenance(\"node\", branchId, id, kindOf(identity), id);\n    }\n  }\n\n  // (7) opt-in ontology type reconciliation over the public-closure glue. Inputs\n  // (incl. base member kinds) were collected per cluster in the canonicalize loop.\n  const reconciliation = reconcileTypes(\n    reconcileInputs,\n    subClassClosure,\n    options.reconcileTypes,\n  );\n  const reconciledClusterByEntityId = new Map<string, ClusterResult>();\n  for (const identity of reconciliation.retypeMap.keys()) {\n    const entityId = idOf(identity);\n    const cluster = clusterByCanonicalIdentity.get(identity);\n    if (cluster !== undefined && !reconciledClusterByEntityId.has(entityId)) {\n      reconciledClusterByEntityId.set(entityId, cluster);\n    }\n  }\n  const typeReconciliations: readonly TypeReconciliation[] =\n    reconciliation.reconciliations.map((item) => {\n      const cluster = reconciledClusterByEntityId.get(item.entityId);\n      return cluster === undefined ? item : (\n          {\n            ...item,\n            decisiveEdges: decisiveEdgesForCluster(cluster, survivingEdges),\n          }\n        );\n    });\n\n  // (8) repoint every staged edge onto its cluster canonical + dedupe. Index the\n  // canonical entities by their `(kind, id)` ONCE so the per-cluster survivor\n  // lookup is O(1) — a linear scan per cluster would make the map build\n  // O(clusters × entities), quadratic over the merged-node universe.\n  const entityByIdentity = new Map<MergeKey, CanonicalEntity>();\n  for (const entity of canonicalEntities) {\n    entityByIdentity.set(mergeKey(entity.kind, entity.canonicalId), entity);\n  }\n  const canonicalOf = buildCanonicalMap(clusters, (cluster) =>\n    pickClusterCanonical(cluster, entityByIdentity),\n  );\n  const canonicalEndpointWindows = new Map<\n    MergeKey,\n    Readonly<{ validFrom?: string; validTo?: string }>\n  >();\n  for (const entity of canonicalEntities) {\n    if (\n      entity.endpointValidFrom === undefined &&\n      entity.endpointValidTo === undefined\n    ) {\n      continue;\n    }\n    const sourceKey = mergeKey(entity.kind, entity.canonicalId);\n    const finalKind = reconciliation.retypeMap.get(sourceKey) ?? entity.kind;\n    canonicalEndpointWindows.set(mergeKey(finalKind, entity.canonicalId), {\n      ...(entity.endpointValidFrom === undefined ?\n        {}\n      : { validFrom: entity.endpointValidFrom }),\n      ...(entity.endpointValidTo === undefined ?\n        {}\n      : { validTo: entity.endpointValidTo }),\n    });\n  }\n  // Repoint identity-assertion endpoints through the same canonical + retype maps\n  // the edges use, so an assertion naming a folded or retyped branch node\n  // references its survivor instead of a dangling `(kind, id)` the commit-time\n  // endpoint guard would reject. The two guards that follow turn the remaining\n  // commit-time identity failures into deterministic plan-time conflicts.\n  const identityRemap = remapIdentityAssertionEndpoints(\n    identity.assertions,\n    canonicalOf,\n    reconciliation.retypeMap,\n    storedIdentityRowsById,\n    canonicalEndpointWindows,\n  );\n  assertIdentityEndpointsNotDeleted(\n    identityRemap.assertions,\n    nodeDeletions,\n    reconciliation.retypeMap,\n  );\n  // Each canonical entity enters the universe under the kind the commit will\n  // actually WRITE — the retyped one when the ontology cascade retypes it —\n  // while its deletion check runs against the source identity, which is how\n  // `nodeDeletions` is keyed.\n  const identityNodeUniverse = [\n    ...canonicalEntities\n      .filter(\n        (entity) =>\n          !nodeDeletions.has(mergeKey(entity.kind, entity.canonicalId)),\n      )\n      .map((entity) => ({\n        kind:\n          reconciliation.retypeMap.get(\n            mergeKey(entity.kind, entity.canonicalId),\n          ) ?? entity.kind,\n        id: entity.canonicalId,\n      })),\n    ...targetPeers.filter(\n      (node) => !nodeDeletions.has(mergeKey(node.kind, node.id)),\n    ),\n  ];\n  assertNoContradictoryIdentityClosure(\n    identityRemap.assertions,\n    survivingRetractions.map((retraction) => retraction.id),\n    staging.baseIdentityAssertions,\n    new Set(nodeDeletions.keys()),\n    canonicalOf,\n    reconciliation.retypeMap,\n    identityContext,\n    identityNodeUniverse,\n  );\n  const { edges: stagedEdges, windowOnlyCarried } = buildStagedEdges(\n    staging,\n    reconciledEdgeModifications.survivingModifications,\n    validWindows.edgeEnds,\n    edgeDeletions,\n  );\n  // An edge id can be staged by MORE THAN ONE branch (e.g. an inherited edge\n  // modified by two branches), so map each id to the SET of contributing branches.\n  // A plain last-write Map would credit only one branch's provenance.\n  //\n  // A branch that authored the row's committed END is a contributor too, and the\n  // staged copy cannot name it: an identity is staged ONCE, so a branch whose only\n  // change is the window has no copy of its own whenever another branch's props\n  // edit already staged the row (issue #402). Folding the window authors in here —\n  // from the resolution that chose the end — credits them against the SURVIVING\n  // edge the repoint decides, exactly as a modifying branch is credited, and a\n  // `Set` keeps a branch that both edited props and moved the window one\n  // contributor.\n  //\n  // A WINDOW-ONLY CARRIER is the exception: that copy exists only to give the\n  // ending a row to ride on, its props are the base's, and the branch holding it\n  // is whichever sorted first — possibly one whose later claim the merge\n  // discarded. Crediting it would name a branch that put nothing in the committed\n  // row, so the row's credit comes from the resolution alone.\n  const stagedEdgeBranches = new Map<string, Set<BranchId>>();\n  for (const staged of stagedEdges) {\n    const identity = mergeKeyOf(staged);\n    const branches = stagedEdgeBranches.get(staged.id) ?? new Set<BranchId>();\n    if (!windowOnlyCarried.has(identity)) {\n      branches.add(staged.branchId);\n    }\n    for (const branchId of validWindows.edgeCredits.get(identity) ?? []) {\n      branches.add(branchId);\n    }\n    stagedEdgeBranches.set(staged.id, branches);\n  }\n  const deletedNodeIdSet = new Set<MergeKey>(nodeDeletions.keys());\n  const repoint = repointEdges<G>(\n    stagedEdges,\n    canonicalOf,\n    deletedNodeIdSet,\n    options.onPropertyConflict,\n    branchRank,\n    weights,\n    preferredBranchId,\n  );\n  for (const merged of repoint.edges) {\n    for (const sourceId of merged.mergedIds) {\n      for (const branchId of stagedEdgeBranches.get(sourceId) ?? []) {\n        recordProvenance(\"edge\", branchId, merged.id, merged.kind, sourceId);\n      }\n    }\n  }\n\n  const dropped: DroppedItem[] = [\n    ...deleteModify.dropped,\n    ...edgeDeleteModify.dropped,\n    ...repoint.dropped,\n    ...reconciliation.dropped,\n    ...identity.dropped,\n    ...overruledRetractionDrops,\n    ...identityRemap.dropped,\n    ...validWindows.dropped,\n  ].sort((left, right) =>\n    compareStrings(`${left.kind}|${left.id}`, `${right.kind}|${right.id}`),\n  );\n\n  return {\n    canonicalEntities,\n    survivingModifications: reconciledModifications.survivingModifications,\n    nodeDeletions,\n    edgeDeletions,\n    mergedEdges: repoint.edges,\n    inheritedEdgeBaseProps: new Map(\n      reconciledEdgeModifications.survivingModifications.map((modification) => [\n        modification.edge.id,\n        modification.edge.baseProps,\n      ]),\n    ),\n    retypeMap: reconciliation.retypeMap,\n    canonicalOf,\n    nodeValidityEnds: validWindows.nodeEnds,\n    edgeValidityEnds: validWindows.edgeEnds,\n    validityEnds: validWindows.resolutions,\n    // Order report arrays by the composite (kind, id) identity — never a bare id\n    // or a `|`-joined string. A bare id ties two different-kind entities that\n    // share an id, and a `|` separator collides on caller-supplied ids/property\n    // names that contain `|`; either makes the comparator non-total, so the\n    // returned order would depend on stable-sort + insertion order and break the\n    // order-independence the whole subsystem guarantees.\n    resolutions: resolutions.sort((left, right) =>\n      compareMergeKeys(\n        mergeKey(left.kind, left.canonicalId),\n        mergeKey(right.kind, right.canonicalId),\n      ),\n    ),\n    propertyConflicts: [...propertyConflicts, ...repoint.conflicts].sort(\n      (left, right) => {\n        const byEntity = compareMergeKeys(\n          mergeKey(left.kind, left.entityId),\n          mergeKey(right.kind, right.entityId),\n        );\n        return byEntity === 0 ?\n            compareStrings(left.property, right.property)\n          : byEntity;\n      },\n    ),\n    deleteModifyConflicts: [\n      ...deleteModify.conflicts,\n      ...edgeDeleteModify.conflicts,\n    ].sort((left, right) =>\n      compareMergeKeys(\n        mergeKey(left.kind, left.entityId),\n        mergeKey(right.kind, right.entityId),\n      ),\n    ),\n    typeReconciliations,\n    dropped,\n    baseAmbiguities: baseAmbiguities.sort((left, right) =>\n      compareMergeKeys(\n        mergeKey(\n          requireDefined(left.baseIds[0]).kind,\n          requireDefined(left.baseIds[0]).id,\n        ),\n        mergeKey(\n          requireDefined(right.baseIds[0]).kind,\n          requireDefined(right.baseIds[0]).id,\n        ),\n      ),\n    ),\n    provenanceRecords,\n    warnings: [...candidateWarnings, ...identityRemap.warnings],\n    ...(options.candidateDiagnostics === undefined ?\n      {}\n    : {\n        candidateDiagnostics: {\n          entries: retainedDiagnostics.slice(\n            0,\n            options.candidateDiagnostics.limit,\n          ),\n          total: candidateDiagnosticsTotal + definitionalExclusions.length,\n          limit: options.candidateDiagnostics.limit,\n          truncated:\n            candidateDiagnosticsTotal + definitionalExclusions.length >\n            options.candidateDiagnostics.limit,\n        },\n      }),\n    identityAssertions: identityRemap.assertions,\n    identityRetractions: survivingRetractions,\n  };\n}\n\n/**\n * The canonical survivor identity of a cluster, taken DIRECTLY from its already-resolved\n * {@link CanonicalEntity} so edge repoint reuses the exact survivor `canonicalizeCluster`\n * chose (base-id-wins, the `options.canonical` hook, and the most-specific-kind pick all\n * already applied there). This is the SINGLE survivor-selection point: re-deriving it\n * here by a second rule could split the canonical between the node write and the edge\n * repoint, so this never re-runs the hook.\n *\n * Every non-empty cluster yields exactly one canonical entity whose `(kind, id)` is one\n * of its members (the survivor is always a cluster member), so the lookup always hits;\n * a miss is an internal invariant violation, not a fallback.\n *\n * `entityByIdentity` maps each canonical entity's `(kind, id)` → entity, built once by\n * the caller, so finding a cluster's survivor is O(cluster.members) rather than a scan\n * of every canonical entity.\n */\nfunction pickClusterCanonical(\n  cluster: ClusterResult,\n  entityByIdentity: ReadonlyMap<MergeKey, CanonicalEntity>,\n): MergeKey {\n  for (const member of cluster.members) {\n    if (entityByIdentity.has(member)) {\n      return member;\n    }\n  }\n  throw new MergeError(\n    \"Internal invariant: cluster has no canonical entity in pickClusterCanonical.\",\n    { details: { members: cluster.members.map((member) => idOf(member)) } },\n  );\n}\n\n/**\n * Builds the prop bag to COMMIT for an inherited modification, HONORING property\n * deletions. A fork's `forkProps` is its full intended state, so a base property\n * ABSENT from it was removed by that fork. The commit upsert shallow-merges the\n * written props onto the existing (base) row, so a removed key would otherwise\n * survive; writing it as `undefined` makes the row write drop it (the props column\n * is JSON-serialized, which omits `undefined`), so the fork's deletion is applied\n * instead of being silently reverted to the base value.\n *\n * The bag is null-prototype ({@link createDataKeyedBag}) because its keys are\n * DATA — property names read off committed rows, and `trustedImportGraph`\n * writes a caller's bag verbatim, so a stored bag CAN carry an own `__proto__`\n * (`JSON.parse` mints it as ordinary own data). Writing the deletion marker for\n * that key into a `{}` literal does not create an entry: it invokes\n * `Object.prototype`'s `__proto__` setter, which with `undefined` as the value\n * is a silent no-op. The tombstone this function exists to write would simply\n * not be written.\n *\n * SCOPE OF THE CLAIM, measured rather than assumed: no reachable write carries\n * an own `__proto__` back into a committed row anyway — Zod drops the key in\n * strip AND loose mode, so the base value does not survive a merge commit with\n * or without the tombstone, and `branch()`'s validating clone refuses such a\n * base outright. So this is the function honoring its own contract\n * independently of what a distant layer happens to strip, NOT a user-visible\n * defect being fixed: the end state is currently identical either way, which is\n * why no end-to-end test guards it (one would pass under the mutation). The\n * live-ammunition key for the deletion contract is a DECLARED prototype-named\n * field such as `toString`, which this file's tests cover.\n */\nfunction commitModificationProps(\n  baseProps: Readonly<Record<string, unknown>>,\n  forkProps: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n  const props = createDataKeyedBag<unknown>();\n  for (const key of Object.keys(forkProps)) {\n    props[key] = forkProps[key];\n  }\n  for (const key of Object.keys(baseProps)) {\n    if (!hasOwnKey(forkProps, key)) {\n      props[key] = undefined;\n    }\n  }\n  return props;\n}\n\n/**\n * The `(kind, id)` an edge endpoint finally carries in the committed target: its\n * own kind unless the ontology retype cascade reconciled that identity to a more\n * specific one. Every consumer — the commit's edge upserts, the write signature,\n * and the incremental endpoint guard — resolves endpoints through here, so a\n * guard can never compare a pre-retype endpoint against a post-retype row.\n */\nfunction finalEdgeEndpoint<G extends GraphDef>(\n  plan: MergePlan<G>,\n  kind: string,\n  id: AnyNodeId,\n): Readonly<{ kind: string; id: AnyNodeId }> {\n  return { kind: plan.retypeMap.get(mergeKey(kind, id)) ?? kind, id };\n}\n\n/**\n * One node row a plan writes: the identity it lands on, the canonical cluster\n * entity it came from (absent for a modification-only write), and the surviving\n * inherited modification folded into it (absent when nothing modified the row).\n *\n * A write with NEITHER is a window-only write: an inherited row whose sole\n * change is its reconciled end-of-validity. It carries no props, and the upsert\n * patch-merges, so it moves the row's window and nothing else.\n */\ntype PlannedNodeWrite = Readonly<{\n  identity: MergeKey;\n  kind: string;\n  id: AnyNodeId;\n  entity?: CanonicalEntity;\n  modification?: ModifiedNode;\n  /**\n   * The valid-time window the write carries. `validFrom` comes only from a\n   * staged canonical survivor (the commit cannot move a live row's lower bound\n   * — see `valid-window.ts`); `validTo` is the survivor's authored end, or, for\n   * an inherited row, the reconciled end-of-validity. Absent means \"do not touch\n   * the committed window\", which is what lets an otherwise-unchanged write\n   * coalesce.\n   */\n  validFrom?: string | null;\n}> &\n  ValidityEndMutation;\n\n/**\n * THE node-write enumeration: every node row a resolved plan writes, in commit\n * order — surviving inherited modifications first, then canonical cluster\n * survivors. Both the commit ({@link applyMergePlan}) and the incremental write\n * guards consume this one function, so which rows a plan touches, which are\n * skipped (finally deleted, or folded into a canonical write), and which kind\n * the retype cascade lands them on are decided in exactly one place. The\n * consumers differ only in how they derive the final props from each write; see\n * {@link nodeWriteProps}.\n *\n * A canonical survivor can ALSO be an inherited modification. Its two writes are\n * folded into one — the standalone modification write is skipped and the entity\n * carries the modification — because the canonical upsert is built from the\n * cluster union, which holds the OLDER base props and would otherwise clobber\n * the fork's edit.\n */\nfunction plannedNodeWrites<G extends GraphDef>(\n  plan: MergePlan<G>,\n): readonly PlannedNodeWrite[] {\n  const canonicalIdentities = new Set<MergeKey>();\n  for (const entity of plan.canonicalEntities) {\n    canonicalIdentities.add(mergeKey(entity.kind, entity.canonicalId));\n  }\n  const modificationsByIdentity = new Map<MergeKey, ModifiedNode>();\n  for (const modification of plan.survivingModifications) {\n    modificationsByIdentity.set(\n      mergeKeyOf(modification.node),\n      modification.node,\n    );\n  }\n\n  const writes: PlannedNodeWrite[] = [];\n  const written = new Set<MergeKey>();\n  for (const modification of plan.survivingModifications) {\n    const identity = mergeKeyOf(modification.node);\n    if (plan.nodeDeletions.has(identity) || canonicalIdentities.has(identity)) {\n      continue;\n    }\n    written.add(identity);\n    const validToChange = plan.nodeValidityEnds.get(identity);\n    writes.push({\n      identity,\n      kind: modification.node.kind,\n      id: modification.node.id,\n      modification: modification.node,\n      ...(validToChange?.kind === \"set\" ? { validTo: validToChange.validTo }\n      : validToChange?.kind === \"clear\" ? { clearValidTo: true as const }\n      : {}),\n    });\n  }\n  for (const entity of plan.canonicalEntities) {\n    // The retype cascade is keyed on the PRE-retype identity, as is the\n    // modification fold: both index the entity as the plan staged it.\n    const sourceIdentity = mergeKey(entity.kind, entity.canonicalId);\n    if (plan.nodeDeletions.has(sourceIdentity)) {\n      continue;\n    }\n    const kind = plan.retypeMap.get(sourceIdentity) ?? entity.kind;\n    const modification = modificationsByIdentity.get(sourceIdentity);\n    written.add(sourceIdentity);\n    // A staged survivor's own authored window is the canonicalize decision —\n    // including the committed-target precedence that module applies — so it\n    // takes priority. The reconciled inherited end fills in only where the\n    // survivor claims no end of its own.\n    const validToChange = plan.nodeValidityEnds.get(sourceIdentity);\n    writes.push({\n      identity: mergeKey(kind, entity.canonicalId),\n      kind,\n      id: entity.canonicalId,\n      entity,\n      ...(modification === undefined ? {} : { modification }),\n      ...(entity.validFrom === undefined ?\n        {}\n      : { validFrom: entity.validFrom }),\n      ...(typeof entity.validTo === \"string\" ? { validTo: entity.validTo }\n      : validToChange?.kind === \"set\" ? { validTo: validToChange.validTo }\n      : validToChange?.kind === \"clear\" ? { clearValidTo: true as const }\n      : {}),\n    });\n  }\n  // An inherited row whose ONLY change is its end-of-validity has neither a\n  // surviving modification nor a canonical entity, so it has no write yet. It\n  // gets one carrying the ending and NO props: the upsert patch-merges, so an\n  // empty bag leaves the row's content exactly as committed. Sorted by identity\n  // so the enumeration stays a pure function of the plan.\n  for (const identity of [...plan.nodeValidityEnds.keys()].sort((left, right) =>\n    compareMergeKeys(left, right),\n  )) {\n    if (written.has(identity) || plan.nodeDeletions.has(identity)) {\n      continue;\n    }\n    const kind = plan.retypeMap.get(identity) ?? kindOf(identity);\n    const validToChange = requireDefined(plan.nodeValidityEnds.get(identity));\n    writes.push({\n      identity: mergeKey(kind, idOf(identity)),\n      kind,\n      id: idOf(identity),\n      ...(validToChange.kind === \"set\" ?\n        { validTo: validToChange.validTo }\n      : { clearValidTo: true as const }),\n    });\n  }\n  return writes;\n}\n\n/**\n * Folds a planned write's sources into the prop bag to write, with the caller\n * supplying the only piece that differs between them: how a folded modification\n * contributes. The commit honors the fork's property DELETIONS (see\n * {@link commitModificationProps}); the incremental guard compares against the\n * fork's raw intended state. Modification props land ON TOP of the cluster\n * union so an explicit fork edit is never lost to the (older) base props the\n * union carried.\n */\nfunction nodeWriteProps(\n  write: PlannedNodeWrite,\n  modificationProps: (\n    modification: ModifiedNode,\n  ) => Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n  return {\n    ...write.entity?.props,\n    ...(write.modification === undefined ?\n      undefined\n    : modificationProps(write.modification)),\n  };\n}\n\ntype NodeWriteWindowOptions = Readonly<{ validFrom?: string | null }> &\n  ValidityEndMutation;\n\n/** Converts the plan's explicit set/clear state into the collection option union. */\nfunction nodeWriteWindowOptions(\n  write: NodeWriteWindowOptions,\n): NodeWriteWindowOptions {\n  const validFrom =\n    write.validFrom === undefined ? {} : { validFrom: write.validFrom };\n  if (write.clearValidTo === true) {\n    return { ...validFrom, clearValidTo: true };\n  }\n  return {\n    ...validFrom,\n    ...(write.validTo === undefined ? {} : { validTo: write.validTo }),\n  };\n}\n\ntype MechanicalNodeWrite = Readonly<{\n  kind: string;\n  id: string;\n  props: Readonly<Record<string, unknown>>;\n  validFrom?: string | null;\n}> &\n  ValidityEndMutation;\n\ntype MechanicalEdgeWrite = Readonly<{\n  kind: string;\n  item: EdgeUpsert;\n}>;\n\nasync function applyNodeRows<G extends GraphDef>(\n  target: Store<G>,\n  txBackend: TransactionBackend,\n  nodesApi: TxNodes,\n  deletions: readonly MergePlanEntityRef[],\n  upserts: readonly MechanicalNodeWrite[],\n): Promise<number> {\n  const afterImages = new Map<MergeKey, Readonly<Record<string, unknown>>>();\n  const upsertsByKind = new Map<string, MechanicalNodeWrite[]>();\n  for (const upsert of upserts) {\n    const items = upsertsByKind.get(upsert.kind);\n    if (items === undefined) upsertsByKind.set(upsert.kind, [upsert]);\n    else items.push(upsert);\n  }\n  for (const [kind, items] of upsertsByKind) {\n    const currentRows = await nodeCollection(nodesApi, kind).getByIds(\n      items.map((item) => item.id),\n      INCLUDE_TOMBSTONES,\n    );\n    const currentById = new Map<string, Readonly<Record<string, unknown>>>();\n    for (const node of currentRows) {\n      if (node !== undefined) currentById.set(node.id, nodeProps(node));\n    }\n    for (const item of items) {\n      const props = createDataKeyedBag<unknown>();\n      const unset = new Set(\n        Object.entries(item.props)\n          .filter(([, value]) => value === undefined)\n          .map(([key]) => key),\n      );\n      for (const [key, value] of Object.entries(\n        currentById.get(item.id) ?? {},\n      )) {\n        if (!unset.has(key)) props[key] = value;\n      }\n      for (const [key, value] of Object.entries(item.props)) {\n        if (value !== undefined) props[key] = value;\n      }\n      afterImages.set(mergeKey(kind, item.id), props);\n    }\n  }\n  return storeRuntime(target).applyResolvedNodeUniqueness(\n    txBackend,\n    {\n      upserts: upserts.map((upsert) => ({\n        kind: upsert.kind,\n        id: upsert.id,\n        props: requireDefined(\n          afterImages.get(mergeKey(upsert.kind, upsert.id)),\n        ),\n      })),\n      releases: deletions,\n    },\n    async () => {\n      for (const deletion of deletions) {\n        await nodeCollection(nodesApi, deletion.kind).delete(deletion.id);\n      }\n      const committed = new Set<MergeKey>();\n      for (const upsert of upserts) {\n        await nodeCollection(nodesApi, upsert.kind).upsertByIdFromRecord(\n          upsert.id,\n          upsert.props,\n          nodeWriteWindowOptions(upsert),\n        );\n        committed.add(mergeKey(upsert.kind, upsert.id));\n      }\n      return committed.size;\n    },\n  );\n}\n\nasync function applyEdgeRows(\n  edgesApi: TxEdges,\n  deletions: readonly MergePlanEntityRef[],\n  upserts: readonly MechanicalEdgeWrite[],\n): Promise<number> {\n  for (const deletion of deletions) {\n    await edgeCollection(edgesApi, deletion.kind).delete(deletion.id);\n  }\n  const byKind = new Map<string, EdgeUpsert[]>();\n  for (const upsert of upserts) {\n    const items = byKind.get(upsert.kind);\n    if (items === undefined) byKind.set(upsert.kind, [upsert.item]);\n    else items.push(upsert.item);\n  }\n  let committed = 0;\n  for (const [kind, items] of byKind) {\n    await edgeCollection(edgesApi, kind).bulkUpsertById(items);\n    committed += items.length;\n  }\n  return committed;\n}\n\nasync function applyIdentityRows<G extends GraphDef>(\n  target: Store<G>,\n  txBackend: TransactionBackend,\n  assertions: readonly IdentityTransferAssertion[],\n  retractions: readonly IdentityTransferAssertion[],\n  assertConsistent?: () => Promise<void>,\n): Promise<Readonly<{ asserted: number; retracted: number }>> {\n  try {\n    const applied = await storeRuntime(target).applyIdentityMergeAtTarget(\n      txBackend,\n      retractions,\n      assertions,\n    );\n    if (assertConsistent !== undefined) await assertConsistent();\n    return { asserted: applied.created, retracted: applied.retracted };\n  } catch (error) {\n    throw translateIdentityCommitError(error);\n  }\n}\n\n/**\n * Applies a resolved {@link MergePlan} through a transaction's collection API.\n * Shared by `commitPlan()` and the guarded `mergeIncremental()` commit path so\n * both modes execute the same resolved semantics.\n */\nasync function applyInternalMergePlan<G extends GraphDef>(\n  plan: MergePlan<G>,\n  nodesApi: TxNodes,\n  edgesApi: TxEdges,\n  target: Store<G>,\n  txBackend: TransactionBackend,\n): Promise<MergedCounts> {\n  const nodeDeletions = [...plan.nodeDeletions].map(([identity, kind]) => ({\n    kind,\n    id: idOf(identity),\n  }));\n  const nodeUpserts = plannedNodeWrites(plan).map((write) => ({\n    kind: write.kind,\n    id: write.id,\n    props: nodeWriteProps(write, (modification) =>\n      commitModificationProps(modification.baseProps, modification.forkProps),\n    ),\n    ...(write.validFrom === undefined ? {} : { validFrom: write.validFrom }),\n    ...(write.clearValidTo === true ? { clearValidTo: true as const }\n    : write.validTo === undefined ? {}\n    : { validTo: write.validTo }),\n  }));\n  const validityEndedNodes = new Set(\n    nodeUpserts\n      .filter((write) => \"validTo\" in write)\n      .map((write) => mergeKey(write.kind, write.id)),\n  );\n  const earlyIdentityRetractions = plan.identityRetractions.filter(\n    (retraction) =>\n      validityEndedNodes.has(mergeKeyOf(retraction.a)) ||\n      validityEndedNodes.has(mergeKeyOf(retraction.b)),\n  );\n  const earlyIdentity = await applyIdentityRows(\n    target,\n    txBackend,\n    [],\n    earlyIdentityRetractions,\n  );\n  let committedNodes: number;\n  try {\n    committedNodes = await applyNodeRows(\n      target,\n      txBackend,\n      nodesApi,\n      nodeDeletions,\n      nodeUpserts,\n    );\n  } catch (error) {\n    throw error instanceof IdentityEndpointValidityError ?\n        translateIdentityCommitError(error)\n      : error;\n  }\n\n  const edgeDeletions = [...plan.edgeDeletions].map(([identity, kind]) => ({\n    kind,\n    id: idOf(identity),\n  }));\n  const edgeUpserts: MechanicalEdgeWrite[] = [];\n  for (const edge of plan.mergedEdges) {\n    // Honor a fork's property deletion on an inherited edge: drop base keys absent\n    // from the merged props (the edge upsert PATCH-merges, so a removed key would\n    // otherwise survive). New edges have no base entry, so their props pass through.\n    const edgeBaseProps = plan.inheritedEdgeBaseProps.get(edge.id);\n    const props =\n      edgeBaseProps === undefined ?\n        edge.props\n      : commitModificationProps(edgeBaseProps, edge.props);\n    // A staged edge's valid-time window travels with the write, mirroring the\n    // canonical-entity upsert above: on a fresh insert it IS the branch's\n    // window, on a resurrection it stops the upsert from resetting a\n    // branch-authored (possibly already ENDED) window to merge time, and on an\n    // inherited edge it is the reconciled end-of-validity. An edge with no\n    // window leaves its committed one untouched.\n    edgeUpserts.push({\n      kind: edge.kind,\n      item: {\n        id: edge.id,\n        from: finalEdgeEndpoint(plan, edge.fromKind, edge.fromId),\n        to: finalEdgeEndpoint(plan, edge.toKind, edge.toId),\n        props,\n        ...(edge.validFrom === undefined ? {} : { validFrom: edge.validFrom }),\n        ...(edge.clearValidTo === true ? { clearValidTo: true as const }\n        : edge.validTo === undefined ? {}\n        : { validTo: edge.validTo }),\n      },\n    });\n  }\n  const committedEdges = await applyEdgeRows(\n    edgesApi,\n    edgeDeletions,\n    edgeUpserts,\n  );\n\n  // The IDENTITY-APPLIER boundary: any refusal from the apply below is an\n  // identity statement by construction, so it is translated into the typed\n  // conflict error here — the completeness backstop for applier invariants\n  // the plan-time simulation does not (yet) mirror.\n  //\n  // The post-write assertion shares the boundary because it is the same kind\n  // of statement, made one step later: with every node, edge and identity\n  // write of this merge in place, the affected identity classes must carry no\n  // contradiction. It is what makes the committed ledger correct independently\n  // of the plan-time simulation, and it runs for BOTH commit modes because\n  // both commit through here.\n  const appliedIdentity = await applyIdentityRows(\n    target,\n    txBackend,\n    plan.identityAssertions,\n    plan.identityRetractions,\n    () => assertMergedIdentityClassesConsistent(target, txBackend, plan),\n  );\n\n  return {\n    nodes: committedNodes,\n    edges: committedEdges,\n    // ACTUAL ledger effects from the applier: rows created (idempotent\n    // exact/pair matches the target already held are excluded — the normal\n    // incremental case, where the target's own additions are staged back at\n    // it) and rows ended (already-ended or unknown ids excluded). Any apply\n    // failure aborts the whole merge, so the counts never describe a\n    // partial commit.\n    identity: {\n      asserted: appliedIdentity.asserted,\n      retracted: earlyIdentity.retracted + appliedIdentity.retracted,\n    },\n  };\n}\n\n/**\n * Attempt budget for every merge commit transaction. A serialization failure\n * or deadlock aborts the whole transaction with nothing committed, so\n * re-running it from the top (the documented PostgreSQL protocol for both) is\n * safe; three attempts absorbs the occasional lost race without masking a\n * genuinely contended target.\n */\nconst MERGE_COMMIT_ATTEMPTS = 3;\n\n/**\n * Applies a resolved {@link MergePlan} to the target via the typed transaction\n * collection API. Surviving inherited modifications are upserted by id, canonical\n * cluster nodes are upserted by id with their unioned + (optionally) retyped\n * props, finally-deleted nodes are soft-deleted, and repointed/deduped edges are\n * upserted by id. Returns the merged node / edge counts.\n *\n * UPDATE-NOT-INSERT (§6.2): every node write is an `upsertById`, so a canonical\n * entity whose id is an ALREADY-COMMITTED base node UPDATES that committed row in\n * place — the committed identity is stable and every edge repointed onto it (the\n * merged edges already carry the canonical endpoint) attaches to the surviving\n * row, never a duplicate insert. This is what lets a base member be the canonical\n * survivor once base sources land. Exported for isolated commit-path testing.\n *\n * COALESCE INTERACTION: when the target store was created with\n * `coalesceUnchangedUpserts`, a canonical/inherited upsert whose props already\n * equal the committed row is skipped (no write, no recorded row). This is sound\n * for merge and needs no bypass: the base@V guard runs BEFORE any upsert\n * (see {@link assertTargetUnchanged}), conflicts are resolved at plan time, and\n * an upsert-by-id never rewrites endpoints — so coalescing only elides writes\n * that would persist a byte-identical value, leaving the merged state\n * identical. It merely declines to re-stamp recorded time on rows the merge did\n * not actually change, which is exactly the option's intent.\n */\nexport async function commitPlan<G extends GraphDef>(\n  target: Store<G>,\n  plan: MergePlan<G>,\n  expectedBaseVersion?: BaseVersion,\n): Promise<MergedCounts> {\n  if (!storeBackend(target).capabilities.execution.interactiveTransactions) {\n    throw new MergeError(\n      \"merge() requires a transaction-capable target backend. The merged plan (canonical upserts, soft-deletes, edge upserts) must commit atomically; a non-transactional fallback would leave a partially-merged graph on a mid-commit failure. (mergeIncremental() enforces the same requirement.)\",\n      { details: { capability: \"execution.interactiveTransactions\" } },\n    );\n  }\n  return runMergeCommit(() =>\n    runRetriedUnit(\n      {\n        operation: \"commitPlan\",\n        attempts: MERGE_COMMIT_ATTEMPTS,\n        target: storeBackend(target),\n      },\n      () =>\n        target.transaction(async (tx) => {\n          // TOCTOU guard: the plan was resolved from reads taken OUTSIDE this\n          // transaction, so the target may have been written between the base@V\n          // precondition and this commit. Revision-anchored stores check their\n          // durable clock under the graph write lock; legacy stores re-derive the\n          // content fingerprint through this transaction's snapshot. Either proof\n          // ensures the plan still describes the live target before committing.\n          if (expectedBaseVersion !== undefined) {\n            await assertTargetUnchanged(\n              transactionBackend(tx),\n              target,\n              expectedBaseVersion,\n            );\n          }\n          // Identity ids are re-validated EXPLICITLY even under a base@V match:\n          // the legacy fingerprint ranges over CURRENT assertions only, so a row\n          // that claimed a planned id in the window and was then ended would pass\n          // the token check and fail generically inside the applier.\n          await assertPlannedIdentityIdsFresh(\n            target,\n            transactionBackend(tx),\n            plan,\n          );\n          return applyInternalMergePlan(\n            plan,\n            tx.nodes as unknown as TxNodes,\n            tx.edges as unknown as TxEdges,\n            target,\n            transactionBackend(tx),\n          );\n        }, mergeCommitTransactionOptions(target)),\n    ),\n  );\n}\n\n/** Runs one atomic commit while preserving the merge boundary's error taxonomy. */\nasync function runMergeCommit<Output>(\n  commit: () => Promise<Output>,\n): Promise<Output> {\n  try {\n    return await commit();\n  } catch (error) {\n    throw translateMergeCommitError(error);\n  }\n}\n\n/**\n * Isolation for the merge commit transaction. SERIALIZABLE closes the window\n * between the in-transaction re-validation reads and COMMIT on multi-writer\n * Postgres (SSI aborts a racing writer with SQLSTATE 40001, which\n * {@link file://../backend/capabilities/retried-unit.ts runRetriedUnit} retries); SQLite and\n * PGlite serialize writers by construction, and the SQLite backend ignores\n * the option.\n */\nconst MERGE_COMMIT_TX_OPTIONS = {\n  isolationLevel: \"serializable\",\n} as const satisfies TransactionOptions;\n\nfunction mergeCommitTransactionOptions<G extends GraphDef>(\n  target: Store<G>,\n): TransactionOptions | undefined {\n  // Recorded-time capture only supports read-committed transactions because it\n  // allocates its durable clock inside the write transaction. Revision-anchored\n  // merges hold that same per-graph lock before checking the anchor, which\n  // closes the TOCTOU gap without asking a history store for SERIALIZABLE.\n  //\n  // `storeCaptureEnabled`, not the public `historyEnabled` getter: the\n  // \"durable clock allocated inside this transaction\" rationale is specific\n  // to TypeGraph's own capture. An engine-native `history: true` store never\n  // allocates anything here — `revisionNow` just reads the committing\n  // session — so it takes the SAME SERIALIZABLE path a non-capturing store\n  // does, unchanged from before this store had a public `historyEnabled`\n  // that could answer `true` for it.\n  return storeCaptureEnabled(target) ? undefined : MERGE_COMMIT_TX_OPTIONS;\n}\n\n/**\n * What an engine-anchor mismatch looks like, once `changesSince` has been\n * consulted and found the anchor genuinely stale — never constructed for an\n * equal revision or an empty delta, both of which are \"unchanged\".\n */\ntype EngineAnchorMismatch = Readonly<{\n  liveRevision: EngineRevision;\n  delta: LineageDelta;\n}>;\n\n/**\n * THE changed-since predicate every engine-anchored base@V guard shares\n * (`assertTargetUnchanged` and `assertForkPointUnchanged`): equal revisions\n * are the O(1) fast path; on a mismatch, `changesSince` scopes the\n * engine-wide bump to `graphId` — empty keys mean the bump landed on a\n * different graph and the anchor is still good (returns `undefined`),\n * anything else (including `unbounded`) is a real divergence the caller\n * must refuse. `session` is the caller's own pinned execution target,\n * forwarded to both `lineage` calls unchanged — see `LineageMembers`' own\n * doc for why a call site never reads `lineage` on one connection and asks\n * it to answer for another.\n */\nasync function engineAnchorMismatch(\n  lineage: LineageMembers,\n  session: LineageSession,\n  graphId: string,\n  expectedRevision: EngineRevision,\n): Promise<EngineAnchorMismatch | undefined> {\n  const liveRevision = await lineage.revision(session);\n  if (liveRevision === expectedRevision) return undefined;\n  const delta = await lineage.changesSince(session, expectedRevision, graphId);\n  if (\n    delta.kind === \"keys\" &&\n    delta.nodes.length === 0 &&\n    delta.edges.length === 0\n  ) {\n    return undefined;\n  }\n  return { liveRevision, delta };\n}\n\n/** Caps how many keys {@link boundedChangedKeys} embeds per list. */\nconst CHANGED_KEYS_DETAIL_LIMIT = 20;\n\n/**\n * Caps a `\"keys\"` {@link LineageDelta}'s node/edge lists for inclusion in a\n * thrown `BaseVersionMismatchError`'s `details` bag: the first\n * {@link CHANGED_KEYS_DETAIL_LIMIT} keys of each list, plus that list's own\n * total count. An engine's `changesSince` can legitimately name thousands of\n * rows (a bulk write on an unrelated portion of a large graph); embedding\n * every one of them in a single thrown error would make the error itself\n * the next thing to worry about.\n */\nfunction boundedChangedKeys(\n  delta: Extract<LineageDelta, { kind: \"keys\" }>,\n): Readonly<{\n  nodes: readonly EntityKey[];\n  nodesTotal: number;\n  edges: readonly EntityKey[];\n  edgesTotal: number;\n}> {\n  return {\n    nodes: delta.nodes.slice(0, CHANGED_KEYS_DETAIL_LIMIT),\n    nodesTotal: delta.nodes.length,\n    edges: delta.edges.slice(0, CHANGED_KEYS_DETAIL_LIMIT),\n    edgesTotal: delta.edges.length,\n  };\n}\n\n/**\n * The in-transaction half of the base@V guard: revision-anchored targets read\n * their durable clock under the graph lock; an engine-anchored target\n * re-reads its active schema version through the pinned transaction backend\n * (the one live fact an engine-anchored commit CAN pin, since no lock is\n * held — see the engine branch's own comment) and then consults\n * {@link engineAnchorMismatch} on a raw revision mismatch; legacy targets\n * recompute their content fingerprint through the transaction-scoped\n * backend. The schema HASH itself cannot drift because it is a pure\n * function of the in-memory graph definition — only the monotonic active\n * VERSION baked alongside it can, which is exactly what the engine branch's\n * fresh read catches.\n */\nasync function assertTargetUnchanged<G extends GraphDef>(\n  txBackend: TransactionBackend,\n  target: Store<G>,\n  expectedBaseVersion: BaseVersion,\n): Promise<void> {\n  if (hasRevisionAnchor(expectedBaseVersion)) {\n    // All tracked writers acquire this lock before touching graph rows and\n    // advance the same clock before committing. Holding it around the\n    // read→apply sequence makes the O(1) anchor check a TOCTOU guard without\n    // relying on the transaction's snapshot being the latest committed state.\n    await lockMergeTargetWrite(txBackend, {\n      graphId: target.graphId,\n      schemaVersion: target.introspect().schemaVersion,\n      graphLock: \"required\",\n      staleSchemaError: (cause) =>\n        new BaseVersionMismatchError(\n          \"The merge target schema changed before the commit transaction; the resolved plan was not applied.\",\n          { cause },\n        ),\n    });\n    const originMatch = await revisionOriginMatch(\n      txBackend,\n      target.revisionSchema,\n      target.graphId,\n      expectedBaseVersion,\n    );\n    if (!originMatch.matches) {\n      throw new BaseVersionMismatchError(\n        \"The merge branch was forked from a different revision-tracked store; the resolved plan was not applied.\",\n        {\n          details: {\n            expectedOrigin: originMatch.expectedOrigin,\n            liveOrigin: originMatch.liveOrigin,\n          },\n          suggestion:\n            \"Merge the branch back into its original base store, or fork a new branch from this target.\",\n        },\n      );\n    }\n    const liveRevision = await readRecordedClock(\n      txBackend,\n      target.revisionSchema,\n      target.graphId,\n    );\n    const expectedRevision = revisionAnchorOf(expectedBaseVersion);\n    if (liveRevision !== expectedRevision) {\n      throw new BaseVersionMismatchError(\n        \"The merge target was modified between the revision-anchor check and the commit transaction; the resolved plan was not applied.\",\n        {\n          details: { expectedRevision, liveRevision },\n          suggestion:\n            \"Re-run the merge (and re-branch if the divergence is real), or route all graph writes through the revision-tracked Store.\",\n        },\n      );\n    }\n    return;\n  }\n  const expectedEngineRevision = engineAnchorOf(expectedBaseVersion);\n  if (expectedEngineRevision !== undefined) {\n    // No graph lock here (unlike the revision-anchor branch above): an\n    // engine-anchored store has revision tracking OFF, so no TypeGraph\n    // writer contends for `lockMergeTargetWrite`'s advisory lock in the\n    // first place. SERIALIZABLE (see `mergeCommitTransactionOptions`) still\n    // protects a write THIS transaction's own apply performs against a\n    // concurrent writer, but it has no read-write dependency to abort\n    // against for the planning reads that produced this plan — those ran\n    // OUTSIDE any transaction (see the residual note below `lineage` is\n    // read). The active schema version is re-read here explicitly for the\n    // same reason: nothing about the transaction's isolation level\n    // backstops a schema commit racing the plan, so this is the fast half\n    // of the fencing the revision-anchor branch above gets for free from\n    // `lockMergeTargetWrite`'s `staleSchemaError`.\n    //\n    // The origin check runs FIRST, on this same pinned `txBackend`, before\n    // either the schema re-read or `changesSince` below — the identical\n    // shape and the SAME shared predicate (`revisionOriginMatch`) the\n    // revision-anchor branch above uses. Without it, a branch forked from a\n    // DIFFERENT store whose engine coincidentally reports the same bare\n    // revision string as this target would fall straight through to\n    // `changesSince`, which has no way to tell a genuine anchor from a\n    // numerically coincidental one minted by an unrelated database.\n    const originMatch = await revisionOriginMatch(\n      txBackend,\n      target.revisionSchema,\n      target.graphId,\n      expectedBaseVersion,\n    );\n    if (!originMatch.matches) {\n      throw new BaseVersionMismatchError(\n        \"The merge branch was forked from a different store; the resolved plan was not applied.\",\n        {\n          details: {\n            expectedOrigin: originMatch.expectedOrigin,\n            liveOrigin: originMatch.liveOrigin,\n          },\n          suggestion:\n            \"Merge the branch back into its original base store, or fork a new branch from this target.\",\n        },\n      );\n    }\n    const liveActiveVersion = await readActiveSchemaVersion(\n      txBackend,\n      target.graphId,\n    );\n    const expectedActiveVersion = schemaActiveVersionOf(expectedBaseVersion);\n    if (liveActiveVersion !== expectedActiveVersion) {\n      throw new BaseVersionMismatchError(\n        \"The merge target schema changed before the commit transaction; the resolved plan was not applied.\",\n        {\n          details: { expectedActiveVersion, liveActiveVersion },\n        },\n      );\n    }\n    // `requireLineage(txBackend, …)` reads `lineage` off the PINNED\n    // transaction handle, never `resolveLineage(target)` off the root: this\n    // is the one guard in the whole module that runs its lineage read from\n    // strictly INSIDE the target's own open commit transaction (no advisory\n    // lock pins an engine-anchored store's write path the way a\n    // revision-anchored one is pinned above, so this re-validation is the\n    // only thing standing between the plan and a concurrent write). Passing\n    // `txBackend` as the session to both `revision`/`changesSince` below\n    // makes that pinning real: the read runs on the exact connection this\n    // transaction holds, so it observes the transaction's own snapshot\n    // rather than a separate connection's possibly-different view (see\n    // `LineageMembers`' own doc). A backend whose `lineage` is threaded\n    // through `EngineProvisioning` carries it onto every `transaction()`\n    // handle it builds, so this is the ordinary, expected path. A `lineage`\n    // reachable only through a root-only `deriveBackend` overlay never\n    // reaches a `transaction()` handle that way; `requireLineage` then\n    // refuses with a `ConfigurationError` naming this operation rather than\n    // silently falling back to a different connection's read (see the\n    // \"vanished source\" test in `base-version-engine-anchor.test.ts`). The\n    // residual gap this branch leaves is real and plainly bounded: an\n    // engine-anchored target detects only the changes `changesSince` reports\n    // for THIS graph, read just before commit — it is not backstopped by the\n    // commit transaction's own write set, because the planning reads that\n    // produced this plan happened OUTSIDE any transaction, so SERIALIZABLE\n    // has no read-write dependency on them to abort against. (The legacy\n    // content-fingerprint branch below does not share this gap: it\n    // recomputes its fingerprint through `txBackend` itself, inside the same\n    // transaction whose write set it then collides with.)\n    const lineage = requireLineage(txBackend, \"assertTargetUnchanged\");\n    const mismatch = await engineAnchorMismatch(\n      lineage,\n      txBackend,\n      target.graphId,\n      expectedEngineRevision,\n    );\n    if (mismatch !== undefined) {\n      throw new BaseVersionMismatchError(\n        \"The merge target was modified between the base@V check and the commit transaction; the resolved plan no longer describes the live target and was not applied.\",\n        {\n          details: {\n            expectedRevision: expectedEngineRevision,\n            liveRevision: mismatch.liveRevision,\n            ...(mismatch.delta.kind === \"keys\" ?\n              { changedKeys: boundedChangedKeys(mismatch.delta) }\n            : {}),\n          },\n          suggestion:\n            \"Re-run the merge (and re-branch if the divergence is real), or serialize writers against merges on this target.\",\n        },\n      );\n    }\n    return;\n  }\n  const liveContent = await computeContentComponent(\n    txBackend,\n    target.graphId,\n    target.graph,\n    await storeRuntime(target).identityAssertionsAtTarget(txBackend, \"state\"),\n  );\n  const expectedContent = contentComponentOf(expectedBaseVersion);\n  if (liveContent !== expectedContent) {\n    throw new BaseVersionMismatchError(\n      \"The merge target was modified between the base@V check and the commit transaction; the resolved plan no longer describes the live target and was not applied.\",\n      {\n        details: {\n          expectedContentFingerprint: expectedContent,\n          liveContentFingerprint: liveContent,\n        },\n        suggestion:\n          \"Re-run the merge (and re-branch if the divergence is real), or serialize writers against merges on this target.\",\n      },\n    );\n  }\n}\n\n/**\n * Runtime-keyed view of the transaction's node collections. The typed\n * `tx.nodes` is keyed by the graph's concrete kinds; the orchestrator dispatches\n * on kind STRINGS, so it indexes through this widened record. Each entry exposes\n * the subset of the collection API the commit uses.\n */\ntype TxNodes = Record<string, NodeCollectionLike>;\n\n/** Runtime-keyed view of the transaction's edge collections. See {@link TxNodes}. */\ntype TxEdges = Record<string, EdgeCollectionLike>;\n\n/** The node-collection surface the commit uses (runtime, kind-string keyed). */\ntype NodeCollectionLike = Readonly<{\n  getByIds: (\n    ids: readonly string[],\n    options?: Readonly<{ temporalMode?: \"includeTombstones\" }>,\n  ) => Promise<readonly (Node | undefined)[]>;\n  upsertByIdFromRecord: (\n    id: string,\n    data: Record<string, unknown>,\n    options?: Readonly<{ validFrom?: string | null }> & ValidityEndMutation,\n  ) => Promise<unknown>;\n  delete: (id: string) => Promise<void>;\n}>;\n\n/** The edge-collection surface the commit uses (runtime, kind-string keyed). */\ntype EdgeCollectionLike = Readonly<{\n  getByIds: (\n    ids: readonly string[],\n    options?: Readonly<{ temporalMode?: \"includeTombstones\" }>,\n  ) => Promise<readonly (Edge | undefined)[]>;\n  bulkUpsertById: (\n    items: readonly (Readonly<{\n      id: string;\n      from: Readonly<{ kind: string; id: string }>;\n      to: Readonly<{ kind: string; id: string }>;\n      props?: Record<string, unknown>;\n      validFrom?: string | null;\n    }> &\n      ValidityEndMutation)[],\n  ) => Promise<unknown>;\n  delete: (id: string) => Promise<void>;\n}>;\n\n/** A single edge upsert payload (the element of a {@link EdgeCollectionLike} batch). */\ntype EdgeUpsert = Parameters<EdgeCollectionLike[\"bulkUpsertById\"]>[0][number];\n\n/** Resolves a node collection by kind, failing loudly on an unknown kind. */\nfunction nodeCollection(nodes: TxNodes, kind: string): NodeCollectionLike {\n  const collection = nodes[kind];\n  if (collection === undefined) {\n    throw new MergeError(`No node collection for kind \"${kind}\".`, {\n      details: { kind },\n    });\n  }\n  return collection;\n}\n\n/** Resolves an edge collection by kind, failing loudly on an unknown kind. */\nfunction edgeCollection(edges: TxEdges, kind: string): EdgeCollectionLike {\n  const collection = edges[kind];\n  if (collection === undefined) {\n    throw new MergeError(`No edge collection for kind \"${kind}\".`, {\n      details: { kind },\n    });\n  }\n  return collection;\n}\n\n/**\n * THE one owner of the engine-anchor tolerance's ELIGIBILITY check —\n * `toleratedByEngineAnchor` and `assertForkPointUnchanged`'s engine branch\n * both consult this before spending a `lineage` round trip. `expectedVersion`\n * must carry an engine anchor, `liveVersion` must ALSO carry one (never a\n * revision anchor or a content fingerprint — this tolerance's\n * `changesSince` consultation only means anything when the live token's OWN\n * form agrees that the engine anchor is still the authority), the two must\n * share an identical schema half, AND the two must share an identical\n * origin: `liveVersion` is always freshly minted by `computeBaseVersion`\n * (which ensures the live origin at read time), so an origin mismatch here\n * means `expectedVersion` was never forked from THIS store no matter how its\n * bare revision number compares — exactly the cross-database collision\n * `engineComponent`'s own doc warns about, and this is where both\n * plan-time callers (`toleratedByEngineAnchor`'s outer precondition,\n * `assertForkPointUnchanged`'s fork-point re-read) catch it, with no extra\n * read of their own needed. A live token that has moved to a different\n * anchor FORM is a real divergence a `changesSince` check on the stale\n * engine revision cannot speak to at all — that path belongs to whichever\n * guard the live token's own form dispatches to, not this one. Returns the\n * shared engine revision to check `changesSince` against, or `undefined`\n * when the pair is not eligible.\n */\nfunction engineAnchorToleranceEligible(\n  expectedVersion: BaseVersion,\n  liveVersion: BaseVersion,\n): EngineRevision | undefined {\n  const expectedRevision = engineAnchorOf(expectedVersion);\n  if (\n    expectedRevision === undefined ||\n    engineAnchorOf(liveVersion) === undefined ||\n    schemaComponentOf(expectedVersion) !== schemaComponentOf(liveVersion) ||\n    engineAnchorOriginOf(expectedVersion) !== engineAnchorOriginOf(liveVersion)\n  ) {\n    return undefined;\n  }\n  return expectedRevision;\n}\n\n/**\n * Whether an outer base@V precondition should accept `liveVersion` even\n * though it textually differs from `expectedVersion` — the SAME tolerance\n * `assertTargetUnchanged`/`assertForkPointUnchanged` apply inside the\n * commit, routed through the identical {@link engineAnchorMismatch}\n * predicate so the changed-since decision has one owner no matter which of\n * the four base@V call sites is asking. Without this, an engine-wide bump\n * from an UNRELATED graph landing between `branch()` and this precondition\n * (both run outside any transaction, so nothing serializes them) would\n * refuse a plan the in-transaction guard would go on to accept — exactly\n * the over-invalidation the module doc's anchor precedence promises never\n * happens.\n *\n * Requires the two tokens to carry an engine anchor over an IDENTICAL\n * schema half ({@link engineAnchorToleranceEligible}); a revision-anchor or\n * content-fingerprint mismatch, or any schema drift, is a real divergence\n * this predicate does not touch.\n */\nasync function toleratedByEngineAnchor<G extends GraphDef>(\n  store: Store<G>,\n  expectedVersion: BaseVersion,\n  liveVersion: BaseVersion,\n): Promise<boolean> {\n  const expectedRevision = engineAnchorToleranceEligible(\n    expectedVersion,\n    liveVersion,\n  );\n  if (expectedRevision === undefined) return false;\n  const lineage = resolveLineage(store);\n  if (lineage === undefined) return false;\n  // PLANNING-time call, strictly outside any commit transaction: the root\n  // backend `store` holds is the only session available, and the same\n  // object `resolveLineage(store)` just resolved `lineage` off of.\n  const mismatch = await engineAnchorMismatch(\n    lineage,\n    storeBackend(store),\n    store.graphId,\n    expectedRevision,\n  );\n  return mismatch === undefined;\n}\n\n/**\n * Validates the `base@V` precondition: every branch's `base` token MUST equal the\n * target's current base version. A mismatch means the branch forked from a\n * divergent schema or base revision, which cannot be merged safely — UNLESS\n * both tokens are engine-anchored over the same schema and\n * {@link toleratedByEngineAnchor} confirms this graph's own rows are\n * untouched by whatever moved the engine-wide revision meanwhile.\n */\nasync function validateBaseVersions<G extends GraphDef>(\n  target: Store<G>,\n  branches: readonly GraphBranch<G>[],\n): Promise<Result<BaseVersion, BaseVersionMismatchError>> {\n  const targetVersion = await computeBaseVersion(target);\n  for (const branch of branches) {\n    if (branch.base === targetVersion) continue;\n    if (await toleratedByEngineAnchor(target, branch.base, targetVersion)) {\n      continue;\n    }\n    return err(\n      new BaseVersionMismatchError(\n        `Branch \"${branch.id}\" forked from base@V \"${branch.base}\", which does not match the merge target's current base@V \"${targetVersion}\".`,\n        {\n          details: {\n            branchId: branch.id,\n            branchBase: branch.base,\n            targetBase: targetVersion,\n          },\n        },\n      ),\n    );\n  }\n  return ok(targetVersion);\n}\n\n/** Normalizes options, converting an invalid-option throw into a typed result. */\nfunction tryNormalize<G extends GraphDef>(\n  optionsInput: MergeOptions<G>,\n  refusedOptions: readonly (keyof MergeOptions<G>)[] = [],\n): Result<NormalizedMergeOptions<G>, MergeError> {\n  const refusedOption = refusedOptions.find((option) =>\n    hasOwnKey(optionsInput, option),\n  );\n  if (refusedOption !== undefined) {\n    return err(\n      new InvalidMergeOptionsError(\n        `This merge operation does not accept options.${refusedOption}.`,\n        { details: { option: refusedOption } },\n      ),\n    );\n  }\n\n  try {\n    return ok(normalizeMergeOptions(optionsInput));\n  } catch (error) {\n    return err(\n      new InvalidMergeOptionsError(\"Invalid merge options.\", { cause: error }),\n    );\n  }\n}\n\n/**\n * Opens (creating if needed) the target's provenance sidecar BEFORE the merge\n * mutates anything, converting a refusal into a typed merge result.\n *\n * `openProvenanceStore` refuses two classes of state — an occupied sidecar graph\n * id (`GRAPH_MERGE_PROVENANCE_ID_COLLISION`) and a backend that cannot fence the\n * ownership claim (`GRAPH_MERGE_PROVENANCE_CLAIM_UNFENCED`) — and both are pure\n * configuration verdicts: they are as true before the merge as after it, and\n * nothing the merge does changes them. Reporting them post-commit as a warning\n * would leave the caller with a committed graph and an option it stated,\n * TypeGraph accepted, and then silently dropped. They are therefore refusals of\n * `options.persistProvenance` itself, carried as `InvalidMergeOptionsError`\n * (`category: \"user\"`, catchable exactly like every other refused merge option)\n * with the originating `ConfigurationError` as its cause.\n *\n * Any OTHER failure is a backend failure, not a verdict about the option, and is\n * wrapped as a plain `MergeError` — still pre-commit, because a merge whose\n * provenance sidecar cannot be reached should not commit half a contract either.\n */\nasync function tryOpenProvenanceStore<G extends GraphDef>(\n  target: Store<G>,\n): Promise<Result<Store<ProvenanceGraph>, MergeError>> {\n  try {\n    return ok(await openProvenanceStore(target));\n  } catch (error) {\n    const code =\n      error instanceof TypeGraphError ?\n        (error.details as Readonly<{ code?: unknown }> | undefined)?.code\n      : undefined;\n    const details = {\n      option: \"persistProvenance\",\n      graphId: provenanceGraphId(target.graphId),\n      targetGraphId: target.graphId,\n      ...(typeof code === \"string\" ? { provenanceErrorCode: code } : {}),\n    };\n    const message = `options.persistProvenance was requested but the merge-provenance sidecar cannot be opened: ${describeCause(error)}`;\n    return err(\n      (\n        code === \"GRAPH_MERGE_PROVENANCE_ID_COLLISION\" ||\n          code === \"GRAPH_MERGE_PROVENANCE_CLAIM_UNFENCED\"\n      ) ?\n        new InvalidMergeOptionsError(message, { details, cause: error })\n      : new MergeError(message, { details, cause: error }),\n    );\n  }\n}\n\n/**\n * The shared resolve→commit→report pipeline behind both `merge()` (snapshot,\n * staged-vs-staged) and `mergeAgainstBase()` (synthetic new-vs-base). It stages the\n * union of branch diffs, generates candidates (with or without the base sources per\n * `useBaseSources`), resolves the plan, commits, and assembles the report. The\n * `base@V` precondition is the CALLER's responsibility — `merge()` enforces it,\n * the synthetic scope deliberately bypasses it (§6.4-B).\n */\ntype ResolvedMerge<G extends GraphDef> = Readonly<{\n  target: Store<G>;\n  plan: MergePlan<G>;\n  options: NormalizedMergeOptions<G>;\n  expectedBaseVersion?: BaseVersion;\n  incrementalGuard?: IncrementalCommitGuard<G>;\n}>;\n\nfunction assertPublicPlanCapability<G extends GraphDef>(\n  target: Store<G>,\n): void {\n  if (!storeBackend(target).capabilities.execution.interactiveTransactions) {\n    throw new MergePlanCapabilityError(\n      \"Public merge plans require a transaction-capable target backend.\",\n      { details: { capability: \"execution.interactiveTransactions\" } },\n    );\n  }\n  if (!target.revisionTrackingEnabled) {\n    throw new MergePlanCapabilityError(\n      \"Public merge plans require durable target revision tracking.\",\n      {\n        details: { capability: \"revisionTracking\" },\n        suggestion:\n          \"Create the target Store with { revisionTracking: true } (or history enabled), then create a new plan.\",\n      },\n    );\n  }\n}\n\nexport async function captureMergePlanTargetFence<G extends GraphDef>(\n  target: Store<G>,\n): Promise<MergePlanTargetFence> {\n  assertPublicPlanCapability(target);\n  const [activeSchema, schemaHash, origin, revision] = await Promise.all([\n    storeBackend(target).getActiveSchema(target.graphId),\n    computeSchemaComponent(target),\n    target.revisionOriginNow(),\n    target.revisionNow(),\n  ]);\n  return {\n    graphId: target.graphId,\n    schema: {\n      managed: activeSchema !== undefined,\n      version: activeSchema?.version ?? 1,\n      hash: activeSchema?.schema_hash ?? schemaHash,\n    },\n    revision: { origin, revision: revision ?? null },\n  };\n}\n\nexport function sameMergePlanTargetFence(\n  left: MergePlanTargetFence,\n  right: MergePlanTargetFence,\n): boolean {\n  return (\n    left.graphId === right.graphId &&\n    left.schema.managed === right.schema.managed &&\n    left.schema.version === right.schema.version &&\n    left.schema.hash === right.schema.hash &&\n    left.revision.origin === right.revision.origin &&\n    left.revision.revision === right.revision.revision\n  );\n}\n\nfunction evolutionPlanMatchesPlanningFence(\n  evolutionPlan: EvolutionPlan,\n  fence: MergePlanTargetFence,\n): boolean {\n  return (\n    fence.graphId === evolutionPlan.graphId &&\n    fence.schema.version === evolutionPlan.baseline.version &&\n    fence.schema.hash === evolutionPlan.baseline.hash\n  );\n}\n\nfunction evolutionResultingFence(\n  evolutionPlan: EvolutionPlan,\n  baselineFence: MergePlanTargetFence,\n): MergePlanTargetFence {\n  return {\n    ...baselineFence,\n    schema: {\n      managed: true,\n      version:\n        evolutionPlan.status === \"change\" ?\n          evolutionPlan.result.version\n        : evolutionPlan.baseline.version,\n      hash: evolutionPlan.result.hash,\n    },\n  };\n}\n\nexport async function assertPlanningFenceUnchanged<G extends GraphDef>(\n  target: Store<G>,\n  startingFence: MergePlanTargetFence,\n): Promise<void> {\n  const endingFence = await captureMergePlanTargetFence(target);\n  if (sameMergePlanTargetFence(startingFence, endingFence)) return;\n  throw new MergePlanningStaleError(\n    \"The merge target changed while the plan was being computed; no reviewable plan was produced.\",\n    { details: { startingFence, endingFence } },\n  );\n}\n\nfunction splitWireProps(props: Readonly<Record<string, unknown>>): Readonly<{\n  setProps: Readonly<Record<string, JsonValue>>;\n  unsetProps: readonly string[];\n}> {\n  const setProps = createDataKeyedBag<JsonValue>();\n  const unsetProps: string[] = [];\n  for (const key of Object.keys(props).sort(compareStrings)) {\n    const value = props[key];\n    if (value === undefined) {\n      unsetProps.push(key);\n    } else {\n      setProps[key] = value as JsonValue;\n    }\n  }\n  return { setProps, unsetProps };\n}\n\nfunction wireEntityRef(kind: string, id: string): MergePlanEntityRef {\n  return { kind, id };\n}\n\nfunction resolvedNodeUpserts<G extends GraphDef>(\n  plan: MergePlan<G>,\n): readonly MergePlanNodeUpsert[] {\n  return plannedNodeWrites(plan).map((write) => ({\n    kind: write.kind,\n    id: write.id,\n    ...splitWireProps(\n      nodeWriteProps(write, (modification) =>\n        commitModificationProps(modification.baseProps, modification.forkProps),\n      ),\n    ),\n    ...(write.validFrom === undefined ? {} : { validFrom: write.validFrom }),\n    ...(write.validTo === undefined ? {} : { validTo: write.validTo }),\n  }));\n}\n\nasync function resolvedMergeArtifact<G extends GraphDef>(\n  resolved: ResolvedMerge<G>,\n  mode: \"snapshot\" | \"incremental\",\n  targetFence: MergePlanTargetFence,\n  anchors: MergePlanAnchors,\n): Promise<MergePlanArtifactV1> {\n  const { plan, options } = resolved;\n  const nodeUpserts = resolvedNodeUpserts(plan);\n  const edgeUpserts = plan.mergedEdges.map((edge) => {\n    const baseProps = plan.inheritedEdgeBaseProps.get(edge.id);\n    const props =\n      baseProps === undefined ?\n        edge.props\n      : commitModificationProps(baseProps, edge.props);\n    return {\n      kind: edge.kind,\n      id: edge.id,\n      from: finalEdgeEndpoint(plan, edge.fromKind, edge.fromId),\n      to: finalEdgeEndpoint(plan, edge.toKind, edge.toId),\n      ...splitWireProps(props),\n      ...(edge.validFrom === undefined ? {} : { validFrom: edge.validFrom }),\n      ...(edge.validTo === undefined ? {} : { validTo: edge.validTo }),\n    };\n  });\n  const input: MergePlanArtifactV1Input = {\n    formatVersion: 1,\n    mode,\n    target: targetFence,\n    anchors,\n    proposed: {\n      nodes: {\n        upserts: nodeUpserts.length,\n        deletions: plan.nodeDeletions.size,\n      },\n      edges: {\n        upserts: edgeUpserts.length,\n        deletions: plan.edgeDeletions.size,\n      },\n      identity: {\n        assertions: plan.identityAssertions.length,\n        retractions: plan.identityRetractions.length,\n      },\n    },\n    writes: {\n      nodeDeletes: [...plan.nodeDeletions].map(([identity, kind]) =>\n        wireEntityRef(kind, idOf(identity)),\n      ),\n      nodeUpserts,\n      edgeDeletes: [...plan.edgeDeletions].map(([identity, kind]) =>\n        wireEntityRef(kind, idOf(identity)),\n      ),\n      edgeUpserts,\n      identityAssertions: plan.identityAssertions,\n      identityRetractions: plan.identityRetractions,\n    },\n    guards: {\n      canonicalMappings: [...plan.canonicalOf]\n        .sort(([left], [right]) => compareMergeKeys(left, right))\n        .map(([member, canonical]) => ({\n          member: wireEntityRef(kindOf(member), idOf(member)),\n          canonical: wireEntityRef(kindOf(canonical), idOf(canonical)),\n        })),\n      retypes: [...plan.retypeMap]\n        .sort(([left], [right]) => compareMergeKeys(left, right))\n        .map(([entity, toKind]) => ({\n          entity: wireEntityRef(kindOf(entity), idOf(entity)),\n          toKind,\n        })),\n      deletedNodes: [...plan.nodeDeletions].map(([identity, kind]) =>\n        wireEntityRef(kind, idOf(identity)),\n      ),\n      ...(resolved.incrementalGuard === undefined ?\n        {}\n      : {\n          incremental: {\n            tombstoneResurrection: \"refuse\" as const,\n            lossyUpdates: \"refuse\" as const,\n            edgeIdentity: \"preserve\" as const,\n          },\n        }),\n    },\n    review: {\n      resolutions: plan.resolutions,\n      conflicts: plan.propertyConflicts as unknown as readonly JsonValue[],\n      deleteModifyConflicts: plan.deleteModifyConflicts,\n      typeReconciliations: plan.typeReconciliations,\n      dropped: plan.dropped,\n      validityEnds: plan.validityEnds,\n      baseAmbiguities: plan.baseAmbiguities,\n      provenanceRecords: plan.provenanceRecords,\n      warnings: plan.warnings,\n      ...(plan.candidateDiagnostics === undefined ?\n        {}\n      : { diagnostics: plan.candidateDiagnostics }),\n    },\n    provenance: {\n      includeInReport: options.provenance,\n      persist: options.persistProvenance,\n    },\n  };\n  return constructMergePlanArtifact(input);\n}\n\nasync function resolveMerge<G extends GraphDef, Output>(\n  store: Store<G>,\n  target: Store<G>,\n  branches: readonly GraphBranch<G>[],\n  options: NormalizedMergeOptions<G>,\n  useBaseSources: boolean,\n  incremental: IncrementalConfig<G> | undefined,\n  expectedBaseVersion: BaseVersion | undefined,\n  complete: (resolved: ResolvedMerge<G>) => Promise<Output>,\n): Promise<Result<Output, MergeError>> {\n  // Reserved BranchIds are used for non-user contributions. Reject real branches\n  // that try to mint them rather than silently corrupting conflict/provenance state.\n  let targetBranchSeen = false;\n  for (const branch of branches) {\n    if (branch.id === BASE_PROVENANCE_BRANCH) {\n      return err(\n        new MergeError(\n          `Branch id \"${BASE_PROVENANCE_BRANCH}\" is reserved for committed-base provenance and cannot be used as a branch id.`,\n          { details: { branchId: branch.id } },\n        ),\n      );\n    }\n    if (branch.id === COMMITTED_TARGET_BRANCH) {\n      if (\n        incremental?.targetBranchId !== COMMITTED_TARGET_BRANCH ||\n        targetBranchSeen\n      ) {\n        return err(\n          new MergeError(\n            `Branch id \"${COMMITTED_TARGET_BRANCH}\" is reserved for the committed incremental target and cannot be used as a branch id.`,\n            { details: { branchId: branch.id } },\n          ),\n        );\n      }\n      targetBranchSeen = true;\n    }\n  }\n\n  // A branch must be a DATA fork. A schema operation on the branch's store\n  // after forking (evolve, migrateSchema, removeKinds) mutates rows through\n  // its own preflights, and the state diff would project those side effects\n  // into the merge as ordinary data changes detached from the schema change\n  // that caused them — e.g. a kind removal's cascaded assertion cleanup\n  // arriving as bare identity retractions against a target that still has the\n  // kind. The check compares the branch's CURRENT committed schema row to the\n  // (version, hash) anchor `branch()` captured at fork — version included, so\n  // a ROUND-TRIP migration that restores the original document hash while\n  // its preflights mutated rows is still refused. Hand-built branch objects\n  // without an anchor fall back to hash equality against the fork source\n  // (which also keeps unmanaged, row-less sources mergeable).\n  for (const branch of branches) {\n    const branchSchemaRow = await storeBackend(branch.store).getActiveSchema(\n      branch.store.graphId,\n    );\n    let drifted: boolean;\n    if (\"schemaAnchor\" in branch) {\n      const anchor = branch.schemaAnchor;\n      drifted =\n        anchor === undefined ?\n          branchSchemaRow !== undefined\n        : branchSchemaRow?.version !== anchor.version ||\n          branchSchemaRow.schema_hash !== anchor.hash;\n    } else {\n      const sourceSchemaRow = await storeBackend(store).getActiveSchema(\n        store.graphId,\n      );\n      drifted = branchSchemaRow?.schema_hash !== sourceSchemaRow?.schema_hash;\n    }\n    if (drifted) {\n      return err(\n        new BaseVersionMismatchError(\n          `Branch \"${branch.id}\"'s store has a committed schema different from its at-fork state — a schema operation ran on the branch after forking. Merge carries data changes only; apply the schema change to the target first (or re-fork), then merge.`,\n          {\n            details: {\n              branchId: branch.id,\n              branchSchemaVersion: branchSchemaRow?.version,\n              branchSchemaHash: branchSchemaRow?.schema_hash,\n              anchor: \"schemaAnchor\" in branch ? branch.schemaAnchor : \"absent\",\n            },\n          },\n        ),\n      );\n    }\n  }\n\n  try {\n    // (2) stage the provenance-tagged union of every branch's diff. For the\n    // incremental path, capture the committed target branch's node versions from\n    // its diff enumeration — the plan-time baseline for the commit-time\n    // lost-update guard (assertInheritedTargetUnchanged).\n    const preferredBranchId = incremental?.targetBranchId;\n    const staging = await stageBranches(store, branches, preferredBranchId);\n    // Pure over the (now fixed) staging set, so the deterministic per-kind order\n    // is computed once and shared by every consumer below.\n    const stagedNewByKind = newNodesByKind(staging);\n\n    // Capture the stable branch order ONCE (never wall-clock).\n    const branchIds = branches.map((branch) => branch.id);\n    const branchOrder =\n      preferredBranchId === undefined ?\n        (options.branchOrder ?? [])\n      : [\n          preferredBranchId,\n          ...(options.branchOrder ?? []).filter(\n            (branchId) => branchId !== preferredBranchId,\n          ),\n        ];\n    const branchRank = buildBranchRank(branchOrder, branchIds);\n\n    // Introspection snapshot: unique constraints for blocking + ontology closure.\n    const introspection = store.introspect();\n    const introspectionKinds = new Map<\n      string,\n      readonly UniqueIntrospection[]\n    >();\n    for (const kind of introspection.kinds) {\n      introspectionKinds.set(kind.name, kind.unique);\n    }\n    const subClassClosure = buildSubClassClosure(introspection.ontology);\n\n    // (3) candidate generation across every resolved kind. When an embedder is\n    // configured, precompute the STAGED texts' vectors ONCE (a batched step) so\n    // the per-pair `vector`/`hybrid` scoring is a pure in-memory cosine; base-node\n    // texts pulled into staged↔base pairs are embedded inside generateAllCandidates\n    // (they are not known until the base sources run). With no embedder,\n    // `embeddings` stays absent and a vector/hybrid kind surfaces\n    // SimilarityUnavailableError in candidate generation.\n    const embeddings =\n      options.embedder === undefined ?\n        undefined\n      : await precomputeEmbeddings(\n          stagedNewByKind,\n          options.resolve,\n          options.embedder,\n        );\n    const ctx: SimilarityContext = {\n      backend: storeBackend(store),\n      ...(embeddings === undefined ? {} : { embeddings }),\n    };\n    const candidates = await generateAllCandidates(\n      target,\n      staging,\n      options,\n      introspectionKinds,\n      ctx,\n      useBaseSources,\n      options.embedder,\n    );\n    if (isErr(candidates)) {\n      return err(candidates.error);\n    }\n\n    // Same-id folding joins nodes no assertion names, so the plan-time\n    // contradiction simulation needs the LIVE target peers sharing any staged\n    // or base id. One kind-free indexed probe.\n    // The identity guard protects EVERY identity-enabled incremental merge —\n    // explicit same/different assertions exist under both profiles. Only the\n    // same-id peer expansion (and the direct-peer window check) is\n    // fold-specific.\n    const identityProbeIds =\n      target.graph.identity === undefined ?\n        undefined\n      : [\n          ...new Set([\n            ...[...stagedNewByKind.values()].flatMap((entries) =>\n              entries.map((entry) => entry.node.id),\n            ),\n            ...staging.modifiedNodes.map((entry) => entry.node.id),\n            ...candidates.data.baseMembers.map((member) => member.id),\n            ...staging.newIdentityAssertions.flatMap((staged) => [\n              staged.assertion.a.id,\n              staged.assertion.b.id,\n            ]),\n          ]),\n        ];\n    const targetPeers =\n      identityProbeIds === undefined ?\n        []\n      : await storeRuntime(target).liveNodesSharingIds(identityProbeIds);\n\n    // Every staged assertion and retraction id's target row, fetched BEFORE\n    // planning. Retractions are validated against the complete truth their id\n    // identifies on the target (a current row with DIFFERENT truth — the\n    // target reused the id independently — must not be ended by a branch that\n    // never saw it), and the survivor dedupe must know which staged ids are\n    // ALREADY COMMITTED on the target: the applier is idempotent per semantic\n    // pair, so a committed row can never lose the survivor pick to a branch's\n    // freshly minted id.\n    const stagedIdentityIds = [\n      ...new Set([\n        ...staging.newIdentityAssertions.map((staged) => staged.assertion.id),\n        ...staging.retractedIdentityAssertions.map(\n          (staged) => staged.assertion.id,\n        ),\n      ]),\n    ];\n    const storedIdentityRowsById =\n      stagedIdentityIds.length === 0 || target.graph.identity === undefined ?\n        NO_STORED_ASSERTIONS\n      : await storeRuntime(target).identityAssertionRowsByIds(\n          stagedIdentityIds,\n        );\n\n    // The target's identity semantics, shared by the plan-time simulation and\n    // the post-plan recheck so both judge legality under one context.\n    const identityContext: PlanIdentityContext = {\n      sameIdAcrossKinds: target.graph.identity?.sameIdAcrossKinds,\n      areDisjoint: (left, right) => target.registry.areDisjoint(left, right),\n    };\n\n    // (4–8) resolve the whole merge into a commit-ready plan.\n    const plan = buildInternalMergePlan(\n      staging,\n      candidates.data.edges,\n      candidates.data.warnings,\n      candidates.data.diagnostics,\n      candidates.data.diagnosticsTotal,\n      candidates.data.baseMembers,\n      options,\n      branchRank,\n      subClassClosure,\n      identityContext,\n      storedIdentityRowsById,\n      targetPeers,\n      preferredBranchId,\n    );\n\n    // The commit guard's baseline must be a VALIDATED state: re-probe the\n    // live peers and snapshot the final seeds' classes AFTER planning, then\n    // re-run the identity simulation against that exact snapshot — its\n    // members join the universe UNLINKED, with connectivity rebuilt from the\n    // deletion-filtered fresh ledger and the checker's fold unions. A class\n    // change in the plan→snapshot window therefore either fails this recheck\n    // as a typed plan-time conflict, or matches the plan; either way the\n    // transaction guard never baselines drift the plan did not validate.\n    // The probe ranges only over ids the final plan folds on — a window row\n    // at an id canonicalization dropped is an unrelated target advance.\n    // One-id-one-truth, for BOTH commit modes: two branches staging one id\n    // for different truths, or a staged id already identifying different\n    // truth in the target (ended rows included), used to surface only inside\n    // the commit as a generic wrap of IDENTITY_IMPORT_ID_CONFLICT.\n    if (plan.identityAssertions.length > 0) {\n      assertOneIdOneTruth(\n        plan.identityAssertions,\n        await storeRuntime(target).identityAssertionRowsByIds(\n          plan.identityAssertions.map((assertion) => assertion.id),\n        ),\n      );\n    }\n\n    let identityGuard: IdentityPeerProbe | undefined;\n    if (identityProbeIds !== undefined && incremental !== undefined) {\n      const freshPeers =\n        await storeRuntime(target).liveNodesSharingIds(identityProbeIds);\n      const built = await buildIdentityPeerProbe(\n        target,\n        identityProbeIds,\n        freshPeers,\n        plan,\n        target.graph.identity?.sameIdAcrossKinds ?? \"ignore\",\n      );\n      // Base assertion endpoints must be judged at their post-merge\n      // identity, exactly as the in-plan check judged them — through the\n      // REAL canonical map the plan carries.\n      const canonicalIdentityOf = plan.canonicalOf;\n      assertNoContradictoryIdentityClosure(\n        plan.identityAssertions,\n        plan.identityRetractions.map((retraction) => retraction.id),\n        // The FRESH target ledger, not the pre-planning staging capture —\n        // a `different` committed in the window must invalidate the plan\n        // here, as a typed conflict, before it can become the baseline.\n        // Connectivity is REBUILT from this deletion-filtered ledger (plus\n        // the fold unions inside the checker) rather than from the old\n        // closure's member lists: filtering a deleted member out of a class\n        // does not model the post-deletion state — deleting a bridge ends\n        // its assertions and SPLITS the class, so pre-linking the filtered\n        // remainder would falsely reject a plan that deletes the bridge and\n        // asserts the ends different.\n        built.ledger,\n        new Set(plan.nodeDeletions.keys()),\n        canonicalIdentityOf,\n        plan.retypeMap,\n        identityContext,\n        // The snapshot's (deletion-filtered) class MEMBERS join the universe\n        // as unlinked refs: their same-id fold links at ids outside the probe\n        // range are re-derived by the checker's fold union, and their\n        // assertion links come from the fresh ledger — never from the old\n        // class shape itself.\n        [...built.probe.seeds, ...built.snapshot.groups.flat()],\n      );\n      identityGuard = built.probe;\n    }\n\n    const incrementalGuard =\n      incremental === undefined ? undefined : (\n        ({\n          stagedNewByKind,\n          options,\n          introspectionKinds,\n          forkPoint: incremental.forkPoint,\n          ...(identityGuard === undefined ?\n            {}\n          : { identityPeerProbe: identityGuard }),\n          plannedBaseMatchKeys: new Set(\n            candidates.data.baseMembers.map((member) => mergeKeyOf(member)),\n          ),\n          targetNodeVersions: staging.targetNodeVersions,\n          targetEdgeSignatures: staging.targetEdgeSignatures,\n        } satisfies IncrementalCommitGuard<G>)\n      );\n\n    return ok(\n      await complete({\n        target,\n        plan,\n        options,\n        ...(expectedBaseVersion === undefined ? {} : { expectedBaseVersion }),\n        ...(incrementalGuard === undefined ? {} : { incrementalGuard }),\n      }),\n    );\n  } catch (error) {\n    // A typed MergeError thrown deeper (e.g. the incremental guard's stale-overwrite\n    // refusal) carries its own precise message — surface it directly rather than\n    // masking it behind the generic wrapper, which is reserved for opaque failures\n    // (a backend error, a malformed row).\n    if (error instanceof MergeError) {\n      return err(error);\n    }\n    return err(\n      new MergeError(\n        `Merge failed while staging or committing: ${describeCause(error)}`,\n        { cause: error },\n      ),\n    );\n  }\n}\n\n/** Commits one already-resolved merge and constructs its compatibility report. */\nasync function commitResolvedMerge<G extends GraphDef>(\n  resolved: ResolvedMerge<G>,\n): Promise<MergeReport<G>> {\n  const { target, plan, options } = resolved;\n  const provenanceStore =\n    options.persistProvenance ?\n      await tryOpenProvenanceStore(target)\n    : undefined;\n  if (provenanceStore !== undefined && isErr(provenanceStore)) {\n    throw provenanceStore.error;\n  }\n  const merged =\n    resolved.incrementalGuard === undefined ?\n      await commitPlan(target, plan, resolved.expectedBaseVersion)\n    : await commitIncrementalPlan(target, plan, resolved.incrementalGuard);\n\n  const provenance: ProvenanceIndex =\n    options.provenance ?\n      buildProvenanceIndex(plan.provenanceRecords)\n    : { byBranch: () => ({ nodeIds: [], edgeIds: [] }) };\n  const warnings = [...plan.warnings];\n  let provenancePersisted: MergeReport<G>[\"provenancePersisted\"];\n  if (provenanceStore !== undefined && !isErr(provenanceStore)) {\n    try {\n      const count = await persistProvenanceRecords(\n        provenanceStore.data,\n        target.graphId,\n        plan.provenanceRecords,\n      );\n      provenancePersisted = {\n        graphId: provenanceGraphId(target.graphId),\n        count,\n      };\n    } catch (error) {\n      warnings.push(\n        \"provenance persistence failed (graph committed; provenance not persisted): \" +\n          (error instanceof Error ? error.message : String(error)),\n      );\n    }\n  }\n\n  return {\n    merged,\n    resolutions: plan.resolutions,\n    conflicts: plan.propertyConflicts,\n    deleteModifyConflicts: plan.deleteModifyConflicts,\n    typeReconciliations: plan.typeReconciliations,\n    dropped: plan.dropped,\n    validityEnds: plan.validityEnds,\n    baseAmbiguities: plan.baseAmbiguities,\n    provenance,\n    warnings,\n    ...(plan.candidateDiagnostics === undefined ?\n      {}\n    : { candidateDiagnostics: plan.candidateDiagnostics }),\n    ...(provenancePersisted === undefined ? {} : { provenancePersisted }),\n  };\n}\n\nfunction incrementalBaseConflictPolicyError<G extends GraphDef>(\n  options: NormalizedMergeOptions<G>,\n): InvalidMergeOptionsError {\n  return new InvalidMergeOptionsError(\n    'mergeIncremental() requires onBasePropertyConflict: \"flag\" (keep-base); a non-keep-base policy could overwrite a newer committed base value with a stale branch value.',\n    {\n      details: {\n        option: \"onBasePropertyConflict\",\n        accepted: \"flag\",\n        received: options.onBasePropertyConflict,\n      },\n    },\n  );\n}\n\nfunction incrementalSchemaError(): MergeError {\n  return new MergeError(\n    \"mergeIncremental() requires target and forkPoint to share a schema; schema drift is not supported (the target content may differ — only the schema must match).\",\n    { details: {} },\n  );\n}\n\n/** Builds a durable, reviewable snapshot merge plan without mutating the target. */\nexport async function planMerge<G extends GraphDef>(\n  store: Store<G>,\n  branchInputs: readonly MergeBranch<G>[],\n  optionsInput: MergeOptions<G> = {},\n): Promise<Result<MergePlanArtifact, MergeError>> {\n  const branches = unwrapMergeBranches(branchInputs);\n  const normalized = tryNormalize(optionsInput);\n  if (isErr(normalized)) return err(normalized.error);\n  const options = normalized.data;\n  const target = options.target ?? store;\n  let targetFence: MergePlanTargetFence;\n  try {\n    targetFence = await captureMergePlanTargetFence(target);\n  } catch (error) {\n    return err(\n      error instanceof MergeError ? error : (\n        new MergePlanCapabilityError(\n          `Unable to capture the target's durable plan fence: ${describeCause(error)}`,\n          { cause: error },\n        )\n      ),\n    );\n  }\n  const precondition = await validateBaseVersions(store, branches);\n  if (isErr(precondition)) return err(precondition.error);\n  // Each branch's OWN raw `base` is recorded here, unlike\n  // `planMergeIncremental`'s sibling `anchors.branches[].baseVersion`,\n  // which normalizes to the resolved `forkVersion` instead. That\n  // normalization exists for one specific reason: `candidate-review.ts`'s\n  // `validateReview` re-checks `anchors.branches[0].baseVersion ===\n  // anchors.forkPoint.baseVersion` for an INCREMENTAL plan under review,\n  // and recording a tolerated branch's stale-looking raw `base` there would\n  // make that already-accepted plan read as \"incompatible-plan\" later. No\n  // snapshot-mode consumer compares `anchors.branches[].baseVersion`\n  // against `anchors.base.baseVersion` the same way — a snapshot plan's\n  // anchors are a durable audit record, not a re-validated equality gate —\n  // so there is nothing here for a tolerated engine-anchor mismatch to\n  // falsely trip, and the raw per-branch `base` is exactly what a reviewer\n  // means to see.\n  const anchors: MergePlanAnchors = {\n    kind: \"snapshot\",\n    base: { graphId: store.graphId, baseVersion: precondition.data },\n    branches: [...branches]\n      .sort((left, right) => compareStrings(left.id, right.id))\n      .map((branch) => ({\n        branchId: branch.id,\n        baseVersion: branch.base,\n      })),\n  };\n  return resolveMerge(\n    store,\n    target,\n    branches,\n    options,\n    false,\n    undefined,\n    precondition.data,\n    async (resolved) => {\n      await assertPlanningFenceUnchanged(target, targetFence);\n      return resolvedMergeArtifact(resolved, \"snapshot\", targetFence, anchors);\n    },\n  );\n}\n\n/**\n * Plans a merge against the graph produced by a reviewed evolution plan.\n * Durable data and revision evidence is still captured from the original\n * target; the schema fence names the version the caller will apply first.\n */\nexport async function planMergeForEvolution<G extends GraphDef>(\n  store: Store<G>,\n  evolutionPlan: EvolutionPlan,\n  branchInputs: readonly MergeBranch<G>[],\n  optionsInput: MergeOptions<G> = {},\n): Promise<Result<MergePlanArtifact, MergeError>> {\n  const branches = unwrapMergeBranches(branchInputs);\n  const normalized = tryNormalize(optionsInput);\n  if (isErr(normalized)) return err(normalized.error);\n  const options = normalized.data;\n  if (options.target !== undefined && options.target !== store) {\n    return err(\n      new MergePlanCapabilityError(\n        \"Evolution merge planning must use the Store that owns the evolution plan.\",\n        { details: { capability: \"evolutionPlanTarget\" } },\n      ),\n    );\n  }\n  let target: Store<G>;\n  let baselineFence: MergePlanTargetFence;\n  try {\n    target = evolutionPlanningTarget(store, evolutionPlan);\n    baselineFence = await captureMergePlanTargetFence(store);\n  } catch (error) {\n    return err(\n      error instanceof MergeError ? error : (\n        new MergePlanCapabilityError(\n          `Unable to prepare an evolution merge target: ${describeCause(error)}`,\n          { cause: error, details: { capability: \"evolutionPlanningTarget\" } },\n        )\n      ),\n    );\n  }\n  if (!evolutionPlanMatchesPlanningFence(evolutionPlan, baselineFence)) {\n    return err(\n      new MergePlanningStaleError(\n        \"The evolution plan baseline no longer matches the active merge target schema.\",\n        { details: { startingFence: baselineFence } },\n      ),\n    );\n  }\n  const resultingFence = evolutionResultingFence(evolutionPlan, baselineFence);\n  const baselinePrecondition = await validateBaseVersions(store, branches);\n  const precondition =\n    isErr(baselinePrecondition) ?\n      await validateBaseVersions(target, branches)\n    : baselinePrecondition;\n  if (isErr(precondition)) return err(precondition.error);\n  const anchors: MergePlanAnchors = {\n    kind: \"snapshot\",\n    base: { graphId: store.graphId, baseVersion: precondition.data },\n    branches: [...branches]\n      .sort((left, right) => compareStrings(left.id, right.id))\n      .map((branch) => ({ branchId: branch.id, baseVersion: branch.base })),\n  };\n  return resolveMerge(\n    target,\n    target,\n    branches,\n    { ...options, target },\n    false,\n    undefined,\n    precondition.data,\n    async (resolved) => {\n      await assertPlanningFenceUnchanged(store, baselineFence);\n      return resolvedMergeArtifact(\n        resolved,\n        \"snapshot\",\n        resultingFence,\n        anchors,\n      );\n    },\n  );\n}\n\n/**\n * Candidate-specific evolution planning: retains incremental committed-target\n * matching while binding the returned artifact to the schema the evolution will\n * commit. General evolution merges remain snapshot merges by design.\n */\nexport async function planMergeIncrementalForEvolution<G extends GraphDef>(\n  store: Store<G>,\n  evolutionPlan: EvolutionPlan,\n  branchInputs: readonly MergeBranch<G>[],\n  optionsInput: MergeOptions<G> = {},\n  startingFence?: MergePlanTargetFence,\n): Promise<Result<MergePlanArtifact, MergeError>> {\n  const branches = unwrapMergeBranches(branchInputs);\n  const normalized = tryNormalize(optionsInput, [\"target\"]);\n  if (isErr(normalized)) return err(normalized.error);\n  const options = normalized.data;\n  if (options.onBasePropertyConflict !== \"flag\") {\n    return err(incrementalBaseConflictPolicyError(options));\n  }\n  let target: Store<G>;\n  let baselineFence: MergePlanTargetFence;\n  try {\n    target = evolutionPlanningTarget(store, evolutionPlan);\n    baselineFence = startingFence ?? (await captureMergePlanTargetFence(store));\n  } catch (error) {\n    return err(\n      error instanceof MergeError ? error : (\n        new MergePlanCapabilityError(\n          `Unable to prepare an evolution merge target: ${describeCause(error)}`,\n          { cause: error, details: { capability: \"evolutionPlanningTarget\" } },\n        )\n      ),\n    );\n  }\n  if (!evolutionPlanMatchesPlanningFence(evolutionPlan, baselineFence)) {\n    return err(\n      new MergePlanningStaleError(\n        \"The evolution plan baseline no longer matches the active merge target schema.\",\n        { details: { startingFence: baselineFence } },\n      ),\n    );\n  }\n  try {\n    await assertPlanningFenceUnchanged(store, baselineFence);\n  } catch (error) {\n    return err(\n      error instanceof MergeError ? error : (\n        new MergeError(\n          `Unable to verify the evolution merge planning fence: ${describeCause(error)}`,\n          { cause: error },\n        )\n      ),\n    );\n  }\n  const forkPrecondition = await validateForkPointVersions(target, branches);\n  if (isErr(forkPrecondition)) {\n    try {\n      await assertPlanningFenceUnchanged(store, baselineFence);\n    } catch (error) {\n      return err(\n        error instanceof MergeError ? error : (\n          new MergeError(\n            `Unable to verify the evolution merge planning fence: ${describeCause(error)}`,\n            { cause: error },\n          )\n        ),\n      );\n    }\n    return err(forkPrecondition.error);\n  }\n  const forkVersion = forkPrecondition.data;\n  const forkSchema = await computeSchemaComponent(target);\n  if (forkSchema !== evolutionPlan.result.hash) {\n    return err(incrementalSchemaError());\n  }\n  const targetBranch: GraphBranch<G> = {\n    id: COMMITTED_TARGET_BRANCH,\n    base: forkVersion,\n    store: target,\n    close: (): Promise<void> => Promise.resolve(),\n  };\n  const resultingFence = evolutionResultingFence(evolutionPlan, baselineFence);\n  const anchors: MergePlanAnchors = {\n    kind: \"incremental\",\n    forkPoint: {\n      graphId: target.graphId,\n      baseVersion: forkVersion,\n      schema: resultingFence.schema,\n    },\n    branches: [...branches]\n      .sort((left, right) => compareStrings(left.id, right.id))\n      .map((branch) => ({\n        branchId: branch.id,\n        baseVersion: forkVersion,\n      })),\n  };\n  return resolveMerge(\n    target,\n    target,\n    [targetBranch, ...branches],\n    options,\n    true,\n    {\n      targetBranchId: COMMITTED_TARGET_BRANCH,\n      forkPoint: { store: target, version: forkVersion },\n    },\n    undefined,\n    async (resolved) => {\n      await assertPlanningFenceUnchanged(store, baselineFence);\n      return resolvedMergeArtifact(\n        resolved,\n        \"incremental\",\n        resultingFence,\n        anchors,\n      );\n    },\n  );\n}\n\n/** Builds a durable, reviewable incremental merge plan without mutating the target. */\nexport async function planMergeIncremental<G extends GraphDef>(\n  args: MergeIncrementalArguments<G>,\n): Promise<Result<MergePlanArtifact, MergeError>> {\n  const { forkPoint, target } = args;\n  const branches = unwrapMergeBranches(args.branches);\n  const normalized = tryNormalize(args.options ?? {}, [\"target\"]);\n  if (isErr(normalized)) return err(normalized.error);\n  const options = normalized.data;\n  if (options.onBasePropertyConflict !== \"flag\") {\n    return err(incrementalBaseConflictPolicyError(options));\n  }\n  let targetFence: MergePlanTargetFence;\n  try {\n    targetFence = await captureMergePlanTargetFence(target);\n  } catch (error) {\n    return err(\n      error instanceof MergeError ? error : (\n        new MergePlanCapabilityError(\n          `Unable to capture the target's durable plan fence: ${describeCause(error)}`,\n          { cause: error },\n        )\n      ),\n    );\n  }\n  const forkPrecondition = await validateForkPointVersions(forkPoint, branches);\n  if (isErr(forkPrecondition)) return err(forkPrecondition.error);\n  const forkVersion = forkPrecondition.data;\n  const [forkSchema, targetSchema] = await Promise.all([\n    computeSchemaComponent(forkPoint),\n    computeSchemaComponent(target),\n  ]);\n  if (forkSchema !== targetSchema) return err(incrementalSchemaError());\n  const forkActiveSchema = await storeBackend(forkPoint).getActiveSchema(\n    forkPoint.graphId,\n  );\n  const targetBranch: GraphBranch<G> = {\n    id: COMMITTED_TARGET_BRANCH,\n    base: forkVersion,\n    store: target,\n    // `target` is the caller's own live store, not a working copy this\n    // function created — modeling it as a GraphBranch is an internal device\n    // for reusing the branch-shaped merge machinery, so closing it here\n    // would close a backend the caller still owns.\n    close: (): Promise<void> => Promise.resolve(),\n  };\n  const anchors: MergePlanAnchors = {\n    kind: \"incremental\",\n    forkPoint: {\n      graphId: forkPoint.graphId,\n      baseVersion: forkVersion,\n      schema: {\n        managed: forkActiveSchema !== undefined,\n        version: forkActiveSchema?.version ?? 1,\n        hash: forkActiveSchema?.schema_hash ?? forkSchema,\n      },\n    },\n    // Recorded as `forkVersion`, NOT the branch's own raw `base` token:\n    // `validateForkPointVersions` above already accepted every branch\n    // either because `branch.base === forkVersion` outright, or because\n    // `toleratedByEngineAnchor` confirmed an engine-wide bump on an\n    // unrelated graph left this graph's own rows untouched — in which case\n    // the branch's diff was, in fact, computed against exactly the current\n    // fork point. Recording the raw (possibly stale-looking) `branch.base`\n    // here would carry that already-resolved tolerance back out as an\n    // apparent mismatch against `forkPoint.baseVersion` above, which\n    // `candidate-review.ts`'s `validateReview` reads as\n    // \"incompatible-plan\" for a plan this function just accepted.\n    branches: [...branches]\n      .sort((left, right) => compareStrings(left.id, right.id))\n      .map((branch) => ({\n        branchId: branch.id,\n        baseVersion: forkVersion,\n      })),\n  };\n  return resolveMerge(\n    forkPoint,\n    target,\n    [targetBranch, ...branches],\n    options,\n    true,\n    {\n      targetBranchId: COMMITTED_TARGET_BRANCH,\n      forkPoint: { store: forkPoint, version: forkVersion },\n    },\n    undefined,\n    async (resolved) => {\n      await assertPlanningFenceUnchanged(target, targetFence);\n      await assertForkPointUnchanged({\n        store: forkPoint,\n        version: forkVersion,\n      });\n      return resolvedMergeArtifact(\n        resolved,\n        \"incremental\",\n        targetFence,\n        anchors,\n      );\n    },\n  );\n}\n\nfunction mergePlanValidationError(\n  failure: Exclude<\n    Awaited<ReturnType<typeof validateMergePlanArtifact>>,\n    Readonly<{ success: true }>\n  >[\"error\"],\n): MergeError {\n  switch (failure.kind) {\n    case \"unsupported-version\": {\n      return new UnsupportedMergePlanVersionError(\n        `Unsupported merge plan format version ${String(failure.received)}.`,\n        { details: { received: failure.received } },\n      );\n    }\n    case \"digest-mismatch\": {\n      return new MergePlanDigestMismatchError(\n        \"The merge plan digest does not match its canonical content.\",\n        { details: { expected: failure.expected, received: failure.received } },\n      );\n    }\n    case \"malformed\": {\n      return new InvalidMergePlanError(\"The merge plan is malformed.\", {\n        details: { issues: failure.issues },\n      });\n    }\n    default: {\n      const exhaustive: never = failure;\n      return exhaustive;\n    }\n  }\n}\n\nfunction wireWriteProps(\n  setProps: Readonly<Record<string, JsonValue>>,\n  unsetProps: readonly string[],\n): Record<string, unknown> {\n  const props = createDataKeyedBag<unknown>();\n  for (const [key, value] of Object.entries(setProps)) props[key] = value;\n  for (const key of unsetProps) props[key] = undefined;\n  return props;\n}\n\nfunction resolvedWireProps(\n  current: Readonly<Record<string, unknown>>,\n  setProps: Readonly<Record<string, JsonValue>>,\n  unsetProps: readonly string[],\n): Record<string, unknown> {\n  const props = createDataKeyedBag<unknown>();\n  const unset = new Set(unsetProps);\n  for (const [key, value] of Object.entries(current)) {\n    if (!unset.has(key)) props[key] = value;\n  }\n  for (const [key, value] of Object.entries(setProps)) props[key] = value;\n  return props;\n}\n\nfunction invalidPlanForTarget(\n  message: string,\n  details: Readonly<Record<string, unknown>>,\n): InvalidMergePlanError {\n  return new InvalidMergePlanError(message, { details });\n}\n\nasync function preflightWireMergeWrites<G extends GraphDef>(\n  target: Store<G>,\n  nodesApi: TxNodes,\n  edgesApi: TxEdges,\n  artifact: MergePlanArtifactV1,\n): Promise<void> {\n  const graphNodes = target.graph.nodes as Record<string, unknown>;\n  const graphEdges = target.graph.edges as Record<\n    string,\n    (typeof target.graph.edges)[keyof typeof target.graph.edges] | undefined\n  >;\n  const assertNodeKind = (kind: string): void => {\n    if (!hasOwnKey(graphNodes, kind)) {\n      throw invalidPlanForTarget(\n        `The merge plan references unknown node kind \"${kind}\".`,\n        { kind, role: \"node\" },\n      );\n    }\n  };\n  const assertEdgeKind = (kind: string): void => {\n    if (!hasOwnKey(graphEdges, kind) || graphEdges[kind] === undefined) {\n      throw invalidPlanForTarget(\n        `The merge plan references unknown edge kind \"${kind}\".`,\n        { kind, role: \"edge\" },\n      );\n    }\n  };\n\n  for (const item of [\n    ...artifact.writes.nodeDeletes,\n    ...artifact.writes.nodeUpserts,\n    ...artifact.guards.deletedNodes,\n    ...artifact.guards.canonicalMappings.flatMap((mapping) => [\n      mapping.member,\n      mapping.canonical,\n    ]),\n    ...artifact.guards.retypes.map((retype) => retype.entity),\n    ...artifact.writes.identityAssertions.flatMap((assertion) => [\n      assertion.a,\n      assertion.b,\n    ]),\n    ...artifact.writes.identityRetractions.flatMap((assertion) => [\n      assertion.a,\n      assertion.b,\n    ]),\n  ]) {\n    assertNodeKind(item.kind);\n  }\n  for (const retype of artifact.guards.retypes) assertNodeKind(retype.toKind);\n  for (const item of [\n    ...artifact.writes.edgeDeletes,\n    ...artifact.writes.edgeUpserts,\n  ]) {\n    assertEdgeKind(item.kind);\n  }\n\n  const plannedNodes = new Set(\n    artifact.writes.nodeUpserts.map((upsert) =>\n      mergeKey(upsert.kind, upsert.id),\n    ),\n  );\n  const deletedNodes = new Set(\n    artifact.writes.nodeDeletes.map((deletion) =>\n      mergeKey(deletion.kind, deletion.id),\n    ),\n  );\n  const endpointRows = new Map<MergeKey, Node | undefined>();\n  const readEndpoint = async (\n    endpoint: MergePlanEntityRef,\n  ): Promise<Node | undefined> => {\n    const key = mergeKey(endpoint.kind, endpoint.id);\n    if (endpointRows.has(key)) return endpointRows.get(key);\n    const row = (\n      await nodeCollection(nodesApi, endpoint.kind).getByIds(\n        [endpoint.id],\n        INCLUDE_TOMBSTONES,\n      )\n    )[0];\n    endpointRows.set(key, row);\n    return row;\n  };\n  const nodeUpsertsByKind = new Map<string, MergePlanNodeUpsert[]>();\n  for (const upsert of artifact.writes.nodeUpserts) {\n    const upserts = nodeUpsertsByKind.get(upsert.kind) ?? [];\n    upserts.push(upsert);\n    nodeUpsertsByKind.set(upsert.kind, upserts);\n  }\n  const currentNodesByIdentity = new Map<MergeKey, Node | undefined>();\n  for (const [kind, upserts] of nodeUpsertsByKind) {\n    const rows = await nodeCollection(nodesApi, kind).getByIds(\n      upserts.map((upsert) => upsert.id),\n      INCLUDE_TOMBSTONES,\n    );\n    for (const [index, upsert] of upserts.entries()) {\n      const row = rows[index];\n      const identity = mergeKey(kind, upsert.id);\n      currentNodesByIdentity.set(identity, row);\n      endpointRows.set(identity, row);\n    }\n  }\n  for (const upsert of artifact.writes.nodeUpserts) {\n    const current = currentNodesByIdentity.get(\n      mergeKey(upsert.kind, upsert.id),\n    );\n    if (\n      artifact.guards.incremental !== undefined &&\n      current?.meta.deletedAt !== undefined\n    ) {\n      throw invalidPlanForTarget(\n        `The incremental merge plan would resurrect soft-deleted committed node \"${upsert.id}\".`,\n        { kind: upsert.kind, id: upsert.id, role: \"node\" },\n      );\n    }\n    const props = resolvedWireProps(\n      current === undefined ? {} : nodeProps(current),\n      upsert.setProps,\n      upsert.unsetProps,\n    );\n    const schema = nodeSchemaFor(target, upsert.kind);\n    if (schema !== undefined && !schema.safeParse(props).success) {\n      throw invalidPlanForTarget(\n        `The merge plan's node write for \"${upsert.id}\" does not validate against the active schema.`,\n        { kind: upsert.kind, id: upsert.id, role: \"node\" },\n      );\n    }\n    if (artifact.guards.incremental !== undefined && current !== undefined) {\n      const analysis = analyzeRevalidatingWrite(\n        schema,\n        nodeProps(current),\n        wireWriteProps(upsert.setProps, upsert.unsetProps),\n      );\n      assertValidRevalidatingWrite(\n        analysis,\n        `The incremental merge plan found committed node \"${upsert.id}\" with props that do not validate against the active schema.`,\n        { kind: upsert.kind, id: upsert.id, role: \"node\" },\n      );\n      if (analysis.stripsCurrentProps && analysis.schemaWouldChange) {\n        throw invalidPlanForTarget(\n          `The incremental merge plan would strip existing props while updating committed node \"${upsert.id}\".`,\n          { kind: upsert.kind, id: upsert.id, role: \"node\" },\n        );\n      }\n    }\n  }\n\n  const currentEdgeIds = new Set<string>();\n  const edgeUpsertsByKind = new Map<string, MergePlanEdgeUpsert[]>();\n  for (const upsert of artifact.writes.edgeUpserts) {\n    const upserts = edgeUpsertsByKind.get(upsert.kind) ?? [];\n    upserts.push(upsert);\n    edgeUpsertsByKind.set(upsert.kind, upserts);\n  }\n  const currentEdgesByIdentity = new Map<MergeKey, Edge | undefined>();\n  for (const [kind, upserts] of edgeUpsertsByKind) {\n    const rows = await edgeCollection(edgesApi, kind).getByIds(\n      upserts.map((upsert) => upsert.id),\n      INCLUDE_TOMBSTONES,\n    );\n    for (const [index, upsert] of upserts.entries()) {\n      const row = rows[index];\n      currentEdgesByIdentity.set(mergeKey(kind, upsert.id), row);\n      if (row !== undefined) currentEdgeIds.add(upsert.id);\n    }\n  }\n  for (const upsert of artifact.writes.edgeUpserts) {\n    const registration = requireDefined(graphEdges[upsert.kind]);\n    const endpointError = validateEdgeEndpoints(\n      upsert.kind,\n      upsert.from.kind,\n      upsert.to.kind,\n      registration,\n      target.registry,\n    );\n    if (endpointError !== undefined) {\n      throw invalidPlanForTarget(endpointError.message, {\n        kind: upsert.kind,\n        id: upsert.id,\n        role: \"edge\",\n      });\n    }\n    for (const endpoint of [upsert.from, upsert.to]) {\n      assertNodeKind(endpoint.kind);\n      const key = mergeKey(endpoint.kind, endpoint.id);\n      if (deletedNodes.has(key)) {\n        throw invalidPlanForTarget(\n          `The merge plan deletes an endpoint required by edge \"${upsert.id}\".`,\n          { edgeKind: upsert.kind, edgeId: upsert.id, endpoint },\n        );\n      }\n      if (plannedNodes.has(key)) continue;\n      const row = await readEndpoint(endpoint);\n      if (row === undefined || row.meta.deletedAt !== undefined) {\n        throw invalidPlanForTarget(\n          `The merge plan references a missing edge endpoint \"${endpoint.id}\".`,\n          { edgeKind: upsert.kind, edgeId: upsert.id, endpoint },\n        );\n      }\n    }\n    const current = currentEdgesByIdentity.get(\n      mergeKey(upsert.kind, upsert.id),\n    );\n    if (\n      artifact.guards.incremental !== undefined &&\n      current?.meta.deletedAt !== undefined\n    ) {\n      throw invalidPlanForTarget(\n        `The incremental merge plan would resurrect soft-deleted committed edge \"${upsert.id}\".`,\n        { kind: upsert.kind, id: upsert.id, role: \"edge\" },\n      );\n    }\n    const props = resolvedWireProps(\n      current === undefined ? {} : edgeProps(current),\n      upsert.setProps,\n      upsert.unsetProps,\n    );\n    const schema = edgeSchemaFor(target, upsert.kind);\n    if (schema !== undefined && !schema.safeParse(props).success) {\n      throw invalidPlanForTarget(\n        `The merge plan's edge write for \"${upsert.id}\" does not validate against the active schema.`,\n        { kind: upsert.kind, id: upsert.id, role: \"edge\" },\n      );\n    }\n    if (artifact.guards.incremental !== undefined && current !== undefined) {\n      const analysis = analyzeRevalidatingWrite(\n        schema,\n        edgeProps(current),\n        wireWriteProps(upsert.setProps, upsert.unsetProps),\n      );\n      assertValidRevalidatingWrite(\n        analysis,\n        `The incremental merge plan found committed edge \"${upsert.id}\" with props that do not validate against the active schema.`,\n        { kind: upsert.kind, id: upsert.id, role: \"edge\" },\n      );\n      if (analysis.stripsCurrentProps && analysis.schemaWouldChange) {\n        throw invalidPlanForTarget(\n          `The incremental merge plan would strip existing props while updating committed edge \"${upsert.id}\".`,\n          { kind: upsert.kind, id: upsert.id, role: \"edge\" },\n        );\n      }\n    }\n    if (\n      current !== undefined &&\n      (current.fromKind !== upsert.from.kind ||\n        current.fromId !== upsert.from.id ||\n        current.toKind !== upsert.to.kind ||\n        current.toId !== upsert.to.id)\n    ) {\n      throw invalidPlanForTarget(\n        `The merge plan would change the immutable endpoints of edge \"${upsert.id}\".`,\n        { kind: upsert.kind, id: upsert.id, role: \"edge\" },\n      );\n    }\n  }\n\n  const missingEdgeIds = artifact.writes.edgeUpserts\n    .map((upsert) => upsert.id)\n    .filter((id) => !currentEdgeIds.has(id));\n  if (missingEdgeIds.length > 0) {\n    const plannedEdgeById = new Map(\n      artifact.writes.edgeUpserts.map((upsert) => [upsert.id, upsert]),\n    );\n    for (const kind of Object.keys(target.graph.edges)) {\n      const rows = await edgeCollection(edgesApi, kind).getByIds(\n        missingEdgeIds,\n        INCLUDE_TOMBSTONES,\n      );\n      for (const [index, row] of rows.entries()) {\n        if (row === undefined) continue;\n        const id = requireDefined(missingEdgeIds[index]);\n        const planned = plannedEdgeById.get(id);\n        if (planned !== undefined && planned.kind !== row.kind) {\n          throw invalidPlanForTarget(\n            `The merge plan reuses edge id \"${id}\" across kinds.`,\n            { id, committedKind: row.kind, plannedKind: planned.kind },\n          );\n        }\n      }\n    }\n  }\n}\n\nasync function assertMergePlanFenceInsideTransaction<G extends GraphDef>(\n  target: Store<G>,\n  txBackend: TransactionBackend,\n  artifact: MergePlanArtifactV1,\n  requireFreshSnapshot: boolean,\n): Promise<void> {\n  await lockMergeTargetWrite(txBackend, {\n    graphId: target.graphId,\n    schemaVersion:\n      artifact.target.schema.managed ?\n        artifact.target.schema.version\n      : undefined,\n    graphLock: \"required\",\n    requireFreshSnapshot,\n    staleSchemaError: (cause) =>\n      new MergePlanSchemaMismatchError(\n        \"The target's active schema no longer matches the merge plan.\",\n        { cause, details: { expected: artifact.target.schema } },\n      ),\n  });\n  const activeSchema = await txBackend.getActiveSchema(target.graphId);\n  const liveSchema = {\n    managed: activeSchema !== undefined,\n    version: activeSchema?.version ?? 1,\n    hash: activeSchema?.schema_hash ?? (await computeSchemaComponent(target)),\n  };\n  if (\n    liveSchema.managed !== artifact.target.schema.managed ||\n    liveSchema.version !== artifact.target.schema.version ||\n    liveSchema.hash !== artifact.target.schema.hash\n  ) {\n    throw new MergePlanSchemaMismatchError(\n      \"The target's active schema no longer matches the merge plan.\",\n      { details: { expected: artifact.target.schema, live: liveSchema } },\n    );\n  }\n  const liveOrigin = await readRevisionOrigin(\n    txBackend,\n    target.revisionSchema,\n    target.graphId,\n  );\n  if (liveOrigin !== artifact.target.revision.origin) {\n    throw new MergePlanOriginMismatchError(\n      \"The merge plan belongs to a different target revision origin.\",\n      {\n        details: {\n          expectedOrigin: artifact.target.revision.origin,\n          liveOrigin,\n        },\n      },\n    );\n  }\n  const liveRevision =\n    (await readRecordedClock(\n      txBackend,\n      target.revisionSchema,\n      target.graphId,\n    )) ?? null;\n  if (liveRevision !== artifact.target.revision.revision) {\n    throw new StaleMergePlanError(\n      \"The target revision changed after this merge plan was created; the plan was not applied.\",\n      {\n        details: {\n          expectedRevision: artifact.target.revision.revision,\n          liveRevision,\n        },\n      },\n    );\n  }\n}\n\nfunction identityConsistencySeeds(\n  artifact: MergePlanArtifactV1,\n  profile: \"fold\" | \"ignore\" | undefined,\n): readonly MergePlanEntityRef[] {\n  const deleted = new Set(\n    artifact.writes.nodeDeletes.map((entity) =>\n      mergeKey(entity.kind, entity.id),\n    ),\n  );\n  const byIdentity = new Map<MergeKey, MergePlanEntityRef>();\n  const add = (entity: MergePlanEntityRef): void => {\n    const identity = mergeKey(entity.kind, entity.id);\n    if (!deleted.has(identity)) byIdentity.set(identity, entity);\n  };\n  for (const assertion of [\n    ...artifact.writes.identityAssertions,\n    ...artifact.writes.identityRetractions,\n  ]) {\n    add(assertion.a);\n    add(assertion.b);\n  }\n  if (profile === \"fold\") {\n    for (const upsert of artifact.writes.nodeUpserts) add(upsert);\n  }\n  return [...byIdentity]\n    .sort(([left], [right]) => compareMergeKeys(left, right))\n    .map(([, entity]) => entity);\n}\n\nasync function applyWireMergeWrites<G extends GraphDef>(\n  target: Store<G>,\n  nodesApi: TxNodes,\n  edgesApi: TxEdges,\n  txBackend: TransactionBackend,\n  artifact: MergePlanArtifactV1,\n): Promise<MergedCounts> {\n  const committedNodes = await applyNodeRows(\n    target,\n    txBackend,\n    nodesApi,\n    artifact.writes.nodeDeletes,\n    artifact.writes.nodeUpserts.map((upsert) => ({\n      kind: upsert.kind,\n      id: upsert.id,\n      props: wireWriteProps(upsert.setProps, upsert.unsetProps),\n      ...(upsert.validFrom === undefined ?\n        {}\n      : { validFrom: upsert.validFrom }),\n      ...(upsert.validTo === undefined ? {} : { validTo: upsert.validTo }),\n    })),\n  );\n  const committedEdges = await applyEdgeRows(\n    edgesApi,\n    artifact.writes.edgeDeletes,\n    artifact.writes.edgeUpserts.map((upsert) => ({\n      kind: upsert.kind,\n      item: {\n        id: upsert.id,\n        from: upsert.from,\n        to: upsert.to,\n        props: wireWriteProps(upsert.setProps, upsert.unsetProps),\n        ...(upsert.validFrom === undefined ?\n          {}\n        : { validFrom: upsert.validFrom }),\n        ...(upsert.validTo === undefined ? {} : { validTo: upsert.validTo }),\n      },\n    })),\n  );\n  const identityAssertions = artifact.writes\n    .identityAssertions as readonly IdentityTransferAssertion[];\n  const identityRetractions = artifact.writes\n    .identityRetractions as readonly IdentityTransferAssertion[];\n  const appliedIdentity = await applyIdentityRows(\n    target,\n    txBackend,\n    identityAssertions,\n    identityRetractions,\n    () =>\n      storeRuntime(target).assertIdentityClassesConsistentAtTarget(\n        txBackend,\n        identityConsistencySeeds(\n          artifact,\n          target.graph.identity?.sameIdAcrossKinds,\n        ),\n      ),\n  );\n  if (\n    !forceRecordedGraphRevision(txBackend, target.graphId) &&\n    !forceWriteTransactionRevision(txBackend)\n  ) {\n    await advanceRevisionClock(\n      txBackend,\n      target.revisionSchema,\n      target.graphId,\n      true,\n    );\n  }\n  return {\n    nodes: committedNodes,\n    edges: committedEdges,\n    identity: {\n      asserted: appliedIdentity.asserted,\n      retracted: appliedIdentity.retracted,\n    },\n  };\n}\n\nexport function reportFromArtifact<G extends GraphDef>(\n  artifact: MergePlanArtifactV1,\n  merged: MergedCounts,\n  warnings: readonly string[],\n  provenancePersisted?: MergeReport<G>[\"provenancePersisted\"],\n): MergeReport<G> {\n  const provenanceRecords = artifact.review\n    .provenanceRecords as unknown as readonly ProvenanceRecord[];\n  return {\n    merged,\n    resolutions: artifact.review\n      .resolutions as unknown as readonly EntityResolution[],\n    conflicts: artifact.review\n      .conflicts as unknown as readonly PropertyConflict<G>[],\n    deleteModifyConflicts: artifact.review\n      .deleteModifyConflicts as unknown as readonly DeleteModifyConflict[],\n    typeReconciliations: artifact.review\n      .typeReconciliations as unknown as readonly TypeReconciliation[],\n    dropped: artifact.review.dropped as unknown as readonly DroppedItem[],\n    validityEnds: artifact.review\n      .validityEnds as unknown as readonly ValidityEndResolution[],\n    baseAmbiguities: artifact.review\n      .baseAmbiguities as unknown as readonly BaseAmbiguity[],\n    provenance:\n      artifact.provenance.includeInReport ?\n        buildProvenanceIndex(provenanceRecords)\n      : { byBranch: () => ({ nodeIds: [], edgeIds: [] }) },\n    warnings,\n    ...(artifact.review.diagnostics === undefined ?\n      {}\n    : {\n        candidateDiagnostics: artifact.review\n          .diagnostics as unknown as CandidateDiagnostics,\n      }),\n    ...(provenancePersisted === undefined ? {} : { provenancePersisted }),\n  };\n}\n\n/** Validates a serialized merge plan and binds it to its target graph. */\nexport async function validateMergePlanForTarget<G extends GraphDef>(\n  target: Store<G>,\n  input: MergePlanArtifact,\n): Promise<MergePlanArtifactV1> {\n  let validation: Awaited<ReturnType<typeof validateMergePlanArtifact>>;\n  try {\n    validation = await validateMergePlanArtifact(input);\n  } catch (error) {\n    throw new InvalidMergePlanError(\n      `Merge plan validation failed: ${describeCause(error)}`,\n      { cause: error },\n    );\n  }\n  if (!validation.success) throw mergePlanValidationError(validation.error);\n  const artifact = validation.artifact;\n  if (artifact.target.graphId !== target.graphId) {\n    throw new MergePlanTargetMismatchError(\n      \"The merge plan names a different target graph.\",\n      {\n        details: {\n          expectedGraphId: artifact.target.graphId,\n          receivedGraphId: target.graphId,\n        },\n      },\n    );\n  }\n  return artifact;\n}\n\nasync function applyValidatedMergePlanInTransaction<G extends GraphDef>(\n  target: Store<G>,\n  tx: TransactionContext<G>,\n  artifact: MergePlanArtifactV1,\n  options: MergePlanApplyOptions<G>,\n  requireFreshSnapshot: boolean,\n): Promise<MergedCounts> {\n  const { beforeApply, afterApply } = options;\n  const txBackend = transactionBackend(tx);\n  await assertMergePlanFenceInsideTransaction(\n    target,\n    txBackend,\n    artifact,\n    requireFreshSnapshot,\n  );\n  if (beforeApply !== undefined) {\n    assertMergeCallbackResult(\n      await beforeApply(mergePlanReadContext(tx, target.graph)),\n      \"beforeApply\",\n    );\n  }\n  await preflightWireMergeWrites(\n    target,\n    tx.nodes as unknown as TxNodes,\n    tx.edges as unknown as TxEdges,\n    artifact,\n  );\n  await assertPlannedIdentityIdsFresh(target, txBackend, {\n    identityAssertions: artifact.writes.identityAssertions,\n    identityRetractions: artifact.writes.identityRetractions,\n  });\n  const applied = await applyWireMergeWrites(\n    target,\n    tx.nodes as unknown as TxNodes,\n    tx.edges as unknown as TxEdges,\n    txBackend,\n    artifact,\n  );\n  if (afterApply !== undefined) {\n    assertMergeCallbackResult(\n      await afterApply(tx, { merged: structuredClone(applied) }),\n      \"afterApply\",\n    );\n  }\n  return applied;\n}\n\n/** Validates and atomically applies an approved serialized merge plan. */\nexport async function applyMergePlan<G extends GraphDef>(\n  target: Store<G>,\n  input: MergePlanArtifact,\n  options: MergePlanApplyOptions<NoInfer<G>> = {},\n): Promise<Result<MergeReport<G>, MergeError>> {\n  let artifact: MergePlanArtifactV1;\n  try {\n    artifact = await validateMergePlanForTarget(target, input);\n  } catch (error) {\n    return err(\n      error instanceof MergeError ? error : (\n        new InvalidMergePlanError(\n          `Merge plan validation failed: ${describeCause(error)}`,\n          { cause: error },\n        )\n      ),\n    );\n  }\n  try {\n    const { beforeApply, afterApply } = options;\n    const composed = beforeApply !== undefined || afterApply !== undefined;\n    const transactionOptions =\n      composed ?\n        ({ isolationLevel: \"read_committed\" } as const)\n      : mergeCommitTransactionOptions(target);\n    assertPublicPlanCapability(target);\n    const provenanceStore =\n      artifact.provenance.persist ?\n        await tryOpenProvenanceStore(target)\n      : undefined;\n    if (provenanceStore !== undefined && isErr(provenanceStore)) {\n      return err(provenanceStore.error);\n    }\n    const merged = await runRetriedUnit(\n      {\n        operation: \"applyMergePlan\",\n        attempts: MERGE_COMMIT_ATTEMPTS,\n        target: storeBackend(target),\n      },\n      () =>\n        target.transaction(\n          (tx) =>\n            applyValidatedMergePlanInTransaction(\n              target,\n              tx,\n              artifact,\n              options,\n              composed,\n            ),\n          transactionOptions,\n        ),\n    );\n    const warnings = [...artifact.review.warnings];\n    let provenancePersisted: MergeReport<G>[\"provenancePersisted\"];\n    if (provenanceStore !== undefined && !isErr(provenanceStore)) {\n      try {\n        const records = artifact.review\n          .provenanceRecords as unknown as readonly ProvenanceRecord[];\n        const count = await persistProvenanceRecords(\n          provenanceStore.data,\n          target.graphId,\n          records,\n        );\n        provenancePersisted = {\n          graphId: provenanceGraphId(target.graphId),\n          count,\n        };\n      } catch (error) {\n        warnings.push(\n          \"provenance persistence failed (graph committed; provenance not persisted): \" +\n            describeCause(error),\n        );\n      }\n    }\n    return ok(\n      reportFromArtifact(artifact, merged, warnings, provenancePersisted),\n    );\n  } catch (error) {\n    const translated = translateMergeCommitError(error);\n    return err(\n      translated instanceof MergeError ? translated : (\n        new MergeError(\n          `Merge plan apply failed: ${describeCause(translated)}`,\n          {\n            cause: translated,\n          },\n        )\n      ),\n    );\n  }\n}\n\n/**\n * Applies an approved serialized merge plan through a caller-owned transaction.\n * `tx` must belong to a currently active callback of `target`; retained contexts\n * and contexts created by another Store are refused. Apply the plan before any\n * graph writes in that transaction, because pending writes are not represented by\n * the plan's durable revision fence.\n *\n * The caller owns commit, rollback, and whole-transaction retry. This function\n * opens no transaction and throws on every failure so the surrounding callback\n * rejects rather than accidentally committing partial work. Plans requesting\n * persisted provenance are refused because the sidecar cannot yet be enlisted in\n * this caller-owned transaction.\n */\nexport async function applyMergePlanInTransaction<G extends GraphDef>(\n  target: Store<G>,\n  tx: TransactionContext<NoInfer<G>>,\n  input: MergePlanArtifact,\n): Promise<MergeReport<G>> {\n  try {\n    let effectiveTarget: Store<G>;\n    try {\n      effectiveTarget = resolveEvolvedTransactionStore(tx, target);\n    } catch (error) {\n      throw new MergePlanCapabilityError(\n        \"The merge transaction must belong to an active callback of the target Store.\",\n        { cause: error, details: { capability: \"mergeTransactionStore\" } },\n      );\n    }\n    const artifact = await validateMergePlanForTarget(effectiveTarget, input);\n    assertPublicPlanCapability(effectiveTarget);\n    if (artifact.provenance.persist) {\n      throw new MergePlanCapabilityError(\n        \"A caller-owned merge transaction cannot persist merge provenance atomically.\",\n        {\n          details: { capability: \"adoptedMergeProvenance\" },\n          suggestion:\n            \"Create the merge plan without persisted provenance, or apply it through applyMergePlan so TypeGraph can manage provenance persistence.\",\n        },\n      );\n    }\n    const txBackend = transactionBackend(tx);\n    await assertMergeTransactionPristine(effectiveTarget, txBackend);\n    const merged = await applyValidatedMergePlanInTransaction(\n      effectiveTarget,\n      tx,\n      artifact,\n      {},\n      true,\n    );\n    return reportFromArtifact(artifact, merged, artifact.review.warnings);\n  } catch (error) {\n    const translated = translateMergeCommitError(error);\n    throw translated instanceof MergeError ? translated : (\n        new MergeError(\n          `Merge plan apply failed: ${describeCause(translated)}`,\n          { cause: translated },\n        )\n      );\n  }\n}\n\n/**\n * Merges a set of branches back into a target store (design §7.2).\n *\n * Validates that every branch forked from the target's current `base@V`, stages\n * the union of their diffs, resolves entities / conflicts / types through the\n * T3–T10 phases, and commits the merged result to `target` (default: the base\n * `store`) in a single transaction. Returns a {@link MergeReport} on success.\n *\n * This is the SNAPSHOT entry point: candidate generation runs the staged sources\n * only (`exactKey`, `unique`) — it never resolves a staged node against the\n * committed base. New-vs-base resolution is the separate {@link mergeAgainstBase}\n * scope, which has a weaker `base@V` contract.\n *\n * Errors are RETURNED (never thrown) as a typed {@link MergeError} subclass:\n * `BaseVersionMismatchError` for the precondition, `MergeError` for a\n * comparison-ceiling overrun / commit failure, `SimilarityUnavailableError` for a\n * `vector`/`hybrid` strategy with no configured vector strategy.\n *\n * @param store The base store the branches forked from. Used as the default merge\n *   target and as the immutable diff reference.\n * @param branches The branches to merge. ORDER DOES NOT AFFECT THE RESULT — the\n *   report and committed graph are identical across any permutation.\n * @param optionsInput Caller-facing {@link MergeOptions}; normalized internally.\n */\nexport async function merge<G extends GraphDef>(\n  store: Store<G>,\n  branchInputs: readonly MergeBranch<G>[],\n  optionsInput: MergeOptions<G> = {},\n): Promise<Result<MergeReport<G>, MergeError>> {\n  const branches = unwrapMergeBranches(branchInputs);\n  const normalized = tryNormalize(optionsInput);\n  if (isErr(normalized)) {\n    return err(normalized.error);\n  }\n  const options = normalized.data;\n  const target = options.target ?? store;\n\n  // (1) base@V precondition — the snapshot contract. The validated token is\n  // re-checked INSIDE the commit transaction (see `commitPlan`), so a target\n  // write landing between this check and the commit fails typed instead of\n  // committing a stale plan.\n  const precondition = await validateBaseVersions(target, branches);\n  if (isErr(precondition)) {\n    return err(precondition.error);\n  }\n\n  return resolveMerge(\n    store,\n    target,\n    branches,\n    options,\n    false,\n    undefined,\n    precondition.data,\n    commitResolvedMerge,\n  );\n}\n\n/**\n * SYNTHETIC new-vs-base merge scope (design §8 \"Slice 1\"). Runs the full\n * candidate-source + scoring + reconciler pipeline WITH the base sources active —\n * so a staged node re-discovering a committed entity resolves against it\n * (base-id-wins, update-not-insert) — while DELIBERATELY bypassing the `base@V`\n * snapshot precondition (§6.4-B) rather than fighting it.\n *\n * This is the lower-level scope the slice's mechanism is built and exercised behind\n * (the fixed-point + determinism gates drive it directly), and it is intentionally\n * NOT re-exported from the package barrel. The public incremental surface over it\n * is {@link mergeIncremental} (§6.6), which adds the fork-point precondition, the\n * keep-base pin, and the transaction-scoped existing-row guard. `merge()` and its\n * snapshot precondition are unchanged.\n */\nexport async function mergeAgainstBase<G extends GraphDef>(\n  store: Store<G>,\n  branchInputs: readonly MergeBranch<G>[],\n  optionsInput: MergeOptions<G> = {},\n): Promise<Result<MergeReport<G>, MergeError>> {\n  const branches = unwrapMergeBranches(branchInputs);\n  const normalized = tryNormalize(optionsInput);\n  if (isErr(normalized)) {\n    return err(normalized.error);\n  }\n  const options = normalized.data;\n  const target = options.target ?? store;\n\n  // No branch-level base@V precondition here (the synthetic scope's contract),\n  // but PLAN STABILITY still holds: the token captured before any planning\n  // read is re-validated inside the commit transaction, so the target must not\n  // move while THIS merge is in flight.\n  const expectedBaseVersion = await computeBaseVersion(target);\n  return resolveMerge(\n    store,\n    target,\n    branches,\n    options,\n    true,\n    undefined,\n    expectedBaseVersion,\n    commitResolvedMerge,\n  );\n}\n\n// --- mergeIncremental: full fork-point-vs-live-target entry point (§6.6) -------\n\n/**\n * The fork-point premise {@link mergeIncremental} established BEFORE planning:\n * this store, at this `base@V`, is the immutable ancestor every branch diff was\n * computed against. Carried into the commit so it can be re-established at the\n * point of no return (see {@link assertForkPointUnchanged}).\n */\ntype ForkPointPrecondition<G extends GraphDef> = Readonly<{\n  store: Store<G>;\n  version: BaseVersion;\n}>;\n\n/** Internal config carried into {@link resolveMerge} for incremental mode. */\ntype IncrementalConfig<G extends GraphDef> = Readonly<{\n  targetBranchId: BranchId;\n  forkPoint: ForkPointPrecondition<G>;\n}>;\n\n/**\n * Incremental precondition: every branch must have forked from THIS fork-point, so\n * the fork-point diff (fork-point → branch) is honest. The analogue of\n * {@link validateBaseVersions}, repointed from `target` to `forkPoint` (§6.6) —\n * including the same {@link toleratedByEngineAnchor} tolerance for an\n * engine-wide bump that lands on the fork point between `branch()` and this\n * precondition without touching any of this graph's own rows.\n */\nasync function validateForkPointVersions<G extends GraphDef>(\n  forkPoint: Store<G>,\n  branches: readonly GraphBranch<G>[],\n): Promise<Result<BaseVersion, BaseVersionMismatchError>> {\n  const forkVersion = await computeBaseVersion(forkPoint);\n  for (const branch of branches) {\n    if (branch.base === forkVersion) continue;\n    if (await toleratedByEngineAnchor(forkPoint, branch.base, forkVersion)) {\n      continue;\n    }\n    return err(\n      new BaseVersionMismatchError(\n        `Branch \"${branch.id}\" forked from base@V \"${branch.base}\", which does not match the fork-point's base@V \"${forkVersion}\". mergeIncremental() requires every branch to have forked from the supplied forkPoint.`,\n        {\n          details: {\n            branchId: branch.id,\n            branchBase: branch.base,\n            forkPointBase: forkVersion,\n          },\n        },\n      ),\n    );\n  }\n  return ok(forkVersion);\n}\n\n/**\n * The minimal schema surface the write guards need: a kind's Zod schema, called the\n * SAME way the commit calls it (`safeParse`). Structural so the guard couples to the\n * parse behaviour, not a zod version.\n */\ntype PropsSchema = Readonly<{\n  safeParse: (\n    value: unknown,\n  ) => { success: true; data: unknown } | { success: false };\n}>;\n\ntype RevalidatingWriteAnalysis =\n  | Readonly<{\n      status: \"valid\";\n      /** Whether TypeGraph's re-validating write would change persisted bytes. */\n      storageWouldChange: boolean;\n      /** Whether declared schema fields would change, ignoring unknown stored keys. */\n      schemaWouldChange: boolean;\n      /** Whether the write would drop current props not preserved by the schema. */\n      stripsCurrentProps: boolean;\n    }>\n  | Readonly<{ status: \"invalid\" }>;\n\n/** The declared schema for a node kind off the public `GraphDef` registry (or none). */\nfunction nodeSchemaFor<G extends GraphDef>(\n  target: Store<G>,\n  kind: string,\n): PropsSchema | undefined {\n  const registry = target.graph.nodes as Record<\n    string,\n    Readonly<{ type?: Readonly<{ schema?: PropsSchema }> }> | undefined\n  >;\n  return registry[kind]?.type?.schema;\n}\n\n/** The declared schema for an edge kind off the public `GraphDef` registry (or none). */\nfunction edgeSchemaFor<G extends GraphDef>(\n  target: Store<G>,\n  kind: string,\n): PropsSchema | undefined {\n  const registry = target.graph.edges as Record<\n    string,\n    Readonly<{ type?: Readonly<{ schema?: PropsSchema }> }> | undefined\n  >;\n  return registry[kind]?.type?.schema;\n}\n\n/**\n * Models TypeGraph's re-validating update semantics for one row —\n * `schema.safeParse({...current, ...planned})`, then storing the parsed result —\n * so `mergeIncremental()` can route each planned write to create / update / skip /\n * error from INSIDE the target transaction, where `current` is the row the commit\n * will actually overwrite.\n */\nfunction analyzeRevalidatingWrite(\n  schema: PropsSchema | undefined,\n  current: Readonly<Record<string, unknown>>,\n  planned: Readonly<Record<string, unknown>>,\n): RevalidatingWriteAnalysis {\n  const merged = { ...current, ...planned };\n  if (schema === undefined) {\n    const storageWouldChange =\n      canonicalizeProps(merged) !== canonicalizeProps(current);\n    return {\n      status: \"valid\",\n      storageWouldChange,\n      schemaWouldChange: storageWouldChange,\n      stripsCurrentProps: false,\n    };\n  }\n\n  const currentParsed = schema.safeParse(current);\n  const mergedParsed = schema.safeParse(merged);\n  if (!currentParsed.success || !mergedParsed.success) {\n    return { status: \"invalid\" };\n  }\n  const normalizedCurrent = currentParsed.data as Record<string, unknown>;\n  const normalizedMerged = mergedParsed.data as Record<string, unknown>;\n  return {\n    status: \"valid\",\n    storageWouldChange:\n      canonicalizeProps(normalizedMerged) !== canonicalizeProps(current),\n    schemaWouldChange:\n      canonicalizeProps(normalizedMerged) !==\n      canonicalizeProps(normalizedCurrent),\n    stripsCurrentProps:\n      canonicalizeProps(normalizedCurrent) !== canonicalizeProps(current),\n  };\n}\n\nexport function writeWouldChangeRow(\n  schema: PropsSchema | undefined,\n  committed: Readonly<Record<string, unknown>>,\n  planned: Readonly<Record<string, unknown>>,\n): boolean {\n  const analysis = analyzeRevalidatingWrite(schema, committed, planned);\n  return analysis.status === \"valid\" ? analysis.storageWouldChange : false;\n}\n\n/**\n * Public node objects spread props at top-level. Strip TypeGraph structural keys so\n * write comparisons operate on the persisted props bag only.\n */\nfunction nodeProps(node: Node): Record<string, unknown> {\n  // Data-keyed: schema property names spread onto the public node.\n  const props = createDataKeyedBag<unknown>();\n  for (const [key, value] of Object.entries(node)) {\n    if (key === \"id\" || key === \"kind\" || key === \"meta\") continue;\n    props[key] = value;\n  }\n  return props;\n}\n\n/**\n * Public edge objects spread props at top-level. Strip TypeGraph structural keys so\n * write comparisons operate on the persisted props bag only.\n */\nfunction edgeProps(edge: Edge): Record<string, unknown> {\n  // Data-keyed: schema property names spread onto the public edge.\n  const props = createDataKeyedBag<unknown>();\n  for (const [key, value] of Object.entries(edge)) {\n    if (\n      key === \"id\" ||\n      key === \"kind\" ||\n      key === \"fromKind\" ||\n      key === \"fromId\" ||\n      key === \"toKind\" ||\n      key === \"toId\" ||\n      key === \"meta\"\n    ) {\n      continue;\n    }\n    props[key] = value;\n  }\n  return props;\n}\n\nconst INCLUDE_TOMBSTONES = { temporalMode: \"includeTombstones\" as const };\n\nfunction assertValidRevalidatingWrite(\n  analysis: RevalidatingWriteAnalysis,\n  message: string,\n  details: Record<string, unknown>,\n): asserts analysis is Extract<RevalidatingWriteAnalysis, { status: \"valid\" }> {\n  if (analysis.status === \"invalid\") {\n    throw new MergeError(message, { details });\n  }\n}\n\nfunction edgeWriteSignature<G extends GraphDef>(\n  edge: MergedEdge,\n  plan: MergePlan<G>,\n): string {\n  const from = finalEdgeEndpoint(plan, edge.fromKind, edge.fromId);\n  const to = finalEdgeEndpoint(plan, edge.toKind, edge.toId);\n  return JSON.stringify([\n    edge.kind,\n    from.kind,\n    from.id,\n    to.kind,\n    to.id,\n    canonicalizeProps(edge.props),\n  ]);\n}\n\nasync function validateIncrementalNodeWrites<G extends GraphDef>(\n  target: Store<G>,\n  nodesApi: TxNodes,\n  plan: MergePlan<G>,\n): Promise<void> {\n  const writes = plannedNodeWrites(plan);\n  const nodeIdsByKind = new Map<string, AnyNodeId[]>();\n  for (const write of writes) {\n    const bucket = nodeIdsByKind.get(write.kind) ?? [];\n    bucket.push(write.id);\n    nodeIdsByKind.set(write.kind, bucket);\n  }\n\n  const currentByIdentity = new Map<MergeKey, Node | undefined>();\n  for (const [kind, ids] of nodeIdsByKind) {\n    const rows = await nodeCollection(nodesApi, kind).getByIds(\n      ids,\n      INCLUDE_TOMBSTONES,\n    );\n    for (const [index, id] of ids.entries()) {\n      currentByIdentity.set(mergeKey(kind, id), rows[index]);\n    }\n  }\n\n  for (const write of writes) {\n    const current = currentByIdentity.get(write.identity);\n    if (current === undefined) {\n      continue;\n    }\n    if (current.meta.deletedAt !== undefined) {\n      throw new MergeError(\n        `mergeIncremental() would resurrect soft-deleted committed node \"${write.id}\" (kind \"${write.kind}\").`,\n        { details: { id: write.id, kind: write.kind } },\n      );\n    }\n    const analysis = analyzeRevalidatingWrite(\n      nodeSchemaFor(target, write.kind),\n      nodeProps(current),\n      nodeWriteProps(write, (modification) => modification.forkProps),\n    );\n    assertValidRevalidatingWrite(\n      analysis,\n      `mergeIncremental() found an existing committed node \"${write.id}\" (kind \"${write.kind}\") whose current props do not validate against the active schema.`,\n      { id: write.id, kind: write.kind },\n    );\n    if (analysis.stripsCurrentProps && analysis.schemaWouldChange) {\n      throw new MergeError(\n        `mergeIncremental() would update committed node \"${write.id}\" (kind \"${write.kind}\") but the write would strip existing props outside the active schema (lossy base update).`,\n        { details: { id: write.id, kind: write.kind } },\n      );\n    }\n  }\n}\n\nasync function validateIncrementalEdgeWrites<G extends GraphDef>(\n  target: Store<G>,\n  edgesApi: TxEdges,\n  plan: MergePlan<G>,\n): Promise<void> {\n  const signatureById = new Map<EdgeId, string>();\n  for (const edge of plan.mergedEdges) {\n    const signature = edgeWriteSignature(edge, plan);\n    const existing = signatureById.get(edge.id);\n    if (existing !== undefined && existing !== signature) {\n      throw new MergeError(\n        `mergeIncremental() would overwrite committed edge \"${edge.id}\" with multiple planned endpoint/prop shapes (edge.id collision).`,\n        { details: { id: edge.id } },\n      );\n    }\n    signatureById.set(edge.id, signature);\n  }\n\n  // Bucket the planned edges by their PLANNED kind and fetch each kind's ids in a\n  // single round-trip. An edge belongs to exactly one kind, so this does O(edges)\n  // lookups instead of scanning EVERY schema edge kind for every id (the old\n  // O(edgeKinds × edges) fan-out that held the write lock far longer than needed).\n  const plannedKindById = new Map<EdgeId, string>();\n  const idsByKind = new Map<string, EdgeId[]>();\n  for (const edge of plan.mergedEdges) {\n    if (plannedKindById.has(edge.id)) {\n      continue; // shape already deduped by the signature guard above\n    }\n    plannedKindById.set(edge.id, edge.kind);\n    const bucket = idsByKind.get(edge.kind) ?? [];\n    bucket.push(edge.id);\n    idsByKind.set(edge.kind, bucket);\n  }\n  const existingById = new Map<string, Edge>();\n  for (const [kind, ids] of idsByKind) {\n    const rows = await edgeCollection(edgesApi, kind).getByIds(\n      ids,\n      INCLUDE_TOMBSTONES,\n    );\n    for (const [index, id] of ids.entries()) {\n      const row = rows[index];\n      if (row !== undefined) {\n        existingById.set(id, row);\n      }\n    }\n  }\n\n  // Cross-kind collision guard: edge ids are GLOBALLY unique, so an id NOT found\n  // under its planned kind may still be committed under a DIFFERENT kind — a silent\n  // overwrite hazard. Scan the schema's edge kinds for ONLY those not-found ids,\n  // through the transaction's collections (never `target.backend`, whose separate\n  // connection would deadlock against the tx-held one). An update-only merge finds\n  // every edge in the bucketed pass above, so this fallback is empty.\n  const notFound = [...plannedKindById.keys()]\n    .filter((id) => !existingById.has(id))\n    .sort((left, right) => compareStrings(left, right));\n  if (notFound.length > 0) {\n    // Sequential: all queries share the same transaction client (a single\n    // pg PoolClient). Concurrent client.query() calls on a PoolClient queue\n    // with a deprecation warning in pg@8 and become an error in pg@9.\n    const crossKindById = new Map<string, Edge>();\n    for (const kind of Object.keys(target.graph.edges)) {\n      const rows = await edgeCollection(edgesApi, kind).getByIds(\n        notFound,\n        INCLUDE_TOMBSTONES,\n      );\n      for (const [index, id] of notFound.entries()) {\n        const row = rows[index];\n        if (row !== undefined && !crossKindById.has(id)) {\n          crossKindById.set(id, row);\n        }\n      }\n    }\n    for (const id of notFound) {\n      const row = crossKindById.get(id);\n      if (row === undefined) {\n        continue;\n      }\n      if (row.meta.deletedAt !== undefined) {\n        throw new MergeError(\n          `mergeIncremental() would resurrect soft-deleted committed edge \"${id}\" (kind \"${row.kind}\").`,\n          { details: { id, committedKind: row.kind } },\n        );\n      }\n      throw new MergeError(\n        `mergeIncremental() would overwrite committed edge \"${id}\" (kind \"${row.kind}\") with a different-kind edge \"${requireDefined(plannedKindById.get(id))}\" of the same id.`,\n        {\n          details: {\n            id,\n            committedKind: row.kind,\n            plannedKind: requireDefined(plannedKindById.get(id)),\n          },\n        },\n      );\n    }\n  }\n\n  for (const edge of plan.mergedEdges) {\n    const current = existingById.get(edge.id);\n    if (current === undefined) {\n      continue;\n    }\n    // `current` was fetched under `edge.kind`, so its kind matches by construction;\n    // a different committed kind for this id is caught by the cross-kind guard above.\n    if (current.meta.deletedAt !== undefined) {\n      throw new MergeError(\n        `mergeIncremental() would resurrect soft-deleted committed edge \"${edge.id}\" (kind \"${current.kind}\").`,\n        { details: { id: edge.id, committedKind: current.kind } },\n      );\n    }\n\n    const from = finalEdgeEndpoint(plan, edge.fromKind, edge.fromId);\n    const to = finalEdgeEndpoint(plan, edge.toKind, edge.toId);\n    if (\n      current.fromId !== from.id ||\n      current.fromKind !== from.kind ||\n      current.toId !== to.id ||\n      current.toKind !== to.kind\n    ) {\n      throw new MergeError(\n        `mergeIncremental() would overwrite committed edge \"${edge.id}\" (kind \"${edge.kind}\") with different endpoints.`,\n        { details: { id: edge.id, kind: edge.kind } },\n      );\n    }\n\n    const analysis = analyzeRevalidatingWrite(\n      edgeSchemaFor(target, edge.kind),\n      edgeProps(current),\n      edge.props,\n    );\n    assertValidRevalidatingWrite(\n      analysis,\n      `mergeIncremental() found an existing committed edge \"${edge.id}\" (kind \"${edge.kind}\") whose current props do not validate against the active schema.`,\n      { id: edge.id, kind: edge.kind },\n    );\n    if (analysis.stripsCurrentProps && analysis.schemaWouldChange) {\n      throw new MergeError(\n        `mergeIncremental() would update committed edge \"${edge.id}\" (kind \"${edge.kind}\") but the write would strip existing props outside the active schema.`,\n        { details: { id: edge.id, kind: edge.kind } },\n      );\n    }\n  }\n}\n\n/**\n * The reads `commitIncrementalPlan` needs to re-run the NEW-vs-BASE identity\n * resolution INSIDE the commit transaction — the inputs to {@link\n * collectBaseMatchKeys}, plus the set of committed `(kind, id)` keys those base\n * sources matched at PLAN time. Comparing the two closes the identity-resolution\n * TOCTOU window (see {@link assertBaseResolutionStable}).\n */\ntype IncrementalCommitGuard<G extends GraphDef> = Readonly<{\n  stagedNewByKind: ReadonlyMap<string, readonly StagedNewNode[]>;\n  options: NormalizedMergeOptions<G>;\n  introspectionKinds: ReadonlyMap<string, readonly UniqueIntrospection[]>;\n  plannedBaseMatchKeys: ReadonlySet<MergeKey>;\n  /**\n   * The fork point and the `base@V` every branch declared against it, checked\n   * before planning and re-checked at the commit (see\n   * {@link assertForkPointUnchanged}).\n   */\n  forkPoint: ForkPointPrecondition<G>;\n  /**\n   * `(kind, id) -> version` for every committed target node observed while\n   * planning (the target-branch diff enumeration). The commit-time guard\n   * re-reads the rows the plan writes OR deletes and refuses if any inherited\n   * row's version advanced in the plan→commit window — a concurrent write the\n   * stale plan would otherwise overwrite (lost update).\n   */\n  targetNodeVersions: ReadonlyMap<MergeKey, number>;\n  /**\n   * `(kind, id) -> content signature` for every committed target edge observed\n   * while planning. The edge-half analogue of {@link targetNodeVersions}: edges\n   * have no version, so the guard fingerprints their mergeable content\n   * (endpoints, liveness, canonical props) and refuses if the fingerprint of an\n   * edge the plan upserts OR deletes drifted in the plan→commit window.\n   */\n  targetEdgeSignatures: ReadonlyMap<MergeKey, string>;\n  /**\n   * The plan-time identity probe: the bare ids probed, the live peer keys\n   * observed, per-seed class fingerprints, and the negative-ledger\n   * fingerprint. Present for EVERY identity-enabled incremental merge (both\n   * profiles — explicit assertions change legality under `\"ignore\"` too; only\n   * the direct-peer window check is fold-specific). The commit-time guard\n   * revalidates all of it through the transaction backend and refuses\n   * plan→commit drift as a typed replan error.\n   */\n  identityPeerProbe?: IdentityPeerProbe;\n}>;\n\n/**\n * Re-runs the NEW-vs-BASE identity probes — each kind's unique constraints\n * (`baseUnique`) and its declared block index (`baseKey`) — for the staged new\n * nodes against `lookupStore`, returning the set of committed `(kind, id)` keys\n * those probes surface. It computes the lookup keys from the SAME staged props\n * the planner used (typegraph owns key derivation), so the result over the\n * plan-time target reproduces `candidates.baseMembers`, and the result over the\n * tx-snapshot target reveals any committed row that became a match in between.\n *\n * Probes are issued STRICTLY SEQUENTIALLY (one awaited query at a time): inside\n * the commit transaction these run on the single tx-held client, where\n * concurrent `client.query()` calls queue with a pg deprecation warning that\n * becomes an error in pg@9.\n */\nasync function collectBaseMatchKeys<G extends GraphDef>(\n  lookupStore: BaseLookupStore,\n  guard: IncrementalCommitGuard<G>,\n): Promise<ReadonlySet<MergeKey>> {\n  const matched = new Set<MergeKey>();\n  for (const [kind, stagedNodes] of guard.stagedNewByKind) {\n    const resolveConfig = guard.options.resolve[kind];\n    // A kind with no resolve config has no base recall — it never pulls a\n    // committed row into scope, so it carries no identity-resolution TOCTOU.\n    if (resolveConfig === undefined) {\n      continue;\n    }\n    const collection = lookupStore.nodes[kind];\n    if (collection === undefined || stagedNodes.length === 0) {\n      continue;\n    }\n    const items = stagedNodes.map((staged) => ({ props: staged.node.props }));\n\n    for (const constraint of uniqueConstraintsFor(\n      guard.introspectionKinds,\n      kind,\n    )) {\n      const matches = await collection.bulkFindByConstraint(\n        constraint.name,\n        items,\n      );\n      for (const base of matches) {\n        if (base !== undefined) {\n          matched.add(mergeKeyOf(base));\n        }\n      }\n    }\n\n    if (resolveConfig.blockIndex !== undefined) {\n      const matchesByItem = await collection.bulkFindByIndex(\n        resolveConfig.blockIndex,\n        items,\n      );\n      for (const perItem of matchesByItem) {\n        for (const base of perItem) {\n          matched.add(mergeKeyOf(base));\n        }\n      }\n    }\n  }\n  return matched;\n}\n\n/**\n * The identity-resolution half of the incremental TOCTOU guard. The planner\n * resolves each branch addition against the target's committed rows from reads\n * taken OUTSIDE this transaction (`baseUnique`/`baseKey` in candidate\n * generation). A committed row sharing a branch addition's unique-constraint or\n * block-index key that LANDS in the plan→commit window is invisible to the\n * per-row write guards — they only re-fetch the plan's own write ids — so the\n * stale plan would commit the addition under its own id, leaving a duplicate the\n * base-source resolution would otherwise have collapsed. A unique-constraint\n * collision is still caught at write time by the uniques side-table, but only as\n * a late, opaque failure mid-apply; a non-unique BLOCK-INDEX collision has no\n * such backstop and commits the duplicate SILENTLY. This guard refuses both\n * early and typed, before any row is touched.\n *\n * Re-deriving the matched base keys through the TX-scoped store and comparing\n * them to the plan-time set proves no new identity match appeared. SERIALIZABLE\n * isolation makes the proof race-free on multi-writer Postgres: a concurrent\n * insert that this read would have to see aborts one side with a retryable\n * serialization failure; the retry re-runs this probe and fails typed.\n */\nasync function assertBaseResolutionStable<G extends GraphDef>(\n  lookupStore: BaseLookupStore,\n  guard: IncrementalCommitGuard<G>,\n): Promise<void> {\n  const liveKeys = await collectBaseMatchKeys(lookupStore, guard);\n  const appeared = [...liveKeys]\n    .filter((key) => !guard.plannedBaseMatchKeys.has(key))\n    .sort((left, right) => compareMergeKeys(left, right));\n  if (appeared.length === 0) {\n    return;\n  }\n  throw new BaseVersionMismatchError(\n    `mergeIncremental() resolved its branch additions against the target as of planning, but ${appeared.length} committed row(s) matching a branch addition's identity key (a unique constraint or block index) were inserted before the commit transaction. Committing the plan would create duplicate entities the base-source resolution would otherwise have collapsed.`,\n    {\n      details: { appeared },\n      suggestion:\n        \"Re-run mergeIncremental(); the re-planned merge resolves the branch additions against the now-committed rows.\",\n    },\n  );\n}\n\n/** A `(kind, id)` the plan will mutate whose identity was an observed target row. */\ntype InheritedTargetRef = Readonly<{ kind: string; id: string }>;\n\n/** Anything keyed by {@link MergeKey} that can answer a membership check. */\ntype MergeKeyMembership = Readonly<{ has(key: MergeKey): boolean }>;\n\n/**\n * Buckets the plan's inherited-target mutations by kind, deduped by identity, for\n * a single batched re-read per kind. `identities` filters to the rows observed at\n * plan time (new rows the plan creates have no baseline and are skipped). Both a\n * write and a delete of the same identity collapse to one entry — either way the\n * row is re-checked once.\n */\nfunction bucketInheritedRefsByKind(\n  refs: Iterable<InheritedTargetRef>,\n  identities: MergeKeyMembership,\n): ReadonlyMap<string, readonly string[]> {\n  const seen = new Set<MergeKey>();\n  const idsByKind = new Map<string, string[]>();\n  for (const ref of refs) {\n    const identity = mergeKey(ref.kind, ref.id);\n    if (!identities.has(identity) || seen.has(identity)) {\n      continue;\n    }\n    seen.add(identity);\n    const bucket = idsByKind.get(ref.kind) ?? [];\n    bucket.push(ref.id);\n    idsByKind.set(ref.kind, bucket);\n  }\n  return idsByKind;\n}\n\n/**\n * The version-check (nodes) and signature-check (edges) halves of the\n * incremental TOCTOU guard share one skeleton — bucket refs by kind, batch-fetch\n * the current rows, compare each against its plan-time baseline, and throw on\n * the first mismatch. `Row` is the fetched row shape and `Expected` the\n * comparable baseline value (a node version or an edge content signature).\n */\nasync function assertInheritedUnchanged<Row, Expected>(\n  args: Readonly<{\n    refs: readonly InheritedTargetRef[];\n    expected: ReadonlyMap<MergeKey, Expected>;\n    fetchRows: (\n      kind: string,\n      ids: readonly string[],\n    ) => Promise<readonly (Row | undefined)[]>;\n    deriveValue: (row: Row | undefined) => Expected | undefined;\n    buildError: (\n      id: string,\n      kind: string,\n      expected: Expected,\n      current: Expected | undefined,\n    ) => Error;\n  }>,\n): Promise<void> {\n  if (args.expected.size === 0) {\n    return;\n  }\n  const idsByKind = bucketInheritedRefsByKind(args.refs, args.expected);\n  for (const [kind, ids] of idsByKind) {\n    const rows = await args.fetchRows(kind, ids);\n    for (const [index, id] of ids.entries()) {\n      const expected = requireDefined(args.expected.get(mergeKey(kind, id)));\n      const current = args.deriveValue(rows[index]);\n      if (current === expected) {\n        continue;\n      }\n      throw args.buildError(id, kind, expected, current);\n    }\n  }\n}\n\n/**\n * The inherited-target-row half of the incremental TOCTOU guard. The plan folds\n * the live target in as a preferred branch and resolves inherited modifications\n * against the target rows it enumerated OUTSIDE this transaction. If a committed\n * row the plan mutates was changed in the plan→commit window, applying the plan\n * would discard that write (a silent lost update) — the per-row write guards only\n * check resurrection / lossy strips, not that the row still holds the value the\n * plan merged from.\n *\n * Covers every path that mutates a committed target row: node writes and node\n * deletions (checked by `version`), and edge upserts and edge deletions (checked\n * by content signature, since edges carry no version). For each, it re-reads the\n * committed row through the tx snapshot and refuses if it drifted (or vanished).\n * SERIALIZABLE + retry then re-plans against the now-committed value, exactly as\n * the snapshot path's {@link assertTargetUnchanged} does for full-graph drift.\n */\nasync function assertInheritedTargetUnchanged<G extends GraphDef>(\n  nodesApi: TxNodes,\n  edgesApi: TxEdges,\n  guard: IncrementalCommitGuard<G>,\n  plan: MergePlan<G>,\n): Promise<void> {\n  // Disjoint collections (nodes vs. edges) with no shared state — safe to run\n  // concurrently.\n  await Promise.all([\n    assertInheritedNodesUnchanged(nodesApi, guard, plan),\n    assertInheritedEdgesUnchanged(edgesApi, guard, plan),\n  ]);\n}\n\n/** Version-checks every committed target node the plan writes or deletes. */\nasync function assertInheritedNodesUnchanged<G extends GraphDef>(\n  nodesApi: TxNodes,\n  guard: IncrementalCommitGuard<G>,\n  plan: MergePlan<G>,\n): Promise<void> {\n  const nodeRefs: InheritedTargetRef[] = plannedNodeWrites(plan).map(\n    (write) => ({ kind: write.kind, id: write.id }),\n  );\n  for (const [identity, kind] of plan.nodeDeletions) {\n    nodeRefs.push({ kind, id: idOf(identity) });\n  }\n  await assertInheritedUnchanged<Node, number>({\n    refs: nodeRefs,\n    expected: guard.targetNodeVersions,\n    fetchRows: (kind, ids) =>\n      nodeCollection(nodesApi, kind).getByIds(ids, INCLUDE_TOMBSTONES),\n    deriveValue: (row) => row?.meta.version,\n    buildError: (id, kind, expected, current) =>\n      new BaseVersionMismatchError(\n        `mergeIncremental() observed committed node \"${id}\" (kind \"${kind}\") at version ${expected} while planning, but it changed before the commit transaction; the resolved plan no longer describes the live target and was not applied.`,\n        {\n          details: {\n            id,\n            kind,\n            expectedVersion: expected,\n            currentVersion: current,\n          },\n          suggestion:\n            \"Re-run mergeIncremental(); the re-planned merge resolves the inherited modifications against the now-committed rows.\",\n        },\n      ),\n  });\n}\n\n/**\n * Signature-checks every committed target edge the plan upserts or deletes. Edges\n * carry no `version`, so the plan-time baseline is a content fingerprint\n * ({@link edgeStateSignature}) captured over the target's edge enumeration; a\n * changed fingerprint means the committed edge's endpoints, liveness, or props\n * drifted in the plan→commit window.\n */\nasync function assertInheritedEdgesUnchanged<G extends GraphDef>(\n  edgesApi: TxEdges,\n  guard: IncrementalCommitGuard<G>,\n  plan: MergePlan<G>,\n): Promise<void> {\n  const edgeRefs: InheritedTargetRef[] = plan.mergedEdges.map((edge) => ({\n    kind: edge.kind,\n    id: edge.id,\n  }));\n  for (const [identity, kind] of plan.edgeDeletions) {\n    edgeRefs.push({ kind, id: idOf(identity) });\n  }\n  await assertInheritedUnchanged<Edge, string>({\n    refs: edgeRefs,\n    expected: guard.targetEdgeSignatures,\n    fetchRows: (kind, ids) =>\n      edgeCollection(edgesApi, kind).getByIds(ids, INCLUDE_TOMBSTONES),\n    deriveValue: (row) =>\n      row === undefined ? undefined : (\n        edgeStateSignature({\n          fromKind: row.fromKind,\n          fromId: row.fromId,\n          toKind: row.toKind,\n          toId: row.toId,\n          live: row.meta.deletedAt === undefined,\n          props: edgeProps(row),\n        })\n      ),\n    buildError: (id, kind) =>\n      new BaseVersionMismatchError(\n        `mergeIncremental() observed committed edge \"${id}\" (kind \"${kind}\") while planning, but its endpoints, liveness, or props changed before the commit transaction; the resolved plan no longer describes the live target and was not applied.`,\n        {\n          details: { id, kind },\n          suggestion:\n            \"Re-run mergeIncremental(); the re-planned merge resolves the inherited modifications against the now-committed rows.\",\n        },\n      ),\n  });\n}\n\n/**\n * Re-establishes `mergeIncremental()`'s fork-point premise at the point of no\n * return — the incremental analogue of the snapshot path's\n * {@link assertTargetUnchanged}.\n *\n * `mergeIncremental()` reads the fork point's `base@V` BEFORE planning, refuses\n * any branch that declares a different one, and then derives the whole plan\n * from fork-point→branch diffs. A write landing on the fork point in that\n * window makes every one of those diffs describe an ancestor that no longer\n * exists — and nothing downstream notices, because the incremental commit\n * deliberately does NOT re-check the TARGET's `base@V` (an advancing target is\n * the feature). Re-reading the fork point here turns that into a typed refusal\n * instead of a committed plan derived from state that is gone.\n *\n * The token is recomputed by {@link computeBaseVersion} — the same and only\n * definition of a store's `base@V` that produced the value being compared, so\n * there is no second spelling of the comparison to drift. A whole-token match\n * needs no separate schema re-check: `computeSchemaComponent` hashes the\n * serialized graph with the version excluded, making it a pure function of\n * the in-memory graph definition, which is exactly why `assertTargetUnchanged`\n * re-checks only the anchor half too. On a whole-token MISMATCH under an\n * engine anchor, though, the schema half IS compared separately\n * ({@link schemaComponentOf}), and so is the origin half\n * ({@link engineAnchorOriginOf}, inside `engineAnchorToleranceEligible`),\n * before the engine-wide revision is allowed to explain the mismatch away —\n * an engine-wide bump tolerating an empty delta must never also paper over\n * a real schema change or a fork point that turns out to belong to a\n * different store entirely.\n *\n * The re-read goes through the fork point's OWN backend rather than this\n * transaction: the fork point is a different store, and what must hold is its\n * COMMITTED state. Deliberately no advisory lock either — the fork point is\n * immutable by contract, so this detects a violated contract rather than\n * excluding a legal writer, and taking the graph write lock on a second\n * connection would deadlock against this very transaction whenever the fork\n * point and the target share one database. The engine-anchor consultation\n * needs no lock for the same reason `assertTargetUnchanged`'s does not: an\n * engine-anchored store has revision tracking off, so no TypeGraph writer\n * contends for it in the first place.\n */\nasync function assertForkPointUnchanged<G extends GraphDef>(\n  precondition: ForkPointPrecondition<G>,\n): Promise<void> {\n  const liveVersion = await computeBaseVersion(precondition.store);\n  if (liveVersion === precondition.version) return;\n  // The full-token equality above already accepts a genuinely unchanged fork\n  // point outright. On a mismatch, an engine anchor gets one more chance:\n  // when the SCHEMA half still matches (a real schema change is never\n  // tolerated here) and `changesSince` shows the engine-wide bump named none\n  // of this graph's rows, the fork point is unchanged for merge purposes —\n  // see the module doc's anchor precedence and `assertTargetUnchanged`'s\n  // twin guard, which this mirrors using the fork point's OWN backend rather\n  // than a transaction (the fork point is a different, immutable store; see\n  // this function's own doc comment on why it takes no lock either).\n  // Eligibility (both tokens engine-anchored, identical schema half) is the\n  // SAME check `toleratedByEngineAnchor` makes — see\n  // `engineAnchorToleranceEligible`'s own doc comment for why `liveVersion`\n  // must carry an engine anchor too, not only `precondition.version`.\n  const expectedEngineRevision = engineAnchorToleranceEligible(\n    precondition.version,\n    liveVersion,\n  );\n  if (expectedEngineRevision !== undefined) {\n    // Read through `resolveLineage` — the ONE owner of lineage source\n    // selection — rather than the fork point's root backend directly: an\n    // engine anchor is chosen only when the BACKEND itself supplies\n    // `lineage` (revision tracking is off in this branch, so the\n    // recorded-relations derivation is unreachable — see the module doc's\n    // anchor precedence), so `resolveLineage(precondition.store)` finds\n    // exactly the same object a direct `storeBackend(...).lineage` read\n    // would. There is no transaction of the fork point's own to pin a\n    // session-scoped read to — it is immutable by contract and this\n    // function takes no lock (see this function's own doc comment on why)\n    // — so the root backend IS the only session available, and `resolveLineage`\n    // reaching it costs nothing over reading it directly. `undefined` here\n    // means the fork point's own backend no longer supplies a `lineage` it\n    // did at plan time; falling through to the generic mismatch below\n    // (rather than refusing on no evidence) keeps the refusal fail-closed.\n    const lineage = resolveLineage(precondition.store);\n    if (lineage !== undefined) {\n      const mismatch = await engineAnchorMismatch(\n        lineage,\n        storeBackend(precondition.store),\n        precondition.store.graphId,\n        expectedEngineRevision,\n      );\n      if (mismatch === undefined) return;\n    }\n  }\n  throw new BaseVersionMismatchError(\n    \"The mergeIncremental() fork point was modified between the fork-point precondition and the commit transaction; every branch diff was computed against the previous fork-point state, so the resolved plan was not applied.\",\n    {\n      details: {\n        expectedForkPointBase: precondition.version,\n        liveForkPointBase: liveVersion,\n      },\n      suggestion:\n        \"Keep the fork-point store immutable for the duration of the merge (it is the diff reference, not a merge target), then re-run mergeIncremental().\",\n    },\n  );\n}\n\n/**\n * The full incremental commit path (§6.6). The planner has already folded the live\n * target in as a preferred synthetic branch, so this path preflights destructive\n * row hazards inside the target transaction and then applies the normal merge plan.\n */\nasync function commitIncrementalPlan<G extends GraphDef>(\n  target: Store<G>,\n  plan: MergePlan<G>,\n  guard: IncrementalCommitGuard<G>,\n): Promise<MergedCounts> {\n  if (!storeBackend(target).capabilities.execution.interactiveTransactions) {\n    throw new MergeError(\n      \"mergeIncremental() requires a transaction-capable target backend. Incremental writes must preflight existing rows and commit atomically; non-transactional fallback would allow partial graph writes.\",\n      { details: { capability: \"execution.interactiveTransactions\" } },\n    );\n  }\n\n  // Legacy targets use SERIALIZABLE + retry: the per-row guards read inside\n  // this transaction, and SSI turns a conflicting concurrent write into a\n  // retryable abort. Recorded-history targets cannot use SERIALIZABLE because\n  // capture allocates its clock in read-committed mode; they instead acquire the\n  // same graph write lock as every captured write before the guards run. In\n  // PostgreSQL read committed each subsequent statement sees committed work that\n  // landed before the lock was acquired, while the lock excludes later tracked\n  // writes until this plan commits.\n  return runMergeCommit(() =>\n    runRetriedUnit(\n      {\n        operation: \"commitIncrementalPlan\",\n        attempts: MERGE_COMMIT_ATTEMPTS,\n        target: storeBackend(target),\n      },\n      () =>\n        target.transaction(async (tx) => {\n          await lockMergeTargetWrite(transactionBackend(tx), {\n            graphId: target.graphId,\n            schemaVersion: target.introspect().schemaVersion,\n            graphLock:\n              target.revisionTrackingEnabled ? \"required\" : \"not-required\",\n            staleSchemaError: (cause) =>\n              new BaseVersionMismatchError(\n                \"The merge target schema changed before the incremental commit transaction; the resolved plan was not applied.\",\n                { cause },\n              ),\n          });\n          // Fork-point TOCTOU guard: the ancestor the whole plan was diffed\n          // against is re-read here, so a write to it in the plan→commit window\n          // refuses the merge instead of committing diffs against a fork point\n          // that has moved. Runs first: it is the premise every later guard's\n          // baseline was derived under, and on a revision-anchored fork point it\n          // is an O(1) read.\n          await assertForkPointUnchanged(guard.forkPoint);\n          const nodesApi = tx.nodes as unknown as TxNodes;\n          const edgesApi = tx.edges as unknown as TxEdges;\n          // Identity-resolution TOCTOU guard: the base-source lookups ran OUTSIDE\n          // this transaction, so re-derive them here (tx snapshot) and refuse the\n          // plan if a matching committed row appeared in the window. `tx` exposes\n          // the same `.nodes` collection record a `BaseLookupStore` needs.\n          await assertBaseResolutionStable(\n            tx as unknown as BaseLookupStore,\n            guard,\n          );\n          // Identity window guards: the by-id freshness check runs DIRECTLY (not\n          // via the probe guard, whose early return must never be able to skip\n          // it), then the probe-based layers revalidate peers, classes, the\n          // negative ledger, and finally re-run the full identity simulation on\n          // the tx snapshot.\n          await assertPlannedIdentityIdsFresh(\n            target,\n            transactionBackend(tx),\n            plan,\n          );\n          await assertIdentityPeersStable(\n            target,\n            transactionBackend(tx),\n            guard.identityPeerProbe,\n            plan,\n          );\n          // Inherited-row TOCTOU guard: refuse if a committed node OR edge the plan\n          // writes or deletes changed since it was observed at plan time (lost update).\n          await assertInheritedTargetUnchanged(nodesApi, edgesApi, guard, plan);\n          await validateIncrementalNodeWrites(target, nodesApi, plan);\n          await validateIncrementalEdgeWrites(target, edgesApi, plan);\n          return applyInternalMergePlan(\n            plan,\n            nodesApi,\n            edgesApi,\n            target,\n            transactionBackend(tx),\n          );\n        }, mergeCommitTransactionOptions(target)),\n    ),\n  );\n}\n\n/**\n * Incremental merge — the public fork-point-vs-live-target entry point (design\n * §6.4-B / §6.6). It treats `forkPoint` as the immutable ancestor, folds the live\n * `target` in as a preferred committed branch, resolves branch additions against\n * committed rows, and propagates inherited node/edge modifications and deletions\n * through the same three-way merge planner.\n *\n * Object-form args so the two same-typed stores (`forkPoint`, `target`) cannot be\n * swapped. The named `target` is authoritative; an untyped caller that also\n * supplies `options.target` is refused rather than silently ignored.\n *\n * Preconditions (typed errors): every branch forked from `forkPoint`\n * (`branch.base === computeBaseVersion(forkPoint)`); `forkPoint` and `target` share a\n * schema hash (schema drift is fatal; target CONTENT may have advanced); and\n * `onBasePropertyConflict` is `\"flag\"` (keep-base for committed-row conflicts).\n *\n * The fork-point precondition is not merely an entry check: it is re-verified\n * inside the commit transaction, so `forkPoint` must stay immutable for the\n * duration of the call. A write to it while the merge is in flight makes every\n * branch diff describe an ancestor that no longer exists, and is refused with\n * `BaseVersionMismatchError` rather than committed (see\n * {@link assertForkPointUnchanged}). The TARGET, by contrast, may advance\n * throughout — that is what \"incremental\" means.\n */\nexport async function mergeIncremental<G extends GraphDef>(\n  args: MergeIncrementalArguments<G>,\n): Promise<Result<MergeReport<G>, MergeError>> {\n  const { forkPoint, target } = args;\n  const branches = unwrapMergeBranches(args.branches);\n\n  const normalized = tryNormalize(args.options ?? {}, [\"target\"]);\n  if (isErr(normalized)) {\n    return err(normalized.error);\n  }\n  const options = normalized.data;\n\n  // Keep-base pin: committed rows remain authoritative under unresolved base\n  // conflicts. A non-keep-base policy would let a stale branch value overwrite a\n  // newer committed value.\n  if (options.onBasePropertyConflict !== \"flag\") {\n    return err(incrementalBaseConflictPolicyError(options));\n  }\n\n  // Every branch must have forked from THIS fork-point (honest diff).\n  const forkPrecondition = await validateForkPointVersions(forkPoint, branches);\n  if (isErr(forkPrecondition)) {\n    return err(forkPrecondition.error);\n  }\n  const forkVersion = forkPrecondition.data;\n\n  // Schema half of base@V stays a hard precondition; target CONTENT may advance.\n  const [forkSchema, targetSchema] = await Promise.all([\n    computeSchemaComponent(forkPoint),\n    computeSchemaComponent(target),\n  ]);\n  if (forkSchema !== targetSchema) {\n    return err(incrementalSchemaError());\n  }\n\n  const targetBranch: GraphBranch<G> = {\n    id: COMMITTED_TARGET_BRANCH,\n    base: forkVersion,\n    store: target,\n    // See the sibling targetBranch above (planMerge's incremental arm): a\n    // stand-in for the caller's own live target, never a working copy this\n    // function owns, so its close is a no-op.\n    close: (): Promise<void> => Promise.resolve(),\n  };\n  return resolveMerge(\n    forkPoint,\n    target,\n    [targetBranch, ...branches],\n    options,\n    true,\n    {\n      targetBranchId: COMMITTED_TARGET_BRANCH,\n      // The fork-point precondition just validated, carried to the commit so\n      // it is re-established there rather than assumed to have held for the\n      // whole of planning (see `assertForkPointUnchanged`).\n      forkPoint: { store: forkPoint, version: forkVersion },\n    },\n    undefined,\n    commitResolvedMerge,\n  );\n}\n","import { z } from \"zod\";\n\nimport {\n  type GraphData,\n  importGraph,\n  InterchangeIdentitySchema,\n} from \"../interchange\";\nimport type { EvolutionPlan } from \"../schema/evolution-plan\";\nimport { isCanonicalIsoDate } from \"../utils/date\";\nimport { computeSchemaComponent } from \"./base-version\";\nimport { CandidateWriteSetError, MergeError } from \"./errors\";\nimport { evolutionPlanningTarget } from \"./evolution-target\";\nimport { ingestionBranch } from \"./ingestion-branch\";\nimport {\n  captureMergePlanTargetFence,\n  planMergeIncremental,\n  planMergeIncrementalForEvolution,\n} from \"./merge\";\nimport type { MergePlanArtifact } from \"./plan-schema\";\nimport type { Result } from \"./result\";\nimport { err, isErr } from \"./result\";\nimport type { GraphDef, Store } from \"./typegraph-internal\";\nimport { storeBackend } from \"./typegraph-internal\";\nimport type { MergeOptions } from \"./types\";\nimport { asBranchId } from \"./types\";\nimport type { MakeBackend } from \"./working-copy\";\n\n/** Current JSON wire version emitted and accepted for candidate write sets. */\nexport const CANDIDATE_WRITE_SET_FORMAT_VERSION = 1 as const;\n\nconst nonEmptyStringSchema = z.string().min(1);\nconst validityTimestampSchema = z.iso\n  .datetime()\n  .refine((value) => isCanonicalIsoDate(value), {\n    message: \"Expected canonical UTC ISO 8601 with fixed milliseconds.\",\n  });\nconst entityReferenceSchema = z.object({\n  kind: nonEmptyStringSchema,\n  id: nonEmptyStringSchema,\n});\nconst jsonObjectSchema = z.record(z.string(), z.json());\n\nconst candidateNodeSchema = z.object({\n  kind: nonEmptyStringSchema,\n  id: nonEmptyStringSchema,\n  properties: jsonObjectSchema,\n  validFrom: validityTimestampSchema.nullable(),\n  validTo: validityTimestampSchema.optional(),\n});\n\nconst candidateEdgeSchema = z.object({\n  kind: nonEmptyStringSchema,\n  id: nonEmptyStringSchema,\n  from: entityReferenceSchema,\n  to: entityReferenceSchema,\n  properties: jsonObjectSchema.default({}),\n  validFrom: validityTimestampSchema.nullable(),\n  validTo: validityTimestampSchema.optional(),\n});\n\n/** Target schema identity carried by a candidate document. */\nexport const CandidateWriteSetTargetSchema = z.object({\n  graphId: nonEmptyStringSchema,\n  schemaVersion: z.number().int().positive(),\n  schemaHash: nonEmptyStringSchema,\n});\nexport type CandidateWriteSetTarget = z.infer<\n  typeof CandidateWriteSetTargetSchema\n>;\n\n/**\n * JSON-safe, source-attributed candidate writes accepted by\n * {@link planCandidateWriteSet}.\n *\n * `sourceId` becomes the existing merge pipeline's branch attribution. Entity\n * ids remain the per-candidate source ids in provenance records. Every temporal\n * lower bound is explicit so replaying identical JSON cannot acquire a new\n * import-time timestamp and change the resulting plan digest.\n */\nexport const CandidateWriteSetSchema = z.object({\n  formatVersion: z.literal(CANDIDATE_WRITE_SET_FORMAT_VERSION),\n  sourceId: nonEmptyStringSchema,\n  target: CandidateWriteSetTargetSchema,\n  nodes: z.array(candidateNodeSchema),\n  edges: z.array(candidateEdgeSchema),\n  identity: InterchangeIdentitySchema.optional(),\n});\nexport type CandidateWriteSet = z.infer<typeof CandidateWriteSetSchema>;\n\n/** Object-form arguments for branch-free candidate planning. */\nexport type PlanCandidateWriteSetArgs<G extends GraphDef> = Readonly<{\n  target: Store<G>;\n  makeBackend: MakeBackend;\n  writeSet: unknown;\n  options?: Omit<MergeOptions<G>, \"target\">;\n}>;\n\n/** Object-form arguments for candidate planning against a planned evolution. */\nexport type PlanCandidateWriteSetForEvolutionArgs<G extends GraphDef> = Omit<\n  PlanCandidateWriteSetArgs<G>,\n  \"target\"\n> &\n  Readonly<{\n    target: Store<G>;\n    evolutionPlan: EvolutionPlan;\n  }>;\n\n/** Captures the schema identity a candidate write set must name. */\nexport async function captureCandidateWriteSetTarget<G extends GraphDef>(\n  target: Store<G>,\n): Promise<CandidateWriteSetTarget> {\n  const activeSchema = await storeBackend(target).getActiveSchema(\n    target.graphId,\n  );\n  return {\n    graphId: target.graphId,\n    schemaVersion:\n      activeSchema?.version ?? target.introspect().schemaVersion ?? 1,\n    schemaHash: await computeSchemaComponent(target),\n  };\n}\n\n/**\n * Captures the schema identity a candidate write set must name after a planned\n * evolution commits. The plan remains nonserializable; this JSON-safe target\n * identity lets a caller author and review candidate data before that commit.\n */\nexport function captureCandidateWriteSetTargetForEvolution<G extends GraphDef>(\n  target: Store<G>,\n  evolutionPlan: EvolutionPlan,\n): CandidateWriteSetTarget {\n  const resultingTarget = evolutionPlanningTarget(target, evolutionPlan);\n  return candidateWriteSetTargetForEvolution(resultingTarget, evolutionPlan);\n}\n\nfunction candidateWriteSetTargetForEvolution<G extends GraphDef>(\n  resultingTarget: Store<G>,\n  evolutionPlan: EvolutionPlan,\n): CandidateWriteSetTarget {\n  return {\n    graphId: resultingTarget.graphId,\n    schemaVersion: evolutionPlan.result.version,\n    schemaHash: evolutionPlan.result.hash,\n  };\n}\n\nfunction sameCandidateTarget(\n  left: CandidateWriteSetTarget,\n  right: CandidateWriteSetTarget,\n): boolean {\n  return (\n    left.graphId === right.graphId &&\n    left.schemaVersion === right.schemaVersion &&\n    left.schemaHash === right.schemaHash\n  );\n}\n\nfunction interchangeDocument(writeSet: CandidateWriteSet): GraphData {\n  return {\n    formatVersion: \"2.0\",\n    // Import does not use transport time. A constant keeps this adapter a pure\n    // function of the candidate JSON and target snapshot.\n    exportedAt: \"1970-01-01T00:00:00.000Z\",\n    source: { type: \"external\", description: writeSet.sourceId },\n    nodes: writeSet.nodes,\n    edges: writeSet.edges,\n    ...(writeSet.identity === undefined ? {} : { identity: writeSet.identity }),\n  };\n}\n\n/**\n * Plans one serializable candidate write set against the current accepted graph.\n *\n * The adapter creates no durable branch and never mutates `target`. It stages in\n * a disposable ingestion working copy, delegates to `planMergeIncremental`, and\n * closes that working copy on success, refusal, or throw. The returned artifact\n * is the ordinary versioned/digested {@link MergePlanArtifact}; no parallel\n * conflict format or scoring implementation exists.\n */\nexport async function planCandidateWriteSet<G extends GraphDef>(\n  args: PlanCandidateWriteSetArgs<G>,\n): Promise<Result<MergePlanArtifact, MergeError>> {\n  const parsed = CandidateWriteSetSchema.safeParse(args.writeSet);\n  if (!parsed.success) {\n    return err(\n      new CandidateWriteSetError(\"The candidate write set is malformed.\", {\n        details: { issues: parsed.error.issues },\n      }),\n    );\n  }\n  const writeSet = parsed.data;\n  let currentTarget: CandidateWriteSetTarget;\n  try {\n    currentTarget = await captureCandidateWriteSetTarget(args.target);\n  } catch (error) {\n    return err(\n      new CandidateWriteSetError(\n        \"Unable to capture the candidate target schema.\",\n        { cause: error },\n      ),\n    );\n  }\n  if (!sameCandidateTarget(writeSet.target, currentTarget)) {\n    return err(\n      new CandidateWriteSetError(\n        \"The candidate write set targets a different graph schema.\",\n        {\n          details: { expected: currentTarget, received: writeSet.target },\n          suggestion:\n            \"Rebuild the candidate write set against the target's current schema, then plan it again.\",\n        },\n      ),\n    );\n  }\n\n  let created: Awaited<ReturnType<typeof ingestionBranch<G>>>;\n  try {\n    created = await ingestionBranch(args.target, args.makeBackend, {\n      id: asBranchId(writeSet.sourceId),\n    });\n  } catch (error) {\n    return err(\n      new CandidateWriteSetError(\n        \"Unable to create the transient candidate staging store.\",\n        { cause: error },\n      ),\n    );\n  }\n  if (isErr(created)) {\n    return err(\n      new CandidateWriteSetError(\n        \"Unable to create the transient candidate staging store.\",\n        { cause: created.error },\n      ),\n    );\n  }\n  const candidate = created.data;\n  try {\n    const imported = await importGraph(\n      candidate,\n      interchangeDocument(writeSet),\n      {\n        onConflict: \"update\",\n        onUnknownProperty: \"error\",\n        validateReferences: true,\n        refreshStatistics: false,\n      },\n    );\n    if (!imported.success) {\n      return err(\n        new CandidateWriteSetError(\n          \"The candidate write set could not be staged against the active schema.\",\n          { details: { errors: imported.errors } },\n        ),\n      );\n    }\n    return await planMergeIncremental({\n      forkPoint: args.target,\n      target: args.target,\n      branches: [candidate],\n      ...(args.options === undefined ? {} : { options: args.options }),\n    });\n  } catch (error) {\n    return err(\n      error instanceof CandidateWriteSetError ? error : (\n        new CandidateWriteSetError(\n          \"Candidate write-set staging or planning failed.\",\n          { cause: error },\n        )\n      ),\n    );\n  } finally {\n    try {\n      await candidate.close();\n    } catch {\n      // A disposable backend close failure must not replace the planner's\n      // success or its original typed refusal.\n    }\n  }\n}\n\n/**\n * Plans a serializable candidate write set against the graph a reviewed\n * evolution will produce.\n *\n * Candidate data is staged in an isolated working copy of the resulting graph,\n * then resolved against accepted target sources through the evolution-aware\n * incremental planner. The returned ordinary merge artifact carries the\n * resulting schema fence, so\n * `withEvolvedTransaction()` and `applyMergePlanInTransaction()` can commit\n * schema and accepted candidate writes in one caller transaction and revision.\n */\nexport async function planCandidateWriteSetForEvolution<G extends GraphDef>(\n  args: PlanCandidateWriteSetForEvolutionArgs<G>,\n): Promise<Result<MergePlanArtifact, MergeError>> {\n  const parsed = CandidateWriteSetSchema.safeParse(args.writeSet);\n  if (!parsed.success) {\n    return err(\n      new CandidateWriteSetError(\"The candidate write set is malformed.\", {\n        details: { issues: parsed.error.issues },\n      }),\n    );\n  }\n  const writeSet = parsed.data;\n  let resultingTarget: Store<G>;\n  let expectedTarget: CandidateWriteSetTarget;\n  let planningFence: Awaited<ReturnType<typeof captureMergePlanTargetFence>>;\n  try {\n    resultingTarget = evolutionPlanningTarget(args.target, args.evolutionPlan);\n    expectedTarget = candidateWriteSetTargetForEvolution(\n      resultingTarget,\n      args.evolutionPlan,\n    );\n    planningFence = await captureMergePlanTargetFence(args.target);\n  } catch (error) {\n    return err(\n      error instanceof MergeError ? error : (\n        new CandidateWriteSetError(\n          \"Unable to prepare the planned evolution target schema.\",\n          { cause: error },\n        )\n      ),\n    );\n  }\n  if (!sameCandidateTarget(writeSet.target, expectedTarget)) {\n    return err(\n      new CandidateWriteSetError(\n        \"The candidate write set targets a different planned evolution schema.\",\n        {\n          details: { expected: expectedTarget, received: writeSet.target },\n          suggestion:\n            \"Rebuild the candidate write set against the planned evolution schema, then plan it again.\",\n        },\n      ),\n    );\n  }\n\n  let created: Awaited<ReturnType<typeof ingestionBranch<G>>>;\n  try {\n    created = await ingestionBranch(resultingTarget, args.makeBackend, {\n      id: asBranchId(writeSet.sourceId),\n    });\n  } catch (error) {\n    return err(\n      new CandidateWriteSetError(\n        \"Unable to create the transient candidate staging store.\",\n        { cause: error },\n      ),\n    );\n  }\n  if (isErr(created)) {\n    return err(\n      new CandidateWriteSetError(\n        \"Unable to create the transient candidate staging store.\",\n        { cause: created.error },\n      ),\n    );\n  }\n  const candidate = created.data;\n  try {\n    const imported = await importGraph(\n      candidate,\n      interchangeDocument(writeSet),\n      {\n        onConflict: \"update\",\n        onUnknownProperty: \"error\",\n        validateReferences: true,\n        refreshStatistics: false,\n      },\n    );\n    if (!imported.success) {\n      return err(\n        new CandidateWriteSetError(\n          \"The candidate write set could not be staged against the planned evolution schema.\",\n          { details: { errors: imported.errors } },\n        ),\n      );\n    }\n    return await planMergeIncrementalForEvolution(\n      args.target,\n      args.evolutionPlan,\n      [candidate],\n      args.options,\n      planningFence,\n    );\n  } catch (error) {\n    return err(\n      error instanceof CandidateWriteSetError || error instanceof MergeError ?\n        error\n      : new CandidateWriteSetError(\n          \"Candidate write-set staging or evolution planning failed.\",\n          { cause: error },\n        ),\n    );\n  } finally {\n    try {\n      await candidate.close();\n    } catch {\n      // A disposable backend close failure must not replace the planner's\n      // success or its original typed refusal.\n    }\n  }\n}\n","import { MergeReviewError } from \"./errors\";\nimport { compareStrings } from \"./node-key\";\nimport { normalizeMergeOptions } from \"./options\";\nimport type { GraphDef, JsonValue } from \"./typegraph-internal\";\nimport { sha256Hex, sortedReplacer } from \"./typegraph-internal\";\nimport type { MergeOptions } from \"./types\";\n\n/** Canonical content identity shared by review wire validation and row evidence. */\nexport function reviewJson(value: unknown): string {\n  // Missing optional fields must compare distinctly from every JSON value.\n  if (value === undefined) return \"undefined\";\n  return JSON.stringify(value, sortedReplacer);\n}\n\nexport async function reviewDigest(value: unknown): Promise<string> {\n  return sha256Hex(reviewJson(value), 32);\n}\n\n/**\n * Preserve every normalized option, including Maps and the presence of callbacks.\n * Callback code/closure identity is deliberately supplied by MergeReviewPolicy.\n * Tagged values keep a literal object from impersonating a callback or Map.\n */\nexport function reviewOptionEvidence<G extends GraphDef>(\n  options: Omit<MergeOptions<G>, \"target\"> | undefined,\n): JsonValue {\n  return encodeOption(normalizeMergeOptions(options), new Set());\n}\n\nfunction encodeOption(value: unknown, ancestors: Set<object>): JsonValue {\n  if (value === undefined) return [\"undefined\"];\n  if (typeof value === \"function\") return [\"callback\"];\n  if (\n    value === null ||\n    typeof value === \"string\" ||\n    typeof value === \"boolean\"\n  ) {\n    return [\"literal\", value];\n  }\n  if (typeof value === \"number\" && Number.isFinite(value))\n    return [\"number\", value];\n  if (typeof value !== \"object\" || ancestors.has(value)) {\n    throw new MergeReviewError(\n      \"Merge options contain unsupported or cyclic review evidence.\",\n    );\n  }\n  const nextAncestors = new Set([...ancestors, value]);\n  if (Array.isArray(value)) {\n    return [\n      \"array\",\n      value.map((item: unknown) => encodeOption(item, nextAncestors)),\n    ];\n  }\n  if (value instanceof Map) {\n    const entries = [...(value as ReadonlyMap<unknown, unknown>)].map(\n      ([key, entry]) => [\n        encodeOption(key, nextAncestors),\n        encodeOption(entry, nextAncestors),\n      ],\n    );\n    entries.sort((left, right) =>\n      compareStrings(reviewJson(left), reviewJson(right)),\n    );\n    return [\"map\", entries];\n  }\n  if (\n    Object.getPrototypeOf(value) !== Object.prototype &&\n    Object.getPrototypeOf(value) !== null\n  ) {\n    throw new MergeReviewError(\n      \"Merge options contain a non-JSON object without a review representation.\",\n    );\n  }\n  return [\n    \"object\",\n    Object.entries(value)\n      .sort(([left], [right]) => compareStrings(left, right))\n      .map(([key, entry]) => [key, encodeOption(entry, nextAncestors)]),\n  ];\n}\n","import type { CandidateWriteSet } from \"./candidate-write-set\";\nimport { parseRowProps } from \"./canonical-props\";\nimport { compareStrings } from \"./node-key\";\nimport type { MergePlanArtifact, MergePlanEntityRef } from \"./plan-schema\";\nimport { reviewDigest } from \"./review-evidence\";\nimport type {\n  MergeReviewBaseline,\n  MergeReviewDifference,\n  MergeReviewRow,\n} from \"./review-schema\";\nimport { enumerateAllEdges, enumerateAllNodes } from \"./state-diff\";\nimport type { GraphDef, Store } from \"./typegraph-internal\";\nimport {\n  getEdgeKinds,\n  getNodeKinds,\n  storeBackend,\n  storeRuntime,\n} from \"./typegraph-internal\";\n\nexport function reviewRowKey(row: MergeReviewRow): string {\n  return JSON.stringify([row.role, row.kind, row.id]);\n}\n\n/** Caller fences these reads together with planning using one target revision. */\nexport async function captureReviewBaseline<G extends GraphDef>(\n  target: Store<G>,\n): Promise<MergeReviewBaseline> {\n  const backend = storeBackend(target);\n  const rows: MergeReviewRow[] = [];\n  for (const kind of getNodeKinds(target.graph)) {\n    for (const row of await enumerateAllNodes(backend, target.graphId, kind)) {\n      rows.push({\n        role: \"node\",\n        kind,\n        id: row.id,\n        digest: await reviewDigest({ ...row, props: parseRowProps(row.props) }),\n      });\n    }\n  }\n  for (const kind of getEdgeKinds(target.graph)) {\n    for (const row of await enumerateAllEdges(backend, target.graphId, kind)) {\n      rows.push({\n        role: \"edge\",\n        kind,\n        id: row.id,\n        digest: await reviewDigest({ ...row, props: parseRowProps(row.props) }),\n      });\n    }\n  }\n  const identity = await storeRuntime(target).readCurrentIdentityAssertions(\n    \"archival\",\n    {\n      includeDeleted: true,\n    },\n  );\n  return {\n    rows: rows.sort((left, right) =>\n      compareStrings(reviewRowKey(left), reviewRowKey(right)),\n    ),\n    identityDigest: await reviewDigest(\n      [...identity].sort((left, right) => compareStrings(left.id, right.id)),\n    ),\n  };\n}\n\n/**\n * Existing rows are all guarded. Also guard absence for every input/write/guard\n * reference, so an insertion cannot turn a reviewed create into an overwrite.\n */\nexport function withReviewAbsences<G extends GraphDef>(\n  baseline: MergeReviewBaseline,\n  writeSet: CandidateWriteSet,\n  plan: MergePlanArtifact,\n  graph: G,\n): MergeReviewBaseline {\n  const rows = new Map(baseline.rows.map((row) => [reviewRowKey(row), row]));\n  function addNode(entity: MergePlanEntityRef): void {\n    // Guard same-id peers too: a new kind can join an implicit identity class\n    // without adding an assertion to the identity ledger. Conservatively guard\n    // every kind even when the current identity profile does not fold them.\n    for (const kind of getNodeKinds(graph)) {\n      const row = { role: \"node\", kind, id: entity.id } as const;\n      if (!rows.has(reviewRowKey(row))) rows.set(reviewRowKey(row), row);\n    }\n  }\n  for (const row of baseline.rows) if (row.role === \"node\") addNode(row);\n  function addEdge(entity: MergePlanEntityRef): void {\n    // Edge ids are graph-wide, including across edge kinds.\n    for (const kind of getEdgeKinds(graph)) {\n      const row = { role: \"edge\", kind, id: entity.id } as const;\n      if (!rows.has(reviewRowKey(row))) rows.set(reviewRowKey(row), row);\n    }\n  }\n  for (const node of [\n    ...writeSet.nodes,\n    ...plan.writes.nodeUpserts,\n    ...plan.writes.nodeDeletes,\n    ...plan.guards.deletedNodes,\n  ])\n    addNode(node);\n  for (const edge of [...writeSet.edges, ...plan.writes.edgeUpserts]) {\n    addEdge(edge);\n    addNode(edge.from);\n    addNode(edge.to);\n  }\n  for (const edge of plan.writes.edgeDeletes) addEdge(edge);\n  for (const assertion of [\n    ...(writeSet.identity?.assertions ?? []),\n    ...plan.writes.identityAssertions,\n    ...plan.writes.identityRetractions,\n  ]) {\n    addNode(assertion.a);\n    addNode(assertion.b);\n    if (assertion.endedBy !== undefined) addNode(assertion.endedBy);\n  }\n  for (const mapping of plan.guards.canonicalMappings) {\n    addNode(mapping.member);\n    addNode(mapping.canonical);\n  }\n  for (const retype of plan.guards.retypes) {\n    addNode(retype.entity);\n    addNode({ kind: retype.toKind, id: retype.entity.id });\n  }\n  return {\n    ...baseline,\n    rows: [...rows.values()].sort((left, right) =>\n      compareStrings(reviewRowKey(left), reviewRowKey(right)),\n    ),\n  };\n}\n\nexport function compareReviewBaseline(\n  reviewed: MergeReviewBaseline,\n  current: MergeReviewBaseline,\n): readonly MergeReviewDifference[] {\n  const currentRows = new Map(\n    current.rows.map((row) => [reviewRowKey(row), row]),\n  );\n  const differences: MergeReviewDifference[] = [];\n  for (const row of reviewed.rows) {\n    if (row.digest !== currentRows.get(reviewRowKey(row))?.digest) {\n      differences.push({\n        category: \"baseline\",\n        path: \"baseline.rows\",\n        entity: { role: row.role, kind: row.kind, id: row.id },\n      });\n    }\n  }\n  if (reviewed.identityDigest !== current.identityDigest) {\n    differences.push({ category: \"baseline\", path: \"baseline.identityDigest\" });\n  }\n  return differences;\n}\n","import { z } from \"zod\";\n\nimport {\n  type CandidateWriteSet,\n  CandidateWriteSetSchema,\n} from \"./candidate-write-set\";\nimport type {\n  MergePlanArtifact,\n  MergePlanDigest,\n  MergePlanEntityRef,\n} from \"./plan-schema\";\nimport { mergePlanArtifactV1Schema } from \"./plan-schema\";\nimport type { JsonValue } from \"./typegraph-internal\";\n\nexport const MERGE_REVIEW_FORMAT_VERSION = 1 as const;\n\n/** Application-owned identity of policy code and all opaque/external dependencies. */\nexport type MergeReviewPolicy = Readonly<{\n  id: string;\n  /** Explicit evidence; use an empty object only when there are no such dependencies. */\n  context: JsonValue;\n}>;\n\n/** A fingerprint of an observed row, or an expected absence. */\nexport type MergeReviewRow = MergePlanEntityRef &\n  Readonly<{\n    role: \"node\" | \"edge\";\n    /** Absent means this reference did not exist at review time. */\n    digest?: string | undefined;\n  }>;\n\n/** Conservative baseline: all original rows and the complete identity ledger. */\nexport type MergeReviewBaseline = Readonly<{\n  rows: readonly MergeReviewRow[];\n  identityDigest: string;\n}>;\n\n/**\n * Immutable review evidence, distinct from its single-use execution plan.\n * V1 supports candidate write sets only. Authenticate stored artifacts separately.\n */\nexport type MergeReviewArtifact = Readonly<{\n  formatVersion: typeof MERGE_REVIEW_FORMAT_VERSION;\n  kind: \"candidate-write-set\";\n  digest: MergePlanDigest;\n  writeSet: CandidateWriteSet;\n  policy: MergeReviewPolicy;\n  options: JsonValue;\n  plan: MergePlanArtifact;\n  baseline: MergeReviewBaseline;\n}>;\n\n/** Structured reason to refuse approval reuse; paths name fields in the review. */\nexport type MergeReviewDifference = Readonly<{\n  category: \"target\" | \"policy\" | \"baseline\" | \"plan\";\n  path: string;\n  entity?: MergePlanEntityRef & Readonly<{ role: \"node\" | \"edge\" }>;\n}>;\n\n/** Compatibility is evidence for application policy, never an authorization decision. */\nexport type MergeReviewRevalidation =\n  | Readonly<{\n      status: \"compatible\";\n      reviewDigest: MergePlanDigest;\n      plan: MergePlanArtifact;\n    }>\n  | Readonly<{\n      status: \"changed\" | \"incompatible\";\n      reviewDigest: MergePlanDigest;\n      differences: readonly MergeReviewDifference[];\n      /** Present when a fresh plan was computed; it requires a new review. */\n      plan?: MergePlanArtifact;\n    }>;\n\nconst digestSchema = z.string().regex(/^[\\da-f]{64}$/u);\n\nexport const mergeReviewPolicySchema = z\n  .object({\n    id: z.string().min(1),\n    context: z.json(),\n  })\n  .strict();\n\nexport const mergeReviewArtifactSchema = z\n  .object({\n    formatVersion: z.literal(MERGE_REVIEW_FORMAT_VERSION),\n    kind: z.literal(\"candidate-write-set\"),\n    digest: z\n      .object({ algorithm: z.literal(\"sha256\"), value: digestSchema })\n      .strict(),\n    writeSet: CandidateWriteSetSchema,\n    policy: mergeReviewPolicySchema,\n    options: z.json(),\n    plan: mergePlanArtifactV1Schema,\n    baseline: z\n      .object({\n        rows: z.array(\n          z\n            .object({\n              role: z.enum([\"node\", \"edge\"]),\n              kind: z.string().min(1),\n              id: z.string().min(1),\n              digest: digestSchema.optional(),\n            })\n            .strict(),\n        ),\n        identityDigest: digestSchema,\n      })\n      .strict(),\n  })\n  .strict();\n","import {\n  CandidateWriteSetSchema,\n  planCandidateWriteSet,\n  type PlanCandidateWriteSetArgs,\n} from \"./candidate-write-set\";\nimport {\n  MergeError,\n  MergePlanningStaleError,\n  MergeReviewError,\n} from \"./errors\";\nimport {\n  assertPlanningFenceUnchanged,\n  captureMergePlanTargetFence,\n  sameMergePlanTargetFence,\n} from \"./merge\";\nimport type { MergePlanArtifact, MergePlanTargetFence } from \"./plan-schema\";\nimport { validateMergePlanArtifact } from \"./plan-wire\";\nimport { err, isErr, ok, type Result } from \"./result\";\nimport {\n  captureReviewBaseline,\n  compareReviewBaseline,\n  reviewRowKey,\n  withReviewAbsences,\n} from \"./review-baseline\";\nimport {\n  reviewDigest,\n  reviewJson,\n  reviewOptionEvidence,\n} from \"./review-evidence\";\nimport {\n  MERGE_REVIEW_FORMAT_VERSION,\n  type MergeReviewArtifact,\n  mergeReviewArtifactSchema,\n  type MergeReviewDifference,\n  type MergeReviewPolicy,\n  mergeReviewPolicySchema,\n  type MergeReviewRevalidation,\n} from \"./review-schema\";\nimport type { GraphDef } from \"./typegraph-internal\";\n\nexport type PlanCandidateWriteSetReviewArgs<G extends GraphDef> =\n  PlanCandidateWriteSetArgs<G> &\n    Readonly<{\n      policy: MergeReviewPolicy;\n    }>;\n\nexport type RevalidateCandidateWriteSetReviewArgs<G extends GraphDef> = Omit<\n  PlanCandidateWriteSetReviewArgs<G>,\n  \"writeSet\"\n> &\n  Readonly<{\n    review: unknown;\n  }>;\n\n/** Capture a durable review, with planning and baseline reads under one fence. */\nexport async function planCandidateWriteSetReview<G extends GraphDef>(\n  args: PlanCandidateWriteSetReviewArgs<G>,\n): Promise<Result<MergeReviewArtifact, MergeError>> {\n  try {\n    const writeSet = CandidateWriteSetSchema.parse(args.writeSet);\n    const policy = mergeReviewPolicySchema.parse(args.policy);\n    const options = reviewOptionEvidence(args.options);\n    const startingFence = await captureMergePlanTargetFence(args.target);\n    const baseline = await captureReviewBaseline(args.target);\n    const planned = await planCandidateWriteSet({ ...args, writeSet });\n    if (isErr(planned)) return planned;\n    assertReviewPlanFence(startingFence, planned.data);\n    await assertPlanningFenceUnchanged(args.target, startingFence);\n    assertOptionsUnchanged(options, reviewOptionEvidence(args.options));\n    const input = {\n      formatVersion: MERGE_REVIEW_FORMAT_VERSION,\n      kind: \"candidate-write-set\" as const,\n      writeSet,\n      policy,\n      options,\n      plan: planned.data,\n      baseline: withReviewAbsences(\n        baseline,\n        writeSet,\n        planned.data,\n        args.target.graph,\n      ),\n    };\n    const review: MergeReviewArtifact = {\n      ...input,\n      digest: { algorithm: \"sha256\", value: await reviewDigest(input) },\n    };\n    mergeReviewArtifactSchema.parse(review);\n    return ok(review);\n  } catch (error) {\n    return err(asReviewError(error));\n  }\n}\n\n/**\n * Replan the retained input and relate it to its original review. Never writes\n * the target, edits an old plan, or authorizes execution. Apply a compatible\n * result with applyMergePlan(), retaining its final transactional revision fence.\n */\nexport async function revalidateCandidateWriteSetReview<G extends GraphDef>(\n  args: RevalidateCandidateWriteSetReviewArgs<G>,\n): Promise<Result<MergeReviewRevalidation, MergeError>> {\n  try {\n    const review = await validateReview(args.review);\n    const policy = mergeReviewPolicySchema.parse(args.policy);\n    const options = reviewOptionEvidence(args.options);\n    const startingFence = await captureMergePlanTargetFence(args.target);\n    const targetDifferences = compareReviewTarget(\n      review.plan.target,\n      startingFence,\n    );\n    if (targetDifferences.length > 0)\n      return ok({\n        status: \"incompatible\",\n        reviewDigest: review.digest,\n        differences: targetDifferences,\n      });\n    if (\n      withReviewAbsences(\n        review.baseline,\n        review.writeSet,\n        review.plan,\n        args.target.graph,\n      ).rows.length !== review.baseline.rows.length\n    ) {\n      throw new MergeReviewError(\n        \"The merge review is missing required baseline evidence.\",\n        { details: { reason: \"incomplete-baseline\" } },\n      );\n    }\n    const policyDifferences = compareFields(\n      \"policy\",\n      { policy: review.policy, options: review.options },\n      { policy, options },\n    );\n    if (policyDifferences.length > 0)\n      return ok({\n        status: \"changed\",\n        reviewDigest: review.digest,\n        differences: policyDifferences,\n      });\n\n    const baseline = await captureReviewBaseline(args.target);\n    const baselineDifferences = compareReviewBaseline(\n      review.baseline,\n      baseline,\n    );\n    if (baselineDifferences.length > 0) {\n      await assertPlanningFenceUnchanged(args.target, startingFence);\n      return ok({\n        status: \"changed\",\n        reviewDigest: review.digest,\n        differences: baselineDifferences,\n      });\n    }\n    const planned = await planCandidateWriteSet({\n      ...args,\n      writeSet: review.writeSet,\n    });\n    if (isErr(planned)) return planned;\n    assertReviewPlanFence(startingFence, planned.data);\n    await assertPlanningFenceUnchanged(args.target, startingFence);\n    assertOptionsUnchanged(options, reviewOptionEvidence(args.options));\n    const differences = compareFields(\n      \"plan\",\n      reviewPlanContent(review.plan),\n      reviewPlanContent(planned.data),\n    );\n    return ok(\n      differences.length === 0 ?\n        {\n          status: \"compatible\",\n          reviewDigest: review.digest,\n          plan: planned.data,\n        }\n      : {\n          status: \"changed\",\n          reviewDigest: review.digest,\n          differences,\n          plan: planned.data,\n        },\n    );\n  } catch (error) {\n    return err(asReviewError(error));\n  }\n}\n\nasync function validateReview(input: unknown): Promise<MergeReviewArtifact> {\n  const review = mergeReviewArtifactSchema.parse(input);\n  // Candidate staging schemas normalize defaults and strip unknown transport\n  // fields. Stored review evidence must already be normalized: otherwise an\n  // added field could disappear before its digest is checked.\n  if (reviewJson(input) !== reviewJson(review)) {\n    throw new MergeReviewError(\n      \"Stored merge review evidence must not require normalization.\",\n      {\n        details: { reason: \"noncanonical-shape\" },\n      },\n    );\n  }\n  const { digest, ...content } = review;\n  if (digest.value !== (await reviewDigest(content))) {\n    throw new MergeReviewError(\n      \"The merge review digest does not match its content.\",\n      { details: { reason: \"digest-mismatch\" } },\n    );\n  }\n  const plan = await validateMergePlanArtifact(review.plan);\n  if (!plan.success)\n    throw new MergeReviewError(\"The reviewed execution plan is invalid.\", {\n      details: { reason: \"invalid-plan\", error: plan.error },\n    });\n  const anchors = plan.artifact.anchors;\n  if (\n    plan.artifact.mode !== \"incremental\" ||\n    anchors.kind !== \"incremental\" ||\n    anchors.forkPoint.graphId !== review.writeSet.target.graphId ||\n    plan.artifact.target.graphId !== review.writeSet.target.graphId ||\n    plan.artifact.target.schema.version !==\n      review.writeSet.target.schemaVersion ||\n    plan.artifact.target.schema.hash !== review.writeSet.target.schemaHash ||\n    reviewJson(anchors.forkPoint.schema) !==\n      reviewJson(plan.artifact.target.schema) ||\n    anchors.branches.length !== 1 ||\n    anchors.branches[0]?.branchId !== review.writeSet.sourceId ||\n    anchors.branches[0].baseVersion !== anchors.forkPoint.baseVersion\n  ) {\n    throw new MergeReviewError(\n      \"The reviewed plan does not describe the retained candidate source and target.\",\n      { details: { reason: \"incompatible-plan\" } },\n    );\n  }\n  if (\n    new Set(review.baseline.rows.map((row) => reviewRowKey(row))).size !==\n    review.baseline.rows.length\n  ) {\n    throw new MergeReviewError(\n      \"The merge review contains duplicate baseline references.\",\n      { details: { reason: \"duplicate-baseline\" } },\n    );\n  }\n  return { ...review, plan: plan.artifact };\n}\n\nfunction assertReviewPlanFence(\n  fence: MergePlanTargetFence,\n  plan: MergePlanArtifact,\n): void {\n  if (!sameMergePlanTargetFence(fence, plan.target)) {\n    throw new MergePlanningStaleError(\n      \"The target changed between review evidence capture and planning.\",\n    );\n  }\n}\n\nfunction assertOptionsUnchanged(before: unknown, after: unknown): void {\n  if (reviewJson(before) !== reviewJson(after))\n    throw new MergeReviewError(\n      \"Merge options changed while review evidence was being captured.\",\n    );\n}\n\nfunction compareReviewTarget(\n  reviewed: MergePlanTargetFence,\n  current: MergePlanTargetFence,\n): readonly MergeReviewDifference[] {\n  return compareFields(\n    \"target\",\n    {\n      graphId: reviewed.graphId,\n      schema: reviewed.schema,\n      origin: reviewed.revision.origin,\n    },\n    {\n      graphId: current.graphId,\n      schema: current.schema,\n      origin: current.revision.origin,\n    },\n  );\n}\n\n/**\n * Only the candidate adapter may replace its target-derived fork/branch anchors:\n * it recreates them from the retained input on every call. No arbitrary snapshot\n * or incremental plan is accepted by this protocol. Keep every other field.\n */\nfunction reviewPlanContent(\n  plan: MergePlanArtifact,\n): Omit<MergePlanArtifact, \"digest\" | \"target\" | \"anchors\"> {\n  const {\n    digest: _digest,\n    target: _target,\n    anchors: _anchors,\n    ...content\n  } = plan;\n  return content;\n}\n\nfunction compareFields(\n  category: MergeReviewDifference[\"category\"],\n  reviewed: Readonly<Record<string, unknown>>,\n  current: Readonly<Record<string, unknown>>,\n): readonly MergeReviewDifference[] {\n  return [...new Set([...Object.keys(reviewed), ...Object.keys(current)])]\n    .sort()\n    .filter((key) => reviewJson(reviewed[key]) !== reviewJson(current[key]))\n    .map((key) => ({ category, path: `${category}.${key}` }));\n}\n\nfunction asReviewError(error: unknown): MergeError {\n  return error instanceof MergeError ? error : (\n      new MergeReviewError(\n        \"Unable to validate or capture merge review evidence.\",\n        { cause: error },\n      )\n    );\n}\n","/**\n * Durable working-copy branches: a JSON-serializable descriptor for a\n * PERSISTENT working copy plus reopen / destroy operations over it.\n *\n * `branch()` produces an {@link GraphBranch} whose store/close handle lives\n * only in the process that minted it. A durable branch instead pairs the normal\n * {@link GraphBranch} with a {@link DurableBranchDescriptor} — a plain JSON\n * document the caller can store anywhere — so a LATER process can reconnect to\n * the SAME mutated working copy without cloning the base and without keeping an\n * in-memory map of open handles.\n *\n * The descriptor has two halves:\n *\n *   - TypeGraph-owned fences: `kind`/`version`, the owning `graphId`, the\n *     branch id, the `base@V` token the working copy forked from, the at-fork\n *     schema anchor (explicitly absent for an unmanaged store), and the\n *     at-fork engine revision when the working copy resolved `lineage`.\n *   - An opaque, strategy-defined `store` locator. TypeGraph never interprets\n *     it and never assumes a database URL, product, or dialect.\n *\n * TAMPER MODEL: the descriptor is a document the caller stores and later hands\n * back, so every TypeGraph-owned fence in it is UNTRUSTED. The durable host is\n * the authority: at seal time it persists the {@link DurableBranchOrigin} that\n * TypeGraph captured at the fork, and at reopen it ATTESTS the complete origin\n * it holds. Reopen refuses unless every descriptor fence equals the attested\n * origin — a tampered `graphId`/`definitionHash`/`base`/`branchId`/\n * `forkRevision`/`schemaAnchor`, including DELETING `schemaAnchor` from the\n * envelope, cannot relabel a fork, because the host's own record is the\n * reference. `destroy` is verified the same way before it deletes (see\n * {@link DurableWorkingCopyStrategy.destroy}), so swapping one working copy's\n * locator for another's cannot destroy the wrong allocation.\n *\n * DEFINITION IDENTITY is part of that origin and is INDEPENDENT of the optional\n * committed `schemaAnchor`: the host attests the `graphId` AND a version-blind\n * {@link getGraphDefinitionHash} of the caller's fork-time definition. An\n * unmanaged working copy (one that committed no schema row, so its\n * `schemaAnchor` is absent) therefore still refuses descriptor `graphId`\n * relabeling, reopening with a different `graphId`, and — the case a missing\n * anchor used to let through — a SAME-ID graph whose definition hashes\n * differently. Definition identity is the fork-time caller definition; the\n * branch's CURRENT committed schema may legitimately evolve after forking, so\n * reopen never compares the live schema row to the fork-time identity.\n *\n * The host lifecycle is split deliberately. `GraphBranch.close()` releases the\n * process's CONNECTION to the working copy — it must never delete it. Explicit\n * teardown is a separate strategy operation, {@link DurableWorkingCopyStrategy.destroy},\n * surfaced through {@link destroyDurableBranch}. This keeps the ephemeral\n * {@link ForkHandle.dispose}-deletes-the-fork contract out of the durable path,\n * where \"the process closed its connection\" and \"the working copy is gone\" are\n * different events.\n *\n * The at-fork schema anchor is IMMUTABLE FORK METADATA, never a statement about\n * the working copy's CURRENT schema: a branch may legitimately evolve its\n * committed schema after forking, and reopen must still succeed. Reopen therefore\n * never compares the live schema row to the anchor; it compares the descriptor's\n * anchor to the host's, and the caller's graph definition to the attested\n * definition hash. The merge path separately refuses a branch whose LIVE schema\n * moved (see `merge.ts`'s at-fork drift guard); reopen is not that gate.\n *\n * Backend-specific mechanics remain entirely within the strategy.\n */\n\nimport { computeBaseVersion, schemaComponentOf } from \"./base-version\";\nimport { readBranchForkState } from \"./branch\";\nimport type { DurableOperationCapability } from \"./durable-operation\";\nimport {\n  BranchError,\n  describeCause,\n  DurableEvidenceUndeliveredError,\n} from \"./errors\";\nimport type { MergePlanArtifactV1 } from \"./plan-schema\";\nimport type { Result } from \"./result\";\nimport { err, ok } from \"./result\";\nimport { diffAgainstBase } from \"./state-diff\";\nimport type {\n  EngineRevision,\n  GraphDef,\n  JsonValue,\n  Store,\n} from \"./typegraph-internal\";\nimport { generateId, getGraphDefinitionHash } from \"./typegraph-internal\";\nimport type {\n  BaseVersion,\n  BranchId,\n  BranchOptions,\n  GraphBranch,\n  MergedCounts,\n} from \"./types\";\nimport { asBranchId } from \"./types\";\nimport { coalescedWorkingCopyClose } from \"./working-copy\";\n\n/**\n * A strategy-defined, JSON-serializable locator for one PERSISTENT working\n * copy. TypeGraph treats it as opaque data: it is carried inside a\n * {@link DurableBranchDescriptor} and handed back to the strategy on reopen and\n * destroy, never inspected. It must survive `JSON.parse(JSON.stringify(...))`\n * unchanged. It MUST be a non-secret identifier: TypeGraph returns it to the\n * caller. Connection strings, credentials, bearer tokens, and other secrets do\n * not belong here; keep those in strategy-owned configuration and resolve this\n * locator there. TypeGraph deliberately omits it from cleanup error details.\n */\nexport type DurableStoreDescriptor = JsonValue;\n\n/**\n * The write-access guarantee a strategy acquired for one opened working copy.\n *\n * `engine-fenced` means the database provides sound cross-client isolation and\n * change fencing for the full Store planning/apply access pattern, across every\n * connection and process that could mutate the working copy.\n * `exclusive` means the host acquired an allocation-wide writer lease before\n * returning. That lease MUST exclude every other process and backend instance,\n * not merely serialize calls through one in-memory queue. TypeGraph releases it\n * after the Store backend closes; a failed release is retried by the next\n * `GraphBranch.close()` call.\n *\n * A backend that provides only `caller-serialized` access MUST use `exclusive`:\n * each backend instance owns a different in-process queue, so that declaration\n * alone does not serialize two durable reopen handles or two processes.\n */\nexport type DurableWorkingCopyAccess =\n  | Readonly<{ kind: \"engine-fenced\" }>\n  | Readonly<{\n      kind: \"exclusive\";\n      leaseId: string;\n      release: () => Promise<void>;\n    }>;\n\n/** Why an authoritative native merge attempt could not safely run. */\nexport type NativeDurableMergeUnsupportedDimension =\n  | \"branchOrigin\"\n  | \"graphScope\"\n  | \"nativeConflicts\"\n  | \"planSemantics\"\n  | \"targetFence\";\n\n/**\n * Result of a host-native merge optimization attempt.\n *\n * `unsupported` proves that NO native merge SQL or host mutation ran; TypeGraph\n * then executes the complete portable plan application. `applied` proves the\n * strategy atomically validated every dimension named by\n * {@link DurableWorkingCopyStrategy.merge} and applied exactly the approved\n * plan. A refusal or uncertain/partial execution throws instead of returning\n * `unsupported`, because falling back after a possible native write would\n * double-apply the plan.\n */\nexport type NativeDurableMergeResult =\n  | Readonly<{\n      outcome: \"applied\";\n      merged: MergedCounts;\n      warnings?: readonly string[] | undefined;\n    }>\n  | Readonly<{\n      outcome: \"unsupported\";\n      dimensions: readonly [\n        NativeDurableMergeUnsupportedDimension,\n        ...NativeDurableMergeUnsupportedDimension[],\n      ];\n    }>;\n\n/**\n * The complete immutable TypeGraph origin of one durable working copy — every\n * TypeGraph-owned fork fence, with NO dependence on the descriptor: the graph\n * id and version-blind graph-definition hash identifying the fork-time caller\n * definition, the branch id, the `base@V` token it forked from, the at-fork\n * schema anchor (`undefined` meaning the working copy committed no schema row —\n * an EXPLICIT absent, so a descriptor that simply omits the field still\n * disagrees with a host that persisted one), and the at-fork engine revision\n * (`undefined` when the working copy resolved no lineage).\n *\n * `graphId` and `definitionHash` are REQUIRED and carry the definition identity\n * even when `schemaAnchor` is absent: an unmanaged working copy still has to\n * reject relabeling and same-id divergent definitions. The host persists this\n * at seal time and attests it at reopen/destroy; it is the reference every\n * descriptor fence is compared against.\n */\nexport type DurableBranchOrigin = Readonly<{\n  graphId: string;\n  definitionHash: string;\n  branchId: BranchId;\n  base: BaseVersion;\n  schemaAnchor: Readonly<{ version: number; hash: string }> | undefined;\n  forkRevision: EngineRevision | undefined;\n}>;\n\n/**\n * The durable envelope for a branch: the TypeGraph-owned fences a reopen\n * re-validates plus the strategy's opaque store locator.\n *\n * `kind`/`version` identify the strategy's descriptor FORMAT. `graphId` and\n * `definitionHash` bind the descriptor to one fork-time graph definition, and\n * `branchId` to one working copy. `base`, `schemaAnchor` and `forkRevision` are\n * the same at-fork fences a live {@link GraphBranch} carries, captured when the\n * branch was created.\n *\n * The fences are untrusted on reopen — see the module doc's tamper model.\n * `schemaAnchor` is PRESENT with value `undefined` when the working copy\n * committed no schema row (an unmanaged store), mirroring `branch()`'s own\n * representation; JSON storage drops the key, and the host's own attestation\n * restores the distinction on reopen.\n */\nexport type DurableBranchDescriptor<\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n> = Readonly<{\n  /** Stable strategy type tag; must equal the reopening strategy's `type`. */\n  kind: string;\n  /** Strategy descriptor format version; must equal the strategy's `version`. */\n  version: number;\n  /** The graph id the working copy belongs to. */\n  graphId: string;\n  /**\n   * The version-blind graph-definition hash of the caller's fork-time\n   * definition. Attested by the host, so it fences a same-id divergent\n   * definition even for an unmanaged working copy with no `schemaAnchor`.\n   */\n  definitionHash: string;\n  /** The TypeGraph branch id the working copy is identified by. */\n  branchId: BranchId;\n  /** The immutable `base@V` token the working copy forked from. */\n  base: BaseVersion;\n  /** The strategy's opaque, JSON-serializable locator for the working copy. */\n  store: TStoreDescriptor;\n  /** The at-fork committed schema `(version, hash)`; `undefined` when unmanaged. */\n  schemaAnchor?: Readonly<{ version: number; hash: string }> | undefined;\n  /** The at-fork engine revision, when the working copy resolves `lineage`. */\n  forkRevision?: EngineRevision | undefined;\n}>;\n\n/**\n * The host-owned half of a durable working copy: how a persistent working copy\n * is allocated, sealed, reconnected to, and explicitly destroyed.\n *\n * The create -> seal/abort protocol has explicit ownership:\n *\n *   1. `create` allocates the persistent working copy and returns a mutable\n *      {@link Store} over it plus the opaque locator. Once `create` resolves,\n *      TypeGraph owns the allocation and the returned store.\n *   2. TypeGraph captures the fork state off the store and calls `seal` with\n *      the complete {@link DurableBranchOrigin}. The host MUST persist that\n *      origin durably before `seal` resolves — it is what later attestations\n *      compare a descriptor against.\n *   3. If capturing OR sealing fails, TypeGraph calls `abort`: the host releases\n *      the just-created allocation (deleting it) so no orphan survives. `abort`\n *      is only ever called on an allocation this same `create` produced, so it\n *      need not verify identity; it MUST tolerate a partially-sealed allocation.\n *      An `abort` failure does NOT mask the original capture/seal failure:\n *      TypeGraph returns a {@link BranchError} preserving that original failure\n *      as its `cause` and reports `details.allocationAborted: false`. The opaque\n *      locator and raw cleanup error are deliberately NOT copied into error\n *      details, where application logging could disclose host credentials or\n *      other strategy-private data. Operator tooling can use the safe TypeGraph\n *      branch id supplied to `create` to identify the orphan.\n *\n * `reopen` reconnects to an EXISTING working copy identified by `descriptor`\n * without cloning, and returns the complete origin the host PERSISTED for that\n * locator. TypeGraph refuses when any descriptor fence disagrees with that\n * attested origin. A reopen failure (missing or deleted store, unreachable\n * host) throws; the strategy must not leave an opened backend behind when it\n * throws.\n *\n * `destroy` is the ONLY operation that may delete or archive the persistent\n * working copy. It receives the locator AND the caller's expected origin and\n * MUST verify, atomically with respect to its own persistence, that the origin\n * stored for that locator equals `expectedOrigin` before deleting — otherwise a\n * descriptor whose locator was swapped for another working copy's would destroy\n * the wrong allocation. A mismatch refuses without deleting. Closing the\n * returned branch's `close()` releases just the connection and must leave the\n * working copy reopenable.\n */\nexport type DurableWorkingCopyStrategy<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n> = Readonly<{\n  type: string;\n  version: number;\n  create: (\n    baseStore: Store<G>,\n    base: BaseVersion,\n    branchId: BranchId,\n  ) => Promise<\n    Readonly<{\n      store: Store<G>;\n      descriptor: TStoreDescriptor;\n      access: DurableWorkingCopyAccess;\n    }>\n  >;\n  seal: (\n    descriptor: TStoreDescriptor,\n    origin: DurableBranchOrigin,\n  ) => Promise<void>;\n  abort: (descriptor: TStoreDescriptor) => Promise<void>;\n  reopen: (\n    graph: G,\n    descriptor: TStoreDescriptor,\n  ) => Promise<\n    Readonly<{\n      store: Store<G>;\n      origin: DurableBranchOrigin;\n      access: DurableWorkingCopyAccess;\n    }>\n  >;\n  destroy: (\n    descriptor: TStoreDescriptor,\n    expectedOrigin: DurableBranchOrigin,\n  ) => Promise<void>;\n  /**\n   * Optional authoritative host-native merge optimization.\n   *\n   * Before returning `applied`, the strategy MUST, atomically with the native\n   * merge operation:\n   *\n   * 1. attest `expectedOrigin` against the same allocation `branch.store` is\n   *    connected to;\n   * 2. validate `plan.target` on the exact target branch/session the host will\n   *    merge into;\n   * 3. prove the host-native diff contains exactly `plan.writes`, including all\n   *    TypeGraph sidecars and no rows belonging to another graph or application;\n   * 4. prove the plan needs no canonicalization, repointing, identity, callback,\n   *    provenance, or other semantic work the native merge would bypass; and\n   * 5. report the actual applied counts.\n   *\n   * A whole-database merge primitive therefore qualifies only for an allocation\n   * whose complete physical diff is owned by this graph and is byte-for-byte\n   * equivalent to the approved TypeGraph plan. If any dimension cannot be\n   * proven, return `unsupported` BEFORE executing host SQL; TypeGraph will apply\n   * the plan through its portable transaction path.\n   */\n  merge?:\n    | ((\n        args: Readonly<{\n          target: Store<G>;\n          branch: GraphBranch<G>;\n          descriptor: TStoreDescriptor;\n          expectedOrigin: DurableBranchOrigin;\n          plan: MergePlanArtifactV1;\n        }>,\n      ) => Promise<NativeDurableMergeResult>)\n    | undefined;\n  /**\n   * Optional atomic operation + evidence capability.\n   *\n   * When present, {@link import(\"./durable-operation\").operateDurableBranch}\n   * commits the host's opaque graph mutation and its immutable evidence in one\n   * host transaction, keyed by idempotency. `destroy` MUST additionally refuse\n   * to remove the allocation while undelivered evidence remains, throwing\n   * {@link DurableEvidenceUndeliveredError}; closing a branch handle still only\n   * releases the connection.\n   *\n   * A strategy that cannot provide the atomic guarantee MUST omit this\n   * capability (or return `unsupported` from `operate`) rather than emulating\n   * atomicity with callbacks or best effort. See `durable-operation.ts`.\n   */\n  operations?: DurableOperationCapability<TStoreDescriptor> | undefined;\n}>;\n\n/**\n * A normal {@link GraphBranch} paired with the serializable descriptor that\n * lets a later process reopen the SAME working copy. `branch` behaves exactly\n * like a `branch()` result — plan/merge APIs and `close()` are unchanged.\n */\nexport type DurableBranch<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n> = Readonly<{\n  branch: GraphBranch<G>;\n  descriptor: DurableBranchDescriptor<TStoreDescriptor>;\n}>;\n\n/**\n * Creates a durable working-copy branch of `baseStore`.\n *\n * Stamps the `base@V` token off the base, mints (or accepts) a {@link BranchId},\n * delegates materialization to `strategy.create`, captures the graph id and\n * version-blind definition hash, the at-fork schema anchor, and the engine\n * revision, then SEALS the complete origin into the host before returning the\n * normal {@link GraphBranch} together with its JSON-serializable\n * {@link DurableBranchDescriptor}.\n *\n * Returns a {@link Result}; any failure is wrapped in a {@link BranchError}.\n * Once `strategy.create` resolves, the working copy's store and persistent\n * allocation belong to this function: a capture or seal failure closes the\n * store and calls `strategy.abort`, so this never returns an unrecoverable\n * success and never leaves an orphan.\n *\n * @param baseStore - The store to fork. Remains untouched.\n * @param strategy - The durable working-copy strategy owning the host mechanics.\n * @param options - Optional `{ id }` to set an explicit branch id.\n */\nexport async function branchDurable<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n>(\n  baseStore: Store<G>,\n  strategy: DurableWorkingCopyStrategy<G, TStoreDescriptor>,\n  options?: BranchOptions,\n): Promise<Result<DurableBranch<G, TStoreDescriptor>, BranchError>> {\n  let base: BaseVersion;\n  let id: BranchId;\n  try {\n    base = await computeBaseVersion(baseStore);\n    id = options?.id ?? asBranchId(generateId());\n  } catch (error) {\n    return err(\n      new BranchError(\n        \"Failed to stamp the durable branch base version for the base store.\",\n        { cause: error },\n      ),\n    );\n  }\n\n  let created: Readonly<{\n    store: Store<G>;\n    descriptor: TStoreDescriptor;\n    access: DurableWorkingCopyAccess;\n  }>;\n  try {\n    created = await strategy.create(baseStore, base, id);\n  } catch (error) {\n    return err(\n      new BranchError(\n        \"Failed to create durable working-copy branch of base store\",\n        { cause: error },\n      ),\n    );\n  }\n\n  // `create` resolved: this function owns the store AND the persistent\n  // allocation. A capture or seal failure abandons both.\n  let forkState;\n  let definitionHash: string;\n  try {\n    await assertDurableWorkingCopyMatchesBase(baseStore, created.store, base);\n    forkState = await readBranchForkState(created.store);\n    definitionHash = await getGraphDefinitionHash(created.store.graph);\n  } catch (error) {\n    return err(await abandonAllocation(strategy, created, id, error));\n  }\n\n  const origin: DurableBranchOrigin = {\n    graphId: created.store.graphId,\n    definitionHash,\n    branchId: id,\n    base,\n    schemaAnchor: forkState.schemaAnchor,\n    forkRevision: forkState.forkRevision,\n  };\n  try {\n    await strategy.seal(created.descriptor, origin);\n  } catch (error) {\n    return err(await abandonAllocation(strategy, created, id, error));\n  }\n\n  const branch: GraphBranch<G> = {\n    id,\n    base,\n    store: created.store,\n    close: coalescedDurableClose(created.store, created.access),\n    ...(forkState.schemaAnchor === undefined ?\n      { schemaAnchor: undefined }\n    : { schemaAnchor: forkState.schemaAnchor }),\n    ...(forkState.forkRevision === undefined ?\n      {}\n    : { forkRevision: forkState.forkRevision }),\n  };\n  const descriptor: DurableBranchDescriptor<TStoreDescriptor> = {\n    kind: strategy.type,\n    version: strategy.version,\n    graphId: created.store.graphId,\n    definitionHash,\n    branchId: id,\n    base,\n    store: created.descriptor,\n    ...(forkState.schemaAnchor === undefined ?\n      { schemaAnchor: undefined }\n    : { schemaAnchor: forkState.schemaAnchor }),\n    ...(forkState.forkRevision === undefined ?\n      {}\n    : { forkRevision: forkState.forkRevision }),\n  };\n  return ok({ branch, descriptor });\n}\n\n/**\n * Proves a durable allocation was created from the stamped source state.\n *\n * A physical database fork preserves the complete `base@V` token, so that\n * common path remains O(1). A strategy may instead build an equivalent\n * persistent copy whose revision namespace is intentionally independent. For\n * that case, compare the complete merge-visible graph state while fencing the\n * source before and after enumeration. The strategy remains responsible for\n * physical fidelity outside TypeGraph's graph semantics.\n */\nasync function assertDurableWorkingCopyMatchesBase<G extends GraphDef>(\n  baseStore: Store<G>,\n  workingCopy: Store<G>,\n  base: BaseVersion,\n): Promise<void> {\n  const sourceVersionBeforeDiff = await computeBaseVersion(baseStore);\n  if (sourceVersionBeforeDiff !== base) {\n    throw new BranchError(\n      \"Base store changed while the durable working copy was being allocated.\",\n      {\n        details: {\n          baseVersion: base,\n          liveBaseVersion: sourceVersionBeforeDiff,\n        },\n      },\n    );\n  }\n\n  if (workingCopy.graphId !== baseStore.graphId) {\n    throw new BranchError(\n      \"Durable working copy belongs to a different graph than its base store.\",\n      {\n        details: {\n          expectedGraphId: baseStore.graphId,\n          receivedGraphId: workingCopy.graphId,\n        },\n      },\n    );\n  }\n\n  const workingCopyVersion = await computeBaseVersion(workingCopy);\n  if (workingCopyVersion === base) return;\n  if (schemaComponentOf(workingCopyVersion) !== schemaComponentOf(base)) {\n    throw new BranchError(\n      \"Durable working copy schema does not match its stamped base schema.\",\n      {\n        details: {\n          baseSchema: schemaComponentOf(base),\n          workingCopySchema: schemaComponentOf(workingCopyVersion),\n        },\n      },\n    );\n  }\n\n  const diff = await diffAgainstBase(baseStore, workingCopy, false);\n  const sourceVersionAfterDiff = await computeBaseVersion(baseStore);\n  if (sourceVersionAfterDiff !== base) {\n    throw new BranchError(\n      \"Base store changed while the durable working copy was being verified.\",\n      {\n        details: {\n          baseVersion: base,\n          liveBaseVersion: sourceVersionAfterDiff,\n        },\n      },\n    );\n  }\n\n  const changed =\n    diff.nodes.new.length > 0 ||\n    diff.nodes.modified.length > 0 ||\n    diff.nodes.deleted.length > 0 ||\n    diff.nodes.windowed.length > 0 ||\n    diff.edges.new.length > 0 ||\n    diff.edges.modified.length > 0 ||\n    diff.edges.deleted.length > 0 ||\n    diff.edges.windowed.length > 0 ||\n    diff.identity.new.length > 0 ||\n    diff.identity.retracted.length > 0;\n  if (!changed) return;\n\n  throw new BranchError(\n    \"Durable working copy does not match its base: the stamped graph state differs.\",\n    {\n      details: {\n        baseVersion: base,\n        workingCopyVersion,\n        changedNodes:\n          diff.nodes.new.length +\n          diff.nodes.modified.length +\n          diff.nodes.deleted.length +\n          diff.nodes.windowed.length,\n        changedEdges:\n          diff.edges.new.length +\n          diff.edges.modified.length +\n          diff.edges.deleted.length +\n          diff.edges.windowed.length,\n        changedIdentityAssertions:\n          diff.identity.new.length + diff.identity.retracted.length,\n      },\n    },\n  );\n}\n\n/**\n * Reconnects to an existing durable working copy and reconstructs the normal\n * {@link GraphBranch} for it.\n *\n * Validates, in order: descriptor shape/type/version, graph id agreement,\n * strategy reconnect, store graph id, and — the load-bearing step — every\n * descriptor fence against the complete origin the host attests. A tampered\n * `graphId`/`definitionHash`/`branchId`/`base`/`schemaAnchor`/`forkRevision`,\n * including a DELETED `schemaAnchor`, is refused here; the host's persisted\n * record is the reference, never the descriptor. Finally the caller's graph\n * definition must hash to the attested fork-time definition AND agree on graph\n * id (a different graph definition, even one reusing the graph id, is not the\n * branch that was forked). Because the definition identity is attested\n * independently of `schemaAnchor`, this holds for an unmanaged working copy\n * with no committed schema row.\n *\n * The working copy's CURRENT committed schema is deliberately NOT compared to\n * the anchor: a branch may evolve its schema after forking and must remain\n * reopenable — the anchor is immutable fork metadata, not current schema.\n *\n * Every refusal is a typed {@link BranchError}, and any backend the strategy\n * opened is closed before the refusal is returned. The persistent working copy\n * is NEVER deleted here.\n *\n * @param graph - The graph definition the working copy was built with.\n * @param descriptor - The serialized descriptor returned by {@link branchDurable}.\n * @param strategy - The SAME strategy that produced `descriptor`.\n */\nexport async function reopenDurableBranch<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n>(\n  graph: G,\n  descriptor: DurableBranchDescriptor<TStoreDescriptor>,\n  strategy: DurableWorkingCopyStrategy<G, TStoreDescriptor>,\n): Promise<Result<GraphBranch<G>, BranchError>> {\n  const refusal = durableDescriptorRefusal(descriptor, strategy);\n  if (refusal !== undefined) return err(refusal);\n  if (descriptor.graphId !== graph.id) {\n    return err(\n      new BranchError(\n        `Durable branch descriptor belongs to graph \"${descriptor.graphId}\", not \"${graph.id}\".`,\n        {\n          details: { descriptorGraphId: descriptor.graphId, graphId: graph.id },\n        },\n      ),\n    );\n  }\n  let reopened: Readonly<{\n    store: Store<G>;\n    origin: DurableBranchOrigin;\n    access: DurableWorkingCopyAccess;\n  }>;\n  try {\n    reopened = await strategy.reopen(graph, descriptor.store);\n  } catch (error) {\n    return err(\n      new BranchError(\n        `Failed to reopen durable working copy for branch \"${descriptor.branchId}\": ${describeCause(error)}`,\n        {\n          cause: error,\n          details: { branchId: descriptor.branchId, graphId: graph.id },\n          suggestion:\n            \"Confirm the persistent working copy still exists and is reachable by the strategy, then retry.\",\n        },\n      ),\n    );\n  }\n  const { access, store, origin } = reopened;\n  try {\n    if (store.graphId !== graph.id) {\n      throw new BranchError(\n        `Reopened working copy belongs to graph \"${store.graphId}\", not \"${graph.id}\".`,\n        {\n          details: {\n            branchId: descriptor.branchId,\n            reopenedGraphId: store.graphId,\n            graphId: graph.id,\n          },\n        },\n      );\n    }\n    const descriptorOrigin = durableOriginOfDescriptor(descriptor);\n    if (!durableOriginsEqual(descriptorOrigin, origin)) {\n      throw new BranchError(\n        `Durable branch descriptor does not match the working copy the host attested for its store locator: the descriptor's TypeGraph fences disagree with the origin recorded at fork. This is a tampered, relabeled, or wrong-branch descriptor.`,\n        {\n          details: {\n            branchId: descriptor.branchId,\n            descriptorOrigin,\n            attestedOrigin: origin,\n          },\n        },\n      );\n    }\n    await assertGraphMatchesAttestedOrigin(graph, origin);\n    return ok(rebuildBranch(store, access, descriptor));\n  } catch (error) {\n    await closeDurableQuietly(store, access);\n    return err(\n      error instanceof BranchError ? error : (\n        new BranchError(\n          `Failed to reattach durable working copy for branch \"${descriptor.branchId}\": ${describeCause(error)}`,\n          { cause: error, details: { branchId: descriptor.branchId } },\n        )\n      ),\n    );\n  }\n}\n\n/**\n * Explicitly destroys (deletes or archives) the persistent working copy the\n * descriptor names. This is the ONLY operation that may do so; closing a\n * reopened branch's `close()` never reaches here.\n *\n * The complete descriptor origin is passed to the strategy alongside the\n * locator and MUST be verified against the host's persisted origin before\n * deletion, so a descriptor whose locator was swapped for another working\n * copy's cannot destroy the wrong allocation.\n *\n * Returns a {@link Result}: a malformed/wrong-strategy descriptor or a strategy\n * failure (including an identity mismatch) is a typed {@link BranchError}. After\n * a successful destroy, reopening the same descriptor fails.\n */\nexport async function destroyDurableBranch<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n>(\n  descriptor: DurableBranchDescriptor<TStoreDescriptor>,\n  strategy: DurableWorkingCopyStrategy<G, TStoreDescriptor>,\n): Promise<Result<void, BranchError>> {\n  const refusal = durableDescriptorRefusal(descriptor, strategy);\n  if (refusal !== undefined) return err(refusal);\n  try {\n    await strategy.destroy(\n      descriptor.store,\n      durableOriginOfDescriptor(descriptor),\n    );\n    return ok(undefined);\n  } catch (error) {\n    // The undelivered-evidence fence is a deliberate, typed refusal: preserve\n    // it instead of flattening it into a generic branch failure, so the caller\n    // can still recover the evidence.\n    if (error instanceof DurableEvidenceUndeliveredError) return err(error);\n    return err(\n      new BranchError(\n        `Failed to destroy durable working copy for branch \"${descriptor.branchId}\": ${describeCause(error)}`,\n        { cause: error, details: { branchId: descriptor.branchId } },\n      ),\n    );\n  }\n}\n\n/**\n * Releases an allocation whose capture or seal failed: closes the store's\n * connection, then asks the strategy to abort (delete) the persistent working\n * copy.\n *\n * The returned {@link BranchError} is truthful about what happened without\n * copying strategy-private values into commonly logged error details:\n *\n *   - The original capture/seal failure is preserved as `cause`.\n *   - `details.allocationAborted` records whether `strategy.abort` actually\n *     succeeded, and the message never claims a failed abort removed the\n *     allocation.\n *   - The opaque locator and raw cleanup error are deliberately omitted from\n *     `details`, because framework errors are commonly logged. Strategy\n *     operator tooling uses the safe `branchId` and `strategyType` instead.\n */\nasync function abandonAllocation<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor,\n>(\n  strategy: DurableWorkingCopyStrategy<G, TStoreDescriptor>,\n  created: Readonly<{\n    store: Store<G>;\n    descriptor: TStoreDescriptor;\n    access: DurableWorkingCopyAccess;\n  }>,\n  branchId: BranchId,\n  cause: unknown,\n): Promise<BranchError> {\n  await closeDurableQuietly(created.store, created.access);\n  let aborted = false;\n  try {\n    await strategy.abort(created.descriptor);\n    aborted = true;\n  } catch {\n    // The raw strategy error may contain connection details. Report the safe\n    // cleanup status below without copying that value into a framework error.\n  }\n  return new BranchError(\n    aborted ?\n      `Failed to finish durable working-copy branch \"${branchId}\" after the host allocated it; the opened store was closed and the persistent allocation was aborted.`\n    : `Failed to finish durable working-copy branch \"${branchId}\" after the host allocated it; the opened store was closed, but the host could NOT abort the persistent allocation, which may survive as an orphan.`,\n    {\n      cause,\n      details: {\n        branchId,\n        strategyType: strategy.type,\n        allocationAborted: aborted,\n      },\n      ...(aborted ?\n        {}\n      : {\n          suggestion:\n            \"The strategy's abort failed, so the persistent allocation for `details.branchId` may still exist. Inspect or remove it through the strategy's operator tooling.\",\n        }),\n    },\n  );\n}\n\n/**\n * The strategy fields descriptor validation reads; nothing host-specific.\n */\ntype DescriptorOwner = Readonly<{ type: string; version: number }>;\n\n/**\n * Structural and format validation of a (possibly JSON-parsed, hence untyped)\n * descriptor against the strategy that must own it. Returns the typed refusal\n * or `undefined` when the envelope is well-formed.\n *\n * Runtime shape checks are load-bearing: a descriptor that round-tripped\n * through JSON has no TypeScript guarantees, so a wrong-strategy, wrong-version,\n * or malformed envelope must be caught before any host is touched. These checks\n * are about FORMAT only; fence soundness is decided against host attestation.\n */\nexport function durableDescriptorRefusal(\n  descriptor: unknown,\n  strategy: DescriptorOwner,\n): BranchError | undefined {\n  if (\n    typeof descriptor !== \"object\" ||\n    descriptor === null ||\n    Array.isArray(descriptor)\n  ) {\n    return new BranchError(\"Durable branch descriptor must be a JSON object.\", {\n      details: { strategyType: strategy.type },\n    });\n  }\n  const record = descriptor as Readonly<Record<string, unknown>>;\n  if (record[\"kind\"] !== strategy.type) {\n    return new BranchError(\n      `Durable branch descriptor belongs to strategy \"${String(record[\"kind\"])}\", not \"${strategy.type}\".`,\n      {\n        details: {\n          descriptorKind: record[\"kind\"],\n          strategyType: strategy.type,\n        },\n      },\n    );\n  }\n  if (record[\"version\"] !== strategy.version) {\n    return new BranchError(\n      `Durable branch descriptor version ${String(record[\"version\"])} is not supported by strategy \"${strategy.type}\" (expected ${strategy.version}).`,\n      {\n        details: {\n          descriptorVersion: record[\"version\"],\n          strategyVersion: strategy.version,\n        },\n      },\n    );\n  }\n  for (const key of [\n    \"graphId\",\n    \"definitionHash\",\n    \"branchId\",\n    \"base\",\n  ] as const) {\n    const value = record[key];\n    if (typeof value !== \"string\" || value.length === 0) {\n      return new BranchError(\n        `Durable branch descriptor is malformed: \"${key}\" must be a non-empty string.`,\n        { details: { key, strategyType: strategy.type } },\n      );\n    }\n  }\n  if (!(\"store\" in record)) {\n    return new BranchError(\n      \"Durable branch descriptor is malformed: no strategy store locator.\",\n      { details: { strategyType: strategy.type } },\n    );\n  }\n  if (record[\"schemaAnchor\"] !== undefined) {\n    const anchor = record[\"schemaAnchor\"];\n    if (\n      typeof anchor !== \"object\" ||\n      anchor === null ||\n      typeof (anchor as Readonly<Record<string, unknown>>)[\"version\"] !==\n        \"number\" ||\n      typeof (anchor as Readonly<Record<string, unknown>>)[\"hash\"] !== \"string\"\n    ) {\n      return new BranchError(\n        \"Durable branch descriptor is malformed: schemaAnchor must be { version: number; hash: string }.\",\n        { details: { strategyType: strategy.type } },\n      );\n    }\n  }\n  if (\n    record[\"forkRevision\"] !== undefined &&\n    typeof record[\"forkRevision\"] !== \"string\"\n  ) {\n    return new BranchError(\n      \"Durable branch descriptor is malformed: forkRevision must be a string.\",\n      { details: { strategyType: strategy.type } },\n    );\n  }\n  return undefined;\n}\n\n/** Extracts the TypeGraph-owned origin from a descriptor envelope. */\nexport function durableOriginOfDescriptor<\n  TStoreDescriptor extends DurableStoreDescriptor,\n>(descriptor: DurableBranchDescriptor<TStoreDescriptor>): DurableBranchOrigin {\n  return {\n    graphId: descriptor.graphId,\n    definitionHash: descriptor.definitionHash,\n    branchId: descriptor.branchId,\n    base: descriptor.base,\n    schemaAnchor: descriptor.schemaAnchor,\n    forkRevision: descriptor.forkRevision,\n  };\n}\n\n/**\n * THE one equality for a descriptor origin against a host-attested one. Every\n * fence participates — including the graph id and version-blind definition hash\n * that carry definition identity independently of `schemaAnchor` — and an\n * absent schema anchor matches only an absent one (explicit-absent semantics),\n * so a descriptor that dropped the key disagrees with a host that persisted the\n * anchor.\n */\nexport function durableOriginsEqual(\n  descriptor: DurableBranchOrigin,\n  attested: DurableBranchOrigin,\n): boolean {\n  return (\n    descriptor.graphId === attested.graphId &&\n    descriptor.definitionHash === attested.definitionHash &&\n    descriptor.branchId === attested.branchId &&\n    descriptor.base === attested.base &&\n    schemaAnchorsEqual(descriptor.schemaAnchor, attested.schemaAnchor) &&\n    descriptor.forkRevision === attested.forkRevision\n  );\n}\n\nfunction schemaAnchorsEqual(\n  left: Readonly<{ version: number; hash: string }> | undefined,\n  right: Readonly<{ version: number; hash: string }> | undefined,\n): boolean {\n  if (left === undefined || right === undefined) return left === right;\n  return left.version === right.version && left.hash === right.hash;\n}\n\n/**\n * The graph-identity half of reopen's fences, against the COMPLETE\n * host-attested {@link DurableBranchOrigin}.\n *\n * The caller's graph must name the attested graph id AND hash to the attested\n * version-blind definition hash: a graph definition that hashes differently is\n * a DIFFERENT definition — even one reusing the graph id — and attaching it\n * would misread the working copy. This is the fence that protects an UNMANAGED\n * working copy, whose `schemaAnchor` is absent; it never consults the anchor and\n * is deliberately NOT a comparison against the working copy's live schema row\n * (a branch may evolve its committed schema after forking and must still\n * reopen). Throws a {@link BranchError}; the caller closes the store.\n */\nasync function assertGraphMatchesAttestedOrigin<G extends GraphDef>(\n  graph: G,\n  origin: DurableBranchOrigin,\n): Promise<void> {\n  if (graph.id !== origin.graphId) {\n    throw new BranchError(\n      `The supplied graph \"${graph.id}\" is not the graph the durable working copy was forked from (\"${origin.graphId}\").`,\n      {\n        details: {\n          graphId: graph.id,\n          attestedGraphId: origin.graphId,\n        },\n      },\n    );\n  }\n  const graphHash = await getGraphDefinitionHash(graph);\n  if (graphHash !== origin.definitionHash) {\n    throw new BranchError(\n      `The supplied graph definition is incompatible with the durable working copy's host-attested fork-time definition: it hashes differently, so it is a different graph definition even though it reuses graph id \"${graph.id}\". This identity check is attested independently of any committed schema anchor, so it also protects an unmanaged working copy.`,\n      {\n        details: {\n          graphId: graph.id,\n          attestedDefinitionHash: origin.definitionHash,\n          graphHash,\n        },\n      },\n    );\n  }\n}\n\n/**\n * Reconstructs the ordinary {@link GraphBranch} view of a reattached store: the\n * descriptor's TypeGraph-owned fences plus a fresh coalesced close over the\n * store. `schemaAnchor` is always present, matching `branch()`.\n */\nfunction rebuildBranch<G extends GraphDef>(\n  store: Store<G>,\n  access: DurableWorkingCopyAccess,\n  descriptor: DurableBranchDescriptor<DurableStoreDescriptor>,\n): GraphBranch<G> {\n  return {\n    id: descriptor.branchId,\n    base: descriptor.base,\n    store,\n    close: coalescedDurableClose(store, access),\n    schemaAnchor: descriptor.schemaAnchor,\n    ...(descriptor.forkRevision === undefined ?\n      {}\n    : { forkRevision: descriptor.forkRevision }),\n  };\n}\n\n/**\n * Releases the opened backend and then its host-wide writer lease, once.\n *\n * The backend closes first so no live connection survives after the exclusive\n * lease becomes available to another process. Each completed phase is retained\n * across retries: if lease release fails, the next `close()` retries only that\n * release and never calls a non-idempotent backend `close()` twice.\n */\nfunction coalescedDurableClose<G extends GraphDef>(\n  store: Store<G>,\n  access: DurableWorkingCopyAccess,\n): () => Promise<void> {\n  const closeBackend = coalescedWorkingCopyClose(store);\n  let complete = false;\n  let accessReleased = false;\n  let inFlight: Promise<void> | undefined;\n  return async () => {\n    if (complete) return;\n    inFlight ??= (async () => {\n      await closeBackend();\n      if (access.kind === \"exclusive\" && !accessReleased) {\n        await access.release();\n        accessReleased = true;\n      }\n      complete = true;\n    })().finally(() => {\n      inFlight = undefined;\n    });\n    await inFlight;\n  };\n}\n\n/**\n * Releases a store's backend, swallowing a close failure so it cannot mask the\n * refusal being returned. The store belongs to this function on every failure\n * path inside `reopenDurableBranch` and `abandonAllocation`.\n */\nasync function closeDurableQuietly<G extends GraphDef>(\n  store: Store<G>,\n  access: DurableWorkingCopyAccess,\n): Promise<void> {\n  try {\n    await coalescedDurableClose(store, access)();\n  } catch {\n    // Intentionally ignored — surface the original refusal.\n  }\n}\n","/**\n * Applies an approved merge plan through an optional host-native merge command,\n * with the ordinary portable applier as the complete fallback.\n *\n * The native command is an optimization attempt, never a second source of merge\n * semantics. TypeGraph validates the serialized plan and durable envelope first.\n * The strategy may return `applied` only after atomically proving and honoring\n * every dimension in `DurableWorkingCopyStrategy.merge`; `unsupported` means it\n * executed no host mutation, so the full portable plan is safe to run.\n */\n\nimport type { MergePlanApplyOptions } from \"./apply-callbacks\";\nimport type {\n  DurableBranchDescriptor,\n  DurableStoreDescriptor,\n  DurableWorkingCopyStrategy,\n  NativeDurableMergeResult,\n} from \"./durable-branch\";\nimport {\n  durableDescriptorRefusal,\n  durableOriginOfDescriptor,\n  durableOriginsEqual,\n} from \"./durable-branch\";\nimport { describeCause, MergeError } from \"./errors\";\nimport {\n  applyMergePlan,\n  reportFromArtifact,\n  validateMergePlanForTarget,\n} from \"./merge\";\nimport type { MergePlanArtifact, MergePlanArtifactV1 } from \"./plan-schema\";\nimport type { Result } from \"./result\";\nimport { err, ok } from \"./result\";\nimport type { GraphDef, Store } from \"./typegraph-internal\";\nimport { getGraphDefinitionHash } from \"./typegraph-internal\";\nimport type { GraphBranch, MergeReport } from \"./types\";\n\n/** Arguments for {@link applyDurableMergePlan}. */\nexport type ApplyDurableMergePlanArgs<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n> = Readonly<{\n  target: Store<G>;\n  branch: GraphBranch<G>;\n  descriptor: DurableBranchDescriptor<TStoreDescriptor>;\n  strategy: DurableWorkingCopyStrategy<G, TStoreDescriptor>;\n  plan: MergePlanArtifact;\n  options?: MergePlanApplyOptions<NoInfer<G>> | undefined;\n}>;\n\n/**\n * Applies an approved durable-branch plan, preferring a proven-equivalent\n * host-native merge and otherwise using {@link applyMergePlan} unchanged.\n *\n * Native merge is deliberately skipped when callbacks or persisted provenance\n * are requested. Those dimensions belong to TypeGraph's transaction and\n * sidecar owners; a raw database branch merge cannot silently drop them.\n */\nexport async function applyDurableMergePlan<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n>(\n  args: ApplyDurableMergePlanArgs<G, TStoreDescriptor>,\n): Promise<Result<MergeReport<G>, MergeError>> {\n  const { branch, descriptor, plan, strategy, target } = args;\n  const options = args.options ?? {};\n  const refusal = durableDescriptorRefusal(descriptor, strategy);\n  if (refusal !== undefined) {\n    return err(\n      new MergeError(\"Durable merge descriptor validation failed.\", {\n        cause: refusal,\n      }),\n    );\n  }\n\n  let artifact: MergePlanArtifactV1;\n  const descriptorOrigin = durableOriginOfDescriptor(descriptor);\n  try {\n    artifact = await validateMergePlanForTarget(target, plan);\n    const branchOrigin = {\n      graphId: branch.store.graphId,\n      definitionHash: await getGraphDefinitionHash(branch.store.graph),\n      branchId: branch.id,\n      base: branch.base,\n      schemaAnchor: branch.schemaAnchor,\n      forkRevision: branch.forkRevision,\n    };\n    if (!durableOriginsEqual(branchOrigin, descriptorOrigin)) {\n      throw new MergeError(\n        \"The durable branch handle does not match the descriptor supplied for native merge.\",\n        {\n          details: {\n            branchOrigin,\n            descriptorOrigin,\n          },\n        },\n      );\n    }\n  } catch (error) {\n    return err(\n      error instanceof MergeError ? error : (\n        new MergeError(\n          `Durable merge validation failed: ${describeCause(error)}`,\n          { cause: error },\n        )\n      ),\n    );\n  }\n\n  const usePortableApply = (): Promise<Result<MergeReport<G>, MergeError>> =>\n    applyMergePlan(target, artifact, options);\n  const hasCallbacks =\n    options.beforeApply !== undefined || options.afterApply !== undefined;\n  if (\n    strategy.merge === undefined ||\n    hasCallbacks ||\n    artifact.provenance.persist\n  ) {\n    return usePortableApply();\n  }\n\n  let nativeResult: NativeDurableMergeResult;\n  try {\n    nativeResult = await strategy.merge({\n      target,\n      branch,\n      descriptor: descriptor.store,\n      expectedOrigin: descriptorOrigin,\n      plan: artifact,\n    });\n  } catch (error) {\n    return err(\n      new MergeError(\n        `Host-native durable merge failed: ${describeCause(error)}`,\n        {\n          cause: error,\n          suggestion:\n            \"Inspect the host-native merge state before retrying. TypeGraph does not run the portable fallback after an uncertain or failed native attempt because the host may have applied a partial change.\",\n        },\n      ),\n    );\n  }\n  if (nativeResult.outcome === \"unsupported\") return usePortableApply();\n  return ok(\n    reportFromArtifact(artifact, nativeResult.merged, [\n      ...artifact.review.warnings,\n      ...(nativeResult.warnings ?? []),\n    ]),\n  );\n}\n","/**\n * Durable-branch operations: a generic, backend-neutral facility for a durable\n * host to combine an opaque graph mutation with immutable operation evidence in\n * ONE host transaction.\n *\n * The facility is deliberately the same shape as the optional host-native merge\n * command ({@link import(\"./durable-merge\").applyDurableMergePlan}): TypeGraph\n * owns descriptor validation, sealed-origin attestation, request\n * canonicalization, and evidence validation; the host owns the database\n * mechanics. A strategy that cannot combine the mutation and its evidence in a\n * single atomic unit returns `unsupported` BEFORE touching the host, and\n * TypeGraph refuses rather than emulating atomicity with callbacks or best\n * effort.\n *\n * WHAT IS OPAQUE. Both `metadata` and `mutation` are JSON-safe host values.\n * TypeGraph never interprets their application fields; it canonicalizes them to\n * derive {@link DurableBranchOperation.operationDigest} and otherwise carries\n * them through untouched. `metadata` is retained as evidence; `mutation` is the\n * host's own description of the graph change it must apply (for example a\n * serialized statement or a host-defined command) atomically with the evidence\n * row.\n *\n * IDEMPOTENCY. The digest is derived from the complete request content\n * (`mutation` plus `metadata`) with the repository's canonical JSON serializer.\n * The strategy is handed the digest and MUST treat `(idempotencyKey)` as the\n * unique key: identical key AND digest returns the previously committed\n * evidence without re-applying; identical key with a different digest fails\n * with {@link DurableOperationConflictError} and mutates nothing.\n *\n * DELIVERY AND DESTRUCTION. Evidence is delivered explicitly via\n * {@link markDurableOperationDelivered}. Archive/destroy is fenced on\n * undelivered evidence: a strategy MUST refuse destruction while undelivered\n * evidence remains, and the refusal is preserved through\n * {@link import(\"./durable-branch\").destroyDurableBranch} as a\n * {@link DurableEvidenceUndeliveredError}. Concurrent `operate` and `destroy`\n * are serialized by the host's own transaction: either the operation commits\n * first (destroy observes undelivered evidence and refuses) or destroy commits\n * first (the operation fails against the removed allocation). No partial state\n * is ever observable.\n *\n * CURSORS. {@link scanDurableOperations} returns evidence in a stable total\n * order the strategy defines (commit order, ties broken deterministically).\n * `cursor` is an opaque continuation token; pass it back as `after` to resume.\n * A missing `cursor` means the scan reached the end.\n */\n\nimport { assertJsonValue } from \"../core/json-value\";\nimport { canonicalValueKey } from \"./canonical-props\";\nimport type {\n  DurableBranchDescriptor,\n  DurableBranchOrigin,\n  DurableStoreDescriptor,\n  DurableWorkingCopyStrategy,\n} from \"./durable-branch\";\nimport {\n  durableDescriptorRefusal,\n  durableOriginOfDescriptor,\n} from \"./durable-branch\";\nimport {\n  describeCause,\n  DurableOperationError,\n  DurableOperationEvidenceError,\n  DurableOperationRequestError,\n  DurableOperationUnsupportedError,\n} from \"./errors\";\nimport type { Result } from \"./result\";\nimport { err, isErr, ok } from \"./result\";\nimport type { EngineRevision, GraphDef, JsonValue } from \"./typegraph-internal\";\nimport { sha256Hex } from \"./typegraph-internal\";\nimport type { BaseVersion } from \"./types\";\n\n/** Default page size for {@link scanDurableOperations}. */\nexport const DURABLE_OPERATION_SCAN_DEFAULT_LIMIT = 100;\n\n/** Largest page a single {@link scanDurableOperations} call may request. */\nexport const DURABLE_OPERATION_SCAN_MAX_LIMIT = 1000;\n\n/** Bytes of the SHA-256 operation digest (128 bits). */\nconst OPERATION_DIGEST_BYTE_LENGTH = 16;\n\n/**\n * The dimensions whose absence a strategy reports through the `unsupported`\n * outcome. Each names a guarantee TypeGraph will not fake.\n */\nexport type DurableOperationUnsupportedDimension =\n  \"atomicMutation\" | \"evidenceStore\" | \"host\";\n\n/**\n * The caller's operation request. `idempotencyKey` identifies the operation;\n * `mutation` is the host's opaque, JSON-safe description of the graph change;\n * `metadata` is opaque, JSON-safe host evidence TypeGraph never interprets.\n */\nexport type DurableBranchOperationRequest = Readonly<{\n  idempotencyKey: string;\n  metadata: JsonValue;\n  mutation: JsonValue;\n}>;\n\n/**\n * The canonical operation handed to the strategy: the request plus the\n * TypeGraph-derived digest the strategy must use for idempotency.\n */\nexport type DurableBranchOperation = Readonly<{\n  idempotencyKey: string;\n  operationDigest: string;\n  metadata: JsonValue;\n  mutation: JsonValue;\n}>;\n\n/**\n * A branch's content coordinates at one point. `base` is the\n * merge-visible base-version fingerprint (as produced by\n * `computeBaseVersion`); `revision` is the engine revision when the working\n * copy resolves lineage.\n */\nexport type DurableBranchCoordinates = Readonly<{\n  base: BaseVersion;\n  revision?: EngineRevision | undefined;\n}>;\n\n/**\n * Immutable evidence of one committed operation. `delivered` is the only\n * mutating dimension, and it moves in one direction (`false` → `true`) under\n * {@link DurableOperationCapability.markDelivered}. A newly `applied`\n * operation must return `false`; an exact `replayed` operation returns its\n * current committed delivery state.\n */\nexport type DurableBranchOperationEvidence = Readonly<{\n  idempotencyKey: string;\n  operationDigest: string;\n  metadata: JsonValue;\n  mutation: JsonValue;\n  before: DurableBranchCoordinates;\n  after: DurableBranchCoordinates;\n  delivered: boolean;\n}>;\n\n/** One stable-order page of evidence returned by {@link scanDurableOperations}. */\nexport type DurableOperationScan = Readonly<{\n  operations: readonly DurableBranchOperationEvidence[];\n  /** Opaque continuation token; absent when the scan reached the end. */\n  cursor?: string | undefined;\n}>;\n\n/** Outcome of an atomic operation attempt. */\nexport type DurableOperationOutcome =\n  | Readonly<{\n      outcome: \"applied\" | \"replayed\";\n      evidence: DurableBranchOperationEvidence;\n    }>\n  | Readonly<{\n      outcome: \"unsupported\";\n      dimensions: readonly [\n        DurableOperationUnsupportedDimension,\n        ...DurableOperationUnsupportedDimension[],\n      ];\n    }>;\n\n/**\n * The optional host capability behind `DurableWorkingCopyStrategy.operations`.\n *\n * Every member receives the opaque locator AND the caller's expected origin, so\n * the host attests the sealed origin exactly as it does for reopen, destroy,\n * and native merge. TypeGraph validates the descriptor before any member is\n * called.\n */\nexport type DurableOperationCapability<\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n> = Readonly<{\n  /**\n   * Atomically applies `request.mutation` and records evidence, or returns\n   * `unsupported` having executed no host SQL or mutation.\n   *\n   * The host MUST:\n   *   1. attest `expectedOrigin` against the allocation `descriptor` names;\n   *   2. return the previously committed evidence unchanged when\n   *      `(idempotencyKey, operationDigest)` matches a committed operation,\n   *      applying nothing;\n   *   3. refuse with {@link DurableOperationConflictError} when the key exists\n   *      with a different digest, applying nothing; and\n   *   4. otherwise apply the mutation and undelivered evidence in ONE\n   *      transaction, returning `outcome: \"applied\"` with `delivered: false`.\n   */\n  operate: (\n    args: Readonly<{\n      descriptor: TStoreDescriptor;\n      expectedOrigin: DurableBranchOrigin;\n      request: DurableBranchOperation;\n    }>,\n  ) => Promise<DurableOperationOutcome>;\n  /** Reads one operation's evidence, or `undefined` when never committed. */\n  get: (\n    args: Readonly<{\n      descriptor: TStoreDescriptor;\n      expectedOrigin: DurableBranchOrigin;\n      idempotencyKey: string;\n    }>,\n  ) => Promise<DurableBranchOperationEvidence | undefined>;\n  /**\n   * Reads evidence in the strategy's stable total order. `after` resumes from\n   * a previous page's `cursor`; `limit` bounds the page.\n   */\n  scan: (\n    args: Readonly<{\n      descriptor: TStoreDescriptor;\n      expectedOrigin: DurableBranchOrigin;\n      after?: string | undefined;\n      limit: number;\n    }>,\n  ) => Promise<DurableOperationScan>;\n  /**\n   * Marks one operation delivered. MUST be idempotent: marking an\n   * already-delivered operation returns the same evidence and writes nothing.\n   * Returns `undefined` when the operation does not exist.\n   */\n  markDelivered: (\n    args: Readonly<{\n      descriptor: TStoreDescriptor;\n      expectedOrigin: DurableBranchOrigin;\n      idempotencyKey: string;\n    }>,\n  ) => Promise<DurableBranchOperationEvidence | undefined>;\n  /** Whether any committed evidence is still undelivered. */\n  hasUndelivered: (\n    args: Readonly<{\n      descriptor: TStoreDescriptor;\n      expectedOrigin: DurableBranchOrigin;\n    }>,\n  ) => Promise<boolean>;\n}>;\n\n/**\n * Derives the operation digest from its canonical content. The digest covers\n * the complete request except the idempotency key, so reusing a key with a\n * different mutation OR different metadata conflicts.\n */\nexport async function computeDurableOperationDigest(\n  request: DurableBranchOperationRequest,\n): Promise<string> {\n  const canonical = canonicalValueKey({\n    metadata: request.metadata,\n    mutation: request.mutation,\n  });\n  return sha256Hex(canonical, OPERATION_DIGEST_BYTE_LENGTH);\n}\n\n/** The capability fields the public orchestrators require. */\ntype OperationStrategy<TStoreDescriptor extends DurableStoreDescriptor> =\n  Readonly<{\n    type: string;\n    version: number;\n    operations?: DurableOperationCapability<TStoreDescriptor> | undefined;\n  }>;\n\nfunction requireDescriptorOwner<\n  TStoreDescriptor extends DurableStoreDescriptor,\n>(\n  descriptor: DurableBranchDescriptor<TStoreDescriptor>,\n  strategy: OperationStrategy<TStoreDescriptor>,\n):\n  | Readonly<{ ok: true; origin: DurableBranchOrigin }>\n  | Readonly<{ ok: false; error: DurableOperationRequestError }> {\n  const refusal = durableDescriptorRefusal(descriptor, strategy);\n  if (refusal !== undefined) {\n    return {\n      ok: false,\n      error: new DurableOperationRequestError(\n        \"Durable operation descriptor validation failed.\",\n        { cause: refusal },\n      ),\n    };\n  }\n  return { ok: true, origin: durableOriginOfDescriptor(descriptor) };\n}\n\n/** Validates JSON safety and shape of a caller-supplied operation request. */\nasync function normalizeOperationRequest(\n  request: DurableBranchOperationRequest,\n): Promise<Result<DurableBranchOperation, DurableOperationRequestError>> {\n  const rawRequest: unknown = request;\n  if (\n    typeof rawRequest !== \"object\" ||\n    rawRequest === null ||\n    Array.isArray(rawRequest)\n  ) {\n    return err(\n      new DurableOperationRequestError(\n        \"Durable operation request must be a JSON object.\",\n      ),\n    );\n  }\n  if (\n    typeof request.idempotencyKey !== \"string\" ||\n    request.idempotencyKey.length === 0\n  ) {\n    return err(\n      new DurableOperationRequestError(\n        \"Durable operation request is malformed: idempotencyKey must be a non-empty string.\",\n        { details: { idempotencyKey: request.idempotencyKey } },\n      ),\n    );\n  }\n  try {\n    assertJsonValue(request.metadata, \"metadata\", \"Durable operation\");\n    assertJsonValue(request.mutation, \"mutation\", \"Durable operation\");\n  } catch (error) {\n    return err(\n      new DurableOperationRequestError(\n        `Durable operation request is not JSON-safe: ${describeCause(error)}`,\n        { cause: error, details: { idempotencyKey: request.idempotencyKey } },\n      ),\n    );\n  }\n  return ok({\n    idempotencyKey: request.idempotencyKey,\n    metadata: request.metadata,\n    mutation: request.mutation,\n    operationDigest: await computeDurableOperationDigest(request),\n  });\n}\n\n/**\n * Validates that evidence returned by a host is structurally sound and\n * consistent with the operation that produced it. A host cannot forge a\n * different digest, echo a different request, or return non-JSON metadata.\n */\nasync function normalizeStoredEvidence(\n  evidence: unknown,\n  expectedIdempotencyKey?: string,\n): Promise<\n  Result<DurableBranchOperationEvidence, DurableOperationEvidenceError>\n> {\n  if (\n    typeof evidence !== \"object\" ||\n    evidence === null ||\n    Array.isArray(evidence)\n  ) {\n    return err(\n      new DurableOperationEvidenceError(\n        \"Durable operation evidence must be a JSON object.\",\n        { details: { idempotencyKey: expectedIdempotencyKey } },\n      ),\n    );\n  }\n  const record = evidence as Readonly<Record<string, unknown>>;\n  if (\n    typeof record[\"idempotencyKey\"] !== \"string\" ||\n    record[\"idempotencyKey\"].length === 0\n  ) {\n    return err(\n      new DurableOperationEvidenceError(\n        \"Durable operation evidence needs a non-empty idempotency key.\",\n        { details: { expectedKey: expectedIdempotencyKey } },\n      ),\n    );\n  }\n  if (\n    expectedIdempotencyKey !== undefined &&\n    record[\"idempotencyKey\"] !== expectedIdempotencyKey\n  ) {\n    return err(\n      new DurableOperationEvidenceError(\n        \"Durable operation evidence does not carry the requested idempotency key.\",\n        {\n          details: {\n            expectedKey: expectedIdempotencyKey,\n            receivedKey: record[\"idempotencyKey\"],\n          },\n        },\n      ),\n    );\n  }\n  if (\n    typeof record[\"operationDigest\"] !== \"string\" ||\n    record[\"operationDigest\"].length === 0\n  ) {\n    return err(\n      new DurableOperationEvidenceError(\n        \"Durable operation evidence needs a non-empty operation digest.\",\n        { details: { idempotencyKey: record[\"idempotencyKey\"] } },\n      ),\n    );\n  }\n  try {\n    assertJsonValue(\n      record[\"metadata\"],\n      \"metadata\",\n      \"Durable operation evidence\",\n    );\n    assertJsonValue(\n      record[\"mutation\"],\n      \"mutation\",\n      \"Durable operation evidence\",\n    );\n  } catch (error) {\n    return err(\n      new DurableOperationEvidenceError(\n        `Durable operation evidence content is not JSON-safe: ${describeCause(error)}`,\n        { cause: error, details: { idempotencyKey: record[\"idempotencyKey\"] } },\n      ),\n    );\n  }\n  const refusal =\n    validateCoordinates(record[\"before\"], record, \"before\") ??\n    validateCoordinates(record[\"after\"], record, \"after\") ??\n    (typeof record[\"delivered\"] === \"boolean\" ?\n      undefined\n    : new DurableOperationEvidenceError(\n        \"Durable operation evidence is missing its delivered flag.\",\n        { details: { idempotencyKey: record[\"idempotencyKey\"] } },\n      ));\n  if (refusal !== undefined) return err(refusal);\n  const normalized = evidence as DurableBranchOperationEvidence;\n  const canonicalDigest = await computeDurableOperationDigest(normalized);\n  if (normalized.operationDigest !== canonicalDigest) {\n    return err(\n      new DurableOperationEvidenceError(\n        \"Durable operation evidence digest disagrees with its canonical content.\",\n        {\n          details: {\n            idempotencyKey: normalized.idempotencyKey,\n            expectedDigest: canonicalDigest,\n            receivedDigest: normalized.operationDigest,\n          },\n        },\n      ),\n    );\n  }\n  return ok(normalized);\n}\n\nasync function validateEvidenceForOperation(\n  evidence: unknown,\n  expected: DurableBranchOperation,\n): Promise<\n  Result<DurableBranchOperationEvidence, DurableOperationEvidenceError>\n> {\n  const normalized = await normalizeStoredEvidence(\n    evidence,\n    expected.idempotencyKey,\n  );\n  if (isErr(normalized)) return normalized;\n  if (normalized.data.operationDigest !== expected.operationDigest) {\n    return err(\n      new DurableOperationEvidenceError(\n        \"Durable operation evidence digest disagrees with the canonical request digest.\",\n        {\n          details: {\n            idempotencyKey: expected.idempotencyKey,\n            expectedDigest: expected.operationDigest,\n            receivedDigest: normalized.data.operationDigest,\n          },\n        },\n      ),\n    );\n  }\n  if (\n    canonicalValueKey(normalized.data.metadata) !==\n      canonicalValueKey(expected.metadata) ||\n    canonicalValueKey(normalized.data.mutation) !==\n      canonicalValueKey(expected.mutation)\n  ) {\n    return err(\n      new DurableOperationEvidenceError(\n        \"Durable operation evidence does not echo the canonical request content.\",\n        { details: { idempotencyKey: expected.idempotencyKey } },\n      ),\n    );\n  }\n  return normalized;\n}\n\nconst DURABLE_OPERATION_UNSUPPORTED_DIMENSIONS =\n  new Set<DurableOperationUnsupportedDimension>([\n    \"atomicMutation\",\n    \"evidenceStore\",\n    \"host\",\n  ]);\n\nfunction isDurableOperationUnsupportedDimension(\n  value: unknown,\n): value is DurableOperationUnsupportedDimension {\n  return (\n    typeof value === \"string\" &&\n    DURABLE_OPERATION_UNSUPPORTED_DIMENSIONS.has(\n      value as DurableOperationUnsupportedDimension,\n    )\n  );\n}\n\n/** Validates the complete result envelope returned by a host operation. */\nasync function normalizeOperationOutcome(\n  outcome: unknown,\n  expected: DurableBranchOperation,\n): Promise<Result<DurableOperationOutcome, DurableOperationEvidenceError>> {\n  if (\n    typeof outcome !== \"object\" ||\n    outcome === null ||\n    Array.isArray(outcome)\n  ) {\n    return err(\n      new DurableOperationEvidenceError(\n        \"Durable operation host returned a malformed outcome envelope.\",\n        { details: { idempotencyKey: expected.idempotencyKey } },\n      ),\n    );\n  }\n\n  const record = outcome as Readonly<Record<string, unknown>>;\n  const outcomeKind = record[\"outcome\"];\n  if (outcomeKind === \"unsupported\") {\n    const dimensions = record[\"dimensions\"];\n    const normalizedDimensions =\n      Array.isArray(dimensions) ?\n        dimensions.filter((dimension) =>\n          isDurableOperationUnsupportedDimension(dimension),\n        )\n      : [];\n    const [firstDimension, ...remainingDimensions] = normalizedDimensions;\n    if (\n      !Array.isArray(dimensions) ||\n      firstDimension === undefined ||\n      normalizedDimensions.length !== dimensions.length ||\n      new Set(normalizedDimensions).size !== normalizedDimensions.length\n    ) {\n      return err(\n        new DurableOperationEvidenceError(\n          \"Durable operation host returned malformed unsupported dimensions.\",\n          { details: { idempotencyKey: expected.idempotencyKey } },\n        ),\n      );\n    }\n    return ok({\n      outcome: \"unsupported\",\n      dimensions: [firstDimension, ...remainingDimensions],\n    });\n  }\n\n  if (outcomeKind !== \"applied\" && outcomeKind !== \"replayed\") {\n    return err(\n      new DurableOperationEvidenceError(\n        \"Durable operation host returned an unknown outcome.\",\n        {\n          details: {\n            idempotencyKey: expected.idempotencyKey,\n            outcome: outcomeKind,\n          },\n        },\n      ),\n    );\n  }\n\n  const evidence = await validateEvidenceForOperation(\n    record[\"evidence\"],\n    expected,\n  );\n  if (isErr(evidence)) return evidence;\n  if (outcomeKind === \"applied\" && evidence.data.delivered) {\n    return err(\n      new DurableOperationEvidenceError(\n        \"Newly applied durable operation evidence must be undelivered.\",\n        { details: { idempotencyKey: expected.idempotencyKey } },\n      ),\n    );\n  }\n  return ok({ outcome: outcomeKind, evidence: evidence.data });\n}\n\nfunction validateCoordinates(\n  coordinates: unknown,\n  evidence: Readonly<Record<string, unknown>>,\n  side: \"before\" | \"after\",\n): DurableOperationEvidenceError | undefined {\n  const idempotencyKey = evidence[\"idempotencyKey\"];\n  if (\n    typeof coordinates !== \"object\" ||\n    coordinates === null ||\n    Array.isArray(coordinates)\n  ) {\n    return new DurableOperationEvidenceError(\n      `Durable operation evidence ${side} coordinates are malformed.`,\n      { details: { idempotencyKey, side } },\n    );\n  }\n  const record = coordinates as Readonly<Record<string, unknown>>;\n  if (typeof record[\"base\"] !== \"string\" || record[\"base\"].length === 0) {\n    return new DurableOperationEvidenceError(\n      `Durable operation evidence ${side} coordinates need a non-empty base.`,\n      { details: { idempotencyKey, side } },\n    );\n  }\n  if (\n    record[\"revision\"] !== undefined &&\n    (typeof record[\"revision\"] !== \"string\" || record[\"revision\"].length === 0)\n  ) {\n    return new DurableOperationEvidenceError(\n      `Durable operation evidence ${side} coordinates revision must be a non-empty string.`,\n      { details: { idempotencyKey, side } },\n    );\n  }\n  return undefined;\n}\n\nfunction unsupportedError(\n  member: string,\n  strategyType: string,\n): DurableOperationUnsupportedError {\n  return new DurableOperationUnsupportedError(\n    `Durable strategy \"${strategyType}\" does not provide the \"${member}\" operation capability.`,\n    {\n      details: { strategyType, member },\n      suggestion:\n        \"Use a strategy whose `operations` capability provides atomic mutation-plus-evidence and evidence access; TypeGraph never emulates the atomic guarantee.\",\n    },\n  );\n}\n\n/**\n * Atomically applies an opaque graph mutation and commits its evidence through\n * the strategy's optional `operations.operate` capability.\n *\n * Descriptor format/type/version validation and the sealed-origin attestation\n * are exactly those of reopen, destroy, and native merge: TypeGraph validates\n * the envelope and hands the caller's expected origin to the host, which\n * attests it inside its own transaction. A strategy without the capability\n * yields the `unsupported` outcome with no host call.\n */\nexport async function operateDurableBranch<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n>(\n  descriptor: DurableBranchDescriptor<TStoreDescriptor>,\n  strategy: DurableWorkingCopyStrategy<G, TStoreDescriptor>,\n  request: DurableBranchOperationRequest,\n): Promise<Result<DurableOperationOutcome, DurableOperationError>> {\n  const owner = requireDescriptorOwner(descriptor, strategy);\n  if (!owner.ok) return err(owner.error);\n  const normalized = await normalizeOperationRequest(request);\n  if (isErr(normalized)) return normalized;\n\n  if (strategy.operations === undefined) {\n    return ok({\n      outcome: \"unsupported\",\n      dimensions: [\"atomicMutation\"],\n    });\n  }\n\n  try {\n    const outcome: unknown = await strategy.operations.operate({\n      descriptor: descriptor.store,\n      expectedOrigin: owner.origin,\n      request: normalized.data,\n    });\n    return await normalizeOperationOutcome(outcome, normalized.data);\n  } catch (error) {\n    return err(\n      error instanceof DurableOperationError ? error : (\n        new DurableOperationError(\n          `Durable operation failed: ${describeCause(error)}`,\n          {\n            cause: error,\n            details: { idempotencyKey: request.idempotencyKey },\n          },\n        )\n      ),\n    );\n  }\n}\n\n/**\n * Reads one operation's evidence. Returns `undefined` when the operation was\n * never committed. A strategy without evidence access is an explicit typed\n * refusal.\n */\nexport async function getDurableOperation<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n>(\n  descriptor: DurableBranchDescriptor<TStoreDescriptor>,\n  strategy: DurableWorkingCopyStrategy<G, TStoreDescriptor>,\n  idempotencyKey: string,\n): Promise<\n  Result<DurableBranchOperationEvidence | undefined, DurableOperationError>\n> {\n  const owner = requireDescriptorOwner(descriptor, strategy);\n  if (!owner.ok) return err(owner.error);\n  if (strategy.operations === undefined) {\n    return err(unsupportedError(\"get\", strategy.type));\n  }\n  try {\n    const evidence = await strategy.operations.get({\n      descriptor: descriptor.store,\n      expectedOrigin: owner.origin,\n      idempotencyKey,\n    });\n    if (evidence === undefined) return ok(undefined);\n    return await normalizeStoredEvidence(evidence, idempotencyKey);\n  } catch (error) {\n    return err(\n      error instanceof DurableOperationError ? error : (\n        new DurableOperationError(\n          `Failed to read durable operation \"${idempotencyKey}\": ${describeCause(error)}`,\n          { cause: error, details: { idempotencyKey } },\n        )\n      ),\n    );\n  }\n}\n\n/**\n * Reads evidence in a stable order. `after` resumes from a previous page's\n * `cursor`; `limit` defaults to {@link DURABLE_OPERATION_SCAN_DEFAULT_LIMIT}\n * and may not exceed {@link DURABLE_OPERATION_SCAN_MAX_LIMIT}. The returned\n * `cursor` is absent at the end of the scan.\n */\nexport async function scanDurableOperations<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n>(\n  descriptor: DurableBranchDescriptor<TStoreDescriptor>,\n  strategy: DurableWorkingCopyStrategy<G, TStoreDescriptor>,\n  options: Readonly<{\n    after?: string | undefined;\n    limit?: number | undefined;\n  }> = {},\n): Promise<Result<DurableOperationScan, DurableOperationError>> {\n  const owner = requireDescriptorOwner(descriptor, strategy);\n  if (!owner.ok) return err(owner.error);\n  const limit = options.limit ?? DURABLE_OPERATION_SCAN_DEFAULT_LIMIT;\n  if (!Number.isInteger(limit) || limit < 1) {\n    return err(\n      new DurableOperationRequestError(\n        \"Durable operation scan limit must be a positive integer.\",\n        { details: { limit } },\n      ),\n    );\n  }\n  if (limit > DURABLE_OPERATION_SCAN_MAX_LIMIT) {\n    return err(\n      new DurableOperationRequestError(\n        `Durable operation scan limit ${limit} exceeds the maximum of ${DURABLE_OPERATION_SCAN_MAX_LIMIT}.`,\n        {\n          details: { limit, max: DURABLE_OPERATION_SCAN_MAX_LIMIT },\n          suggestion: `Request at most ${DURABLE_OPERATION_SCAN_MAX_LIMIT} operations per page and page with the returned cursor.`,\n        },\n      ),\n    );\n  }\n  if (strategy.operations === undefined) {\n    return err(unsupportedError(\"scan\", strategy.type));\n  }\n  try {\n    const rawPage: unknown = await strategy.operations.scan({\n      descriptor: descriptor.store,\n      expectedOrigin: owner.origin,\n      after: options.after,\n      limit,\n    });\n    if (\n      typeof rawPage !== \"object\" ||\n      rawPage === null ||\n      Array.isArray(rawPage)\n    ) {\n      return err(\n        new DurableOperationEvidenceError(\n          \"Durable operation scan returned a malformed page.\",\n          { details: { limit } },\n        ),\n      );\n    }\n    const page = rawPage as Readonly<Record<string, unknown>>;\n    const rawOperations = page[\"operations\"];\n    const cursor = page[\"cursor\"];\n    if (\n      !Array.isArray(rawOperations) ||\n      rawOperations.length > limit ||\n      (cursor !== undefined &&\n        (typeof cursor !== \"string\" || cursor.length === 0))\n    ) {\n      return err(\n        new DurableOperationEvidenceError(\n          \"Durable operation scan returned a malformed page.\",\n          { details: { limit } },\n        ),\n      );\n    }\n    const operations: DurableBranchOperationEvidence[] = [];\n    for (const evidence of rawOperations) {\n      const normalized = await normalizeStoredEvidence(evidence);\n      if (isErr(normalized)) return normalized;\n      operations.push(normalized.data);\n    }\n    return ok(\n      cursor === undefined ? { operations } : { operations, cursor: cursor },\n    );\n  } catch (error) {\n    return err(\n      error instanceof DurableOperationError ? error : (\n        new DurableOperationError(\n          `Failed to scan durable operations: ${describeCause(error)}`,\n          { cause: error, details: { limit } },\n        )\n      ),\n    );\n  }\n}\n\n/**\n * Marks one operation delivered, idempotently. Marking an already-delivered\n * operation returns the same evidence without writing. Returns `undefined` when\n * the operation does not exist.\n */\nexport async function markDurableOperationDelivered<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n>(\n  descriptor: DurableBranchDescriptor<TStoreDescriptor>,\n  strategy: DurableWorkingCopyStrategy<G, TStoreDescriptor>,\n  idempotencyKey: string,\n): Promise<\n  Result<DurableBranchOperationEvidence | undefined, DurableOperationError>\n> {\n  const owner = requireDescriptorOwner(descriptor, strategy);\n  if (!owner.ok) return err(owner.error);\n  if (strategy.operations === undefined) {\n    return err(unsupportedError(\"markDelivered\", strategy.type));\n  }\n  try {\n    const evidence = await strategy.operations.markDelivered({\n      descriptor: descriptor.store,\n      expectedOrigin: owner.origin,\n      idempotencyKey,\n    });\n    if (evidence === undefined) return ok(undefined);\n    const normalized = await normalizeStoredEvidence(evidence, idempotencyKey);\n    if (isErr(normalized)) return normalized;\n    if (!normalized.data.delivered) {\n      return err(\n        new DurableOperationEvidenceError(\n          \"Durable operation delivery marking returned undelivered evidence.\",\n          { details: { idempotencyKey } },\n        ),\n      );\n    }\n    return normalized;\n  } catch (error) {\n    return err(\n      error instanceof DurableOperationError ? error : (\n        new DurableOperationError(\n          `Failed to mark durable operation \"${idempotencyKey}\" delivered: ${describeCause(error)}`,\n          { cause: error, details: { idempotencyKey } },\n        )\n      ),\n    );\n  }\n}\n\n/**\n * Reports whether any committed evidence is still undelivered. Archive/destroy\n * must fence on this; the strategy enforces the fence atomically, this is the\n * queryable half.\n */\nexport async function durableBranchHasUndeliveredEvidence<\n  G extends GraphDef,\n  TStoreDescriptor extends DurableStoreDescriptor = DurableStoreDescriptor,\n>(\n  descriptor: DurableBranchDescriptor<TStoreDescriptor>,\n  strategy: DurableWorkingCopyStrategy<G, TStoreDescriptor>,\n): Promise<Result<boolean, DurableOperationError>> {\n  const owner = requireDescriptorOwner(descriptor, strategy);\n  if (!owner.ok) return err(owner.error);\n  if (strategy.operations === undefined) {\n    return err(unsupportedError(\"hasUndelivered\", strategy.type));\n  }\n  try {\n    const hasUndelivered: unknown = await strategy.operations.hasUndelivered({\n      descriptor: descriptor.store,\n      expectedOrigin: owner.origin,\n    });\n    return typeof hasUndelivered === \"boolean\" ?\n        ok(hasUndelivered)\n      : err(\n          new DurableOperationEvidenceError(\n            \"Durable operation undelivered query returned a non-boolean value.\",\n          ),\n        );\n  } catch (error) {\n    return err(\n      error instanceof DurableOperationError ? error : (\n        new DurableOperationError(\n          `Failed to query undelivered durable evidence: ${describeCause(error)}`,\n          { cause: error },\n        )\n      ),\n    );\n  }\n}\n","import type { GraphDef } from \"../core/define-graph\";\nimport type { EvolutionPlan } from \"../schema/evolution-plan\";\nimport type { Store } from \"../store/store\";\nimport { branch } from \"./branch\";\nimport { type BranchError, MergePlanCapabilityError } from \"./errors\";\nimport { evolutionPlanningTarget } from \"./evolution-target\";\nimport type { Result } from \"./result\";\nimport { err } from \"./result\";\nimport type { BranchOptions, GraphBranch } from \"./types\";\nimport type { MakeBackend } from \"./working-copy\";\n\n/**\n * Forks an isolated branch from an evolution plan's resulting graph, before\n * the caller opens its schema-write transaction. The original Store remains\n * pinned to its baseline; planMergeForEvolution checks its durable fence.\n */\nexport async function branchForEvolution<G extends GraphDef>(\n  store: Store<G>,\n  plan: EvolutionPlan,\n  makeBackend: MakeBackend,\n  options?: BranchOptions,\n): Promise<Result<GraphBranch<G>, BranchError | MergePlanCapabilityError>> {\n  try {\n    const candidate = evolutionPlanningTarget(store, plan);\n    const result = await branch(candidate, makeBackend, options);\n    return result;\n  } catch (error) {\n    if (error instanceof MergePlanCapabilityError) return err(error);\n    return err(\n      new MergePlanCapabilityError(\n        \"Could not fork a resulting-schema branch.\",\n        { cause: error, details: { capability: \"evolutionBranch\" } },\n      ),\n    );\n  }\n}\n"]}