Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

refactor(mongo-migration): move subsystem to target-mongo and add planner dual output - #348

Merged
wmadden merged 17 commits into
mainfrom
migration-subsystem-refactor
Apr 16, 2026
Merged

wmadden merged 17 commits into
mainfrom
migration-subsystem-refactor

Conversation

@wmadden

@wmadden wmadden commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

closes TML-2219

Key snippets

Runner depends on abstract interfaces only

export interface MarkerOperations {
  readMarker(): Promise<ContractMarkerRecord | null>;
  initMarker(destination: { ... }): Promise<void>;
  updateMarker(expectedFrom: string, destination: { ... }): Promise<boolean>;
  writeLedgerEntry(entry: { ... }): Promise<void>;
}

export class MongoMigrationRunner implements MigrationRunner<'mongo', 'mongo'> {
  constructor(private readonly createDeps: MongoRunnerDependenciesFactory) {}
  // zero mongodb imports
}

OpFactoryCall visitor pattern

export interface OpFactoryCallVisitor<R> {
  createIndex(call: CreateIndexCall): R;
  dropIndex(call: DropIndexCall): R;
  createCollection(call: CreateCollectionCall): R;
  dropCollection(call: DropCollectionCall): R;
  collMod(call: CollModCall): R;
}

// Visitor usage in render-ops.ts:
const renderVisitor: OpFactoryCallVisitor<MongoMigrationPlanOperation> = {
  createIndex(call) { return createIndex(call.collection, call.keys, call.options); },
  // ...
};
export function renderOps(calls: ReadonlyArray<OpFactoryCall>) {
  return calls.map((call) => call.accept(renderVisitor));
}

Intent

Correct the layering of the Mongo migration subsystem so that target-agnostic orchestration (planner, runner, serializer) lives in the target package and the adapter contains only concrete mongodb driver bindings. Then introduce a structured intermediate representation (OpFactoryCall) that separates schema-diff logic from operation materialization, enabling both runtime execution and TypeScript code generation.

Change map

The story

  1. Move pure modules from adapter to target. Five modules (planner, serializer, contract-to-schema, DDL formatter, filter evaluator) are git-renamed with 100% similarity. The runner is renamed with modifications. Test files follow.

  2. Decouple the runner from mongodb. The runner's two dependencies on Db — DDL execution and marker operations — are abstracted behind interfaces. A MongoRunnerDependenciesFactory bridges the lifecycle gap (runner constructed before driver available). The concrete factory (createMongoRunnerDeps) lives in the adapter.

  3. Remove all adapter re-exports, update consumers. The adapter's control.ts no longer re-exports any symbol from target-mongo. Eight consumer files updated to import from @prisma-next/target-mongo/control.

  4. Introduce OpFactoryCall intermediate representation. The planner's planCalls() method produces an array of OpFactoryCall objects describing which factory to call with which arguments. plan() becomes a thin wrapper: planCalls() → renderOps().

  5. Add dual renderers. renderOps() calls factory functions to produce MongoMigrationPlanOperation[] (preserving existing behavior). renderTypeScript() generates a complete runnable migration file with correct imports and factory calls.

  6. Refactor OpFactoryCall to AST class/visitor pattern. The plain discriminated union is replaced with frozen subclasses and an OpFactoryCallVisitor<R> interface. All switch statements are replaced with visitor implementations, giving compile-time exhaustiveness.

  7. Fix TypeScript errors. Add missing MongoSchemaIR import and @prisma-next/migration-tools dependency.

Behavior changes & evidence

  • Module relocation (no behavior change): Five pure modules move from adapter-mongo to target-mongo. All symbols now exported from @prisma-next/target-mongo/control.

    • Implementation: Git renames in packages/3-mongo-target/
    • Tests: Moved test files with 100% similarity
  • Runner no longer depends on Db or mongodb types: The runner receives all dependencies through abstract interfaces.

  • Adapter re-exports removed; consumers import from target: All 12 backward-compat re-exports removed. Consumer files updated.

  • Adds planCalls() method returning OpFactoryCall[]: The planner produces a structured intermediate representation of the schema diff.

  • Adds renderOps() and renderTypeScript() renderers: Two visitor-based functions that interpret OpFactoryCall — one produces runtime operations, the other produces TypeScript source code.

  • Adds collMod factory function: Handles collection modification operations with configurable metadata.

  • OpFactoryCall uses AST class/visitor pattern (structural change, no behavior change): Plain union replaced with frozen classes + OpFactoryCallVisitor<R>. All dispatch sites use visitors instead of switches.

    • Why: Compile-time exhaustiveness — adding a new variant forces all visitors to handle it.
    • Implementation: op-factory-call.ts
    • Tests: All tests updated to construct class instances

Compatibility / migration / risk

  • MongoMigrationRunner constructor signature changed: No-arg → requires MongoRunnerDependenciesFactory. The only construction site (mongoTargetDescriptor.createRunner()) is updated.
  • Adapter no longer exports moved symbols: Consumers must import from @prisma-next/target-mongo/control. One file missed (db-verify-sign.test.ts).
  • OpFactoryCall is no longer plain data: Tests must construct class instances. If any consumer needs to serialize/deserialize OpFactoryCall, a deserialization function will be needed.
  • Runner creates new deps on every execute() call: When running multiple migrations sequentially, executors and marker-ops bindings are reconstructed each time from the same Db handle.

Follow-ups / open questions

  • Fix db-verify-sign.test.ts broken import.
  • Resolve runner factory design — either change the runner to accept pre-constructed dependencies, or accept the factory pattern and update the spec.
  • Decide whether OpFactoryCall should be plain data (as spec says) or AST classes (as implemented) and update the spec accordingly.
  • The "executable with tsx" and "round-trip via execution" ACs for renderTypeScript are not covered by tests.

Non-goals / intentionally out of scope

  • Refactoring the planner's internal diffing logic (beyond the planCalls() separation)
  • CLI integration for prisma migration plan --emit-ts
  • Refactoring the marker-ledger's internal implementation
  • Changing the framework's MigrationRunner interface

Summary by CodeRabbit

  • New Features

    • Add collMod migration operation, op-call model, and TypeScript migration code generation for MongoDB.
    • Expose a Mongo migration planner and runner API surface for planning and executing migrations.
  • Improvements

    • Runner now uses explicit dependency injection; planner classifies operations and detects conflicts.
    • Package exports and runtime dependencies updated to support new rendering/planning path.
  • Documentation

    • Migration examples updated to use named migration classes.
  • Tests

    • Large suite of unit and E2E tests covering planner, rendering, collMod, and round-trips.

@coderabbitai

coderabbitai Bot commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Migration planning moved from the adapter to the target layer; the migration runner was refactored to accept injected dependencies; a visitor-based op-call model and TypeScript rendering were added; adapter exports were narrowed and a runner-deps factory introduced; many tests and README examples updated.

Changes

Cohort / File(s) Summary
Skills Documentation
\.agents/skills/ast-visitor-pattern/SKILL.md
New documentation describing a frozen-class + visitor pattern for TypeScript discriminated unions and related testing guidance.
Target: Planner & Runner
packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts, packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
Added MongoMigrationPlanner (diffs contract→schema to OpFactoryCall[]); refactored MongoMigrationRunner to accept MongoRunnerDependencies and MarkerOperations, removing direct driver/db usage and dropping driver from execute options.
Target: Op model & Rendering
packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts, .../migration-factories.ts, .../render-ops.ts, .../render-typescript.ts
Introduced immutable visitor-based OpFactoryCall nodes and helpers, added collMod factory, renderOps (calls→plan ops), and renderTypeScript (calls→TS migration source).
Target: Exports & Tests
packages/3-mongo-target/1-mongo-target/src/exports/control.ts, .../exports/migration.ts, packages/3-mongo-target/1-mongo-target/test/*
Expanded public exports to include planner/runner/op factories/renderers; added unit and E2E tests for planner, factories, render-ops, and TypeScript round-trip.
Adapter: Removed Planner, Added Runner Factory
packages/3-mongo-target/2-mongo-adapter/src/core/mongo-planner.ts, .../runner-deps.ts, .../src/exports/control.ts, .../test/mongo-runner.test.ts
Deleted adapter-side MongoMigrationPlanner; added createMongoRunnerDeps(driver) to produce MongoRunnerDependencies from a control driver; updated adapter exports and tests to use DI and stop exporting target-layer planner/runner members.
Family & Descriptor Wiring
packages/2-mongo-family/9-family/src/core/control-instance.ts, .../mongo-target-descriptor.ts
Switched imports to target-layer implementations for marker/schema helpers and made migrations.createRunner lazily derive/cache runner deps via createMongoRunnerDeps(driver).
Examples & Integration Tests
examples/*/test/manual-migration.test.ts, test/integration/test/mongo/*.test.ts, test/integration/test/cli.*.e2e.test.ts
Updated imports to use @prisma-next/target-mongo/control for planner/runner/ops and replaced zero-arg MongoMigrationRunner() with new MongoMigrationRunner(createMongoRunnerDeps(controlDriver)); removed passing driver into execute.
Packaging & READMEs
packages/3-mongo-target/1-mongo-target/package.json, .../README.md, packages/2-mongo-family/9-family/README.md
Added runtime dependencies and adjusted README examples to export named migration classes and call Migration.run(import.meta.url, MigrationClass).
Misc Tests & Tooling
packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts, .../vitest.config.ts, various tests
Minor V8 coverage pragmas, coverage excludes, many new/updated tests validating planner, renderer, and factories.

Sequence Diagram(s)

sequenceDiagram
  participant Dev as Developer
  participant Driver as ControlDriver
  participant Adapter as Adapter (createMongoRunnerDeps)
  participant Runner as MongoMigrationRunner
  participant Planner as MongoMigrationPlanner
  participant DB as MongoDB

  Dev->>Driver: create control driver
  Dev->>Adapter: createMongoRunnerDeps(driver)
  Adapter->>Driver: extract Db (throws if missing)
  Adapter->>Runner: return MongoRunnerDependencies
  Dev->>Runner: new MongoMigrationRunner(deps)
  Dev->>Planner: request plan(contract, schema)
  Planner->>Planner: diff -> OpFactoryCall[]
  Dev->>Runner: runner.execute(plan)
  Runner->>Runner: use deps.commandExecutor / deps.inspectionExecutor / deps.markerOps
  Runner->>DB: execute DDL & inspection via executors
  Runner->>DB: read/update marker via markerOps
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🐇
I hop where planners used to hide,
I stitch dependencies side by side,
Visitors whisper, factories call,
TypeScript prints the migration's hall,
A carrot-coded warren, tidy and wide.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately summarizes the primary changes: moving the Mongo migration subsystem to the target package and adding planner dual output (planCalls and rendering capabilities).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch migration-subsystem-refactor

Comment @coderabbitai help to get the list of available commands and usage tips.

wmadden added 9 commits April 16, 2026 08:03
…o to target-mongo

Move planner, runner, serializer, and helper modules (contract-to-schema,
ddl-formatter, filter-evaluator) from adapter-mongo to target-mongo to
correct package layering. These modules operate on AST/IR and have no
runtime dependency on the mongodb driver.

Refactor MongoMigrationRunner to accept an executor factory via constructor
injection, removing its direct dependency on MongoCommandExecutor and
MongoInspectionExecutor. The runner file no longer imports from mongodb.

Adapter-mongo retains backward-compatible re-exports from target-mongo
and keeps the concrete executor implementations (command-executor,
introspect-schema, mongo-control-driver).
… adapter re-exports

Decouple MongoMigrationRunner from the mongodb driver by replacing
direct marker-ledger function calls with a MarkerOperations interface
injected via a RunnerDependenciesFactory. The runner no longer imports
Db or any mongodb types.

Remove all 12 backward-compat re-exports from adapter-mongo control.ts.
Update 8 consumer files (integration tests, example tests) to import
moved symbols from @prisma-next/target-mongo/control directly.

Add createMongoRunnerDeps in adapter-mongo as the concrete factory that
constructs executors and marker ops from a control driver instance.
…dual renderers

Refactor MongoMigrationPlanner to produce OpFactoryCall[] via planCalls(),
then delegate plan() to planCalls() + renderOps(). This separates the
schema-diff logic from operation materialization, enabling both runtime
execution (renderOps) and code generation (renderTypeScript).

Add collMod factory function with meta overrides for id/label/operationClass.
Add schemaIndexToCreateIndexOptions and schemaCollectionToCreateCollectionOptions
helpers that extract creation options from schema IR types.

renderTypeScript generates complete runnable Migration files that import
from @prisma-next/family-mongo/migration and @prisma-next/target-mongo/migration.

260 tests pass including round-trip equivalence tests that verify
renderOps(planCalls()) produces identical JSON to the original plan().
…oryCall

Replace the plain discriminated-union OpFactoryCall type with frozen
subclasses (CreateIndexCall, DropIndexCall, CreateCollectionCall,
DropCollectionCall, CollModCall) extending an abstract base class, plus
an OpFactoryCallVisitor<R> interface. This matches the established
MongoAstNode/MongoDdlCommandVisitor pattern from mongo-query-ast.

Convert all switch-on-factory sites (renderOps, renderTypeScript,
operationClassForFactory, labelForCall) to visitor implementations.
Adding a new variant now forces all visitors to handle it at compile
time.
Codifies when and how to use the frozen-class/visitor pattern for
discriminated unions with multiple dispatch sites. Points to
MongoAstNode and OpFactoryCall as codebase examples.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

🧹 Nitpick comments (7)
packages/1-framework/3-tooling/migration/test/migration-base.test.ts (2)

56-56: Use timeout helper instead of hardcoded value.

Per repo guidelines, prefer @prisma-next/test-utils timeout helpers over hardcoded numbers.

♻️ Suggested fix
+import { timeouts } from '@prisma-next/test-utils';
+
-describe('Migration.run() subprocess', { timeout: 15_000 }, () => {
+describe('Migration.run() subprocess', { timeout: timeouts.subprocess }, () => {

Note: Verify the appropriate timeout constant name in @prisma-next/test-utils/timeouts.ts (e.g., subprocess, typeScriptCompilation, or similar).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/3-tooling/migration/test/migration-base.test.ts` at line
56, Replace the hardcoded timeout 15_000 in the describe block for
"Migration.run() subprocess" with the shared timeout constant from
`@prisma-next/test-utils`: import the appropriate constant (e.g., subprocess or
typeScriptCompilation) from '@prisma-next/test-utils/timeouts' and use that
constant in the describe call (the describe('Migration.run() subprocess', {
timeout: ... }) invocation); ensure you add the import at the top of the file
and use the correctly named exported symbol so the test follows the repo timeout
helper convention.

196-202: Consider using toMatchObject for related assertions.

Per coding guidelines, prefer object matchers over multiple individual expect().toBe() calls when checking 2+ related values.

♻️ Suggested refactor
-      expect(manifest.from).toBe('abc123');
-      expect(manifest.to).toBe('def456');
-      expect(manifest.labels).toEqual(['add-users']);
-      expect(manifest.migrationId).toBeNull();
-      expect(manifest.kind).toBe('regular');
-      expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
+      expect(manifest).toMatchObject({
+        from: 'abc123',
+        to: 'def456',
+        labels: ['add-users'],
+        migrationId: null,
+        kind: 'regular',
+      });
+      expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/3-tooling/migration/test/migration-base.test.ts` around
lines 196 - 202, Replace the multiple individual assertions on the parsed
manifest with a single object matcher: instead of separate
expect(manifest.from).toBe(...), expect(manifest.to).toBe(...),
expect(manifest.labels)... and expect(manifest.migrationId)..., use
expect(manifest).toMatchObject({ from: 'abc123', to: 'def456', labels:
['add-users'], migrationId: null, kind: 'regular' }) and keep the createdAt
assertion as-is (e.g.,
expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/)); update the test that
parses migration.json (variable manifest in migration-base.test.ts) to use
toMatchObject for the related fields.
packages/3-mongo-target/1-mongo-target/src/exports/control.ts (1)

18-27: Avoid exposing the concrete AST classes on the public control surface.

Re-exporting CollModCall/CreateIndexCall/etc. bakes the current class-based representation into the API and makes the plain-data-vs-AST decision much harder to change later. Prefer exported interfaces/factories here and keep the classes internal. As per coding guidelines, “Export interfaces and factory functions for public APIs; keep concrete classes as private implementation details”.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/1-mongo-target/src/exports/control.ts` around lines
18 - 27, The current file re-exports concrete AST classes (CollModCall,
CreateCollectionCall, CreateIndexCall, DropCollectionCall, DropIndexCall) which
leaks implementation details; change this export surface to expose only
plain-data interfaces and/or factory functions (e.g., Export an ICollModCall,
ICreateCollectionCall, ICreateIndexCall, IDropCollectionCall, IDropIndexCall or
factory creators) while removing direct re-exports of the class symbols
(CollModCall, CreateCollectionCall, CreateIndexCall, DropCollectionCall,
DropIndexCall) so the class implementations remain internal to
../core/op-factory-call; keep existing exported types like CollModMeta,
OpFactoryCall, OpFactoryCallVisitor but add or re-export interface types and
factory functions instead of the classes.
packages/2-mongo-family/9-family/README.md (1)

105-119: Consider using a named class in the example.

The anonymous class pattern (export default class extends Migration) combined with Migration.run(import.meta.url) doesn't demonstrate the actual API correctly. The other example migrations in this PR (e.g., examples/mongo-demo/migrations/.../migration.ts) use named classes.

📝 Suggested improvement
-export default class extends Migration {
+class AddUsersCollection extends Migration {
   describe() {
     return { from: "abc123", to: "def456", labels: ["add-users"] }
   }

   plan() {
     return [
       createCollection("users", {
         validator: { $jsonSchema: { required: ["email"] } },
         validationLevel: "strict",
       }),
       createIndex("users", [{ field: "email", direction: 1 }], { unique: true }),
     ]
   }
 }

-Migration.run(import.meta.url)
+export default AddUsersCollection;
+Migration.run(import.meta.url, AddUsersCollection)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/9-family/README.md` around lines 105 - 119, Replace
the anonymous "export default class extends Migration" with a named class (e.g.,
"class AddUsersMigration extends Migration") and export that name (or export
default the named class) so examples using Migration.run(import.meta.url) map to
a concrete class name; update the describe() and plan() methods remain unchanged
and keep references to createCollection and createIndex inside the named class.
packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts (1)

1-1208: Consider splitting this test file in a follow-up.

This file is 1208 lines, significantly exceeding the 500-line guideline. Consider splitting by functionality in a follow-up PR:

  • mongo-planner.index-diffing.test.ts
  • mongo-planner.validator-diffing.test.ts
  • mongo-planner.collection-lifecycle.test.ts
  • mongo-planner.plan-calls.test.ts

As per coding guidelines: "Keep test files under 500 lines to maintain readability and navigability."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts` around
lines 1 - 1208, The test file exceeds the 500-line guideline; split the large
mongo-planner test into smaller, focused files by moving the relevant describe
blocks into separate test files (e.g., create
mongo-planner.index-diffing.test.ts containing the "index diffing" describe,
mongo-planner.validator-diffing.test.ts for "validator diffing",
mongo-planner.collection-lifecycle.test.ts for "collection lifecycle" and
ordering/plan metadata as appropriate, and mongo-planner.plan-calls.test.ts for
the "planCalls" describe). Ensure each new file imports the same utilities and
types used here (MongoMigrationPlanner, planSuccess/planCallsSuccess helpers,
CollModCall/CreateIndexCall, MongoSchemaIR/Collection/Index/Validator, and the
makeContract/ascIndex helpers or move those helpers into a shared test-utils
file) so tests compile and preserve the existing describe/it blocks and
assertions unchanged.
examples/retail-store/test/manual-migration.test.ts (1)

60-69: Consider using object matcher for manifest assertions.

Multiple individual assertions on the same object can be consolidated for better readability and more actionable failure messages.

♻️ Suggested refactor
     it('migration.json has expected structure', () => {
       const manifest = JSON.parse(readFileSync(resolve(migrationDir, 'migration.json'), 'utf-8'));

-      expect(manifest.migrationId).toBeNull();
-      expect(manifest.kind).toBe('regular');
-      expect(manifest.labels).toEqual(['add-product-validation']);
-      expect(manifest.from).toMatch(/^sha256:/);
-      expect(manifest.to).toMatch(/^sha256:/);
-      expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
+      expect(manifest).toMatchObject({
+        migrationId: null,
+        kind: 'regular',
+        labels: ['add-product-validation'],
+      });
+      expect(manifest.from).toMatch(/^sha256:/);
+      expect(manifest.to).toMatch(/^sha256:/);
+      expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
     });

As per coding guidelines: "Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests"

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/retail-store/test/manual-migration.test.ts` around lines 60 - 69,
Consolidate the multiple expects in the "migration.json has expected structure"
test by asserting the parsed manifest object with a single object matcher:
replace the individual expect(manifest.*) calls with one assertion using
expect(manifest).toEqual or
expect(manifest).toMatchObject/expect.objectContaining that verifies
migrationId: null, kind: 'regular', labels: ['add-product-validation'] and uses
expect.stringMatching(/ˆsha256:/) (or expect.stringMatching) for from and to and
expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/) for createdAt; update the test
block that defines manifest accordingly to improve readability and failure
messages.
packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts (1)

1-556: Consider splitting this test file in a follow-up.

This file is 556 lines, slightly over the 500-line guideline. Consider splitting by factory type in a follow-up:

  • migration-factories.index.test.ts (createIndex, dropIndex)
  • migration-factories.collection.test.ts (createCollection, dropCollection)
  • migration-factories.validation.test.ts (setValidation, collMod, validatedCollection)
  • migration-factories.serialization.test.ts (round-trip tests)

As per coding guidelines: "Keep test files under 500 lines to maintain readability and navigability."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts`
around lines 1 - 556, The test file exceeds the 500-line guideline; split tests
by factory into separate files to improve readability: move createIndex and
dropIndex describe blocks into migration-factories.index.test.ts, move
createCollection and dropCollection describe blocks into
migration-factories.collection.test.ts, move setValidation, collMod, and
validatedCollection describe blocks into migration-factories.validation.test.ts,
and move the serialization round-trip describe block into
migration-factories.serialization.test.ts; ensure each new file imports the same
symbols used in its tests (e.g., createIndex, dropIndex, createCollection,
dropCollection, setValidation, collMod, validatedCollection, plus
ListIndexesCommand, CreateIndexCommand, CreateCollectionCommand,
DropCollectionCommand, CollModCommand, MongoFieldFilter, MongoAndExpr,
keysToKeySpec, defaultMongoIndexName, buildIndexOpId) and preserve all
assertions and test names exactly so behavior and JSON round-trip comparisons
remain unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.agents/skills/ast-visitor-pattern/SKILL.md:
- Around line 19-47: Add a minimal BazNode class to the example so BazNode is
declared and the union Foo and visitor FooVisitor type-check; implement BazNode
as a subclass of FooNode with readonly kind = 'baz', a readonly field (e.g.,
count: number), a constructor that sets the field and calls this.freeze(), and
an accept<R>(visitor: FooVisitor<R>): R method that calls visitor.baz(this);
ensure the new class name BazNode matches all existing references
(FooVisitor.baz, Foo union) so the snippet is copy/paste friendly.

In `@packages/2-mongo-family/9-family/README.md`:
- Line 121: Update the README example to call Migration.run with the required
second argument: pass the migration class (e.g., AddUsersCollection) as the
second parameter to Migration.run(import.meta.url, AddUsersCollection); ensure
the migration shown above follows the named class pattern (export default class
AddUsersCollection extends Migration) so the identifier matches the call.

In `@packages/3-mongo-target/1-mongo-target/README.md`:
- Around line 39-52: The README example defines an anonymous default class that
implements plan() but then calls Migration.run(import.meta.url) with only one
argument; update the example to export a named migration class (e.g.,
UsersMigration extends Migration) that contains the plan() method and invoke
Migration.run(import.meta.url, UsersMigration) so the required second parameter
(the MigrationClass) is passed; keep the existing plan implementation
(createCollection/createIndex) and the Migration.run call updated to reference
the named class.

In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts`:
- Around line 31-46: buildIndexLookupKey() currently omits the index name so
renames go undetected; update the function (buildIndexLookupKey) to include the
index's explicit name in the constructed lookup key (e.g., add a
"name:<index.name>" token into the opts array when index.name exists, taking
care to use a stable representation for empty/undefined names) so that indexes
with identical keys/options but different names are treated as different entries
by the planner.
- Around line 171-175: The code currently only emits a CreateCollectionCall when
collectionHasOptions(destColl) is true, so plain new collections with no options
get no create op; update the block in the !originColl && destColl branch to
always push a CreateCollectionCall for collName and pass options only when
present (e.g., compute opts = collectionHasOptions(destColl) ?
schemaCollectionToCreateCollectionOptions(destColl) : undefined; then
collCreates.push(new CreateCollectionCall(collName, opts))); keep using the
existing helpers (collectionHasOptions,
schemaCollectionToCreateCollectionOptions) and the CreateCollectionCall and
collName identifiers.

In `@packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts`:
- Around line 33-35: The freeze() method on OpFactoryCall (in
op-factory-call.ts) only freezes the outer object, leaving nested payload
properties (keys, options, meta) mutable; update freeze() to perform a deep
freeze (or clone-then-freeze) of those nested objects so the AST node becomes
fully immutable—use a well-established utility (e.g., lodash's cloneDeep +
freeze, or Object.freeze combined with a robust deep-freeze helper) or a modern
native pattern to recursively freeze keys, options, and meta before calling
Object.freeze(this), ensuring functions/methods that construct planned calls
(e.g., the OpFactoryCall constructor) pass through this new deep-freeze step.
- Around line 136-147: The mapper schemaIndexToCreateIndexOptions currently
omits explicit index names from the returned CreateIndexOptions; update
schemaIndexToCreateIndexOptions (and use the MongoSchemaIndex.name field) to
include the index name (e.g., set name: index.name || undefined) so that
CreateIndexOptions preserves contract-defined index names instead of letting
Mongo generate one.

In `@packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts`:
- Around line 1-15: The renderer renderTypeScript currently imports
MigrationMeta from `@prisma-next/migration-tools`, violating the core plane
boundary; fix by either (A) moving the renderTypeScript implementation out of
the shared core into the migration-plane module so it may keep using the
MigrationMeta type, or (B) remove the external MigrationMeta import and define a
local metadata shape (e.g., a MigrationMetaLocal interface or use a
generic/unknown meta param) in the same module and update
renderTypeScript(calls, meta?) signature and all callers to use that local
shape; ensure no direct import of MigrationMeta remains in this file.
- Around line 120-121: renderKey currently emits keys matching the identifier
regex unquoted, which leaves "__proto__" unquoted and thus sets an object's
prototype; modify renderKey to explicitly treat "__proto__" as a quoted key
(i.e., return JSON.stringify(key) for key === "__proto__") even if it matches
/^[a-zA-Z_$][a-zA-Z0-9_$]*$/, so that emitting object literals uses a normal own
property for "__proto__" instead of altering the prototype.

In `@packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts`:
- Around line 12-20: The function extractDb uses a blind cast to assume driver
has a db property; replace that with a proper type guard: add a predicate (e.g.,
isMongoDriverWithDb(driver): driver is ControlDriverInstance<'mongo','mongo'> &
{ db: Db }) that checks Object.hasOwn(driver, 'db') and that driver.db is
truthy, then use that predicate in extractDb to narrow the type and safely
return mongoDriver.db or throw the same Error; update references to
ControlDriverInstance and mongoDriver.db accordingly.

In `@packages/3-mongo-target/2-mongo-adapter/src/exports/control.ts`:
- Line 9: The test import is pulling initMarker from the wrong package; update
the import in db-verify-sign.test.ts so it imports initMarker from
`@prisma-next/target-mongo/control` (where initMarker is actually exported)
instead of `@prisma-next/adapter-mongo/control`; locate the import line for
initMarker in db-verify-sign.test.ts and change the module path to
`@prisma-next/target-mongo/control` so the test imports the correct symbol.

---

Nitpick comments:
In `@examples/retail-store/test/manual-migration.test.ts`:
- Around line 60-69: Consolidate the multiple expects in the "migration.json has
expected structure" test by asserting the parsed manifest object with a single
object matcher: replace the individual expect(manifest.*) calls with one
assertion using expect(manifest).toEqual or
expect(manifest).toMatchObject/expect.objectContaining that verifies
migrationId: null, kind: 'regular', labels: ['add-product-validation'] and uses
expect.stringMatching(/ˆsha256:/) (or expect.stringMatching) for from and to and
expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/) for createdAt; update the test
block that defines manifest accordingly to improve readability and failure
messages.

In `@packages/1-framework/3-tooling/migration/test/migration-base.test.ts`:
- Line 56: Replace the hardcoded timeout 15_000 in the describe block for
"Migration.run() subprocess" with the shared timeout constant from
`@prisma-next/test-utils`: import the appropriate constant (e.g., subprocess or
typeScriptCompilation) from '@prisma-next/test-utils/timeouts' and use that
constant in the describe call (the describe('Migration.run() subprocess', {
timeout: ... }) invocation); ensure you add the import at the top of the file
and use the correctly named exported symbol so the test follows the repo timeout
helper convention.
- Around line 196-202: Replace the multiple individual assertions on the parsed
manifest with a single object matcher: instead of separate
expect(manifest.from).toBe(...), expect(manifest.to).toBe(...),
expect(manifest.labels)... and expect(manifest.migrationId)..., use
expect(manifest).toMatchObject({ from: 'abc123', to: 'def456', labels:
['add-users'], migrationId: null, kind: 'regular' }) and keep the createdAt
assertion as-is (e.g.,
expect(manifest.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/)); update the test that
parses migration.json (variable manifest in migration-base.test.ts) to use
toMatchObject for the related fields.

In `@packages/2-mongo-family/9-family/README.md`:
- Around line 105-119: Replace the anonymous "export default class extends
Migration" with a named class (e.g., "class AddUsersMigration extends
Migration") and export that name (or export default the named class) so examples
using Migration.run(import.meta.url) map to a concrete class name; update the
describe() and plan() methods remain unchanged and keep references to
createCollection and createIndex inside the named class.

In `@packages/3-mongo-target/1-mongo-target/src/exports/control.ts`:
- Around line 18-27: The current file re-exports concrete AST classes
(CollModCall, CreateCollectionCall, CreateIndexCall, DropCollectionCall,
DropIndexCall) which leaks implementation details; change this export surface to
expose only plain-data interfaces and/or factory functions (e.g., Export an
ICollModCall, ICreateCollectionCall, ICreateIndexCall, IDropCollectionCall,
IDropIndexCall or factory creators) while removing direct re-exports of the
class symbols (CollModCall, CreateCollectionCall, CreateIndexCall,
DropCollectionCall, DropIndexCall) so the class implementations remain internal
to ../core/op-factory-call; keep existing exported types like CollModMeta,
OpFactoryCall, OpFactoryCallVisitor but add or re-export interface types and
factory functions instead of the classes.

In `@packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts`:
- Around line 1-556: The test file exceeds the 500-line guideline; split tests
by factory into separate files to improve readability: move createIndex and
dropIndex describe blocks into migration-factories.index.test.ts, move
createCollection and dropCollection describe blocks into
migration-factories.collection.test.ts, move setValidation, collMod, and
validatedCollection describe blocks into migration-factories.validation.test.ts,
and move the serialization round-trip describe block into
migration-factories.serialization.test.ts; ensure each new file imports the same
symbols used in its tests (e.g., createIndex, dropIndex, createCollection,
dropCollection, setValidation, collMod, validatedCollection, plus
ListIndexesCommand, CreateIndexCommand, CreateCollectionCommand,
DropCollectionCommand, CollModCommand, MongoFieldFilter, MongoAndExpr,
keysToKeySpec, defaultMongoIndexName, buildIndexOpId) and preserve all
assertions and test names exactly so behavior and JSON round-trip comparisons
remain unchanged.

In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts`:
- Around line 1-1208: The test file exceeds the 500-line guideline; split the
large mongo-planner test into smaller, focused files by moving the relevant
describe blocks into separate test files (e.g., create
mongo-planner.index-diffing.test.ts containing the "index diffing" describe,
mongo-planner.validator-diffing.test.ts for "validator diffing",
mongo-planner.collection-lifecycle.test.ts for "collection lifecycle" and
ordering/plan metadata as appropriate, and mongo-planner.plan-calls.test.ts for
the "planCalls" describe). Ensure each new file imports the same utilities and
types used here (MongoMigrationPlanner, planSuccess/planCallsSuccess helpers,
CollModCall/CreateIndexCall, MongoSchemaIR/Collection/Index/Validator, and the
makeContract/ascIndex helpers or move those helpers into a shared test-utils
file) so tests compile and preserve the existing describe/it blocks and
assertions unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 219688f4-a5f7-458e-b745-839d7c4bc9e6

📥 Commits

Reviewing files that changed from the base of the PR and between 31ce5a7 and 918f7f2.

⛔ Files ignored due to path filters (8)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/mongo-migration-authoring/assets/migration-authoring-design.md is excluded by !projects/**
  • projects/mongo-migration-authoring/plan.md is excluded by !projects/**
  • projects/mongo-migration-authoring/plans/data-migrations-plan.md is excluded by !projects/**
  • projects/mongo-migration-authoring/spec.md is excluded by !projects/**
  • projects/mongo-migration-authoring/specs/data-migrations.spec.md is excluded by !projects/**
  • projects/mongo-migration-authoring/specs/migration-subsystem-refactor.spec.md is excluded by !projects/**
  • projects/mongo-migration-authoring/specs/planner-dual-output.spec.md is excluded by !projects/**
📒 Files selected for processing (57)
  • .agents/skills/ast-visitor-pattern/SKILL.md
  • examples/mongo-demo/migrations/20260415_add-posts-author-index/migration.json
  • examples/mongo-demo/migrations/20260415_add-posts-author-index/migration.ts
  • examples/mongo-demo/migrations/20260415_add-posts-author-index/ops.json
  • examples/mongo-demo/package.json
  • examples/mongo-demo/test/manual-migration.test.ts
  • examples/retail-store/migrations/20260415_add-product-validation/migration.json
  • examples/retail-store/migrations/20260415_add-product-validation/migration.ts
  • examples/retail-store/migrations/20260415_add-product-validation/ops.json
  • examples/retail-store/package.json
  • examples/retail-store/test/manual-migration.test.ts
  • packages/1-framework/3-tooling/migration/package.json
  • packages/1-framework/3-tooling/migration/src/exports/migration.ts
  • packages/1-framework/3-tooling/migration/src/migration-base.ts
  • packages/1-framework/3-tooling/migration/test/migration-base.test.ts
  • packages/1-framework/3-tooling/migration/tsdown.config.ts
  • packages/2-mongo-family/9-family/README.md
  • packages/2-mongo-family/9-family/package.json
  • packages/2-mongo-family/9-family/src/core/control-instance.ts
  • packages/2-mongo-family/9-family/src/core/mongo-migration.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • packages/2-mongo-family/9-family/src/exports/migration.ts
  • packages/2-mongo-family/9-family/tsdown.config.ts
  • packages/3-mongo-target/1-mongo-target/README.md
  • packages/3-mongo-target/1-mongo-target/package.json
  • packages/3-mongo-target/1-mongo-target/src/core/contract-to-schema.ts
  • packages/3-mongo-target/1-mongo-target/src/core/ddl-formatter.ts
  • packages/3-mongo-target/1-mongo-target/src/core/filter-evaluator.ts
  • packages/3-mongo-target/1-mongo-target/src/core/migration-factories.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts
  • packages/3-mongo-target/1-mongo-target/src/core/render-ops.ts
  • packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/migration.ts
  • packages/3-mongo-target/1-mongo-target/test/contract-to-schema.test.ts
  • packages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.ts
  • packages/3-mongo-target/1-mongo-target/test/filter-evaluator.test.ts
  • packages/3-mongo-target/1-mongo-target/test/migration-e2e.test.ts
  • packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-ops-serializer.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts
  • packages/3-mongo-target/1-mongo-target/test/render-ops.test.ts
  • packages/3-mongo-target/1-mongo-target/test/render-typescript.test.ts
  • packages/3-mongo-target/1-mongo-target/tsdown.config.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/mongo-planner.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • packages/3-mongo-target/2-mongo-adapter/src/exports/control.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
  • test/integration/test/cli.mongo-db-sign.e2e.test.ts
  • test/integration/test/cli.mongo-db-verify.e2e.test.ts
  • test/integration/test/mongo/migration-authoring-e2e.test.ts
  • test/integration/test/mongo/migration-e2e.test.ts
  • test/integration/test/mongo/migration-m2-vocabulary.test.ts
  • test/integration/test/mongo/migration-psl-authoring.test.ts
💤 Files with no reviewable changes (1)
  • packages/3-mongo-target/2-mongo-adapter/src/core/mongo-planner.ts

@wmadden
wmadden force-pushed the migration-subsystem-refactor branch from 918f7f2 to 55ba9f4 Compare April 16, 2026 05:08
@pkg-pr-new

pkg-pr-new Bot commented Apr 16, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-runtime@348

@prisma-next/family-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-mongo@348

@prisma-next/sql-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-runtime@348

@prisma-next/family-sql

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-sql@348

@prisma-next/middleware-telemetry

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/middleware-telemetry@348

@prisma-next/mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo@348

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-paradedb@348

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-pgvector@348

@prisma-next/postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/postgres@348

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-orm-client@348

@prisma-next/sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sqlite@348

@prisma-next/target-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-mongo@348

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-mongo@348

@prisma-next/driver-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-mongo@348

@prisma-next/contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract@348

@prisma-next/utils

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/utils@348

@prisma-next/config

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/config@348

@prisma-next/errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/errors@348

@prisma-next/framework-components

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/framework-components@348

@prisma-next/operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/operations@348

@prisma-next/contract-authoring

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-authoring@348

@prisma-next/ids

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ids@348

@prisma-next/psl-parser

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-parser@348

@prisma-next/psl-printer

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-printer@348

@prisma-next/cli

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli@348

@prisma-next/emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/emitter@348

@prisma-next/migration-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/migration-tools@348

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/vite-plugin-contract-emit@348

@prisma-next/runtime-executor

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/runtime-executor@348

@prisma-next/mongo-codec

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-codec@348

@prisma-next/mongo-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract@348

@prisma-next/mongo-value

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-value@348

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-psl@348

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-ts@348

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-emitter@348

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-schema-ir@348

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-ast@348

@prisma-next/mongo-orm

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-orm@348

@prisma-next/mongo-pipeline-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-pipeline-builder@348

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-lowering@348

@prisma-next/mongo-wire

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-wire@348

@prisma-next/sql-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract@348

@prisma-next/sql-errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-errors@348

@prisma-next/sql-operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-operations@348

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-schema-ir@348

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-psl@348

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-ts@348

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-emitter@348

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane-query-builder@348

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-relational-core@348

@prisma-next/sql-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-builder@348

@prisma-next/target-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-postgres@348

@prisma-next/target-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-sqlite@348

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-postgres@348

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-sqlite@348

@prisma-next/driver-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-postgres@348

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-sqlite@348

commit: 23590db

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

♻️ Duplicate comments (2)
packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts (2)

120-121: ⚠️ Potential issue | 🔴 Critical

Quote __proto__ keys when emitting object literals.

Line 121 can emit __proto__ unquoted, which changes object prototype semantics instead of emitting a normal own property in generated migration code.

Suggested fix
 function renderKey(key: string): string {
+  if (key === '__proto__') return JSON.stringify(key);
   return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
 }
#!/bin/bash
node <<'EOF'
const a = ({ __proto__: { polluted: true }, x: 1 });
const b = ({ "__proto__": { polluted: true }, x: 1 });
console.log('a own __proto__:', Object.hasOwn(a, '__proto__')); // false
console.log('b own __proto__:', Object.hasOwn(b, '__proto__')); // true
EOF
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts` around
lines 120 - 121, The renderKey function currently returns an unquoted identifier
for keys matching /^[a-zA-Z_$][a-zA-Z0-9_$]*$/, which will emit __proto__
unquoted and change prototype semantics; update renderKey to treat "__proto__"
as a non-identifier and return JSON.stringify(key) for that specific string
(i.e., in function renderKey(key: string) add a guard like if (key ===
"__proto__") return JSON.stringify(key) before the regex test, or modify the
condition to require key !== "__proto__" so __proto__ is always quoted).

1-15: ⚠️ Potential issue | 🟠 Major

src/core imports migration-plane type directly (layer boundary break).

This file imports MigrationMeta from @prisma-next/migration-tools/migration, which introduces a plane-crossing dependency in shared core.

As per coding guidelines, packages/**/src/core/**: “Keep src/core/** free of migration/runtime imports; depend only on shared-plane packages.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts` around
lines 1 - 15, The file imports MigrationMeta from
`@prisma-next/migration-tools/migration` which breaks the core/shared-plane
boundary; replace that direct migration-plane import by depending only on a
shared-plane type (or by declaring a local minimal MigrationMeta interface) and
update the renderTypeScript signature to use the shared/local type instead of
MigrationMeta; specifically change the import of MigrationMeta and any type
annotations in the renderTypeScript(calls: ReadonlyArray<OpFactoryCall>, meta?:
MigrationMeta) declaration to reference the new shared-local type so src/core
stays free of migration/runtime imports.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/3-mongo-target/1-mongo-target/src/core/migration-factories.ts`:
- Around line 210-223: The postcheck currently only adds filters for collection
name and optional validationLevel/validationAction, so when options.validator is
present but those two are omitted the check only verifies collection existence;
update the postcheck building in migration-factories.ts (the block that
constructs the ListCollectionsCommand filter used when hasValidator is true) to
also include a MongoFieldFilter for the validator when options.validator is
provided (e.g. add MongoFieldFilter.eq('options.validator', options.validator)
or an appropriate deep-equality check) alongside the existing
MongoFieldFilter.eq('name', collection) so the "validator applied" check
actually verifies the validator contents.

In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts`:
- Around line 13-18: The imports for MongoDdlCommandVisitor and
MongoInspectionCommandVisitor in mongo-runner.ts are coming from the
migration/control plane; move those types to a shared-plane export and update
the import to avoid a plane-crossing dependency: add or use an existing
shared-plane module that re-exports MongoDdlCommandVisitor and
MongoInspectionCommandVisitor (e.g., from a shared types package), change the
imports in the file to import these two symbols from that shared-plane module
instead of '@prisma-next/mongo-query-ast/control', and keep other
control-plane-only symbols (MongoMigrationCheck, MongoMigrationPlanOperation)
untouched so src/core remains free of migration/runtime imports.
- Around line 58-60: The MongoMigrationRunner is incorrectly bound to the
constructor-injected driver (deps) so execute() ignores the runtime
options.driver; update the class so execute() uses the driver passed in options
(options.driver) rather than always using constructor deps, or fall back to deps
only if options.driver is absent; inspect and change the MongoMigrationRunner
constructor/fields and the execute(...) implementation to reference the runtime
driver symbol (options.driver) and remove any hard-coded use of deps.driver so a
single runner can run against multiple drivers.

---

Duplicate comments:
In `@packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts`:
- Around line 120-121: The renderKey function currently returns an unquoted
identifier for keys matching /^[a-zA-Z_$][a-zA-Z0-9_$]*$/, which will emit
__proto__ unquoted and change prototype semantics; update renderKey to treat
"__proto__" as a non-identifier and return JSON.stringify(key) for that specific
string (i.e., in function renderKey(key: string) add a guard like if (key ===
"__proto__") return JSON.stringify(key) before the regex test, or modify the
condition to require key !== "__proto__" so __proto__ is always quoted).
- Around line 1-15: The file imports MigrationMeta from
`@prisma-next/migration-tools/migration` which breaks the core/shared-plane
boundary; replace that direct migration-plane import by depending only on a
shared-plane type (or by declaring a local minimal MigrationMeta interface) and
update the renderTypeScript signature to use the shared/local type instead of
MigrationMeta; specifically change the import of MigrationMeta and any type
annotations in the renderTypeScript(calls: ReadonlyArray<OpFactoryCall>, meta?:
MigrationMeta) declaration to reference the new shared-local type so src/core
stays free of migration/runtime imports.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 9c06d6f8-6800-4138-9573-593522f8b994

📥 Commits

Reviewing files that changed from the base of the PR and between 918f7f2 and 55ba9f4.

⛔ Files ignored due to path filters (3)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/mongo-migration-authoring/specs/migration-subsystem-refactor.spec.md is excluded by !projects/**
  • projects/mongo-migration-authoring/specs/planner-dual-output.spec.md is excluded by !projects/**
📒 Files selected for processing (38)
  • .agents/skills/ast-visitor-pattern/SKILL.md
  • examples/mongo-demo/test/manual-migration.test.ts
  • examples/retail-store/test/manual-migration.test.ts
  • packages/2-mongo-family/9-family/src/core/control-instance.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • packages/3-mongo-target/1-mongo-target/package.json
  • packages/3-mongo-target/1-mongo-target/src/core/contract-to-schema.ts
  • packages/3-mongo-target/1-mongo-target/src/core/ddl-formatter.ts
  • packages/3-mongo-target/1-mongo-target/src/core/filter-evaluator.ts
  • packages/3-mongo-target/1-mongo-target/src/core/migration-factories.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts
  • packages/3-mongo-target/1-mongo-target/src/core/render-ops.ts
  • packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/migration.ts
  • packages/3-mongo-target/1-mongo-target/test/contract-to-schema.test.ts
  • packages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.ts
  • packages/3-mongo-target/1-mongo-target/test/filter-evaluator.test.ts
  • packages/3-mongo-target/1-mongo-target/test/migration-e2e.test.ts
  • packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-ops-serializer.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts
  • packages/3-mongo-target/1-mongo-target/test/render-ops.test.ts
  • packages/3-mongo-target/1-mongo-target/test/render-typescript.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/mongo-planner.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • packages/3-mongo-target/2-mongo-adapter/src/exports/control.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
  • test/integration/test/cli.mongo-db-sign.e2e.test.ts
  • test/integration/test/cli.mongo-db-verify.e2e.test.ts
  • test/integration/test/mongo/db-verify-sign.test.ts
  • test/integration/test/mongo/migration-authoring-e2e.test.ts
  • test/integration/test/mongo/migration-e2e.test.ts
  • test/integration/test/mongo/migration-m2-vocabulary.test.ts
  • test/integration/test/mongo/migration-psl-authoring.test.ts
💤 Files with no reviewable changes (1)
  • packages/3-mongo-target/2-mongo-adapter/src/core/mongo-planner.ts
✅ Files skipped from review due to trivial changes (7)
  • test/integration/test/mongo/migration-psl-authoring.test.ts
  • packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/migration.ts
  • packages/3-mongo-target/1-mongo-target/test/render-typescript.test.ts
  • .agents/skills/ast-visitor-pattern/SKILL.md
  • test/integration/test/mongo/migration-m2-vocabulary.test.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts
🚧 Files skipped from review as they are similar to previous changes (13)
  • test/integration/test/cli.mongo-db-verify.e2e.test.ts
  • examples/retail-store/test/manual-migration.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • test/integration/test/mongo/migration-authoring-e2e.test.ts
  • test/integration/test/mongo/migration-e2e.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/exports/control.ts
  • test/integration/test/cli.mongo-db-sign.e2e.test.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
  • packages/3-mongo-target/1-mongo-target/test/migration-e2e.test.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
  • packages/3-mongo-target/1-mongo-target/package.json
  • packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts

wmadden added 3 commits April 16, 2026 08:18
…__proto__ key

Replace MigrationMeta import from @prisma-next/migration-tools/migration with a
local RenderMigrationMeta type to keep src/core/ within the shared plane.

Add explicit __proto__ check in renderKey to prevent prototype pollution in
generated object literals.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/3-mongo-target/1-mongo-target/src/exports/control.ts (1)

3-3: Avoid exposing concrete classes in the public control API.

Re-exporting concrete implementations (FilterEvaluator, MongoMigrationPlanner, MongoMigrationRunner, and *Call classes) makes internal refactors breaking for consumers. Prefer exposing interfaces/types + factory functions from this surface.

As per coding guidelines, "Export interfaces and factory functions for public APIs; keep concrete classes as private implementation details."

Also applies to: 11-13, 16-20

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/1-mongo-target/src/exports/control.ts` at line 3, The
public control surface is exporting concrete classes (e.g., FilterEvaluator,
MongoMigrationPlanner, MongoMigrationRunner and the *Call classes); change these
exports to expose only interfaces/types and factory functions instead: define
and export interfaces (e.g., IFilterEvaluator, IMongoMigrationPlanner,
IMongoMigrationRunner or export existing types) and implement private concrete
classes inside the package, then add and export factory functions (e.g.,
createFilterEvaluator(...), createMongoMigrationPlanner(...),
createMongoMigrationRunner(...), createXCall(...)) that return the interface
types; update the export list in control.ts to export the interfaces and the new
factory function names and remove re-exports of the concrete class symbols so
consumers depend on interfaces/factories only.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/3-mongo-target/1-mongo-target/src/exports/control.ts`:
- Line 3: The public control surface is exporting concrete classes (e.g.,
FilterEvaluator, MongoMigrationPlanner, MongoMigrationRunner and the *Call
classes); change these exports to expose only interfaces/types and factory
functions instead: define and export interfaces (e.g., IFilterEvaluator,
IMongoMigrationPlanner, IMongoMigrationRunner or export existing types) and
implement private concrete classes inside the package, then add and export
factory functions (e.g., createFilterEvaluator(...),
createMongoMigrationPlanner(...), createMongoMigrationRunner(...),
createXCall(...)) that return the interface types; update the export list in
control.ts to export the interfaces and the new factory function names and
remove re-exports of the concrete class symbols so consumers depend on
interfaces/factories only.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: a044fa9d-4360-48cd-8e8a-59e604e3bb4e

📥 Commits

Reviewing files that changed from the base of the PR and between 55ba9f4 and 14d06f3.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • .agents/skills/ast-visitor-pattern/SKILL.md
  • packages/2-mongo-family/9-family/README.md
  • packages/3-mongo-target/1-mongo-target/README.md
  • packages/3-mongo-target/1-mongo-target/package.json
  • packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/3-mongo-target/1-mongo-target/package.json
  • .agents/skills/ast-visitor-pattern/SKILL.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/3-mongo-target/1-mongo-target/src/core/render-typescript.ts

wmadden added 2 commits April 16, 2026 08:28
MongoMigrationRunner no longer implements the framework MigrationRunner
interface directly — the wrapper in mongoTargetDescriptor.createRunner()
satisfies it instead. The runner accepts pre-constructed deps and has no
knowledge of drivers.
Exclude mongo-runner.ts from unit coverage (integration-tested in adapter).
Add tests for render-typescript edge cases (multiline arrays, null,
empty arrays/objects, __proto__ key quoting, bigint fallback, undefined
in arrays, special-char keys). Add tests for op-factory-call helpers
(bare collection, clusteredIndex mapping). Add tests for ddl-formatter
branches (max/timeseries/collation/clusteredIndex, command-less steps).
Add planner tests for sparse index lookup, timeseries/clusteredIndex
immutable changes, and policy violation labels. Refactor planner
if-else chain to simple if/else-if/else to avoid logically impossible
V8 branch. Add v8-ignore blocks for unreachable defensive fallbacks
in module-level visitors and serializer error handling.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts (1)

24-33: Consider documenting the single-driver invariant for the returned wrapper.

The cachedDeps ??= createMongoRunnerDeps(options.driver) pattern caches dependencies from the first execute() call. Subsequent calls will reuse these deps regardless of options.driver. This is safe given the current framework usage where each wrapper is tied to a single driver, but could become a subtle bug if that invariant changes.

Consider either:

  1. Adding a comment documenting this assumption, or
  2. Asserting the driver hasn't changed on subsequent calls
🛡️ Optional defensive check
 createRunner(_family: MongoControlFamilyInstance) {
   let cachedDeps: MongoRunnerDependencies | undefined;
+  let boundDriver: unknown;
   return {
     async execute(options) {
+      if (cachedDeps && boundDriver !== options.driver) {
+        throw new Error('Runner wrapper cannot be reused across different drivers');
+      }
       cachedDeps ??= createMongoRunnerDeps(options.driver);
+      boundDriver = options.driver;
       const { driver: _, ...runnerOptions } = options;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts` around
lines 24 - 33, The createRunner wrapper caches dependencies via cachedDeps ??=
createMongoRunnerDeps(options.driver) which assumes a single driver per wrapper;
add a short comment above the cachedDeps line documenting the single-driver
invariant for createRunner (or implement a defensive check: on subsequent
execute calls verify options.driver === cachedDeps.driver or throw) so callers
and future maintainers know the assumption; reference createRunner, cachedDeps,
createMongoRunnerDeps, MongoMigrationRunner and execute when making the change.
packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts (2)

1141-1152: Consider using toMatchObject for related property assertions.

Multiple separate assertions for collection and keys could be consolidated for clearer test output.

♻️ Optional refactor
     expect(calls).toHaveLength(1);
     expect(calls[0]).toBeInstanceOf(CreateIndexCall);
     const call = calls[0] as CreateIndexCall;
-    expect(call.collection).toBe('users');
-    expect(call.keys).toEqual([{ field: 'email', direction: 1 }]);
+    expect(call).toMatchObject({
+      collection: 'users',
+      keys: [{ field: 'email', direction: 1 }],
+    });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts` around
lines 1141 - 1152, Replace the two separate assertions on the CreateIndexCall
instance with a single object-shape assertion using toMatchObject: after getting
calls[0] (instanceof CreateIndexCall), assert that the call matches {
collection: 'users', keys: [{ field: 'email', direction: 1 }] } to consolidate
related property checks; keep the instanceof CreateIndexCall check and use
makeContract/planCallsSuccess/CreateIndexCall/calls to locate the code to
change.

1228-1233: Consider using toMatchObject for meta property assertions.

The three meta property assertions could be consolidated for clearer test output and reduced verbosity.

♻️ Optional refactor
     expect(calls).toHaveLength(1);
     expect(calls[0]).toBeInstanceOf(CollModCall);
     const call = calls[0] as CollModCall;
-    expect(call.meta?.id).toBe('validator.users.update');
-    expect(call.meta?.label).toBe('Update validator on users');
-    expect(call.meta?.operationClass).toBe('destructive');
+    expect(call.meta).toMatchObject({
+      id: 'validator.users.update',
+      label: 'Update validator on users',
+      operationClass: 'destructive',
+    });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts` around
lines 1228 - 1233, Replace the three separate assertions on the CollModCall meta
with a single consolidated assertion using toMatchObject: locate the test that
inspects calls[0] (instanceOf CollModCall), cast to call and replace the
expect(call.meta?.id), expect(call.meta?.label) and
expect(call.meta?.operationClass) lines with one
expect(call.meta).toMatchObject({ id: 'validator.users.update', label: 'Update
validator on users', operationClass: 'destructive' }) so the meta properties are
asserted in one clear statement.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts`:
- Around line 329-349: The planner currently passes
changeStreamPreAndPostImages: undefined to CollModCall when the destination
removed the property; change MongoSchemaCollectionOptions handling in
planMutableOptionsDiffCall so that if dest?.changeStreamPreAndPostImages is
undefined you pass { enabled: false } instead (e.g., const desiredCSPPI =
destCSPPI ?? { enabled: false }) and use desiredCSPPI in the CollModCall and to
compute operationClass; keep CollModCall, collName and the id/label fields
intact.

In `@packages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.ts`:
- Around line 367-385: Replace the direct "as never" cast on the no-op execute
step inside the test op with the double-cast pattern to preserve typing
boundaries; e.g. change "{ description: 'no-op step' } as never" to "{
description: 'no-op step' } as unknown as typeof op.execute[number]". Update the
execute array in the test (the op variable used with formatMongoOperations and
CreateIndexCommand) so the first step uses the double-cast instead of "as
never".

---

Nitpick comments:
In `@packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts`:
- Around line 24-33: The createRunner wrapper caches dependencies via cachedDeps
??= createMongoRunnerDeps(options.driver) which assumes a single driver per
wrapper; add a short comment above the cachedDeps line documenting the
single-driver invariant for createRunner (or implement a defensive check: on
subsequent execute calls verify options.driver === cachedDeps.driver or throw)
so callers and future maintainers know the assumption; reference createRunner,
cachedDeps, createMongoRunnerDeps, MongoMigrationRunner and execute when making
the change.

In `@packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts`:
- Around line 1141-1152: Replace the two separate assertions on the
CreateIndexCall instance with a single object-shape assertion using
toMatchObject: after getting calls[0] (instanceof CreateIndexCall), assert that
the call matches { collection: 'users', keys: [{ field: 'email', direction: 1 }]
} to consolidate related property checks; keep the instanceof CreateIndexCall
check and use makeContract/planCallsSuccess/CreateIndexCall/calls to locate the
code to change.
- Around line 1228-1233: Replace the three separate assertions on the
CollModCall meta with a single consolidated assertion using toMatchObject:
locate the test that inspects calls[0] (instanceOf CollModCall), cast to call
and replace the expect(call.meta?.id), expect(call.meta?.label) and
expect(call.meta?.operationClass) lines with one
expect(call.meta).toMatchObject({ id: 'validator.users.update', label: 'Update
validator on users', operationClass: 'destructive' }) so the meta properties are
asserted in one clear statement.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: bb505928-4144-4085-8c4b-6101648bf31f

📥 Commits

Reviewing files that changed from the base of the PR and between 14d06f3 and 7f6b994.

📒 Files selected for processing (16)
  • examples/mongo-demo/test/manual-migration.test.ts
  • examples/retail-store/test/manual-migration.test.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.ts
  • packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts
  • packages/3-mongo-target/1-mongo-target/test/render-typescript.test.ts
  • packages/3-mongo-target/1-mongo-target/vitest.config.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
  • test/integration/test/mongo/migration-authoring-e2e.test.ts
  • test/integration/test/mongo/migration-e2e.test.ts
  • test/integration/test/mongo/migration-m2-vocabulary.test.ts
  • test/integration/test/mongo/migration-psl-authoring.test.ts
✅ Files skipped from review due to trivial changes (5)
  • packages/3-mongo-target/1-mongo-target/vitest.config.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts
  • test/integration/test/mongo/migration-authoring-e2e.test.ts
  • packages/3-mongo-target/1-mongo-target/test/migration-factories.test.ts
  • packages/3-mongo-target/1-mongo-target/test/render-typescript.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • test/integration/test/mongo/migration-m2-vocabulary.test.ts
  • examples/retail-store/test/manual-migration.test.ts
  • test/integration/test/mongo/migration-psl-authoring.test.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
  • test/integration/test/mongo/migration-e2e.test.ts

… dest

planMutableOptionsDiffCall was passing undefined to CollModCall when the
destination removed changeStreamPreAndPostImages, which would be a no-op
instead of actually disabling the feature. Now defaults to { enabled: false }.

Also: use double-cast in ddl-formatter test, consolidate assertions
with toMatchObject in planner tests, add single-driver invariant
comment to createRunner wrapper.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts (1)

153-154: Consider runtime validation for external contract/schema.

The casts from unknown to MongoContract/MongoSchemaIR work correctly but rely on callers providing correctly-typed objects. Since these come through an interface boundary, runtime validation could catch misconfiguration earlier.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts` around
lines 153 - 154, The code unsafely casts options.contract and options.schema to
MongoContract and MongoSchemaIR (contract and originIR) without runtime checks;
add runtime validation using a type-guard or schema validator (e.g., custom
isMongoContract/isMongoSchemaIR functions or a Zod/io-ts schema) to verify
options.contract and options.schema before casting, and throw a clear error if
validation fails so callers get an early, descriptive failure instead of runtime
type errors; update the code paths that use contract and originIR to use the
validated values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts`:
- Around line 153-154: The code unsafely casts options.contract and
options.schema to MongoContract and MongoSchemaIR (contract and originIR)
without runtime checks; add runtime validation using a type-guard or schema
validator (e.g., custom isMongoContract/isMongoSchemaIR functions or a Zod/io-ts
schema) to verify options.contract and options.schema before casting, and throw
a clear error if validation fails so callers get an early, descriptive failure
instead of runtime type errors; update the code paths that use contract and
originIR to use the validated values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 58b27151-ebc9-488a-948e-772b6ee3ee79

📥 Commits

Reviewing files that changed from the base of the PR and between 7f6b994 and 9ce3327.

📒 Files selected for processing (4)
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-planner.ts
  • packages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.ts
  • packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/3-mongo-target/1-mongo-target/test/ddl-formatter.test.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/3-mongo-target/1-mongo-target/test/mongo-planner.test.ts

…all nodes

These properties are intrinsic to each call type, not external concerns.
Eliminates the operationClassVisitor/labelVisitor indirection and the
v8 ignore blocks they required.
@wmadden
wmadden merged commit 931df5c into main Apr 16, 2026
15 checks passed
@wmadden
wmadden deleted the migration-subsystem-refactor branch April 16, 2026 07:31
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant