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

Mongo PoC - #264

Merged
wmadden merged 133 commits into
mainfrom
mongo-poc
Mar 31, 2026
Merged

wmadden merged 133 commits into
mainfrom
mongo-poc

Conversation

@wmadden

@wmadden wmadden commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • First-class MongoDB support: typed ORM, runtime, adapter and driver for find/insert/update/delete/aggregate; include handling and embed vs reference relations; codec-backed field typing and conversions; polymorphic models (discriminator + variants).
  • Documentation

    • Extensive Mongo planning, ADRs, design guides, idioms, user journey, migration model, and package READMEs.
  • Tests

    • Unit and integration suites covering codecs, adapter, driver, runtime, ORM, and contract validation (in-memory DB test harness).
  • Chores

    • Architecture config updated to add mongo domain/targets, layer ordering, and cross-domain import rules.

@coderabbitai

coderabbitai Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a MongoDB family and target: new packages for mongo-core, mongo-orm, mongo-runtime, target pack/adapter/driver; introduces contract/codec/plan types and validators, adapter/driver implementations, ORM/runtime wiring, in-memory integration tests, ADRs and docs, and workspace/tooling updates.

Changes

Cohort / File(s) Summary
Architecture config
architecture.config.json
Add mongo domain and layerOrder; map mongo-family and mongo-target packages; update cross-domain import rules to allow mongo and permit targets/extensions to import from mongo.
Mongo core (package)
packages/2-mongo-family/1-core/...
New @prisma-next/mongo-core: codec types & registry, command & wire-command classes, contract schemas/types, domain/storage validators, plan/result/driver/adapter interfaces, param-ref/results, public exports, unit tests, tsconfigs and build config. Attention: contract/schema validation and public API surface.
Mongo ORM (package)
packages/2-mongo-family/4-orm/...
New @prisma-next/mongo-orm: type utilities (InferRow/include/filter), mongoOrm() implementation building per-root collections and $lookup pipelines for includes, public exports and type-level tests. Review include pipeline generation and type inference.
Mongo runtime (package)
packages/2-mongo-family/5-runtime/...
New @prisma-next/mongo-runtime: runtime that lowers via adapter and dispatches to driver, createMongoRuntime, in-memory test harness (withMongod), integration tests exercising CRUD/aggregate flows, async-iterable wrapping and lifecycle handling.
Mongo target pack
packages/3-mongo-target/1-mongo-target/...
New target descriptor pack exposing mongoTargetDescriptorMeta via pack export and descriptor tests.
Mongo adapter
packages/3-mongo-target/2-mongo-adapter/...
New @prisma-next/adapter-mongo: codec ID constants and concrete codecs, adapter lowering (MongoCommand → MongoWireCommand), param/document resolution, factory export and adapter/codec tests. Review: value resolution correctness and exhaustive kind handling.
Mongo driver
packages/3-mongo-target/3-mongo-driver/...
New @prisma-next/driver-mongo: createMongoDriver implementing wire-command dispatch to MongoDB, yields AsyncIterable results, close lifecycle, and in-memory driver tests. Review: command handlers and connection/cleanup.
Docs & ADRs
docs/..., docs/planning/...
Add ADRs (172–176), Mongo family subsystem docs, planning/design docs, migration theory & solutions, references (idioms, priorities, user journey), glossary updates, READMEs and planning index.
Design artifacts (mongo-target)
docs/planning/mongo-target/...
Design docs: contract symmetry, execution components, example schemas, PoC plan, design questions, and cross-cutting learnings.
Integration tests & fixtures
test/integration/test/mongo/..., test/utils/src/timeouts.ts
Integration harness and fixtures for in-memory Mongo, end-to-end ORM/runtime tests, type tests, and new spin-up timeout constant.
Workspace & tooling
package manifests & configs
Add package.json, tsconfig, tsdown/vitest/biome configs for new packages; update pnpm-workspace.yaml, test/integration/package.json to include mongo packages and dev deps.
Misc & docs
.agents/..., package READMEs
Add architecture-writing skill doc, package READMEs for mongo packages; remove docs/Execution Enums.md.

Sequence Diagram(s)

sequenceDiagram
    rect rgba(0,128,0,0.5)
    participant User as User Code
    end
    rect rgba(0,0,128,0.5)
    participant ORM as mongoOrm
    participant Executor as QueryExecutor
    end
    rect rgba(128,0,128,0.5)
    participant Runtime as MongoRuntime
    participant Adapter as MongoAdapter
    participant Driver as MongoDriver
    end
    rect rgba(128,128,0,0.5)
    participant DB as MongoDB
    end

    User->>ORM: findMany({ where, include })
    ORM->>ORM: build MongoQueryPlan (FindCommand + meta)
    ORM->>Executor: execute(plan)
    Executor->>Runtime: execute(plan)
    Runtime->>Adapter: lower(plan, context)
    Adapter->>Adapter: resolve params / MongoCommand → MongoWireCommand
    Adapter-->>Runtime: MongoExecutionPlan (wireCommand)
    Runtime->>Driver: execute(wireCommand)
    Driver->>DB: run find/aggregate/insert/update/delete
    DB-->>Driver: cursor / results
    Driver-->>Runtime: AsyncIterable<Row>
    Runtime-->>Executor: AsyncIterableResult<Row>
    Executor-->>ORM: results
    ORM-->>User: typed rows
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I nibbled through codecs, contracts, and plans,

twitching whiskers over ObjectId strands.
Roots and variants now leap in a row,
includes join like carrots — neat and slow.
Mongo landed softly; the burrow's aglow.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch mongo-poc

@pkg-pr-new

pkg-pr-new Bot commented Mar 30, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/runtime-executor

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

@prisma-next/mongo-core

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-runtime

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

@prisma-next/sql-runtime

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract-authoring

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

@prisma-next/contract-ts

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/emitter

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

@prisma-next/eslint-plugin

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/eslint-plugin@264

@prisma-next/migration-tools

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

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

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

@prisma-next/family-sql

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

@prisma-next/sql-kysely-lane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-kysely-lane@264

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder-new

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

@prisma-next/sql-lane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane@264

@prisma-next/target-postgres

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

@prisma-next/adapter-postgres

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

@prisma-next/driver-postgres

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

@prisma-next/core-control-plane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/core-control-plane@264

@prisma-next/core-execution-plane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/core-execution-plane@264

@prisma-next/config

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

@prisma-next/contract

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

@prisma-next/operations

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

@prisma-next/plan

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/plan@264

@prisma-next/utils

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

commit: 82f16cd

@wmadden
wmadden marked this pull request as draft March 30, 2026 07:51

@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: 17

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

🟡 Minor comments (16)
packages/3-mongo-target/3-mongo-driver/tsconfig.json-6-7 (1)

6-7: ⚠️ Potential issue | 🟡 Minor

Add fixture exclusion in exclude list.

Line 7 omits test/fixtures/**/*, which can pull fixture-only types into package typechecking.

Suggested change
-  "exclude": ["dist", "dist-tsc", "dist-tsc-prod", "node_modules"]
+  "exclude": ["dist", "dist-tsc", "dist-tsc-prod", "node_modules", "test/fixtures/**/*"]

As per coding guidelines: "**/tsconfig.json: Exclude test fixture files from TypeScript typechecking in tsconfig.json using 'exclude': ['test/fixtures/**/*']".

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

In `@packages/3-mongo-target/3-mongo-driver/tsconfig.json` around lines 6 - 7,
Update the tsconfig.json exclude array to omit test fixture files so
fixture-only types aren't picked up during typechecking: add the pattern
"test/fixtures/**/*" to the existing "exclude" array (the same tsconfig.json
that currently contains "include": ["src", "test", "*.config.*", "package.json"]
and "exclude": ["dist", "dist-tsc", "dist-tsc-prod", "node_modules"]) so
TypeScript will ignore fixture files during compilation.
docs/planning/mongo-target/1-design-docs/mongo-execution-components.md-19-35 (1)

19-35: ⚠️ Potential issue | 🟡 Minor

Add a language to this fenced block.

markdownlint is already flagging this block with MD040; text is sufficient here.

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

In `@docs/planning/mongo-target/1-design-docs/mongo-execution-components.md`
around lines 19 - 35, The fenced code block showing the Mongo flow (containing
MongoQueryPlan, MongoRuntimeCore, and MongoDriver) is missing a language
identifier and triggers markdownlint MD040; update the block fence to include a
language (e.g., "text") so it reads ```text before the diagram and closes with
``` after it to satisfy the linter.
docs/planning/mongo-target/1-design-docs/design-questions.md-221-226 (1)

221-226: ⚠️ Potential issue | 🟡 Minor

Refresh the Mongo model.storage description.

This section still frames Mongo storage as field -> codec, but the contract shape in this PR puts codecId on model.fields and uses model.storage only as the persistence bridge. Leaving this stale here will point the ContractBase work in the wrong direction.

As per coding guidelines, "Keep docs, READMEs, and rules up-to-date."

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

In `@docs/planning/mongo-target/1-design-docs/design-questions.md` around lines
221 - 226, The docs wrongly describe Mongo `model.storage` as `field -> codec`
whereas the PR moved `codecId` into `model.fields` and uses `model.storage` only
as the persistence bridge; update the paragraph under ContractBase to reflect
that `model.fields` now contain `{ nullable, codecId }` and `model.storage` is a
family-specific persistence mapping (not the location of codecId), and mention
the SQL vs Mongo divergence: SQL maps field→column while Mongo uses
`fields.codecId` with `model.storage` providing any additional persistence
metadata or bridge info; reference `ContractBase`, `model.fields`,
`model.storage`, and `codecId` when making this change.
docs/planning/0-references/community-generator-migration-analysis.md-27-28 (1)

27-28: ⚠️ Potential issue | 🟡 Minor

Update the repeated SQL-only baseline.

These sections say the repo only has SQL implemented, but this PR introduces a Mongo family/target/runtime/ORM PoC. Please rebaseline the premise here and the downstream fragmentation analysis that depends on it.

As per coding guidelines, "Keep documentation current including READMEs, rules, and links. Reference .cursor/rules/doc-maintenance.mdc for details."

Also applies to: 260-262, 280-281

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

In `@docs/planning/0-references/community-generator-migration-analysis.md` around
lines 27 - 28, Update the "Important caveat" paragraph and the downstream
fragmentation analysis to reflect that a Mongo family/target/runtime/ORM PoC now
exists rather than SQL being the only implemented target: replace absolute
statements that only SQL is implemented (mentions of ExecutionContext and
SqlContract as the only runtime/contract types) with language acknowledging the
new Mongo PoC while noting remaining gaps (e.g., ContractBase and
DocumentContract stubs), adjust the "Cross-family support" analysis to
re-evaluate fragmentation risk given Mongo PoC, and apply the same baseline
change to the other referenced sections; follow the doc-maintenance guideline in
.cursor/rules/doc-maintenance.mdc when updating wording and links.
docs/planning/mongo-target/1-design-docs/mongo-execution-components.md-11-15 (1)

11-15: ⚠️ Potential issue | 🟡 Minor

Don't equate MongoQueryPlan with SQL's ExecutionPlan.

The table and the narrative describe Mongo as having a single plan/wire type, but the implementation in this PR still lowers MongoQueryPlan through the adapter before the driver sees a wire command. That wording collapses two layers that the architecture now keeps separate.

Based on learnings, ExecutionPlan and SqlQueryPlan are intentionally distinct types and map to different architectural layers.

Also applies to: 37-40

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

In `@docs/planning/mongo-target/1-design-docs/mongo-execution-components.md`
around lines 11 - 15, The docs incorrectly equate MongoQueryPlan with the SQL
ExecutionPlan; update the text and table to reflect that MongoQueryPlan is a
higher-level plan that is lowered via the adapter before the driver sees a wire
command, and that ExecutionPlan/SqlQueryPlan are distinct lower-layer types;
specifically revise wording around MongoQueryPlan, MongoRuntimeCore, MongoDriver
(and the rows at lines 37-40) to state that MongoQueryPlan is translated by the
adapter into a driver-level wire command/SqlQueryPlan/ExecutionPlan rather than
being the same type as ExecutionPlan.
test/integration/test/mongo/orm.test.ts-22-26 (1)

22-26: ⚠️ Potential issue | 🟡 Minor

Don't couple this test to natural result order.

findMany() is unsorted here, so asserting results[0] is Alice and results[1] is Bob can flake if collection scan order changes. Assert as an unordered set, or add an explicit sort before checking row contents.

💡 Safer assertion
       const results = await orm.users.findMany();

       expect(results).toHaveLength(2);
-      expect(results[0]).toMatchObject({ name: 'Alice', email: '[email protected]' });
-      expect(results[1]).toMatchObject({ name: 'Bob', email: '[email protected]' });
+      expect(results).toEqual(
+        expect.arrayContaining([
+          expect.objectContaining({ name: 'Alice', email: '[email protected]' }),
+          expect.objectContaining({ name: 'Bob', email: '[email protected]' }),
+        ]),
+      );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/integration/test/mongo/orm.test.ts` around lines 22 - 26, The test
assumes a stable order from orm.users.findMany() by checking results[0] and
results[1], which can flake; change the assertion to be order-independent by
either calling a deterministic sorter (e.g., sort by name or email) on the
results before asserting, or assert the returned set contains both expected
objects regardless of order (e.g., compare a set/array of found names/emails to
expected values). Update the assertions referencing orm.users.findMany and the
results variable to use the chosen approach so the test no longer depends on
natural collection order.
docs/planning/mongo-target/9-references/mongodb-primitives-reference.md-429-433 (1)

429-433: ⚠️ Potential issue | 🟡 Minor

Clarify index behavior with multiple $match stages.

The statement "only the first $match can use indexes" oversimplifies MongoDB's optimization. Consecutive $match stages are automatically coalesced, and the optimizer can push later $match stages earlier if preceding stages don't affect their predicates. The actual constraint is reshaping stages like $project or $group — those prevent index usage in subsequent $match stages. Rephrase to reflect that $match works best early, but the limiting factor is stream materialization, not ordinal position.

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

In `@docs/planning/mongo-target/9-references/mongodb-primitives-reference.md`
around lines 429 - 433, Update the "Key architectural difference from SQL"
paragraph to clarify MongoDB index behavior: state that multiple consecutive
$match stages may be coalesced and the query planner can move later $match
stages earlier when safe, but that reshaping or materializing stages (e.g.,
$project, $group, $unwind) can prevent subsequent $match stages from using
indexes; keep the guidance that $match works best early and recommend placing
filtering before any stage that changes the document shape or materializes the
stream. Reference the terms $match, $project, $group, $unwind, "aggregation
pipelines", and "Prisma Next lowering" so the change is easy to locate.
docs/planning/mongo-target/9-references/mongodb-primitives-reference.md-173-180 (1)

173-180: ⚠️ Potential issue | 🟡 Minor

Junction collections are a valid and officially documented MongoDB many-to-many pattern.

MongoDB supports three patterns for many-to-many relationships: embedding, referencing (arrays of IDs), and junction/intermediate collections. The statement that junction tables are "not possible" is inaccurate. Junction collections are particularly valuable when relationship arrays grow unbounded, when you need to store edge metadata (enrollment date, grade, etc.), or when relationships are high-cardinality. Update the wording to reflect all supported patterns rather than stating junction tables are impossible.

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

In `@docs/planning/mongo-target/9-references/mongodb-primitives-reference.md`
around lines 173 - 180, Update the "Many-to-many" section to remove the
definitive claim that junction/join tables are "not possible" and explicitly
mention the three supported MongoDB relationship patterns (embedding,
referencing via arrays of IDs, and junction/intermediate collections), noting
when to prefer a junction collection (high-cardinality relationships, unbounded
arrays, or when storing edge metadata like enrollment date/grade); change the
"Many-to-many" paragraph near the "One-to-many (reference)" and "Many-to-many"
headings to reflect this nuance and include examples/use-cases for using a
junction collection.
packages/2-mongo-family/4-orm/test/orm-types.test-d.ts-99-108 (1)

99-108: ⚠️ Potential issue | 🟡 Minor

Assert literal discriminator values to protect narrowed-union contract.

The test currently passes if InferRootRow widens type to string for both branches, which prevents type-based narrowing on task.type. Strengthen the assertion by adding literal discriminator values (type: 'bug' and type: 'feature') to each union branch so the test catches regressions in discriminator narrowing.

Suggested fix
-  type BugRowPart = { severity: string };
-  type FeatureRowPart = { priority: string; targetRelease: string };
+  type BugRowPart = { type: 'bug'; severity: string };
+  type FeatureRowPart = { type: 'feature'; priority: string; targetRelease: string };

   expectTypeOf<TaskRow>().toExtend<
-    | ({ _id: string; title: string; type: string; assigneeId: string } & BugRowPart)
-    | ({ _id: string; title: string; type: string; assigneeId: string } & FeatureRowPart)
+    | ({ _id: string; title: string; assigneeId: string } & BugRowPart)
+    | ({ _id: string; title: string; assigneeId: string } & FeatureRowPart)
   >();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/4-orm/test/orm-types.test-d.ts` around lines 99 -
108, The test "InferRootRow for polymorphic model returns union of base+variant
rows" currently allows the discriminator `type` to be widened to string; update
the expected union assertion so each branch includes literal discriminator
values (`type: 'bug'` and `type: 'feature'`) instead of `type: string` to ensure
InferRootRow preserves discriminated union narrowing—modify the assertion that
uses TaskRow / InferRootRow<Contract, 'Task'> to expect ({ _id: string; title:
string; type: 'bug'; assigneeId: string } & BugRowPart) | ({ _id: string; title:
string; type: 'feature'; assigneeId: string } & FeatureRowPart).
docs/planning/mongo-target/9-references/mongo-idioms.md-7-12 (1)

7-12: ⚠️ Potential issue | 🟡 Minor

Fix the heading level jump at Sources.

Line 7 jumps from # straight to ###, which trips MD001 and makes the outline inconsistent. Promote it to ## Sources.

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

In `@docs/planning/mongo-target/9-references/mongo-idioms.md` around lines 7 - 12,
The heading "Sources" currently uses a level-3 heading ("### Sources") which
jumps from the top-level and triggers MD001; change that heading to level-2 ("##
Sources") so the document outline is consistent and the MD001 rule is satisfied,
updating the line that reads "### Sources" to "## Sources".
docs/planning/mongo-target/9-references/mongo-idioms.md-190-205 (1)

190-205: ⚠️ Potential issue | 🟡 Minor

Use one array-filter operator name across the Mongo docs.

Line 204 documents hasAll, but docs/planning/mongo-target/1-design-docs/user-promise.md uses hasEvery for the same "array contains all values" behavior. Pick one now; otherwise the planned ORM surface is documented two different ways.

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

In `@docs/planning/mongo-target/9-references/mongo-idioms.md` around lines 190 -
205, The docs use two different names for the same array operator—`hasAll` in
mongo-idioms.md and `hasEvery` in user-promise.md—so pick one and make both
files consistent; update the occurrence in
docs/planning/mongo-target/9-references/mongo-idioms.md (replace `hasAll` or
change the other file) and the occurrence in
docs/planning/mongo-target/1-design-docs/user-promise.md so both use the single
agreed operator name (either `hasAll` or `hasEvery`) everywhere, and run a quick
grep across the docs to ensure no other files reference the old variant.
packages/2-mongo-family/1-core/src/validate-domain.ts-136-168 (1)

136-168: ⚠️ Potential issue | 🟡 Minor

Reachability for orphan warnings has to start from roots.

Lines 147-159 add relation/variant/base edges from every model up front, so a disconnected cluster of models that only references itself is marked "referenced" and never warned. Seed the walk from contract.roots and traverse outward instead.

🌐 Suggested root-reachability walk
 function detectOrphanedModels(
   contract: DomainContractShape,
   modelNames: Set<string>,
   warnings: string[],
 ): void {
-  const referenced = new Set<string>();
-
-  for (const modelName of Object.values(contract.roots)) {
-    referenced.add(modelName);
-  }
-
-  for (const model of Object.values(contract.models)) {
-    for (const relation of Object.values(model.relations)) {
-      referenced.add(relation.to);
-    }
-    if (model.variants) {
-      for (const variantName of Object.keys(model.variants)) {
-        referenced.add(variantName);
-      }
-    }
-    if (model.base) {
-      referenced.add(model.base);
-    }
-  }
+  const referenced = new Set(Object.values(contract.roots));
+  const queue = [...referenced];
+
+  while (queue.length > 0) {
+    const modelName = queue.pop()!;
+    const model = contract.models[modelName];
+    if (!model) continue;
+
+    for (const relation of Object.values(model.relations)) {
+      if (!referenced.has(relation.to)) {
+        referenced.add(relation.to);
+        queue.push(relation.to);
+      }
+    }
+
+    for (const variantName of Object.keys(model.variants ?? {})) {
+      if (!referenced.has(variantName)) {
+        referenced.add(variantName);
+        queue.push(variantName);
+      }
+    }
+
+    if (model.base && !referenced.has(model.base)) {
+      referenced.add(model.base);
+      queue.push(model.base);
+    }
+  }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/1-core/src/validate-domain.ts` around lines 136 -
168, The current detectOrphanedModels marks every model as "referenced" by
collecting all outgoing edges globally, which misses disconnected clusters;
instead implement a reachability walk seeded from contract.roots: in
detectOrphanedModels, start a DFS/BFS from each model name in
Object.values(contract.roots), maintain a visited Set, and for each visited
model push its outbound neighbors (model.relations[*].to,
Object.keys(model.variants) if present, and model.base if present) onto the
stack/queue; after the traversal, any modelName in modelNames not in visited
should produce the orphan warning string used today.
packages/2-mongo-family/4-orm/src/mongo-orm.ts-54-55 (1)

54-55: ⚠️ Potential issue | 🟡 Minor

Fail closed if an include relation points at a missing model.

Line 55 currently drops the requested include and keeps running. If an invalid contract slips through here, callers get silently partial data instead of a clear configuration error.

💡 Suggested fail-closed path
-    const targetModel = contract.models[refRelation.to];
-    if (!targetModel) continue;
+    const targetModel = contract.models[refRelation.to];
+    if (!targetModel) {
+      throw new Error(`Relation "${relName}" targets missing model "${refRelation.to}"`);
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/4-orm/src/mongo-orm.ts` around lines 54 - 55, The
code currently ignores missing include targets by checking const targetModel =
contract.models[refRelation.to]; if (!targetModel) continue; — change this to
fail closed: detect when an include/refRelation.to refers to a non-existent
model and throw a descriptive error (include refRelation.to and the current
model name/context) instead of continuing; update any surrounding logic in the
function that uses targetModel (e.g., the include resolution loop) to expect an
exception for invalid contract references so callers receive a clear
configuration error rather than partial data.
packages/2-mongo-family/1-core/src/validate-domain.ts-84-87 (1)

84-87: ⚠️ Potential issue | 🟡 Minor

Use Object.hasOwn() for own-property checks in contract membership validation.

Lines 85 and 116 use the in operator to check object membership, which also accepts inherited properties. This violates the Biome lint rule noPrototypeBuiltins. Use Object.hasOwn() instead, which safely checks only own properties and cannot be overridden.

Changes required
-      if (!baseModel.variants || !(modelName in baseModel.variants)) {
+      if (!baseModel.variants || !Object.hasOwn(baseModel.variants, modelName)) {
         errors.push(
           `Model "${modelName}" has base "${model.base}" which does not list it as a variant`,
         );
       }
-      if (!(model.discriminator.field in model.fields)) {
+      if (!Object.hasOwn(model.fields, model.discriminator.field)) {
         errors.push(
           `Discriminator field "${model.discriminator.field}" is not a field on model "${modelName}"`,
         );
       }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/1-core/src/validate-domain.ts` around lines 84 - 87,
Replace uses of the `in` operator for membership checks with Object.hasOwn to
avoid prototype-builtins issues: where the code checks `modelName in
baseModel.variants` (referencing baseModel and modelName) and the other check at
the similar pattern around contract.models (referencing contract.models and
modelName), change them to use Object.hasOwn(baseModel.variants, modelName) and
Object.hasOwn(contract.models, modelName) respectively so you only test own
properties safely.
docs/planning/mongo-target/1-design-docs/mongo-poc-plan.md-36-43 (1)

36-43: ⚠️ Potential issue | 🟡 Minor

Add language specifier to fenced code block.

The code block showing the contract hierarchy should have a language specifier for proper syntax highlighting and accessibility.

📝 Proposed fix
-```
+```text
 ContractBase (shared domain: roots, models with fields/discriminator/variants, relations)
 ├── SqlContract (model.storage: field → column; top-level storage: tables, columns, indexes)
 │   └── Targets: Postgres, MySQL, SQLite...
 └── MongoContract (model.storage: field → codecId; top-level storage: collections)
     └── Target: MongoDB
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @docs/planning/mongo-target/1-design-docs/mongo-poc-plan.md around lines 36 -
43, Add a language specifier to the fenced code block that documents the
contract hierarchy so it renders with proper syntax highlighting and
accessibility; locate the block containing ContractBase, SqlContract and
MongoContract and change the opening fence to include an explicit language token
(for example use "text" or "mermaid" if you want diagram styling) so the block
begins with text (or another appropriate language) instead of just .


</details>

</blockquote></details>
<details>
<summary>docs/planning/mongo-target/Mongo Overview.md-107-117 (1)</summary><blockquote>

`107-117`: _⚠️ Potential issue_ | _🟡 Minor_

**Add language specifier to the package layout code block.**

The fenced code block should have a language specifier for consistency and accessibility.


<details>
<summary>📝 Proposed fix</summary>

```diff
-```
+```text
 packages/2-mongo-family/
   1-core/            -- MongoContract types, MongoQueryPlan, MongoCodec interfaces
   5-runtime/         -- MongoRuntime, MongoPlugin interface

 packages/3-mongo-target/
   1-mongo-target/    -- Target pack definition
   2-mongo-adapter/   -- Concrete codecs (objectId, string, int32, boolean, date)
   3-mongo-driver/    -- MongoDriver (wraps the mongodb Node.js driver)
 ```
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @docs/planning/mongo-target/Mongo Overview.md around lines 107 - 117, The
fenced code block in the Mongo Overview markdown lacks a language specifier;
update the triple-backtick fence that surrounds the package layout sample (the
block showing "packages/2-mongo-family/" and "packages/3-mongo-target/") to
include a language specifier (e.g., change totext) so the block becomes
text and remains closed with ; no content changes needed inside the block.


</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>🧹 Nitpick comments (8)</summary><blockquote>

<details>
<summary>packages/2-mongo-family/5-runtime/vitest.config.ts (1)</summary><blockquote>

`23-28`: **100% coverage thresholds are ambitious for a PoC.**

While strict coverage is admirable, 100% thresholds on all metrics may cause friction during rapid iteration. Consider whether slightly lower thresholds (e.g., 90%) would be more practical for the proof-of-concept phase, with the option to increase later.

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/5-runtime/vitest.config.ts` around lines 23 - 28, The
coverage thresholds in the vitest config (the thresholds object in
vitest.config.ts) are set to 100% for statements, branches, functions, and
lines; lower these to a more practical PoC level (e.g., 90%) by updating the
numeric values in the thresholds object so tests won’t be blocked by unrealistic
full coverage during early iteration.
```

</details>

</blockquote></details>
<details>
<summary>packages/2-mongo-family/5-runtime/test/contract-execution.test.ts (1)</summary><blockquote>

`33-39`: **Consider using `toMatchObject` for related field assertions.**

Lines 35-38 check four related fields from the same `user` row. Per coding guidelines, prefer object matchers over multiple individual `expect().toBe()` calls when checking 2+ related values.



<details>
<summary>♻️ Proposed refactor</summary>

```diff
       expect(rows).toHaveLength(1);
       const user = rows[0]!;
-      expect(user.name).toBe('Alice');
-      expect(user.email).toBe('[email protected]');
-      expect(user.bio).toBeNull();
-      expect(user.createdAt).toEqual(new Date('2024-01-15T10:00:00Z'));
+      expect(user).toMatchObject({
+        name: 'Alice',
+        email: '[email protected]',
+        bio: null,
+        createdAt: new Date('2024-01-15T10:00:00Z'),
+      });
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/5-runtime/test/contract-execution.test.ts` around
lines 33 - 39, Replace the four individual assertions on the same user object
with a single object matcher: after extracting user from rows (rows and user
variables), use expect(user).toMatchObject({ name: 'Alice', email:
'[email protected]', bio: null, createdAt: new Date('2024-01-15T10:00:00Z') })
so related field checks are grouped; keep the initial
expect(rows).toHaveLength(1) and remove the separate expect(user.name)…
expect(user.createdAt) calls.
```

</details>

</blockquote></details>
<details>
<summary>test/integration/test/mongo/setup.ts (1)</summary><blockquote>

`24-29`: **Consider making the contract parameterizable for more flexible test scenarios.**

The `loweringContext.contract` is hardcoded with empty roots/storage/models. For tests requiring contract-aware lowering behavior, consider accepting an optional contract parameter.



<details>
<summary>♻️ Optional: Accept contract parameter</summary>

```diff
+import type { MongoContract } from '@prisma-next/mongo-core';
+
+export interface WithMongodOptions {
+  readonly contract?: MongoContract<unknown, unknown, unknown>;
+}
+
-export async function withMongod<T>(fn: (ctx: MongodContext) => Promise<T>): Promise<T> {
+export async function withMongod<T>(
+  fn: (ctx: MongodContext) => Promise<T>,
+  options?: WithMongodOptions,
+): Promise<T> {
   // ...
   const loweringContext: MongoLoweringContext = {
-    contract: { targetFamily: 'mongo', roots: {}, storage: { collections: {} }, models: {} },
+    contract: options?.contract ?? { targetFamily: 'mongo', roots: {}, storage: { collections: {} }, models: {} },
   };
```

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@test/integration/test/mongo/setup.ts` around lines 24 - 29, The test setup
hardcodes loweringContext.contract with empty roots/storage/models which
prevents contract-aware tests; update the setup to accept an optional contract
parameter (e.g., add an optional "contract?: ContractType" arg to the setup
function that creates adapter/driver) and construct loweringContext using the
provided contract or fall back to the existing empty default, then pass that
loweringContext into createMongoRuntime(adapter, driver, loweringContext)
(references: MongoLoweringContext, loweringContext, createMongoRuntime,
createMongoDriver, createMongoAdapter) so tests can supply custom contracts when
needed.
```

</details>

</blockquote></details>
<details>
<summary>packages/3-mongo-target/2-mongo-adapter/package.json (1)</summary><blockquote>

`34-38`: **Consider adding type definitions to exports for better TypeScript resolution.**

The exports field only maps to `.mjs` files. While tsdown auto-populates conditional exports during build, consumers may benefit from explicit type mappings if they're not using conditions that tsdown generates.



<details>
<summary>♻️ Optional: Add conditional exports with types</summary>

```diff
   "exports": {
-    ".": "./dist/index.mjs",
-    "./codec-types": "./dist/codec-types.mjs",
+    ".": {
+      "import": "./dist/index.mjs",
+      "types": "./dist/index.d.mts"
+    },
+    "./codec-types": {
+      "import": "./dist/codec-types.mjs",
+      "types": "./dist/codec-types.d.mts"
+    },
     "./package.json": "./package.json"
   },
```

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/2-mongo-adapter/package.json` around lines 34 - 38,
The exports field only points to .mjs bundles and lacks type definition
mappings; update the package.json "exports" to include type entries for the
existing exports (e.g. map "." to "./dist/index.mjs" plus a types path such as
"./dist/index.d.ts", and "./codec-types" to "./dist/codec-types.mjs" plus
"./dist/codec-types.d.ts") so TypeScript consumers resolve declarations; ensure
the generated .d.ts files exist (from your build) and add the "types" (or
conditional "types"/"import") entries alongside the .mjs paths in the "exports"
object.
```

</details>

</blockquote></details>
<details>
<summary>packages/2-mongo-family/5-runtime/test/find.test.ts (1)</summary><blockquote>

`54-56`: **Consider simplifying the projection assertion.**

The current loop with `Object.keys()` check works but could be more direct using `toEqual` since you're validating the exact shape.



<details>
<summary>♻️ Optional: Simplify with toEqual</summary>

```diff
       const rows = await ctx.runtime.execute(plan);
       expect(rows).toHaveLength(3);
-      for (const row of rows) {
-        expect(Object.keys(row as Record<string, unknown>)).toEqual(['name']);
-      }
+      expect(rows).toEqual([
+        { name: 'Alice' },
+        { name: 'Bob' },
+        { name: 'Charlie' },
+      ]);
```

This validates both the shape and order, though may be more brittle if insertion order isn't guaranteed.

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/5-runtime/test/find.test.ts` around lines 54 - 56,
Replace the for-loop assertion over "rows" that checks Object.keys(row) for each
"row" with a single toEqual assertion: compute rows.map(r => Object.keys(r)) and
assert it equals an array of ['name'] repeated for each row (e.g. rows.map(() =>
['name'])), so the test validates the exact projected keys in one assertion
instead of a loop.
```

</details>

</blockquote></details>
<details>
<summary>packages/2-mongo-family/5-runtime/test/setup.ts (1)</summary><blockquote>

`59-65`: **Cleanup could fail to complete if early teardown throws.**

If `runtime.close()` or `client.close()` throws, subsequent cleanup steps won't execute. For test infrastructure this is usually acceptable, but for robustness consider independent cleanup.


<details>
<summary>♻️ More robust cleanup pattern</summary>

```diff
   try {
     return await fn(ctx);
   } finally {
-    await runtime.close();
-    await client.close();
-    await replSet.stop();
+    await runtime.close().catch(() => {});
+    await client.close().catch(() => {});
+    await replSet.stop();
   }
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/5-runtime/test/setup.ts` around lines 59 - 65, The
finally block currently runs runtime.close(), client.close(), and replSet.stop()
sequentially so a thrown error from runtime.close() or client.close() prevents
later cleanup; change it to invoke each cleanup independently (e.g., use
Promise.allSettled or wrap each call in its own try/catch) so runtime.close(),
client.close(), and replSet.stop() are all attempted and errors are
captured/aggregated before rethrowing or logging; update the finally in the
wrapper around fn(ctx) to ensure no single failure aborts the remaining cleanup.
```

</details>

</blockquote></details>
<details>
<summary>packages/2-mongo-family/1-core/test/validate.test.ts (1)</summary><blockquote>

`126-133`: **Consider using `toMatchObject` for related value checks.**

These assertions check related properties of the validation result. Per coding guidelines, prefer object matchers when checking 2+ related values.


<details>
<summary>♻️ Suggested refactor</summary>

```diff
   describe('happy path', () => {
     it('validates the ORM test contract', () => {
       const result = validateMongoContract(ormContractJson);
-      expect(result.contract).toBeDefined();
-      expect(result.warnings).toHaveLength(0);
-      expect(result.indices.variantToBase).toBeDefined();
-      expect(result.indices.modelToVariants).toBeDefined();
+      expect(result).toMatchObject({
+        contract: expect.anything(),
+        warnings: [],
+        indices: {
+          variantToBase: expect.anything(),
+          modelToVariants: expect.anything(),
+        },
+      });
     });
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/1-core/test/validate.test.ts` around lines 126 - 133,
Replace the multiple related expects in the "happy path" test for
validateMongoContract with a single object matcher: assert the result matches an
object containing a defined contract, warnings as an empty array, and indices
with defined variantToBase and modelToVariants. Locate the test block using
validateMongoContract and ormContractJson and change the separate
expect(result.contract), expect(result.warnings).toHaveLength(0),
expect(result.indices.variantToBase) and expect(result.indices.modelToVariants)
assertions into one expect(result).toMatchObject(...) that checks these
properties together.
```

</details>

</blockquote></details>
<details>
<summary>packages/2-mongo-family/1-core/src/contract-types.ts (1)</summary><blockquote>

`68-77`: **Consider removing generic defaults from `MongoContract`.**

The defaults (`Record<string, string>`, `MongoStorage`, `Record<string, MongoModelDefinition>`) create a structurally valid but semantically empty contract. Per coding guidelines, avoid defaults that create a false "optional" API where the type is pointless without concrete generics. Consumers should always provide explicit type parameters for meaningful contracts.


<details>
<summary>♻️ Proposed refactor to remove defaults</summary>

```diff
 export type MongoContract<
-  Roots extends Record<string, string> = Record<string, string>,
-  S extends MongoStorage = MongoStorage,
-  M extends Record<string, MongoModelDefinition> = Record<string, MongoModelDefinition>,
+  Roots extends Record<string, string>,
+  S extends MongoStorage,
+  M extends Record<string, MongoModelDefinition>,
 > = {
   readonly targetFamily: string;
   readonly roots: Roots;
   readonly storage: S;
   readonly models: M;
 };
```
</details>

As per coding guidelines: "Don't add generic defaults unless the type is meaningfully usable with the default."

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/1-core/src/contract-types.ts` around lines 68 - 77,
Remove the meaningless generic defaults from the MongoContract type so callers
must supply concrete generics: change the declaration of MongoContract to
require Roots, S, and M without defaulting to Record<string, string>,
MongoStorage, or Record<string, MongoModelDefinition>; update the type
parameters (Roots, S, M) and any internal references to continue using those
type names (e.g., MongoContract, Roots, S, M, MongoStorage,
MongoModelDefinition) but make them mandatory, and then audit and update any
call sites that previously relied on the defaults to pass explicit type
arguments.
```

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>🤖 Prompt for all review comments with AI agents</summary>

Verify each finding against the current code and only fix it if needed.

Inline comments:
In @docs/planning/0-references/framework-integration-analysis.md:

  • Around line 248-261: The snippet overwrites globalForDb.db without disposing
    the previous runtime/pool; update the logic (or the proposed helper createDevDb)
    to call an explicit teardown on the old runtime before assigning a new one —
    e.g., detect existing globalForDb.db and await its disconnect/close/teardown
    method (or store a teardown function alongside the runtime) before replacing it
    when contractJson.storageHash changes; additionally consider wiring an HMR
    dispose hook (module.hot?.dispose) to call the same teardown so connections are
    cleaned both on swap and on module hot-unload.

In @docs/planning/mongo-target/1-design-docs/user-promise.md:

  • Around line 229-245: Reword the "Cascade delete"/referential rules and the
    "Schema validation" section so every enforcement is qualified by
    adapter/deployment capability and connect-time negotiation: state that cascade
    cross-collection deletes are performed by PN only when the connected adapter
    reports support for multi-document transactions and required permissions
    (otherwise PN rejects the operation or fails closed), that server-side
    $jsonSchema push is attempted only when the adapter allows it and may be skipped
    with a clear diagnostic, and that strict read-mode validation is optional and
    enforced by PN only if the adapter/deployment scenario supports and consents to
    it; update the phrases under the "Cascade delete", "Server-side validation
    (optional)", and "On reads (configurable)" bullets to reflect adapter-reported
    capabilities and negotiated behavior at connect time.

In @packages/2-mongo-family/1-core/src/codecs.ts:

  • Around line 8-19: The factory mongoCodec currently requires config.encode even
    though the public MongoCodec interface marks encode as optional; update the
    factory signature so encode is optional (change the config type to encode?:
    (value: TJs) => TWire) and have the returned object set encode to config.encode
    (which may be undefined) so the produced value matches MongoCodec; reference
    mongoCodec, MongoCodec, encode, decode, config.typeId and config.targetTypes
    when making the change.

In @packages/2-mongo-family/1-core/src/contract-schema.ts:

  • Around line 50-60: The schema currently re-validates a raw Record via
    type('Record<string, unknown>').pipe(...) and a loop calling
    MongoModelFieldSchema, which duplicates validation logic; replace each instance
    with an Arktype record schema that enforces per-value validation directly (use
    type({ "[string]": MongoModelFieldSchema }) for the fields property and the
    other four analogous properties), and if you need custom error wording wrap the
    resulting record schema in a single .pipe() that inspects the validated record
    and throws a formatted Error; update the occurrences that reference fields and
    the five similar blocks so Arktype handles shape/element validation instead of
    manual Object.entries()/MongoModelFieldSchema re-validation.

In @packages/2-mongo-family/1-core/src/driver-types.ts:

  • Line 4: Remove the unsafe generic default on MongoDriver.execute by
    eliminating "= Record<string, unknown>" so the signature becomes
    execute(wireCommand: AnyMongoWireCommand): AsyncIterable; this forces
    callers to rely on the Row type carried by MongoQueryPlan (as propagated in
    mongo-runtime.ts) rather than overriding it, improving type safety—update the
    declaration of MongoDriver.execute accordingly and run type checks to ensure all
    call sites still supply the Row generic through existing MongoQueryPlan
    propagation.

In @packages/2-mongo-family/1-core/src/param-ref.ts:

  • Around line 1-16: Replace the exported concrete class MongoParamRef with an
    exported interface named MongoParamRef that describes the readonly properties
    value, name, and codecId, and provide a factory function (e.g.,
    createMongoParamRef or mongoParamRefOf) that returns the interface; keep the
    concrete class implementation unexported (rename to e.g., MongoParamRefImpl or
    keep as class inside module but not exported) and have the factory call new on
    that private class, preserving the existing constructor behavior and the
    previous static of API by mapping it to the new factory function; ensure
    Object.freeze behavior is retained on instances produced by the factory.

In @packages/2-mongo-family/1-core/src/validate-domain.ts:

  • Around line 110-115: The validateDiscriminators function only enforces that
    when model.discriminator exists then model.variants must be present, but not the
    inverse; update validateDiscriminators to also detect models that have a
    non-empty model.variants but lack model.discriminator and push an error (e.g.,
    Model "${modelName}" has variants but no discriminator) so models with
    variants cannot validate without a discriminator; locate the check inside
    validateDiscriminators iterating contract.models and add the inverse conditional
    referencing model.variants and model.discriminator to produce the error.

In @packages/2-mongo-family/1-core/src/validate-mongo-contract.ts:

  • Around line 18-33: The function validateMongoContract currently declares a
    generic TContract and uses an unsafe cast (as unknown as TContract) after
    parsing with MongoContractSchema; remove the generic parameter and the blind
    cast: change the signature to return ValidatedMongoContract (no
    type parameter), keep parsing via MongoContractSchema and assign the parsed
    value to a variable typed as MongoContract, then return { contract, indices,
    warnings } where contract is of type MongoContract; update any references to
    TContract in this function to use MongoContract and ensure downstream callers
    expect ValidatedMongoContract.

In @packages/2-mongo-family/1-core/src/values.ts:

  • Around line 3-10: The MongoValue union must be extended to carry encoded
    native values so codec-wrapped types like "mongo/objectId@1" can flow through
    the wire format; add a new type (e.g., EncodedNative = { codec: string; value:
    unknown } or a generic wrapper) and include it in the MongoValue union (or
    alternatively make MongoValue generic such as MongoValue<E = EncodedNative> and
    use that generic throughout: MongoDocument, MongoArray, MongoExpr,
    MongoUpdateDocument) so encoded artifacts are represented alongside
    LiteralValue, MongoDocument, MongoArray, and MongoParamRef.

In @packages/2-mongo-family/1-core/test/codecs.test.ts:

  • Line 2: The test imports createMongoCodecRegistry, MongoCodec and mongoCodec
    from the package export surface ('../src/exports/index'); change the import to
    reference the actual implementation/source modules that define those symbols
    (the files where createMongoCodecRegistry, MongoCodec type and mongoCodec are
    implemented) so the test imports directly from ../src/... instead of
    ../src/exports; update the import statement to point to the concrete source
    module paths that export createMongoCodecRegistry, MongoCodec and mongoCodec.

In @packages/2-mongo-family/4-orm/src/mongo-orm.ts:

  • Around line 95-145: findMany currently discards type info and uses a blind
    cast for the filter, and mongoOrm returns an unverified client object; fix by
    (1) changing findMany's return type to the executor's Row-based
    AsyncIterableResult (infer the Row type from this.#executor.execute so the
    method returns AsyncIterableResult instead of
    AsyncIterableResult), (2) remove the unnecessary cast on options.where
    and type filter as the declared MongoWhereFilter<TContract, ModelName> (it is
    structurally compatible with MongoExpr), and (3) construct the client in
    mongoOrm with a correctly typed container (e.g. a mapped/partial typed object
    keyed by contract.roots whose values are MongoCollectionImpl instances) so the
    compiler can verify each instantiation of MongoCollectionImpl matches the
    expected MongoOrmClient shape rather than returning an unknown-typed
    object; refer to findMany, this.#executor.execute, mongoOrm, and
    MongoCollectionImpl to locate the code to change.

In @packages/2-mongo-family/5-runtime/src/mongo-runtime.ts:

  • Around line 9-13: MongoRuntimeOptions currently lacks decode metadata so
    execute() just forwards driver.execute() rows unchanged; update
    MongoRuntimeOptions to include the necessary codec/result metadata (e.g., add a
    codecs or resultDecoders field) and modify MongoRuntime.execute (the method that
    calls driver.execute()) to map/transform each driver row through the appropriate
    decoder before yielding/returning it; use MongoLoweringContext or MongoAdapter
    metadata to locate per-field/result decoders and apply them to each row emitted
    from driver.execute() so storage types are converted back to the logical types.

In @packages/3-mongo-target/2-mongo-adapter/src/exports/codec-types.ts:

  • Around line 1-7: The export file src/exports/codec-types.ts currently defines
    CodecTypes inline but must be a pure re-export; move the type definition named
    CodecTypes into a core module (create/export it from the core codec-types
    module) and replace the body of src/exports/codec-types.ts with a single
    re-export of that core symbol (export type { CodecTypes } from the core module).
    Ensure the exported symbol name is unchanged so callers keep the same API.

In @packages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.ts:

  • Around line 66-70: The aggregate branch currently only shallow-copies pipeline
    stages, so MongoParamRef and nested params aren't resolved; update the case for
    'aggregate' to deep-resolve parameter refs in each stage (and inside nested
    arrays/documents such as $match, $project, $lookup.pipeline) before constructing
    AggregateWireCommand. Reuse the same resolution helpers used by the
    find/insertOne/updateOne paths (e.g., resolveValue, resolveDocument or the
    param-resolution function already present in this module) to walk and replace
    MongoParamRef instances in each stage and any nested structures, then pass the
    resolved pipeline to AggregateWireCommand.
  • Around line 78-91: The #resolveValue method incorrectly treats any non-null
    object as a MongoExpr and recursively walks BSON/special objects; update it to
    first detect plain JS objects before calling this.#resolveDocument. Add a
    plain-object type guard (e.g., check typeof value === 'object', not
    Array.isArray, and that value's constructor is Object or Object.prototype ===
    Object.getPrototypeOf(value)) and use that predicate to narrow to MongoExpr
    instead of the blind cast "as MongoExpr"; keep existing handling for
    MongoParamRef, Date, and arrays and only call this.#resolveDocument when the
    plain-object guard passes.

In @packages/3-mongo-target/2-mongo-adapter/tsconfig.json:

  • Around line 1-8: The tsconfig is missing Vitest globals in compilerOptions
    which causes tests under the "test" include to lack proper types; update the
    "compilerOptions" object (the existing rootDir setting) to add a "types" array
    that includes "vitest/globals" so the test files get Vitest type definitions and
    match other packages' tsconfig conventions.

In @packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts:

  • Around line 42-50: Both #executeFindCommand and #executeAggregateCommand leak
    Mongo cursors if the caller stops iteration early; update each method (functions
    named #executeFindCommand and #executeAggregateCommand) to wrap the cursor
    iteration in a try/finally: perform yield* cursor (or iterate) inside try, and
    in finally call await cursor.close() to ensure the server cursor is always
    closed and resources freed even when iteration is aborted early.

Minor comments:
In @docs/planning/0-references/community-generator-migration-analysis.md:

  • Around line 27-28: Update the "Important caveat" paragraph and the downstream
    fragmentation analysis to reflect that a Mongo family/target/runtime/ORM PoC now
    exists rather than SQL being the only implemented target: replace absolute
    statements that only SQL is implemented (mentions of ExecutionContext and
    SqlContract as the only runtime/contract types) with language acknowledging the
    new Mongo PoC while noting remaining gaps (e.g., ContractBase and
    DocumentContract stubs), adjust the "Cross-family support" analysis to
    re-evaluate fragmentation risk given Mongo PoC, and apply the same baseline
    change to the other referenced sections; follow the doc-maintenance guideline in
    .cursor/rules/doc-maintenance.mdc when updating wording and links.

In @docs/planning/mongo-target/1-design-docs/design-questions.md:

  • Around line 221-226: The docs wrongly describe Mongo model.storage as field -> codec whereas the PR moved codecId into model.fields and uses
    model.storage only as the persistence bridge; update the paragraph under
    ContractBase to reflect that model.fields now contain { nullable, codecId }
    and model.storage is a family-specific persistence mapping (not the location
    of codecId), and mention the SQL vs Mongo divergence: SQL maps field→column
    while Mongo uses fields.codecId with model.storage providing any additional
    persistence metadata or bridge info; reference ContractBase, model.fields,
    model.storage, and codecId when making this change.

In @docs/planning/mongo-target/1-design-docs/mongo-execution-components.md:

  • Around line 19-35: The fenced code block showing the Mongo flow (containing
    MongoQueryPlan, MongoRuntimeCore, and MongoDriver) is missing a language
    identifier and triggers markdownlint MD040; update the block fence to include a
    language (e.g., "text") so it reads ```text before the diagram and closes with
- Around line 11-15: The docs incorrectly equate MongoQueryPlan with the SQL
ExecutionPlan; update the text and table to reflect that MongoQueryPlan is a
higher-level plan that is lowered via the adapter before the driver sees a wire
command, and that ExecutionPlan/SqlQueryPlan are distinct lower-layer types;
specifically revise wording around MongoQueryPlan, MongoRuntimeCore, MongoDriver
(and the rows at lines 37-40) to state that MongoQueryPlan is translated by the
adapter into a driver-level wire command/SqlQueryPlan/ExecutionPlan rather than
being the same type as ExecutionPlan.

In `@docs/planning/mongo-target/1-design-docs/mongo-poc-plan.md`:
- Around line 36-43: Add a language specifier to the fenced code block that
documents the contract hierarchy so it renders with proper syntax highlighting
and accessibility; locate the block containing ContractBase, SqlContract and
MongoContract and change the opening fence to include an explicit language token
(for example use "text" or "mermaid" if you want diagram styling) so the block
begins with ```text (or another appropriate language) instead of just ```.

In `@docs/planning/mongo-target/9-references/mongo-idioms.md`:
- Around line 7-12: The heading "Sources" currently uses a level-3 heading ("###
Sources") which jumps from the top-level and triggers MD001; change that heading
to level-2 ("## Sources") so the document outline is consistent and the MD001
rule is satisfied, updating the line that reads "### Sources" to "## Sources".
- Around line 190-205: The docs use two different names for the same array
operator—`hasAll` in mongo-idioms.md and `hasEvery` in user-promise.md—so pick
one and make both files consistent; update the occurrence in
docs/planning/mongo-target/9-references/mongo-idioms.md (replace `hasAll` or
change the other file) and the occurrence in
docs/planning/mongo-target/1-design-docs/user-promise.md so both use the single
agreed operator name (either `hasAll` or `hasEvery`) everywhere, and run a quick
grep across the docs to ensure no other files reference the old variant.

In `@docs/planning/mongo-target/9-references/mongodb-primitives-reference.md`:
- Around line 429-433: Update the "Key architectural difference from SQL"
paragraph to clarify MongoDB index behavior: state that multiple consecutive
$match stages may be coalesced and the query planner can move later $match
stages earlier when safe, but that reshaping or materializing stages (e.g.,
$project, $group, $unwind) can prevent subsequent $match stages from using
indexes; keep the guidance that $match works best early and recommend placing
filtering before any stage that changes the document shape or materializes the
stream. Reference the terms $match, $project, $group, $unwind, "aggregation
pipelines", and "Prisma Next lowering" so the change is easy to locate.
- Around line 173-180: Update the "Many-to-many" section to remove the
definitive claim that junction/join tables are "not possible" and explicitly
mention the three supported MongoDB relationship patterns (embedding,
referencing via arrays of IDs, and junction/intermediate collections), noting
when to prefer a junction collection (high-cardinality relationships, unbounded
arrays, or when storing edge metadata like enrollment date/grade); change the
"Many-to-many" paragraph near the "One-to-many (reference)" and "Many-to-many"
headings to reflect this nuance and include examples/use-cases for using a
junction collection.

In `@docs/planning/mongo-target/Mongo` Overview.md:
- Around line 107-117: The fenced code block in the Mongo Overview markdown
lacks a language specifier; update the triple-backtick fence that surrounds the
package layout sample (the block showing "packages/2-mongo-family/" and
"packages/3-mongo-target/") to include a language specifier (e.g., change ``` to
```text) so the block becomes ```text and remains closed with ```; no content
changes needed inside the block.

In `@packages/2-mongo-family/1-core/src/validate-domain.ts`:
- Around line 136-168: The current detectOrphanedModels marks every model as
"referenced" by collecting all outgoing edges globally, which misses
disconnected clusters; instead implement a reachability walk seeded from
contract.roots: in detectOrphanedModels, start a DFS/BFS from each model name in
Object.values(contract.roots), maintain a visited Set, and for each visited
model push its outbound neighbors (model.relations[*].to,
Object.keys(model.variants) if present, and model.base if present) onto the
stack/queue; after the traversal, any modelName in modelNames not in visited
should produce the orphan warning string used today.
- Around line 84-87: Replace uses of the `in` operator for membership checks
with Object.hasOwn to avoid prototype-builtins issues: where the code checks
`modelName in baseModel.variants` (referencing baseModel and modelName) and the
other check at the similar pattern around contract.models (referencing
contract.models and modelName), change them to use
Object.hasOwn(baseModel.variants, modelName) and Object.hasOwn(contract.models,
modelName) respectively so you only test own properties safely.

In `@packages/2-mongo-family/4-orm/src/mongo-orm.ts`:
- Around line 54-55: The code currently ignores missing include targets by
checking const targetModel = contract.models[refRelation.to]; if (!targetModel)
continue; — change this to fail closed: detect when an include/refRelation.to
refers to a non-existent model and throw a descriptive error (include
refRelation.to and the current model name/context) instead of continuing; update
any surrounding logic in the function that uses targetModel (e.g., the include
resolution loop) to expect an exception for invalid contract references so
callers receive a clear configuration error rather than partial data.

In `@packages/2-mongo-family/4-orm/test/orm-types.test-d.ts`:
- Around line 99-108: The test "InferRootRow for polymorphic model returns union
of base+variant rows" currently allows the discriminator `type` to be widened to
string; update the expected union assertion so each branch includes literal
discriminator values (`type: 'bug'` and `type: 'feature'`) instead of `type:
string` to ensure InferRootRow preserves discriminated union narrowing—modify
the assertion that uses TaskRow / InferRootRow<Contract, 'Task'> to expect ({
_id: string; title: string; type: 'bug'; assigneeId: string } & BugRowPart) | ({
_id: string; title: string; type: 'feature'; assigneeId: string } &
FeatureRowPart).

In `@packages/3-mongo-target/3-mongo-driver/tsconfig.json`:
- Around line 6-7: Update the tsconfig.json exclude array to omit test fixture
files so fixture-only types aren't picked up during typechecking: add the
pattern "test/fixtures/**/*" to the existing "exclude" array (the same
tsconfig.json that currently contains "include": ["src", "test", "*.config.*",
"package.json"] and "exclude": ["dist", "dist-tsc", "dist-tsc-prod",
"node_modules"]) so TypeScript will ignore fixture files during compilation.

In `@test/integration/test/mongo/orm.test.ts`:
- Around line 22-26: The test assumes a stable order from orm.users.findMany()
by checking results[0] and results[1], which can flake; change the assertion to
be order-independent by either calling a deterministic sorter (e.g., sort by
name or email) on the results before asserting, or assert the returned set
contains both expected objects regardless of order (e.g., compare a set/array of
found names/emails to expected values). Update the assertions referencing
orm.users.findMany and the results variable to use the chosen approach so the
test no longer depends on natural collection order.

---

Nitpick comments:
In `@packages/2-mongo-family/1-core/src/contract-types.ts`:
- Around line 68-77: Remove the meaningless generic defaults from the
MongoContract type so callers must supply concrete generics: change the
declaration of MongoContract to require Roots, S, and M without defaulting to
Record<string, string>, MongoStorage, or Record<string, MongoModelDefinition>;
update the type parameters (Roots, S, M) and any internal references to continue
using those type names (e.g., MongoContract, Roots, S, M, MongoStorage,
MongoModelDefinition) but make them mandatory, and then audit and update any
call sites that previously relied on the defaults to pass explicit type
arguments.

In `@packages/2-mongo-family/1-core/test/validate.test.ts`:
- Around line 126-133: Replace the multiple related expects in the "happy path"
test for validateMongoContract with a single object matcher: assert the result
matches an object containing a defined contract, warnings as an empty array, and
indices with defined variantToBase and modelToVariants. Locate the test block
using validateMongoContract and ormContractJson and change the separate
expect(result.contract), expect(result.warnings).toHaveLength(0),
expect(result.indices.variantToBase) and expect(result.indices.modelToVariants)
assertions into one expect(result).toMatchObject(...) that checks these
properties together.

In `@packages/2-mongo-family/5-runtime/test/contract-execution.test.ts`:
- Around line 33-39: Replace the four individual assertions on the same user
object with a single object matcher: after extracting user from rows (rows and
user variables), use expect(user).toMatchObject({ name: 'Alice', email:
'[email protected]', bio: null, createdAt: new Date('2024-01-15T10:00:00Z') })
so related field checks are grouped; keep the initial
expect(rows).toHaveLength(1) and remove the separate expect(user.name)…
expect(user.createdAt) calls.

In `@packages/2-mongo-family/5-runtime/test/find.test.ts`:
- Around line 54-56: Replace the for-loop assertion over "rows" that checks
Object.keys(row) for each "row" with a single toEqual assertion: compute
rows.map(r => Object.keys(r)) and assert it equals an array of ['name'] repeated
for each row (e.g. rows.map(() => ['name'])), so the test validates the exact
projected keys in one assertion instead of a loop.

In `@packages/2-mongo-family/5-runtime/test/setup.ts`:
- Around line 59-65: The finally block currently runs runtime.close(),
client.close(), and replSet.stop() sequentially so a thrown error from
runtime.close() or client.close() prevents later cleanup; change it to invoke
each cleanup independently (e.g., use Promise.allSettled or wrap each call in
its own try/catch) so runtime.close(), client.close(), and replSet.stop() are
all attempted and errors are captured/aggregated before rethrowing or logging;
update the finally in the wrapper around fn(ctx) to ensure no single failure
aborts the remaining cleanup.

In `@packages/2-mongo-family/5-runtime/vitest.config.ts`:
- Around line 23-28: The coverage thresholds in the vitest config (the
thresholds object in vitest.config.ts) are set to 100% for statements, branches,
functions, and lines; lower these to a more practical PoC level (e.g., 90%) by
updating the numeric values in the thresholds object so tests won’t be blocked
by unrealistic full coverage during early iteration.

In `@packages/3-mongo-target/2-mongo-adapter/package.json`:
- Around line 34-38: The exports field only points to .mjs bundles and lacks
type definition mappings; update the package.json "exports" to include type
entries for the existing exports (e.g. map "." to "./dist/index.mjs" plus a
types path such as "./dist/index.d.ts", and "./codec-types" to
"./dist/codec-types.mjs" plus "./dist/codec-types.d.ts") so TypeScript consumers
resolve declarations; ensure the generated .d.ts files exist (from your build)
and add the "types" (or conditional "types"/"import") entries alongside the .mjs
paths in the "exports" object.

In `@test/integration/test/mongo/setup.ts`:
- Around line 24-29: The test setup hardcodes loweringContext.contract with
empty roots/storage/models which prevents contract-aware tests; update the setup
to accept an optional contract parameter (e.g., add an optional "contract?:
ContractType" arg to the setup function that creates adapter/driver) and
construct loweringContext using the provided contract or fall back to the
existing empty default, then pass that loweringContext into
createMongoRuntime(adapter, driver, loweringContext) (references:
MongoLoweringContext, loweringContext, createMongoRuntime, createMongoDriver,
createMongoAdapter) so tests can supply custom contracts when needed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

Comment thread docs/reference/mongodb-user-promise.md Resolved
wmadden added 26 commits March 30, 2026 17:42
Distills 10 non-obvious design questions from the MongoDB primitives
exploration — embed vs. reference modeling, referential integrity
enforcement, execution plan generalization, update operators, read-time
validation, type unions, relation loading strategy, aggregation pipeline
scope, change streams, and the shared contract surface.
Defines three core promises — domain model as source of truth, type-safe
querying with Mongo-native operations, and configurable guardrails — with
concrete code examples showing the intended UX. Establishes what PN does
and does not promise for Mongo, and positions it against the raw driver,
Mongoose, and Prisma ORM.
Updates design-questions.md:
- Note High priority signal from MongoDB team on polymorphism/inheritance
- Add design question #11 (introspection from existing databases)
- Add design question #12 (extension packs for Vector Search, Atlas Search, geospatial)
- Add design question #13 (CSFLE / queryable encryption)

Updates user-promise.md:
- Add introspection to the domain model promise
- Add extension pack ecosystem (Vector Search, Atlas Search, geospatial)
- Add CSFLE to non-promises section
- Expand ecosystem comparison table with polymorphism, Vector/Atlas Search,
  change streams, and introspection rows
…arget

Polymorphism is a cross-family concern — SQL needs single-table
inheritance and enum-discriminated rows, MongoDB needs polymorphic
collections, embedded fields, and mixed-type arrays. Both require
discriminated unions in the contract type system.

Rewrites design question #6 to cover both families with concrete storage
mapping patterns and defines minimum April validation scope: contract
can express discriminated unions, emitter produces narrowed TS types,
ORM queries return narrowed types, STI storage mapping works for both
families.
Catalogs the patterns experienced MongoDB developers use and expect
tools to support — data modeling (embed vs reference, extended reference,
subset, polymorphic collections, schema versioning, bucket, tree),
query (dot notation, array matching, projection, cursor pagination,
aggregation, distinct), mutation (atomic operators, array mutations,
upsert, bulk writes, findOneAndUpdate), and operational (change streams,
TTL, read/write concern). Each idiom notes the PN implication and links
to relevant design questions.
Three representative schemas — blog platform, e-commerce, and SaaS task
management with polymorphism — each with raw MongoDB document structure,
speculative Prisma Next PSL, and concrete ORM query examples. Covers
embed vs reference, polymorphic collections with discriminated unions,
atomic operators, array mutations, dot-notation filters, cursor
pagination, upsert, and cross-collection includes. Includes idiom
coverage matrix against mongo-idioms.md.
Mongo has no DDL — schema evolution is entirely data migration.
The invariant model from the migration workstream is a natural
fit. Add a future user promise (schema evolution via data
invariants) and design question #14 linking the two workstreams.
Link each idiom to its official MongoDB docs page(s) for
traceability and easy reference during implementation.
The claim that SQL plugins work unchanged for Mongo is unvalidated
and depends on the plugin interface being truly family-agnostic.
Makes capability gaps and strengths scannable at a glance.
Start from contract consumption (hand-craft contract, write query
code, make it execute) rather than bottom-up (authoring, emission,
adapter). The contract shape should be driven by what the query
client needs.
Steps 4-8 cover broadening CRUD, embedded docs, relations,
cross-family validation, and polymorphism spike. Risk summary
categorizes all 14 design questions by what they threaten and
which ones the PoC must answer.
…ract

Mongo is its own family (not a target under "document") because
document databases do not share a common query interface the way
SQL databases do. The ORM client will be built independently from
sql-orm-client, with common abstractions extracted afterward.
Traces the SQL execution flow, describes the Mongo equivalent,
and documents why ExecutionPlan/plugins cannot be generalized
across families. Plugins are family-specific because they inspect
family-specific query payloads. The shared surface is the lifecycle
and metadata, not the query plan.
Each family gets its own plan type, plugin interface, and runtime.
The shared surface is the lifecycle pattern and metadata, not the
query payload. Evidence: existing SQL plugins inspect plan.sql and
plan.ast directly, making generalization impractical.
Subscriptions (change streams, realtime) are a separate operation
type with their own lifecycle, not a variant of execute(). The
query input is shared within a family across request/subscribe
modes; the output shape and lifecycle differ. Change events may
standardize across families better than query plans do.
The "What IS shared" section was written before the streaming
analysis and claimed the plugin lifecycle is universally shared.
Updated to show sharing across two dimensions (family and operation
type) and extended the speculative CrossFamilyPlugin interface
with subscription hooks.
Add README.md as the entrypoint with question-centric spine,
April milestone reconciliation, testing strategy, package layout,
and reading guide. Trim premature streaming speculation in
execution-architecture.md to a focused summary. Fix internal
inconsistencies in mongo-poc-plan.md: reference resolved design
questions, clarify exploration-oriented framing, and split the
deferred list into April-scope vs beyond-April.
Restructure from an administrative dashboard (milestone
reconciliation, status tables, operational details) to a
narrative arc: why Mongo, what makes it different, what we
are building, what we know, what we do not know, how we are
finding answers. Add a "Maintaining these docs" section for
agents and team members iterating on the design.
Separate the entrypoint (Mongo Overview.md) from analytical
design docs (1-design-docs/) and stable reference material
(9-references/), mirroring the main architecture docs layout.

All cross-references updated to reflect the new paths.
Rewrite "What makes MongoDB different" to cover aggregation
pipelines, polymorphism, and real-time streaming as first-class
differences. Strengthen referential integrity consequences,
clarify mutation operators. Lead execution pipeline analysis
with reasoning instead of "analysis shows." Use
mongodb-memory-server for test provisioning. Add layering
enforcement constraint for the mongo domain.
Add VP5 to workstream 3: validate that runtime interfaces can
accommodate streaming subscriptions via Supabase Realtime. This
is strategically important — Prisma Postgres will need streaming
support, and stabilizing interfaces without validating streaming
risks closing that door for contributors.

Also update key risks to call out the streaming concern.
Link Mongo Overview, PoC plan, and April milestone workstream 4
to the new streaming VP5 in workstream 3. Streaming is validated
via Supabase Realtime in the SQL runtime; the Mongo PoC defers
change streams but must not prevent them.
Aggregation pipelines fill the same architectural role for Mongo
that the SQL query builder fills for SQL: a lower-level escape
hatch when the ORM cannot express a query. The lane interface is
family-specific but the role and interop guarantees (shared
session/transaction) are the same pattern across families.
wmadden added 11 commits March 30, 2026 21:57
Captures lessons from the MongoDB subsystem doc rewrite: write about the
system not the project, explain why before what, use concrete examples,
pair problems with solutions, and organize references by durability.
…skill

Move the contract JSON example to the top of 10. MongoDB Family.md so
readers have a concrete visual reference before encountering abstract
concepts. The Contract section now back-references the example instead
of duplicating it.

Update the write-architecture-docs skill to codify this practice: lead
with a complete code snippet, JSON example, or diagram near the top.
Document the six design principles that shape contract and ORM decisions
across families, with MongoDB as the forcing function that made each
explicit. Key addition: principle #5 states each model has one canonical
storage location (consistency boundary), and the embedded documents
section now explains how denormalized snapshots are value types, not the
model itself.

Update the doc-writing skill to recommend articulating design principles
early in architecture docs.
…rence

The Mongo Overview was redundant with the subsystem doc and ADRs.
Replace its narrative content with a concise index linking to canonical
architecture docs, planning docs, and reference material.

Move user-promise.md to docs/reference/mongodb-user-promise.md so it
survives the eventual deletion of the planning directory. Update all
cross-references (design-questions.md, mongo-poc-plan.md, subsystem doc,
overview).
New glossary entries from the MongoDB effort: aggregate root, model
(entity), value type (composite), relation strategy (reference/embed),
discriminator, variant, base model, specialization/generalization,
domain/storage separation, ContractBase, and Collection.
The glossary incorrectly marked prismaContract()/typescriptContract()
and the contract: config property as pending renames to schema-based
names. The contract naming is correct and intentional. Rename the
section to "Contract Provider", update function names, and remove the
four related rows from the terminology alignment tracker.
Contract is now the primary concept: users author their contract in PSL
or TypeScript, the system compiles it to contract.json. Schema refers
specifically to the database's actual structure (tables, collections,
indexes), not the user-authored model definitions.

Make Plan, Adapter, Driver, and Target entries family-agnostic by
including MongoDB examples alongside SQL.
"Composite" is a DDD pattern for recursive whole-part hierarchies,
which is not what we mean. "Value Type" is confusing in JS where every
primitive is a value type. "Value Object" is Evans's original DDD term,
self-describing, and communicates the key semantic: identity is defined
by field values, not by a separate ID.

Updated in glossary, subsystem docs, ADR 174, cross-cutting learnings,
design questions, PoC plan, data contract doc, and contract symmetry.
Drop the Contract Structure section (Domain/Storage Separation and
ContractBase are architectural concepts, not terminology). Remove the
speculative Typed SQL query builder entry.
@wmadden
wmadden marked this pull request as ready for review March 31, 2026 07:23
…e suppression

Replace non-null assertions with guard clauses in validate-domain.ts
(the modelNames.has() check above already guarantees existence, but
biome cannot see through it). Remove a stale biome-ignore comment in
validate.test.ts.

@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: 12

🧹 Nitpick comments (9)
docs/glossary.md (2)

130-130: Simplify link path format.

The ADR link uses URL-encoded spaces (%20), which reduces readability. Consider using actual spaces or angle brackets for paths with spaces to align with clearer path-only repo-relative link style.

🔗 Proposed fix
-The primary ORM abstraction for querying a model. Each aggregate root gets a `Collection` instance (e.g., `db.users` is a `Collection<Contract, 'User'>`). Collections use immutable fluent chaining — each method call (`.where()`, `.include()`, `.take()`) returns a new Collection with accumulated state. Nothing executes until a terminal method (`.all()`, `.first()`) compiles the state into a family-specific query plan. The Collection interface is shared across families; only the terminal compilation differs. See [ADR 175](architecture%20docs/adrs/ADR%20175%20-%20Shared%20ORM%20Collection%20interface.md).
+The primary ORM abstraction for querying a model. Each aggregate root gets a `Collection` instance (e.g., `db.users` is a `Collection<Contract, 'User'>`). Collections use immutable fluent chaining — each method call (`.where()`, `.include()`, `.take()`) returns a new Collection with accumulated state. Nothing executes until a terminal method (`.all()`, `.first()`) compiles the state into a family-specific query plan. The Collection interface is shared across families; only the terminal compilation differs. See [ADR 175](docs/architecture docs/adrs/ADR 175 - Shared ORM Collection interface.md).

Note: Verify the correct relative path from docs/glossary.md to the ADR file location.

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

In `@docs/glossary.md` at line 130, Update the ADR link text so it doesn't use
URL-encoded spaces: replace the current
"architecture%20docs/adrs/ADR%20175%20-%20Shared%20ORM%20Collection%20interface.md"
with a readable repo-relative path using spaces wrapped in angle brackets (e.g.,
<architecture docs/adrs/ADR 175 - Shared ORM Collection interface.md>) or
otherwise a space-preserving format; ensure the visible link target still
references ADR 175 - Shared ORM Collection interface so the reference in the
paragraph remains correct.

64-64: Use straight quotes for consistency.

The phrase uses curly quotes around "document". While the ASCII preference guideline specifically targets Mermaid labels, using straight quotes throughout the documentation improves consistency and avoids potential encoding issues.

📝 Proposed fix
-A category of databases that share fundamental characteristics. SQL is a family — Postgres, MySQL, and SQLite are all SQL targets that share concepts like tables, columns, and joins. MongoDB is its own family (not a target under a generic "document" family). Prisma Next defines shared behavior at the family level so individual targets only need to handle what's specific to them.
+A category of databases that share fundamental characteristics. SQL is a family — Postgres, MySQL, and SQLite are all SQL targets that share concepts like tables, columns, and joins. MongoDB is its own family (not a target under a generic "document" family). Prisma Next defines shared behavior at the family level so individual targets only need to handle what's specific to them.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/glossary.md` at line 64, Replace the curly (typographic) quotes around
the word “document” with ASCII straight quotes so the sentence uses consistent
straight quotes throughout; locate the phrase containing the curly-quoted
“document” in glossary.md (the sentence referencing MongoDB as its own family)
and replace the surrounding quotation marks with standard double quotes
"document".
docs/planning/mongo-target/1-design-docs/mongo-poc-plan.md (1)

36-42: Add language specifier to fenced code block.

The code block is missing a language specifier. Even for pseudo-code or plain text, specify a language (e.g., text or plaintext) to satisfy linting and improve rendering.

📝 Suggested fix
-```
+```text
 Desired state = target contract hash + required data invariants {I₁, I₂, …}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/planning/mongo-target/1-design-docs/mongo-poc-plan.md` around lines 36 -
42, The fenced code block containing the contract model tree (lines showing
ContractBase, SqlContract, MongoContract and Targets/Target) lacks a language
specifier; update the markdown block by adding a language token (e.g., "text" or
"plaintext") after the opening triple backticks so the block renders and passes
linting (target the block that shows "ContractBase (shared domain: roots, models
with fields/discriminator/variants, relations)" and its
SqlContract/MongoContract children).
packages/2-mongo-family/4-orm/src/mongo-orm.ts (1)

22-27: Consider making stubMeta more descriptive or documenting its purpose.

The stubMeta constant uses placeholder values (storageHash: 'orm', lane: 'mongo-orm'). While acceptable for a PoC, a brief comment explaining this is intentionally a stub would help future readers understand this is temporary.

📝 Suggested documentation
+// Stub metadata for PoC - real implementation should derive from contract
 const stubMeta: PlanMeta = {
   target: 'mongo',
   storageHash: 'orm',
   lane: 'mongo-orm',
   paramDescriptors: [],
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-mongo-family/4-orm/src/mongo-orm.ts` around lines 22 - 27, The
stubMeta constant (type PlanMeta) uses placeholder values and should be
documented as an intentional temporary stub: add a concise comment above
stubMeta explaining that these values (e.g., storageHash: 'orm', lane:
'mongo-orm') are PoC placeholders, what they represent, and include a TODO to
replace them with production-safe identifiers or to derive them from real
configuration; reference the PlanMeta shape and the stubMeta symbol so future
maintainers know where to update or remove the stub.
docs/architecture docs/subsystems/10. MongoDB Family.md (3)

220-230: Add language identifier to package layout code block.

-```
+```text
 packages/2-mongo-family/
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/architecture` docs/subsystems/10. MongoDB Family.md around lines 220 -
230, The code block showing the package layout (the block starting with
"packages/2-mongo-family/") lacks a language identifier; update that fenced code
block to use a language tag by changing the opening fence from ``` to ```text so
it becomes ```text and retains the same content and formatting.

149-155: Add language identifier to fenced code block.

The diagram code block is missing a language specifier. Use text or plaintext if no syntax highlighting is desired.

-```
+```text
 ContractBase (shared domain: roots, models with fields/discriminator/variants, relations)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/architecture` docs/subsystems/10. MongoDB Family.md around lines 149 -
155, The fenced diagram block lacking a language identifier should be updated to
include a language specifier (e.g., use ```text or ```plaintext) so the diagram
renders correctly; locate the block containing "ContractBase (shared domain:
roots, models with fields/discriminator/variants, relations)" along with
"SqlContract" and "MongoContract" and replace the opening triple backticks with
```text (or ```plaintext).

268-273: Planning doc references should be removed or relocated.

While these are labeled as "Historical context," durable architecture docs under docs/ should not reference transient planning artifacts. These links will become stale as milestones evolve. Consider:

  1. Moving essential design rationale into this doc or stable ADRs
  2. Removing these references entirely
  3. Moving this section to a separate planning index if the links are still valuable during active development

Based on learnings: "Ensure that all READMEs and system documentation under any 'packages' or 'docs' directory do not reference transient project artifacts located under a 'projects' directory."

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

In `@docs/architecture` docs/subsystems/10. MongoDB Family.md around lines 268 -
273, The "Historical context (planning docs):" section currently lists transient
planning links (e.g., "Design questions", "Contract symmetry", "Cross-cutting
learnings", "Execution components", "Example schemas") which should not live in
durable docs; remove or relocate these links by either (a) extracting any
essential rationale into this document or stable ADRs and replacing the links
with ADR references, (b) moving the entire block into a separate planning index
for transient artifacts, or (c) deleting the section if it’s not needed — update
the "Historical context (planning docs):" heading and the five bullet entries
accordingly so the durable docs no longer reference files under transient
planning locations.
docs/planning/mongo-target/1-design-docs/mongo-execution-components.md (1)

19-35: Add language identifier to data flow diagram.

-```
+```text
 MongoQueryPlan { command, meta }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/planning/mongo-target/1-design-docs/mongo-execution-components.md`
around lines 19 - 35, The data-flow diagram block is missing a language
identifier for the fenced code block; update the fenced block that contains
"MongoQueryPlan { command, meta }" to include a language tag (e.g., ```text) so
syntax highlighting/plaintext rendering is explicit. Locate the diagram lines
referencing MongoQueryPlan, MongoRuntimeCore, and MongoDriver and change the
opening fence to include the chosen identifier, leaving the diagram content
unchanged.
packages/2-mongo-family/4-orm/src/types.ts (1)

133-143: Consider whether MongoWhereFilter should allow null for nullable fields.

InferModelRow in contract-types.ts correctly adds | null to the output type for fields where nullable: true. However, MongoWhereFilter only extracts the codec's output type without checking the nullable property.

If filtering by null is a valid use case (e.g., where: { deletedAt: null }), the filter type should include | null for nullable fields:

 export type MongoWhereFilter<
   TContract extends MongoContractWithTypeMaps<MongoContract, MongoTypeMaps>,
   ModelName extends string & keyof TContract['models'],
   TCodecTypes extends Record<string, { output: unknown }> = ExtractMongoCodecTypes<TContract>,
 > = {
-  readonly [K in keyof TContract['models'][ModelName]['fields']]?: TContract['models'][ModelName]['fields'][K] extends {
-    readonly codecId: infer CId extends string & keyof TCodecTypes;
-  }
-    ? TCodecTypes[CId]['output']
+  readonly [K in keyof TContract['models'][ModelName]['fields']]?: TContract['models'][ModelName]['fields'][K] extends {
+    readonly codecId: infer CId extends string & keyof TCodecTypes;
+    readonly nullable: infer N;
+  }
+    ? N extends true
+      ? TCodecTypes[CId]['output'] | null
+      : TCodecTypes[CId]['output']
     : unknown;
 };

If intentional (filters always match exact non-null values), consider adding a comment explaining the design decision.

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

In `@packages/2-mongo-family/4-orm/src/types.ts` around lines 133 - 143,
MongoWhereFilter currently maps field K to the codec output type but ignores the
field's nullable flag, so nullable fields cannot be filtered with null; update
the mapped type in MongoWhereFilter to append | null when the corresponding
field definition in TContract['models'][ModelName]['fields'][K] has nullable:
true (e.g. test the field type against { nullable: true } and return
TCodecTypes[CId]['output'] | null), or if the current behavior is intentional
add a clear comment on MongoWhereFilter explaining filters never accept nulls;
reference the MongoWhereFilter type and the field shapes used by InferModelRow
to implement the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/architecture` docs/adrs/ADR 172 - Contract domain-storage separation.md:
- Around line 192-193: The Related section of "ADR 172 - Contract domain-storage
separation" currently links to transient planning docs (contract-symmetry.md and
cross-cutting-learnings.md); update the ADR so it no longer depends on
docs/planning: replace those links with stable ADRs or subsystem documentation
(or fold the durable learnings into this ADR itself), and ensure the Related
list references only permanent artifacts (existing ADRs or docs/ subsystem
pages) and not PoC or planning notes.
- Around line 125-127: The inline markup is malformed for contract keys like
**nullable**, **codecId** and **model.relations** so they render literally; fix
each occurrence by replacing the incorrect combination of backticks/asterisks
with simple code formatting (e.g., use `nullable`, `codecId`, `model.relations`)
so the identifiers render as inline code; search the document for other
occurrences (notably the ones around the referenced lines 161-162) and apply the
same replacement consistently.
- Around line 180-186: Update the "What this requires" section into two
subsections: "Implemented in this PR" and "Remaining work"; under "Implemented
in this PR" note that model-level relations/storage has already been applied to
the Mongo implementation (MongoContract) and the contract-types change is
present, and under "Remaining work" keep the tasks for the emitter changes, the
SQL emitter moving relations onto each model, updating consumer libraries
(notably the SQL ORM client), and designing ContractBase as a new abstraction
(not mechanically extracted); reference the symbols SqlContract, MongoContract,
ContractBase, emitter and SQL emitter so readers can locate the related code.

In `@docs/architecture` docs/subsystems/1. Data Contract.md:
- Around line 167-171: The "Entity vs value object" bullet currently points to a
transient planning note ("cross-cutting learnings"); replace that link with a
durable docs-level reference (create or point to a stable page under docs/ that
will persist) so the architecture subsystem page doesn't depend on planning
artifacts — update the link target in the "Entity vs value object" bullet and,
if needed, move or copy the referenced content into the durable docs page so the
link remains valid long-term.

In `@docs/planning/mongo-target/1-design-docs/mongo-execution-components.md`:
- Around line 103-107: The documentation incorrectly refers to dispatch
switching on command.operation while the implementation uses wireCommand.kind;
update the text and examples to use wireCommand.kind (e.g., change any mentions
like "Dispatch is a switch on `command.operation`" to "Dispatch is a switch on
`wireCommand.kind`") and adjust the listed cases (e.g., `find`, `insertOne`,
`aggregate`) to show they are matched against wireCommand.kind so the doc
matches the behavior in the mongo driver implementation.
- Line 37: The docs incorrectly state Mongo has no lowering step; update the
paragraph to say Mongo does perform a type-level lowering from MongoQueryPlan to
MongoExecutionPlan (the adapter.lower call used by MongoRuntimeImpl.execute with
this.#loweringContext) which adds the wireCommand used by the driver—explain
it's less transformative than SQL (no stringification) but still converts
plan.command to plan.wireCommand and produces distinct MongoQueryPlan and
MongoExecutionPlan types.

In `@docs/planning/mongo-target/cross-cutting-learnings.md`:
- Around line 66-67: The Markdown has mis-placed bold delimiters around
model.storage (currently written as `**model.storage`**); fix the formatting by
placing the bold asterisks correctly so the token is fully enclosed (e.g.,
**model.storage**) or use inline code backticks (`model.storage`) if you prefer
code styling; update the line containing the `model.storage` token (the phrase
shown as **model.storage`**) to use the corrected delimiters.

In `@docs/planning/mongo-target/Mongo` Overview.md:
- Line 34: Remove the transient `projects/` bullet from the index in "Mongo
Overview.md": either delete the `projects/ — implementation specs and plans
(transient, per the Drive workflow)` line or replace it with a stable ADR or
subsystem reference (e.g., an ADR link or docs/ path) so the index does not
point to a non-resolvable, transient location; update any adjacent bullets if
needed to preserve list formatting.

In `@docs/reference/mongodb-feature-support-priorities.md`:
- Around line 8-12: The inline code example containing strategy: "reference" |
"embed" is breaking the Markdown table because the pipe is unescaped; update the
table cell that contains the `strategy: "reference" | "embed"` snippet (the
string with strategy) to escape the pipe (e.g., `strategy: "reference" \|
"embed"` or replace the pipe with the HTML entity &#124;) so the entire Notes
column renders correctly; locate the occurrence by searching for the literal
text strategy: "reference" | "embed" in the file and apply the escape.

In `@docs/reference/mongodb-idioms.md`:
- Line 7: Heading level for "Sources" is too low and breaks the document
outline; change the Markdown heading "### Sources" to an H2 by replacing it with
"## Sources" in docs/reference/mongodb-idioms.md (look for the heading text
"Sources") so the file's heading hierarchy flows from the H1 to this H2 and
resolves markdownlint navigation errors.
- Around line 36-37: The reference page includes a transient planning link in
the sentence starting with "**PN implication**" that reads "See design question
`#1`"; remove that link and either replace it with a stable docs reference (an ADR
or a durable subsystem doc under docs/) or expand the note inline so it is
self-contained; apply the same change to the other occurrences that reference
planning design notes (the other "See design question..." / planning-links in
this file) so the durable docs no longer depend on transient planning artifacts.

In `@packages/2-mongo-family/1-core/src/contract-schema.ts`:
- Line 88: The schema MongoStorageCollectionSchema currently uses type({}) which
allows any properties and therefore doesn't match the TypeScript
MongoStorageCollection = Record<string, never> expectation; update
MongoStorageCollectionSchema to reject additional properties (e.g., configure
the type schema with '+': 'reject') so the validator disallows extra keys and
enforces an empty object shape consistent with MongoStorageCollection.

---

Nitpick comments:
In `@docs/architecture` docs/subsystems/10. MongoDB Family.md:
- Around line 220-230: The code block showing the package layout (the block
starting with "packages/2-mongo-family/") lacks a language identifier; update
that fenced code block to use a language tag by changing the opening fence from
``` to ```text so it becomes ```text and retains the same content and
formatting.
- Around line 149-155: The fenced diagram block lacking a language identifier
should be updated to include a language specifier (e.g., use ```text or
```plaintext) so the diagram renders correctly; locate the block containing
"ContractBase (shared domain: roots, models with fields/discriminator/variants,
relations)" along with "SqlContract" and "MongoContract" and replace the opening
triple backticks with ```text (or ```plaintext).
- Around line 268-273: The "Historical context (planning docs):" section
currently lists transient planning links (e.g., "Design questions", "Contract
symmetry", "Cross-cutting learnings", "Execution components", "Example schemas")
which should not live in durable docs; remove or relocate these links by either
(a) extracting any essential rationale into this document or stable ADRs and
replacing the links with ADR references, (b) moving the entire block into a
separate planning index for transient artifacts, or (c) deleting the section if
it’s not needed — update the "Historical context (planning docs):" heading and
the five bullet entries accordingly so the durable docs no longer reference
files under transient planning locations.

In `@docs/glossary.md`:
- Line 130: Update the ADR link text so it doesn't use URL-encoded spaces:
replace the current
"architecture%20docs/adrs/ADR%20175%20-%20Shared%20ORM%20Collection%20interface.md"
with a readable repo-relative path using spaces wrapped in angle brackets (e.g.,
<architecture docs/adrs/ADR 175 - Shared ORM Collection interface.md>) or
otherwise a space-preserving format; ensure the visible link target still
references ADR 175 - Shared ORM Collection interface so the reference in the
paragraph remains correct.
- Line 64: Replace the curly (typographic) quotes around the word “document”
with ASCII straight quotes so the sentence uses consistent straight quotes
throughout; locate the phrase containing the curly-quoted “document” in
glossary.md (the sentence referencing MongoDB as its own family) and replace the
surrounding quotation marks with standard double quotes "document".

In `@docs/planning/mongo-target/1-design-docs/mongo-execution-components.md`:
- Around line 19-35: The data-flow diagram block is missing a language
identifier for the fenced code block; update the fenced block that contains
"MongoQueryPlan { command, meta }" to include a language tag (e.g., ```text) so
syntax highlighting/plaintext rendering is explicit. Locate the diagram lines
referencing MongoQueryPlan, MongoRuntimeCore, and MongoDriver and change the
opening fence to include the chosen identifier, leaving the diagram content
unchanged.

In `@docs/planning/mongo-target/1-design-docs/mongo-poc-plan.md`:
- Around line 36-42: The fenced code block containing the contract model tree
(lines showing ContractBase, SqlContract, MongoContract and Targets/Target)
lacks a language specifier; update the markdown block by adding a language token
(e.g., "text" or "plaintext") after the opening triple backticks so the block
renders and passes linting (target the block that shows "ContractBase (shared
domain: roots, models with fields/discriminator/variants, relations)" and its
SqlContract/MongoContract children).

In `@packages/2-mongo-family/4-orm/src/mongo-orm.ts`:
- Around line 22-27: The stubMeta constant (type PlanMeta) uses placeholder
values and should be documented as an intentional temporary stub: add a concise
comment above stubMeta explaining that these values (e.g., storageHash: 'orm',
lane: 'mongo-orm') are PoC placeholders, what they represent, and include a TODO
to replace them with production-safe identifiers or to derive them from real
configuration; reference the PlanMeta shape and the stubMeta symbol so future
maintainers know where to update or remove the stub.

In `@packages/2-mongo-family/4-orm/src/types.ts`:
- Around line 133-143: MongoWhereFilter currently maps field K to the codec
output type but ignores the field's nullable flag, so nullable fields cannot be
filtered with null; update the mapped type in MongoWhereFilter to append | null
when the corresponding field definition in
TContract['models'][ModelName]['fields'][K] has nullable: true (e.g. test the
field type against { nullable: true } and return TCodecTypes[CId]['output'] |
null), or if the current behavior is intentional add a clear comment on
MongoWhereFilter explaining filters never accept nulls; reference the
MongoWhereFilter type and the field shapes used by InferModelRow to implement
the change.
🪄 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: 47afbe68-7cac-453f-8eca-8a324f38ad63

📥 Commits

Reviewing files that changed from the base of the PR and between ff6ca76 and f8400d2.

📒 Files selected for processing (96)
  • .agents/skills/write-architecture-docs/SKILL.md
  • architecture.config.json
  • docs/Execution Enums.md
  • docs/architecture docs/adrs/ADR 172 - Contract domain-storage separation.md
  • docs/architecture docs/adrs/ADR 173 - Polymorphism via discriminator and variants.md
  • docs/architecture docs/adrs/ADR 174 - Aggregate roots and relation strategies.md
  • docs/architecture docs/adrs/ADR 175 - Shared ORM Collection interface.md
  • docs/architecture docs/adrs/ADR 176 - Data migrations as invariant-guarded transitions.md
  • docs/architecture docs/subsystems/1. Data Contract.md
  • docs/architecture docs/subsystems/10. MongoDB Family.md
  • docs/architecture docs/subsystems/3. Query Lanes.md
  • docs/glossary.md
  • docs/planning/april-milestone.md
  • docs/planning/mongo-target/1-design-docs/contract-symmetry.md
  • docs/planning/mongo-target/1-design-docs/design-questions.md
  • docs/planning/mongo-target/1-design-docs/example-schemas.md
  • docs/planning/mongo-target/1-design-docs/mongo-execution-components.md
  • docs/planning/mongo-target/1-design-docs/mongo-poc-plan.md
  • docs/planning/mongo-target/Mongo Overview.md
  • docs/planning/mongo-target/cross-cutting-learnings.md
  • docs/reference/community-generator-migration-analysis.md
  • docs/reference/framework-integration-analysis.md
  • docs/reference/mongodb-feature-support-priorities.md
  • docs/reference/mongodb-idioms.md
  • docs/reference/mongodb-primitives-reference.md
  • docs/reference/mongodb-user-journey.md
  • docs/reference/mongodb-user-promise.md
  • packages/2-mongo-family/1-core/biome.jsonc
  • packages/2-mongo-family/1-core/package.json
  • packages/2-mongo-family/1-core/src/adapter-types.ts
  • packages/2-mongo-family/1-core/src/codec-registry.ts
  • packages/2-mongo-family/1-core/src/codecs.ts
  • packages/2-mongo-family/1-core/src/commands.ts
  • packages/2-mongo-family/1-core/src/contract-schema.ts
  • packages/2-mongo-family/1-core/src/contract-types.ts
  • packages/2-mongo-family/1-core/src/driver-types.ts
  • packages/2-mongo-family/1-core/src/exports/index.ts
  • packages/2-mongo-family/1-core/src/param-ref.ts
  • packages/2-mongo-family/1-core/src/plan.ts
  • packages/2-mongo-family/1-core/src/results.ts
  • packages/2-mongo-family/1-core/src/validate-domain.ts
  • packages/2-mongo-family/1-core/src/validate-mongo-contract.ts
  • packages/2-mongo-family/1-core/src/validate-storage.ts
  • packages/2-mongo-family/1-core/src/values.ts
  • packages/2-mongo-family/1-core/src/wire-commands.ts
  • packages/2-mongo-family/1-core/test/codecs.test.ts
  • packages/2-mongo-family/1-core/test/fixtures/orm-contract.d.ts
  • packages/2-mongo-family/1-core/test/fixtures/orm-contract.json
  • packages/2-mongo-family/1-core/test/validate-domain.test.ts
  • packages/2-mongo-family/1-core/test/validate-storage.test.ts
  • packages/2-mongo-family/1-core/test/validate.test.ts
  • packages/2-mongo-family/1-core/tsconfig.json
  • packages/2-mongo-family/1-core/tsconfig.prod.json
  • packages/2-mongo-family/1-core/tsdown.config.ts
  • packages/2-mongo-family/1-core/vitest.config.ts
  • packages/2-mongo-family/4-orm/package.json
  • packages/2-mongo-family/4-orm/src/exports/index.ts
  • packages/2-mongo-family/4-orm/src/mongo-orm.ts
  • packages/2-mongo-family/4-orm/src/types.ts
  • packages/2-mongo-family/4-orm/test/orm-types.test-d.ts
  • packages/2-mongo-family/4-orm/tsconfig.json
  • packages/2-mongo-family/4-orm/tsconfig.prod.json
  • packages/2-mongo-family/4-orm/tsdown.config.ts
  • packages/2-mongo-family/4-orm/vitest.config.ts
  • packages/2-mongo-family/5-runtime/biome.jsonc
  • packages/2-mongo-family/5-runtime/package.json
  • packages/2-mongo-family/5-runtime/src/exports/index.ts
  • packages/2-mongo-family/5-runtime/src/mongo-runtime.ts
  • packages/2-mongo-family/5-runtime/test/aggregate.test.ts
  • packages/2-mongo-family/5-runtime/test/contract-execution.test.ts
  • packages/2-mongo-family/5-runtime/test/contract-types.test-d.ts
  • packages/2-mongo-family/5-runtime/test/delete.test.ts
  • packages/2-mongo-family/5-runtime/test/find.test.ts
  • packages/2-mongo-family/5-runtime/test/fixtures/contract.d.ts
  • packages/2-mongo-family/5-runtime/test/fixtures/contract.json
  • packages/2-mongo-family/5-runtime/test/insert.test.ts
  • packages/2-mongo-family/5-runtime/test/orm-contract-types.test-d.ts
  • packages/2-mongo-family/5-runtime/test/setup.ts
  • packages/2-mongo-family/5-runtime/test/update.test.ts
  • packages/2-mongo-family/5-runtime/tsconfig.json
  • packages/2-mongo-family/5-runtime/tsconfig.prod.json
  • packages/2-mongo-family/5-runtime/tsdown.config.ts
  • packages/2-mongo-family/5-runtime/vitest.config.ts
  • packages/3-mongo-target/1-mongo-target/biome.jsonc
  • packages/3-mongo-target/1-mongo-target/package.json
  • packages/3-mongo-target/1-mongo-target/src/core/descriptor-meta.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/pack.ts
  • packages/3-mongo-target/1-mongo-target/test/descriptor-meta.test.ts
  • packages/3-mongo-target/1-mongo-target/tsconfig.json
  • packages/3-mongo-target/1-mongo-target/tsconfig.prod.json
  • packages/3-mongo-target/1-mongo-target/tsdown.config.ts
  • packages/3-mongo-target/1-mongo-target/vitest.config.ts
  • packages/3-mongo-target/2-mongo-adapter/biome.jsonc
  • packages/3-mongo-target/2-mongo-adapter/package.json
  • packages/3-mongo-target/2-mongo-adapter/src/core/codec-ids.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/codecs.ts
💤 Files with no reviewable changes (1)
  • docs/Execution Enums.md
✅ Files skipped from review due to trivial changes (57)
  • packages/2-mongo-family/1-core/tsconfig.prod.json
  • packages/3-mongo-target/1-mongo-target/biome.jsonc
  • packages/2-mongo-family/4-orm/tsconfig.json
  • packages/2-mongo-family/5-runtime/biome.jsonc
  • packages/2-mongo-family/5-runtime/tsconfig.json
  • packages/2-mongo-family/4-orm/tsdown.config.ts
  • packages/3-mongo-target/1-mongo-target/tsconfig.prod.json
  • packages/2-mongo-family/1-core/tsconfig.json
  • packages/3-mongo-target/2-mongo-adapter/biome.jsonc
  • packages/2-mongo-family/1-core/tsdown.config.ts
  • packages/2-mongo-family/5-runtime/test/aggregate.test.ts
  • packages/3-mongo-target/1-mongo-target/test/descriptor-meta.test.ts
  • packages/2-mongo-family/1-core/biome.jsonc
  • packages/3-mongo-target/2-mongo-adapter/src/core/codec-ids.ts
  • packages/2-mongo-family/5-runtime/src/exports/index.ts
  • packages/2-mongo-family/5-runtime/test/contract-types.test-d.ts
  • packages/3-mongo-target/1-mongo-target/tsdown.config.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/pack.ts
  • packages/2-mongo-family/4-orm/vitest.config.ts
  • packages/2-mongo-family/1-core/src/adapter-types.ts
  • packages/2-mongo-family/5-runtime/tsdown.config.ts
  • packages/2-mongo-family/5-runtime/test/insert.test.ts
  • docs/architecture docs/adrs/ADR 175 - Shared ORM Collection interface.md
  • packages/3-mongo-target/1-mongo-target/tsconfig.json
  • packages/2-mongo-family/1-core/vitest.config.ts
  • docs/reference/mongodb-user-journey.md
  • packages/2-mongo-family/5-runtime/test/orm-contract-types.test-d.ts
  • docs/architecture docs/adrs/ADR 173 - Polymorphism via discriminator and variants.md
  • packages/2-mongo-family/1-core/src/results.ts
  • packages/2-mongo-family/4-orm/tsconfig.prod.json
  • packages/2-mongo-family/1-core/test/codecs.test.ts
  • docs/architecture docs/subsystems/3. Query Lanes.md
  • docs/planning/mongo-target/1-design-docs/example-schemas.md
  • packages/2-mongo-family/4-orm/src/exports/index.ts
  • packages/2-mongo-family/1-core/src/driver-types.ts
  • packages/2-mongo-family/5-runtime/tsconfig.prod.json
  • packages/2-mongo-family/1-core/test/fixtures/orm-contract.json
  • packages/2-mongo-family/1-core/test/validate.test.ts
  • packages/2-mongo-family/5-runtime/test/update.test.ts
  • docs/architecture docs/adrs/ADR 174 - Aggregate roots and relation strategies.md
  • packages/2-mongo-family/1-core/src/codec-registry.ts
  • packages/2-mongo-family/5-runtime/test/contract-execution.test.ts
  • docs/reference/mongodb-user-promise.md
  • docs/planning/mongo-target/1-design-docs/contract-symmetry.md
  • packages/2-mongo-family/5-runtime/test/find.test.ts
  • packages/2-mongo-family/5-runtime/package.json
  • packages/2-mongo-family/5-runtime/test/fixtures/contract.json
  • packages/2-mongo-family/1-core/src/values.ts
  • packages/2-mongo-family/1-core/package.json
  • packages/3-mongo-target/1-mongo-target/package.json
  • packages/2-mongo-family/4-orm/package.json
  • packages/2-mongo-family/1-core/src/plan.ts
  • packages/3-mongo-target/2-mongo-adapter/package.json
  • packages/2-mongo-family/1-core/src/wire-commands.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/codecs.ts
  • packages/2-mongo-family/1-core/src/commands.ts
  • packages/2-mongo-family/1-core/src/exports/index.ts
🚧 Files skipped from review as they are similar to previous changes (12)
  • packages/2-mongo-family/5-runtime/test/delete.test.ts
  • packages/3-mongo-target/1-mongo-target/src/core/descriptor-meta.ts
  • packages/2-mongo-family/1-core/src/param-ref.ts
  • packages/2-mongo-family/1-core/src/validate-storage.ts
  • packages/3-mongo-target/1-mongo-target/vitest.config.ts
  • packages/2-mongo-family/5-runtime/src/mongo-runtime.ts
  • packages/2-mongo-family/5-runtime/vitest.config.ts
  • packages/2-mongo-family/5-runtime/test/setup.ts
  • packages/2-mongo-family/1-core/src/contract-types.ts
  • packages/2-mongo-family/4-orm/test/orm-types.test-d.ts
  • packages/2-mongo-family/1-core/src/codecs.ts
  • packages/2-mongo-family/5-runtime/test/fixtures/contract.d.ts

Comment thread docs/reference/mongodb-idioms.md Resolved
Comment thread docs/reference/mongodb-idioms.md Resolved
wmadden added 3 commits March 31, 2026 09:43
Each README includes Responsibilities and Dependencies sections
as required by the validate-package-readmes script.
- Remove unsafe generic default from MongoDriver.execute() (T5)
- Reject variants declared without a discriminator (T7)
- Import test targets from source modules, not exports barrel (T10)
- Add vitest/globals to mongo-adapter tsconfig types (T16)
- Enforce empty collection objects in contract schema (T29)
- Fix malformed backtick/asterisk order in ADR 172 (T18)
- Update ADR 172 follow-up list to reflect Mongo PoC progress (T19)
- Replace planning doc links with durable ADR/subsystem refs (T20, T21, T28)
- Fix lowering step description in execution components doc (T22)
- Fix wireCommand.kind terminology in execution components doc (T23)
- Fix model.storage formatting in cross-cutting-learnings (T24)
- Remove projects/ pointer from Mongo Overview (T25)
- Escape pipe in feature support priorities table (T26)
- Fix heading hierarchy in mongodb-idioms.md (T27)

@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: 5

🧹 Nitpick comments (1)
packages/2-mongo-family/1-core/src/validate-domain.ts (1)

70-71: Minor: Redundant null checks after Set membership verification.

Lines 70-71 and 85-86 check if (!variantModel/baseModel) continue; immediately after confirming the name exists in modelNames (which is derived from Object.keys(contract.models)). These are defensive but technically redundant.

Per coding guidelines, assertions are preferred over defensive checks when data is guaranteed valid. However, given this is a PoC and the cost is minimal, this is acceptable.

Also applies to: 85-86

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

In `@packages/2-mongo-family/1-core/src/validate-domain.ts` around lines 70 - 71,
The checks `if (!variantModel) continue;` and `if (!baseModel) continue;` are
redundant because `modelNames` is derived from `Object.keys(contract.models)`
and guarantees presence; remove these defensive null checks in the loop that
iterates over `modelNames` (where `variantModel = contract.models[variantName]`
and later `baseModel = contract.models[baseName]`) or replace them with
assertions (e.g., using an assert helper) referencing `variantModel` and
`baseModel` so the code reflects the guaranteed invariants without unnecessary
continues.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/planning/mongo-target/1-design-docs/mongo-execution-components.md`:
- Around line 14-15: Update the doc text to correctly reflect current PoC
behavior: either mark the hook lifecycle (beforeExecute/onRow/afterExecute) as
"planned/future" or adjust the described behavior to match the actual
implementation in packages/2-mongo-family/5-runtime/src/mongo-runtime.ts which
currently calls lower() then the driver and wraps results in AsyncIterableResult
without orchestrating hooks; update mentions of MongoRuntimeCore,
RuntimeCoreImpl, MongoDriver, Queryable and the lines referenced (14, 24, 33,
125-132, 139-140) so they explicitly state the current behavior and note the
planned hook orchestration as a future enhancement.
- Around line 162-169: Update the outdated package paths in the docs so they
point to the current repo layout: replace references to 2-mongo/1-core/ and
3-targets/6-adapters/mongo/... with the canonical package paths
packages/2-mongo-family/... and packages/3-mongo-target/... (or equivalent
current names) wherever the codec abstractions (MongoCodec, mongoCodec(),
MongoCodecRegistry) and base codec implementations (objectId codec,
string/int32/boolean/date in codecs.ts) are described; ensure the ObjectId
representation paragraph and the "Base codecs" line reference the correct file
location (e.g., packages/3-mongo-target/src/core/codecs.ts) so docs match the
actual code layout.
- Line 45: Update the MongoCommand docs to reflect the implemented
discriminated-union command model instead of the “speculative shape”: replace
the single optional-field `operation` object description with the
`kind`-discriminated union that lists concrete command variants (`find`,
`insertOne`, `updateOne`, `deleteOne`, `aggregate`) and remove references to
`insertMany`/`updateMany`/`deleteMany`; ensure examples, field names, and any
JSON shapes shown match the actual command classes and the `kind` discriminator
used in the codebase (e.g., the implemented `MongoCommand` union).
- Around line 19-35: The fenced code block showing the Mongo execution flow
(containing MongoQueryPlan, MongoRuntimeCore, and MongoDriver) is unlabeled and
triggers MD040; update the opening fence from ``` to include a language tag (for
example ```text) so the block becomes ```text and keep the rest unchanged so
markdown linting passes.
- Around line 96-100: The interface declaration for MongoDriverInterface is
incorrect: update the execute method's parameter type from MongoCommand to the
runtime type used by the driver (AnyMongoWireCommand) so the docs match
implementation; locate the MongoDriverInterface and its execute<Row =
Record<string, unknown>>(command: MongoCommand) declaration and change the
parameter type to AnyMongoWireCommand and adjust any surrounding text to mention
that execute consumes AnyMongoWireCommand at the runtime/driver boundary.

---

Nitpick comments:
In `@packages/2-mongo-family/1-core/src/validate-domain.ts`:
- Around line 70-71: The checks `if (!variantModel) continue;` and `if
(!baseModel) continue;` are redundant because `modelNames` is derived from
`Object.keys(contract.models)` and guarantees presence; remove these defensive
null checks in the loop that iterates over `modelNames` (where `variantModel =
contract.models[variantName]` and later `baseModel = contract.models[baseName]`)
or replace them with assertions (e.g., using an assert helper) referencing
`variantModel` and `baseModel` so the code reflects the guaranteed invariants
without unnecessary continues.
🪄 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: 75820c83-3b44-463b-a5c3-7df3569c3ae6

📥 Commits

Reviewing files that changed from the base of the PR and between a0603f5 and 237c2c1.

📒 Files selected for processing (13)
  • docs/architecture docs/adrs/ADR 172 - Contract domain-storage separation.md
  • docs/architecture docs/subsystems/1. Data Contract.md
  • docs/planning/mongo-target/1-design-docs/mongo-execution-components.md
  • docs/planning/mongo-target/Mongo Overview.md
  • docs/planning/mongo-target/cross-cutting-learnings.md
  • docs/reference/mongodb-feature-support-priorities.md
  • docs/reference/mongodb-idioms.md
  • packages/2-mongo-family/1-core/src/contract-schema.ts
  • packages/2-mongo-family/1-core/src/driver-types.ts
  • packages/2-mongo-family/1-core/src/validate-domain.ts
  • packages/2-mongo-family/1-core/test/codecs.test.ts
  • packages/2-mongo-family/1-core/test/validate-domain.test.ts
  • packages/3-mongo-target/2-mongo-adapter/tsconfig.json
✅ Files skipped from review due to trivial changes (8)
  • packages/2-mongo-family/1-core/src/driver-types.ts
  • packages/3-mongo-target/2-mongo-adapter/tsconfig.json
  • docs/planning/mongo-target/Mongo Overview.md
  • docs/reference/mongodb-feature-support-priorities.md
  • packages/2-mongo-family/1-core/test/codecs.test.ts
  • docs/planning/mongo-target/cross-cutting-learnings.md
  • docs/architecture docs/adrs/ADR 172 - Contract domain-storage separation.md
  • packages/2-mongo-family/1-core/test/validate-domain.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/architecture docs/subsystems/1. Data Contract.md
  • docs/reference/mongodb-idioms.md

wmadden added 2 commits March 31, 2026 14:26
- Mark plugin hooks as planned, not current behavior
- Add language tag to fenced code block
- Update MongoCommand section from speculative to implemented
  discriminated union model
- Fix driver interface to use AnyMongoWireCommand
- Update codec location paths to current package layout
- Update MongoRuntime section to reflect PoC implementation
The contract example referenced Post in roots and User.relations but
never defined it, making the example inconsistent.

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/architecture` docs/subsystems/10. MongoDB Family.md:
- Around line 163-169: The fenced code blocks in the Markdown snippet (the tree
block starting with "ContractBase..." and the packages block starting with
"packages/2-mongo-family/") lack language identifiers and violate markdownlint
MD040; update both fenced blocks to include a language tag (e.g., ```text) so
they become "```text" ... "```". Also apply the same change to the other
affected fenced block region mentioned (lines 236-246) so any additional
triple-backtick blocks include a language identifier; locate the blocks by
searching for the code fences in the "10. MongoDB Family.md" content and replace
the opening ``` with ```text.
- Line 68: The markdown emphasis/backtick sequence around Address and storage is
malformed; replace "`**Address` has `storage: {}**`" with properly balanced
backticks/emphasis such as "`Address` has `storage: {}` — empty because it
doesn't own a collection; its data lives within User's storage." Ensure
`Address`, `storage: {}`, and `User` are wrapped with backticks (or use
consistent bold/italic) so rendering is correct.
- Around line 34-35: The JSON example for the embed relation is missing the
required field property required by MongoEmbedRelation; update the example entry
for "addresses" (which currently has "to": "Address", "cardinality": "1:N",
"strategy": "embed") to include the required "field" key with an example field
name (e.g., "field": "addresses") so the contract matches the MongoEmbedRelation
shape and is structurally valid.
- Line 181: Replace references to transient planning artifacts with stable
architecture or package-level documents: remove the link to
../../planning/mongo-target/1-design-docs/contract-symmetry.md (and any other
../../planning/... links noted around the file) and instead point to a stable
ADR or architecture doc or a package README that captures the same "contract
symmetry" analysis; update the link target and link text to reference the
canonical architecture/ADR title (or create a short stable ADR if none exists)
and ensure all similar planning-doc links in this Markdown are replaced
consistently.
🪄 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: 098981bb-0314-4ed4-a2e7-5d5346b38b51

📥 Commits

Reviewing files that changed from the base of the PR and between 237c2c1 and d40b95f.

📒 Files selected for processing (2)
  • docs/architecture docs/subsystems/10. MongoDB Family.md
  • docs/planning/mongo-target/1-design-docs/mongo-execution-components.md
✅ Files skipped from review due to trivial changes (1)
  • docs/planning/mongo-target/1-design-docs/mongo-execution-components.md

wmadden added 2 commits March 31, 2026 14:57
Address has no _id and no independent identity — it is a value object,
not an entity. Using it as a model contradicts the design principle
that all models are entities. Replace with Comment (which has _id)
embedded in Post, and clarify that value objects have no contract
representation yet.
Add `text` language identifiers to two fenced code blocks (contract
hierarchy diagram and package layout) and replace inline planning-doc
links in the body with references to the stable References section.

@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.

♻️ Duplicate comments (1)
docs/architecture docs/subsystems/10. MongoDB Family.md (1)

290-297: ⚠️ Potential issue | 🟠 Major

Remove transient planning-doc links from durable architecture references.

Line 290-Line 297 reintroduce ../../planning/... links in a durable docs/architecture page. Please replace these with stable ADR/package/docs links (or drop the section if no stable target exists).

Proposed doc change
-**Historical context (planning docs):**
-
-- [Design questions](../../planning/mongo-target/1-design-docs/design-questions.md) — open architectural questions with full analysis
-- [Contract symmetry](../../planning/mongo-target/1-design-docs/contract-symmetry.md) — where Mongo and SQL contracts converge and diverge
-- [Cross-cutting learnings](../../planning/mongo-target/cross-cutting-learnings.md) — design principles affecting the framework core
-- [Execution components](../../planning/mongo-target/1-design-docs/mongo-execution-components.md) — execution pipeline component details
-- [Example schemas](../../planning/mongo-target/1-design-docs/example-schemas.md) — concrete MongoDB schemas with speculative PSL
+**Historical context:**
+
+- See architecture ADRs above and stable docs under `docs/reference/` for current guidance.

Based on learnings: "Do not reference transient project artifacts (e.g., under projects/ such as specs, plans, milestone documents) from durable system documentation... Apply this pattern to all Markdown documentation files (READMEs and docs) across the repo."

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

In `@docs/architecture` docs/subsystems/10. MongoDB Family.md around lines 290 -
297, The "Historical context (planning docs):" section currently embeds
transient "../../planning/mongo-target/..." links; replace each of those
planning-doc links (e.g.,
"../../planning/mongo-target/1-design-docs/design-questions.md",
"contract-symmetry.md", "cross-cutting-learnings.md",
"mongo-execution-components.md", "example-schemas.md") with stable targets or
remove the section: either point to permanent ADRs/package docs/archived RFCs
that cover the same topics, or drop the entire "Historical context (planning
docs):" block if no stable equivalent exists; ensure the header "Historical
context (planning docs):" and the listed bullet items are updated consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@docs/architecture` docs/subsystems/10. MongoDB Family.md:
- Around line 290-297: The "Historical context (planning docs):" section
currently embeds transient "../../planning/mongo-target/..." links; replace each
of those planning-doc links (e.g.,
"../../planning/mongo-target/1-design-docs/design-questions.md",
"contract-symmetry.md", "cross-cutting-learnings.md",
"mongo-execution-components.md", "example-schemas.md") with stable targets or
remove the section: either point to permanent ADRs/package docs/archived RFCs
that cover the same topics, or drop the entire "Historical context (planning
docs):" block if no stable equivalent exists; ensure the header "Historical
context (planning docs):" and the listed bullet items are updated consistently.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 57caff20-560d-42ba-8a47-11cd6f2dc88c

📥 Commits

Reviewing files that changed from the base of the PR and between d40b95f and ce0b3f2.

📒 Files selected for processing (1)
  • docs/architecture docs/subsystems/10. MongoDB Family.md

@wmadden
wmadden merged commit 2d06c5e into main Mar 31, 2026
14 checks passed
@wmadden
wmadden deleted the mongo-poc branch March 31, 2026 14:38
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