{"version":3,"file":"control.mjs","names":["record"],"sources":["../src/core/op-factory-call.ts","../src/core/render-ops.ts","../src/core/render-typescript.ts","../src/core/planner-produced-migration.ts","../src/core/mongo-planner.ts","../src/core/filter-evaluator.ts","../src/core/mongo-ops-serializer.ts","../src/core/mongo-runner.ts","../src/core/mongo-target-database.ts","../src/core/mongo-target-contract-serializer.ts","../src/core/mongo-target-schema-verifier.ts","../src/core/scope-verify-result.ts","../src/core/control-target.ts"],"sourcesContent":["/**\n * Mongo migration IR: one concrete `*Call` class per pure factory under\n * `migration-factories.ts`, plus a shared `OpFactoryCallNode` abstract\n * base. Every call class carries the literal arguments its backing\n * factory would receive, computes a human-readable `label` in its\n * constructor, and implements two polymorphic hooks:\n *\n * - `toOp()` — converts the IR node to a runtime\n *   `MongoMigrationPlanOperation` by delegating to the matching pure\n *   factory in `migration-factories.ts`.\n * - `renderTypeScript()` / `importRequirements()` — inherited from\n *   `TsExpression`. Used by `renderCallsToTypeScript` to emit the call\n *   as a TypeScript expression inside the scaffolded `migration.ts`.\n *\n * The abstract base and all concrete classes are package-private.\n * External consumers see only the framework-level `OpFactoryCall`\n * interface and the `OpFactoryCall` union.\n */\n\nimport type {\n  OpFactoryCall as FrameworkOpFactoryCall,\n  MigrationOperationClass,\n} from '@prisma-next/framework-components/control';\nimport type {\n  CollModOptions,\n  CreateCollectionOptions,\n  CreateIndexOptions,\n  MongoIndexKey,\n  MongoMigrationPlanOperation,\n} from '@prisma-next/mongo-query-ast/control';\nimport type {\n  MongoSchemaCollection,\n  MongoSchemaCollectionOptions,\n  MongoSchemaIndex,\n  MongoSchemaValidator,\n} from '@prisma-next/mongo-schema-ir';\nimport { type ImportRequirement, jsonToTsSource, TsExpression } from '@prisma-next/ts-render';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport {\n  collMod,\n  createCollection,\n  createIndex,\n  dropCollection,\n  dropIndex,\n} from './migration-factories';\n\nexport interface CollModMeta {\n  readonly id?: string;\n  readonly label?: string;\n  readonly operationClass?: MigrationOperationClass;\n}\n\nconst TARGET_MIGRATION_MODULE = '@prisma-next/target-mongo/migration';\n\nabstract class OpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {\n  abstract readonly factoryName: string;\n  abstract readonly operationClass: MigrationOperationClass;\n  abstract readonly label: string;\n  abstract toOp(): MongoMigrationPlanOperation;\n\n  importRequirements(): readonly ImportRequirement[] {\n    return [{ moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName }];\n  }\n\n  protected freeze(): void {\n    Object.freeze(this);\n  }\n}\n\nfunction formatKeys(keys: ReadonlyArray<MongoIndexKey>): string {\n  return keys.map((k) => `${k.field}:${k.direction}`).join(', ');\n}\n\nexport class CreateIndexCall extends OpFactoryCallNode {\n  readonly factoryName = 'createIndex' as const;\n  readonly operationClass = 'additive' as const;\n  readonly collection: string;\n  readonly keys: ReadonlyArray<MongoIndexKey>;\n  readonly options: CreateIndexOptions | undefined;\n  readonly label: string;\n\n  constructor(\n    collection: string,\n    keys: ReadonlyArray<MongoIndexKey>,\n    options?: CreateIndexOptions,\n  ) {\n    super();\n    this.collection = collection;\n    this.keys = keys;\n    this.options = options;\n    this.label = `Create index on ${collection} (${formatKeys(keys)})`;\n    this.freeze();\n  }\n\n  toOp(): MongoMigrationPlanOperation {\n    return createIndex(this.collection, this.keys, this.options);\n  }\n\n  renderTypeScript(): string {\n    return this.options\n      ? `createIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)}, ${jsonToTsSource(this.options)})`\n      : `createIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)})`;\n  }\n}\n\nexport class DropIndexCall extends OpFactoryCallNode {\n  readonly factoryName = 'dropIndex' as const;\n  readonly operationClass = 'destructive' as const;\n  readonly collection: string;\n  readonly keys: ReadonlyArray<MongoIndexKey>;\n  readonly label: string;\n\n  constructor(collection: string, keys: ReadonlyArray<MongoIndexKey>) {\n    super();\n    this.collection = collection;\n    this.keys = keys;\n    this.label = `Drop index on ${collection} (${formatKeys(keys)})`;\n    this.freeze();\n  }\n\n  toOp(): MongoMigrationPlanOperation {\n    return dropIndex(this.collection, this.keys);\n  }\n\n  renderTypeScript(): string {\n    return `dropIndex(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.keys)})`;\n  }\n}\n\nexport class CreateCollectionCall extends OpFactoryCallNode {\n  readonly factoryName = 'createCollection' as const;\n  readonly operationClass = 'additive' as const;\n  readonly collection: string;\n  readonly options: CreateCollectionOptions | undefined;\n  readonly label: string;\n\n  constructor(collection: string, options?: CreateCollectionOptions) {\n    super();\n    this.collection = collection;\n    this.options = options;\n    this.label = `Create collection ${collection}`;\n    this.freeze();\n  }\n\n  toOp(): MongoMigrationPlanOperation {\n    return createCollection(this.collection, this.options);\n  }\n\n  renderTypeScript(): string {\n    return this.options\n      ? `createCollection(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)})`\n      : `createCollection(${jsonToTsSource(this.collection)})`;\n  }\n}\n\nexport class DropCollectionCall extends OpFactoryCallNode {\n  readonly factoryName = 'dropCollection' as const;\n  readonly operationClass = 'destructive' as const;\n  readonly collection: string;\n  readonly label: string;\n\n  constructor(collection: string) {\n    super();\n    this.collection = collection;\n    this.label = `Drop collection ${collection}`;\n    this.freeze();\n  }\n\n  toOp(): MongoMigrationPlanOperation {\n    return dropCollection(this.collection);\n  }\n\n  renderTypeScript(): string {\n    return `dropCollection(${jsonToTsSource(this.collection)})`;\n  }\n}\n\nexport class CollModCall extends OpFactoryCallNode {\n  readonly factoryName = 'collMod' as const;\n  readonly collection: string;\n  readonly options: CollModOptions;\n  readonly meta: CollModMeta | undefined;\n  readonly operationClass: MigrationOperationClass;\n  readonly label: string;\n\n  constructor(collection: string, options: CollModOptions, meta?: CollModMeta) {\n    super();\n    this.collection = collection;\n    this.options = options;\n    this.meta = meta;\n    this.operationClass = meta?.operationClass ?? 'destructive';\n    this.label = meta?.label ?? `Modify collection ${collection}`;\n    this.freeze();\n  }\n\n  toOp(): MongoMigrationPlanOperation {\n    return collMod(this.collection, this.options, this.meta);\n  }\n\n  renderTypeScript(): string {\n    return this.meta\n      ? `collMod(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)}, ${jsonToTsSource(this.meta)})`\n      : `collMod(${jsonToTsSource(this.collection)}, ${jsonToTsSource(this.options)})`;\n  }\n}\n\nexport type OpFactoryCall =\n  | CreateIndexCall\n  | DropIndexCall\n  | CreateCollectionCall\n  | DropCollectionCall\n  | CollModCall;\n\nexport function schemaIndexToCreateIndexOptions(index: MongoSchemaIndex): CreateIndexOptions {\n  return {\n    ...(index.unique ? { unique: true } : {}),\n    ...ifDefined('sparse', index.sparse),\n    ...ifDefined('expireAfterSeconds', index.expireAfterSeconds),\n    ...ifDefined('partialFilterExpression', index.partialFilterExpression),\n    ...ifDefined('wildcardProjection', index.wildcardProjection),\n    ...ifDefined('collation', index.collation),\n    ...ifDefined('weights', index.weights),\n    ...ifDefined('default_language', index.default_language),\n    ...ifDefined('language_override', index.language_override),\n  };\n}\n\nexport function schemaCollectionToCreateCollectionOptions(\n  coll: MongoSchemaCollection,\n): CreateCollectionOptions | undefined {\n  const opts: MongoSchemaCollectionOptions | undefined = coll.options;\n  const validator: MongoSchemaValidator | undefined = coll.validator;\n  if (!opts && !validator) return undefined;\n  return {\n    ...(opts?.capped ? { capped: true } : {}),\n    ...ifDefined('size', opts?.capped?.size),\n    ...ifDefined('max', opts?.capped?.max),\n    ...ifDefined('timeseries', opts?.timeseries),\n    ...ifDefined('collation', opts?.collation),\n    ...(opts?.clusteredIndex\n      ? {\n          clusteredIndex: {\n            key: { _id: 1 } satisfies Record<string, number>,\n            unique: true,\n            ...(opts.clusteredIndex.name != null ? { name: opts.clusteredIndex.name } : {}),\n          },\n        }\n      : {}),\n    ...(validator ? { validator: { $jsonSchema: validator.jsonSchema } } : {}),\n    ...ifDefined('validationLevel', validator?.validationLevel),\n    ...ifDefined('validationAction', validator?.validationAction),\n    ...ifDefined('changeStreamPreAndPostImages', opts?.changeStreamPreAndPostImages),\n  };\n}\n","import type { MongoMigrationPlanOperation } from '@prisma-next/mongo-query-ast/control';\nimport type { OpFactoryCall } from './op-factory-call';\n\nexport function renderOps(calls: ReadonlyArray<OpFactoryCall>): MongoMigrationPlanOperation[] {\n  return calls.map((call) => call.toOp());\n}\n","import { detectScaffoldRuntime, shebangLineFor } from '@prisma-next/migration-tools/migration-ts';\nimport { type ImportRequirement, renderImports } from '@prisma-next/ts-render';\nimport type { OpFactoryCall } from './op-factory-call';\n\nexport interface RenderMigrationMeta {\n  readonly from: string | null;\n  readonly to: string;\n}\n\n/**\n * Always-present base imports for the rendered scaffold:\n *\n * - `Migration` from `@prisma-next/family-mongo/migration` — the\n *   user-facing Mongo `Migration` base; subclasses don't need to\n *   redeclare `targetId` or thread family/target generics.\n * - `MigrationCLI` from `@prisma-next/cli/migration-cli` — the\n *   migration-file CLI entrypoint that loads `prisma-next.config.ts`,\n *   assembles a `ControlStack`, and instantiates the migration class.\n *   The migration file owns this dependency directly: pulling CLI\n *   machinery in at script run time is acceptable because the script's\n *   whole purpose is to be invoked from the project that owns the\n *   config. (Mirrors the postgres facade pattern; pulling `MigrationCLI`\n *   into `@prisma-next/family-mongo/migration` so a Mongo migration only\n *   needs one import is tracked separately as a follow-up.)\n */\nconst BASE_IMPORTS: readonly ImportRequirement[] = [\n  { moduleSpecifier: '@prisma-next/family-mongo/migration', symbol: 'Migration' },\n  { moduleSpecifier: '@prisma-next/cli/migration-cli', symbol: 'MigrationCLI' },\n];\n\n/**\n * Render a list of Mongo `OpFactoryCall`s as a `migration.ts` source string.\n * The result is shebanged, imports the committed contract JSON\n * (`end-contract.json`, plus `start-contract.json` for a non-baseline\n * migration), extends `Migration<Start, End>` (or `Migration<never, End>` for\n * a baseline) from `@prisma-next/family-mongo`, assigns the JSON to\n * `endContractJson` / `startContractJson`, and implements `operations`. The\n * `Migration` base derives `describe()` from those fields.\n *\n * The walk is polymorphic: each call node contributes its own\n * `renderTypeScript()` expression and declares its own `importRequirements()`.\n * The top-level renderer aggregates imports across all nodes and emits one\n * `import { … } from \"…\"` line per module. The `Migration` / `MigrationCLI`\n * base imports and the contract-JSON imports are always emitted, independent\n * of the call nodes.\n */\nexport function renderCallsToTypeScript(\n  calls: ReadonlyArray<OpFactoryCall>,\n  meta: RenderMigrationMeta,\n): string {\n  const imports = buildImports(calls, meta);\n  const operationsBody = calls.map((c) => c.renderTypeScript()).join(',\\n');\n  const hasStart = meta.from !== null;\n  const startField = hasStart ? ['  override readonly startContractJson = startContract;'] : [];\n\n  return [\n    shebangLineFor(detectScaffoldRuntime()),\n    imports,\n    '',\n    `class M extends Migration<${hasStart ? 'Start' : 'never'}, End> {`,\n    ...startField,\n    '  override readonly endContractJson = endContract;',\n    '',\n    '  override get operations() {',\n    '    return [',\n    indent(operationsBody, 6),\n    '    ];',\n    '  }',\n    '}',\n    '',\n    'export default M;',\n    'MigrationCLI.run(import.meta.url, M);',\n    '',\n  ].join('\\n');\n}\n\nfunction buildImports(calls: ReadonlyArray<OpFactoryCall>, meta: RenderMigrationMeta): string {\n  const requirements: ImportRequirement[] = [...BASE_IMPORTS, ...contractImports(meta)];\n  for (const call of calls) {\n    for (const req of call.importRequirements()) {\n      requirements.push(req);\n    }\n  }\n  return renderImports(requirements);\n}\n\n/**\n * The committed contract-JSON imports the scaffold reads its from/to identity\n * from. `end-contract.json` is always present; `start-contract.json` is added\n * only for a non-baseline migration (`meta.from !== null`). The matching\n * `Contract` type imports (aliased `Start`/`End`) feed the\n * `Migration<Start, End>` generics. Baseline emits `Migration<never, End>` with\n * no start imports — `never` is the honest \"no prior contract\" Start.\n */\nfunction contractImports(meta: RenderMigrationMeta): readonly ImportRequirement[] {\n  const reqs: ImportRequirement[] = [\n    {\n      moduleSpecifier: './end-contract.json',\n      symbol: 'endContract',\n      kind: 'default',\n      attributes: { type: 'json' },\n    },\n    { moduleSpecifier: './end-contract', symbol: 'Contract', alias: 'End', typeOnly: true },\n  ];\n  if (meta.from !== null) {\n    reqs.push({\n      moduleSpecifier: './start-contract.json',\n      symbol: 'startContract',\n      kind: 'default',\n      attributes: { type: 'json' },\n    });\n    reqs.push({\n      moduleSpecifier: './start-contract',\n      symbol: 'Contract',\n      alias: 'Start',\n      typeOnly: true,\n    });\n  }\n  return reqs;\n}\n\nfunction indent(text: string, spaces: number): string {\n  const pad = ' '.repeat(spaces);\n  return text\n    .split('\\n')\n    .map((line) => (line.trim() ? `${pad}${line}` : line))\n    .join('\\n');\n}\n","import type { MigrationPlanWithAuthoringSurface } from '@prisma-next/framework-components/control';\nimport { Migration, type MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport type { AnyMongoMigrationOperation } from '@prisma-next/mongo-query-ast/control';\nimport type { OpFactoryCall } from './op-factory-call';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\n\n/**\n * Planner-produced Mongo migration, returned by `MongoMigrationPlanner.plan(...)`\n * and `MongoMigrationPlanner.emptyMigration(...)`.\n *\n * Unlike user-authored migrations (which extend `MongoMigration` from\n * `@prisma-next/family-mongo/migration`), this class lives inside the target\n * and holds the richer authoring IR (`OpFactoryCall[]`) needed to render\n * itself back to TypeScript source. It implements\n * `MigrationPlanWithAuthoringSurface` so that the CLI can uniformly ask any\n * planner result to serialize itself to a `migration.ts`.\n *\n * Extends the framework `Migration` base class directly (not\n * `MongoMigration`) because `MongoMigration` lives in `@prisma-next/family-mongo`,\n * which depends on this package — extending it here would create a dependency\n * cycle.\n */\nexport class PlannerProducedMongoMigration\n  extends Migration<AnyMongoMigrationOperation>\n  implements MigrationPlanWithAuthoringSurface\n{\n  readonly targetId = 'mongo' as const;\n\n  constructor(\n    private readonly calls: readonly OpFactoryCall[],\n    private readonly meta: MigrationMeta,\n  ) {\n    super();\n  }\n\n  override get operations(): readonly AnyMongoMigrationOperation[] {\n    return renderOps(this.calls);\n  }\n\n  override describe(): MigrationMeta {\n    return this.meta;\n  }\n\n  renderTypeScript(): string {\n    return renderCallsToTypeScript(this.calls, {\n      from: this.meta.from,\n      to: this.meta.to,\n    });\n  }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { contractToMongoSchemaIR } from '@prisma-next/family-mongo/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n  MigrationOperationClass,\n  MigrationOperationPolicy,\n  MigrationPlanner,\n  MigrationPlannerConflict,\n  MigrationPlannerResult,\n  MigrationPlanWithAuthoringSurface,\n  MigrationScaffoldContext,\n} from '@prisma-next/framework-components/control';\nimport type { MongoContract } from '@prisma-next/mongo-contract';\nimport type {\n  MongoSchemaCollection,\n  MongoSchemaCollectionOptions,\n  MongoSchemaIndex,\n  MongoSchemaIR,\n  MongoSchemaValidator,\n} from '@prisma-next/mongo-schema-ir';\nimport { canonicalize, deepEqual } from '@prisma-next/mongo-schema-ir';\nimport type { OpFactoryCall } from './op-factory-call';\nimport {\n  CollModCall,\n  CreateCollectionCall,\n  CreateIndexCall,\n  DropCollectionCall,\n  DropIndexCall,\n  schemaCollectionToCreateCollectionOptions,\n  schemaIndexToCreateIndexOptions,\n} from './op-factory-call';\nimport { PlannerProducedMongoMigration } from './planner-produced-migration';\n\nfunction buildIndexLookupKey(index: MongoSchemaIndex): string {\n  const keys = index.keys.map((k) => `${k.field}:${k.direction}`).join(',');\n  const opts = [\n    index.unique ? 'unique' : '',\n    index.sparse ? 'sparse' : '',\n    index.expireAfterSeconds != null ? `ttl:${index.expireAfterSeconds}` : '',\n    index.partialFilterExpression ? `pfe:${canonicalize(index.partialFilterExpression)}` : '',\n    index.wildcardProjection ? `wp:${canonicalize(index.wildcardProjection)}` : '',\n    index.collation ? `col:${canonicalize(index.collation)}` : '',\n    index.weights ? `wt:${canonicalize(index.weights)}` : '',\n    index.default_language ? `dl:${index.default_language}` : '',\n    index.language_override ? `lo:${index.language_override}` : '',\n  ]\n    .filter(Boolean)\n    .join(';');\n  return opts ? `${keys}|${opts}` : keys;\n}\n\nfunction validatorsEqual(\n  a: MongoSchemaValidator | undefined,\n  b: MongoSchemaValidator | undefined,\n): boolean {\n  if (!a && !b) return true;\n  if (!a || !b) return false;\n  return (\n    a.validationLevel === b.validationLevel &&\n    a.validationAction === b.validationAction &&\n    canonicalize(a.jsonSchema) === canonicalize(b.jsonSchema)\n  );\n}\n\nfunction classifyValidatorUpdate(\n  origin: MongoSchemaValidator,\n  dest: MongoSchemaValidator,\n): 'widening' | 'destructive' {\n  // Moving to a stricter action or level narrows the accepted value space.\n  if (origin.validationAction !== dest.validationAction && dest.validationAction === 'error') {\n    return 'destructive';\n  }\n  if (origin.validationLevel !== dest.validationLevel && dest.validationLevel === 'strict') {\n    return 'destructive';\n  }\n\n  if (canonicalize(origin.jsonSchema) === canonicalize(dest.jsonSchema)) {\n    return 'widening';\n  }\n\n  // Check whether the schema change only adds non-required properties (widening).\n  return isWideningSchemaChange(origin.jsonSchema, dest.jsonSchema) ? 'widening' : 'destructive';\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n  return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/**\n * Returns true when `dest` is a structural superset of `origin` for the common\n * additive case: adding non-required properties to a top-level object schema.\n * Anything uncertain falls through to the safe `destructive` default.\n */\nfunction isWideningSchemaChange(\n  origin: Record<string, unknown>,\n  dest: Record<string, unknown>,\n): boolean {\n  // Only handle top-level object schemas.\n  if (origin['bsonType'] !== 'object' || dest['bsonType'] !== 'object') {\n    return false;\n  }\n\n  // Any change to keys besides 'required' and 'properties' is uncertain → destructive.\n  const allKeys = new Set([...Object.keys(origin), ...Object.keys(dest)]);\n  for (const key of allKeys) {\n    if (key === 'required' || key === 'properties') continue;\n    if (canonicalize(origin[key]) !== canonicalize(dest[key])) return false;\n  }\n\n  // dest.required must be a subset of origin.required — no new required fields.\n  const originRequired = new Set<unknown>(\n    Array.isArray(origin['required']) ? origin['required'] : [],\n  );\n  const destRequired = Array.isArray(dest['required']) ? dest['required'] : [];\n  for (const field of destRequired) {\n    if (!originRequired.has(field)) return false;\n  }\n\n  // All properties that existed in origin must still exist unchanged.\n  // New properties in dest (absent from origin) are allowed — widening.\n  const originProps = isPlainObject(origin['properties']) ? origin['properties'] : {};\n  const destProps = isPlainObject(dest['properties']) ? dest['properties'] : {};\n  for (const field of Object.keys(originProps)) {\n    if (!Object.hasOwn(destProps, field)) return false; // Property removed → destructive.\n    if (canonicalize(originProps[field]) !== canonicalize(destProps[field])) return false; // Property narrowed → destructive.\n  }\n\n  return true;\n}\n\nfunction hasImmutableOptionChange(\n  origin: MongoSchemaCollectionOptions | undefined,\n  dest: MongoSchemaCollectionOptions | undefined,\n): string | undefined {\n  if (canonicalize(origin?.capped) !== canonicalize(dest?.capped)) return 'capped';\n  if (canonicalize(origin?.timeseries) !== canonicalize(dest?.timeseries)) return 'timeseries';\n  if (canonicalize(origin?.collation) !== canonicalize(dest?.collation)) return 'collation';\n  if (canonicalize(origin?.clusteredIndex) !== canonicalize(dest?.clusteredIndex))\n    return 'clusteredIndex';\n  return undefined;\n}\n\nfunction collectionHasOptions(coll: MongoSchemaCollection): boolean {\n  return !!(coll.options || coll.validator);\n}\n\nexport type PlanCallsResult =\n  | { readonly kind: 'success'; readonly calls: OpFactoryCall[] }\n  | { readonly kind: 'failure'; readonly conflicts: MigrationPlannerConflict[] };\n\nexport class MongoMigrationPlanner implements MigrationPlanner<'mongo', 'mongo'> {\n  planCalls(options: {\n    readonly contract: unknown;\n    readonly schema: unknown;\n    readonly policy: MigrationOperationPolicy;\n    readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;\n  }): PlanCallsResult {\n    const contract = options.contract as MongoContract;\n    const originIR = options.schema as MongoSchemaIR;\n    const destinationIR = contractToMongoSchemaIR(contract);\n\n    const collCreates: OpFactoryCall[] = [];\n    const drops: OpFactoryCall[] = [];\n    const creates: OpFactoryCall[] = [];\n    const validatorOps: OpFactoryCall[] = [];\n    const mutableOptionOps: OpFactoryCall[] = [];\n    const collDrops: OpFactoryCall[] = [];\n    const conflicts: MigrationPlannerConflict[] = [];\n\n    const allCollectionNames = new Set([\n      ...originIR.collectionNames,\n      ...destinationIR.collectionNames,\n    ]);\n\n    for (const collName of [...allCollectionNames].sort()) {\n      const originColl = originIR.collection(collName);\n      const destColl = destinationIR.collection(collName);\n\n      if (!originColl) {\n        // Provision contract-declared collections that are absent from\n        // the live database. MongoDB lazily materialises a collection\n        // on first write, so subsequent `createIndex` calls in the same\n        // plan would create the collection for us implicitly — but the\n        // schema verifier treats an unmaterialised contract collection\n        // as a `missing_table` issue, so a plan that lacks both options\n        // and indexes (e.g. a plain `users` collection from the init\n        // scaffold) ends up provisioning nothing and failing verify.\n        // The planner therefore emits an explicit createCollection for\n        // any contract collection that has options/validator OR no\n        // indexes to ride along on. Collections that have indexes\n        // continue to rely on createIndex for materialisation, keeping\n        // existing plans byte-stable.\n        if (destColl && (collectionHasOptions(destColl) || destColl.indexes.length === 0)) {\n          const opts = collectionHasOptions(destColl)\n            ? schemaCollectionToCreateCollectionOptions(destColl)\n            : undefined;\n          collCreates.push(new CreateCollectionCall(collName, opts));\n        }\n      } else if (!destColl) {\n        collDrops.push(new DropCollectionCall(collName));\n      } else {\n        const immutableChange = hasImmutableOptionChange(originColl.options, destColl.options);\n        if (immutableChange) {\n          conflicts.push({\n            kind: 'policy-violation',\n            summary: `Cannot change immutable collection option '${immutableChange}' on ${collName}`,\n            why: `MongoDB does not support modifying the '${immutableChange}' option after collection creation`,\n          });\n        }\n\n        const mutableCall = planMutableOptionsDiffCall(\n          collName,\n          originColl.options,\n          destColl.options,\n        );\n        if (mutableCall) mutableOptionOps.push(mutableCall);\n\n        const validatorCall = planValidatorDiffCall(\n          collName,\n          originColl.validator,\n          destColl.validator,\n        );\n        if (validatorCall) validatorOps.push(validatorCall);\n      }\n\n      const originLookup = new Map<string, MongoSchemaIndex>();\n      if (originColl) {\n        for (const idx of originColl.indexes) {\n          originLookup.set(buildIndexLookupKey(idx), idx);\n        }\n      }\n\n      const destLookup = new Map<string, MongoSchemaIndex>();\n      if (destColl) {\n        for (const idx of destColl.indexes) {\n          destLookup.set(buildIndexLookupKey(idx), idx);\n        }\n      }\n\n      for (const [lookupKey, idx] of originLookup) {\n        if (!destLookup.has(lookupKey)) {\n          drops.push(new DropIndexCall(collName, idx.keys));\n        }\n      }\n\n      for (const [lookupKey, idx] of destLookup) {\n        if (!originLookup.has(lookupKey)) {\n          creates.push(\n            new CreateIndexCall(collName, idx.keys, schemaIndexToCreateIndexOptions(idx)),\n          );\n        }\n      }\n    }\n\n    if (conflicts.length > 0) {\n      return { kind: 'failure', conflicts };\n    }\n\n    const allCalls = [\n      ...collCreates,\n      ...drops,\n      ...creates,\n      ...validatorOps,\n      ...mutableOptionOps,\n      ...collDrops,\n    ];\n\n    for (const call of allCalls) {\n      if (!options.policy.allowedOperationClasses.includes(call.operationClass)) {\n        conflicts.push({\n          kind: 'policy-violation',\n          summary: `${call.operationClass} operation disallowed: ${call.label}`,\n          why: `Policy does not allow '${call.operationClass}' operations`,\n        });\n      }\n    }\n\n    if (conflicts.length > 0) {\n      return { kind: 'failure', conflicts };\n    }\n\n    return { kind: 'success', calls: allCalls };\n  }\n\n  plan(options: {\n    readonly contract: unknown;\n    readonly schema: unknown;\n    readonly policy: MigrationOperationPolicy;\n    /**\n     * The \"from\" contract (state the planner assumes the database starts at),\n     * or `null` for reconciliation flows. Used to populate `describe().from`\n     * on the produced plan as `fromContract?.storage.storageHash ?? null`.\n     */\n    readonly fromContract: Contract | null;\n    readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;\n  }): MigrationPlannerResult {\n    const contract = options.contract as MongoContract;\n    const result = this.planCalls(options);\n    if (result.kind === 'failure') return result;\n    return {\n      kind: 'success',\n      plan: new PlannerProducedMongoMigration(result.calls, {\n        from: options.fromContract?.storage.storageHash ?? null,\n        to: contract.storage.storageHash,\n      }),\n    };\n  }\n\n  /**\n   * Produce an empty `migration.ts` authoring surface for `migration new`.\n   *\n   * The \"empty migration\" is a `PlannerProducedMongoMigration` with no\n   * operations; `renderTypeScript()` emits a stub class with the correct\n   * `from`/`to` metadata that the user then fills in with operations. The\n   * contract path on the context is unused — Mongo's emitted source does\n   * not import from the generated contract `.d.ts`.\n   */\n  emptyMigration(context: MigrationScaffoldContext): MigrationPlanWithAuthoringSurface {\n    return new PlannerProducedMongoMigration([], {\n      from: context.fromHash,\n      to: context.toHash,\n    });\n  }\n}\n\nfunction planValidatorDiffCall(\n  collName: string,\n  originValidator: MongoSchemaValidator | undefined,\n  destValidator: MongoSchemaValidator | undefined,\n): OpFactoryCall | undefined {\n  if (validatorsEqual(originValidator, destValidator)) return undefined;\n\n  if (destValidator) {\n    const operationClass: MigrationOperationClass = originValidator\n      ? classifyValidatorUpdate(originValidator, destValidator)\n      : 'destructive';\n    return new CollModCall(\n      collName,\n      {\n        validator: { $jsonSchema: destValidator.jsonSchema },\n        validationLevel: destValidator.validationLevel,\n        validationAction: destValidator.validationAction,\n      },\n      {\n        id: `validator.${collName}.${originValidator ? 'update' : 'add'}`,\n        label: `${originValidator ? 'Update' : 'Add'} validator on ${collName}`,\n        operationClass,\n      },\n    );\n  }\n\n  return new CollModCall(\n    collName,\n    {\n      validator: {},\n      validationLevel: 'strict',\n      validationAction: 'error',\n    },\n    {\n      id: `validator.${collName}.remove`,\n      label: `Remove validator on ${collName}`,\n      operationClass: 'widening',\n    },\n  );\n}\n\nfunction planMutableOptionsDiffCall(\n  collName: string,\n  origin: MongoSchemaCollectionOptions | undefined,\n  dest: MongoSchemaCollectionOptions | undefined,\n): OpFactoryCall | undefined {\n  const originCSPPI = origin?.changeStreamPreAndPostImages;\n  const destCSPPI = dest?.changeStreamPreAndPostImages;\n  if (deepEqual(originCSPPI, destCSPPI)) return undefined;\n\n  const desiredCSPPI = destCSPPI ?? { enabled: false };\n  return new CollModCall(\n    collName,\n    {\n      changeStreamPreAndPostImages: desiredCSPPI,\n    },\n    {\n      id: `options.${collName}.update`,\n      label: `Update mutable options on ${collName}`,\n      operationClass: desiredCSPPI.enabled ? 'widening' : 'destructive',\n    },\n  );\n}\n","import type {\n  MongoAndExpr,\n  MongoExistsExpr,\n  MongoExprFilter,\n  MongoFieldFilter,\n  MongoFilterExpr,\n  MongoFilterVisitor,\n  MongoNotExpr,\n  MongoOrExpr,\n} from '@prisma-next/mongo-query-ast/control';\nimport { deepEqual } from '@prisma-next/mongo-schema-ir';\nimport type { MongoValue } from '@prisma-next/mongo-value';\n\nfunction getNestedField(doc: Record<string, unknown>, path: string): unknown {\n  const parts = path.split('.');\n  let current: unknown = doc;\n  for (const part of parts) {\n    if (current === null || current === undefined || typeof current !== 'object') {\n      return undefined;\n    }\n    const record = current as Record<string, unknown>;\n    if (!Object.hasOwn(record, part)) {\n      return undefined;\n    }\n    current = record[part];\n  }\n  return current;\n}\n\nfunction evaluateFieldOp(op: string, actual: unknown, expected: MongoValue): boolean {\n  switch (op) {\n    case '$eq':\n      return deepEqual(actual, expected);\n    case '$ne':\n      return !deepEqual(actual, expected);\n    case '$gt':\n      return typeof actual === typeof expected && (actual as number) > (expected as number);\n    case '$gte':\n      return typeof actual === typeof expected && (actual as number) >= (expected as number);\n    case '$lt':\n      return typeof actual === typeof expected && (actual as number) < (expected as number);\n    case '$lte':\n      return typeof actual === typeof expected && (actual as number) <= (expected as number);\n    case '$in':\n      return Array.isArray(expected) && expected.some((v) => deepEqual(actual, v));\n    default:\n      throw new Error(`Unsupported filter operator in migration check: ${op}`);\n  }\n}\n\nexport class FilterEvaluator implements MongoFilterVisitor<boolean> {\n  private doc: Record<string, unknown> = {};\n\n  evaluate(filter: MongoFilterExpr, doc: Record<string, unknown>): boolean {\n    this.doc = doc;\n    return filter.accept(this);\n  }\n\n  field(expr: MongoFieldFilter): boolean {\n    const value = getNestedField(this.doc, expr.field);\n    return evaluateFieldOp(expr.op, value, expr.value);\n  }\n\n  and(expr: MongoAndExpr): boolean {\n    return expr.exprs.every((child) => child.accept(this));\n  }\n\n  or(expr: MongoOrExpr): boolean {\n    return expr.exprs.some((child) => child.accept(this));\n  }\n\n  not(expr: MongoNotExpr): boolean {\n    return !expr.expr.accept(this);\n  }\n\n  exists(expr: MongoExistsExpr): boolean {\n    const has = getNestedField(this.doc, expr.field) !== undefined;\n    return expr.exists ? has : !has;\n  }\n\n  expr(_expr: MongoExprFilter): boolean {\n    throw new Error('Aggregation expression filters are not supported in migration checks');\n  }\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { MigrationOperationClass } from '@prisma-next/framework-components/control';\nimport {\n  type AnyMongoDdlCommand,\n  type AnyMongoInspectionCommand,\n  type AnyMongoMigrationOperation,\n  CollModCommand,\n  CreateCollectionCommand,\n  CreateIndexCommand,\n  DropCollectionCommand,\n  DropIndexCommand,\n  ListCollectionsCommand,\n  ListIndexesCommand,\n  MongoAndExpr,\n  type MongoDataTransformCheck,\n  type MongoDataTransformOperation,\n  MongoExistsExpr,\n  MongoFieldFilter,\n  type MongoFilterExpr,\n  type MongoMigrationCheck,\n  type MongoMigrationPlanOperation,\n  type MongoMigrationStep,\n  MongoNotExpr,\n  MongoOrExpr,\n} from '@prisma-next/mongo-query-ast/control';\nimport {\n  AggregateCommand,\n  type AnyMongoCommand,\n  MongoAddFieldsStage,\n  MongoLimitStage,\n  MongoLookupStage,\n  MongoMatchStage,\n  MongoMergeStage,\n  type MongoPipelineStage,\n  MongoProjectStage,\n  type MongoQueryPlan,\n  MongoSortStage,\n  type MongoUpdatePipelineStage,\n  RawAggregateCommand,\n  RawDeleteManyCommand,\n  RawDeleteOneCommand,\n  RawFindOneAndDeleteCommand,\n  RawFindOneAndUpdateCommand,\n  RawInsertManyCommand,\n  RawInsertOneCommand,\n  RawUpdateManyCommand,\n  RawUpdateOneCommand,\n} from '@prisma-next/mongo-query-ast/execution';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type } from 'arktype';\n\nconst IndexKeyDirection = type('1 | -1 | \"text\" | \"2dsphere\" | \"2d\" | \"hashed\"');\nconst IndexKeyJson = type({ field: 'string', direction: IndexKeyDirection });\n\nconst CollationJson = type({\n  locale: 'string',\n  'caseLevel?': 'boolean',\n  'caseFirst?': 'string',\n  'strength?': 'number',\n  'numericOrdering?': 'boolean',\n  'alternate?': 'string',\n  'maxVariable?': 'string',\n  'backwards?': 'boolean',\n  'normalization?': 'boolean',\n});\n\nconst CreateIndexJson = type({\n  kind: '\"createIndex\"',\n  collection: 'string',\n  keys: IndexKeyJson.array().atLeastLength(1),\n  'unique?': 'boolean',\n  'sparse?': 'boolean',\n  'expireAfterSeconds?': 'number',\n  'partialFilterExpression?': 'Record<string, unknown>',\n  'name?': 'string',\n  'wildcardProjection?': 'Record<string, 0 | 1>',\n  'collation?': CollationJson,\n  'weights?': 'Record<string, number>',\n  'default_language?': 'string',\n  'language_override?': 'string',\n});\n\nconst DropIndexJson = type({\n  kind: '\"dropIndex\"',\n  collection: 'string',\n  name: 'string',\n});\n\nconst CreateCollectionJson = type({\n  kind: '\"createCollection\"',\n  collection: 'string',\n  'validator?': 'Record<string, unknown>',\n  'validationLevel?': '\"strict\" | \"moderate\"',\n  'validationAction?': '\"error\" | \"warn\"',\n  'capped?': 'boolean',\n  'size?': 'number',\n  'max?': 'number',\n  'timeseries?': {\n    timeField: 'string',\n    'metaField?': 'string',\n    'granularity?': '\"seconds\" | \"minutes\" | \"hours\"',\n  },\n  'collation?': CollationJson,\n  'changeStreamPreAndPostImages?': { enabled: 'boolean' },\n  'clusteredIndex?': {\n    key: 'Record<string, number>',\n    unique: 'boolean',\n    'name?': 'string',\n  },\n});\n\nconst DropCollectionJson = type({\n  kind: '\"dropCollection\"',\n  collection: 'string',\n});\n\nconst CollModJson = type({\n  kind: '\"collMod\"',\n  collection: 'string',\n  'validator?': 'Record<string, unknown>',\n  'validationLevel?': '\"strict\" | \"moderate\"',\n  'validationAction?': '\"error\" | \"warn\"',\n  'changeStreamPreAndPostImages?': { enabled: 'boolean' },\n});\n\nconst ListIndexesJson = type({\n  kind: '\"listIndexes\"',\n  collection: 'string',\n});\n\nconst ListCollectionsJson = type({\n  kind: '\"listCollections\"',\n});\n\nconst FieldFilterJson = type({\n  kind: '\"field\"',\n  field: 'string',\n  op: 'string',\n  value: 'unknown',\n});\n\nconst ExistsFilterJson = type({\n  kind: '\"exists\"',\n  field: 'string',\n  exists: 'boolean',\n});\n\n// ============================================================================\n// DML command schemas\n// ============================================================================\n\nconst RawInsertOneJson = type({\n  kind: '\"rawInsertOne\"',\n  collection: 'string',\n  document: 'Record<string, unknown>',\n});\n\nconst RawInsertManyJson = type({\n  kind: '\"rawInsertMany\"',\n  collection: 'string',\n  documents: 'Record<string, unknown>[]',\n});\n\nconst RawUpdateOneJson = type({\n  kind: '\"rawUpdateOne\"',\n  collection: 'string',\n  filter: 'Record<string, unknown>',\n  update: 'Record<string, unknown> | Record<string, unknown>[]',\n});\n\nconst RawUpdateManyJson = type({\n  kind: '\"rawUpdateMany\"',\n  collection: 'string',\n  filter: 'Record<string, unknown>',\n  update: 'Record<string, unknown> | Record<string, unknown>[]',\n});\n\nconst RawDeleteOneJson = type({\n  kind: '\"rawDeleteOne\"',\n  collection: 'string',\n  filter: 'Record<string, unknown>',\n});\n\nconst RawDeleteManyJson = type({\n  kind: '\"rawDeleteMany\"',\n  collection: 'string',\n  filter: 'Record<string, unknown>',\n});\n\nconst RawAggregateJson = type({\n  kind: '\"rawAggregate\"',\n  collection: 'string',\n  pipeline: 'Record<string, unknown>[]',\n});\n\nconst RawFindOneAndUpdateJson = type({\n  kind: '\"rawFindOneAndUpdate\"',\n  collection: 'string',\n  filter: 'Record<string, unknown>',\n  update: 'Record<string, unknown> | Record<string, unknown>[]',\n  upsert: 'boolean',\n});\n\nconst RawFindOneAndDeleteJson = type({\n  kind: '\"rawFindOneAndDelete\"',\n  collection: 'string',\n  filter: 'Record<string, unknown>',\n});\n\nconst TypedAggregateJson = type({\n  kind: '\"aggregate\"',\n  collection: 'string',\n  pipeline: 'Record<string, unknown>[]',\n});\n\nconst PlanMetaJson = type({\n  target: 'string',\n  storageHash: 'string',\n  lane: 'string',\n  'targetFamily?': 'string',\n  'profileHash?': 'string',\n  'annotations?': 'Record<string, unknown>',\n});\n\nconst QueryPlanJson = type({\n  collection: 'string',\n  command: 'Record<string, unknown>',\n  meta: PlanMetaJson,\n});\n\n// ============================================================================\n// DDL check/step schemas\n// ============================================================================\n\nconst CheckJson = type({\n  description: 'string',\n  source: 'Record<string, unknown>',\n  filter: 'Record<string, unknown>',\n  expect: '\"exists\" | \"notExists\"',\n});\n\nconst StepJson = type({\n  description: 'string',\n  command: 'Record<string, unknown>',\n});\n\nconst DdlOperationJson = type({\n  id: 'string',\n  label: 'string',\n  operationClass: '\"additive\" | \"widening\" | \"destructive\"',\n  precheck: 'Record<string, unknown>[]',\n  execute: 'Record<string, unknown>[]',\n  postcheck: 'Record<string, unknown>[]',\n});\n\nconst DataTransformCheckJson = type({\n  description: 'string',\n  source: 'Record<string, unknown>',\n  filter: 'Record<string, unknown>',\n  expect: '\"exists\" | \"notExists\"',\n});\n\nconst DataTransformOperationJson = type({\n  id: 'string',\n  label: 'string',\n  operationClass: '\"data\"',\n  name: 'string',\n  precheck: 'Record<string, unknown>[]',\n  run: 'Record<string, unknown>[]',\n  postcheck: 'Record<string, unknown>[]',\n});\n\nfunction validate<T>(schema: { assert: (data: unknown) => T }, data: unknown, context: string): T {\n  try {\n    return schema.assert(stripUndefinedDeep(data));\n  } catch (error) {\n    /* v8 ignore start -- assertion libraries always throw Error instances */\n    const message = error instanceof Error ? error.message : String(error);\n    /* v8 ignore stop */\n    throw new Error(`Invalid ${context}: ${message}`);\n  }\n}\n\n/**\n * Strip `undefined`-valued properties before they reach arktype's optional-key\n * assertions.\n *\n * Op IRs (e.g. `CreateCollectionCommand`) assign every optional field on\n * every instance — fields the caller did not provide land as\n * `undefined`-valued properties. arktype treats `{ foo?: 'boolean' }` as\n * \"key may be absent, but if present must be boolean\", so the bare instance\n * fails validation when it crosses the deserialize boundary in-process\n * (no JSON round-trip happens between planner → runner). This helper\n * recovers the JSON-round-tripped shape (undefined keys absent) without\n * forcing every caller to round-trip.\n *\n * Returns the original value reference whenever no change is needed.\n * That preserves prototype-bound payload values such as BSON wrappers\n * (`ObjectId`, `Decimal128`, `Binary`, …) which embed no `undefined`\n * own-enumerable properties and therefore never trigger a rebuild.\n * Top-level op IRs (class instances with `undefined` optional fields)\n * still get flattened to plain records as required by arktype.\n */\nfunction stripUndefinedDeep(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    let changed = false;\n    const next = value.map((item) => {\n      const stripped = stripUndefinedDeep(item);\n      if (stripped !== item) changed = true;\n      return stripped;\n    });\n    return changed ? next : value;\n  }\n  if (value === null || typeof value !== 'object') {\n    return value;\n  }\n  const entries = Object.entries(value as Record<string, unknown>);\n  const out: Record<string, unknown> = {};\n  let changed = false;\n  for (const [key, val] of entries) {\n    if (val === undefined) {\n      changed = true;\n      continue;\n    }\n    const stripped = stripUndefinedDeep(val);\n    if (stripped !== val) changed = true;\n    out[key] = stripped;\n  }\n  return changed ? out : value;\n}\n\nfunction deserializeFilterExpr(json: unknown): MongoFilterExpr {\n  const record = json as Record<string, unknown>;\n  const kind = record['kind'] as string;\n  switch (kind) {\n    case 'field': {\n      const data = validate(FieldFilterJson, json, 'field filter');\n      return MongoFieldFilter.of(data.field, data.op, data.value as never);\n    }\n    case 'and': {\n      const exprs = record['exprs'];\n      if (!Array.isArray(exprs)) throw new Error('Invalid and filter: missing exprs array');\n      return MongoAndExpr.of(exprs.map(deserializeFilterExpr));\n    }\n    case 'or': {\n      const exprs = record['exprs'];\n      if (!Array.isArray(exprs)) throw new Error('Invalid or filter: missing exprs array');\n      return MongoOrExpr.of(exprs.map(deserializeFilterExpr));\n    }\n    case 'not': {\n      const expr = record['expr'];\n      if (!expr || typeof expr !== 'object') throw new Error('Invalid not filter: missing expr');\n      return new MongoNotExpr(deserializeFilterExpr(expr));\n    }\n    case 'exists': {\n      const data = validate(ExistsFilterJson, json, 'exists filter');\n      return new MongoExistsExpr(data.field, data.exists);\n    }\n    default:\n      throw new Error(`Unknown filter expression kind: ${kind}`);\n  }\n}\n\n// ============================================================================\n// Pipeline stage deserialization\n// ============================================================================\n\nexport function deserializePipelineStage(json: unknown): MongoPipelineStage {\n  const record = json as Record<string, unknown>;\n  const kind = record['kind'] as string;\n  switch (kind) {\n    case 'match':\n      return new MongoMatchStage(deserializeFilterExpr(record['filter']));\n    case 'limit':\n      return new MongoLimitStage(record['limit'] as number);\n    case 'sort':\n      return new MongoSortStage(record['sort'] as Record<string, 1 | -1>);\n    case 'project':\n      return new MongoProjectStage(record['projection'] as Record<string, 0 | 1>);\n    case 'addFields':\n      return new MongoAddFieldsStage(record['fields'] as Record<string, never>);\n    case 'lookup': {\n      const opts: {\n        from: string;\n        as: string;\n        localField?: string;\n        foreignField?: string;\n        pipeline?: ReadonlyArray<MongoPipelineStage>;\n        let_?: Record<string, never>;\n      } = {\n        from: record['from'] as string,\n        as: record['as'] as string,\n      };\n      if (record['localField'] !== undefined) opts.localField = record['localField'] as string;\n      if (record['foreignField'] !== undefined)\n        opts.foreignField = record['foreignField'] as string;\n      if (record['pipeline'] !== undefined)\n        opts.pipeline = (record['pipeline'] as unknown[]).map(deserializePipelineStage);\n      if (record['let_'] !== undefined) opts.let_ = record['let_'] as Record<string, never>;\n      return new MongoLookupStage(opts);\n    }\n    case 'merge': {\n      const opts: {\n        into: string | { db: string; coll: string };\n        on?: string | ReadonlyArray<string>;\n        whenMatched?: string | ReadonlyArray<MongoUpdatePipelineStage>;\n        whenNotMatched?: string;\n      } = {\n        into: record['into'] as string | { db: string; coll: string },\n      };\n      if (record['on'] !== undefined) opts.on = record['on'] as string | string[];\n      if (record['whenMatched'] !== undefined) {\n        const wm = record['whenMatched'];\n        opts.whenMatched =\n          typeof wm === 'string'\n            ? wm\n            : ((wm as unknown[]).map(deserializePipelineStage) as MongoUpdatePipelineStage[]);\n      }\n      if (record['whenNotMatched'] !== undefined)\n        opts.whenNotMatched = record['whenNotMatched'] as string;\n      return new MongoMergeStage(opts);\n    }\n    default:\n      throw new Error(`Unknown pipeline stage kind: ${kind}`);\n  }\n}\n\n// ============================================================================\n// DML command deserialization\n// ============================================================================\n\nexport function deserializeDmlCommand(json: unknown): AnyMongoCommand {\n  const record = json as Record<string, unknown>;\n  const kind = record['kind'] as string;\n  switch (kind) {\n    case 'rawInsertOne': {\n      const data = validate(RawInsertOneJson, json, 'rawInsertOne command');\n      return new RawInsertOneCommand(data.collection, data.document);\n    }\n    case 'rawInsertMany': {\n      const data = validate(RawInsertManyJson, json, 'rawInsertMany command');\n      return new RawInsertManyCommand(data.collection, data.documents);\n    }\n    case 'rawUpdateOne': {\n      const data = validate(RawUpdateOneJson, json, 'rawUpdateOne command');\n      return new RawUpdateOneCommand(data.collection, data.filter, data.update);\n    }\n    case 'rawUpdateMany': {\n      const data = validate(RawUpdateManyJson, json, 'rawUpdateMany command');\n      return new RawUpdateManyCommand(data.collection, data.filter, data.update);\n    }\n    case 'rawDeleteOne': {\n      const data = validate(RawDeleteOneJson, json, 'rawDeleteOne command');\n      return new RawDeleteOneCommand(data.collection, data.filter);\n    }\n    case 'rawDeleteMany': {\n      const data = validate(RawDeleteManyJson, json, 'rawDeleteMany command');\n      return new RawDeleteManyCommand(data.collection, data.filter);\n    }\n    case 'rawAggregate': {\n      const data = validate(RawAggregateJson, json, 'rawAggregate command');\n      return new RawAggregateCommand(data.collection, data.pipeline);\n    }\n    case 'rawFindOneAndUpdate': {\n      const data = validate(RawFindOneAndUpdateJson, json, 'rawFindOneAndUpdate command');\n      return new RawFindOneAndUpdateCommand(data.collection, data.filter, data.update, data.upsert);\n    }\n    case 'rawFindOneAndDelete': {\n      const data = validate(RawFindOneAndDeleteJson, json, 'rawFindOneAndDelete command');\n      return new RawFindOneAndDeleteCommand(data.collection, data.filter);\n    }\n    case 'aggregate': {\n      const data = validate(TypedAggregateJson, json, 'aggregate command');\n      const pipeline = data.pipeline.map(deserializePipelineStage);\n      return new AggregateCommand(data.collection, pipeline);\n    }\n    default:\n      throw new Error(`Unknown DML command kind: ${kind}`);\n  }\n}\n\n// ============================================================================\n// MongoQueryPlan deserialization\n// ============================================================================\n\nexport function deserializeMongoQueryPlan(json: unknown): MongoQueryPlan {\n  const data = validate(QueryPlanJson, json, 'Mongo query plan');\n  const command = deserializeDmlCommand(data.command);\n  const m = data.meta;\n  const meta: PlanMeta = {\n    target: m.target,\n    storageHash: m.storageHash,\n    lane: m.lane,\n    ...ifDefined('targetFamily', m.targetFamily),\n    ...ifDefined('profileHash', m.profileHash),\n    ...ifDefined('annotations', m.annotations),\n  };\n  return { collection: data.collection, command, meta };\n}\n\n// ============================================================================\n// DDL command deserialization\n// ============================================================================\n\nfunction deserializeDdlCommand(json: unknown): AnyMongoDdlCommand {\n  const record = json as Record<string, unknown>;\n  const kind = record['kind'] as string;\n  switch (kind) {\n    case 'createIndex': {\n      const data = validate(CreateIndexJson, json, 'createIndex command');\n      return new CreateIndexCommand(data.collection, data.keys, {\n        ...ifDefined('unique', data.unique),\n        ...ifDefined('sparse', data.sparse),\n        ...ifDefined('expireAfterSeconds', data.expireAfterSeconds),\n        ...ifDefined('partialFilterExpression', data.partialFilterExpression),\n        ...ifDefined('name', data.name),\n        ...ifDefined('wildcardProjection', data.wildcardProjection),\n        ...ifDefined('collation', data.collation),\n        ...ifDefined('weights', data.weights),\n        ...ifDefined('default_language', data.default_language),\n        ...ifDefined('language_override', data.language_override),\n      });\n    }\n    case 'dropIndex': {\n      const data = validate(DropIndexJson, json, 'dropIndex command');\n      return new DropIndexCommand(data.collection, data.name);\n    }\n    case 'createCollection': {\n      const data = validate(CreateCollectionJson, json, 'createCollection command');\n      return new CreateCollectionCommand(data.collection, {\n        ...ifDefined('validator', data.validator),\n        ...ifDefined('validationLevel', data.validationLevel),\n        ...ifDefined('validationAction', data.validationAction),\n        ...ifDefined('capped', data.capped),\n        ...ifDefined('size', data.size),\n        ...ifDefined('max', data.max),\n        ...ifDefined('timeseries', data.timeseries),\n        ...ifDefined('collation', data.collation),\n        ...ifDefined('changeStreamPreAndPostImages', data.changeStreamPreAndPostImages),\n        ...ifDefined('clusteredIndex', data.clusteredIndex),\n      });\n    }\n    case 'dropCollection': {\n      const data = validate(DropCollectionJson, json, 'dropCollection command');\n      return new DropCollectionCommand(data.collection);\n    }\n    case 'collMod': {\n      const data = validate(CollModJson, json, 'collMod command');\n      return new CollModCommand(data.collection, {\n        ...ifDefined('validator', data.validator),\n        ...ifDefined('validationLevel', data.validationLevel),\n        ...ifDefined('validationAction', data.validationAction),\n        ...ifDefined('changeStreamPreAndPostImages', data.changeStreamPreAndPostImages),\n      });\n    }\n    default:\n      throw new Error(`Unknown DDL command kind: ${kind}`);\n  }\n}\n\nfunction deserializeInspectionCommand(json: unknown): AnyMongoInspectionCommand {\n  const record = json as Record<string, unknown>;\n  const kind = record['kind'] as string;\n  switch (kind) {\n    case 'listIndexes': {\n      const data = validate(ListIndexesJson, json, 'listIndexes command');\n      return new ListIndexesCommand(data.collection);\n    }\n    case 'listCollections': {\n      validate(ListCollectionsJson, json, 'listCollections command');\n      return new ListCollectionsCommand();\n    }\n    default:\n      throw new Error(`Unknown inspection command kind: ${kind}`);\n  }\n}\n\nfunction deserializeCheck(json: unknown): MongoMigrationCheck {\n  const data = validate(CheckJson, json, 'migration check');\n  return {\n    description: data.description,\n    source: deserializeInspectionCommand(data.source),\n    filter: deserializeFilterExpr(data.filter),\n    expect: data.expect,\n  };\n}\n\nfunction deserializeStep(json: unknown): MongoMigrationStep {\n  const data = validate(StepJson, json, 'migration step');\n  return {\n    description: data.description,\n    command: deserializeDdlCommand(data.command),\n  };\n}\n\nfunction isDataTransformJson(json: unknown): boolean {\n  return (\n    typeof json === 'object' &&\n    json !== null &&\n    (json as Record<string, unknown>)['operationClass'] === 'data'\n  );\n}\n\nfunction deserializeDdlOp(json: unknown): MongoMigrationPlanOperation {\n  const data = validate(DdlOperationJson, json, 'migration operation');\n  return {\n    id: data.id,\n    label: data.label,\n    operationClass: data.operationClass as MigrationOperationClass,\n    precheck: data.precheck.map(deserializeCheck),\n    execute: data.execute.map(deserializeStep),\n    postcheck: data.postcheck.map(deserializeCheck),\n  };\n}\n\nfunction deserializeDataTransformCheck(json: unknown): MongoDataTransformCheck {\n  const data = validate(DataTransformCheckJson, json, 'data transform check');\n  return {\n    description: data.description,\n    source: deserializeMongoQueryPlan(data.source),\n    filter: deserializeFilterExpr(data.filter),\n    expect: data.expect,\n  };\n}\n\nfunction deserializeDataTransformOp(json: unknown): MongoDataTransformOperation {\n  const data = validate(DataTransformOperationJson, json, 'data transform operation');\n  return {\n    id: data.id,\n    label: data.label,\n    operationClass: 'data',\n    name: data.name,\n    precheck: data.precheck.map(deserializeDataTransformCheck),\n    run: data.run.map(deserializeMongoQueryPlan),\n    postcheck: data.postcheck.map(deserializeDataTransformCheck),\n  };\n}\n\nexport function deserializeMongoOp(json: unknown): AnyMongoMigrationOperation {\n  if (isDataTransformJson(json)) {\n    return deserializeDataTransformOp(json);\n  }\n  return deserializeDdlOp(json);\n}\n\nexport function deserializeMongoOps(json: readonly unknown[]): AnyMongoMigrationOperation[] {\n  return json.map(deserializeMongoOp);\n}\n\nexport function serializeMongoOps(ops: readonly AnyMongoMigrationOperation[]): string {\n  return JSON.stringify(ops, null, 2);\n}\n","import type { MarkerOperations, MongoRunnerDependencies } from '@prisma-next/adapter-mongo/control';\nimport type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport { errorRunnerFailed } from '@prisma-next/errors/execution';\nimport { verifyMongoSchema } from '@prisma-next/family-mongo/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport {\n  APP_SPACE_ID,\n  type MigrationOperationPolicy,\n  type MigrationPlan,\n  type MigrationPlanOperation,\n  type MigrationRunnerExecutionChecks,\n  type MigrationRunnerFailure,\n  type MigrationRunnerPerSpaceSuccessValue,\n  type OperationContext,\n  type VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport type { AggregateMigrationEdgeRef } from '@prisma-next/migration-tools/aggregate';\nimport type { MongoContract } from '@prisma-next/mongo-contract';\nimport type { MongoAdapter, MongoDriver } from '@prisma-next/mongo-lowering';\nimport type {\n  AnyMongoMigrationOperation,\n  MongoDataTransformCheck,\n  MongoDataTransformOperation,\n  MongoInspectionCommandVisitor,\n  MongoMigrationCheck,\n  MongoMigrationPlanOperation,\n} from '@prisma-next/mongo-query-ast/control';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { FilterEvaluator } from './filter-evaluator';\nimport { deserializeMongoOps } from './mongo-ops-serializer';\n\nconst READ_ONLY_CHECK_COMMAND_KINDS: ReadonlySet<string> = new Set(['aggregate', 'rawAggregate']);\n\nexport type { MarkerOperations, MongoRunnerDependencies };\n\nexport interface MongoMigrationRunnerExecuteOptions {\n  readonly plan: MigrationPlan;\n  readonly destinationContract: MongoContract;\n  readonly policy: MigrationOperationPolicy;\n  readonly callbacks?: {\n    onOperationStart?(op: MigrationPlanOperation): void;\n    onOperationComplete?(op: MigrationPlanOperation): void;\n  };\n  readonly executionChecks?: MigrationRunnerExecutionChecks;\n  readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;\n  readonly strictVerification?: boolean;\n  readonly context?: OperationContext;\n  /**\n   * Per-space verify-result scope. When set, the runner verifies the\n   * destination contract against the **full** introspected schema, then\n   * applies this to scope the result to the space the contract claims —\n   * dropping the `extra` findings for collections a sibling space owns.\n   *\n   * The target descriptor's `execute` injects this callback, derived from\n   * the sibling spaces in the aggregate. Callers that don't scope leave it\n   * unset and verify against the whole introspected schema.\n   */\n  readonly scopeVerifyResult?: (result: VerifyDatabaseSchemaResult) => VerifyDatabaseSchemaResult;\n  /** Per-edge breakdown from graph-walk planning; drives per-edge ledger writes. */\n  readonly migrationEdges: readonly AggregateMigrationEdgeRef[];\n}\n\nexport type MongoMigrationRunnerResult = Result<\n  MigrationRunnerPerSpaceSuccessValue,\n  MigrationRunnerFailure\n>;\n\nfunction runnerFailure(\n  code: string,\n  summary: string,\n  opts?: { why?: string; meta?: Record<string, unknown> },\n): MongoMigrationRunnerResult {\n  return notOk<MigrationRunnerFailure>({\n    code,\n    summary,\n    ...opts,\n  });\n}\n\nexport class MongoMigrationRunner {\n  constructor(private readonly deps: MongoRunnerDependencies) {}\n\n  async execute(options: MongoMigrationRunnerExecuteOptions): Promise<MongoMigrationRunnerResult> {\n    const { inspectionExecutor, adapter, driver, executeDdl, markerOps } = this.deps;\n    const operations = deserializeMongoOps(options.plan.operations as readonly unknown[]);\n    // Plans produced by the contract-space-aware planner stamp `spaceId`\n    // onto the plan; plans without one fall through to the application's\n    // well-known space.\n    const space = options.plan.spaceId ?? APP_SPACE_ID;\n\n    const policyCheck = this.enforcePolicyCompatibility(options.policy, operations);\n    if (policyCheck) return policyCheck;\n\n    const existingMarker = await markerOps.readMarker(space);\n\n    const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n    if (markerCheck) return markerCheck;\n\n    const checks = options.executionChecks;\n    const runPrechecks = checks?.prechecks !== false;\n    const runPostchecks = checks?.postchecks !== false;\n    const runIdempotency = checks?.idempotencyChecks !== false;\n\n    const filterEvaluator = new FilterEvaluator();\n\n    let operationsExecuted = 0;\n\n    for (const operation of operations) {\n      options.callbacks?.onOperationStart?.(operation);\n      try {\n        if (operation.operationClass === 'data') {\n          const result = await this.executeDataTransform(\n            operation as MongoDataTransformOperation,\n            adapter,\n            driver,\n            filterEvaluator,\n            runIdempotency,\n            runPrechecks,\n            runPostchecks,\n          );\n          if (result.failure) return result.failure;\n          if (result.executed) {\n            operationsExecuted += 1;\n          }\n          continue;\n        }\n\n        const ddlOp = operation as MongoMigrationPlanOperation;\n\n        if (runPostchecks && runIdempotency) {\n          const allSatisfied = await this.allChecksSatisfied(\n            ddlOp.postcheck,\n            inspectionExecutor,\n            filterEvaluator,\n          );\n          if (allSatisfied) continue;\n        }\n\n        if (runPrechecks) {\n          const precheckResult = await this.evaluateChecks(\n            ddlOp.precheck,\n            inspectionExecutor,\n            filterEvaluator,\n          );\n          if (!precheckResult) {\n            return runnerFailure(\n              'PRECHECK_FAILED',\n              `Operation ${operation.id} failed during precheck`,\n              { meta: { operationId: operation.id } },\n            );\n          }\n        }\n\n        for (const step of ddlOp.execute) {\n          await executeDdl(step.command);\n        }\n\n        if (runPostchecks) {\n          const postcheckResult = await this.evaluateChecks(\n            ddlOp.postcheck,\n            inspectionExecutor,\n            filterEvaluator,\n          );\n          if (!postcheckResult) {\n            return runnerFailure(\n              'POSTCHECK_FAILED',\n              `Operation ${operation.id} failed during postcheck`,\n              { meta: { operationId: operation.id } },\n            );\n          }\n        }\n\n        operationsExecuted += 1;\n      } finally {\n        options.callbacks?.onOperationComplete?.(operation);\n      }\n    }\n\n    const destination = options.plan.destination;\n    const profileHash = options.destinationContract.profileHash ?? destination.storageHash;\n\n    const incomingInvariants = options.plan.providedInvariants ?? [];\n    const existingInvariantSet = new Set(existingMarker?.invariants ?? []);\n    const incomingIsSubsetOfExisting = incomingInvariants.every((id) =>\n      existingInvariantSet.has(id),\n    );\n    const markerAlreadyAtDestination =\n      existingMarker !== null &&\n      existingMarker.storageHash === destination.storageHash &&\n      existingMarker.profileHash === profileHash;\n\n    // Skip marker/ledger writes (and schema verification) only when the apply\n    // is a true no-op: no operations executed, marker already at destination,\n    // and every incoming invariant is already in the stored set.\n    //\n    // Divergence from the SQL runners (postgres/sqlite): those runners gate\n    // the no-op skip on `isSelfEdge` (origin === destination) only, so a\n    // non-self-edge `db update` that introspects-as-no-op still writes a\n    // ledger entry. Mongo skips even those because the runner has no\n    // structural distinction between self-edge and re-apply — invariant-\n    // aware routing here does not yet differentiate between the two\n    // ledger semantics. If the SQL audit-trail behavior should hold for\n    // Mongo too, gate this `isNoOp` on a self-edge check (or, conversely,\n    // align the SQL runners to skip non-self-edge no-ops uniformly).\n    const isNoOp =\n      operationsExecuted === 0 && markerAlreadyAtDestination && incomingIsSubsetOfExisting;\n\n    if (!isNoOp) {\n      const liveSchema = await this.deps.introspectSchema();\n      // When an aggregate spans more than one space the live database holds\n      // collections owned by sibling spaces; verify against the full schema,\n      // then let the target descriptor's `execute`-injected `scopeVerifyResult`\n      // drop the `extra` findings for the collections those siblings own.\n      // Callers that don't scope leave the result unchanged.\n      const rawVerifyResult = verifyMongoSchema({\n        contract: options.destinationContract,\n        schema: liveSchema,\n        strict: options.strictVerification ?? true,\n        frameworkComponents: options.frameworkComponents,\n        ...(options.context ? { context: options.context } : {}),\n      });\n      const verifyResult = options.scopeVerifyResult\n        ? options.scopeVerifyResult(rawVerifyResult)\n        : rawVerifyResult;\n      if (!verifyResult.ok) {\n        return runnerFailure('SCHEMA_VERIFY_FAILED', verifyResult.summary, {\n          why: 'The resulting database schema does not satisfy the destination contract.',\n          meta: { issues: verifyResult.schema.issues },\n        });\n      }\n\n      if (existingMarker) {\n        const updated = await markerOps.updateMarker(space, existingMarker.storageHash, {\n          storageHash: destination.storageHash,\n          profileHash,\n          invariants: incomingInvariants,\n        });\n        if (!updated) {\n          return runnerFailure(\n            'MARKER_CAS_FAILURE',\n            'Marker was modified by another process during migration execution.',\n            {\n              meta: {\n                space,\n                expectedStorageHash: existingMarker.storageHash,\n                destinationStorageHash: destination.storageHash,\n              },\n            },\n          );\n        }\n      } else {\n        await markerOps.initMarker(space, {\n          storageHash: destination.storageHash,\n          profileHash,\n          invariants: incomingInvariants,\n        });\n      }\n\n      await this.recordLedgerEntries(markerOps, space, options);\n    }\n\n    return ok({ operationsPlanned: operations.length, operationsExecuted });\n  }\n\n  private async recordLedgerEntries(\n    markerOps: MarkerOperations,\n    space: string,\n    options: MongoMigrationRunnerExecuteOptions,\n  ): Promise<void> {\n    const plan = options.plan;\n    const edges = options.migrationEdges;\n    const totalEdgeOps = edges.reduce((sum, edge) => sum + edge.operationCount, 0);\n    if (totalEdgeOps !== plan.operations.length) {\n      throw new Error(\n        `Ledger write: plan.operations length (${plan.operations.length}) does not match sum of migrationEdges operationCount (${totalEdgeOps})`,\n      );\n    }\n    let offset = 0;\n    for (const edge of edges) {\n      const edgeOps = plan.operations.slice(offset, offset + edge.operationCount);\n      offset += edge.operationCount;\n      await markerOps.writeLedgerEntry(space, {\n        edgeId: `${edge.from}->${edge.to}`,\n        from: edge.from,\n        to: edge.to,\n        migrationName: edge.dirName,\n        migrationHash: edge.migrationHash,\n        operations: edgeOps,\n      });\n    }\n  }\n\n  private async executeDataTransform(\n    op: MongoDataTransformOperation,\n    adapter: MongoAdapter,\n    driver: MongoDriver,\n    filterEvaluator: FilterEvaluator,\n    runIdempotency: boolean,\n    runPrechecks: boolean,\n    runPostchecks: boolean,\n  ): Promise<{ executed: boolean; failure?: MongoMigrationRunnerResult }> {\n    if (runPostchecks && runIdempotency && op.postcheck.length > 0) {\n      const allSatisfied = await this.evaluateDataTransformChecks(\n        op.postcheck,\n        adapter,\n        driver,\n        filterEvaluator,\n      );\n      if (allSatisfied) return { executed: false };\n    }\n\n    if (runPrechecks && op.precheck.length > 0) {\n      const passed = await this.evaluateDataTransformChecks(\n        op.precheck,\n        adapter,\n        driver,\n        filterEvaluator,\n      );\n      if (!passed) {\n        return {\n          executed: false,\n          failure: runnerFailure('PRECHECK_FAILED', `Operation ${op.id} failed during precheck`, {\n            meta: { operationId: op.id, name: op.name },\n          }),\n        };\n      }\n    }\n\n    for (const plan of op.run) {\n      const wireCommand = await adapter.lower(plan, {});\n      for await (const _ of driver.execute(wireCommand)) {\n        /* consume */\n      }\n    }\n\n    if (runPostchecks && op.postcheck.length > 0) {\n      const passed = await this.evaluateDataTransformChecks(\n        op.postcheck,\n        adapter,\n        driver,\n        filterEvaluator,\n      );\n      if (!passed) {\n        return {\n          executed: false,\n          failure: runnerFailure('POSTCHECK_FAILED', `Operation ${op.id} failed during postcheck`, {\n            meta: { operationId: op.id, name: op.name },\n          }),\n        };\n      }\n    }\n\n    return { executed: true };\n  }\n\n  private async evaluateDataTransformChecks(\n    checks: readonly MongoDataTransformCheck[],\n    adapter: MongoAdapter,\n    driver: MongoDriver,\n    filterEvaluator: FilterEvaluator,\n  ): Promise<boolean> {\n    for (const check of checks) {\n      const commandKind = check.source.command.kind;\n      if (!READ_ONLY_CHECK_COMMAND_KINDS.has(commandKind)) {\n        throw errorRunnerFailed(\n          `Data-transform check rejected: command kind \"${commandKind}\" is not read-only`,\n          {\n            why: 'Data-transform checks must use aggregate or rawAggregate commands so the pre/postcheck path cannot mutate the database.',\n            fix: 'Author the check.source as an aggregate pipeline (or rawAggregate) rather than a DML write command.',\n            meta: {\n              checkDescription: check.description,\n              commandKind,\n              collection: check.source.collection,\n            },\n          },\n        );\n      }\n      const wireCommand = await adapter.lower(check.source, {});\n      let matchFound = false;\n      for await (const row of driver.execute<Record<string, unknown>>(wireCommand)) {\n        if (filterEvaluator.evaluate(check.filter, row)) {\n          matchFound = true;\n          break;\n        }\n      }\n      const passed = check.expect === 'exists' ? matchFound : !matchFound;\n      if (!passed) return false;\n    }\n    return true;\n  }\n\n  private async evaluateChecks(\n    checks: readonly MongoMigrationCheck[],\n    inspectionExecutor: MongoInspectionCommandVisitor<Promise<Record<string, unknown>[]>>,\n    filterEvaluator: FilterEvaluator,\n  ): Promise<boolean> {\n    for (const check of checks) {\n      const documents = await check.source.accept(inspectionExecutor);\n      const matchFound = documents.some((doc) => filterEvaluator.evaluate(check.filter, doc));\n      const passed = check.expect === 'exists' ? matchFound : !matchFound;\n      if (!passed) return false;\n    }\n    return true;\n  }\n\n  private async allChecksSatisfied(\n    checks: readonly MongoMigrationCheck[],\n    inspectionExecutor: MongoInspectionCommandVisitor<Promise<Record<string, unknown>[]>>,\n    filterEvaluator: FilterEvaluator,\n  ): Promise<boolean> {\n    if (checks.length === 0) return false;\n    return this.evaluateChecks(checks, inspectionExecutor, filterEvaluator);\n  }\n\n  private enforcePolicyCompatibility(\n    policy: MigrationOperationPolicy,\n    operations: readonly AnyMongoMigrationOperation[],\n  ): MongoMigrationRunnerResult | undefined {\n    const allowedClasses = new Set(policy.allowedOperationClasses);\n    for (const operation of operations) {\n      if (!allowedClasses.has(operation.operationClass)) {\n        return runnerFailure(\n          'POLICY_VIOLATION',\n          `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n          {\n            why: `Policy only allows: ${[...allowedClasses].join(', ')}.`,\n            meta: {\n              operationId: operation.id,\n              operationClass: operation.operationClass,\n            },\n          },\n        );\n      }\n    }\n    return undefined;\n  }\n\n  private ensureMarkerCompatibility(\n    marker: ContractMarkerRecord | null,\n    plan: MigrationPlan,\n  ): MongoMigrationRunnerResult | undefined {\n    const origin = plan.origin ?? null;\n    if (!origin) {\n      // No origin assertion on the plan — the caller has done its own\n      // correctness check (typically `db update` via live-schema\n      // introspection) and does not rely on marker continuity.\n      return undefined;\n    }\n\n    if (!marker) {\n      return runnerFailure(\n        'MARKER_ORIGIN_MISMATCH',\n        `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n        { meta: { expectedOriginStorageHash: origin.storageHash } },\n      );\n    }\n\n    if (marker.storageHash !== origin.storageHash) {\n      return runnerFailure(\n        'MARKER_ORIGIN_MISMATCH',\n        `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n        {\n          meta: {\n            markerStorageHash: marker.storageHash,\n            expectedOriginStorageHash: origin.storageHash,\n          },\n        },\n      );\n    }\n\n    return undefined;\n  }\n}\n","import {\n  freezeNode,\n  hydrateNamespaceEntities,\n  NamespaceBase,\n  UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport type {\n  MongoCollection,\n  MongoCollectionInput,\n  MongoNamespaceEntries,\n  MongoValueSetInput,\n} from '@prisma-next/mongo-contract';\nimport { composeMongoEntityKinds } from '@prisma-next/mongo-contract/entity-kinds';\nimport { blindCast } from '@prisma-next/utils/casts';\n\nexport interface MongoTargetDatabaseInput {\n  readonly id: string;\n  readonly entries?: Readonly<Record<string, Readonly<Record<string, unknown>>>> & {\n    readonly collection?: Readonly<Record<string, MongoCollectionInput>>;\n    readonly valueSet?: Readonly<Record<string, MongoValueSetInput>>;\n  };\n}\n\n/**\n * Mongo target `Namespace` concretion. In Mongo the \"namespace\" concept\n * binds to the connection's `db` field — a `MongoTargetDatabase` instance\n * names the database the collections live under. `entries['collection']`\n * holds collection IR. The unbound singleton (below) is the late-bound\n * namespace whose binding the connection's `db` resolves at runtime rather\n * than at authoring time.\n *\n * Qualifier emission is the rendering seam: query / DDL emission asks the\n * namespace for its qualifier (e.g. `\"<db>.<collection>\"`) and consumes\n * the result polymorphically. The unbound singleton overrides these\n * methods to elide the prefix entirely — call sites stay polymorphic and\n * never branch on `id === UNBOUND_NAMESPACE_ID`.\n */\nexport class MongoTargetDatabase extends NamespaceBase {\n  declare readonly kind: string;\n  readonly id: string;\n  readonly entries: MongoNamespaceEntries;\n\n  constructor(input: MongoTargetDatabaseInput) {\n    super();\n    this.id = input.id;\n\n    const rawEntries: Record<string, Readonly<Record<string, unknown>>> = {\n      collection: {},\n      ...input.entries,\n    };\n    this.entries = Object.freeze(\n      blindCast<\n        MongoNamespaceEntries,\n        'composeMongoEntityKinds() supplies the collection→MongoCollection descriptor, so this open-dict result holds the typed collection member MongoNamespaceEntries declares; the descriptor Map erases that per-kind Node type from the return.'\n      >(hydrateNamespaceEntities(rawEntries, composeMongoEntityKinds(), 'carry')),\n    );\n    Object.defineProperty(this, 'kind', {\n      value: 'database',\n      writable: false,\n      enumerable: false,\n      configurable: true,\n    });\n    freezeNode(this);\n  }\n\n  get collection(): Readonly<Record<string, MongoCollection>> {\n    return this.entries.collection ?? Object.freeze({});\n  }\n\n  /**\n   * The bare qualifier as it would appear in a rendered string. The\n   * unbound-database singleton overrides this to return `''`.\n   */\n  qualifier(): string {\n    return this.id;\n  }\n\n  /**\n   * Qualify a collection name with the database prefix. The\n   * unbound-database singleton overrides this to emit just the\n   * collection name. Used by emission/introspection paths that need a\n   * fully-qualified reference.\n   */\n  qualifyCollection(collectionName: string): string {\n    return `${this.id}.${collectionName}`;\n  }\n}\n\n/**\n * Singleton subclass for the reserved sentinel namespace id\n * (`UNBOUND_NAMESPACE_ID`) — the late-bound namespace whose binding the\n * connection's `db` resolves at runtime. Overrides qualifier emission\n * to elide the database prefix; call sites that consume `qualifier()`\n * / `qualifyCollection()` get unqualified output without branching on\n * the namespace id.\n *\n * This is the target-side materialization of \"the framework provides\n * affordances; targets implement specifics\": the framework names the\n * sentinel; Mongo decides what late-bound means here (the collection\n * name, naked — the database is supplied by the live connection).\n */\nexport class MongoTargetUnboundDatabase extends MongoTargetDatabase {\n  static readonly instance: MongoTargetUnboundDatabase = new MongoTargetUnboundDatabase();\n\n  private constructor() {\n    super({ id: UNBOUND_NAMESPACE_ID });\n  }\n\n  override qualifier(): string {\n    return '';\n  }\n\n  override qualifyCollection(collectionName: string): string {\n    return collectionName;\n  }\n}\n","import { MongoContractSerializerBase } from '@prisma-next/family-mongo/ir';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n  type MongoCollectionInput,\n  type MongoContract,\n  MongoStorage,\n  type MongoValueSetInput,\n} from '@prisma-next/mongo-contract';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport type { MongoTargetContract } from './mongo-target-contract';\nimport { MongoTargetDatabase, MongoTargetUnboundDatabase } from './mongo-target-database';\n\nexport class MongoTargetContractSerializer extends MongoContractSerializerBase<MongoTargetContract> {\n  protected constructTargetContract(validated: MongoContract): MongoTargetContract {\n    const { storage, ...rest } = validated;\n    const namespaces = Object.fromEntries(\n      Object.entries(storage.namespaces).map(([nsId, nsData]) => {\n        const collectionCount = Object.keys(nsData.entries.collection ?? {}).length;\n        const valueSetCount = Object.keys(nsData.entries['valueSet'] ?? {}).length;\n        if (nsId === UNBOUND_NAMESPACE_ID && collectionCount === 0 && valueSetCount === 0) {\n          return [nsId, MongoTargetUnboundDatabase.instance];\n        }\n        const dbInput: {\n          id: string;\n          entries?: Readonly<Record<string, Readonly<Record<string, unknown>>>> & {\n            readonly collection?: Readonly<Record<string, MongoCollectionInput>>;\n            readonly valueSet?: Readonly<Record<string, MongoValueSetInput>>;\n          };\n        } = { id: nsData.id };\n        if (\n          nsData.entries['collection'] !== undefined ||\n          nsData.entries['valueSet'] !== undefined\n        ) {\n          dbInput.entries = {\n            collection: blindCast<\n              Readonly<Record<string, MongoCollectionInput>>,\n              'collection entries validated by the mongo storage schema before hydration'\n            >(nsData.entries['collection'] ?? {}),\n            ...ifDefined(\n              'valueSet',\n              blindCast<\n                Readonly<Record<string, MongoValueSetInput>> | undefined,\n                'valueSet entries validated by the mongo storage schema before hydration'\n              >(nsData.entries['valueSet']),\n            ),\n          };\n        }\n        return [nsId, new MongoTargetDatabase(dbInput)];\n      }),\n    );\n    const targetStorage = new MongoStorage({\n      storageHash: storage.storageHash,\n      namespaces,\n    });\n    return { ...rest, storage: targetStorage };\n  }\n\n  override serializeContract(contract: MongoTargetContract): JsonObject {\n    const { storage, ...rest } = contract;\n    const namespacesJson: Record<string, JsonObject> = {};\n    for (const [nsId, ns] of Object.entries(storage.namespaces)) {\n      const collectionsOut: Record<string, JsonObject> = {};\n      for (const [collName, coll] of Object.entries(ns.entries.collection ?? {})) {\n        collectionsOut[collName] = JSON.parse(JSON.stringify(coll)) as JsonObject;\n      }\n      const valueSetOut: Record<string, JsonObject> = {};\n      for (const [vsName, vs] of Object.entries(ns.entries.valueSet ?? {})) {\n        valueSetOut[vsName] = blindCast<\n          JsonObject,\n          'a value-set IR node serializes to a JSON-safe { kind, values } object'\n        >(JSON.parse(JSON.stringify(vs)));\n      }\n      namespacesJson[nsId] = {\n        id: ns.id,\n        kind: 'mongo-database',\n        entries: {\n          collection: collectionsOut,\n          ...ifDefined('valueSet', Object.keys(valueSetOut).length > 0 ? valueSetOut : undefined),\n        },\n      };\n    }\n    return blindCast<\n      JsonObject,\n      'rest carries plain domain/capabilities JSON fields; storage has been serialized to JSON-safe form'\n    >({\n      ...rest,\n      storage: {\n        storageHash: String(storage.storageHash),\n        namespaces: namespacesJson,\n      },\n    });\n  }\n}\n","import {\n  canonicalizeSchemasForVerification,\n  contractToMongoSchemaIR,\n  diffMongoSchemas,\n} from '@prisma-next/family-mongo/control';\nimport { MongoSchemaVerifierBase } from '@prisma-next/family-mongo/ir';\nimport type {\n  SchemaDiffIssue,\n  SchemaVerifyOptions,\n} from '@prisma-next/framework-components/control';\nimport type { Namespace } from '@prisma-next/framework-components/ir';\nimport type { MongoSchemaIR } from '@prisma-next/mongo-schema-ir';\nimport type { MongoTargetContract } from './mongo-target-contract';\n\n/**\n * Mongo target `SchemaVerifier` concretion. Extends the family base's\n * namespace-walk scaffolding and contributes the per-namespace diff via\n * `verifyNamespace`; the diff body reuses the existing target-side\n * helpers (`contractToMongoSchemaIR`, `canonicalizeSchemasForVerification`,\n * `diffMongoSchemas`) so production verification behaviour is unchanged.\n *\n * Today's invariant: every Mongo contract carries exactly one\n * namespace (the unbound singleton, materialised as\n * `MongoTargetUnboundDatabase`), so the family-base namespace walk\n * dispatches exactly once and the per-namespace body runs the existing\n * whole-schema diff. Future per-collection namespace assignment will\n * have this hook project the diff to the namespace's owned collections.\n *\n * `verifyTargetExtensions` returns the empty list — Mongo has no\n * target-only kinds today.\n *\n * Strict diff mode is `false` for SPI-routed calls; production\n * verification today still goes through `verifyMongoSchema` which\n * receives strict from the CLI.\n */\nexport class MongoTargetSchemaVerifier extends MongoSchemaVerifierBase<\n  MongoTargetContract,\n  MongoSchemaIR\n> {\n  protected verifyNamespace(options: {\n    readonly contract: MongoTargetContract;\n    readonly schema: MongoSchemaIR;\n    readonly namespaceId: string;\n    readonly namespace: Namespace;\n  }): readonly SchemaDiffIssue[] {\n    const expectedIR = contractToMongoSchemaIR(options.contract);\n    const { live, expected } = canonicalizeSchemasForVerification(options.schema, expectedIR);\n    const collectionControlPolicy = (name: string) =>\n      this.collectionControlPolicyForName(options.contract, name);\n    const { failures, warnings } = diffMongoSchemas(live, expected, false, collectionControlPolicy);\n    return [...failures, ...warnings];\n  }\n\n  protected verifyTargetExtensions(\n    _options: SchemaVerifyOptions<MongoTargetContract, MongoSchemaIR>,\n  ): readonly SchemaDiffIssue[] {\n    return [];\n  }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n  SchemaDiffIssue,\n  VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport { issueOutcome } from '@prisma-next/framework-components/control';\nimport { elementCoordinates } from '@prisma-next/framework-components/ir';\n\n/**\n * The bare entity names the given contracts declare, unioned. The Mongo runner\n * asks this of every OTHER contract space in a multi-space apply, so each\n * space's post-apply verify can drop the extras those siblings claim.\n */\nexport function entityNamesDeclaredBy(contracts: ReadonlyArray<Contract>): Set<string> {\n  const owned = new Set<string>();\n  for (const contract of contracts) {\n    for (const { entityName } of elementCoordinates(contract.storage)) {\n      owned.add(entityName);\n    }\n  }\n  return owned;\n}\n\n/**\n * True when an issue reports a whole collection present in the database but\n * declared by no contract (an extra) — its path is exactly the collection\n * name, never a deeper index/validator/options auxiliary.\n */\nfunction extraCollectionName(issue: SchemaDiffIssue): string | undefined {\n  if (issueOutcome(issue) !== 'not-expected' || issue.path.length !== 1) return undefined;\n  return issue.path[0];\n}\n\n/**\n * Scope a per-space post-apply verify result to the contract space's own\n * elements: drop the `extra` findings for collections another contract space\n * claims. The runner verifies the destination contract against the full live\n * database, which holds sibling spaces' collections — without the scoping a\n * multi-space apply could never pass strict verify. Extras claimed by NO space\n * survive, so genuine drift still fails the runner's verdict.\n *\n * The result is issue-based, so the verdict recomputes directly from the\n * surviving list: `ok` holds exactly when it is empty.\n */\nexport function scopeVerifyResultToSpace(\n  result: VerifyDatabaseSchemaResult,\n  ownedByOtherSpaces: ReadonlySet<string>,\n): VerifyDatabaseSchemaResult {\n  if (ownedByOtherSpaces.size === 0) return result;\n\n  const issues = result.schema.issues.filter((issue) => {\n    const name = extraCollectionName(issue);\n    return name === undefined || !ownedByOtherSpaces.has(name);\n  });\n  if (issues.length === result.schema.issues.length) return result;\n\n  const ok = issues.length === 0;\n  const { code: staleCode, ...envelope } = result;\n  void staleCode;\n  return {\n    ...envelope,\n    ok,\n    ...(ok ? {} : { code: result.code ?? 'PN-RUN-3010' }),\n    summary: ok ? 'Database schema satisfies contract' : result.summary,\n    schema: { ...result.schema, issues },\n  };\n}\n","import {\n  createMongoRunnerDeps,\n  extractDb,\n  type MongoRunnerDependencies,\n} from '@prisma-next/adapter-mongo/control';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { MongoDriverImpl } from '@prisma-next/driver-mongo';\nimport type {\n  MongoControlFamilyInstance,\n  MongoControlTargetDescriptor,\n} from '@prisma-next/family-mongo/control';\nimport { contractToMongoSchemaIR } from '@prisma-next/family-mongo/control';\nimport type { MongoControlAdapter } from '@prisma-next/family-mongo/control-adapter';\nimport type {\n  MigrationRunner,\n  MigrationRunnerPerSpaceSuccessValue,\n  MigrationRunnerResult,\n  VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport type { MongoContract } from '@prisma-next/mongo-contract';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { mongoTargetDescriptorMeta } from './descriptor-meta';\nimport { MongoMigrationPlanner } from './mongo-planner';\nimport { MongoMigrationRunner, type MongoMigrationRunnerExecuteOptions } from './mongo-runner';\nimport type { MongoTargetContract } from './mongo-target-contract';\nimport { MongoTargetContractSerializer } from './mongo-target-contract-serializer';\nimport { MongoTargetSchemaVerifier } from './mongo-target-schema-verifier';\nimport { entityNamesDeclaredBy, scopeVerifyResultToSpace } from './scope-verify-result';\n\nexport type { MongoControlTargetDescriptor };\n\n/**\n * `migration.ts` default-exports a `Migration` subclass whose `operations`\n * getter returns the ordered list of operations and whose `describe()`\n * returns the manifest identity metadata. `MongoMigrationPlanner.plan()`\n * returns a `MigrationPlanWithAuthoringSurface` that knows how to render\n * itself back to such a file; `MongoMigrationPlanner.emptyMigration()`\n * returns the same shape for `migration new`. Users run the scaffolded\n * `migration.ts` directly (via `node migration.ts`) to self-emit\n * `ops.json` and attest the `migrationHash`.\n */\nexport const mongoTargetDescriptor: MongoControlTargetDescriptor<MongoTargetContract> = {\n  ...mongoTargetDescriptorMeta,\n  contractSerializer: new MongoTargetContractSerializer(),\n  schemaVerifier: new MongoTargetSchemaVerifier(),\n  migrations: {\n    createPlanner(_adapter: MongoControlAdapter<'mongo'>) {\n      return new MongoMigrationPlanner();\n    },\n    createRunner(family: MongoControlFamilyInstance) {\n      // Deps are bound to the first driver passed to execute() and cached for\n      // subsequent calls. Callers must not change the driver between calls.\n      let cachedDeps: MongoRunnerDependencies | undefined;\n\n      const runMongo = async (\n        driver: Parameters<MigrationRunner<'mongo', 'mongo'>['execute']>[0]['driver'],\n        runnerOptions: Omit<MongoMigrationRunnerExecuteOptions, 'destinationContract'> & {\n          readonly destinationContract: unknown;\n        },\n      ) => {\n        cachedDeps ??= createMongoRunnerDeps(\n          driver,\n          MongoDriverImpl.fromDb(extractDb(driver)),\n          family,\n        );\n        // The framework `MigrationRunner` interface types `destinationContract`\n        // as `unknown`; the Mongo runner narrows to `MongoContract`. Validation\n        // happens upstream — `migrate` calls\n        // `familyInstance.deserializeContract(contract)` on the project-root\n        // contract loaded from disk before routing it here, so this cast\n        // preserves the framework signature without weakening the runner's\n        // typed surface.\n        return new MongoMigrationRunner(cachedDeps).execute({\n          ...runnerOptions,\n          destinationContract: blindCast<\n            MongoContract,\n            'framework MigrationRunner types destinationContract as unknown; deserializeContract validated it upstream'\n          >(runnerOptions.destinationContract),\n        });\n      };\n\n      const runner: MigrationRunner<'mongo', 'mongo'> = {\n        // Mongo cannot wrap DDL ops in a session transaction (createCollection,\n        // createIndex, collMod, setValidation all bypass transactions even on\n        // replica sets), so the cross-space envelope is *resumable* rather than\n        // transactional. Per-space-internal verify-gated marker atomicity\n        // already lives in `MongoMigrationRunner.execute`: ops apply, schema is\n        // introspected and verified, and the marker advances only on verify-pass.\n        // This loop composes that guarantee across spaces — earlier-advanced\n        // markers are not rolled back when a later space fails. Re-running reads\n        // each marker, finds spaces 1..N−1 at-head (no-op skip), retries N onward.\n        //\n        // Per-space verify is scoped by `scopeVerifyResultToSpace`: the live DB\n        // holds collections owned by sibling contract spaces, so each space\n        // verifies the full schema and then drops the `extra` findings for the\n        // collections a sibling space claims. Without the scoping an aggregate\n        // of two spaces could not pass strict verify (every other-space\n        // collection would look like an extra).\n        //\n        // See `docs/architecture docs/subsystems/10. MongoDB Family.md` §\n        // Contract spaces and ADR 212 — Contract spaces.\n        async execute({ driver, perSpaceOptions }): Promise<MigrationRunnerResult> {\n          const contracts = perSpaceOptions.map((opts) =>\n            blindCast<Contract, 'destinationContract validated at aggregate boundary'>(\n              opts.destinationContract,\n            ),\n          );\n          const perSpaceResults: Array<{\n            space: string;\n            value: MigrationRunnerPerSpaceSuccessValue;\n          }> = [];\n          for (let i = 0; i < perSpaceOptions.length; i++) {\n            const spaceOptions = perSpaceOptions[i];\n            if (!spaceOptions) continue;\n            // The runner verifies the destination contract against the full\n            // introspected schema; scope the result to this space, dropping the\n            // `extra` findings for collections a sibling space claims.\n            const ownedByOtherSpaces = entityNamesDeclaredBy(contracts.filter((_, j) => j !== i));\n            const scopeVerifyResult = (\n              result: VerifyDatabaseSchemaResult,\n            ): VerifyDatabaseSchemaResult => scopeVerifyResultToSpace(result, ownedByOtherSpaces);\n            const { space, ...runnerOptions } = spaceOptions;\n            const result = await runMongo(driver, { ...runnerOptions, scopeVerifyResult });\n            if (!result.ok) {\n              return notOk({\n                ...result.failure,\n                failingSpace: space,\n              });\n            }\n            perSpaceResults.push({ space, value: result.value });\n          }\n          return ok({ perSpaceResults });\n        },\n      };\n      return runner;\n    },\n    contractToSchema(contract: Contract | null) {\n      return contractToMongoSchemaIR(\n        blindCast<\n          MongoContract | null,\n          'framework contractToSchema types contract as the generic Contract; any contract reaching the mongo target is MongoContract by construction'\n        >(contract),\n      );\n    },\n  },\n  create() {\n    return { familyId: 'mongo' as const, targetId: 'mongo' as const };\n  },\n};\n"],"mappings":";;;;;;;;;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