@dbsp/core 3.3.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transition/canonical-json.ts","../src/transition/durably-loaded-run.ts","../src/transition/transition-lessor.ts","../src/transition/declaration.ts","../src/transition/minting.ts","../src/transition/stable-json.ts","../src/transition/lifecycle-interpreter.ts","../src/transition/outcome-protocol.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\n/** Raised when a value cannot cross the durable JSON payload boundary. */\nexport class CanonicalJsonError extends TypeError {\n\tconstructor(path: string, detail: string, options?: ErrorOptions) {\n\t\tsuper(`canonical JSON refuses ${path}: ${detail}`, options);\n\t\tthis.name = 'CanonicalJsonError';\n\t}\n}\n\n/**\n * Encodes a JSON value with lexically sorted object keys and preserved array\n * order. Unlike JSON.stringify, this refuses values it would omit or coerce.\n */\nexport function canonicalJson(value: unknown): string {\n\treturn encodeCanonicalJson(value, '$');\n}\n\n/** Hashes the canonical durable representation of a JSON payload. */\nexport function canonicalJsonDigest(value: unknown): string {\n\treturn createHash('sha256').update(canonicalJson(value)).digest('hex');\n}\n\nconst MAX_RENDERED_PATH_KEY = 160;\n\nfunction memberPath(path: string, key: string): string {\n\tconst rendered =\n\t\tkey.length <= MAX_RENDERED_PATH_KEY\n\t\t\t? key\n\t\t\t: `${key.slice(0, MAX_RENDERED_PATH_KEY)}…<truncated>`;\n\t// JSON bracket notation is deliberate: member keys never appear raw in a\n\t// diagnostic, and dots/control characters cannot impersonate path syntax.\n\treturn `${path}[${JSON.stringify(rendered)}]`;\n}\n\nfunction scalar(value: unknown, path: string): string | undefined {\n\tif (value === null) return 'null';\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\tcase 'boolean':\n\t\t\treturn JSON.stringify(value);\n\t\tcase 'number':\n\t\t\tif (!Number.isFinite(value))\n\t\t\t\tthrow new CanonicalJsonError(\n\t\t\t\t\tpath,\n\t\t\t\t\t'numbers must be finite JSON numbers',\n\t\t\t\t);\n\t\t\treturn JSON.stringify(value);\n\t\tcase 'undefined':\n\t\t\tthrow new CanonicalJsonError(path, 'undefined is not a JSON value');\n\t\tcase 'bigint':\n\t\tcase 'function':\n\t\tcase 'symbol':\n\t\t\tthrow new CanonicalJsonError(path, `${typeof value} is not a JSON value`);\n\t\tcase 'object':\n\t\t\treturn undefined;\n\t}\n}\n\n/** Reflection may invoke proxy traps; preserve the boundary's typed refusal. */\nfunction captureReflection<T>(path: string, capture: () => T): T {\n\ttry {\n\t\treturn capture();\n\t} catch (error) {\n\t\tthrow new CanonicalJsonError(path, 'reflection failed', { cause: error });\n\t}\n}\n\ntype EncodeTask =\n\t| { readonly kind: 'value'; readonly value: unknown; readonly path: string }\n\t| { readonly kind: 'text'; readonly text: string }\n\t| {\n\t\t\treadonly kind: 'close';\n\t\t\treadonly value: object;\n\t\t\treadonly text: ']' | '}';\n\t };\n\n/** Iterative so every refusal, including deep graphs and cycles, uses our error contract. */\nfunction encodeCanonicalJson(value: unknown, path: string): string {\n\tconst output: string[] = [];\n\tconst active = new WeakSet<object>();\n\tconst tasks: EncodeTask[] = [{ kind: 'value', value, path }];\n\twhile (tasks.length > 0) {\n\t\tconst task = tasks.pop();\n\t\tif (!task) continue;\n\t\tif (task.kind === 'text') {\n\t\t\toutput.push(task.text);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === 'close') {\n\t\t\tactive.delete(task.value);\n\t\t\toutput.push(task.text);\n\t\t\tcontinue;\n\t\t}\n\t\tconst encoded = scalar(task.value, task.path);\n\t\tif (encoded !== undefined) {\n\t\t\toutput.push(encoded);\n\t\t\tcontinue;\n\t\t}\n\t\tconst object = task.value as object;\n\t\tif (active.has(object))\n\t\t\tthrow new CanonicalJsonError(\n\t\t\t\ttask.path,\n\t\t\t\t'cyclic values are not JSON values',\n\t\t\t);\n\t\tactive.add(object);\n\t\tconst isArray = captureReflection(task.path, () => Array.isArray(object));\n\t\tif (isArray) {\n\t\t\tif (\n\t\t\t\tcaptureReflection(task.path, () => Object.getPrototypeOf(object)) !==\n\t\t\t\tArray.prototype\n\t\t\t)\n\t\t\t\tthrow new CanonicalJsonError(\n\t\t\t\t\ttask.path,\n\t\t\t\t\t'arrays require Array.prototype',\n\t\t\t\t);\n\t\t\tif (\n\t\t\t\tcaptureReflection(task.path, () => Object.getOwnPropertySymbols(object))\n\t\t\t\t\t.length > 0\n\t\t\t)\n\t\t\t\tthrow new CanonicalJsonError(\n\t\t\t\t\ttask.path,\n\t\t\t\t\t'symbol-keyed members are not JSON members',\n\t\t\t\t);\n\t\t\tfor (const key of captureReflection(task.path, () =>\n\t\t\t\tObject.getOwnPropertyNames(object),\n\t\t\t)) {\n\t\t\t\tif (key === 'length') continue;\n\t\t\t\tif (!/^(?:0|[1-9][0-9]*)$/u.test(key))\n\t\t\t\t\tthrow new CanonicalJsonError(\n\t\t\t\t\t\ttask.path,\n\t\t\t\t\t\t'array non-index members are not JSON members',\n\t\t\t\t\t);\n\t\t\t\tif (BigInt(key) > 4294967294n)\n\t\t\t\t\tthrow new CanonicalJsonError(\n\t\t\t\t\t\ttask.path,\n\t\t\t\t\t\t'array non-index members are not JSON members',\n\t\t\t\t\t);\n\t\t\t}\n\t\t\toutput.push('[');\n\t\t\ttasks.push({ kind: 'close', value: object, text: ']' });\n\t\t\tconst length = captureReflection(\n\t\t\t\ttask.path,\n\t\t\t\t() => (object as unknown[]).length,\n\t\t\t);\n\t\t\tfor (let index = length - 1; index >= 0; index -= 1) {\n\t\t\t\tconst itemPath = `${task.path}[${index}]`;\n\t\t\t\tconst descriptor = captureReflection(itemPath, () =>\n\t\t\t\t\tObject.getOwnPropertyDescriptor(object, String(index)),\n\t\t\t\t);\n\t\t\t\tif (!descriptor)\n\t\t\t\t\tthrow new CanonicalJsonError(\n\t\t\t\t\t\titemPath,\n\t\t\t\t\t\t'array holes are not JSON values',\n\t\t\t\t\t);\n\t\t\t\tif (!descriptor.enumerable || !('value' in descriptor))\n\t\t\t\t\tthrow new CanonicalJsonError(\n\t\t\t\t\t\titemPath,\n\t\t\t\t\t\t'array members must be enumerable data properties',\n\t\t\t\t\t);\n\t\t\t\tif (index < length - 1) tasks.push({ kind: 'text', text: ',' });\n\t\t\t\ttasks.push({ kind: 'value', value: descriptor.value, path: itemPath });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst prototype = captureReflection(task.path, () =>\n\t\t\tObject.getPrototypeOf(object),\n\t\t);\n\t\tif (prototype !== Object.prototype && prototype !== null)\n\t\t\tthrow new CanonicalJsonError(\n\t\t\t\ttask.path,\n\t\t\t\t'only plain objects are JSON objects',\n\t\t\t);\n\t\tif (\n\t\t\tcaptureReflection(task.path, () => Object.getOwnPropertySymbols(object))\n\t\t\t\t.length > 0\n\t\t)\n\t\t\tthrow new CanonicalJsonError(\n\t\t\t\ttask.path,\n\t\t\t\t'symbol-keyed members are not JSON members',\n\t\t\t);\n\t\tconst entries = Object.entries(\n\t\t\tcaptureReflection(task.path, () =>\n\t\t\t\tObject.getOwnPropertyDescriptors(object),\n\t\t\t),\n\t\t);\n\t\tfor (const [key, descriptor] of entries) {\n\t\t\tconst keyPath = memberPath(task.path, key);\n\t\t\tif (!descriptor.enumerable)\n\t\t\t\tthrow new CanonicalJsonError(\n\t\t\t\t\tkeyPath,\n\t\t\t\t\t'non-enumerable members are not JSON members',\n\t\t\t\t);\n\t\t\tif (!('value' in descriptor))\n\t\t\t\tthrow new CanonicalJsonError(\n\t\t\t\t\tkeyPath,\n\t\t\t\t\t'accessor members are not JSON values',\n\t\t\t\t);\n\t\t\tif (descriptor.value === undefined)\n\t\t\t\tthrow new CanonicalJsonError(keyPath, 'undefined is not a JSON value');\n\t\t}\n\t\tentries.sort(([left], [right]) =>\n\t\t\tleft < right ? -1 : left > right ? 1 : 0,\n\t\t);\n\t\toutput.push('{');\n\t\ttasks.push({ kind: 'close', value: object, text: '}' });\n\t\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\t\tconst entry = entries[index];\n\t\t\tif (!entry) continue;\n\t\t\tconst [key, descriptor] = entry;\n\t\t\tif (index < entries.length - 1) tasks.push({ kind: 'text', text: ',' });\n\t\t\ttasks.push({\n\t\t\t\tkind: 'value',\n\t\t\t\tvalue: descriptor.value,\n\t\t\t\tpath: memberPath(task.path, key),\n\t\t\t});\n\t\t\ttasks.push({ kind: 'text', text: `${JSON.stringify(key)}:` });\n\t\t}\n\t}\n\treturn output.join('');\n}\n","import type { TransitionRunMetadata } from '@dbsp/types';\n\ndeclare const durablyLoadedRunBrand: unique symbol;\n\n/**\n * Core-minted evidence that run metadata passed the execution entry boundary.\n * Its nominal member prevents accidental structural construction; the private\n * record keeps the runtime check meaningful when JavaScript is the caller.\n */\nexport interface DurablyLoadedRun {\n\treadonly metadata: Readonly<TransitionRunMetadata>;\n\treadonly [durablyLoadedRunBrand]: 'dbsp-durably-loaded-run';\n}\n\nconst durablyLoadedRuns = new WeakSet<object>();\n\nfunction frozenMetadata(\n\trun: TransitionRunMetadata,\n): Readonly<TransitionRunMetadata> {\n\treturn Object.freeze({ ...run });\n}\n\n/** Internal mint used only by the two core execution boundaries. */\nexport function mintDurablyLoadedRun(\n\trun: TransitionRunMetadata,\n): DurablyLoadedRun {\n\tconst witness = Object.freeze({\n\t\tmetadata: frozenMetadata(run),\n\t}) as DurablyLoadedRun;\n\tdurablyLoadedRuns.add(witness);\n\treturn witness;\n}\n\n/** Runtime authenticity check for trusted internal consumers. */\nexport function isDurablyLoadedRun(value: unknown): value is DurablyLoadedRun {\n\treturn (\n\t\tvalue != null &&\n\t\t(typeof value === 'object' || typeof value === 'function') &&\n\t\tdurablyLoadedRuns.has(value as object)\n\t);\n}\n","import type {\n\tExclusiveTransitionTarget,\n\tPlanAssessment,\n\tSemanticArtifactRef,\n\tTransitionLessor,\n\tTransitionQueryClient,\n\tTransitionSessionClient,\n} from '@dbsp/types';\n\nconst TRANSITION_LESSOR_BRAND = Symbol.for('dbsp.transition.lessor');\nconst TRANSITION_LESSOR_PROTOCOL_VERSION = 2;\nexport const TRANSITION_LESSOR_REJECTION =\n\t'transition target must be a core-minted lessor';\nconst TRANSITION_LESSOR_REJECTION_DETAIL =\n\t'The supplied transition target was refused because it is not a core-minted protocol-v2 lessor carrying a revocation capability.';\n\ntype LessorBrand = {\n\treadonly protocolVersion: number;\n\treadonly revocation: TransitionSessionRevocationPropagation;\n};\n\n/**\n * Every lease is checked here, once, at the runtime acquisition boundary. The\n * brand says the caller declared a source of leases; this captures the members\n * the engine will use before it relies on that declaration.\n *\n * A rejected acquisition never reaches a caller, so no `finally` upstream can\n * recover it. An acquisition without a usable `query()`/`release()` pair cannot\n * be used; when this boundary captured a callable `release()`, it uses that\n * path before rejecting. Otherwise, an adapter that opened a real connection\n * to acquire must close its own failure before returning, the way\n * createPgTransitionLessor does.\n */\ntype CapturedLease = {\n\treadonly raw: unknown;\n\treadonly query: (...args: readonly unknown[]) => unknown;\n\treadonly queryPlanOperation:\n\t\t| ((...args: readonly unknown[]) => unknown)\n\t\t| undefined;\n\treadonly release: (...args: readonly unknown[]) => unknown;\n};\n\n/** A lessor declared by a caller did not uphold the lease contract. */\nclass TransitionLessorContractRejection extends Error {\n\tconstructor(detail: string) {\n\t\tsuper(detail);\n\t\tthis.name = 'TransitionLessorContractRejection';\n\t}\n}\n\nasync function captureLease(value: unknown): Promise<CapturedLease> {\n\tconst { query, queryPlanOperation, release } = leaseMembers(value);\n\tif (typeof query !== 'function' || typeof release !== 'function') {\n\t\tconst rejection = new TransitionLessorContractRejection(\n\t\t\t'A transition lessor must acquire a lease exposing query() and release(). ' +\n\t\t\t\t'This acquisition returned an unusable member pair.',\n\t\t);\n\t\treleaseMalformedAcquisition(value, release, rejection);\n\t\tthrow rejection;\n\t}\n\treturn {\n\t\traw: value,\n\t\tquery: query as CapturedLease['query'],\n\t\tqueryPlanOperation:\n\t\t\ttypeof queryPlanOperation === 'function'\n\t\t\t\t? (queryPlanOperation as NonNullable<\n\t\t\t\t\t\tCapturedLease['queryPlanOperation']\n\t\t\t\t\t>)\n\t\t\t\t: undefined,\n\t\trelease: release as CapturedLease['release'],\n\t};\n}\n\n/** Return the safe operator-facing detail for a rejected lease contract. */\nexport function transitionLessorRejectionDetail(\n\terror: unknown,\n): string | undefined {\n\ttry {\n\t\treturn error instanceof TransitionLessorContractRejection\n\t\t\t? error.message\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** A core-owned lease: packs receive its session, while core retains release. */\nexport type TransitionLease = {\n\treadonly session: TransitionSessionClient;\n\treadonly release: (failure?: TransitionLeaseFailure) => Promise<void>;\n};\n\nconst planOperationQueries = new WeakMap<\n\tobject,\n\t(sql: string, params?: unknown) => Promise<unknown>\n>();\n/**\n * A brand transports this narrow peer hook across compatible core instances.\n * It is not this instance's authority: it is always invoked with the raw\n * physical client as its receiver, after this core has set its own latch.\n */\ntype TransitionSessionRevocationPropagation = Readonly<{\n\tcompromise(): void;\n\tisCompromised(): boolean;\n}>;\n\ntype TransitionSessionRevocationLatch = {\n\tcompromised: boolean;\n};\n\ntype TransitionSessionRevocationCapability = Readonly<{\n\tcompromise(): void;\n\tisCompromised(): boolean;\n}>;\n\nconst transitionSessionRevocations = new WeakMap<\n\tobject,\n\tTransitionSessionRevocationCapability\n>();\nconst transitionSessionLatches = new WeakMap<\n\tobject,\n\tTransitionSessionRevocationLatch\n>();\nconst physicalSessionRevocationLatches = new WeakMap<\n\tobject,\n\tTransitionSessionRevocationLatch\n>();\ntype RemintedLessorState = {\n\treadonly latch: TransitionSessionRevocationLatch;\n\treadonly revocation: TransitionSessionRevocationCapability;\n};\n\nconst remintedLessorStates = new WeakMap<object, RemintedLessorState>();\n\nfunction mintTransitionSessionRevocationLatch(): TransitionSessionRevocationLatch {\n\treturn { compromised: false };\n}\n\n/** Mint or resolve this core's one authoritative latch for a raw client. */\nfunction resolvePhysicalSessionRevocationLatch(\n\tphysicalSession: object,\n): TransitionSessionRevocationLatch {\n\tconst existing = physicalSessionRevocationLatches.get(physicalSession);\n\tif (existing) return existing;\n\tconst latch = mintTransitionSessionRevocationLatch();\n\tphysicalSessionRevocationLatches.set(physicalSession, latch);\n\treturn latch;\n}\n\n/**\n * Build the cross-instance side of a brand. Its receiver is intentionally the\n * physical session, so a lessor never has one broad revocation bit for all of\n * its pool clients.\n */\nfunction mintTransitionSessionRevocationPropagation(): TransitionSessionRevocationPropagation {\n\treturn Object.freeze({\n\t\tcompromise(this: unknown): void {\n\t\t\tif (!isObject(this)) return;\n\t\t\tresolvePhysicalSessionRevocationLatch(this).compromised = true;\n\t\t},\n\t\tisCompromised(this: unknown): boolean {\n\t\t\treturn (\n\t\t\t\tisObject(this) &&\n\t\t\t\tresolvePhysicalSessionRevocationLatch(this).compromised\n\t\t\t);\n\t\t},\n\t});\n}\n\n/**\n * Wrap a core-local latch with optional cross-instance propagation. The local\n * state is authoritative and changes before any peer code can run.\n */\nfunction mintTransitionSessionRevocation(\n\tlatch: TransitionSessionRevocationLatch,\n\tphysicalSession: object,\n\tpropagation: TransitionSessionRevocationPropagation,\n): TransitionSessionRevocationCapability {\n\treturn Object.freeze({\n\t\tcompromise(): void {\n\t\t\tlatch.compromised = true;\n\t\t\ttry {\n\t\t\t\tpropagation.compromise.call(physicalSession);\n\t\t\t} catch {\n\t\t\t\t// A foreign brand can add compromise, but it can never block this mark.\n\t\t\t}\n\t\t},\n\t\tisCompromised(): boolean {\n\t\t\tif (latch.compromised) return true;\n\t\t\ttry {\n\t\t\t\treturn propagation.isCompromised.call(physicalSession) === true;\n\t\t\t} catch {\n\t\t\t\t// A throwing peer is not evidence that this core's clean latch is dirty.\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t});\n}\n\nfunction revocationForTransitionSession(\n\tsession: TransitionSessionClient,\n): TransitionSessionRevocationCapability {\n\tconst revocation = transitionSessionRevocations.get(session as object);\n\tif (!revocation)\n\t\tthrow new Error(\n\t\t\t'transition session was not minted by the transition lessor',\n\t\t);\n\treturn revocation;\n}\n\nfunction latchForTransitionSession(\n\tsession: TransitionSessionClient,\n): TransitionSessionRevocationLatch {\n\tconst latch = transitionSessionLatches.get(session as object);\n\tif (!latch)\n\t\tthrow new Error(\n\t\t\t'transition session was not minted by the transition lessor',\n\t\t);\n\treturn latch;\n}\n\nfunction mintTransitionSession(\n\trevocation: TransitionSessionRevocationCapability,\n\tlatch: TransitionSessionRevocationLatch,\n\tquery: (\n\t\tsession: TransitionSessionClient,\n\t\tsql: string,\n\t\tparams?: unknown,\n\t) => unknown,\n): TransitionSessionClient {\n\tconst session = Object.freeze({\n\t\tquery: (sql: string, params?: unknown) => query(session, sql, params),\n\t}) as TransitionSessionClient;\n\ttransitionSessionRevocations.set(session as object, revocation);\n\ttransitionSessionLatches.set(session as object, latch);\n\treturn session;\n}\n\nfunction transitionSessionIsCompromised(\n\tsession: TransitionSessionClient,\n): boolean {\n\treturn revocationForTransitionSession(session).isCompromised();\n}\n\n/**\n * Read the revocation bit carried by a physical lease source.\n *\n * This is deliberately a boolean-only adapter seam: adapters retain the\n * physical lease through its final release, while core retains the token and\n * every logical wrapper that shares it. An unwrapped source has not been\n * leased, so it cannot have been marked compromised.\n */\nexport function transitionPhysicalSessionIsCompromised(\n\tphysicalSession: object,\n): boolean {\n\treturn (\n\t\tphysicalSessionRevocationLatches.get(physicalSession)?.compromised === true\n\t);\n}\n\nfunction compromisedTransitionSessionError(): Error {\n\treturn new Error('transition execution marked its leased client compromised');\n}\n\n/**\n * Outcome code may poison the current lease when a transport or protocol fault\n * leaves its backend unsafe for reuse. The release boundary consumes this bit\n * and returns the client with a truthy error so pg destroys it.\n */\nexport function markTransitionClientCompromised(\n\tsession: TransitionSessionClient,\n): void {\n\trevocationForTransitionSession(session).compromise();\n}\n\n/**\n * Mint the session passed to an operation's executeOperation() method.\n *\n * The returned client has the same narrow query surface as a normal session,\n * but its provenance is carried by the lease channel selected here, not by\n * recognizing the SQL text. A pack never receives the unwrapped session.\n */\nexport function planOperationSession(\n\tsession: TransitionSessionClient,\n): TransitionSessionClient {\n\tconst query = planOperationQueries.get(session as object);\n\tif (!query) return session;\n\tconst revocation = revocationForTransitionSession(session);\n\tconst latch = latchForTransitionSession(session);\n\treturn mintTransitionSession(\n\t\trevocation,\n\t\tlatch,\n\t\t(planSession, sql, params) => {\n\t\t\tif (transitionSessionIsCompromised(planSession)) {\n\t\t\t\treturn Promise.reject(compromisedTransitionSessionError());\n\t\t\t}\n\t\t\treturn query(sql, params);\n\t\t},\n\t);\n}\n\ntype ExclusiveTargetState = {\n\treadonly target: TransitionLessor;\n\treadonly isLive: () => boolean;\n};\n\nconst exclusiveTargets = new WeakMap<object, ExclusiveTargetState>();\n\n/**\n * Mint a durable target from an adapter-held exclusive lease.\n *\n * The adapter owns the liveness closure. Core retains the only lookup table,\n * so a durable caller cannot substitute a generic lessor or retain a target\n * after the adapter callback has finished.\n */\nexport function createExclusiveTransitionTarget(\n\ttarget: TransitionLessor,\n\tisLive: () => boolean,\n): ExclusiveTransitionTarget {\n\tif (!isTransitionLessor(target)) {\n\t\tthrow new Error(\n\t\t\t'exclusive transition target requires a core-minted lessor',\n\t\t);\n\t}\n\tconst exclusive = Object.freeze({});\n\texclusiveTargets.set(exclusive, { target, isLive });\n\treturn exclusive as ExclusiveTransitionTarget;\n}\n\n/** Recognize a core-minted exclusive durable target. */\nexport function isExclusiveTransitionTarget(\n\tvalue: unknown,\n): value is ExclusiveTransitionTarget {\n\treturn (\n\t\tvalue != null &&\n\t\t(typeof value === 'object' || typeof value === 'function') &&\n\t\texclusiveTargets.has(value as object)\n\t);\n}\n\n/** Acquire the callback-live lease underlying a durable execution target. */\nexport async function acquireExclusiveTransitionLease(\n\ttarget: ExclusiveTransitionTarget,\n): Promise<TransitionLease> {\n\tconst state = exclusiveTargets.get(target as object);\n\tif (!state?.isLive()) {\n\t\tthrow new Error(\n\t\t\t'exclusive transition target is only valid while its adapter lock callback is running',\n\t\t);\n\t}\n\tconst lease = await acquireTransitionLease(state.target);\n\tif (!state.isLive()) {\n\t\tawait lease.release({\n\t\t\terror: new Error(\n\t\t\t\t'exclusive transition target ended while acquiring its lease',\n\t\t\t),\n\t\t});\n\t\tthrow new Error(\n\t\t\t'exclusive transition target ended while acquiring its lease',\n\t\t);\n\t}\n\treturn lease;\n}\n\n/** A non-executing transition read may use either normal or exclusive access. */\nexport type TransitionReadTarget = TransitionLessor | ExclusiveTransitionTarget;\n\nexport function acquireTransitionTargetLease(\n\ttarget: TransitionReadTarget,\n): Promise<TransitionLease> {\n\treturn isTransitionLessor(target)\n\t\t? acquireTransitionLease(target)\n\t\t: acquireExclusiveTransitionLease(target);\n}\n\n/**\n * Cross the engine's acquisition boundary.\n *\n * A lessor brand is a declaration, not a security boundary, so every\n * acquisition is checked here even when a caller forged that declaration.\n */\nexport async function acquireTransitionLease(\n\ttarget: TransitionLessor,\n): Promise<TransitionLease> {\n\tif (!isTransitionLessor(target)) {\n\t\tthrow new Error(TRANSITION_LESSOR_REJECTION);\n\t}\n\tconst captured = await captureLease(await target.acquire());\n\tconst { raw, query, release } = captured;\n\tconst physicalSession = raw as object;\n\tconst reminted = remintedLessorStates.get(target as object);\n\tconst latch =\n\t\treminted?.latch ?? resolvePhysicalSessionRevocationLatch(physicalSession);\n\tif (reminted) {\n\t\tphysicalSessionRevocationLatches.set(physicalSession, reminted.latch);\n\t}\n\tconst revocation =\n\t\treminted?.revocation ??\n\t\tmintTransitionSessionRevocation(\n\t\t\tlatch,\n\t\t\tphysicalSession,\n\t\t\tlessorBrand(target).revocation,\n\t\t);\n\t/**\n\t * One bit, set before any driver code runs. The driver's `release()` is\n\t * called synchronously, so a driver that re-enters — or a consumer who wires\n\t * one to — observes this state rather than the state before it.\n\t */\n\tlet closed = false;\n\tconst session = mintTransitionSession(\n\t\trevocation,\n\t\tlatch,\n\t\t(leasedSession, sql, params) => {\n\t\t\t// The connection may already belong to another borrower, so this must\n\t\t\t// not reach the driver. Rejecting rather than throwing keeps the\n\t\t\t// contract a promise for a caller who only attaches a handler.\n\t\t\tif (closed) {\n\t\t\t\treturn Promise.reject(\n\t\t\t\t\tnew Error('transition lease was already given back'),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (transitionSessionIsCompromised(leasedSession)) {\n\t\t\t\treturn Promise.reject(compromisedTransitionSessionError());\n\t\t\t}\n\t\t\treturn query.call(raw, sql, params);\n\t\t},\n\t);\n\tif (captured.queryPlanOperation) {\n\t\tplanOperationQueries.set(session as object, (sql, params) =>\n\t\t\tPromise.resolve(\n\t\t\t\tcaptured.queryPlanOperation?.call(captured.raw, sql, params),\n\t\t\t),\n\t\t);\n\t}\n\t/**\n\t * Give this lease back. pg destroys a session released with an error instead\n\t * of pooling it, so the failure is passed through rather than dropped.\n\t *\n\t * Giving a lease back happens once. A second call is inert and answers with\n\t * a settled promise, so the failure the first caller reported is the one pg\n\t * sees, and a release that throws still leaves the lease closed. It is\n\t * deliberately not answered with the release already in flight: a driver\n\t * that hands that promise back as its own return value would make the\n\t * release wait on itself, forever, and hang every consumer's cleanup.\n\t *\n\t * #403: a cleanup failure must not mask the outcome the caller already\n\t * holds.\n\t *\n\t * The engine does not wait for cleanup either. `release` is declared to\n\t * return void — pg's returns nothing — but TypeScript lets an implementation\n\t * hand back a promise, so one is contained rather than awaited. Containment\n\t * is what keeps a rejection from surfacing unhandled after the call that\n\t * owned it returned; not awaiting is what keeps a promise the driver\n\t * invented outside the contract, and may never settle, from holding the\n\t * engine open.\n\t */\n\tconst releaseLease = (failure?: TransitionLeaseFailure): Promise<void> => {\n\t\tif (closed) {\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tclosed = true;\n\t\ttry {\n\t\t\tconst effectiveFailure =\n\t\t\t\tfailure ??\n\t\t\t\t(transitionSessionIsCompromised(session)\n\t\t\t\t\t? {\n\t\t\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t\t\t'transition execution marked its leased client compromised',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined);\n\t\t\tconst returned: unknown = effectiveFailure\n\t\t\t\t? release.call(raw, releaseArgument(effectiveFailure))\n\t\t\t\t: release.call(raw);\n\t\t\tvoid Promise.resolve(returned).catch(() => undefined);\n\t\t} catch {\n\t\t\t// A cleanup failure must not mask the outcome the caller already holds.\n\t\t}\n\t\treturn Promise.resolve();\n\t};\n\treturn Object.freeze({\n\t\tsession,\n\t\trelease: releaseLease,\n\t});\n}\n\n/**\n * Read both members once, treating a member that throws on read as absent.\n *\n * Inspecting the acquisition is itself part of the acquisition boundary: a\n * getter that throws must produce a rejection this function can still clean up\n * after, not an exception thrown past the only code holding the lease. `release`\n * is read first and separately, so a lease whose `query` is what misbehaves can\n * still be given back.\n */\nfunction leaseMembers(value: unknown): {\n\treadonly query: unknown;\n\treadonly queryPlanOperation: unknown;\n\treadonly release: unknown;\n} {\n\tif (\n\t\tvalue == null ||\n\t\t(typeof value !== 'object' && typeof value !== 'function')\n\t) {\n\t\treturn {\n\t\t\tquery: undefined,\n\t\t\tqueryPlanOperation: undefined,\n\t\t\trelease: undefined,\n\t\t};\n\t}\n\t// Capture the way back before reading anything else: a getter is caller code,\n\t// and one that runs first could remove the member this boundary needs to give\n\t// the lease back.\n\tconst release = readMember(value, 'release');\n\treturn {\n\t\tquery: readMember(value, 'query'),\n\t\tqueryPlanOperation: readMember(value, 'queryPlanOperation'),\n\t\trelease,\n\t};\n}\n\nfunction readMember(\n\tvalue: object,\n\tmember: 'query' | 'queryPlanOperation' | 'release',\n): unknown {\n\ttry {\n\t\treturn (value as Record<string, unknown>)[member];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Give back what a rejected acquisition holds, when it can be given back.\n *\n * Contained rather than awaited, on the same policy as a lease's own release: a\n * `release()` declared to return void is called for its effect, and a promise\n * returned against that contract gets a handler in this turn so it cannot\n * surface unhandled.\n */\nfunction releaseMalformedAcquisition(\n\tvalue: unknown,\n\trelease: unknown,\n\trejection: Error,\n): void {\n\tif (typeof release !== 'function') {\n\t\treturn;\n\t}\n\ttry {\n\t\tvoid Promise.resolve(release.call(value, rejection)).catch(() => undefined);\n\t} catch {\n\t\t// Reporting the malformed acquisition matters more than this cleanup.\n\t}\n}\n\n/**\n * Mint a declared source of transition leases.\n *\n * This declares a source of leases; it does not inspect individual\n * acquisitions. Every acquisition crosses `acquireTransitionLease`, the\n * runtime boundary that validates and captures it exactly once.\n *\n * The wrapper is allocated and frozen by core. Its non-writable,\n * non-configurable `Symbol.for('dbsp.transition.lessor')` brand carries this\n * protocol version, so independently installed incompatible core versions do\n * not accept one another's lessors. The global symbol is intentionally not a\n * security boundary: code already running in this realm can forge it. This\n * protects callers from passing the wrong connection object by accident.\n */\nexport function createTransitionLessor(\n\tacquire: () => Promise<TransitionQueryClient>,\n): TransitionLessor {\n\treturn mintTransitionLessor(acquire);\n}\n\n/**\n * Remint a lessor that can only ever borrow a session core already minted.\n *\n * This intentionally is not re-exported through either core barrel: durable\n * execution needs it to pin a preflight lease, while callers must never retain\n * or supply the revocation capability themselves.\n */\nexport function remintTransitionLessorFromSession(\n\tsession: TransitionSessionClient,\n\tacquire: () => Promise<TransitionQueryClient>,\n): TransitionLessor {\n\treturn mintTransitionLessor(acquire, {\n\t\tlatch: latchForTransitionSession(session),\n\t\trevocation: revocationForTransitionSession(session),\n\t});\n}\n\nfunction mintTransitionLessor(\n\tacquire: () => Promise<TransitionQueryClient>,\n\treminted?: RemintedLessorState,\n): TransitionLessor {\n\tconst lessor = { acquire };\n\tObject.defineProperty(lessor, TRANSITION_LESSOR_BRAND, {\n\t\tvalue: Object.freeze({\n\t\t\tprotocolVersion: TRANSITION_LESSOR_PROTOCOL_VERSION,\n\t\t\trevocation:\n\t\t\t\treminted?.revocation ?? mintTransitionSessionRevocationPropagation(),\n\t\t}),\n\t\twritable: false,\n\t\tconfigurable: false,\n\t});\n\tconst frozenLessor = Object.freeze(lessor) as TransitionLessor;\n\tif (reminted) {\n\t\tremintedLessorStates.set(frozenLessor as object, reminted);\n\t}\n\treturn frozenLessor;\n}\n\n/**\n * Recognize a core-minted transition lessor. The shape check only rejects a\n * contradictory declaration (a branded object without acquire()); the brand\n * and protocol version are the declaration.\n */\nexport function isTransitionLessor(value: unknown): value is TransitionLessor {\n\ttry {\n\t\tif (\n\t\t\tvalue == null ||\n\t\t\t(typeof value !== 'object' && typeof value !== 'function') ||\n\t\t\tArray.isArray(value)\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tconst brand = (value as Record<symbol, unknown>)[TRANSITION_LESSOR_BRAND];\n\t\treturn (\n\t\t\tbrand != null &&\n\t\t\ttypeof brand === 'object' &&\n\t\t\t(brand as LessorBrand).protocolVersion ===\n\t\t\t\tTRANSITION_LESSOR_PROTOCOL_VERSION &&\n\t\t\tisTransitionSessionRevocationCapability(\n\t\t\t\t(brand as LessorBrand).revocation,\n\t\t\t) &&\n\t\t\ttypeof (value as { readonly acquire?: unknown }).acquire === 'function'\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction lessorBrand(target: TransitionLessor): LessorBrand {\n\tconst brand = (target as unknown as Record<symbol, LessorBrand | undefined>)[\n\t\tTRANSITION_LESSOR_BRAND\n\t];\n\tif (!brand) throw new Error(TRANSITION_LESSOR_REJECTION);\n\treturn brand;\n}\n\nfunction isTransitionSessionRevocationCapability(\n\tvalue: unknown,\n): value is TransitionSessionRevocationPropagation {\n\treturn (\n\t\tvalue != null &&\n\t\ttypeof value === 'object' &&\n\t\tObject.isFrozen(value) &&\n\t\ttypeof (value as TransitionSessionRevocationPropagation).compromise ===\n\t\t\t'function' &&\n\t\ttypeof (value as TransitionSessionRevocationPropagation).isCompromised ===\n\t\t\t'function'\n\t);\n}\n\nfunction isObject(value: unknown): value is object {\n\treturn (\n\t\tvalue != null && (typeof value === 'object' || typeof value === 'function')\n\t);\n}\n\n/**\n * Carries the error that ended a lease's use. Its presence — not the value it\n * holds — is what says the lease is being returned after a failure.\n */\nexport type TransitionLeaseFailure = { readonly error: unknown };\n\n/** Raised in place of a falsy thrown value, so the session is still destroyed. */\nexport class TransitionLeaseFailureError extends Error {\n\tconstructor(cause: unknown) {\n\t\tsuper('transition lease released after a failure', { cause });\n\t\tthis.name = 'TransitionLeaseFailureError';\n\t}\n}\n\n/**\n * The value handed to `release()` when a lease is returned after a failure.\n *\n * pg decides whether to destroy a session or pool it by testing this argument\n * for truthiness, not for presence, so `throw undefined` — or `''`, `0`,\n * `false`, `null` — would release a poisoned session back into the pool for\n * reuse. A falsy failure is therefore carried inside a real Error, which keeps\n * the original value reachable as its `cause`.\n */\nfunction releaseArgument(failure: TransitionLeaseFailure): unknown {\n\treturn failure.error\n\t\t? failure.error\n\t\t: new TransitionLeaseFailureError(failure.error);\n}\n\n/** Builds the uniform entry-point result for an undeclared transition lessor. */\nexport function transitionLessorRejectionAssessment(\n\tartifact: SemanticArtifactRef,\n\tlifecycle: PlanAssessment['lifecycle'] = 'planned',\n\tdetail = TRANSITION_LESSOR_REJECTION_DETAIL,\n): PlanAssessment {\n\treturn {\n\t\tdecision: 'blocked',\n\t\tassurance: 'unproven',\n\t\tlifecycle,\n\t\tcontinuation: 'human-intervention-required',\n\t\treasons: [\n\t\t\t{\n\t\t\t\tcode: 'context-mismatch',\n\t\t\t\tartifact,\n\t\t\t\tfact: {\n\t\t\t\t\tkey: 'transition-lessor',\n\t\t\t\t\tvalue: TRANSITION_LESSOR_REJECTION,\n\t\t\t\t},\n\t\t\t\tdetail,\n\t\t\t\tscope: [],\n\t\t\t},\n\t\t],\n\t};\n}\n","import type {\n\tCatalogueIdentity,\n\tDeclarableKind,\n\tDeclarableResourceAddress,\n\tDeclarationSet,\n\tJsonValue,\n\tManagedDeclaration,\n\tModelIR,\n\tResourceAddress,\n} from '@dbsp/types';\nimport { canonicalResourceParent } from '@dbsp/types';\nimport { canonicalJson, canonicalJsonDigest } from './canonical-json.js';\nimport type { InProcessProvenPlan } from './index.js';\nimport { mintInProcessPlan } from './minting.js';\nimport { stableJson } from './stable-json.js';\n\nexport interface DeclarationAddressContext {\n\treadonly engine: string;\n\treadonly database: string;\n\treadonly schema: string;\n}\n\n/**\n * The declaration layer deliberately depends on this small structural naming\n * boundary rather than an adapter package. Callers pass the same strategy that\n * comparison and proof use for the target database.\n */\nexport interface DeclarationNamingStrategy {\n\ttoDatabase(identifier: string): string;\n}\n\nconst identityDeclarationNaming: DeclarationNamingStrategy = {\n\ttoDatabase: (identifier) => identifier,\n};\n\nfunction jsonError(path: string, detail: string): Error {\n\treturn new Error(\n\t\t`declaration is not canonicalizable JSON at ${path}: ${detail}`,\n\t);\n}\n\nfunction childPath(parent: string, key: string | number): string {\n\tif (typeof key === 'number') return `${parent}[${key}]`;\n\treturn /^[A-Za-z_$][\\w$]*$/u.test(key)\n\t\t? `${parent}.${key}`\n\t\t: `${parent}[${JSON.stringify(key)}]`;\n}\n\n/**\n * Reject every JavaScript value whose JSON representation is lossy or\n * host-dependent. JSON.stringify alone is unsuitable because it silently drops\n * functions and undefined object members, exactly the ColumnDef.default case.\n */\nexport function assertCanonicalizableJson(\n\tvalue: unknown,\n\tpath = '$',\n\tseen = new WeakSet<object>(),\n): asserts value is JsonValue {\n\tif (value === null || typeof value === 'string' || typeof value === 'boolean')\n\t\treturn;\n\tif (typeof value === 'number') {\n\t\tif (!Number.isFinite(value)) throw jsonError(path, 'number must be finite');\n\t\treturn;\n\t}\n\tif (typeof value !== 'object') {\n\t\tthrow jsonError(path, `found ${typeof value}`);\n\t}\n\tif (seen.has(value)) throw jsonError(path, 'cyclic value');\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\tif (!Object.hasOwn(value, index))\n\t\t\t\t\tthrow jsonError(childPath(path, index), 'array hole');\n\t\t\t\tassertCanonicalizableJson(value[index], childPath(path, index), seen);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tReflect.ownKeys(value).some(\n\t\t\t\t\t(key) =>\n\t\t\t\t\t\tkey !== 'length' &&\n\t\t\t\t\t\t!(typeof key === 'string' && /^(0|[1-9]\\d*)$/u.test(key)),\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow jsonError(path, 'array has a non-index property');\n\t\t\treturn;\n\t\t}\n\t\tif (Object.getPrototypeOf(value) !== Object.prototype)\n\t\t\tthrow jsonError(\n\t\t\t\tpath,\n\t\t\t\t`found ${value.constructor?.name ?? 'non-plain object'}`,\n\t\t\t);\n\t\tfor (const key of Reflect.ownKeys(value)) {\n\t\t\tif (typeof key !== 'string') throw jsonError(path, 'symbol key');\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor || 'get' in descriptor || 'set' in descriptor)\n\t\t\t\tthrow jsonError(childPath(path, key), 'accessor property');\n\t\t\tif (!descriptor.enumerable)\n\t\t\t\tthrow jsonError(childPath(path, key), 'non-enumerable property');\n\t\t\tassertCanonicalizableJson(descriptor.value, childPath(path, key), seen);\n\t\t}\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nfunction canonicalPayload(value: unknown, path: string): JsonValue {\n\tassertCanonicalizableJson(value, path);\n\treturn JSON.parse(canonicalJson(value)) as JsonValue;\n}\n\nfunction digest(value: JsonValue): string {\n\treturn canonicalJsonDigest(value);\n}\n\nfunction address<K extends DeclarableKind>(\n\tcontext: DeclarationAddressContext,\n\tkind: K,\n\tname: string,\n\tparent?: ResourceAddress,\n\tidentity?: CatalogueIdentity,\n): DeclarableResourceAddress<K> {\n\treturn {\n\t\tengine: context.engine,\n\t\tdatabase: context.database,\n\t\t...(kind === 'extension' ? {} : { schema: context.schema }),\n\t\t...(parent === undefined\n\t\t\t? {}\n\t\t\t: { parent: canonicalResourceParent(parent) }),\n\t\tkind,\n\t\tname,\n\t\t...(identity === undefined ? {} : { catalogueIdentity: identity }),\n\t};\n}\n\nfunction declaration<K extends DeclarableKind>(\n\tcontext: DeclarationAddressContext,\n\tkind: K,\n\tname: string,\n\tfragment: unknown,\n\tpath: string,\n\tparent?: ResourceAddress,\n): ManagedDeclaration<K> {\n\tconst canonical = canonicalPayload(fragment, path);\n\treturn {\n\t\taddress: address(context, kind, name, parent),\n\t\tfragment: canonical,\n\t\tdigest: digest(canonical),\n\t};\n}\n\nfunction optional<T>(key: string, value: T | undefined): Record<string, T> {\n\treturn value === undefined ? {} : { [key]: value };\n}\n\nfunction tableAddress(\n\tcontext: DeclarationAddressContext,\n\tname: string,\n): ResourceAddress {\n\treturn address(context, 'table', name);\n}\n\n/**\n * Slice only the declarable part of ModelIR. Deliberately absent are\n * logicalIdentity, pseudoColumns, comment, partition, rlsEnabled and policies;\n * their omission is encoded here once, rather than re-checked at every caller.\n */\nexport function declarationSetFromModel(\n\tmodel: ModelIR,\n\tcontext: DeclarationAddressContext,\n\tnaming: DeclarationNamingStrategy = identityDeclarationNaming,\n): DeclarationSet {\n\tconst declarations: ManagedDeclaration[] = [];\n\tconst toDatabase = (identifier: string) => naming.toDatabase(identifier);\n\tfor (const [tableKey, table] of [...model.tables].sort(([a], [b]) =>\n\t\ta < b ? -1 : a > b ? 1 : 0,\n\t)) {\n\t\tconst tablePath = `schema.tables[${JSON.stringify(tableKey)}]`;\n\t\tconst tableName = toDatabase(table.name);\n\t\tconst parent = tableAddress(context, tableName);\n\t\tdeclarations.push(\n\t\t\tdeclaration(context, 'table', tableName, { name: tableName }, tablePath),\n\t\t);\n\t\tfor (const [index, column] of table.columns.entries()) {\n\t\t\tconst fragment = {\n\t\t\t\tname: toDatabase(column.name),\n\t\t\t\ttype: column.type,\n\t\t\t\tnullable: column.nullable,\n\t\t\t\t...optional('js', column.js),\n\t\t\t\t...optional('default', column.default),\n\t\t\t\t...optional('originalDbType', column.originalDbType),\n\t\t\t\t...optional('originalDbTypeSchema', column.originalDbTypeSchema),\n\t\t\t\t...optional(\n\t\t\t\t\t'originalDbTypeSchemaScope',\n\t\t\t\t\tcolumn.originalDbTypeSchemaScope,\n\t\t\t\t),\n\t\t\t\t...optional('unique', column.unique),\n\t\t\t\t...optional('uniqueConstraintName', column.uniqueConstraintName),\n\t\t\t\t...optional('autoIncrement', column.autoIncrement),\n\t\t\t\t...optional('collation', column.collation),\n\t\t\t\t...optional('identity', column.identity),\n\t\t\t};\n\t\t\tdeclarations.push(\n\t\t\t\tdeclaration(\n\t\t\t\t\tcontext,\n\t\t\t\t\t'column',\n\t\t\t\t\ttoDatabase(column.name),\n\t\t\t\t\tfragment,\n\t\t\t\t\t`${tablePath}.columns[${index}]`,\n\t\t\t\t\tparent,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tfor (const [index, item] of table.indexes.entries()) {\n\t\t\t// These addresses are physical PostgreSQL names, shared with the\n\t\t\t// generator manifest. Positional pseudo-names cannot be adopted.\n\t\t\tconst physicalItem = {\n\t\t\t\t...item,\n\t\t\t\t...(item.name === undefined ? {} : { name: toDatabase(item.name) }),\n\t\t\t\tcolumns: item.columns.map(toDatabase),\n\t\t\t\t...(item.include === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { include: item.include.map(toDatabase) }),\n\t\t\t\t...(item.opclass === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\topclass: Object.fromEntries(\n\t\t\t\t\t\t\t\tObject.entries(item.opclass).map(([key, value]) => [\n\t\t\t\t\t\t\t\t\ttoDatabase(key),\n\t\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}),\n\t\t\t};\n\t\t\tconst name =\n\t\t\t\tphysicalItem.name ??\n\t\t\t\t`idx_${tableName}_${physicalItem.columns.join('_')}`;\n\t\t\tdeclarations.push(\n\t\t\t\tdeclaration(\n\t\t\t\t\tcontext,\n\t\t\t\t\t'index',\n\t\t\t\t\tname,\n\t\t\t\t\tphysicalItem,\n\t\t\t\t\t`${tablePath}.indexes[${index}]`,\n\t\t\t\t\tparent,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (table.primaryKey !== undefined) {\n\t\t\tconst columns =\n\t\t\t\ttypeof table.primaryKey === 'string'\n\t\t\t\t\t? toDatabase(table.primaryKey)\n\t\t\t\t\t: table.primaryKey.map(toDatabase);\n\t\t\tdeclarations.push(\n\t\t\t\tdeclaration(\n\t\t\t\t\tcontext,\n\t\t\t\t\t'constraint',\n\t\t\t\t\t`pk_${tableName}`,\n\t\t\t\t\t{ kind: 'primary-key', columns },\n\t\t\t\t\t`${tablePath}.primaryKey`,\n\t\t\t\t\tparent,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tfor (const [index, item] of table.foreignKeys.entries()) {\n\t\t\tconst physicalItem = {\n\t\t\t\t...item,\n\t\t\t\tcolumns: item.columns.map(toDatabase),\n\t\t\t\treferences: {\n\t\t\t\t\t...item.references,\n\t\t\t\t\ttable: toDatabase(item.references.table),\n\t\t\t\t\tcolumns: item.references.columns.map(toDatabase),\n\t\t\t\t},\n\t\t\t};\n\t\t\tdeclarations.push(\n\t\t\t\tdeclaration(\n\t\t\t\t\tcontext,\n\t\t\t\t\t'constraint',\n\t\t\t\t\t`fk_${tableName}_${physicalItem.columns.join('_')}`,\n\t\t\t\t\t{ kind: 'foreign-key', ...physicalItem },\n\t\t\t\t\t`${tablePath}.foreignKeys[${index}]`,\n\t\t\t\t\tparent,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tfor (const [index, item] of (table.checkConstraints ?? []).entries()) {\n\t\t\tconst physicalItem = { ...item, name: toDatabase(item.name) };\n\t\t\tdeclarations.push(\n\t\t\t\tdeclaration(\n\t\t\t\t\tcontext,\n\t\t\t\t\t'constraint',\n\t\t\t\t\tphysicalItem.name,\n\t\t\t\t\t{ kind: 'check', ...physicalItem },\n\t\t\t\t\t`${tablePath}.checkConstraints[${index}]`,\n\t\t\t\t\tparent,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\tfor (const [name, item] of [...(model.enums ?? new Map())].sort(([a], [b]) =>\n\t\ta < b ? -1 : a > b ? 1 : 0,\n\t)) {\n\t\tdeclarations.push(\n\t\t\tdeclaration(\n\t\t\t\tcontext,\n\t\t\t\t'enum',\n\t\t\t\ttoDatabase(name),\n\t\t\t\t{ ...item, name: toDatabase(item.name) },\n\t\t\t\t`schema.enums[${JSON.stringify(name)}]`,\n\t\t\t),\n\t\t);\n\t}\n\tfor (const [name, item] of [...(model.sequences ?? new Map())].sort(\n\t\t([a], [b]) => (a < b ? -1 : a > b ? 1 : 0),\n\t)) {\n\t\tdeclarations.push(\n\t\t\tdeclaration(\n\t\t\t\tcontext,\n\t\t\t\t'sequence',\n\t\t\t\ttoDatabase(name),\n\t\t\t\t{ ...item, name: toDatabase(item.name) },\n\t\t\t\t`schema.sequences[${JSON.stringify(name)}]`,\n\t\t\t),\n\t\t);\n\t}\n\tfor (const name of [...(model.extensions ?? [])].sort()) {\n\t\tdeclarations.push(\n\t\t\tdeclaration(\n\t\t\t\tcontext,\n\t\t\t\t'extension',\n\t\t\t\tname,\n\t\t\t\t{ name },\n\t\t\t\t`schema.extensions[${JSON.stringify(name)}]`,\n\t\t\t),\n\t\t);\n\t}\n\tconst canonicalDeclarations = declarations.sort((left, right) => {\n\t\tconst a = stableJson(left.address);\n\t\tconst b = stableJson(right.address);\n\t\treturn a < b ? -1 : a > b ? 1 : 0;\n\t});\n\tconst setValue = canonicalPayload(\n\t\t{ version: 1, declarations: canonicalDeclarations },\n\t\t'schema.declarations',\n\t);\n\treturn {\n\t\tversion: 1,\n\t\tdeclarations: canonicalDeclarations,\n\t\tdigest: digest(setValue),\n\t};\n}\n\n/** Validate the complete declarable surface before comparison can short-circuit plan time. */\nexport function validateDeclarationModel(model: ModelIR): void {\n\tdeclarationSetFromModel(model, {\n\t\tengine: 'declaration-validation',\n\t\tdatabase: 'declaration-validation',\n\t\tschema: 'declaration-validation',\n\t});\n}\n\n/** Compare only the recorded/live identity and retain the precise mismatch reason. */\nexport function admitRecordedIdentity(\n\trecorded: ResourceAddress,\n\tlive: ResourceAddress,\n): { readonly ok: true } | { readonly ok: false; readonly detail: string } {\n\tif (recorded.catalogueIdentity === undefined)\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `recorded address ${recorded.kind} ${recorded.name} has no catalogue identity`,\n\t\t};\n\tif (live.catalogueIdentity === undefined)\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `live address ${live.kind} ${live.name} has no catalogue identity`,\n\t\t};\n\tif (\n\t\tstableJson(recorded.catalogueIdentity) !==\n\t\tstableJson(live.catalogueIdentity)\n\t)\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `identity drift for ${recorded.kind} ${recorded.name}: recorded ${stableJson(recorded.catalogueIdentity)} does not match live ${stableJson(live.catalogueIdentity)}`,\n\t\t};\n\treturn { ok: true };\n}\n\n/** Attach the canonical declaration artifact before metadata/digest minting. */\nexport function bindDeclarationSet(\n\tplan: InProcessProvenPlan,\n\tdeclarations: DeclarationSet,\n): InProcessProvenPlan {\n\treturn mintInProcessPlan({ ...plan, declarations });\n}\n","import type { ProvenPlanShape } from '@dbsp/types';\nimport type { InProcessProvenPlan } from './index.js';\n\nconst minted = new WeakSet<object>();\n\nfunction isObject(value: unknown): value is object {\n\treturn (\n\t\t(typeof value === 'object' && value !== null) || typeof value === 'function'\n\t);\n}\n\nfunction childPath(parent: string, key: string | symbol): string {\n\tif (typeof key === 'symbol') {\n\t\treturn `${parent}[${String(key)}]`;\n\t}\n\tif (/^(0|[1-9]\\d*)$/.test(key)) {\n\t\treturn `${parent}[${key}]`;\n\t}\n\tif (/^[A-Za-z_$][\\w$]*$/.test(key)) {\n\t\treturn `${parent}.${key}`;\n\t}\n\treturn `${parent}[${JSON.stringify(key)}]`;\n}\n\nfunction kindOf(value: object): string {\n\tif (typeof value === 'function') {\n\t\treturn 'function';\n\t}\n\tif (value instanceof Map) {\n\t\treturn 'Map';\n\t}\n\tif (value instanceof Set) {\n\t\treturn 'Set';\n\t}\n\tif (value instanceof Date) {\n\t\treturn 'Date';\n\t}\n\tif (value instanceof RegExp) {\n\t\treturn 'RegExp';\n\t}\n\tif (ArrayBuffer.isView(value)) {\n\t\treturn 'typed array';\n\t}\n\tif (value instanceof ArrayBuffer) {\n\t\treturn 'ArrayBuffer';\n\t}\n\treturn value.constructor?.name ?? 'object';\n}\n\nfunction plainDataError(kind: string, path: string): Error {\n\treturn new Error(\n\t\t`a minted plan must be plain data; found ${kind} at ${path}`,\n\t);\n}\n\n/**\n * Whether `stableJson` will serialize this own key of an array. Its array branch\n * walks `0 .. length - 1` and reads nothing else, so the bound is the array's own\n * length rather than the language's array-index range: assigning `a[2 ** 32]`\n * leaves `length` untouched, which is exactly how a property stays readable by\n * the executor and absent from the digest.\n */\nfunction isVisibleArrayIndex(value: readonly unknown[], key: string): boolean {\n\tconst index = Number(key);\n\treturn (\n\t\tString(index) === key &&\n\t\tNumber.isInteger(index) &&\n\t\tindex >= 0 &&\n\t\tindex < value.length\n\t);\n}\n\nfunction assertPlainDataAndFreeze(\n\tvalue: unknown,\n\tpath: string,\n\tseen: WeakSet<object>,\n): void {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value === 'string' ||\n\t\ttypeof value === 'number' ||\n\t\ttypeof value === 'boolean' ||\n\t\ttypeof value === 'undefined'\n\t) {\n\t\treturn;\n\t}\n\tif (typeof value === 'bigint' || typeof value === 'symbol') {\n\t\tthrow plainDataError(typeof value, path);\n\t}\n\tif (!isObject(value)) {\n\t\treturn;\n\t}\n\tif (seen.has(value)) {\n\t\treturn;\n\t}\n\tseen.add(value);\n\tif (typeof value === 'function') {\n\t\tthrow plainDataError('function', path);\n\t}\n\tif (\n\t\tvalue instanceof Map ||\n\t\tvalue instanceof Set ||\n\t\tvalue instanceof Date ||\n\t\tvalue instanceof RegExp ||\n\t\tArrayBuffer.isView(value) ||\n\t\tvalue instanceof ArrayBuffer\n\t) {\n\t\tthrow plainDataError(kindOf(value), path);\n\t}\n\n\tlet prototype: object | null;\n\tlet keys: readonly (string | symbol)[];\n\ttry {\n\t\tprototype = Object.getPrototypeOf(value);\n\t\tkeys = Reflect.ownKeys(value);\n\t} catch (error) {\n\t\tthrow plainDataError(\n\t\t\terror instanceof Error ? `Proxy (${error.message})` : 'Proxy',\n\t\t\tpath,\n\t\t);\n\t}\n\n\tconst isPlainObject = prototype === Object.prototype;\n\tconst isPlainArray = Array.isArray(value) && prototype === Array.prototype;\n\tif (!isPlainObject && !isPlainArray) {\n\t\tthrow plainDataError(kindOf(value), path);\n\t}\n\n\tfor (const key of keys) {\n\t\tif (typeof key === 'symbol') {\n\t\t\tthrow plainDataError('symbol key', childPath(path, key));\n\t\t}\n\t\tlet descriptor: PropertyDescriptor | undefined;\n\t\ttry {\n\t\t\tdescriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t} catch (error) {\n\t\t\tthrow plainDataError(\n\t\t\t\terror instanceof Error ? `Proxy (${error.message})` : 'Proxy',\n\t\t\t\tchildPath(path, key),\n\t\t\t);\n\t\t}\n\t\tif (!descriptor) {\n\t\t\tcontinue;\n\t\t}\n\t\tif ('get' in descriptor || 'set' in descriptor) {\n\t\t\tthrow plainDataError('accessor', childPath(path, key));\n\t\t}\n\t\tif (isPlainObject && !descriptor.enumerable) {\n\t\t\t// This property is readable by execution code but invisible to stableJson\n\t\t\t// and JSON.stringify, so it could change the stored plan under one digest.\n\t\t\tthrow plainDataError('non-enumerable property', childPath(path, key));\n\t\t}\n\t\tif (isPlainArray && key !== 'length' && !isVisibleArrayIndex(value, key)) {\n\t\t\t// This property is readable by execution code but invisible to stableJson\n\t\t\t// and JSON.stringify, so it could change the stored plan under one digest.\n\t\t\tthrow plainDataError('named array property', childPath(path, key));\n\t\t}\n\t\tassertPlainDataAndFreeze(descriptor.value, childPath(path, key), seen);\n\t}\n\n\ttry {\n\t\tObject.freeze(value);\n\t} catch (error) {\n\t\tthrow plainDataError(\n\t\t\terror instanceof Error ? `Proxy (${error.message})` : 'Proxy',\n\t\t\tpath,\n\t\t);\n\t}\n}\n\nexport function mintInProcessPlan(shape: ProvenPlanShape): InProcessProvenPlan {\n\tassertPlainDataAndFreeze(shape, '$', new WeakSet<object>());\n\tminted.add(shape);\n\treturn shape as InProcessProvenPlan;\n}\n\nexport function isMintedInProcessPlan(\n\tplan: unknown,\n): plan is InProcessProvenPlan {\n\treturn isObject(plan) && minted.has(plan);\n}\n","function stableNumber(value: number): string {\n\tif (Number.isNaN(value)) {\n\t\treturn 'number:NaN';\n\t}\n\tif (Object.is(value, -0)) {\n\t\treturn 'number:-0';\n\t}\n\tif (value === Number.POSITIVE_INFINITY) {\n\t\treturn 'number:Infinity';\n\t}\n\tif (value === Number.NEGATIVE_INFINITY) {\n\t\treturn 'number:-Infinity';\n\t}\n\treturn `number:${value}`;\n}\n\nfunction objectTag(value: object): string {\n\treturn Object.prototype.toString.call(value);\n}\n\nfunction stableJsonInner(value: unknown, seen: WeakSet<object>): string {\n\tif (value === null) {\n\t\treturn 'null';\n\t}\n\tswitch (typeof value) {\n\t\tcase 'undefined':\n\t\t\treturn 'undefined';\n\t\tcase 'boolean':\n\t\t\treturn `boolean:${value ? 'true' : 'false'}`;\n\t\tcase 'number':\n\t\t\treturn stableNumber(value);\n\t\tcase 'bigint':\n\t\t\treturn `bigint:${value.toString()}`;\n\t\tcase 'string':\n\t\t\treturn `string:${JSON.stringify(value)}`;\n\t\tcase 'symbol':\n\t\t\treturn `symbol:${JSON.stringify(String(value.description ?? ''))}`;\n\t\tcase 'function':\n\t\t\treturn `function:${JSON.stringify(value.name)}`;\n\t\tcase 'object':\n\t\t\tbreak;\n\t}\n\n\tif (seen.has(value)) {\n\t\tthrow new TypeError('stableJson cannot serialize cyclic structures');\n\t}\n\tseen.add(value);\n\ttry {\n\t\tif (value instanceof Date) {\n\t\t\tconst time = value.getTime();\n\t\t\treturn Number.isNaN(time) ? 'date:Invalid' : `date:${time}`;\n\t\t}\n\t\tif (value instanceof RegExp) {\n\t\t\treturn `regexp:${JSON.stringify(value.source)}/${value.flags}`;\n\t\t}\n\t\tif (value instanceof Map) {\n\t\t\tconst entries = [...value.entries()]\n\t\t\t\t.map(\n\t\t\t\t\t([key, item]) =>\n\t\t\t\t\t\t`[${stableJsonInner(key, seen)},${stableJsonInner(item, seen)}]`,\n\t\t\t\t)\n\t\t\t\t.sort();\n\t\t\treturn `map:[${entries.join(',')}]`;\n\t\t}\n\t\tif (value instanceof Set) {\n\t\t\tconst entries = [...value.values()]\n\t\t\t\t.map((item) => stableJsonInner(item, seen))\n\t\t\t\t.sort();\n\t\t\treturn `set:[${entries.join(',')}]`;\n\t\t}\n\t\tif (Array.isArray(value)) {\n\t\t\tconst entries: string[] = [];\n\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\tentries.push(\n\t\t\t\t\tObject.hasOwn(value, index)\n\t\t\t\t\t\t? stableJsonInner(value[index], seen)\n\t\t\t\t\t\t: 'array-hole',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn `array:[${entries.join(',')}]`;\n\t\t}\n\t\tconst tag = objectTag(value);\n\t\tconst entries = Object.entries(value as Record<string, unknown>)\n\t\t\t// Code-unit order, never `localeCompare`: that one reads the host's\n\t\t\t// default locale, and `sv-SE` sorts `ä` after `z` where `en-US` sorts it\n\t\t\t// between `a` and `z`. This ordering decides the digest a durable\n\t\t\t// transition run is resumed against, so a locale-sensitive comparison\n\t\t\t// would make a plan persisted on one host unresumable on another.\n\t\t\t// This file is duplicated between @dbsp/core and @dbsp/adapter-pgsql\n\t\t\t// and the two must stay byte-identical: the digest core computes is\n\t\t\t// compared against plans this package serializes.\n\t\t\t.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n\t\t\t.map(\n\t\t\t\t([key, item]) =>\n\t\t\t\t\t`${JSON.stringify(key)}:${stableJsonInner(item, seen)}`,\n\t\t\t);\n\t\treturn `${tag}:{${entries.join(',')}}`;\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nexport function stableJson(value: unknown): string {\n\treturn stableJsonInner(value, new WeakSet());\n}\n","import {\n\tLEDGER_EVENT_KINDS,\n\ttype LedgerAddress,\n\ttype LedgerChainMember,\n\ttype LedgerChainProjection,\n\ttype LedgerClaimKind,\n\ttype LedgerHome,\n\ttype LedgerLifecycleGrammarColumn,\n\ttype LedgerOpenClaim,\n\ttype LedgerPayload,\n\ttype LedgerReportedState,\n\ttype LedgerStableState,\n\ttype ProjectedLedgerChain,\n\tsameLedgerAddress,\n\ttype UnprojectableChainReason,\n\ttype UnprojectableLedgerChain,\n} from '@dbsp/types';\n\n/** Bump whenever the malformed-chain vocabulary or interpretation changes. */\nexport const LEDGER_PROJECTION_CODE_VERSION = 1 as const;\n\n/**\n * The one closed grammar matrix. Later claim and token producers consume this\n * interpreter; they do not reconstruct lifecycle state from ledger spellings.\n */\nexport const LEDGER_LIFECYCLE_GRAMMAR: Readonly<\n\tRecord<LedgerClaimKind, LedgerLifecycleGrammarColumn>\n> = {\n\tintent: {\n\t\tclaimKind: 'intent',\n\t\topensFrom: ['unknown', 'managed', 'absent'],\n\t\tresolvesThrough: [\n\t\t\t'refused',\n\t\t\t'executing',\n\t\t\t'observed',\n\t\t\t'indeterminate',\n\t\t\t'resolved',\n\t\t],\n\t},\n\t'retire-intent': {\n\t\tclaimKind: 'retire-intent',\n\t\topensFrom: ['managed'],\n\t\tresolvesThrough: [\n\t\t\t'refused',\n\t\t\t'executing',\n\t\t\t'absent',\n\t\t\t'indeterminate',\n\t\t\t'resolved',\n\t\t],\n\t},\n\t'readdress-intent': {\n\t\tclaimKind: 'readdress-intent',\n\t\topensFrom: ['unknown', 'managed', 'absent'],\n\t\tresolvesThrough: [\n\t\t\t'refused',\n\t\t\t'indeterminate',\n\t\t\t'readdressed-to',\n\t\t\t'readdressed-from',\n\t\t],\n\t},\n\t'adopt-intent': {\n\t\tclaimKind: 'adopt-intent',\n\t\topensFrom: ['unknown'],\n\t\tresolvesThrough: ['refused', 'adopt'],\n\t},\n};\n\nconst CLAIM_KINDS = new Set<LedgerClaimKind>([\n\t'adopt-intent',\n\t'intent',\n\t'retire-intent',\n\t'readdress-intent',\n]);\n\ninterface LifecycleFrame {\n\treadonly stableState: LedgerStableState;\n\treadonly openClaim?: LedgerOpenClaim;\n}\n\ntype LifecycleStep =\n\t| { readonly kind: 'ok'; readonly frame: LifecycleFrame }\n\t| { readonly kind: 'invalid'; readonly detail: string };\n\nexport interface LedgerChainProjectionInput {\n\treadonly ledger: LedgerHome;\n\treadonly address: LedgerAddress;\n\treadonly events: readonly LedgerChainMember[];\n}\n\nfunction isLedgerEventKind(value: string): boolean {\n\treturn (LEDGER_EVENT_KINDS as readonly string[]).includes(value);\n}\n\nfunction invalid(detail: string): LifecycleStep {\n\treturn { kind: 'invalid', detail };\n}\n\nfunction requiresReadBack(\n\tevent: LedgerChainMember,\n\tlabel: string,\n): LifecycleStep | undefined {\n\tif (event.observed !== undefined) return undefined;\n\treturn invalid(`${label} requires its supporting read-back`);\n}\n\nfunction opensClaim(\n\tstableState: LedgerStableState,\n\tevent: LedgerChainMember,\n): LifecycleStep {\n\tif (!CLAIM_KINDS.has(event.eventKind as LedgerClaimKind)) {\n\t\treturn invalid(`event ${event.eventKind} cannot open a claim`);\n\t}\n\tconst claimKind = event.eventKind as LedgerClaimKind;\n\tconst column = LEDGER_LIFECYCLE_GRAMMAR[claimKind];\n\tif (!column.opensFrom.includes(stableState)) {\n\t\treturn invalid(`${claimKind} cannot open from stable state ${stableState}`);\n\t}\n\tif (claimKind === 'readdress-intent' && !event.pairId) {\n\t\treturn invalid('readdress-intent requires a pair id');\n\t}\n\treturn {\n\t\tkind: 'ok',\n\t\tframe: {\n\t\t\tstableState,\n\t\t\topenClaim: {\n\t\t\t\tevent,\n\t\t\t\tkind: claimKind,\n\t\t\t\tstableStateBeforeClaim: stableState,\n\t\t\t\tphase: 'claimed',\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction resolveStableState(\n\tclaim: LedgerOpenClaim,\n\tevent: LedgerChainMember,\n): LedgerStableState {\n\tif (claim.kind === 'intent')\n\t\treturn event.observed === undefined\n\t\t\t? claim.stableStateBeforeClaim\n\t\t\t: 'managed';\n\treturn event.observed === undefined ? 'absent' : 'managed';\n}\n\n/** Interprets exactly one terminal-to-next lifecycle edge. */\nexport function interpretLedgerLifecycle(\n\tframe: LifecycleFrame,\n\tevent: LedgerChainMember,\n): LifecycleStep {\n\tif (frame.openClaim === undefined && event.eventKind === 'released') {\n\t\t// LedgerEventKind is closed at fourteen spellings and has no\n\t\t// release-intent member. Until unit 13 supplies its claim protocol,\n\t\t// released is the atomic managed-to-unknown event in that vocabulary.\n\t\tif (frame.stableState !== 'managed')\n\t\t\treturn invalid('released requires a managed stable state');\n\t\treturn { kind: 'ok', frame: { stableState: 'unknown' } };\n\t}\n\tif (frame.openClaim === undefined)\n\t\treturn opensClaim(frame.stableState, event);\n\n\tconst claim = frame.openClaim;\n\tconst allowed = LEDGER_LIFECYCLE_GRAMMAR[claim.kind].resolvesThrough;\n\tif (!allowed.includes(event.eventKind)) {\n\t\treturn invalid(\n\t\t\t`${event.eventKind} is not in the ${claim.kind} resolution column`,\n\t\t);\n\t}\n\n\tswitch (event.eventKind) {\n\t\tcase 'refused':\n\t\t\tif (claim.phase === 'indeterminate')\n\t\t\t\treturn invalid('refused cannot close an indeterminate claim');\n\t\t\treturn { kind: 'ok', frame: { stableState: frame.stableState } };\n\t\tcase 'executing':\n\t\t\tif (claim.phase !== 'claimed')\n\t\t\t\treturn invalid('executing may follow only a newly opened claim');\n\t\t\treturn {\n\t\t\t\tkind: 'ok',\n\t\t\t\tframe: {\n\t\t\t\t\tstableState: frame.stableState,\n\t\t\t\t\topenClaim: { ...claim, phase: 'executing' },\n\t\t\t\t},\n\t\t\t};\n\t\tcase 'observed': {\n\t\t\tconst readBack = requiresReadBack(event, 'observed');\n\t\t\tif (readBack) return readBack;\n\t\t\tif (claim.phase === 'indeterminate')\n\t\t\t\treturn invalid('observed cannot close an indeterminate claim');\n\t\t\treturn { kind: 'ok', frame: { stableState: 'managed' } };\n\t\t}\n\t\tcase 'absent':\n\t\t\tif (claim.phase === 'indeterminate')\n\t\t\t\treturn invalid('absent cannot close an indeterminate claim');\n\t\t\treturn { kind: 'ok', frame: { stableState: 'absent' } };\n\t\tcase 'indeterminate':\n\t\t\tif (claim.phase === 'indeterminate')\n\t\t\t\treturn invalid('indeterminate may be appended only once');\n\t\t\treturn {\n\t\t\t\tkind: 'ok',\n\t\t\t\tframe: {\n\t\t\t\t\tstableState: frame.stableState,\n\t\t\t\t\topenClaim: { ...claim, phase: 'indeterminate' },\n\t\t\t\t},\n\t\t\t};\n\t\tcase 'resolved': {\n\t\t\tif (claim.phase !== 'indeterminate')\n\t\t\t\treturn invalid('resolved closes only an indeterminate claim');\n\t\t\t// A payload establishes managed. An absence read-back has no catalogue\n\t\t\t// shape to persist in LedgerChainMember, so its stable outcome is the\n\t\t\t// non-managed arm of the originating claim column.\n\t\t\treturn {\n\t\t\t\tkind: 'ok',\n\t\t\t\tframe: { stableState: resolveStableState(claim, event) },\n\t\t\t};\n\t\t}\n\t\tcase 'adopt': {\n\t\t\tconst readBack = requiresReadBack(event, 'adopt');\n\t\t\tif (readBack) return readBack;\n\t\t\treturn { kind: 'ok', frame: { stableState: 'managed' } };\n\t\t}\n\t\tcase 'readdressed-to':\n\t\t\tif (claim.stableStateBeforeClaim !== 'managed')\n\t\t\t\treturn invalid('readdressed-to resolves only a managed source');\n\t\t\tif (event.pairId !== claim.event.pairId)\n\t\t\t\treturn invalid('readdressed-to pair id does not match its claim');\n\t\t\treturn { kind: 'ok', frame: { stableState: 'unknown' } };\n\t\tcase 'readdressed-from': {\n\t\t\tconst readBack = requiresReadBack(event, 'readdressed-from');\n\t\t\tif (readBack) return readBack;\n\t\t\tif (claim.stableStateBeforeClaim === 'managed')\n\t\t\t\treturn invalid('readdressed-from resolves only an unoccupied target');\n\t\t\tif (event.pairId !== claim.event.pairId)\n\t\t\t\treturn invalid('readdressed-from pair id does not match its claim');\n\t\t\treturn { kind: 'ok', frame: { stableState: 'managed' } };\n\t\t}\n\t\tdefault:\n\t\t\treturn invalid(`${event.eventKind} cannot resolve a claim`);\n\t}\n}\n\nfunction unprojectable(\n\tinput: LedgerChainProjectionInput,\n\treason: UnprojectableChainReason,\n): UnprojectableLedgerChain {\n\treturn {\n\t\tkind: 'unprojectable-ledger-chain',\n\t\tledger: input.ledger,\n\t\taddress: input.address,\n\t\tevents: input.events,\n\t\treason,\n\t\tcodeVersion: LEDGER_PROJECTION_CODE_VERSION,\n\t};\n}\n\nfunction reportState(frame: LifecycleFrame): LedgerReportedState {\n\tif (frame.openClaim === undefined) return { kind: frame.stableState };\n\treturn frame.openClaim.phase === 'indeterminate'\n\t\t? {\n\t\t\t\tkind: 'blocked',\n\t\t\t\tstableState: frame.stableState,\n\t\t\t\tclaim: frame.openClaim,\n\t\t\t}\n\t\t: {\n\t\t\t\tkind: 'pending',\n\t\t\t\tstableState: frame.stableState,\n\t\t\t\tclaim: frame.openClaim,\n\t\t\t};\n}\n\nfunction projected(\n\tinput: LedgerChainProjectionInput,\n\tframe: LifecycleFrame,\n\tdeclaration: LedgerPayload | undefined,\n\tobservation: LedgerPayload | undefined,\n): ProjectedLedgerChain {\n\treturn {\n\t\tkind: 'projected-ledger-chain',\n\t\tledger: input.ledger,\n\t\taddress: input.address,\n\t\tevents: input.events,\n\t\tstableState: frame.stableState,\n\t\t...(frame.openClaim === undefined ? {} : { openClaim: frame.openClaim }),\n\t\treportedState: reportState(frame),\n\t\t...(declaration === undefined ? {} : { declaration }),\n\t\t...(observation === undefined ? {} : { observation }),\n\t};\n}\n\n/**\n * Projects a whole address chain without using insertion order. Malformed\n * chains deliberately return a structured value so mutation callers fail\n * closed while readers retain the evidence needed to diagnose it.\n */\nexport function projectLedgerChain(\n\tinput: LedgerChainProjectionInput,\n): LedgerChainProjection {\n\tconst byId = new Map<string, LedgerChainMember>();\n\tconst children = new Map<string | undefined, LedgerChainMember[]>();\n\tfor (const event of input.events) {\n\t\tif (!sameLedgerAddress(input.address, event.address))\n\t\t\treturn unprojectable(input, {\n\t\t\t\tcode: 'address-mismatch',\n\t\t\t\teventId: event.eventId,\n\t\t\t});\n\t\tif (!isLedgerEventKind(event.eventKind))\n\t\t\treturn unprojectable(input, {\n\t\t\t\tcode: 'unknown-event-kind',\n\t\t\t\teventId: event.eventId,\n\t\t\t\teventKind: event.eventKind,\n\t\t\t});\n\t\tif (byId.has(event.eventId))\n\t\t\treturn unprojectable(input, {\n\t\t\t\tcode: 'duplicate-event-id',\n\t\t\t\teventId: event.eventId,\n\t\t\t});\n\t\tbyId.set(event.eventId, event);\n\t\tconst siblings = children.get(event.predecessor) ?? [];\n\t\tsiblings.push(event);\n\t\tchildren.set(event.predecessor, siblings);\n\t}\n\n\tfor (const event of input.events) {\n\t\tif (event.predecessor !== undefined && !byId.has(event.predecessor)) {\n\t\t\treturn unprojectable(input, {\n\t\t\t\tcode: 'missing-predecessor',\n\t\t\t\teventId: event.eventId,\n\t\t\t\tpredecessor: event.predecessor,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const [predecessor, siblings] of children) {\n\t\tif (siblings.length > 1)\n\t\t\treturn unprojectable(input, {\n\t\t\t\tcode: 'fork',\n\t\t\t\t...(predecessor === undefined ? {} : { predecessor }),\n\t\t\t\teventIds: siblings.map((event) => event.eventId),\n\t\t\t});\n\t}\n\n\tconst roots = children.get(undefined) ?? [];\n\tif (roots.length > 1)\n\t\treturn unprojectable(input, {\n\t\t\tcode: 'fork',\n\t\t\teventIds: roots.map((event) => event.eventId),\n\t\t});\n\tif (input.events.length > 0 && roots.length === 0)\n\t\treturn unprojectable(input, {\n\t\t\tcode: 'cycle',\n\t\t\teventIds: input.events.map((event) => event.eventId),\n\t\t});\n\n\tlet frame: LifecycleFrame = { stableState: 'unknown' };\n\tlet declaration: LedgerPayload | undefined;\n\tlet observation: LedgerPayload | undefined;\n\tlet current = roots[0];\n\tconst visited = new Set<string>();\n\twhile (current !== undefined) {\n\t\tif (visited.has(current.eventId))\n\t\t\treturn unprojectable(input, {\n\t\t\t\tcode: 'cycle',\n\t\t\t\teventIds: [...visited, current.eventId],\n\t\t\t});\n\t\tvisited.add(current.eventId);\n\t\tconst step = interpretLedgerLifecycle(frame, current);\n\t\tif (step.kind === 'invalid')\n\t\t\treturn unprojectable(input, {\n\t\t\t\tcode: 'invalid-lifecycle-edge',\n\t\t\t\teventId: current.eventId,\n\t\t\t\tdetail: step.detail,\n\t\t\t});\n\t\tframe = step.frame;\n\t\tif (current.declared !== undefined) declaration = current.declared;\n\t\tif (current.observed !== undefined) observation = current.observed;\n\t\tcurrent = children.get(current.eventId)?.[0];\n\t}\n\n\tif (visited.size !== input.events.length)\n\t\treturn unprojectable(input, {\n\t\t\tcode: 'cycle',\n\t\t\teventIds: input.events\n\t\t\t\t.filter((event) => !visited.has(event.eventId))\n\t\t\t\t.map((event) => event.eventId),\n\t\t});\n\treturn projected(input, frame, declaration, observation);\n}\n","import { createHash } from 'node:crypto';\nimport type {\n\tClaimBundleStatement,\n\tClaimStatementBundle,\n\tClaimToken,\n\tLedgerAddress,\n\tLedgerChainMember,\n\tOutcomeClaimAdmission,\n\tOutcomeClaimAdmissionInput,\n\tOutcomeClaimPlan,\n\tOutcomeProtocolRefusal,\n\tOutcomeRecoveryClassification,\n\tOutcomeRecoveryInput,\n\tOutcomeRecoveryReadBack,\n} from '@dbsp/types';\nimport * as transitionTypes from '@dbsp/types';\nimport { refusalFor, sameLedgerAddress } from '@dbsp/types';\nimport { admitRecordedIdentity } from './declaration.js';\nimport { LEDGER_LIFECYCLE_GRAMMAR } from './lifecycle-interpreter.js';\nimport { stableJson } from './stable-json.js';\n\ninterface ClaimTokenRecord {\n\treadonly claimId: string;\n\treadonly bundle: ClaimStatementBundle;\n\tconsumed: boolean;\n}\n\nconst tokenRecords = new WeakMap<object, ClaimTokenRecord>();\n\ntype ControllerIdentity = { readonly name: string; readonly oid: string };\ntype ControllerIdentityHelper = (\n\trecorded: ControllerIdentity,\n\tcurrent: ControllerIdentity,\n) => boolean;\n\nconst sameControllerIdentity =\n\t(\n\t\ttransitionTypes as typeof transitionTypes & {\n\t\t\treadonly sameControllerIdentity?: ControllerIdentityHelper;\n\t\t}\n\t).sameControllerIdentity ??\n\t((recorded, current) =>\n\t\trecorded.name === current.name && recorded.oid === current.oid);\n\n/**\n * Return the sole terminal member by predecessor topology, or undefined when\n * the chain has zero or multiple terminals. This remains linear for large\n * durable chains and centralizes the protocol's exactly-one-terminal rule.\n */\nexport function findUniqueLedgerTerminal<\n\tT extends {\n\t\treadonly eventId: string;\n\t\treadonly predecessor?: string;\n\t},\n>(events: readonly T[]): T | undefined {\n\tconst predecessors = new Set<string>();\n\tfor (const event of events) {\n\t\tif (event.predecessor !== undefined) predecessors.add(event.predecessor);\n\t}\n\tlet terminal: T | undefined;\n\tfor (const event of events) {\n\t\tif (predecessors.has(event.eventId)) continue;\n\t\tif (terminal !== undefined) return undefined;\n\t\tterminal = event;\n\t}\n\treturn terminal;\n}\n\n/**\n * The sole durable identity builder for a managed outcome claim. An address\n * is the stable chain key, while the claim id is execution-scoped:\n * hash(executionId, plannedClaimKey, address[, closureMemberKey]). Hashing the\n * canonical representation keeps the persisted identifier opaque, compact,\n * and free of serializer type tags.\n */\nexport function outcomeClaimId(\n\texecutionId: string,\n\tplannedClaimKey: string,\n\taddress: LedgerAddress,\n\tclosureMemberKey?: string,\n): string {\n\treturn `dbsp.transition.outcome.${createHash('sha256')\n\t\t.update(\n\t\t\tstableJson({ executionId, plannedClaimKey, address, closureMemberKey }),\n\t\t)\n\t\t.digest('hex')}`;\n}\n\n/** Resolution and progress ids cannot collide across execution attempts either. */\nexport function outcomeClaimEventId(claimId: string, role: string): string {\n\treturn `dbsp.transition.outcome.${createHash('sha256')\n\t\t.update(stableJson({ claimId, role }))\n\t\t.digest('hex')}`;\n}\n\nfunction refusal(reason: string): OutcomeProtocolRefusal {\n\treturn { kind: 'outcome-protocol-refused', reason };\n}\n\nfunction bundleRefusal(\n\tplan: OutcomeClaimPlan,\n): OutcomeProtocolRefusal | undefined {\n\tconst statements = plan.statementBundle.statements;\n\tif (plan.claimSpecies === 'cascade-covered') {\n\t\tif (statements.length !== 0)\n\t\t\treturn refusal(\n\t\t\t\t`cascade-covered claim ${plan.claimId} has a non-empty statement bundle`,\n\t\t\t);\n\t\treturn undefined;\n\t}\n\tif (plan.claimSpecies === 'adoption') {\n\t\tif (plan.claimKind !== 'adopt-intent' || statements.length !== 0)\n\t\t\treturn refusal(\n\t\t\t\t`adoption claim ${plan.claimId} has an invalid statement bundle`,\n\t\t\t);\n\t\treturn undefined;\n\t}\n\tif (statements.length === 0)\n\t\treturn refusal(`claim ${plan.claimId} has an empty statement bundle`);\n\tfor (let index = 0; index < statements.length; index += 1) {\n\t\tconst statement = statements[index];\n\t\tif (!statement || statement.ordinal !== index || statement.sql.length === 0)\n\t\t\treturn refusal(\n\t\t\t\t`claim ${plan.claimId} has an invalid statement bundle at ordinal ${index}`,\n\t\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction fixedBundle(bundle: ClaimStatementBundle): ClaimStatementBundle {\n\treturn Object.freeze({\n\t\tstatements: Object.freeze(\n\t\t\tbundle.statements.map((statement) =>\n\t\t\t\tObject.freeze({ ordinal: statement.ordinal, sql: statement.sql }),\n\t\t\t),\n\t\t),\n\t});\n}\n\n/**\n * The sole token producer. The documented package API does not expose managed\n * DDL or ledger-append primitives; capability checks prevent accidental\n * bypass within supported integrations. This is not a security boundary\n * against code already running in this Node process or a database role\n * authorized to issue DDL or write ledger tables.\n */\nexport function mintClaimToken(plan: OutcomeClaimPlan): ClaimToken {\n\tconst token = Object.freeze({}) as ClaimToken;\n\ttokenRecords.set(token, {\n\t\tclaimId: plan.claimId,\n\t\tbundle: fixedBundle(plan.statementBundle),\n\t\tconsumed: false,\n\t});\n\treturn token;\n}\n\n/**\n * Reads the claim identity of a core-minted capability without exposing its\n * bundle or giving callers a way to mint one.\n */\nexport function claimIdForToken(token: ClaimToken): string | undefined {\n\treturn tokenRecords.get(token)?.claimId;\n}\n\n/**\n * Consumes exactly one planned statement. The PostgreSQL execution sink calls\n * this immediately before it sends SQL, after it has verified the claim is\n * still open in the ledger.\n */\nexport function consumeClaimToken(\n\ttoken: ClaimToken,\n\tclaimId: string,\n\tstatements: readonly ClaimBundleStatement[],\n): ClaimStatementBundle | OutcomeProtocolRefusal {\n\tconst record = tokenRecords.get(token);\n\tif (!record) return refusal('claim token was not minted by claim admission');\n\tif (record.claimId !== claimId)\n\t\treturn refusal(\n\t\t\t`claim token belongs to claim ${record.claimId}, not ${claimId}`,\n\t\t);\n\tif (record.consumed)\n\t\treturn refusal(\n\t\t\t`claim token for claim ${claimId} has already been consumed`,\n\t\t);\n\tif (\n\t\tstatements.length !== record.bundle.statements.length ||\n\t\tstatements.some((statement, index) => {\n\t\t\tconst expected = record.bundle.statements[index];\n\t\t\treturn (\n\t\t\t\texpected === undefined ||\n\t\t\t\texpected.ordinal !== statement.ordinal ||\n\t\t\t\texpected.sql !== statement.sql\n\t\t\t);\n\t\t})\n\t)\n\t\treturn refusal(`statements are outside claim ${claimId}'s recorded bundle`);\n\trecord.consumed = true;\n\treturn record.bundle;\n}\n\n/**\n * Admits an open claim from the one lifecycle grammar, and mints the execution\n * token only after the chain and plan-time bundle have both passed.\n */\nexport function admitOutcomeClaim(\n\tinput: OutcomeClaimAdmissionInput,\n): OutcomeClaimAdmission {\n\tconst { plan, projection } = input;\n\tconst bundleError = bundleRefusal(plan);\n\tif (bundleError) return bundleError;\n\tif (projection.kind !== 'projected-ledger-chain')\n\t\treturn refusal(\n\t\t\t`claim ${plan.claimId} refuses malformed ledger chain: ${projection.reason.code}`,\n\t\t);\n\tif (!sameLedgerAddress(plan.address, projection.address))\n\t\treturn refusal(\n\t\t\t`claim ${plan.claimId} address does not match its ledger chain`,\n\t\t);\n\tif (projection.openClaim !== undefined)\n\t\treturn refusal(\n\t\t\t`claim ${plan.claimId} refuses open claim ${projection.openClaim.event.eventId}`,\n\t\t);\n\tconst column = LEDGER_LIFECYCLE_GRAMMAR[plan.claimKind];\n\tif (!column.opensFrom.includes(projection.stableState))\n\t\treturn refusal(\n\t\t\t`${plan.claimKind} cannot open from stable state ${projection.stableState}`,\n\t\t);\n\tif (projection.stableState === 'managed' && plan.requiresVacancy !== true) {\n\t\tconst terminal = findUniqueLedgerTerminal(projection.events);\n\t\tif (!terminal)\n\t\t\treturn refusal(\n\t\t\t\t`claim ${plan.claimId} refuses managed chain without terminal`,\n\t\t\t);\n\t\tconst currentController = (\n\t\t\tinput as OutcomeClaimAdmissionInput & {\n\t\t\t\treadonly currentController?: ControllerIdentity;\n\t\t\t}\n\t\t).currentController;\n\t\tconst controllerOid = (\n\t\t\tterminal as LedgerChainMember & {\n\t\t\t\treadonly controllerOid?: string;\n\t\t\t}\n\t\t).controllerOid;\n\t\tif (currentController) {\n\t\t\tif (!controllerOid)\n\t\t\t\treturn refusal(\n\t\t\t\t\t`claim ${plan.claimId} refuses managed controller without recorded OID`,\n\t\t\t\t);\n\t\t\tif (\n\t\t\t\t!sameControllerIdentity(\n\t\t\t\t\t{ name: terminal.controller, oid: controllerOid },\n\t\t\t\t\tcurrentController,\n\t\t\t\t)\n\t\t\t)\n\t\t\t\treturn refusal(\n\t\t\t\t\t`claim ${plan.claimId} refuses managed-by-other controller ${terminal.controller}`,\n\t\t\t\t);\n\t\t} else\n\t\t\treturn refusal(\n\t\t\t\t`claim ${plan.claimId} refuses unreadable current controller identity`,\n\t\t\t);\n\t\tif (!input.liveAddress)\n\t\t\treturn refusal(\n\t\t\t\t`claim ${plan.claimId} refuses missing live identity admission`,\n\t\t\t);\n\t\tconst recorded = terminal.catalogueIdentity\n\t\t\t? { ...plan.address, catalogueIdentity: terminal.catalogueIdentity }\n\t\t\t: plan.address;\n\t\tconst identity = admitRecordedIdentity(recorded, input.liveAddress);\n\t\tif (!identity.ok) return refusal(identity.detail);\n\t}\n\treturn {\n\t\tkind: 'admitted-outcome-claim',\n\t\tplan,\n\t\tstableStateBeforeClaim: projection.stableState,\n\t\ttoken: mintClaimToken(plan),\n\t};\n}\n\nfunction recoveryPending(\n\tinput: OutcomeRecoveryInput,\n\treason: string,\n\treasonCode?: 'catalogue-unavailable',\n): OutcomeRecoveryClassification {\n\treturn {\n\t\tkind: 'outcome-recovery-pending',\n\t\taddress: input.projection.address,\n\t\treason,\n\t\t...(reasonCode === undefined ? {} : { reasonCode }),\n\t};\n}\n\nfunction appendRecovery(\n\tinput: OutcomeRecoveryInput,\n\treadBack: OutcomeRecoveryReadBack,\n\teventKind: 'refused' | 'observed' | 'absent' | 'indeterminate' | 'resolved',\n\treason: string,\n): OutcomeRecoveryClassification {\n\tconst projection = input.projection;\n\tif (projection.kind !== 'projected-ledger-chain')\n\t\treturn {\n\t\t\tkind: 'outcome-recovery-malformed-chain',\n\t\t\taddress: projection.address,\n\t\t\treason: projection.reason.code,\n\t\t};\n\tconst claim = projection.openClaim;\n\tconst predecessor = findUniqueLedgerTerminal(projection.events);\n\tif (!claim || !predecessor)\n\t\treturn recoveryPending(\n\t\t\tinput,\n\t\t\t'recovery could not identify the open claim terminal',\n\t\t);\n\treturn {\n\t\tkind: 'outcome-recovery-append',\n\t\taddress: projection.address,\n\t\tresolution: {\n\t\t\teventKind,\n\t\t\tpredecessor: predecessor.eventId,\n\t\t\trootClaimId: claim.event.eventId,\n\t\t\treason,\n\t\t\treadBack,\n\t\t\t...(eventKind === 'refused'\n\t\t\t\t? {\n\t\t\t\t\t\trefusal: refusalFor('ERR-11', {\n\t\t\t\t\t\t\taddress: projection.address,\n\t\t\t\t\t\t\tstate: projection.stableState,\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t},\n\t};\n}\n\n/**\n * Classifies one open outcome-protocol claim from a fresh catalogue read.\n * It never issues DDL; its only mutation instruction is an append for the\n * adapter to perform after the read has completed. Calling this once per\n * address deliberately keeps interrupted closures independently recoverable.\n */\nexport async function classifyOutcomeRecovery(\n\tinput: OutcomeRecoveryInput,\n): Promise<OutcomeRecoveryClassification> {\n\tconst projection = input.projection;\n\tif (projection.kind !== 'projected-ledger-chain')\n\t\treturn {\n\t\t\tkind: 'outcome-recovery-malformed-chain',\n\t\t\taddress: projection.address,\n\t\t\treason: projection.reason.code,\n\t\t};\n\tif (projection.openClaim === undefined)\n\t\treturn {\n\t\t\tkind: 'outcome-recovery-no-open-claim',\n\t\t\taddress: projection.address,\n\t\t};\n\n\tconst claim = projection.openClaim;\n\tif (claim.phase === 'indeterminate') {\n\t\tif (!input.resolveIndeterminate)\n\t\t\treturn {\n\t\t\t\tkind: 'outcome-recovery-blocked',\n\t\t\t\taddress: projection.address,\n\t\t\t\treason:\n\t\t\t\t\t'indeterminate claim remains blocked until resolved with a read-back',\n\t\t\t};\n\t\tconst evidence = input.indeterminateEvidence;\n\t\tif (\n\t\t\tevidence === undefined ||\n\t\t\tevidence.claimId !== claim.event.eventId ||\n\t\t\tevidence.executionId !== claim.event.executionId ||\n\t\t\tevidence.plannedClaimKey !== claim.event.plannedClaimKey ||\n\t\t\tevidence.persistedBundleDigest !== evidence.admittedBundleDigest ||\n\t\t\tevidence.planDigest !== evidence.externalDdlExclusion.planDigest ||\n\t\t\t!sameLedgerAddress(\n\t\t\t\tevidence.externalDdlExclusion.address,\n\t\t\t\tprojection.address,\n\t\t\t)\n\t\t)\n\t\t\treturn {\n\t\t\t\tkind: 'outcome-recovery-blocked',\n\t\t\t\taddress: projection.address,\n\t\t\t\treason:\n\t\t\t\t\t'indeterminate claim refuses a missing or mismatched admission envelope',\n\t\t\t};\n\t}\n\n\t// The envelope gates indeterminate reconciliation before it is allowed to\n\t// consult an operation-specific read-back. A failed read remains pending,\n\t// including a claim that has not reached DDL.\n\tconst readBack = await input.catalogue(projection.address);\n\tif (readBack.kind === 'catalogue-unavailable')\n\t\treturn recoveryPending(input, readBack.reason, 'catalogue-unavailable');\n\n\tif (claim.phase === 'indeterminate') {\n\t\t// `applied` means the operation compared this claim's recorded expected\n\t\t// declaration/identity to its own address's live shape field-by-field;\n\t\t// generic same-name presence proves only that a name exists.\n\t\tif (readBack.effect !== 'applied')\n\t\t\treturn {\n\t\t\t\tkind: 'outcome-recovery-blocked',\n\t\t\t\taddress: projection.address,\n\t\t\t\treason:\n\t\t\t\t\t'indeterminate claim requires an operation-specific applied read-back',\n\t\t\t};\n\t\tif (claim.kind === 'intent') {\n\t\t\tif (readBack.kind === 'present')\n\t\t\t\treturn appendRecovery(\n\t\t\t\t\tinput,\n\t\t\t\t\treadBack,\n\t\t\t\t\t'resolved',\n\t\t\t\t\t'resolved intent is supported by the catalogue read-back',\n\t\t\t\t);\n\t\t\tif (claim.stableStateBeforeClaim !== 'managed')\n\t\t\t\treturn appendRecovery(\n\t\t\t\t\tinput,\n\t\t\t\t\treadBack,\n\t\t\t\t\t'resolved',\n\t\t\t\t\t'resolved intent absence is supported by the catalogue read-back',\n\t\t\t\t);\n\t\t\treturn {\n\t\t\t\tkind: 'outcome-recovery-blocked',\n\t\t\t\taddress: projection.address,\n\t\t\t\treason:\n\t\t\t\t\t'catalogue absence cannot resolve an indeterminate modify intent to managed',\n\t\t\t};\n\t\t}\n\t\tif (claim.kind === 'retire-intent')\n\t\t\treturn appendRecovery(\n\t\t\t\tinput,\n\t\t\t\treadBack,\n\t\t\t\t'resolved',\n\t\t\t\treadBack.kind === 'absent'\n\t\t\t\t\t? 'resolved retirement absence is supported by the catalogue read-back'\n\t\t\t\t\t: 'resolved retirement is supported by the catalogue read-back',\n\t\t\t);\n\t\treturn {\n\t\t\tkind: 'outcome-recovery-blocked',\n\t\t\taddress: projection.address,\n\t\t\treason: `indeterminate ${claim.kind} has no resolved grammar column`,\n\t\t};\n\t}\n\n\tif (claim.phase === 'claimed')\n\t\treturn appendRecovery(\n\t\t\tinput,\n\t\t\treadBack,\n\t\t\t'refused',\n\t\t\t'recovery read live state before refusing a claim that never reached executing',\n\t\t);\n\n\tif (claim.kind === 'intent') {\n\t\t// A committed executing marker records only that the sender was allowed to\n\t\t// proceed; it does not prove that SQL left the process. Catalogue absence\n\t\t// is therefore decisive evidence that this creation was not issued. Test\n\t\t// this before an operation-specific verifier: a verifier can only call the\n\t\t// present-object case unverifiable (for example an invalid concurrent index).\n\t\tif (readBack.kind === 'absent')\n\t\t\treturn appendRecovery(\n\t\t\t\tinput,\n\t\t\t\treadBack,\n\t\t\t\t'refused',\n\t\t\t\t'recovery read-back proves no effect after executing',\n\t\t\t);\n\t\t// A managed alteration can keep its catalogue object while doing nothing.\n\t\t// When the operation's own postcondition observation proves its expected\n\t\t// before-state, that is stronger than generic catalogue presence.\n\t\tif (readBack.effect === 'no-effect')\n\t\t\treturn appendRecovery(\n\t\t\t\tinput,\n\t\t\t\treadBack,\n\t\t\t\t'refused',\n\t\t\t\t'recovery operation read-back proves no effect after executing',\n\t\t\t);\n\t\tif (readBack.effect === 'unverifiable')\n\t\t\treturn recoveryPending(\n\t\t\t\tinput,\n\t\t\t\t'recovery operation read-back cannot verify effect after executing',\n\t\t\t);\n\t\tif (\n\t\t\tclaim.stableStateBeforeClaim === 'managed' &&\n\t\t\treadBack.effect !== 'applied'\n\t\t)\n\t\t\treturn recoveryPending(\n\t\t\t\tinput,\n\t\t\t\t'recovery executing managed modification requires an operation-specific applied read-back',\n\t\t\t);\n\t\tif (\n\t\t\tclaim.stableStateBeforeClaim !== 'managed' &&\n\t\t\t!input.acceptedExternalDdlExclusion\n\t\t)\n\t\t\treturn appendRecovery(\n\t\t\t\tinput,\n\t\t\t\treadBack,\n\t\t\t\t'indeterminate',\n\t\t\t\t'create read-back requires claim-bound external-ddl-exclusion and operation postcondition evidence',\n\t\t\t);\n\t\treturn appendRecovery(\n\t\t\tinput,\n\t\t\treadBack,\n\t\t\t'observed',\n\t\t\t'recovery observed the live catalogue read-back after executing',\n\t\t);\n\t}\n\tif (claim.kind === 'retire-intent') {\n\t\tif (readBack.kind === 'absent')\n\t\t\treturn appendRecovery(\n\t\t\t\tinput,\n\t\t\t\treadBack,\n\t\t\t\t'absent',\n\t\t\t\t'recovery observed retirement absence after executing',\n\t\t\t);\n\t\treturn recoveryPending(\n\t\t\tinput,\n\t\t\t'retirement remains unverifiable because the catalogue object is present',\n\t\t);\n\t}\n\n\t// Readdress and adopt never have an executing edge in their own grammar.\n\treturn recoveryPending(\n\t\tinput,\n\t\t`executing ${claim.kind} is not a recoverable lifecycle edge`,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAGpB,IAAM,qBAAN,cAAiC,UAAU;AAAA,EACjD,YAAY,MAAc,QAAgB,SAAwB;AACjE,UAAM,0BAA0B,IAAI,KAAK,MAAM,IAAI,OAAO;AAC1D,SAAK,OAAO;AAAA,EACb;AACD;AAMO,SAAS,cAAc,OAAwB;AACrD,SAAO,oBAAoB,OAAO,GAAG;AACtC;AAGO,SAAS,oBAAoB,OAAwB;AAC3D,SAAO,WAAW,QAAQ,EAAE,OAAO,cAAc,KAAK,CAAC,EAAE,OAAO,KAAK;AACtE;AAEA,IAAM,wBAAwB;AAE9B,SAAS,WAAW,MAAc,KAAqB;AACtD,QAAM,WACL,IAAI,UAAU,wBACX,MACA,GAAG,IAAI,MAAM,GAAG,qBAAqB,CAAC;AAG1C,SAAO,GAAG,IAAI,IAAI,KAAK,UAAU,QAAQ,CAAC;AAC3C;AAEA,SAAS,OAAO,OAAgB,MAAkC;AACjE,MAAI,UAAU,KAAM,QAAO;AAC3B,UAAQ,OAAO,OAAO;AAAA,IACrB,KAAK;AAAA,IACL,KAAK;AACJ,aAAO,KAAK,UAAU,KAAK;AAAA,IAC5B,KAAK;AACJ,UAAI,CAAC,OAAO,SAAS,KAAK;AACzB,cAAM,IAAI;AAAA,UACT;AAAA,UACA;AAAA,QACD;AACD,aAAO,KAAK,UAAU,KAAK;AAAA,IAC5B,KAAK;AACJ,YAAM,IAAI,mBAAmB,MAAM,+BAA+B;AAAA,IACnE,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACJ,YAAM,IAAI,mBAAmB,MAAM,GAAG,OAAO,KAAK,sBAAsB;AAAA,IACzE,KAAK;AACJ,aAAO;AAAA,EACT;AACD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AAAA,EACD;AAEA,MAAI,MAAM,UAAU;AACnB,WAAO;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAED,MAAI,MAAM,SAAS,UAAU;AAM5B,QAAI,SAAS,SAAS;AACrB,aAAO;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACD;AAID,QAAI,SAAS,WAAW;AACvB,aAAO;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACD;AACD,QAAI,SAAS,WAAW;AACvB,aAAO;AAAA,QACN;AAAA,QACA;AAAA,MACD;AACD,QACC,MAAM,2BAA2B,aACjC,SAAS,WAAW;AAEpB,aAAO;AAAA,QACN;AAAA,QACA;AAAA,MACD;AACD,QACC,MAAM,2BAA2B,aACjC,CAAC,MAAM;AAEP,aAAO;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACD;AACD,WAAO;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAAA,EACD;AACA,MAAI,MAAM,SAAS,iBAAiB;AACnC,QAAI,SAAS,SAAS;AACrB,aAAO;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACD;AACD,WAAO;AAAA,MACN;AAAA,MACA;AAAA,IACD;AAAA,EACD;AAGA,SAAO;AAAA,IACN;AAAA,IACA,aAAa,MAAM,IAAI;AAAA,EACxB;AACD;","names":["isObject","entries","childPath","declaration","createHash","sameLedgerAddress","sameControllerIdentity","address","createHash","sameLedgerAddress"]}