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

TML-2778: control policy — set control/defaultControl from the TS contract builder - #692

Merged
wmadden merged 8 commits into
mainfrom
tml-2778-control-policy-slice-4-ts-authoring
Jun 2, 2026
Merged

wmadden merged 8 commits into
mainfrom
tml-2778-control-policy-slice-4-ts-authoring

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

At a glance

Control policy is a per-object setting that says how much the framework's migration and verification machinery is allowed to touch a given database object — on a spectrum from managed (the framework fully owns it: create, alter, drop) to external (the framework knows about it but must never emit DDL for it — think Supabase's auth.users). The policy lives on the contract IR already, and the verifier and planner react to it (sibling PRs #694 and #693). This PR is the authoring surface — how a person actually sets the policy from the TypeScript contract builder:

const contract = defineContract({
  defaultControl: 'external',          // every object defaults to "don't touch" …
  models: {
    User:    model('User',    { /* … */ }).sql({ table: 'app_user',     control: 'managed' }), // …except this one
    Profile: model('Profile', { /* … */ }).sql({ table: 'user_profile' }),                     // inherits 'external'
  },
});

That is the entire surface: one contract-level defaultControl, one per-table control override. After this PR, effectiveControl(node.control, contract.defaultControl) (the resolver from slice 1) returns managed for app_user and external for user_profile — exactly the value the verifier and planner branch on.

The decision

Set the policy in two places, both of which lower straight to the IR with no authoring-time logic: a contract-level defaultControl on defineContract({…}) (the 80% path — an extension author sets it once for their whole space) and a per-table control on .sql({…}) (the override). Critically, authoring does not validate combinations — a managed table inside a defaultControl: 'external' contract is accepted here, not rejected. The planner's safety floor (#693) is the audit trail for that case. Rejecting it here would duplicate that rule in a second place and force authors to learn it twice; we keep one source of truth.

How it works

defaultControl is a new optional field on the defineContract input and lowers verbatim to Contract.defaultControl. The per-table control rides on the existing .sql({…}) stage spec — co-located with the other table-level storage metadata like table: — and lowers to StorageTable.control. Both are typed to the four ControlPolicy literals, so an invalid value ('mananged') is a compile error; a negative type test pins that.

Because slice 1 omits control from the serialized form whenever it equals the effective default, the tests assert effective control through the resolver rather than raw field presence, and confirm the omit-when-default property survives a canonical round-trip (validateSqlContractFully). That is what keeps existing managed contracts hashing identically — no fixture churn from this change.

Scope

In: SQL TS defaultControl + per-table control, type-checked, lowering-only; an integration test mixing a contract default with per-table overrides and round-tripping through the canonical SQL deserializer.

Out (deliberately): PSL authoring (slice 5, TML-2779 — the spelling is still an open question); per-column override (project non-goal); enum / Mongo TS authoring; any verifier or planner behaviour (#694, #693).

Testing: pnpm typecheck + pnpm test (269) in @prisma-next/sql-contract-ts, pnpm lint:deps — all green. Independent review returned SATISFIED.

Alternatives considered

  • Reject managed-in-external at authoring time. Rejected: the planner already enforces this floor at plan time (a per-object override cannot escalate above a namespace's external floor), so an authoring-time rejection would be a second copy of the same rule, in a layer that otherwise carries no policy logic.
  • A dedicated .control(...) builder method instead of a .sql({ control }) key. Rejected: control is table-level storage metadata, like table: and the target schema, so it belongs in the existing stage spec rather than introducing a new chained method.
  • Round-trip through the full PostgresContractSerializer. Not available at this layer: that serializer lives in 3-targets and importing it into a 2-authoring package would break layering. The test uses validateSqlContractFully — the canonical SQL deserialize path that SqlContractSerializerBase.deserializeContract itself calls — which is the canonical path reachable here.

@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 2, 2026 12:39
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR extends the SQL contract authoring and building pipeline to accept and propagate optional ControlPolicy metadata. Contract definitions now accept defaultControl, SQL stages accept per-model control, and this metadata is threaded through type definitions, contract lowering, and final contract assembly into storage table inputs.

Changes

ControlPolicy Integration

Layer / File(s) Summary
Type contract and DSL extensions
contract-definition.ts, contract-dsl.ts, contract-builder.ts
ControlPolicy is imported and integrated into public types: ModelNode.control, ContractDefinition.defaultControl, SqlStageSpec.control, ContractInput.defaultControl, and the exported defineContract surface now accept these optional fields.
Control propagation through lowering and assembly
contract-lowering.ts, build-contract.ts
RuntimeModelSpec collects control from SQL stage specs; resolveModelNode and buildContractDefinition conditionally propagate control into final ModelNode and ContractDefinition objects; buildSqlContractFromDefinition applies control to each StorageTableInput and the assembled Contract object.
Control policy test coverage
test/contract-builder.control-policy.test.ts, test/contract-builder.dsl.types.test.ts
Tests validate defaultControl retention/omission, per-table control resolution across all policy values, mixed default-plus-per-table scenarios with canonical round-trip validation, and compile-time type rejection of invalid control values.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • prisma/prisma-next#691: Introduces ControlPolicy and effectiveControl IR primitives that this PR now integrates throughout the SQL contract authoring layer, populating control metadata on storage table inputs and contract definitions.

Poem

A rabbit hops through schemas fine,
Control policies aligned,
Metadata threads through every node,
From DSL to contract code,
Tests ensure the journey's true! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly references the main objective of the PR: adding control policy support (defaultControl and per-table control) to the TypeScript contract builder, which aligns with the comprehensive changes across multiple files implementing this feature.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2778-control-policy-slice-4-ts-authoring

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@pkg-pr-new

pkg-pr-new Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

npm i https://pkg.pr.new/@prisma-next/extension-author-tools@692

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/@prisma-next/extension-arktype-json@692

@prisma-next/middleware-cache

npm i https://pkg.pr.new/@prisma-next/middleware-cache@692

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

npm i https://pkg.pr.new/@prisma-next/extension-postgis@692

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

npm i https://pkg.pr.new/@prisma-next/ts-render@692

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/@prisma-next/mongo-query-builder@692

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 65720eb

@github-actions

github-actions Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 136.51 KB (+0.04% 🔺)
postgres / emit 108.81 KB (0%)
mongo / no-emit 75.77 KB (0%)
mongo / emit 70.78 KB (0%)
cf-worker / no-emit 165.4 KB (+0.03% 🔺)
cf-worker / emit 134.51 KB (0%)

@wmadden-electric wmadden-electric changed the title TML-2778: control policy — TS authoring surface (defaultControl + per-table control) TML-2778: control policy — set control/defaultControl from the TS contract builder Jun 2, 2026
@wmadden
wmadden force-pushed the tml-2778-control-policy-slice-4-ts-authoring branch from 536a1ac to 75a6eb9 Compare June 2, 2026 14:26
wmadden-electric pushed a commit that referenced this pull request Jun 2, 2026
Read per-table control through sqlSpec in lowering (drop redundant
RuntimeModelSpec field). Pin compile-time rejection of invalid per-table
control literals and assert managed override is written on the table.

Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric force-pushed the tml-2778-control-policy-slice-4-ts-authoring branch from 75a6eb9 to b9bcbea Compare June 2, 2026 14:51
wmadden added a commit that referenced this pull request Jun 2, 2026
Read per-table control through sqlSpec in lowering (drop redundant
RuntimeModelSpec field). Pin compile-time rejection of invalid per-table
control literals and assert managed override is written on the table.

Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden force-pushed the tml-2778-control-policy-slice-4-ts-authoring branch from b9bcbea to 439b356 Compare June 2, 2026 15:37
@wmadden
wmadden enabled auto-merge (rebase) June 2, 2026 15:37
wmadden added 8 commits June 2, 2026 18:14
Thread optional contract-level defaultControl through the SQL TS
builder into Contract.defaultControl so extension authors can declare
the default control policy once.

Signed-off-by: Will Madden <[email protected]>
Thread optional control on the model sql stage into StorageTable.control
and add tests that assert effective control via effectiveControl, including
a mixed default plus per-table override contract that round-trips.

Signed-off-by: Will Madden <[email protected]>
Address review nits: drop the loose expectTypeOf from the describe body
(the type-level rejection assertion already lives in an it in the
type-test file), add an explicit no-control/no-defaultControl omission
test to pin the no-hash-churn guarantee at the authoring layer, and
round-trip the mixed-control contract through validateSqlContractFully
(the canonical SQL deserializer) instead of a bare JSON reshape.

Signed-off-by: Will Madden <[email protected]>
Read per-table control through sqlSpec in lowering (drop redundant
RuntimeModelSpec field). Pin compile-time rejection of invalid per-table
control literals and assert managed override is written on the table.

Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric force-pushed the tml-2778-control-policy-slice-4-ts-authoring branch from 439b356 to 65720eb Compare June 2, 2026 16:20
@wmadden
wmadden merged commit 1406432 into main Jun 2, 2026
20 checks passed
wmadden added a commit that referenced this pull request Jun 2, 2026
Read per-table control through sqlSpec in lowering (drop redundant
RuntimeModelSpec field). Pin compile-time rejection of invalid per-table
control literals and assert managed override is written on the table.

Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden deleted the tml-2778-control-policy-slice-4-ts-authoring branch June 2, 2026 16:31
medz pushed a commit to medz/prisma-next that referenced this pull request Jun 5, 2026
…ect's control policy (prisma#694)

## At a glance

**Control policy** is a per-object setting that says *how much the
framework manages a given database object* — from `managed` (fully
owned) to `external` (known about but never touched — think Supabase's
`auth.users`). The policy lives on the contract IR already (slice 1).
**This PR teaches the schema verifier to react to it**, instead of
demanding every object match the contract exactly.

The motivating case: an app declares a foreign key into Supabase's
`auth.users` and marks that table `external`. The verifier should
confirm the columns the app *declared* are present and shape-compatible
— but ignore the dozens of columns Supabase adds that the app never
mentioned. Today the verifier treats every object as `managed`, so any
such divergence is an error. After this PR it branches on
`effectiveControl(node.control, contract.defaultControl)` and maps the
**existing** issue kinds onto pass / warn / fail / suppressed — no new
issue kinds, no result-shape change:

| Live-vs-declared | `managed` | `tolerated` | `external` | `observed` |
|---|---|---|---|---|
| Declared column missing | fail | fail | fail | warn |
| Declared column type-incompatible | fail (exact) | fail (exact) | fail
(compatible-shape) | warn |
| Extra column | fail | suppress | suppress | warn |
| Extra constraint / index | fail | fail | suppress | warn |
| Enum value drift | fail | fail | suppress | warn |
| Object absent entirely | fail | fail | fail | warn |

## The decision

**Strict by default.** A non-`managed` policy does *not* soften checks
on the columns you actually declared — `tolerated` and `external` still
**fail** on a declared column that's missing or type-incompatible; they
only relax what they say about *undeclared* extras. Only `observed`
downgrades everything to `warn`.

The reasoning is one-directional and the deciding factor: **loosening a
check later (fail → warn) is a non-breaking change, but tightening one
(warn → fail) turns previously-green builds red.** Starting strict keeps
the cheaper evolution path open. Two supporting decisions follow the
same instinct:

- **Conservative compatible-shape for `external`:** Postgres's
`columnsCompatible` is identical-or-explicitly-listed, and the list is
empty in v0.1 — so `varchar` vs `text` is still a `fail` today. Widening
the compatible set later is additive and safe.
- **`external` requires existence:** an `external` object (or enum) that
is absent entirely is a `fail` — declaring an external dependency that
isn't there is a real error, not a tolerable divergence.

## How it works

The severity mapping is one small pure pair — `verifierDisposition` /
`classifyVerifierIssueKind` — placed in the framework-agnostic
`@prisma-next/contract` foundation package so both the SQL and Mongo
families consume the *same* table with no upward import (mirroring the
`effectiveControl` precedent from slice 1). Each family base calls it
through thin `pushControlled*` emit helpers.

The compatible-shape relation is a **target-supplied hook**: abstract on
the family base, concrete `postgresColumnsCompatible` on Postgres,
threaded through both the migration-verify and runtime-verify paths so
they agree. Enum (`PostgresEnumStorageEntry`) verification dispatches
through the same table — the proof that target-contributed node kinds
flow through one dispatch rather than a parallel hardcoded path.

## Scope

**In:** four-way severity/suppression dispatch on the SQL + Mongo family
verifier bases; the target-supplied compatible-shape hook + the
conservative Postgres relation; enum dispatch; per-policy tests for both
families.

**Out (unchanged):** planner DDL gating (prisma#693), TS/PSL authoring (prisma#692 /
slice 5), and widening the compatible-pair list.

**Testing:** `pnpm typecheck` (contract, family-sql, target-postgres,
adapter-postgres); package tests (contract 159, family-sql 309,
target-postgres 331, adapter-postgres 537 + 4 expected-fail) with real
status assertions per policy for SQL, Mongo, and enums; `pnpm lint:deps`
clean, `pnpm lint:casts` delta 0.

## Alternatives considered

- **Loosen by default** (let `tolerated`/`external` soften checks on
declared columns too). Rejected on the one-directional argument above:
we can always relax later without breaking anyone; we cannot tighten
without breaking green builds.
- **Introduce new `SchemaIssue` kinds for tolerated/external
divergence.** Rejected: reusing the existing kinds plus a disposition
keeps the result shape stable and avoids forcing every issue consumer to
learn a new vocabulary.
- **Aggressive compatible-shape** (treat `varchar`/`text`,
`int4`/`int8`, etc. as compatible out of the gate). Deferred: starting
from exact-equality and widening additively is safe; starting wide and
narrowing is not.

**Acknowledged transitional shapes (not blocking):**
`PostgresSchemaVerifier.verifyCommonSqlSchema` is still an empty
SPI-migration stub, so the class-based `columnsCompatible` is reached
via the `verifySqlSchema` function option rather than the abstract
method — two seams for one concept, to consolidate when the SPI
migration lands. Whole extra tables/collections still `fail` under
`tolerated`/`external` (the severity table is column/constraint-grained)
— defensible under strict-by-default.

---------

Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Will Madden <[email protected]>
medz pushed a commit to medz/prisma-next that referenced this pull request Jun 5, 2026
…l policy (prisma#693)

## At a glance

**Control policy** is a per-object setting that says *how much the
framework's migration machinery is allowed to touch a given database
object* — from `managed` (fully owned: create, alter, drop) to
`external` (known about but never emitted — think Supabase's
`auth.users`). The policy lives on the contract IR already (slice 1).
**This PR teaches the migration planner to obey it.** Before, the
planner treated every object as fully owned and emitted whatever DDL the
diff implied. Now it consults `effectiveControl(node.control,
contract.defaultControl)` for each object first:

| Policy | DDL the planner will emit |
|---|---|
| `managed` | full lifecycle — `CREATE` / `ALTER` / `DROP` *(unchanged
from today)* |
| `tolerated` | `CREATE` if missing — never `ALTER` / `DROP` |
| `external` | none |
| `observed` | none |

So a table marked `external` produces **no** migration DDL, even when
the live database differs from the contract — which is exactly what you
want for a table some other system owns.

## The decision

On top of the per-object gate sits an **un-overridable safety floor**:
when a contract space's `defaultControl` is `external`, the planner
emits **zero** DDL into that space's namespaces *even if* an object
inside carries a per-object `control: 'managed'`. A per-object override
**cannot escalate above** the namespace floor. When the floor suppresses
DDL that a `managed` declaration would otherwise have produced, the
planner emits a **`warn`-level** diagnostic
(`control_managed_in_external_space`) naming the object and namespace —
and lets the plan proceed.

We chose **`warn`, not `fail`**: the safe thing has already happened
(nothing leaked into the external schema), so halting the entire plan
would be heavier than a single mis-declaration warrants. And we made the
floor **un-overridable** on purpose — an `external` space is precisely
where a stray `managed` object must not be able to punch a hole.

## How it works

The per-node gate is a pure function of effective control, placed on the
SQL family seam so any SQL target inherits it; Postgres supplies the
concrete planner wiring. The external-namespace floor is computed per
namespace from the space's `defaultControl`, independent of the
per-object values beneath it. The `warn` diagnostic is attached to the
concrete `PostgresPlanResult`. Unit tests cover all four policy gates
plus the mis-declaration (managed-in-external) case with real
assertions.

## Scope

**In:** per-node DDL gate (SQL family seam + Postgres planner), the
external-namespace floor, the `warn`-level conflict diagnostic, and unit
tests for all four policies + the mis-declaration case.

**Out (unchanged):** verifier comparison strategies (prisma#694), TS/PSL
authoring (prisma#692 / slice 5), the Mongo planner, and introspection
defaulting.

**Known follow-up (out of scope, tracked):** the `warn` diagnostic is
produced on `PostgresPlanResult`, but the framework
`MigrationPlannerResult` success variant has no `warnings` field yet, so
nothing surfaces it to a user end-to-end. Wiring it through the
framework result type + CLI is tracked in **TML-2792**.

**Testing:** `pnpm typecheck` (`family-sql`, `target-postgres`), package
tests (family-sql 309/309, target-postgres 339/339), `pnpm lint:casts`
delta 0, `pnpm lint:deps` — all green.

## Alternatives considered

- **`fail` instead of `warn` for managed-in-external.** Rejected: the
unsafe outcome was already prevented, so a hard failure over-penalises a
recoverable mis-declaration.
- **Make the floor overridable by a per-object `managed`.** Rejected:
that defeats the purpose of marking a whole space `external` — the floor
exists so a single mis-declared object can't escalate the space back
into "framework emits DDL here."
- **Gate with bare `as` casts** (the first implementation). Replaced: an
independent review flagged 5 net-new bare casts tripping the
`lint:casts` ratchet; they were eliminated by narrowing (typed accessors
/ discriminated-union narrowing), leaving the ratchet delta at 0 with no
`blindCast`.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

## Release Notes

* **New Features**
* Control policy filtering now integrated into migration planning to
respect table and schema management modes (managed, tolerated, external,
observed).
  * Added public APIs for control policy filtering and resolution.
  * New helper utilities for safe table lookups in storage.

* **Tests**
* Added comprehensive test coverage for control policy filtering across
all management modes.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Will Madden <[email protected]>
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.

2 participants