@nicia-ai/typegraph 0.73.0 → 0.73.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/backend/postgres/pglite-store.cjs +1 -1
  3. package/dist/backend/postgres/pglite-store.js +1 -1
  4. package/dist/backend/postgres/working-copy.cjs +85 -85
  5. package/dist/backend/postgres/working-copy.js +4 -4
  6. package/dist/backend/sqlite/local-store.cjs +1 -1
  7. package/dist/backend/sqlite/local-store.js +1 -1
  8. package/dist/{chunk-7QQ3ICAZ.cjs → chunk-BZ5EXHZX.cjs} +11 -11
  9. package/dist/{chunk-7QQ3ICAZ.cjs.map → chunk-BZ5EXHZX.cjs.map} +1 -1
  10. package/dist/{chunk-ZN24TFVZ.cjs → chunk-GLDGT3L3.cjs} +6 -3
  11. package/dist/chunk-GLDGT3L3.cjs.map +1 -0
  12. package/dist/{chunk-ORTKLAAU.js → chunk-LJG2TYCN.js} +3 -3
  13. package/dist/{chunk-ORTKLAAU.js.map → chunk-LJG2TYCN.js.map} +1 -1
  14. package/dist/{chunk-VKMLQTXP.cjs → chunk-MPCF5XBW.cjs} +159 -159
  15. package/dist/{chunk-VKMLQTXP.cjs.map → chunk-MPCF5XBW.cjs.map} +1 -1
  16. package/dist/{chunk-5RTWCMBC.js → chunk-OA4PF2QI.js} +6 -3
  17. package/dist/chunk-OA4PF2QI.js.map +1 -0
  18. package/dist/{chunk-XGYVKBI5.cjs → chunk-P52FOZSI.cjs} +8 -8
  19. package/dist/{chunk-XGYVKBI5.cjs.map → chunk-P52FOZSI.cjs.map} +1 -1
  20. package/dist/{chunk-KI7VMCOG.cjs → chunk-QJGQ3FN2.cjs} +16 -16
  21. package/dist/{chunk-KI7VMCOG.cjs.map → chunk-QJGQ3FN2.cjs.map} +1 -1
  22. package/dist/{chunk-MSUUUG5B.js → chunk-TI2O2U4G.js} +4 -4
  23. package/dist/{chunk-MSUUUG5B.js.map → chunk-TI2O2U4G.js.map} +1 -1
  24. package/dist/{chunk-FC7INRDS.js → chunk-WX7BQELV.js} +4 -4
  25. package/dist/{chunk-FC7INRDS.js.map → chunk-WX7BQELV.js.map} +1 -1
  26. package/dist/{chunk-NMLLXBGF.js → chunk-XIFBU27X.js} +3 -3
  27. package/dist/{chunk-NMLLXBGF.js.map → chunk-XIFBU27X.js.map} +1 -1
  28. package/dist/graph-merge/index.cjs +531 -531
  29. package/dist/graph-merge/index.js +6 -6
  30. package/dist/index.cjs +43 -43
  31. package/dist/index.js +2 -2
  32. package/dist/interchange/index.cjs +26 -26
  33. package/dist/interchange/index.js +3 -3
  34. package/dist/{local-store-impl-ALYCG7CX.js → local-store-impl-HPNBERU4.js} +4 -4
  35. package/dist/{local-store-impl-ALYCG7CX.js.map → local-store-impl-HPNBERU4.js.map} +1 -1
  36. package/dist/{local-store-impl-2HTGPM6A.cjs → local-store-impl-WIVQ5HDM.cjs} +5 -5
  37. package/dist/{local-store-impl-2HTGPM6A.cjs.map → local-store-impl-WIVQ5HDM.cjs.map} +1 -1
  38. package/dist/{pglite-store-impl-F2WHYIM7.cjs → pglite-store-impl-IXKIXLH6.cjs} +5 -5
  39. package/dist/{pglite-store-impl-F2WHYIM7.cjs.map → pglite-store-impl-IXKIXLH6.cjs.map} +1 -1
  40. package/dist/{pglite-store-impl-3UUTJLGP.js → pglite-store-impl-U3TW3Z4C.js} +4 -4
  41. package/dist/{pglite-store-impl-3UUTJLGP.js.map → pglite-store-impl-U3TW3Z4C.js.map} +1 -1
  42. package/package.json +1 -1
  43. package/dist/chunk-5RTWCMBC.js.map +0 -1
  44. package/dist/chunk-ZN24TFVZ.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/graph-merge/errors.ts","../src/graph-merge/types.ts","../src/graph-merge/canonical-props.ts","../src/graph-merge/node-key.ts","../src/graph-merge/temporal-identity-closure.ts","../src/graph-merge/merge-identity.ts","../src/graph-merge/state-diff.ts","../src/graph-merge/base-version.ts","../src/graph-merge/working-copy.ts","../src/graph-merge/branch.ts","../src/graph-merge/durable-branch.ts"],"names":["branch"],"mappings":";;;;;;;;;;;;;;;;;AAgBO,IAAM,iBAAA,GAAoB;AAAA,EAC/B,KAAA,EAAO,mBAAA;AAAA,EACP,cAAA,EAAgB,6BAAA;AAAA,EAChB,MAAA,EAAQ,0BAAA;AAAA,EACR,qBAAA,EAAuB,oCAAA;AAAA,EACvB,QAAA,EAAU,sBAAA;AAAA,EACV,kBAAA,EAAoB,iCAAA;AAAA,EACpB,gBAAA,EAAkB,+BAAA;AAAA,EAClB,mBAAA,EAAqB,mCAAA;AAAA,EACrB,cAAA,EAAgB,6BAAA;AAAA,EAChB,WAAA,EAAa,0BAAA;AAAA,EACb,sBAAA,EAAwB,sCAAA;AAAA,EACxB,kBAAA,EAAoB,kCAAA;AAAA,EACpB,kBAAA,EAAoB,kCAAA;AAAA,EACpB,kBAAA,EAAoB,kCAAA;AAAA,EACpB,kBAAA,EAAoB,kCAAA;AAAA,EACpB,SAAA,EAAW,wBAAA;AAAA,EACX,aAAA,EAAe,4BAAA;AAAA,EACf,eAAA,EAAiB,8BAAA;AAAA,EACjB,QAAA,EAAU,sBAAA;AAAA,EACV,iBAAA,EAAmB,iCAAA;AAAA,EACnB,MAAA,EAAQ,oBAAA;AAAA,EACR,SAAA,EAAW,uBAAA;AAAA,EACX,gBAAA,EAAkB,+BAAA;AAAA,EAClB,iBAAA,EAAmB,gCAAA;AAAA,EACnB,oBAAA,EAAsB,mCAAA;AAAA,EACtB,iBAAA,EAAmB,gCAAA;AAAA,EACnB,oBAAA,EAAsB;AACxB;AAmBA,SAAS,uBAAA,CACP,UACA,OAAA,EACuB;AACvB,EAAA,OAAO;AAAA,IACL,QAAA;AAAA,IACA,GAAI,QAAQ,OAAA,KAAY,MAAA,GAAY,EAAC,GAAI,EAAE,OAAA,EAAS,OAAA,CAAQ,OAAA,EAAQ;AAAA,IACpE,GAAI,QAAQ,UAAA,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GAC9B,EAAC,GACD,EAAE,YAAA,EAAc,UAAA,CAAW,YAAA,EAAa;AAAA,IAC1C,GAAI,WAAW,iBAAA,KAAsB,MAAA,GACnC,EAAC,GACD,EAAE,iBAAA,EAAmB,UAAA,CAAW,iBAAA;AAAkB,GACtD;AACF;AAUA,SAAS,qBAAA,CACP,OACA,MAAA,EACqB;AACrB,EAAA,MAAM,YAAA,GAAe,0BAA0B,KAAK,CAAA;AACpD,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,IAAI,cAAA,GAAiB,KAAA;AACrB,EAAA,IAAI,QAAA;AACJ,EAAA,OAAO,YAAY;AACjB,IAAA,IAAI,QAAA,EAAU;AACd,IAAA,QAAA,KAAA,CAAc,YAAY;AACxB,MAAA,MAAM,YAAA,EAAa;AACnB,MAAA,IAAI,MAAA,CAAO,IAAA,KAAS,WAAA,IAAe,CAAC,cAAA,EAAgB;AAClD,QAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,QAAA,cAAA,GAAiB,IAAA;AAAA,MACnB;AACA,MAAA,QAAA,GAAW,IAAA;AAAA,IACb,CAAA,GAAG,CAAE,OAAA,CAAQ,MAAM;AACjB,MAAA,QAAA,GAAW,MAAA;AAAA,IACb,CAAC,CAAA;AACD,IAAA,MAAM,QAAA;AAAA,EACR,CAAA;AACF;AAOA,eAAe,mBAAA,CACb,OACA,MAAA,EACe;AACf,EAAA,IAAI;AACF,IAAA,MAAM,qBAAA,CAAsB,KAAA,EAAO,MAAM,CAAA,EAAE;AAAA,EAC7C,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"chunk-FC7INRDS.js","sourcesContent":["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 best effort or\n * with callbacks that run outside the evidence transaction (see\n * {@link DurableWorkingCopyStrategy.operations}).\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","/**\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 { RecordedInstant } from \"../core/temporal\";\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/** An attested source cut for a branch forked from a history-enabled graph. */\nexport type RecordedForkPoint = Readonly<{\n recorded: RecordedInstant;\n base: BaseVersion;\n}>;\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 * The source graph's recorded high-water mark at the fork cut, paired with\n * the base token captured from that same source state. Present only when\n * the source Store records history and had a captured write at fork time.\n */\n recordedForkPoint?: RecordedForkPoint;\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> | RecordedForkPoint;\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 * 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 { 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 hasScopedIdentityReads,\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 runtime = storeRuntime(target);\n if (hasScopedIdentityReads(runtime)) {\n return runtime.identityAssertionsTouchingAtTarget(\n backend,\n [...memberKeys].map((key) => ({ kind: kindOf(key), id: idOf(key) })),\n \"state\",\n );\n }\n // Older custom Store runtimes lack the scoped read. Preserve their original\n // full-ledger guard, using the same transaction target and endpoint filter.\n return (await runtime.identityAssertionsAtTarget(backend, \"state\")).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\";\nimport type { CandidateIdentityScope } from \"./candidate-identity-closure\";\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/** Raw ancestor reads used by the state diff, including tombstones and ended assertions. */\nexport type StateDiffBaseReader = Readonly<{\n readNodes: (\n kind: string,\n ids?: readonly string[],\n ) => Promise<readonly NodeRow[]>;\n readEdges: (\n kind: string,\n ids?: readonly string[],\n ) => Promise<readonly EdgeRow[]>;\n readIdentity: (\n mode: \"state\" | \"archival\",\n ) => Promise<readonly IdentityTransferAssertion[]>;\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/** Enumerate declared kinds in graph-wide pages when the backend supports it. */\nexport async function enumerateGraphNodes(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kinds: readonly string[],\n): Promise<ReadonlyMap<string, readonly NodeRow[]>> {\n const rowsByKind = new Map<string, NodeRow[]>();\n if (kinds.length === 0) return rowsByKind;\n const readPage = backend.findNodesAcrossKinds;\n if (readPage === undefined) {\n for (const kind of kinds) {\n rowsByKind.set(kind, [\n ...(await enumerateAllNodes(backend, graphId, kind)),\n ]);\n }\n return rowsByKind;\n }\n let after: Readonly<{ kind: string; id: string }> | undefined;\n for (;;) {\n const page = await readPage({\n graphId,\n kinds,\n limit: ENUMERATION_PAGE_SIZE,\n excludeDeleted: false,\n ...(after === undefined ? {} : { after }),\n });\n for (const row of page) {\n const rows = rowsByKind.get(row.kind) ?? [];\n rows.push(row);\n rowsByKind.set(row.kind, rows);\n }\n if (page.length < ENUMERATION_PAGE_SIZE) break;\n const last = requireDefined(page.at(-1));\n after = { kind: last.kind, id: last.id };\n }\n return rowsByKind;\n}\n\n/** Edge counterpart of {@link enumerateGraphNodes}. */\nexport async function enumerateGraphEdges(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kinds: readonly string[],\n): Promise<ReadonlyMap<string, readonly EdgeRow[]>> {\n const rowsByKind = new Map<string, EdgeRow[]>();\n if (kinds.length === 0) return rowsByKind;\n const readPage = backend.findEdgesAcrossKinds;\n if (readPage === undefined) {\n for (const kind of kinds) {\n rowsByKind.set(kind, [\n ...(await enumerateAllEdges(backend, graphId, kind)),\n ]);\n }\n return rowsByKind;\n }\n let after: Readonly<{ kind: string; id: string }> | undefined;\n for (;;) {\n const page = await readPage({\n graphId,\n kinds,\n limit: ENUMERATION_PAGE_SIZE,\n excludeDeleted: false,\n ...(after === undefined ? {} : { after }),\n });\n for (const row of page) {\n const rows = rowsByKind.get(row.kind) ?? [];\n rows.push(row);\n rowsByKind.set(row.kind, rows);\n }\n if (page.length < ENUMERATION_PAGE_SIZE) break;\n const last = requireDefined(page.at(-1));\n after = { kind: last.kind, id: last.id };\n }\n return rowsByKind;\n}\n\n/** Bound the rows retained by a graph-wide read while preserving kind order. */\nfunction createKindBatchReader<Row>(\n kinds: readonly string[],\n kindsPerBatch: number,\n enumerateBatch: (\n batchKinds: readonly string[],\n ) => Promise<ReadonlyMap<string, readonly Row[]>>,\n): (kind: string) => Promise<readonly Row[]> {\n let nextIndex = 0;\n let rowsByKind: ReadonlyMap<string, readonly Row[]> = new Map();\n return async (kind) => {\n if (kinds[nextIndex] !== kind) {\n throw new Error(\n \"Graph kind batches must be consumed in declaration order.\",\n );\n }\n if (nextIndex % kindsPerBatch === 0) {\n rowsByKind = await enumerateBatch(\n kinds.slice(nextIndex, nextIndex + kindsPerBatch),\n );\n }\n nextIndex++;\n return rowsByKind.get(kind) ?? [];\n };\n}\n\n/** A bounded set of kinds amortizes empty-kind round trips without a graph-sized buffer. */\nconst ENUMERATION_KINDS_PER_BATCH = 8;\n\nexport function createGraphNodeKindReader(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kinds: readonly string[],\n): (kind: string) => Promise<readonly NodeRow[]> {\n return createKindBatchReader(\n kinds,\n backend.findNodesAcrossKinds === undefined ?\n 1\n : ENUMERATION_KINDS_PER_BATCH,\n (batchKinds) => enumerateGraphNodes(backend, graphId, batchKinds),\n );\n}\n\nexport function createGraphEdgeKindReader(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kinds: readonly string[],\n): (kind: string) => Promise<readonly EdgeRow[]> {\n return createKindBatchReader(\n kinds,\n backend.findEdgesAcrossKinds === undefined ?\n 1\n : ENUMERATION_KINDS_PER_BATCH,\n (batchKinds) => enumerateGraphEdges(backend, graphId, batchKinds),\n );\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 options.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 options.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, a distinct live-store fork still\n * enumerates in full for its lost-update baseline. When the fork and base\n * are the same Store, the bounded point reads serve both sides and capture\n * only those keys. A recorded ancestor likewise captures only the bounded\n * delta; the incremental planner fills any additional plan-touched target\n * baselines by id before its commit guard is built.\n */\nexport async function diffAgainstBase<G extends GraphDef>(\n baseStore: Store<G>,\n forkStore: Store<G>,\n options: Readonly<{\n captureForkState?: boolean;\n pruneTo?: LineageDelta | undefined;\n baseReader?: StateDiffBaseReader | undefined;\n scopedIdentity?: CandidateIdentityScope | undefined;\n }> = {},\n): Promise<StateDiff> {\n const {\n captureForkState = true,\n pruneTo,\n baseReader,\n scopedIdentity,\n } = options;\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 sameStore = baseReader === undefined && baseStore === forkStore;\n // A same-store diff has identical rows on both sides even when the caller\n // requests a bounded fork-state snapshot. Reuse the point reads so that\n // snapshot stays proportional to the requested keys.\n const reuseRows = sameStore;\n // Branch clones export current identity state, not historical rows. Compare\n // that seed against the fork's archival rows so branch-authored endings keep\n // their `endedBy` stamps without treating assertions that were already ended\n // at the base as branch retractions. A same-store diff reads one shared\n // state snapshot to preserve its identical-snapshot contract.\n const baseIdentityPromise =\n baseReader === undefined ?\n scopedIdentity === undefined ?\n storeRuntime(baseStore).readCurrentIdentityAssertions(\"state\")\n : Promise.resolve(scopedIdentity.baseState)\n : baseReader.readIdentity(\"state\");\n const [baseIdentity, forkIdentity] = await Promise.all([\n baseIdentityPromise,\n sameStore ? baseIdentityPromise : (\n storeRuntime(forkStore).readCurrentIdentityAssertions(\"archival\")\n ),\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 const baseNodeRows =\n baseReader === undefined && prunedKeys === undefined ?\n createGraphNodeKindReader(\n storeBackend(baseStore),\n baseStore.graphId,\n nodeKinds,\n )\n : undefined;\n const forkNodeRows =\n (\n !reuseRows &&\n (prunedKeys === undefined ||\n (captureForkState && baseReader === undefined))\n ) ?\n createGraphNodeKindReader(\n storeBackend(forkStore),\n forkStore.graphId,\n nodeKinds,\n )\n : undefined;\n\n for (const kind of nodeKinds) {\n const nodeIds =\n prunedKeys === undefined ? [] : idsForKind(prunedKeys.nodes, kind);\n const baseRows =\n baseReader === undefined ?\n prunedKeys === undefined ?\n await requireDefined(baseNodeRows)(kind)\n : await fetchNodesByIds(\n storeBackend(baseStore),\n baseStore.graphId,\n kind,\n nodeIds,\n )\n : await baseReader.readNodes(\n kind,\n prunedKeys === undefined ? undefined : nodeIds,\n );\n const forkRowsFetched =\n reuseRows ? baseRows\n : forkNodeRows === undefined ?\n await fetchNodesByIds(\n storeBackend(forkStore),\n forkStore.graphId,\n kind,\n nodeIds,\n )\n : await forkNodeRows(kind);\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 (\n prunedKeys === undefined ||\n !captureForkState ||\n baseReader !== undefined\n ) ?\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 const baseEdgeRows =\n baseReader === undefined && prunedKeys === undefined ?\n createGraphEdgeKindReader(\n storeBackend(baseStore),\n baseStore.graphId,\n edgeKinds,\n )\n : undefined;\n const forkEdgeRows =\n (\n !reuseRows &&\n (prunedKeys === undefined ||\n (captureForkState && baseReader === undefined))\n ) ?\n createGraphEdgeKindReader(\n storeBackend(forkStore),\n forkStore.graphId,\n edgeKinds,\n )\n : undefined;\n\n for (const kind of edgeKinds) {\n const edgeIds =\n prunedKeys === undefined ? [] : idsForKind(prunedKeys.edges, kind);\n const baseRows =\n baseReader === undefined ?\n prunedKeys === undefined ?\n await requireDefined(baseEdgeRows)(kind)\n : await fetchEdgesByIds(\n storeBackend(baseStore),\n baseStore.graphId,\n kind,\n edgeIds,\n )\n : await baseReader.readEdges(\n kind,\n prunedKeys === undefined ? undefined : edgeIds,\n );\n const forkRowsFetched =\n reuseRows ? baseRows\n : forkEdgeRows === undefined ?\n await fetchEdgesByIds(\n storeBackend(forkStore),\n forkStore.graphId,\n kind,\n edgeIds,\n )\n : await forkEdgeRows(kind);\n const forkRows =\n (\n prunedKeys === undefined ||\n !captureForkState ||\n baseReader !== undefined\n ) ?\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 * `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 `|`:\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, 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`). A lineage-capable backend with revision\n * origin support also carries the graph's durable origin beside the\n * fingerprint, preserving the clear and cross-store fence. Hashing\n * keeps the content digest fixed-width regardless of 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 { canonicalizeProps, parseRowProps } from \"./canonical-props\";\nimport { compareStrings } from \"./node-key\";\nimport {\n createGraphEdgeKindReader,\n createGraphNodeKindReader,\n} 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 ensureRevisionOriginRow,\n mintsOriginNamespacedAnchor,\n readRecordedClock,\n readRevisionOrigin,\n recordedRelationsLineage,\n recordedRevisionOriginsVerdict,\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 component is a hex digest plus an optional `#s<version>` tag, so\n * it never contains `|`: the FIRST `|` delimits the two components even when\n * an engine revision after it contains one. Printable, so a token survives\n * every text store an application persists it in; PostgreSQL `text` and\n * `jsonb` both reject NUL.\n */\nconst TOKEN_SEPARATOR = \"|\";\n\n/** The separator tokens were minted with before it became printable. */\nconst LEGACY_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 * Recognizes retired engine-anchor tokens so they can be refused explicitly.\n */\nconst ENGINE_COMPONENT_PREFIX = \"engine:\";\nconst CONTENT_ORIGIN_PREFIX = \"origin:\";\n\n/**\n * Falls back to schema version `1` when the backend has not recorded an active\n * schema version. The schema hash deliberately excludes this number, while\n * the token's `#s` component carries it to fence schema round-trips.\n */\nconst FALLBACK_SCHEMA_VERSION = 1;\n\nfunction versionedSchemaComponent(schemaHash: string, version: number): string {\n return `${schemaHash}${SCHEMA_VERSION_TAG}${version}`;\n}\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 const readNodes = createGraphNodeKindReader(backend, graphId, nodeKinds);\n for (const kind of nodeKinds) {\n const rows = await readNodes(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 const readEdges = createGraphEdgeKindReader(backend, graphId, edgeKinds);\n for (const kind of edgeKinds) {\n const rows = await readEdges(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 return computeBaseVersionOn(store, storeBackend(store), {\n mintOrigin: () => mintRevisionOrigin(store),\n readRevision: () => store.revisionNow(),\n });\n}\n\n/**\n * Reads or creates the graph's revision origin on the root backend, relation\n * DDL included. A tracking store mints through its own base backend, because\n * its `storeBackend` is the recorded-capture wrapper that refuses raw writes.\n */\nfunction mintRevisionOrigin<G extends GraphDef>(\n store: Store<G>,\n): Promise<string> {\n if (store.revisionTrackingEnabled) return store.revisionOriginNow();\n const backend = storeBackend(store);\n return ensureRevisionOrigin(\n backend,\n recordedRevisionOriginsVerdict(backend),\n store.revisionSchema,\n store.graphId,\n );\n}\n\n/**\n * {@link computeBaseVersion} read through ONE pinned transaction session, so a\n * caller inside a write transaction observes that transaction's own pending\n * state (an uncommitted mutation, a capture flush that already ran on this\n * session) rather than the last committed state a root-backend read sees.\n *\n * The decision logic is {@link computeBaseVersionOn}'s, shared with\n * {@link computeBaseVersion}; the only divergence is where the revision origin\n * and clock are read. The origins RELATION is DDL and is never projected onto\n * an open transaction, so this path mints the ROW only and requires the\n * relation to already exist (every bundled backend installs it with the base\n * schema).\n */\nexport async function computeBaseVersionAtTarget<G extends GraphDef>(\n store: Store<G>,\n target: TransactionBackend,\n): Promise<BaseVersion> {\n return computeBaseVersionOn(store, target, targetAnchorReads(store, target));\n}\n\n/** How one base-version computation reads the graph's revision anchor. */\ntype RevisionAnchorReads = Readonly<{\n /** Reads the graph's revision origin, creating it when absent. */\n mintOrigin: () => Promise<string>;\n readRevision: () => Promise<string | undefined>;\n}>;\n\n/** The anchor reads a pinned transaction session can also make without minting. */\ntype TargetAnchorReads = RevisionAnchorReads &\n Readonly<{\n /** Reads the graph's revision origin; never creates it. */\n readOrigin: () => Promise<string | undefined>;\n }>;\n\n/**\n * THE one owner of how a pinned transaction session reads the revision anchor,\n * for both the token a caller mints ({@link computeBaseVersionAtTarget}) and the\n * token it checks ({@link compareBaseVersionAtTarget}).\n */\nfunction targetAnchorReads<G extends GraphDef>(\n store: Store<G>,\n target: TransactionBackend,\n): TargetAnchorReads {\n return {\n mintOrigin: () =>\n ensureRevisionOriginRow(target, store.revisionSchema, store.graphId),\n readOrigin: () =>\n readRevisionOrigin(target, store.revisionSchema, store.graphId),\n readRevision: () =>\n readRecordedClock(target, store.revisionSchema, store.graphId),\n };\n}\n\n/**\n * THE one owner of the schema half of a live base version: the active schema\n * version and the version-blind hash of the store's graph at that version, read\n * through `target`.\n */\nasync function readLiveSchemaHalf<G extends GraphDef>(\n store: Store<G>,\n target: Pick<GraphBackend, \"getActiveSchema\">,\n): Promise<Readonly<{ activeVersion: number; schemaComponent: string }>> {\n const activeVersion = await readActiveSchemaVersion(target, store.graphId);\n const schemaComponent = await computeSchemaHash(\n serializeSchema(store.graph, activeVersion),\n );\n return { activeVersion, schemaComponent };\n}\n\n/**\n * THE one owner of the content half of a live base version: the live-content\n * fingerprint, current identity assertions included, read through `target`.\n */\nasync function readLiveContentComponent<G extends GraphDef>(\n store: Store<G>,\n target: GraphBackend | TransactionBackend,\n): Promise<string> {\n return computeContentComponent(\n target,\n store.graphId,\n store.graph,\n await storeRuntime(store).identityAssertionsAtTarget(target, \"state\"),\n );\n}\n\n/**\n * THE one owner of base-version mode dispatch: revision-anchored when the store\n * tracks revisions, otherwise the live-content fingerprint (origin-namespaced\n * when lineage mints one). Reads are sequential because a pinned transaction\n * session must not overlap queries. `reads` names how the revision origin and\n * clock are read, the only members a caller varies.\n */\nasync function computeBaseVersionOn<G extends GraphDef>(\n store: Store<G>,\n target: GraphBackend | TransactionBackend,\n reads: RevisionAnchorReads,\n): Promise<BaseVersion> {\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 content branch below carries this version too, because an\n // otherwise identical schema round-trip still changes the committed cut.\n const { activeVersion, schemaComponent } = await readLiveSchemaHalf(\n store,\n target,\n );\n if (store.revisionTrackingEnabled) {\n const origin = await reads.mintOrigin();\n const revision = await reads.readRevision();\n return revisionBaseVersion(\n schemaComponent,\n activeVersion,\n origin,\n revision,\n );\n }\n // Without TypeGraph revision tracking, the complete graph fingerprint is\n // the commit-spanning fence, including current identity assertions.\n const contentComponent = await readLiveContentComponent(store, target);\n const originsSupported = recordedRevisionOriginsVerdict(\n storeBackend(store),\n ).supported;\n return contentBaseVersion(\n schemaComponent,\n activeVersion,\n contentComponent,\n mintsOriginNamespacedAnchor(store, originsSupported) ?\n await reads.mintOrigin()\n : undefined,\n );\n}\n\n/** Assembles the O(1) revision-anchored token; the one owner of that spelling. */\nfunction revisionBaseVersion(\n schemaComponent: string,\n activeVersion: number,\n origin: string,\n revision: string | undefined,\n): BaseVersion {\n return asBaseVersion(\n `${versionedSchemaComponent(schemaComponent, activeVersion)}${TOKEN_SEPARATOR}${revisionComponent(origin, revision)}`,\n );\n}\n\n/** Assembles the content-fingerprint token, origin-namespaced when lineage minted one. */\nfunction contentBaseVersion(\n schemaComponent: string,\n activeVersion: number,\n contentComponent: string,\n origin: string | undefined,\n): BaseVersion {\n const contentAnchor =\n origin === undefined ? contentComponent : (\n `${CONTENT_ORIGIN_PREFIX}${origin}:${contentComponent}`\n );\n return asBaseVersion(\n `${versionedSchemaComponent(schemaComponent, activeVersion)}${TOKEN_SEPARATOR}${contentAnchor}`,\n );\n}\n\n/** The observed component that disagrees with a stamped base version. */\nexport type BaseVersionTargetComparison =\n | Readonly<{ matches: true }>\n | Readonly<{\n matches: false;\n kind: \"schema\";\n expected: string;\n live: string;\n expectedActiveVersion: number | undefined;\n liveActiveVersion: number;\n }>\n | Readonly<{\n matches: false;\n kind: \"revision-origin\" | \"revision\" | \"content-origin\" | \"content\";\n expected: string | undefined;\n live: string | undefined;\n }>;\n\n/**\n * Compares a base token with graph state read through one pinned transaction.\n * The caller establishes the needed graph locks before invoking this reader.\n * Reading through `target` also avoids opening a second pool session while the\n * caller holds those locks.\n */\nexport async function compareBaseVersionAtTarget<G extends GraphDef>(\n store: Store<G>,\n target: TransactionBackend,\n expected: BaseVersion,\n): Promise<BaseVersionTargetComparison> {\n const { activeVersion, schemaComponent } = await readLiveSchemaHalf(\n store,\n target,\n );\n const liveSchema = versionedSchemaComponent(schemaComponent, activeVersion);\n const expectedSchema = schemaComponentOf(expected);\n if (liveSchema !== expectedSchema) {\n return {\n matches: false,\n kind: \"schema\",\n expected: expectedSchema,\n live: liveSchema,\n expectedActiveVersion: schemaActiveVersionOf(expected),\n liveActiveVersion: activeVersion,\n };\n }\n\n const reads = targetAnchorReads(store, target);\n if (hasRevisionAnchor(expected)) {\n const originMatch = await revisionOriginMatch(reads.readOrigin, expected);\n if (!originMatch.matches) {\n return {\n matches: false,\n kind: \"revision-origin\",\n expected: originMatch.expectedOrigin,\n live: originMatch.liveOrigin,\n };\n }\n const expectedRevision = revisionAnchorOf(expected);\n const liveRevision = await reads.readRevision();\n return liveRevision === expectedRevision ?\n { matches: true }\n : {\n matches: false,\n kind: \"revision\",\n expected: expectedRevision,\n live: liveRevision,\n };\n }\n\n const expectedOrigin = contentOriginOf(expected);\n if (expectedOrigin !== undefined) {\n const liveOrigin = await reads.readOrigin();\n if (liveOrigin !== expectedOrigin) {\n return {\n matches: false,\n kind: \"content-origin\",\n expected: expectedOrigin,\n live: liveOrigin,\n };\n }\n }\n const liveContent = await readLiveContentComponent(store, target);\n const expectedContent = contentFingerprintOf(expected);\n return liveContent === expectedContent ?\n { matches: true }\n : {\n matches: false,\n kind: \"content\",\n expected: expectedContent,\n live: liveContent,\n };\n}\n\n/** Parses the durable origin carried by a content-fingerprinted base token. */\nexport function contentOriginOf(version: BaseVersion): string | undefined {\n const component = contentComponentOf(version);\n if (!component.startsWith(CONTENT_ORIGIN_PREFIX)) return undefined;\n const separator = component.indexOf(\":\", CONTENT_ORIGIN_PREFIX.length);\n return separator === -1 ? undefined : (\n component.slice(CONTENT_ORIGIN_PREFIX.length, separator)\n );\n}\n\n/** Returns the graph-content digest from a content-fingerprinted token. */\nfunction contentFingerprintOf(version: BaseVersion): string {\n const component = contentComponentOf(version);\n if (!component.startsWith(CONTENT_ORIGIN_PREFIX)) return component;\n const separator = component.indexOf(\":\", CONTENT_ORIGIN_PREFIX.length);\n return separator === -1 ? component : component.slice(separator + 1);\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. The decoder also recognizes retired engine-anchor tokens, so\n * there is exactly one place that parses `<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/** 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 a previously minted engine-anchor token.\n * New tokens never use this form; the merge commit refuses it.\n */\nexport function engineAnchorOf(\n version: BaseVersion,\n): EngineRevision | undefined {\n return engineAnchorParts(version)?.revision;\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 origin-match decision for TypeGraph revision anchors: compare the\n * token's origin with the live origin `readOrigin` reads from the caller's own\n * session. Both the merge commit and lineage pruning use this comparison.\n * Returns the two values actually compared alongside the verdict, so a caller\n * that refuses on a mismatch embeds both in its own error `details` without a\n * second read.\n */\nasync function revisionOriginMatch(\n readOrigin: () => Promise<string | undefined>,\n expectedVersion: BaseVersion,\n): Promise<\n Readonly<{\n expectedOrigin: string | undefined;\n liveOrigin: string | undefined;\n matches: boolean;\n }>\n> {\n const expectedOrigin = revisionOriginOf(expectedVersion);\n const liveOrigin = await readOrigin();\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 * Whether `version` was minted in the retired NUL-separated format. Such a\n * token can never equal one a live store mints now, so every precondition\n * refuses it; callers use this only to say why.\n */\nexport function isLegacyBaseVersion(version: BaseVersion): boolean {\n return (version as string).includes(LEGACY_TOKEN_SEPARATOR);\n}\n\n/** Refusal details shared by every site that rejects a legacy token. */\nexport const LEGACY_BASE_VERSION_REFUSAL = {\n reason: \"legacy-token-format\",\n suggestion:\n \"This token was minted by an earlier TypeGraph release in a retired format. Re-branch or re-plan from the current target.\",\n} as const;\n\n/**\n * Index of the component separator, or -1 for a token with no schema\n * component. A legacy token parses as having none, so no anchor or schema\n * half is ever read out of it.\n */\nfunction tokenSeparatorIndex(version: BaseVersion): number {\n if (isLegacyBaseVersion(version)) return -1;\n return (version as string).indexOf(TOKEN_SEPARATOR);\n}\n\n/**\n * Extracts the second component from a `base@V` token. The schema component\n * contains no separator, so the substring after the separator is exactly the\n * durable revision or content fingerprint (possibly with its origin).\n *\n * Used by revision-token parsing and content-fingerprint re-validation.\n */\nexport function contentComponentOf(version: BaseVersion): string {\n const separatorIndex = tokenSeparatorIndex(version);\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.\n */\nexport function schemaComponentOf(version: BaseVersion): string {\n const separatorIndex = tokenSeparatorIndex(version);\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 current token's\n * schema half, or `undefined` for an older content token. The document hash\n * never contains `#s`\n * (hex digits only), so the tag position is unambiguous.\n *\n * Pairs with {@link readActiveSchemaVersion} inside the target commit\n * transaction so a schema round-trip cannot restore an older fence.\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 * TypeGraph revision anchors are answered directly through the recorded\n * relations. Content-fingerprinted and retired engine tokens return\n * `undefined`, selecting the complete diff.\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 () =>\n readRevisionOrigin(\n storeBackend(baseStore),\n baseStore.revisionSchema,\n baseStore.graphId,\n ),\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 return undefined;\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 * @param options - Set `revisionJournal: false` when the clone does not need\n * journal-backed changed-key lineage. This avoids installing journal\n * triggers on its tables. Set `refreshStatistics: false` for a short-lived\n * copy that will not benefit from refreshed query statistics.\n */\nexport function cloneWorkingCopyStrategy<G extends GraphDef>(\n makeBackend: MakeBackend,\n options: Readonly<{\n revisionJournal?: false;\n refreshStatistics?: false;\n }> = {},\n): WorkingCopyStrategy<G> {\n return cloneWorkingCopyWithGraphStrategy(\n makeBackend,\n (baseStore) => baseStore.graph,\n options,\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(\n makeBackend,\n (baseStore) => graphWithoutNodeUniqueness(baseStore.graph),\n { revisionJournal: false, refreshStatistics: false },\n );\n}\n\nfunction cloneWorkingCopyWithGraphStrategy<G extends GraphDef>(\n makeBackend: MakeBackend,\n graphForClone: (baseStore: Store<G>) => G,\n options: Readonly<{\n revisionJournal?: false;\n refreshStatistics?: false;\n }> = {},\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 ...(options.revisionJournal === false ?\n { revisionJournal: false as const }\n : {}),\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 ...(options.refreshStatistics === false ?\n { refreshStatistics: false as const }\n : {}),\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 */\nexport function 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 captureRevision = true,\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 = captureRevision ? resolveLineage(store) : undefined;\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","/**\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 allocation id, the owning\n * `graphId`, the branch id, the `base@V` token the working copy forked from, the at-fork\n * schema anchor (explicitly absent for an unmanaged store), the at-fork\n * engine revision when the working copy resolved `lineage`, and the\n * source recorded-time cut when history was captured.\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 `allocationId`/`graphId`/`definitionHash`/`base`/`branchId`/\n * `forkRevision`/`schemaAnchor`/`recordedForkPoint`, including DELETING\n * `schemaAnchor` from the\n * envelope, cannot relabel a fork, because the host's own record is the\n * reference. Allocation identity is independent of a caller-supplied branch\n * name, so even two allocations with the same branch id cannot be relabeled.\n * `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 { asRecordedInstant } from \"../core/temporal\";\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 { 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 RecordedForkPoint,\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/**\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 * allocation id, graph 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), plus the source\n * recorded-time cut when history was captured.\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 /** Unique identity of this physical allocation, independent of branch name. */\n allocationId: string;\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 recordedForkPoint?: RecordedForkPoint;\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 /** Unique identity of the sealed physical allocation. */\n allocationId: string;\n /** Stable strategy type tag; must equal the reopening strategy's `type`. */\n kind: string;\n /** Strategy locator format version; must be readable by the strategy. */\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 /** Source recorded-time cut, when the source captured history at fork time. */\n recordedForkPoint?: RecordedForkPoint;\n}>;\n\n/** A branch handle bound to the sealed physical allocation it opened. */\nexport type DurableGraphBranch<G extends GraphDef> = GraphBranch<G> &\n Readonly<{ allocationId: string }>;\n\n/** Persist `allocationId` before calling when host-side recovery is required. */\nexport type DurableBranchOptions = BranchOptions &\n Readonly<{ allocationId?: string | undefined }>;\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 under `allocationId` and\n * returns a mutable {@link Store} over it plus the opaque locator. An\n * allocation id MUST NOT name a second physical copy. If a previous\n * attempt may have allocated the id, the host MUST refuse `create` and\n * require explicit recovery through host tooling; it MUST NOT return a\n * sealed allocation as a newly created one. If it supplies\n * `forkRevision`, that revision MUST be captured atomically with the\n * physical fork; otherwise TypeGraph uses a full diff at merge time.\n * Once `create` resolves, TypeGraph owns the allocation and the 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. Every connection and transaction of the returned Store MUST stay\n * bound to this allocation's native branch; a checkout on one pooled session\n * is not evidence that later sessions read the same branch.\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 written by new descriptors. */\n version: number;\n /** Older locator versions every strategy method can still read and manage. */\n readableVersions?: readonly number[] | undefined;\n create: (\n baseStore: Store<G>,\n base: BaseVersion,\n branchId: BranchId,\n allocationId: string,\n ) => Promise<\n Readonly<{\n store: Store<G>;\n descriptor: TStoreDescriptor;\n access: DurableWorkingCopyAccess;\n forkRevision?: EngineRevision | undefined;\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 descriptorVersion: number,\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 descriptorVersion: number,\n ) => Promise<void>;\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 best effort or with callbacks that run outside the evidence\n * transaction. A callback the strategy runs inside that transaction is the\n * host's atomic mutation, not an emulation. 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: DurableGraphBranch<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?: DurableBranchOptions,\n): Promise<Result<DurableBranch<G, TStoreDescriptor>, BranchError>> {\n if (options?.allocationId !== undefined && options.id === undefined) {\n return err(\n new BranchError(\n \"A caller-supplied durable allocation id requires a stable branch id for retries.\",\n ),\n );\n }\n if (options?.allocationId === \"\") {\n return err(new BranchError(\"Durable allocation id must not be empty.\"));\n }\n let base: BaseVersion;\n let recordedForkPoint: RecordedForkPoint | undefined;\n let id: BranchId;\n let allocationId: string;\n try {\n base = await computeBaseVersion(baseStore);\n if (baseStore.historyEnabled) {\n const recorded = await baseStore.recordedNow();\n if (recorded !== undefined) recordedForkPoint = { recorded, base };\n }\n id = options?.id ?? asBranchId(generateId());\n allocationId = options?.allocationId ?? 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 forkRevision?: EngineRevision | undefined;\n }>;\n try {\n created = await strategy.create(baseStore, base, id, allocationId);\n } catch (error) {\n return err(\n new BranchError(\n \"Failed to create durable working-copy branch of base store. The host may have allocated it before reporting failure.\",\n {\n cause: error,\n details: { branchId: id, allocationId, strategyType: strategy.type },\n suggestion:\n \"Use the strategy's operator tooling to inspect and recover this allocation id before retrying.\",\n },\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 const captured = await readBranchForkState(created.store, false);\n forkState = { ...captured, forkRevision: created.forkRevision };\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 allocationId,\n graphId: created.store.graphId,\n definitionHash,\n branchId: id,\n base,\n schemaAnchor: forkState.schemaAnchor,\n forkRevision: forkState.forkRevision,\n ...(recordedForkPoint === undefined ? {} : { recordedForkPoint }),\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: DurableGraphBranch<G> = {\n allocationId: origin.allocationId,\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 ...(recordedForkPoint === undefined ? {} : { recordedForkPoint }),\n };\n const descriptor: DurableBranchDescriptor<TStoreDescriptor> = {\n allocationId: origin.allocationId,\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 ...(recordedForkPoint === undefined ? {} : { recordedForkPoint }),\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, {\n captureForkState: false,\n });\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<DurableGraphBranch<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(\n graph,\n descriptor.store,\n descriptor.version,\n );\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 descriptor.version,\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 * 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: Readonly<{\n type: string;\n version: number;\n readableVersions?: readonly number[] | undefined;\n }>,\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 (\n record[\"version\"] !== strategy.version &&\n !(\n typeof record[\"version\"] === \"number\" &&\n strategy.readableVersions?.includes(record[\"version\"])\n )\n ) {\n return new BranchError(\n `Durable branch descriptor version ${String(record[\"version\"])} is not supported by strategy \"${strategy.type}\".`,\n {\n details: {\n descriptorVersion: record[\"version\"],\n strategyVersion: strategy.version,\n readableVersions: strategy.readableVersions ?? [],\n },\n },\n );\n }\n for (const key of [\n \"allocationId\",\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 if (record[\"recordedForkPoint\"] !== undefined) {\n const point = record[\"recordedForkPoint\"];\n if (\n typeof point !== \"object\" ||\n point === null ||\n typeof (point as Readonly<Record<string, unknown>>)[\"recorded\"] !==\n \"string\" ||\n typeof (point as Readonly<Record<string, unknown>>)[\"base\"] !== \"string\"\n ) {\n return new BranchError(\n \"Durable branch descriptor is malformed: recordedForkPoint must be { recorded: string, base: string }.\",\n { details: { strategyType: strategy.type } },\n );\n }\n try {\n asRecordedInstant((point as Readonly<{ recorded: string }>).recorded);\n } catch (error) {\n return new BranchError(\n \"Durable branch descriptor has an invalid recorded fork instant.\",\n { cause: error, details: { strategyType: strategy.type } },\n );\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 allocationId: descriptor.allocationId,\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 ...(descriptor.recordedForkPoint === undefined ?\n {}\n : { recordedForkPoint: descriptor.recordedForkPoint }),\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.allocationId === attested.allocationId &&\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 recordedForkPointsEqual(\n descriptor.recordedForkPoint,\n attested.recordedForkPoint,\n )\n );\n}\n\nfunction recordedForkPointsEqual(\n left: DurableBranchOrigin[\"recordedForkPoint\"],\n right: DurableBranchOrigin[\"recordedForkPoint\"],\n): boolean {\n if (left === undefined || right === undefined) return left === right;\n return left.recorded === right.recorded && left.base === right.base;\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 *\n * Exported for a strategy that attaches a caller's graph to an allocation\n * without going through reopen (the PostgreSQL manager's operation members), so\n * this decision keeps one owner.\n */\nexport async 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): DurableGraphBranch<G> {\n return {\n allocationId: descriptor.allocationId,\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 ...(descriptor.recordedForkPoint === undefined ?\n {}\n : { recordedForkPoint: descriptor.recordedForkPoint }),\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"]}
1
+ {"version":3,"sources":["../src/graph-merge/errors.ts","../src/graph-merge/types.ts","../src/graph-merge/canonical-props.ts","../src/graph-merge/node-key.ts","../src/graph-merge/temporal-identity-closure.ts","../src/graph-merge/merge-identity.ts","../src/graph-merge/state-diff.ts","../src/graph-merge/base-version.ts","../src/graph-merge/working-copy.ts","../src/graph-merge/branch.ts","../src/graph-merge/durable-branch.ts"],"names":["branch"],"mappings":";;;;;;;;;;;;;;;;;AAgBO,IAAM,iBAAA,GAAoB;AAAA,EAC/B,KAAA,EAAO,mBAAA;AAAA,EACP,cAAA,EAAgB,6BAAA;AAAA,EAChB,MAAA,EAAQ,0BAAA;AAAA,EACR,qBAAA,EAAuB,oCAAA;AAAA,EACvB,QAAA,EAAU,sBAAA;AAAA,EACV,kBAAA,EAAoB,iCAAA;AAAA,EACpB,gBAAA,EAAkB,+BAAA;AAAA,EAClB,mBAAA,EAAqB,mCAAA;AAAA,EACrB,cAAA,EAAgB,6BAAA;AAAA,EAChB,WAAA,EAAa,0BAAA;AAAA,EACb,sBAAA,EAAwB,sCAAA;AAAA,EACxB,kBAAA,EAAoB,kCAAA;AAAA,EACpB,kBAAA,EAAoB,kCAAA;AAAA,EACpB,kBAAA,EAAoB,kCAAA;AAAA,EACpB,kBAAA,EAAoB,kCAAA;AAAA,EACpB,SAAA,EAAW,wBAAA;AAAA,EACX,aAAA,EAAe,4BAAA;AAAA,EACf,eAAA,EAAiB,8BAAA;AAAA,EACjB,QAAA,EAAU,sBAAA;AAAA,EACV,iBAAA,EAAmB,iCAAA;AAAA,EACnB,MAAA,EAAQ,oBAAA;AAAA,EACR,SAAA,EAAW,uBAAA;AAAA,EACX,gBAAA,EAAkB,+BAAA;AAAA,EAClB,iBAAA,EAAmB,gCAAA;AAAA,EACnB,oBAAA,EAAsB,mCAAA;AAAA,EACtB,iBAAA,EAAmB,gCAAA;AAAA,EACnB,oBAAA,EAAsB;A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{ 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 best effort or\n * with callbacks that run outside the evidence transaction (see\n * {@link DurableWorkingCopyStrategy.operations}).\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","/**\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 { RecordedInstant } from \"../core/temporal\";\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/** An attested source cut for a branch forked from a history-enabled graph. */\nexport type RecordedForkPoint = Readonly<{\n recorded: RecordedInstant;\n base: BaseVersion;\n}>;\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 * The source graph's recorded high-water mark at the fork cut, paired with\n * the base token captured from that same source state. Present only when\n * the source Store records history and had a captured write at fork time.\n */\n recordedForkPoint?: RecordedForkPoint;\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> | RecordedForkPoint;\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 * 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 { 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 hasScopedIdentityReads,\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 runtime = storeRuntime(target);\n if (hasScopedIdentityReads(runtime)) {\n return runtime.identityAssertionsTouchingAtTarget(\n backend,\n [...memberKeys].map((key) => ({ kind: kindOf(key), id: idOf(key) })),\n \"state\",\n );\n }\n // Older custom Store runtimes lack the scoped read. Preserve their original\n // full-ledger guard, using the same transaction target and endpoint filter.\n return (await runtime.identityAssertionsAtTarget(backend, \"state\")).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\";\nimport type { CandidateIdentityScope } from \"./candidate-identity-closure\";\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/** Raw ancestor reads used by the state diff, including tombstones and ended assertions. */\nexport type StateDiffBaseReader = Readonly<{\n readNodes: (\n kind: string,\n ids?: readonly string[],\n ) => Promise<readonly NodeRow[]>;\n readEdges: (\n kind: string,\n ids?: readonly string[],\n ) => Promise<readonly EdgeRow[]>;\n readIdentity: (\n mode: \"state\" | \"archival\",\n ) => Promise<readonly IdentityTransferAssertion[]>;\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/** Enumerate declared kinds in graph-wide pages when the backend supports it. */\nexport async function enumerateGraphNodes(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kinds: readonly string[],\n): Promise<ReadonlyMap<string, readonly NodeRow[]>> {\n const rowsByKind = new Map<string, NodeRow[]>();\n if (kinds.length === 0) return rowsByKind;\n const readPage = backend.findNodesAcrossKinds;\n if (readPage === undefined) {\n for (const kind of kinds) {\n rowsByKind.set(kind, [\n ...(await enumerateAllNodes(backend, graphId, kind)),\n ]);\n }\n return rowsByKind;\n }\n let after: Readonly<{ kind: string; id: string }> | undefined;\n for (;;) {\n const page = await readPage({\n graphId,\n kinds,\n limit: ENUMERATION_PAGE_SIZE,\n excludeDeleted: false,\n ...(after === undefined ? {} : { after }),\n });\n for (const row of page) {\n const rows = rowsByKind.get(row.kind) ?? [];\n rows.push(row);\n rowsByKind.set(row.kind, rows);\n }\n if (page.length < ENUMERATION_PAGE_SIZE) break;\n const last = requireDefined(page.at(-1));\n after = { kind: last.kind, id: last.id };\n }\n return rowsByKind;\n}\n\n/** Edge counterpart of {@link enumerateGraphNodes}. */\nexport async function enumerateGraphEdges(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kinds: readonly string[],\n): Promise<ReadonlyMap<string, readonly EdgeRow[]>> {\n const rowsByKind = new Map<string, EdgeRow[]>();\n if (kinds.length === 0) return rowsByKind;\n const readPage = backend.findEdgesAcrossKinds;\n if (readPage === undefined) {\n for (const kind of kinds) {\n rowsByKind.set(kind, [\n ...(await enumerateAllEdges(backend, graphId, kind)),\n ]);\n }\n return rowsByKind;\n }\n let after: Readonly<{ kind: string; id: string }> | undefined;\n for (;;) {\n const page = await readPage({\n graphId,\n kinds,\n limit: ENUMERATION_PAGE_SIZE,\n excludeDeleted: false,\n ...(after === undefined ? {} : { after }),\n });\n for (const row of page) {\n const rows = rowsByKind.get(row.kind) ?? [];\n rows.push(row);\n rowsByKind.set(row.kind, rows);\n }\n if (page.length < ENUMERATION_PAGE_SIZE) break;\n const last = requireDefined(page.at(-1));\n after = { kind: last.kind, id: last.id };\n }\n return rowsByKind;\n}\n\n/** Bound the rows retained by a graph-wide read while preserving kind order. */\nfunction createKindBatchReader<Row>(\n kinds: readonly string[],\n kindsPerBatch: number,\n enumerateBatch: (\n batchKinds: readonly string[],\n ) => Promise<ReadonlyMap<string, readonly Row[]>>,\n): (kind: string) => Promise<readonly Row[]> {\n let nextIndex = 0;\n let rowsByKind: ReadonlyMap<string, readonly Row[]> = new Map();\n return async (kind) => {\n if (kinds[nextIndex] !== kind) {\n throw new Error(\n \"Graph kind batches must be consumed in declaration order.\",\n );\n }\n if (nextIndex % kindsPerBatch === 0) {\n rowsByKind = await enumerateBatch(\n kinds.slice(nextIndex, nextIndex + kindsPerBatch),\n );\n }\n nextIndex++;\n return rowsByKind.get(kind) ?? [];\n };\n}\n\n/** A bounded set of kinds amortizes empty-kind round trips without a graph-sized buffer. */\nconst ENUMERATION_KINDS_PER_BATCH = 8;\n\nexport function createGraphNodeKindReader(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kinds: readonly string[],\n): (kind: string) => Promise<readonly NodeRow[]> {\n return createKindBatchReader(\n kinds,\n backend.findNodesAcrossKinds === undefined ?\n 1\n : ENUMERATION_KINDS_PER_BATCH,\n (batchKinds) => enumerateGraphNodes(backend, graphId, batchKinds),\n );\n}\n\nexport function createGraphEdgeKindReader(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kinds: readonly string[],\n): (kind: string) => Promise<readonly EdgeRow[]> {\n return createKindBatchReader(\n kinds,\n backend.findEdgesAcrossKinds === undefined ?\n 1\n : ENUMERATION_KINDS_PER_BATCH,\n (batchKinds) => enumerateGraphEdges(backend, graphId, batchKinds),\n );\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 options.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 options.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, a distinct live-store fork still\n * enumerates in full for its lost-update baseline. When the fork and base\n * are the same Store, the bounded point reads serve both sides and capture\n * only those keys. A recorded ancestor likewise captures only the bounded\n * delta; the incremental planner fills any additional plan-touched target\n * baselines by id before its commit guard is built.\n */\nexport async function diffAgainstBase<G extends GraphDef>(\n baseStore: Store<G>,\n forkStore: Store<G>,\n options: Readonly<{\n captureForkState?: boolean;\n pruneTo?: LineageDelta | undefined;\n baseReader?: StateDiffBaseReader | undefined;\n scopedIdentity?: CandidateIdentityScope | undefined;\n }> = {},\n): Promise<StateDiff> {\n const {\n captureForkState = true,\n pruneTo,\n baseReader,\n scopedIdentity,\n } = options;\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 sameStore = baseReader === undefined && baseStore === forkStore;\n // A same-store diff has identical rows on both sides even when the caller\n // requests a bounded fork-state snapshot. Reuse the point reads so that\n // snapshot stays proportional to the requested keys.\n const reuseRows = sameStore;\n // Branch clones export current identity state, not historical rows. Compare\n // that seed against the fork's archival rows so branch-authored endings keep\n // their `endedBy` stamps without treating assertions that were already ended\n // at the base as branch retractions. A same-store diff reads one shared\n // state snapshot to preserve its identical-snapshot contract.\n const baseIdentityPromise =\n baseReader === undefined ?\n scopedIdentity === undefined ?\n storeRuntime(baseStore).readCurrentIdentityAssertions(\"state\")\n : Promise.resolve(scopedIdentity.baseState)\n : baseReader.readIdentity(\"state\");\n const [baseIdentity, forkIdentity] = await Promise.all([\n baseIdentityPromise,\n sameStore ? baseIdentityPromise : (\n storeRuntime(forkStore).readCurrentIdentityAssertions(\"archival\")\n ),\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 const baseNodeRows =\n baseReader === undefined && prunedKeys === undefined ?\n createGraphNodeKindReader(\n storeBackend(baseStore),\n baseStore.graphId,\n nodeKinds,\n )\n : undefined;\n const forkNodeRows =\n (\n !reuseRows &&\n (prunedKeys === undefined ||\n (captureForkState && baseReader === undefined))\n ) ?\n createGraphNodeKindReader(\n storeBackend(forkStore),\n forkStore.graphId,\n nodeKinds,\n )\n : undefined;\n\n for (const kind of nodeKinds) {\n const nodeIds =\n prunedKeys === undefined ? [] : idsForKind(prunedKeys.nodes, kind);\n const baseRows =\n baseReader === undefined ?\n prunedKeys === undefined ?\n await requireDefined(baseNodeRows)(kind)\n : await fetchNodesByIds(\n storeBackend(baseStore),\n baseStore.graphId,\n kind,\n nodeIds,\n )\n : await baseReader.readNodes(\n kind,\n prunedKeys === undefined ? undefined : nodeIds,\n );\n const forkRowsFetched =\n reuseRows ? baseRows\n : forkNodeRows === undefined ?\n await fetchNodesByIds(\n storeBackend(forkStore),\n forkStore.graphId,\n kind,\n nodeIds,\n )\n : await forkNodeRows(kind);\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 (\n prunedKeys === undefined ||\n !captureForkState ||\n baseReader !== undefined\n ) ?\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 const baseEdgeRows =\n baseReader === undefined && prunedKeys === undefined ?\n createGraphEdgeKindReader(\n storeBackend(baseStore),\n baseStore.graphId,\n edgeKinds,\n )\n : undefined;\n const forkEdgeRows =\n (\n !reuseRows &&\n (prunedKeys === undefined ||\n (captureForkState && baseReader === undefined))\n ) ?\n createGraphEdgeKindReader(\n storeBackend(forkStore),\n forkStore.graphId,\n edgeKinds,\n )\n : undefined;\n\n for (const kind of edgeKinds) {\n const edgeIds =\n prunedKeys === undefined ? [] : idsForKind(prunedKeys.edges, kind);\n const baseRows =\n baseReader === undefined ?\n prunedKeys === undefined ?\n await requireDefined(baseEdgeRows)(kind)\n : await fetchEdgesByIds(\n storeBackend(baseStore),\n baseStore.graphId,\n kind,\n edgeIds,\n )\n : await baseReader.readEdges(\n kind,\n prunedKeys === undefined ? undefined : edgeIds,\n );\n const forkRowsFetched =\n reuseRows ? baseRows\n : forkEdgeRows === undefined ?\n await fetchEdgesByIds(\n storeBackend(forkStore),\n forkStore.graphId,\n kind,\n edgeIds,\n )\n : await forkEdgeRows(kind);\n const forkRows =\n (\n prunedKeys === undefined ||\n !captureForkState ||\n baseReader !== undefined\n ) ?\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 * `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 `|`:\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, 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`). A lineage-capable backend with revision\n * origin support also carries the graph's durable origin beside the\n * fingerprint, preserving the clear and cross-store fence. Hashing\n * keeps the content digest fixed-width regardless of 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 { canonicalizeProps, parseRowProps } from \"./canonical-props\";\nimport { compareStrings } from \"./node-key\";\nimport {\n createGraphEdgeKindReader,\n createGraphNodeKindReader,\n} 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 ensureRevisionOriginRow,\n mintsOriginNamespacedAnchor,\n readRecordedClock,\n readRevisionOrigin,\n recordedRelationsLineage,\n recordedRevisionOriginsVerdict,\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 component is a hex digest plus an optional `#s<version>` tag, so\n * it never contains `|`: the FIRST `|` delimits the two components even when\n * an engine revision after it contains one. Printable, so a token survives\n * every text store an application persists it in; PostgreSQL `text` and\n * `jsonb` both reject NUL.\n */\nconst TOKEN_SEPARATOR = \"|\";\n\n/** The separator tokens were minted with before it became printable. */\nconst LEGACY_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 * Recognizes retired engine-anchor tokens so they can be refused explicitly.\n */\nconst ENGINE_COMPONENT_PREFIX = \"engine:\";\nconst CONTENT_ORIGIN_PREFIX = \"origin:\";\n\n/**\n * Falls back to schema version `1` when the backend has not recorded an active\n * schema version. The schema hash deliberately excludes this number, while\n * the token's `#s` component carries it to fence schema round-trips.\n */\nconst FALLBACK_SCHEMA_VERSION = 1;\n\nfunction versionedSchemaComponent(schemaHash: string, version: number): string {\n return `${schemaHash}${SCHEMA_VERSION_TAG}${version}`;\n}\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 const readNodes = createGraphNodeKindReader(backend, graphId, nodeKinds);\n for (const kind of nodeKinds) {\n const rows = await readNodes(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 const readEdges = createGraphEdgeKindReader(backend, graphId, edgeKinds);\n for (const kind of edgeKinds) {\n const rows = await readEdges(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 return computeBaseVersionOn(store, storeBackend(store), {\n mintOrigin: () => mintRevisionOrigin(store),\n readRevision: () => store.revisionNow(),\n });\n}\n\n/**\n * Reads or creates the graph's revision origin on the root backend, relation\n * DDL included. A tracking store mints through its own base backend, because\n * its `storeBackend` is the recorded-capture wrapper that refuses raw writes.\n */\nfunction mintRevisionOrigin<G extends GraphDef>(\n store: Store<G>,\n): Promise<string> {\n if (store.revisionTrackingEnabled) return store.revisionOriginNow();\n const backend = storeBackend(store);\n return ensureRevisionOrigin(\n backend,\n recordedRevisionOriginsVerdict(backend),\n store.revisionSchema,\n store.graphId,\n );\n}\n\n/**\n * {@link computeBaseVersion} read through ONE pinned transaction session, so a\n * caller inside a write transaction observes that transaction's own pending\n * state (an uncommitted mutation, a capture flush that already ran on this\n * session) rather than the last committed state a root-backend read sees.\n *\n * The decision logic is {@link computeBaseVersionOn}'s, shared with\n * {@link computeBaseVersion}; the only divergence is where the revision origin\n * and clock are read. The origins RELATION is DDL and is never projected onto\n * an open transaction, so this path mints the ROW only and requires the\n * relation to already exist (every bundled backend installs it with the base\n * schema).\n */\nexport async function computeBaseVersionAtTarget<G extends GraphDef>(\n store: Store<G>,\n target: TransactionBackend,\n): Promise<BaseVersion> {\n return computeBaseVersionOn(store, target, targetAnchorReads(store, target));\n}\n\n/** How one base-version computation reads the graph's revision anchor. */\ntype RevisionAnchorReads = Readonly<{\n /** Reads the graph's revision origin, creating it when absent. */\n mintOrigin: () => Promise<string>;\n readRevision: () => Promise<string | undefined>;\n}>;\n\n/** The anchor reads a pinned transaction session can also make without minting. */\ntype TargetAnchorReads = RevisionAnchorReads &\n Readonly<{\n /** Reads the graph's revision origin; never creates it. */\n readOrigin: () => Promise<string | undefined>;\n }>;\n\n/**\n * THE one owner of how a pinned transaction session reads the revision anchor,\n * for both the token a caller mints ({@link computeBaseVersionAtTarget}) and the\n * token it checks ({@link compareBaseVersionAtTarget}).\n */\nfunction targetAnchorReads<G extends GraphDef>(\n store: Store<G>,\n target: TransactionBackend,\n): TargetAnchorReads {\n return {\n mintOrigin: () =>\n ensureRevisionOriginRow(target, store.revisionSchema, store.graphId),\n readOrigin: () =>\n readRevisionOrigin(target, store.revisionSchema, store.graphId),\n readRevision: () =>\n readRecordedClock(target, store.revisionSchema, store.graphId),\n };\n}\n\n/**\n * THE one owner of the schema half of a live base version: the active schema\n * version and the version-blind hash of the store's graph at that version, read\n * through `target`.\n */\nasync function readLiveSchemaHalf<G extends GraphDef>(\n store: Store<G>,\n target: Pick<GraphBackend, \"getActiveSchema\">,\n): Promise<Readonly<{ activeVersion: number; schemaComponent: string }>> {\n const activeVersion = await readActiveSchemaVersion(target, store.graphId);\n const schemaComponent = await computeSchemaHash(\n serializeSchema(store.graph, activeVersion),\n );\n return { activeVersion, schemaComponent };\n}\n\n/**\n * THE one owner of the content half of a live base version: the live-content\n * fingerprint, current identity assertions included, read through `target`.\n */\nasync function readLiveContentComponent<G extends GraphDef>(\n store: Store<G>,\n target: GraphBackend | TransactionBackend,\n): Promise<string> {\n return computeContentComponent(\n target,\n store.graphId,\n store.graph,\n await storeRuntime(store).identityAssertionsAtTarget(target, \"state\"),\n );\n}\n\n/**\n * THE one owner of base-version mode dispatch: revision-anchored when the store\n * tracks revisions, otherwise the live-content fingerprint (origin-namespaced\n * when lineage mints one). Reads are sequential because a pinned transaction\n * session must not overlap queries. `reads` names how the revision origin and\n * clock are read, the only members a caller varies.\n */\nasync function computeBaseVersionOn<G extends GraphDef>(\n store: Store<G>,\n target: GraphBackend | TransactionBackend,\n reads: RevisionAnchorReads,\n): Promise<BaseVersion> {\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 content branch below carries this version too, because an\n // otherwise identical schema round-trip still changes the committed cut.\n const { activeVersion, schemaComponent } = await readLiveSchemaHalf(\n store,\n target,\n );\n if (store.revisionTrackingEnabled) {\n const origin = await reads.mintOrigin();\n const revision = await reads.readRevision();\n return revisionBaseVersion(\n schemaComponent,\n activeVersion,\n origin,\n revision,\n );\n }\n // Without TypeGraph revision tracking, the complete graph fingerprint is\n // the commit-spanning fence, including current identity assertions.\n const contentComponent = await readLiveContentComponent(store, target);\n const originsSupported = recordedRevisionOriginsVerdict(\n storeBackend(store),\n ).supported;\n return contentBaseVersion(\n schemaComponent,\n activeVersion,\n contentComponent,\n mintsOriginNamespacedAnchor(store, originsSupported) ?\n await reads.mintOrigin()\n : undefined,\n );\n}\n\n/** Assembles the O(1) revision-anchored token; the one owner of that spelling. */\nfunction revisionBaseVersion(\n schemaComponent: string,\n activeVersion: number,\n origin: string,\n revision: string | undefined,\n): BaseVersion {\n return asBaseVersion(\n `${versionedSchemaComponent(schemaComponent, activeVersion)}${TOKEN_SEPARATOR}${revisionComponent(origin, revision)}`,\n );\n}\n\n/** Assembles the content-fingerprint token, origin-namespaced when lineage minted one. */\nfunction contentBaseVersion(\n schemaComponent: string,\n activeVersion: number,\n contentComponent: string,\n origin: string | undefined,\n): BaseVersion {\n const contentAnchor =\n origin === undefined ? contentComponent : (\n `${CONTENT_ORIGIN_PREFIX}${origin}:${contentComponent}`\n );\n return asBaseVersion(\n `${versionedSchemaComponent(schemaComponent, activeVersion)}${TOKEN_SEPARATOR}${contentAnchor}`,\n );\n}\n\n/** The observed component that disagrees with a stamped base version. */\nexport type BaseVersionTargetComparison =\n | Readonly<{ matches: true }>\n | Readonly<{\n matches: false;\n kind: \"schema\";\n expected: string;\n live: string;\n expectedActiveVersion: number | undefined;\n liveActiveVersion: number;\n }>\n | Readonly<{\n matches: false;\n kind: \"revision-origin\" | \"revision\" | \"content-origin\" | \"content\";\n expected: string | undefined;\n live: string | undefined;\n }>;\n\n/**\n * Compares a base token with graph state read through one pinned transaction.\n * The caller establishes the needed graph locks before invoking this reader.\n * Reading through `target` also avoids opening a second pool session while the\n * caller holds those locks.\n */\nexport async function compareBaseVersionAtTarget<G extends GraphDef>(\n store: Store<G>,\n target: TransactionBackend,\n expected: BaseVersion,\n): Promise<BaseVersionTargetComparison> {\n const { activeVersion, schemaComponent } = await readLiveSchemaHalf(\n store,\n target,\n );\n const liveSchema = versionedSchemaComponent(schemaComponent, activeVersion);\n const expectedSchema = schemaComponentOf(expected);\n if (liveSchema !== expectedSchema) {\n return {\n matches: false,\n kind: \"schema\",\n expected: expectedSchema,\n live: liveSchema,\n expectedActiveVersion: schemaActiveVersionOf(expected),\n liveActiveVersion: activeVersion,\n };\n }\n\n const reads = targetAnchorReads(store, target);\n if (hasRevisionAnchor(expected)) {\n const originMatch = await revisionOriginMatch(reads.readOrigin, expected);\n if (!originMatch.matches) {\n return {\n matches: false,\n kind: \"revision-origin\",\n expected: originMatch.expectedOrigin,\n live: originMatch.liveOrigin,\n };\n }\n const expectedRevision = revisionAnchorOf(expected);\n const liveRevision = await reads.readRevision();\n return liveRevision === expectedRevision ?\n { matches: true }\n : {\n matches: false,\n kind: \"revision\",\n expected: expectedRevision,\n live: liveRevision,\n };\n }\n\n const expectedOrigin = contentOriginOf(expected);\n if (expectedOrigin !== undefined) {\n const liveOrigin = await reads.readOrigin();\n if (liveOrigin !== expectedOrigin) {\n return {\n matches: false,\n kind: \"content-origin\",\n expected: expectedOrigin,\n live: liveOrigin,\n };\n }\n }\n const liveContent = await readLiveContentComponent(store, target);\n const expectedContent = contentFingerprintOf(expected);\n return liveContent === expectedContent ?\n { matches: true }\n : {\n matches: false,\n kind: \"content\",\n expected: expectedContent,\n live: liveContent,\n };\n}\n\n/** Parses the durable origin carried by a content-fingerprinted base token. */\nexport function contentOriginOf(version: BaseVersion): string | undefined {\n const component = contentComponentOf(version);\n if (!component.startsWith(CONTENT_ORIGIN_PREFIX)) return undefined;\n const separator = component.indexOf(\":\", CONTENT_ORIGIN_PREFIX.length);\n return separator === -1 ? undefined : (\n component.slice(CONTENT_ORIGIN_PREFIX.length, separator)\n );\n}\n\n/** Returns the graph-content digest from a content-fingerprinted token. */\nfunction contentFingerprintOf(version: BaseVersion): string {\n const component = contentComponentOf(version);\n if (!component.startsWith(CONTENT_ORIGIN_PREFIX)) return component;\n const separator = component.indexOf(\":\", CONTENT_ORIGIN_PREFIX.length);\n return separator === -1 ? component : component.slice(separator + 1);\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. The decoder also recognizes retired engine-anchor tokens, so\n * there is exactly one place that parses `<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/** 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 a previously minted engine-anchor token.\n * New tokens never use this form; the merge commit refuses it.\n */\nexport function engineAnchorOf(\n version: BaseVersion,\n): EngineRevision | undefined {\n return engineAnchorParts(version)?.revision;\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 origin-match decision for TypeGraph revision anchors: compare the\n * token's origin with the live origin `readOrigin` reads from the caller's own\n * session. Both the merge commit and lineage pruning use this comparison.\n * Returns the two values actually compared alongside the verdict, so a caller\n * that refuses on a mismatch embeds both in its own error `details` without a\n * second read.\n */\nasync function revisionOriginMatch(\n readOrigin: () => Promise<string | undefined>,\n expectedVersion: BaseVersion,\n): Promise<\n Readonly<{\n expectedOrigin: string | undefined;\n liveOrigin: string | undefined;\n matches: boolean;\n }>\n> {\n const expectedOrigin = revisionOriginOf(expectedVersion);\n const liveOrigin = await readOrigin();\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 * Whether `version` was minted in the retired NUL-separated format. Such a\n * token can never equal one a live store mints now, so every precondition\n * refuses it; callers use this only to say why.\n */\nexport function isLegacyBaseVersion(version: BaseVersion): boolean {\n return (version as string).includes(LEGACY_TOKEN_SEPARATOR);\n}\n\n/** Refusal details shared by every site that rejects a legacy token. */\nexport const LEGACY_BASE_VERSION_REFUSAL = {\n reason: \"legacy-token-format\",\n suggestion:\n \"This token was minted by an earlier TypeGraph release in a retired format. Re-branch or re-plan from the current target.\",\n} as const;\n\n/**\n * Index of the component separator, or -1 for a token with no schema\n * component. A legacy token parses as having none, so no anchor or schema\n * half is ever read out of it.\n */\nfunction tokenSeparatorIndex(version: BaseVersion): number {\n if (isLegacyBaseVersion(version)) return -1;\n return (version as string).indexOf(TOKEN_SEPARATOR);\n}\n\n/**\n * Extracts the second component from a `base@V` token. The schema component\n * contains no separator, so the substring after the separator is exactly the\n * durable revision or content fingerprint (possibly with its origin).\n *\n * Used by revision-token parsing and content-fingerprint re-validation.\n */\nexport function contentComponentOf(version: BaseVersion): string {\n const separatorIndex = tokenSeparatorIndex(version);\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.\n */\nexport function schemaComponentOf(version: BaseVersion): string {\n const separatorIndex = tokenSeparatorIndex(version);\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 current token's\n * schema half, or `undefined` for an older content token. The document hash\n * never contains `#s`\n * (hex digits only), so the tag position is unambiguous.\n *\n * Pairs with {@link readActiveSchemaVersion} inside the target commit\n * transaction so a schema round-trip cannot restore an older fence.\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 * TypeGraph revision anchors are answered directly through the recorded\n * relations. Content-fingerprinted and retired engine tokens return\n * `undefined`, selecting the complete diff.\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 () =>\n readRevisionOrigin(\n storeBackend(baseStore),\n baseStore.revisionSchema,\n baseStore.graphId,\n ),\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 return undefined;\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 * @param options - Set `revisionJournal: false` when the clone does not need\n * journal-backed changed-key lineage. This avoids installing journal\n * triggers on its tables. Set `refreshStatistics: false` for a short-lived\n * copy that will not benefit from refreshed query statistics.\n */\nexport function cloneWorkingCopyStrategy<G extends GraphDef>(\n makeBackend: MakeBackend,\n options: Readonly<{\n revisionJournal?: false;\n refreshStatistics?: false;\n }> = {},\n): WorkingCopyStrategy<G> {\n return cloneWorkingCopyWithGraphStrategy(\n makeBackend,\n (baseStore) => baseStore.graph,\n options,\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(\n makeBackend,\n (baseStore) => graphWithoutNodeUniqueness(baseStore.graph),\n { revisionJournal: false, refreshStatistics: false },\n );\n}\n\nfunction cloneWorkingCopyWithGraphStrategy<G extends GraphDef>(\n makeBackend: MakeBackend,\n graphForClone: (baseStore: Store<G>) => G,\n options: Readonly<{\n revisionJournal?: false;\n refreshStatistics?: false;\n }> = {},\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 ...(options.revisionJournal === false ?\n { revisionJournal: false as const }\n : {}),\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 ...(options.refreshStatistics === false ?\n { refreshStatistics: false as const }\n : {}),\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 */\nexport function 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 captureRevision = true,\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 = captureRevision ? resolveLineage(store) : undefined;\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","/**\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 allocation id, the owning\n * `graphId`, the branch id, the `base@V` token the working copy forked from, the at-fork\n * schema anchor (explicitly absent for an unmanaged store), the at-fork\n * engine revision when the working copy resolved `lineage`, and the\n * source recorded-time cut when history was captured.\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 `allocationId`/`graphId`/`definitionHash`/`base`/`branchId`/\n * `forkRevision`/`schemaAnchor`/`recordedForkPoint`, including DELETING\n * `schemaAnchor` from the\n * envelope, cannot relabel a fork, because the host's own record is the\n * reference. Allocation identity is independent of a caller-supplied branch\n * name, so even two allocations with the same branch id cannot be relabeled.\n * `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 { asRecordedInstant } from \"../core/temporal\";\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 { 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 RecordedForkPoint,\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/**\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 * allocation id, graph 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), plus the source\n * recorded-time cut when history was captured.\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 /** Unique identity of this physical allocation, independent of branch name. */\n allocationId: string;\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 recordedForkPoint?: RecordedForkPoint;\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 /** Unique identity of the sealed physical allocation. */\n allocationId: string;\n /** Stable strategy type tag; must equal the reopening strategy's `type`. */\n kind: string;\n /** Strategy locator format version; must be readable by the strategy. */\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 /** Source recorded-time cut, when the source captured history at fork time. */\n recordedForkPoint?: RecordedForkPoint;\n}>;\n\n/** A branch handle bound to the sealed physical allocation it opened. */\nexport type DurableGraphBranch<G extends GraphDef> = GraphBranch<G> &\n Readonly<{ allocationId: string }>;\n\n/** Persist `allocationId` before calling when host-side recovery is required. */\nexport type DurableBranchOptions = BranchOptions &\n Readonly<{ allocationId?: string | undefined }>;\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 under `allocationId` and\n * returns a mutable {@link Store} over it plus the opaque locator. An\n * allocation id MUST NOT name a second physical copy. If a previous\n * attempt may have allocated the id, the host MUST refuse `create` and\n * require explicit recovery through host tooling; it MUST NOT return a\n * sealed allocation as a newly created one. If it supplies\n * `forkRevision`, that revision MUST be captured atomically with the\n * physical fork; otherwise TypeGraph uses a full diff at merge time.\n * Once `create` resolves, TypeGraph owns the allocation and the 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. Every connection and transaction of the returned Store MUST stay\n * bound to this allocation's native branch; a checkout on one pooled session\n * is not evidence that later sessions read the same branch.\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 written by new descriptors. */\n version: number;\n /** Older locator versions every strategy method can still read and manage. */\n readableVersions?: readonly number[] | undefined;\n create: (\n baseStore: Store<G>,\n base: BaseVersion,\n branchId: BranchId,\n allocationId: string,\n ) => Promise<\n Readonly<{\n store: Store<G>;\n descriptor: TStoreDescriptor;\n access: DurableWorkingCopyAccess;\n forkRevision?: EngineRevision | undefined;\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 descriptorVersion: number,\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 descriptorVersion: number,\n ) => Promise<void>;\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 best effort or with callbacks that run outside the evidence\n * transaction. A callback the strategy runs inside that transaction is the\n * host's atomic mutation, not an emulation. 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: DurableGraphBranch<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?: DurableBranchOptions,\n): Promise<Result<DurableBranch<G, TStoreDescriptor>, BranchError>> {\n if (options?.allocationId !== undefined && options.id === undefined) {\n return err(\n new BranchError(\n \"A caller-supplied durable allocation id requires a stable branch id for retries.\",\n ),\n );\n }\n if (options?.allocationId === \"\") {\n return err(new BranchError(\"Durable allocation id must not be empty.\"));\n }\n let base: BaseVersion;\n let recordedForkPoint: RecordedForkPoint | undefined;\n let id: BranchId;\n let allocationId: string;\n try {\n base = await computeBaseVersion(baseStore);\n if (baseStore.historyEnabled) {\n const recorded = await baseStore.recordedNow();\n if (recorded !== undefined) recordedForkPoint = { recorded, base };\n }\n id = options?.id ?? asBranchId(generateId());\n allocationId = options?.allocationId ?? 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 forkRevision?: EngineRevision | undefined;\n }>;\n try {\n created = await strategy.create(baseStore, base, id, allocationId);\n } catch (error) {\n return err(\n new BranchError(\n \"Failed to create durable working-copy branch of base store. The host may have allocated it before reporting failure.\",\n {\n cause: error,\n details: { branchId: id, allocationId, strategyType: strategy.type },\n suggestion:\n \"Use the strategy's operator tooling to inspect and recover this allocation id before retrying.\",\n },\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 const captured = await readBranchForkState(created.store, false);\n forkState = { ...captured, forkRevision: created.forkRevision };\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 allocationId,\n graphId: created.store.graphId,\n definitionHash,\n branchId: id,\n base,\n schemaAnchor: forkState.schemaAnchor,\n forkRevision: forkState.forkRevision,\n ...(recordedForkPoint === undefined ? {} : { recordedForkPoint }),\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: DurableGraphBranch<G> = {\n allocationId: origin.allocationId,\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 ...(recordedForkPoint === undefined ? {} : { recordedForkPoint }),\n };\n const descriptor: DurableBranchDescriptor<TStoreDescriptor> = {\n allocationId: origin.allocationId,\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 ...(recordedForkPoint === undefined ? {} : { recordedForkPoint }),\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, {\n captureForkState: false,\n });\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<DurableGraphBranch<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(\n graph,\n descriptor.store,\n descriptor.version,\n );\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 descriptor.version,\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 * 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: Readonly<{\n type: string;\n version: number;\n readableVersions?: readonly number[] | undefined;\n }>,\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 (\n record[\"version\"] !== strategy.version &&\n !(\n typeof record[\"version\"] === \"number\" &&\n strategy.readableVersions?.includes(record[\"version\"])\n )\n ) {\n return new BranchError(\n `Durable branch descriptor version ${String(record[\"version\"])} is not supported by strategy \"${strategy.type}\".`,\n {\n details: {\n descriptorVersion: record[\"version\"],\n strategyVersion: strategy.version,\n readableVersions: strategy.readableVersions ?? [],\n },\n },\n );\n }\n for (const key of [\n \"allocationId\",\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 if (record[\"recordedForkPoint\"] !== undefined) {\n const point = record[\"recordedForkPoint\"];\n if (\n typeof point !== \"object\" ||\n point === null ||\n typeof (point as Readonly<Record<string, unknown>>)[\"recorded\"] !==\n \"string\" ||\n typeof (point as Readonly<Record<string, unknown>>)[\"base\"] !== \"string\"\n ) {\n return new BranchError(\n \"Durable branch descriptor is malformed: recordedForkPoint must be { recorded: string, base: string }.\",\n { details: { strategyType: strategy.type } },\n );\n }\n try {\n asRecordedInstant((point as Readonly<{ recorded: string }>).recorded);\n } catch (error) {\n return new BranchError(\n \"Durable branch descriptor has an invalid recorded fork instant.\",\n { cause: error, details: { strategyType: strategy.type } },\n );\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 allocationId: descriptor.allocationId,\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 ...(descriptor.recordedForkPoint === undefined ?\n {}\n : { recordedForkPoint: descriptor.recordedForkPoint }),\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.allocationId === attested.allocationId &&\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 recordedForkPointsEqual(\n descriptor.recordedForkPoint,\n attested.recordedForkPoint,\n )\n );\n}\n\nfunction recordedForkPointsEqual(\n left: DurableBranchOrigin[\"recordedForkPoint\"],\n right: DurableBranchOrigin[\"recordedForkPoint\"],\n): boolean {\n if (left === undefined || right === undefined) return left === right;\n return left.recorded === right.recorded && left.base === right.base;\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 *\n * Exported for a strategy that attaches a caller's graph to an allocation\n * without going through reopen (the PostgreSQL manager's operation members), so\n * this decision keeps one owner.\n */\nexport async 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): DurableGraphBranch<G> {\n return {\n allocationId: descriptor.allocationId,\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 ...(descriptor.recordedForkPoint === undefined ?\n {}\n : { recordedForkPoint: descriptor.recordedForkPoint }),\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"]}