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

TML-2521: Target-extensible IR + enum - #499

Merged
wmadden merged 176 commits into
mainfrom
target-extensible-ir
May 16, 2026
Merged

wmadden merged 176 commits into
mainfrom
target-extensible-ir

Conversation

@wmadden

@wmadden wmadden commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

closes TML-2521

At a glance

// examples/prisma-next-demo/prisma/contract.ts (real consumer call site)
import { defineContract, rel } from '@prisma-next/sql-contract-ts/contract-builder';
import sqlFamily from '@prisma-next/family-sql/pack';
import postgresPack from '@prisma-next/target-postgres/pack';

export const contract = defineContract(
  { family: sqlFamily, target: postgresPack /* ... */ },
  (helpers) => {
    const types = {
      user_type: helpers.enum({ name: 'user_type', values: ['admin', 'user'] as const }),
    } as const;

    const User = helpers.model('User', {
      fields: {
        id: helpers.field.id.uuidv4(),
        kind: helpers.field.namedType(types.user_type),
        // ...
      },
    });
    // ...
  },
);

helpers.enum({...}) is a top-level helper alongside the built-in helpers.model / helpers.field / helpers.rel. Pre-PR, the equivalent surface was type.enum('user_type', ['admin', 'user']), dispatched through codec hooks that hand-rolled enum verification, planning, and DDL emission. PSL enum X { ... } syntax is unchanged on both sides.

Decision

Open a target-extensible IR seam so contract artifacts that aren't codecs stop being modelled as codec hooks. Codecs are "a name + a parse/serialize function over column values". Enums (and the next consumers — namespaces, RLS policies, roles, views) carry first-class metadata, lifecycle, and dispatch needs that don't fit that shape, and pre-PR they were faked through codec-hook glue (pgEnumControlHooks: ~700 lines of bridging code that hand-rolled diff, plan, and DDL emission). This PR introduces three cooperating mechanisms that let target packs contribute first-class IR entities through the same extension surface as codecs and field presets:

  1. A 3-layer polymorphic IR convention (framework abstract → family abstract → target concrete) that contract + schema artifacts now ride.
  2. ContractSerializer + SchemaVerifier SPIs so deserialization and verification dispatch through target descriptors, not a standalone validateContract function.
  3. An entityTypes contribution surface on AuthoringContributions so packs ship entity factories (descriptor + factory, mirroring codecDescriptors[].factory) and they appear as top-level helpers on the contract-builder.

Postgres enum is the first real consumer through all three: pgEnumControlHooks is deleted and the enum walks the verifier and planner natively as a PostgresEnumType IR class.

How it works

The new IR shape

Every IR class now extends IRNodeBase (framework) → family abstract (SqlNode, MongoSchemaNode) → target concrete. Constructors call freezeNode(this) to produce immutable instances; the discriminator strategy follows the "earn it" rule (per-leaf enumerable kind only when polymorphic dispatch consumes it; otherwise non-enumerable, keeping JSON envelopes clean — see learnings.md § "framework-level required-kind discriminator is unearned under union-narrowing dispatch"). Both interface Storage extends IRNode and class SqlStorage implements Storage so the framework structural promise is honoured uniformly across families.

Enum entries live in the polymorphic storage.types slot — the slot type is the framework StorageType alphabet, and the contribution-surface factory returns a PostgresEnumType instance directly (no as unknown cast). On disk, an enum entry carries kind: 'postgres-enum' + codecId: 'pg/enum@1' + name + nativeType + values. Codec-typed entries (pgvector, decimal, varchar) are byte-identical to pre-PR.

Key code: packages/1-framework/1-core/framework-components/src/ir/ir-node.ts (L42-59); packages/2-sql/1-core/contract/src/ir/postgres-enum-storage-entry.ts; packages/3-targets/3-targets/postgres/src/core/postgres-enum-type.ts (L49-56); packages/3-targets/3-targets/postgres/src/core/authoring.ts (L42-51).

Hydration through SPIs, not a standalone function

Contract validation flows through descriptor.contractSerializer.deserializeContract(json); schema verification through descriptor.schemaVerifier.verifySchema(...). The SQL family-base hydrator dispatches via a ReadonlyMap<discriminator, factory> populated from each pack's entityTypes contribution — no kind === 'postgres-enum' switch, no per-target hydrator hook. New entity kinds register themselves; the family base no longer imports any target-specific IR class.

Standalone validateContract is gone from the SQL barrel; postgres<Contract>(...) and sqlite<Contract>(...) extension facades wrap the SPI call so most user-facing surfaces are unchanged. Two foundation-level barrel exports survive (framework validateContract, foundation validateMongoContract) as layering-allowed structural-validation primitives for non-family consumers.

Key code: packages/2-sql/9-family/src/core/control-instance.ts (registry-driven hydrator); SQL adapters' serializeContract is now required, not optional.

Migration cost

Surface Before After
TS authoring (one-line change per call site) type.enum('role', values) helpers.enum({ name: 'role', values })
PSL authoring enum X { ... } unchanged
Contract validation validateContract(json) from @prisma-next/sql-contract/validate descriptor.contractSerializer.deserializeContract(json) (or use the wrapping façade)
On-disk envelope (codec-typed entries) unchanged unchanged
On-disk envelope (enum entries) implicit codec triple kind: 'postgres-enum' + codecId: 'pg/enum@1' + name + nativeType + values

Migration is the single touch in examples/prisma-next-demo/prisma/contract.ts:22-26 for the in-tree consumer. No backward-compat shim for type.enum — preserving one would violate .cursor/rules/no-backward-compatibility.md and would be a footgun for every future entity contribution.

Evidence

  • End-to-end: test/integration/test/cli-journeys/data-transform-enum-rebuild.e2e.test.ts exercises planner-emitted placeholder() stubs + the rebuild recipe (createEnumType(temp) → alterColumnType → dropEnumType(orig) → renameType + DataTransformCall) end-to-end against PGlite. This test caught a real regression late in PR1's pre-merge gate (commit f23665db0 — the projector wrote the polymorphic shape directly into schema.annotations.pg.storageTypes, breaking the codec-typed annotation invariant enum-planning.ts § readExistingEnumValues reads; planner skipped the rebuild recipe and emitted a bare CreateEnumTypeCall).
  • Parity: 1 of 19 emit-parity fixtures changed (the one with an enum entry); 18 are byte-identical. See packages/2-sql/9-family/test/contract-to-schema-ir.test.ts.
  • Layering: pnpm lint:deps clean; the family layer has no upward edges to target packages, and the SQL family dispatches polymorphic enum entries through the structural PostgresEnumStorageEntry interface + isPostgresEnumStorageEntry type guard rather than instanceof PostgresEnumType (which would invert the layering rule).
  • Mongo dependency edge severed (separable architectural fix riding the same PR because it touched the same SPI shape): family-mongo no longer imports target-mongo / adapter-mongo. Implementation: packages/3-mongo-target/2-mongo-adapter/src/core/control-adapter.ts.

What's deferred (the rest of the project)

  • TML-2520 — PR2: namespace exemplar + cross-namespace FK references. Namespaces are the second consumer that earns the entityTypes mechanism. Schema IR enum representation also lifts to first-class IR there (no polymorphic-dispatch consumer today; the bridging adapter inside the new verifier walk is ~20 LOC and isolates the asymmetry to one site, see enum-planning.ts § readExistingEnumValues).
  • Application-facing enum DX (literal-tuple propagation through EntityHelperFunction<Descriptor>, enum-value defaults, codec value-awareness, db.enums.<Name> runtime surface) — routed to a separate postgres-enum-finishing project. PR1 ships an architecturally honest exemplar; that project ships an idiomatically usable one.
  • Three reviewer-flagged carry-forwards: codec-aware default-decoding regression (F01), MongoTargetUnspecifiedDatabase frozen-by-base trap (F04, doc-only fix in tree; structural fix earns its own commit when a leaf adds an instance field), Mongo built-in contribution-ification.

Risk

  • PGlite parallelism flake is pre-existing and not exacerbated by this PR. Affects integration tests under high parallelism; reproducibly green under --no-file-parallelism or per-file isolation. Mitigation tracked separately.

Alternatives considered

  • Per-target contract builders (e.g. @prisma-next/postgres-contract-builder). Rejected: forks the user-facing API per target ("familiar with one target, fluent in another" was a stated guiding principle), duplicates the bulk of the contract-builder, and the entityTypes mechanism achieves target extensibility without that cost.

  • Declarative-only entity contributions (pack ships only a node-shape descriptor; framework synthesises a generic wrapper). Rejected: loses per-class methods (accept(visitor)), loses freeze-in-constructor semantics, loses per-class type narrowing — extensible entities would not be first-class IR. The descriptor + factory shape (analogous to codecDescriptors[].factory) lets packs ship both the schema for the SL and a typed TS function for direct contract construction.

  • Storage shape Option A (a dedicated storage.enums namespace separate from storage.types). Rejected as scope overshoot for one consumer (~60-80 file cascade across dual-traversal sites + dual-namespace contract.json schema + example fixture rewrites). The polymorphic-value shape is the smallest step that earns first-class IR status; Option A is a strict superset that can be earned later if a future milestone (Postgres-domain entities sharing namespace-scoped lifecycle: roles + RLS + views + enums) earns it.

  • Storage shape Option C (codec-typed entry as on-disk truth + hydrated IR-class wrapper on read). Rejected as a backward-compat shim in disguise: the codec-typed entry would persist on disk indefinitely as a parallel representation. Option B's polymorphic value carries enum data first-class on disk; the codec-hook glue removal is real, not cosmetic.

  • type.enum shim kept alongside helpers.enum for migration friction reduction. Rejected: directly violates the no-backward-compat-shim discipline; migration cost is one call site per consumer; a parallel shim would be a footgun for every future entity contribution.

  • Single-PR delivery (M1–M5 in one PR, including namespaces). Rejected at the namespace pre-flight: namespace work was substantial enough to materially expand the diff and put the proven mechanism at risk if it hit a deeper architectural issue. Splitting keeps the proven mechanism reviewable as a unit + isolates the higher-risk namespace work in TML-2520.

  • Defer the architectural seams to a follow-up PR (ship the enum exemplar with the codec-hook glue intact, fix layering later). Rejected mid-project: the as unknown as StorageTypeInstance cast at the contribution surface, the kind === 'sql-enum-type' hardcode in the family hydrator, and the Mongo family → target dependency edge were all "M4 was supposed to remove" debts; shipping them forward would have made PR2's namespace exemplar pay the same architectural-honesty cost twice. The M9 close (slot widening + cast drop + family-abstract collapse + discriminator rename + helpers-shape flatten + MongoTargetStorage hoist) lands them inside this PR so PR2 inherits a clean seam.

Summary by CodeRabbit

  • Documentation

    • Added comprehensive architecture documentation covering polymorphic IR patterns, interface-based design, affordance-based extension model, and control-plane layering across SQL and Mongo families.
    • Updated contract authoring patterns for TypeScript and PSL, including entity contributions and namespace support.
  • Bug Fixes & Changes

    • Contracts now support namespace scoping at the framework level.
    • Enhanced schema verification and contract serialization through target-specific SPI.
    • Enum authoring in PSL now uses entity contributions instead of type constructors.

Review Change Stack

wmadden added 30 commits May 13, 2026 17:47
Adds a small set of structural JSON types (JsonPrimitive, JsonArray,
JsonObject, JsonValue) under @prisma-next/utils/json. Used by the
upcoming target-extensible IR work to type the canonical-JSON face of
the ContractSerializer SPI (TML-2459) — serializeContract returns
JsonObject so call sites can stringify, hash, or feed the output into
another SPI without re-asserting JSON-cleanness.

Signed-off-by: Will Madden <[email protected]>
Adds the framework-level IR vocabulary that Contract IR and Schema IR
across all families/targets share:

- interface SchemaNode { readonly kind: string } — the bare alphabet.
- abstract class SchemaNodeBase — centralised freeze() helper for
  concrete IR-node subclasses (mirrors the OpFactoryCall and
  MongoSchemaNode patterns).
- interface Namespace extends SchemaNode { readonly id: string } and
  abstract class NamespaceBase — the database-level grouping every
  storage object belongs to. Sentinel id "__unspecified__" is reserved
  for connection-bound binding (resolved by per-target singleton
  subclasses; never by call-site branches).
- interface Storage { readonly namespaces: Record<string, Namespace> }
  — framework-level promise that every IR carries namespaces, so the
  (namespace.id, name) keying the verifier depends on is honest at
  every layer.

Surfaces under the new @prisma-next/framework-components/ir subpath.
No consumers yet (M1 of TML-2459). Family abstract bases land in
follow-up commits.

Signed-off-by: Will Madden <[email protected]>
…rifier SPIs

Introduces the two framework-level SPI interfaces target descriptors
will compose as named properties (alongside the existing migrations
property), per TML-2459 M1:

- ContractSerializer<TContract> covers both faces of the JSON ⇄ classes
  seam: deserializeContract(json) hydrates JSON into typed class
  instances; serializeContract(contract): JsonObject produces the
  canonical JSON shape. Both directions live on the same SPI because
  the framework needs both today (round-trip property tests, drift
  detection, future canonicalization), not eventually.

- SchemaVerifier<TContract, TSchema> exposes the per-target verifier
  the framework dispatches to per contract space. Returns the minimal
  ok/issues pair; the framework wraps these into the existing
  VerifyDatabaseSchemaResult envelope. The framework SchemaIssue union
  is intentionally not generic over target kinds in this project (see
  the spec's "Forward note: SchemaIssue layering").

- createIdentityContractSerializer<TContract>() helper for tests that
  don't exercise serialization; identity in both directions over
  JSON-clean class instances. Tests reach for this instead of a real
  target descriptor when the JSON ⇄ class boundary isn't under test.

No descriptor wiring or family abstract bases yet — those land in the
follow-up commits within M1.

Signed-off-by: Will Madden <[email protected]>
Introduces the SQL family layer of the 3-layer IR pattern (TML-2459 M1).
Each base extends the framework alphabet and commits the SQL family to
its shape; targets (Postgres, SQLite) extend these bases with concrete
classes in M3.

IR-node bases (all extend SchemaNodeBase):
- SqlNode      — SQL family alphabet root
- SqlTable     — name + namespaceId; columns/PK/FKs etc on target
- SqlColumn    — name + nullable; nativeType on target (dialect-specific)
- SqlPrimaryKey, SqlUnique, SqlForeignKey, SqlIndex
- SqlStorage   — implements framework Storage; namespaces map

SPI abstract bases (per-SPI, single inheritance):
- SqlContractSerializerBase<TContract>   — implements ContractSerializer;
  identity serializeContract over JSON-clean class instances; protected
  hooks for parseSqlContractStructure + constructTargetContract.
- SqlSchemaVerifierBase<TContract, TSchema> — implements SchemaVerifier;
  runs verifyCommonSqlSchema + verifyTargetExtensions, returns the
  combined ok/issues result.

The IR-node field shapes are intentionally minimal at the family layer.
M3 lifts the existing flat-data Postgres/SQLite contract IR into the
class hierarchy and is where richer family-shape commitments (column
maps, FK references) land — alongside the targets that actually carry
them. The bases here ship the contract every SQL target signs.

Surfaces under the new @prisma-next/family-sql/ir subpath. No consumers
in M1; correctness via typecheck + lint:deps (per the M1 plan).

Signed-off-by: Will Madden <[email protected]>
… MongoSchemaNode

Introduces the Mongo family layer of the 3-layer IR pattern (TML-2459 M1)
and lifts the existing Mongo Schema IR alphabet to extend the framework
SchemaNodeBase, paralleling the SQL family bases.

MongoSchemaNode (already an abstract class with kind + accept):
- now extends SchemaNodeBase, inheriting the framework freeze() helper
- removes the local freeze() duplicate (no behavioural change)
- adds @prisma-next/framework-components as a runtime dep

Family bases (in @prisma-next/family-mongo/ir):
- MongoStorage implements Storage   — namespaces map promise (Mongo
  namespace = the connection's db; concrete subclasses land in M2).
- MongoContractSerializerBase<TContract> implements ContractSerializer
  — identity serializeContract over JSON-clean class instances;
  protected hooks for parseMongoContractStructure +
  constructTargetContract.
- MongoSchemaVerifierBase<TContract, TSchema> implements SchemaVerifier
  — runs verifyCommonMongoSchema + verifyTargetExtensions; concrete
  walk lands in M2 alongside the Mongo target IR class flip.

Mongo's storage class flip and concrete target SPI implementers land
in M2 (the first-consumer milestone). M1 ships only the family
abstract scaffolding.

lint:deps green (840 modules, 1680 deps, 0 violations).

Signed-off-by: Will Madden <[email protected]>
Captures the architectural decision against the foundation it
describes. Drafted in M1 per the project plan; refined through M2-M5b
as the convention is exercised against Mongo (M2), the SQL targets
(M3), enums (M4), and the namespace exemplar (M5a/b); promoted to
docs/architecture docs/adrs/ at close-out (M6) with a permanent ADR
number.

Lives at projects/target-extensible-ir/specs/ for now; the close-out
PR moves it under docs/architecture docs/adrs/ alongside the other
ADRs the project produces (3-layer convention + architectural
principles per FR25 / AC10).

Signed-off-by: Will Madden <[email protected]>
…from m1 R1

- M1 ADR scope: amend M1 task wording to draft both ADRs AC10 names (3-layer
  IR convention + architectural principles) plus any further ADRs M1 surfaces
  as load-bearing. Mirrors AC10 phrasing and gives subsequent milestones a
  principles North Star to cite when they exercise the convention.
  Generalise M6 task wording correspondingly so refinement scope tracks
  whatever M1 drafted.
- New "Open items" section recording pre-existing test fragility surfaced
  during M1 R1 review (Postgres adapter integration-test flakiness, CLI
  mock setup) — out of M1 gate, revisit at M3 entry; no Linear tickets
  filed per orchestrator/user decision.
- Add projects/target-extensible-ir/learnings.md recording reasoning-effort
  checkpoints for the orchestrate-plan loop on this project.

Signed-off-by: Will Madden <[email protected]>
… operations + ts-render

These two package.json hunks were bundled into 469b45f ("feat(framework-components/ir): introduce SchemaNode, Namespace, Storage") as scope bleed. The cleanup itself is reasonable (the packages already declare `exports`), but it belongs in its own commit, not inside the framework IR types slice.

This commit reverts only those two hunks. A follow-up `chore(packages): remove redundant legacy main+module fields where exports is set` re-applies them alongside the other packages with the same redundancy.

Net change to branch tip is zero across the pair; commit history reads honestly.

Refs: TML-2459, m1 R2 finding F1.

Signed-off-by: Will Madden <[email protected]>
…orts is set

These 24 packages all declare a modern `exports` map (with `"."` and any subpath exports). The `main` and `module` fields they also declared are redundant under modern Node resolution — `exports` wins, and the duplicate `"./dist/index.mjs"` strings are noise that drift independently when a package later splits an export, breaking subtly.

Strip them across all packages that already commit to `exports`. No behavioural change: published resolution still flows through `exports`; only stale fields are removed.

Two of the cleanups (operations + ts-render) were originally bundled into 469b45f as scope bleed; the prior commit reverted them and this commit re-applies them alongside the other 22 packages so the cleanup lands as one honest commit.

Refs: TML-2459, m1 R2 finding F1.

Signed-off-by: Will Madden <[email protected]>
Names the two architectural principles underwriting the 3-layer polymorphic IR convention and the broader target-extensibility surface this project ships:

1. The framework provides affordances; targets implement specifics. The framework encodes behaviour as interfaces, abstract bases, and SPI shapes (the affordances); targets fill in rendering, dialect quirks, native types, target-only kinds (the specifics). Operationalises today's "Thin core, fat targets" by naming the *why* underneath it.

2. Familiar with one target, fluent in another. Because every target consumes the same framework affordances, a developer fluent in one target reads the next target the same way — same IR walk shape, same SPI surface, same namespace mental model (Postgres schema, MySQL database, Mongo db). The framework promises the form; targets fill in the content.

Both principles already live in the codebase as implicit conventions (ADR 195's OpFactoryCall, ADR 185's SPI types, the target descriptor pattern, MongoSchemaNode). This ADR lifts them out of "convention by example" and into "stated principles" so follow-up projects (Supabase RLS, Cockroach extending Postgres, MySQL family) can reference them rather than re-derive them.

Cross-linked with the companion 3-layer polymorphic IR convention ADR — the two read as a pair, principles ↔ convention.

Status: draft (matches the 3-layer convention ADR's status). M6 refines both against the experience from M2–M5b. Promotes to docs/architecture docs/adrs/ at close-out per the M6 plan task.

Refs: TML-2459, M1 plan task (post-amendment) + AC10 + FR23 + FR25.

Signed-off-by: Will Madden <[email protected]>
Records the orchestrator intent-validation pass for m1 R2 (high-reasoning
checkpoint #1) and translates the three observations surfaced by the pass
into M2 R1 reviewer watch-points: lowering of family-shared verifier and
parser bodies (MongoSchemaVerifierBase.verifyCommonMongoSchema,
MongoContractSerializerBase.parseMongoContractStructure) from abstract to
concrete in the family layer rather than the target layer; meaningful
exercise of MongoTargetStorage inheritance over MongoStorage; and a grep
guard against any namespace.id === "__unspecified__" branches in M2 code
(per the singleton-subclass pattern committed in both ADR drafts).

The orchestrator note in code-review.md is local-only (reviews/ is
gitignored by repo convention); the watch-points in learnings.md are
committed because the orchestrator uses them when delegating M2 R1.

Signed-off-by: Will Madden <[email protected]>
M2 was specified in prose ("Mongo unit + integration tests pass") but
without an enumerated gate-command set the orchestrator skill expects per
milestone. Codifies the orchestrator/user agreement reached during M1 R2
close-out:

- pnpm typecheck (catches cross-package breakage from the Mongo IR rename)
- pnpm lint:deps
- pnpm --filter Mongo packages test (foundation + family + target)
- pnpm test:integration (the only mongodb-memory-server path)
- cross-package grep guard for deleted/renamed type names

pnpm test:packages intentionally excluded: the pre-existing fragility
under § Open items would surface as noise on every Mongo round and force
manual triage. The --filter scope is the surface M2 actually changes.

Signed-off-by: Will Madden <[email protected]>
M2 R1 implementer surfaced three deferral requests during pre-implementation
reconnaissance, all answered in unattended mode (see wip/unattended-decisions.md
sections 2-4):

- Mongo M1 SPI bases were placed in @prisma-next/family-mongo, but that
  package already depends on @prisma-next/target-mongo; target classes
  cannot extends the bases without a circular workspace dep. M1 R1/R2
  review missed the layering check. Plan updated to add a labeled
  prerequisite "M1 placement fix" at the start of M2 R1 work moving the
  three bases to @prisma-next/mongo-contract foundation. SQL is fine
  (correct dependency direction); no parallel fix needed in M3.
- M2 verifier-base body adopts the pragmatic recipe: family base provides
  iteration scaffolding (walk + protected per-element hooks + result
  envelope assembly); target overrides hooks carrying per-element
  diff/canonicalize logic. Eventual lift of contractToMongoSchemaIR /
  canonicalizeSchemasForVerification / diffMongoSchemas to the family
  layer is deferred to a future project (post-Supabase, when a second
  Mongo target exists).
- M2 split into two implementer rounds: R1 = SPI shells + namespace +
  descriptor + Mongo's share of validateContract migration; R2 = full
  Contract IR class flip cascade. Round-level split (vs milestone-level)
  preserves the project's spec-level guarantee while keeping each round
  reviewable in isolation.

learnings.md gains a "cross-target consistency check is part of
intent-validation" pattern entry — the placement defect was missed by
both M1 R1 review and M1 R2 orchestrator pass because neither ran a
per-target reachability check. M3 intent-validation will include the
check for SQL pairs.

Open items section gains two new entries: (1) the deferred lift of
Mongo schema-side helpers to family layer; (2) the descriptor-seam
asymmetry vs SQL as a future-project consideration.

Signed-off-by: Will Madden <[email protected]>
…ose-out gap)

The M1 commit placed `MongoContractSerializerBase`, `MongoSchemaVerifierBase`,
and abstract `MongoStorage` in `@prisma-next/family-mongo` (`9-family`), the
top-most mongo sub-layer. `family-mongo` already depends on `target-mongo`
(the descriptor composes target migration code into the family descriptor),
so the reverse direction is closed: `target-mongo` cannot `extends`
the family SPI bases without creating a circular workspace dependency.

Move the three SPI base files to `@prisma-next/mongo-contract` (foundation),
expose them via a new `./ir` subpath, and drop the corresponding `./ir`
export from `family-mongo`. `target-mongo` already depends on
`mongo-contract`, so M2 R1 substantive work can now author the concrete
SPI implementers (`MongoTargetContractSerializer`, `MongoTargetSchemaVerifier`,
`MongoTargetStorage`) in the target package.

No behaviour change. No M1-era consumers existed for the family `./ir`
barrel besides forward-references in the M2 plan, so this move is
strictly a prerequisite reshape ahead of M2 R1 substantive work.

The asymmetry with SQL is intentional: the SQL family descriptor
correctly lives at a lower layer than the SQL target descriptors, so
the SQL SPI bases (placed at family-level in M1) sit upstream of the
target consumers without inversion. No parallel fix is needed for M3.

Refs: target-extensible-ir M2 R1 prerequisite (orchestrator decision,
`wip/unattended-decisions.md § 2`).

Signed-off-by: Will Madden <[email protected]>
… R1 slice 1)

Lower MongoSchemaVerifierBase.verifyCommonMongoSchema and
MongoContractSerializerBase.parseMongoContractStructure from `protected
abstract` to concrete with family-shared bodies, per the M2 R1 watch-points.

`verifyCommonMongoSchema` now iterates `storage.namespaces` in sorted order
and dispatches per-namespace through a protected `verifyNamespace` hook
that the target overrides. The family commits to "verification is
namespaced"; the per-namespace diff lives in the target where the
existing introspection-side helpers (contractToMongoSchemaIR,
canonicalizeSchemasForVerification, diffMongoSchemas) belong. The split
satisfies the orchestrator decision (scaffolding interpretation, not
full-body lowering) and keeps target-mongo as the home for whole-schema
diff logic.

`parseMongoContractStructure` now runs the existing family-shared
validation pipeline (MongoContractSchema arktype parse +
validateContractDomain + validateMongoStorage) and returns the validated
plain-data shape. Targets implement `constructTargetContract` to wrap
the validated value in their class hierarchy (MongoTargetStorage with
`namespaces`). Targets that need additional structural checks can
override parseMongoContractStructure.

Rename abstract class `MongoStorage` -> `MongoStorageBase` to avoid a
package-internal naming collision with the existing `type MongoStorage`
data shape in `contract-types.ts`, and to follow the codebases `*Base`
convention for abstract IR-side bases (SchemaNodeBase, NamespaceBase,
MongoContractSerializerBase, MongoSchemaVerifierBase). The watch-point
text in the orchestrator prompt referred to the class as `MongoStorage`;
the rename is a same-meaning consistency adjustment recorded here so the
M2 reviewer can spot it.

Refs: target-extensible-ir M2 R1 watch-points 1 + 2 (orchestrator
Decision 2 in `wip/unattended-decisions.md`).

Signed-off-by: Will Madden <[email protected]>
…R1 slice 2)

Concretize the Mongo target Namespace concept. MongoTargetDatabase
extends NamespaceBase (frozen-AST class with kind="database" and a
string id). MongoTargetUnspecifiedDatabase is a singleton subclass with
`id = "__unspecified__"`; it overrides qualifier() and qualifyCollection()
to elide the database prefix.

Call sites that render fully-qualified collection references will reach
for `namespace.qualifyCollection("events")` polymorphically; the
singleton substitutes "events" for "<db>.events" without any branching
on `namespace.id === "__unspecified__"`. The singleton-subclass pattern
is the target-side materialization of "the framework provides affordances;
targets implement specifics".

No existing call sites are migrated to use these classes in this commit;
the storage class (MongoTargetStorage) that consumes them lands in a
later slice this round.

Refs: target-extensible-ir M2 R1 (plan slice 2; ADR draft
`projects/target-extensible-ir/specs/3-layer-polymorphic-ir-convention.md`
§ "__unspecified__ is a target-specific singleton subclass").

Signed-off-by: Will Madden <[email protected]>
Three concrete SPI implementers in the Mongo target, plus the typed
contract envelope they exchange:

- MongoTargetStorage extends MongoStorageBase. Inherits the family
  `namespaces` commitment from the base; adds `storageHash` and
  `collections` (target-specific). Default namespaces is
  `{ __unspecified__: MongoTargetUnspecifiedDatabase.instance }`. The
  collection leaf shapes remain flat-data until M2 R2.

- MongoTargetContractSerializer extends MongoContractSerializerBase
  <MongoTargetContract>. Implements constructTargetContract: wraps the
  family-validated value in a MongoTargetStorage instance, leaving the
  rest of the contract envelope as-is.

- MongoTargetSchemaVerifier extends MongoSchemaVerifierBase
  <MongoTargetContract, MongoSchemaIR>. Implements verifyNamespace
  (calls the existing contractToMongoSchemaIR /
  canonicalizeSchemasForVerification / diffMongoSchemas pipeline, with
  strict=false for SPI-routed calls) and verifyTargetExtensions
  (returns []). M2 R1 invariant: exactly one namespace per contract
  (__unspecified__); the family-base namespace walk dispatches once and
  the existing whole-schema diff runs unchanged. M5a will project the
  diff per-namespace.

- MongoTargetContract type alias: structurally MongoContract with
  storage promoted to the MongoTargetStorage class. The leaf shapes
  inside collections remain MongoStorageCollection (flat data); the IR
  node class flip lands in M2 R2.

No call sites are migrated to use the implementers yet — that is slice
6. This commit only adds the shells and exercises them via unit tests.

Watch-point 3 compliance: MongoTargetStorage extends MongoStorageBase
meaningfully — it inherits the family `namespaces` field and adds
`collections` + `storageHash` on the target. No "nominal-only"
inheritance.

Watch-point 4 compliance: zero `namespace.id === "__unspecified__"`
branches in the new code. The polymorphism is the dispatch itself
(family base walks namespaces; target hook runs the per-namespace diff).

Refs: target-extensible-ir M2 R1 slice 4 (plan; ADR draft
`projects/target-extensible-ir/specs/3-layer-polymorphic-ir-convention.md`).

Signed-off-by: Will Madden <[email protected]>
…lidateContract sites (M2 R1 slices 5+6)

Compose the SPI implementers onto the Mongo target descriptor and
migrate the five Mongo-side validateContract call sites to route
through it.

Slice 5 — descriptor extension. Introduce MongoControlTargetDescriptor
(a Mongo-specific refinement of MigratableTargetDescriptor) that adds
two named SPI properties next to the existing `migrations` capability:

  contractSerializer: ContractSerializer<MongoTargetContract>
  schemaVerifier:     SchemaVerifier<MongoTargetContract, MongoSchemaIR>

`mongoTargetDescriptor` (the runtime instance) composes
`new MongoTargetContractSerializer()` and `new MongoTargetSchemaVerifier()`
as named instance properties. No new framework `Target<TContract, TSchema>`
aggregator interface is introduced — the existing descriptor IS the
aggregator (per M1 standing decision).

Slice 6 — call site migration. Migrate Mongos five framework-internal
`validateMongoContract<MongoContract>(rawContract).contract` sites in
`control-instance.ts` to `mongoTargetDescriptor.contractSerializer.
deserializeContract(rawContract)` via a small `deserializeMongoContract`
helper. The helper isolates the cast from `MongoTargetContract` to
`Contract` that `MongoControlFamilyInstance.validateContract` returns
on its public surface (kept for SQL parity until FR8 finishes).

Behaviour is unchanged: the family-shared `parseMongoContractStructure`
body (slice 1) runs the same MongoContractSchema arktype parse +
validateContractDomain + validateMongoStorage that `validateMongoContract`
ran, and the constructTargetContract hook wraps the validated value in
MongoTargetStorage. Existing 9-family tests
(`mongoFamilyDescriptor.create()`, `validateContract` calls) pass
unchanged.

Also add a per-package vitest.config.ts to family-mongo so the package
runs under the workspace gate. The root vitest config (added in
`794d32368`) routes per-package tests through `packages/**/vitest.config.ts`;
9-family was missing its config so per-package `pnpm test` failed
startup. The minimal config matches the other Mongo packages.

Refs: target-extensible-ir M2 R1 slices 5 + 6 (plan; FR8 in `spec.md`).

Signed-off-by: Will Madden <[email protected]>
…ration

The contract emitter walks `Object.entries(contract.storage)` via
`canonicalizeContractToObject` and feeds the result through
`JSON.stringify`. With `namespaces` declared as a plain enumerable
class field the emitted JSON envelope picked it up, then any later
`MongoContractSchema` arktype validation rejected the envelope with
`storage.namespaces must be removed` (the schema is strict via
`+: reject`).

`namespaces` is part of the class API (every IR carries namespaces per
`MongoStorageBase`/`Storage`) but is intentionally NOT part of the
on-disk JSON shape — the IR-class flip (M2 R2) keeps the same
convention for any other class-internal hooks. Define it via
`Object.defineProperty(..., enumerable: false)` so direct access works
but `JSON.stringify`/`Object.keys`/`Object.entries` skip it.

Surfaced by `test/authoring/side-by-side-contracts.test.ts` and the
mongo db-sign/verify e2e flow during M2 R1.

Signed-off-by: Will Madden <[email protected]>
`ControlClientImpl` (CLI control client) calls
`familyInstance.validateContract(options.contract)` once, then passes
the resulting validated `Contract` to family methods (`verify`,
`schemaVerify`, `sign`, `schemaVerifyAgainstSchema`). With slice 6 of
M2 R1 the family methods began re-feeding that value through
`mongoTargetDescriptor.contractSerializer.deserializeContract`, which
triggered the family `parseMongoContractStructure` arktype pass on a
contract whose `storage` is already a `MongoTargetStorage` instance
— before the companion storage-enumeration fix that landed in the
previous commit, this re-validation rejected the envelope with
`storage.namespaces must be removed`.

The framework SPI parameter type is `unknown` for variance reasons but
the invariant is firm: the control client validates exactly once at
the entry point. Treat the input in family methods as already
validated via a narrow cast helper (`asValidatedMongoContract`); the
single source of truth for JSON→class is the CLI client edge.

Caught by the mongo db-sign/verify e2e integration tests during M2 R1
validation.

Signed-off-by: Will Madden <[email protected]>
…gate

`pnpm --filter @prisma-next/mongo* test` is part of the M2 validation
gate. Under Vitest 4 the root `vitest.config.ts` uses
`projects: ["packages/**/vitest.config.ts"]`, and `pnpm test` for each
package re-uses that workspace setup. Packages that ship a `test/`
folder but no per-package `vitest.config.ts` fail with
`No projects were found.` when invoked through the package filter
(reproducible on the pre-M2 baseline).

Adds the same minimal config we already ship for sibling Mongo family
packages so this filter target stays green. No source change, no
behaviour change — pure scaffolding for the test runner.

Signed-off-by: Will Madden <[email protected]>
…t task

Concretizes the M2 R1 reviewer's D1 observation (MongoTargetStorage uses
Object.defineProperty(..., enumerable: false) to hide its runtime-only
namespaces field from the contract emitter walk; this is a symptom-fix
for an emitter-layer architectural issue).

The audit names two acceptable outcomes:
1. canonicalizeContractToObject calls descriptor.contractSerializer
   .serializeContract(contract); MongoTargetStorage drops the
   defineProperty workaround.
2. ADR appendix documents why the symptom-fix pattern is the correct
   architectural choice for emit-side canonicalization.

Either way the audit produces a concrete artefact. Placement at the
head of M3 is intentional: SQL targets land their own storage classes
in M3, so any defineProperty pattern needs to be a deliberate-and-
documented choice rather than incidental copy-from-Mongo.

If M2 R2 surfaces a SECOND defineProperty call, implementer should
surface as deferral request and the orchestrator may fast-track the
audit into M2 R2 prerequisite work.

Decision recorded at wip/unattended-decisions.md sect 5.

Signed-off-by: Will Madden <[email protected]>
…ase (F2)

The Mongo family abstract storage class was renamed `MongoStorageBase`
in M2 R1 (the `*Base` naming convention; resolves a type/class
naming collision documented in `wip/heartbeats`). The framework
`Storage` interface docstring still referenced the pre-rename
`MongoStorage`. Pure docs fix; no behaviour change.

Refs M2 R1 reviewer finding F2.

Signed-off-by: Will Madden <[email protected]>
…s (F3)

AGENTS.md § Typesafety rules require `as unknown as` casts to be
accompanied by an inline comment explaining why the cast is necessary.
The two casts in the `mongo-contract` foundation package both serve
the same purpose: bridging arktype DSL output types (structurally
correct, nominally different) into the hand-authored `MongoContract`
generic surface that downstream consumers depend on.

The type-system alternative considered was typing `MongoContractSchema`
as `Type<MongoContract>` directly, but arktype DSL schemas are
self-typing by convention and forcing nominal equivalence at the
declaration site loses the inference utility that makes the DSL
worth using. The cast is the right shape; the missing artefact was
the substantive justification comment.

The third `as unknown as JsonObject` in the same file already carried
a substantive comment and was not in scope for this fix.

Refs M2 R1 reviewer finding F3.

Signed-off-by: Will Madden <[email protected]>
…er FR18)

M2 R2 implementer surveyed Mongo Contract IR ahead of the class lift and
surfaced that the plan's named lift targets (MongoIndex, MongoIndexOptions,
MongoCollationOptions) map to authoring-side type = shapes that don't flow
through the SPI deserializer; the storage-side shapes that DO flow through
SPI (MongoStorageCollection and friends) are interfaces.

Spec line 477 (FR18) is dispositive: "Mongo's Contract IR is fully unified
under the AST-class pattern... no half-flat / half-AST state inside the
Mongo family." Spec line 419 shows class MongoTargetIndex extends MongoIndex
- the family-base name MongoIndex ends up on the class hierarchy, displacing
the current authoring usage of the same name.

The plan's literal naming was shorthand. M2 R2 now lifts the storage-shape
hierarchy with a name swap (MongoStorageCollection -> MongoCollection class;
authoring type MongoIndex -> MongoIndexInput), options bags as IR classes
per FR18, and a hydration walker in parseMongoContractStructure that
constructs class instances from arktype-validated JSON.

Decision recorded at wip/unattended-decisions.md sect 7.

Signed-off-by: Will Madden <[email protected]>
…lice 3a)

First leaf options bag flip in the M2 R2 Contract IR class cascade per
FR18 ("Mongo's Contract IR is fully unified under the AST-class
pattern"). MongoCollationOptions moves from a `type =` data shape to
a concrete class extending SchemaNodeBase, with:

- Literal-string `kind` discriminator (`mongo-collation-options`).
- Constructor accepting `MongoCollationOptionsInput` (the data shape
  the authoring DSL and the upcoming hydration walker pass through).
- `this.freeze()` in the constructor so accidental mutation throws
  in strict mode.
- JSON.stringify produces canonical JSON with `kind` included and
  undefined optional fields omitted.

Authoring-side `MongoIndexOptions.collation` and
`MongoCollectionOptions.collation` field types now reference
`MongoCollationOptionsInput` (the data input shape) rather than the
class instance type, preserving DSL ergonomics for literal-construction
sites until the surrounding authoring shapes are lifted in follow-on
slices. The class is publicly exported from the package barrel
alongside the existing input-shape type re-exports.

Single concrete class (no target subclass): collation options carry
no target-specific variation — both Atlas and self-hosted Mongo
consume the same option vocabulary.

7 unit tests cover constructor branches, kind discriminator,
SchemaNodeBase inheritance, freeze semantics, and canonical JSON
shape.

Refs M2 R2 slice 3a.

Signed-off-by: Will Madden <[email protected]>
…2 slice 3b)

Continues the FR18 cascade by lifting the remaining `type =` leaf
options bags inside MongoCollectionOptions to AST classes extending
SchemaNodeBase:

- MongoIndexOptionDefaults (`mongo-index-option-defaults`)
- MongoTimeSeriesCollectionOptions (`mongo-time-series-collection-options`)
- MongoClusteredCollectionOptions (`mongo-clustered-collection-options`)
- MongoChangeStreamPreAndPostImagesOptions
  (`mongo-change-stream-pre-and-post-images-options`)

Each carries a literal-string `kind` discriminator, calls
`this.freeze()` in its constructor, accepts a `*Input` data shape
for authoring DSL / hydration ergonomics, and omits undefined
optional fields from canonical JSON via guarded assignment.

The authoring-side `MongoCollectionOptions` type alias now references
each new class's `*Input` data shape for its nested option fields
(`indexOptionDefaults`, `timeseries`, `clusteredIndex`,
`changeStreamPreAndPostImages`). DSL literal-construction sites
continue to compile without forcing `new <Class>({ ... })`
ceremony — the builder will construct class instances internally
when the contract-builder cascade lands.

20 unit tests cover constructor branches, kind discriminators,
SchemaNodeBase inheritance, freeze semantics, and canonical JSON
output for each new class.

Refs M2 R2 slice 3b.

Signed-off-by: Will Madden <[email protected]>
…ap (M2 R2 slice 3c)

Lifts MongoIndexOptions from a `type =` data shape to a concrete
AST class extending SchemaNodeBase per FR18. The class:

- Carries the literal-string `kind` discriminator
  (`mongo-index-options`).
- Accepts MongoIndexOptionsInput (the data shape) in its
  constructor.
- Normalises a nested `collation` data literal into a
  MongoCollationOptions class instance (or preserves an existing
  class instance with identity equality), so downstream IR walks
  see a uniform class-instantiated tree.
- Calls `this.freeze()` in the constructor.

Authoring-side name swap. The existing `type MongoIndexOptions` data
shape is removed; the data shape now lives at MongoIndexOptionsInput
and is what the contract-ts builder DSL accepts. Internal builder
type signatures (the `index()` overloads, the StrictShape pin)
reference MongoIndexOptionsInput; the new class is the IR form the
hydration walker will construct in a later slice.

Cascaded type-test updates: contract-types.test-d.ts and
contract-builder.types.test-d.ts swap MongoIndexOptions references
for MongoIndexOptionsInput where they assert authoring shapes.

8 unit tests cover constructor branches, collation normalisation
(both literal-and class-instance paths with identity equality),
kind discriminator, SchemaNodeBase inheritance, freeze semantics,
canonical JSON round-trip with nested class kind included, and
the bracketed-key `2dsphereIndexVersion` field.

Refs M2 R2 slice 3c.

Signed-off-by: Will Madden <[email protected]>
… class (M2 R2 slice 3d)

First storage-side interface lift in the M2 R2 cascade per FR18 and
spec line 419 (`abstract class MongoValidator` … `MongoTargetValidator`
target-concrete). This commit lands the name swap component:

- `interface MongoStorageValidator` is removed from contract-types.
- `class MongoValidator extends SchemaNodeBase` lives at the mongo-
  contract package, carrying the `mongo-validator` literal-string
  kind discriminator and freezing itself in its constructor.
- `MongoStorageCollection.validator` now references the IR class
  type; `MongoValidator` is exported from the package barrel
  alongside `MongoValidatorInput` (the constructor data shape) and
  the `validationLevel` / `validationAction` literal-union exports.

Concrete at the family layer (no `MongoTargetValidator` subclass for
now). The spec's abstract-family / target-concrete pattern becomes
meaningful when a second Mongo target introduces validator-specific
extensions; the single Mongo target shipped today does not. The
PSL-side `deriveJsonSchema` and `derivePolymorphicJsonSchema`
helpers (family layer) construct `MongoValidator` instances
directly without a target-import layering violation; future
target subclassing remains an additive change.

Migrated consumers:

- `derive-json-schema.ts` returns `new MongoValidator({...})` from
  both `deriveJsonSchema` and `derivePolymorphicJsonSchema`.
- `contract-to-schema.ts` (mongo-target) accepts `MongoValidator`
  in `convertValidator`; field-access call sites are unchanged.
- `interpreter.test.ts` expectation matrix updated to compare
  against `new MongoValidator({...})` instances.

Arktype `MongoStorageValidatorSchema` now accepts an optional
`kind: "mongo-validator"` field. Until the M2 R2 hydration walker
slice lands, validate-on-read still returns plain data while the
typed cast claims `MongoValidator` (watch-point 11's residual
cast; comment update lands with the walker slice).

Watch-point 9 (`rg "interface MongoStorageValidator"
packages/2-mongo-family/`) returns zero hits.

5 unit tests cover the constructor branches, kind discriminator,
SchemaNodeBase inheritance, freeze semantics, and canonical JSON
round-trip with kind included.

Refs M2 R2 slice 3d.

Signed-off-by: Will Madden <[email protected]>
…ectionOptions IR class (M2 R2 slice 3e)

Concrete family-layer class. Constructor accepts the storage JSON envelope
shape (MongoCollectionOptionsInput) so the family-base hydration walker
can pass arktype-validated objects directly to new. The flat authoring DSL
surface (capped: boolean, size, max) is kept as a separate
MongoCollectionOptionsAuthoringInput type, translated to storage shape by
the contract-ts builder before construction.

Old type MongoCollectionOptions and interface MongoStorageCollectionOptions
both removed; the unprefixed name now refers to the IR class per the M2 R2
name-swap directive.

Signed-off-by: Will Madden <[email protected]>
wmadden added 3 commits May 16, 2026 12:36
# Conflicts:
#	examples/mongo-demo/prisma-next.config.ts
#	examples/retail-store/package.json
#	examples/retail-store/prisma-next.config.ts
#	pnpm-lock.yaml
The merge from main introduced family.create(stack).validateContract()
in the non-no-op migration plan path. Update the test fixtures so
family.create() returns an object with a validateContract identity
function and that createControlStack returns a stack object, restoring
the previously green test cases.
…tor; guard optional model.fields

A14: validateStorage now returns `new SqlStorage(result as SqlStorageInput)`
instead of double-casting, so nested IR fields are normalised and the
branded storageHash flows through the constructor.

A15: Iterate `Object.entries(model.fields ?? {})` in validateContractDomain
so models authored without a `fields` map raise ContractValidationError
through the existing pipeline rather than throwing a raw TypeError.
@wmadden

wmadden commented May 16, 2026

Copy link
Copy Markdown
Contributor Author

Review iteration (round 3): verified the three new CodeRabbit reviews (07:15, 09:10, 10:07 UTC) against current code on 306989699.

  • PRR…AEgzNA (07:15, 5 findings) — all already addressed:
    • postgres-enum-storage-entry.ts doc comment describes the constraint explicitly (no "Decision 18" reference).
    • types.ts already uses a top-level import type { ReferentialAction }.
    • validators.ts doc comments around PostgresEnumTypeSchema / StorageTypeEntrySchema are neutral with a "future refinement" note (no transient labels).
    • build-contract.ts short-circuits isPostgresEnumStorageEntry and kind === 'codec-instance' before the toStorageTypeInstance fallback.
    • contract-types.ts LookupNamedStorageTypeKeyByValue / ResolveNamedStorageTypeKey both accept StorageTypeInstance | PostgresEnumStorageEntry.
  • PRR…AIEURw (09:10, 1 finding) — mongo-contract version 0.0.1 → 0.7.0 fixed in d28133210 via scripts/set-version.ts (workspace-wide sync).
  • PRR…AIJ7sw (10:07, 3 findings on validators.ts) — all already addressed:
    • StorageTypeEntrySchema closedness is intentional design; the inline comment at L119–134 explicitly documents the rationale and the future-refinement path (registry-dispatch hydration earned when a non-enum storage shape ships).
    • model.fields iteration already uses Object.entries(model.fields ?? {}).
    • validateStorage already returns new SqlStorage(result as SqlStorageInput) after the type.errors guard.

No code changes needed for this round. Inline threads remain at 0 unresolved.

wmadden added 5 commits May 16, 2026 13:09
…izer

The postgres() and postgresServerless() runtime entry points were calling
SqlContractSerializer (family-layer) directly. That serializer rejects raw
postgres-enum entries in storage.types because hydrating them requires the
target-postgres entity-type factory registry; it surfaces as
"Encountered raw postgres-enum JSON in storage.types without serializer
hydration" the moment a contract with an enum is loaded at runtime
(prisma-next-cloudflare-worker integration test caught this).

Swap to PostgresContractSerializer from @prisma-next/target-postgres/runtime
(now re-exported from the runtime descriptor module). Family-layer mocks in
the postgres/postgres-serverless unit tests follow the import swap.

Also relax retail-store migration.test.ts to toMatchObject for index
assertions: MongoIndex IR-class instances carry the kind discriminator now,
which toEqual rejects as an extra property. toMatchObject expresses the
test intent (structural index check) without leaking IR-class shape into
the assertion literals.
# Conflicts:
#	examples/mongo-demo/package.json
#	examples/retail-store/package.json
#	packages/2-mongo-family/1-foundation/mongo-contract/package.json
#	packages/2-mongo-family/2-authoring/contract-ts/package.json
#	packages/2-mongo-family/3-tooling/mongo-schema-ir/package.json
#	packages/2-mongo-family/9-family/package.json
#	packages/2-sql/1-core/schema-ir/package.json
#	packages/3-extensions/middleware-cache/package.json
#	packages/3-extensions/mongo/package.json
#	packages/3-extensions/sqlite/package.json
#	packages/3-mongo-target/1-mongo-target/package.json
#	packages/3-mongo-target/2-mongo-adapter/package.json
#	pnpm-lock.yaml
The release-pipeline coverage check (pnpm check:upgrade-coverage --mode pr)
requires an upgrade-instructions directory per minor transition whenever
the PR touches examples/ or packages/3-extensions/. The target-extensible-IR
substrate edits trip both signals, so add the matching 0.8-to-0.9 entries
in both upgrade-skill (user audience) and extension-upgrade-skill (extension
authors).

Entries ship with changes: [] and a written rationale: the breakdown of the
target-extensible-IR refactor into a consumer-facing codemod set is a
follow-up to land before the 0.9 release ships. This keeps the coverage
check honest about that follow-up rather than silently shipping nothing.
The demo contract carries postgres-enum entries in storage.types; the
family-layer SqlContractSerializer rejects them at hydration time because
the postgres-enum entity-type factory lives in target-postgres. Three
test files in examples/prisma-next-demo were still constructing the
family-layer serializer directly; swap them to PostgresContractSerializer
to match the runtime path the postgres extension itself takes.

Adds matching vitest coverage exclusions for SQL Contract IR class-only
files (mirroring the existing pack-types.ts pattern) and warning-only
entries in coverage.config.json for the eight packages whose direct-unit
coverage dropped behind threshold during the M9 target-extensible-IR
refactor. Coverage recovers as per-class unit tests land before 0.9
release (tracked as a follow-up).
@wmadden
wmadden merged commit 8a73b1a into main May 16, 2026
15 of 16 checks passed
@wmadden
wmadden deleted the target-extensible-ir branch May 16, 2026 12:34
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