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

TML-2931: a generic tree-walking schema differ — RLS now plans in migration plan - #868

Merged
wmadden merged 27 commits into
mainfrom
slice/entity-kind-migration-seam
Jun 28, 2026
Merged

wmadden merged 27 commits into
mainfrom
slice/entity-kind-migration-seam

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

At a glance

A SELECT policy authored in PSL:

namespace public {
  model Profile {
    id       String @id @default(uuid())
    owner_id String
    @@map("profile")
  }

  policy_select profile_owner_read {
    target = Profile
    roles  = [authenticated]
    using  = "owner_id::uuid = auth.uid()"
  }
}

prisma-next migration plan used to refuse to plan it offline:

✗ migration plan does not yet emit RLS policies — author RLS via 'db update' / 'db init' against a live database.

Now it plans the policy with no database in reach:

ALTER TABLE profile ENABLE ROW LEVEL SECURITY;
CREATE POLICY "profile_owner_read_dc40c58a" ON profile
  AS PERMISSIVE FOR SELECT TO authenticated
  USING (owner_id::uuid = auth.uid());

The decision

A schema diff is computed between two derived schema IRs, walked as a tree. Each side is produced by a derivation — read from a contract, or introspected from a live database — and a generic differ walks the two trees, pairing nodes by coordinate and comparing them, while naming no node type of its own. Because both sides are the same derived shape, one comparison serves every command, and a target-contributed entity kind (here, a Postgres RLS policy) participates in all of them.

Design detail: adr-schema-diff-over-structured-ir.md.

Why migration plan was broken

The differ was being fed asymmetrically. On the live-database commands (db init / db update / db verify) one side was a real introspected PostgresSchemaIR while the diff reached into the contract object for the other. But migration plan has no database: it derives both sides from contracts, and that derivation dropped target-specific objects entirely — so policies were absent on both sides, and the planner failed loud rather than emit a migration that silently contained no RLS.

This change removes the asymmetry: a Postgres contract now projects to a populated PostgresSchemaIR, so both sides are homogeneous derived IRs on every command.

What changed

  • A generic tree-walking differ (schema-diff.ts). diffSchema(expected, actual) walks two roots; each node answers coord() / isEqualTo() / children(). It recurses into matched pairs, so the diff keeps the IR's structure — the planner orders operations by how nodes relate (a role before the policy that names it, a table before its policies). The flat diffNodes is gone; the node method identity() is renamed coord(). RLS is one level deep today, so its diff output is unchanged.
  • project-from-contract (projectPostgresSchemaFromContract). The Postgres contractToSchema hook returns a populated PostgresSchemaIR instead of a bare relational one.
  • A provenance-agnostic planner. The migration plan fail-loud and the planner's isPostgresSchemaIR command-branches are deleted — nothing downstream asks which command produced a side.
  • Ownership as a post-diff step. The differ walks the full introspected tree; a policy in a namespace this contract doesn't own (another space's public.*) is left alone by filtering the diff's extra outcomes, not by pre-filtering the tree.

Scope

Deliberately deferred, each with its consequence:

  • Roles are projected into the IR but not yet diffed — missing-role detection and the policy→role dependency edge are the next slice.
  • No derivation registry. Each target writes its two derivations directly; a generic registration surface is owed only once a second contributed kind makes its shape concrete.
  • The relational kinds stay on the existing per-kind verifier — they aren't placed in the walked tree, so there is no double-diff.

Verification

  • build, typecheck, the package suite, lint:deps, fixtures:check, and e2e are green.
  • Integration is green on these changes; the lone failure is a known PGlite portal "C_N" does not exist flake that hops between sql-orm-client tests run-to-run and passes in isolation.
  • Independent review confirmed all nine acceptance criteria — including a genuine two-level recursion test and the migration plan test asserting the emitted CREATE POLICY / ENABLE ROW LEVEL SECURITY ops.

Slice spec: slices/entity-kind-migration-seam/spec.md.

Alternatives considered

  • Flatten both IRs to a node list, then diff the lists. Simpler while the entities are flat and unrelated, but it discards the structure the planner needs to order operations — every later pass would have to rebuild relationships the diff threw away.
  • Diff a derived IR against the raw contract. The two are different shapes, so the comparison must special-case which side is which, and a command with no database (offline migration plan) has no IR on that side at all. Deriving both sides to one shape makes every command uniform.
  • Build a derivation registry now. A registration surface designed around a single contributed kind on a single target is designed against one example. Deferred until a second consumer grounds its shape.
  • Port the relational kinds onto the differ in this change. Each carries its own non-structural equality and cross-sibling synthesis; the differ already walks a tree of any depth, so which kinds populate it can grow independently.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added a coordinate-aligned schema differ (diffSchemas) and wired it into Postgres RLS drift detection via diffPostgresSchema.
  • Bug Fixes
    • Schema comparison now aligns nodes by stable coordinates, enforces unique sibling coordinate keys, and reports missing/extra/mismatch items at the correct coordinate.
    • “Extra” RLS items are only included when their namespace is owned by the contract.
    • Postgres RLS diff/planning now consistently operates on PostgresSchemaIR, rejecting non-Postgres inputs.

wmadden-electric and others added 4 commits June 24, 2026 18:01
…pec)

Shaping for Slice 1.5 of postgres-rls. Accepts the schema-diff-over-structured-IR
ADR: a schema diff is computed between two derived schema IRs, walked as a tree
(coord()/isEqualTo()/children()); both sides project from contract/database;
ownership is a post-diff disposition, not a pre-filter. Registry deferred
(follow-on C). Plan Slice 1.5 + a prescriptive slice spec (units A-E, exact
signatures, 9 ACs).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…TreeNode is taken)

A CLI schema-view class already owns SchemaTreeNode (~33 call sites, out of
scope). Keep the existing DiffableNode interface name; add coord()/children()
and a new DiffableRoot for the root. Avoids the collision and the SchemaDiffIssue
retype churn.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… provenance-symmetric RLS diff)

Generic differ walks two schema-IR roots (DiffableRoot/DiffableNode with
coord()/isEqualTo()/children()); diffNodes removed. project-from-contract
(projectPostgresSchemaFromContract) makes the postgres contractToSchema yield a
populated PostgresSchemaIR, so migration plan emits CREATE POLICY. The RLS diff
walks the full actual tree and applies owned-namespace suppression to outcomes,
not inputs. Planner fail-loud deleted; planRlsDiff guard throws on a
non-PostgresSchemaIR schema (an invariant post-seam).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…s to PostgresSchemaIR

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 25, 2026 09:12
@coderabbitai

coderabbitai Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR replaces flat schema-node diffing with recursive coordinate-based diffing, updates Postgres schema IR nodes to expose coordinates and children, and rewires Postgres migration planning, exports, and tests to use PostgresSchemaIR and diffPostgresSchema.

Changes

Schema diff and Postgres planner wiring

Layer / File(s) Summary
Recursive schema diff API
packages/1-framework/1-core/framework-components/src/control/schema-diff.ts, packages/1-framework/1-core/framework-components/src/exports/control.ts, packages/1-framework/1-core/framework-components/test/schema-diff.test.ts, packages/1-framework/1-core/framework-components/test/rls-layer-invariant.test.ts
DiffableRoot and DiffableNode now use children() and coord(), diffSchemas recurses through matched children and rejects duplicate sibling coordinates, and the schema-diff tests and barrel export follow the new API.
Postgres diffable nodes
packages/3-targets/3-targets/postgres/src/core/postgres-schema-ir.ts, packages/3-targets/3-targets/postgres/src/core/postgres-role.ts, packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts, packages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.ts
PostgresSchemaIR, PostgresRole, and PostgresRlsPolicy now expose coord() and children(), and the diffable-node tests assert the updated coordinates, leaf behavior, and error text.
Postgres contract projection and schema diff
packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts, packages/3-targets/3-targets/postgres/src/core/migrations/collect-contract-postgres-nodes.ts, packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts, packages/3-targets/3-targets/postgres/src/core/migrations/diff-postgres-schema.ts, packages/3-targets/3-targets/postgres/src/core/migrations/verify-postgres-rls-policies.ts, packages/3-targets/3-targets/postgres/src/exports/*, packages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.ts, packages/3-targets/3-targets/postgres/test/migrations/diff-postgres-schema.test.ts, packages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.ts
contractToPostgresSchemaIR adds roles and RLS policies to PostgresSchemaIR, diffPostgresSchema compares policy trees with diffSchema and filters unowned extras, and the public exports and tests follow the new flow.
Planner and adapter wiring
packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts, packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts, packages/3-targets/6-adapters/postgres/test/migrations/rls-migration-plan.integration.test.ts
The Postgres planner and control adapter route RLS handling through diffPostgresSchema and planPostgresSchemaDiff, and the offline planner test asserts the RLS SQL path.
pgvector and Postgres planner fixtures
packages/3-extensions/pgvector/test/migrations/*, packages/3-targets/6-adapters/postgres/test/migrations/*, test/integration/test/cross-package/postgres-control-policy-planner.test.ts, skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
The planner tests construct PostgresSchemaIR inputs, update helper signatures to the new schema shape, read enum existence from nativeEnumTypeNames, and the upgrade notes record the extension-facing seam for these fixture changes.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • prisma/prisma-next#771: Introduces the earlier diffNodes/identity() differ that this PR replaces with diffSchemas/coord() plus children()/DiffableRoot.

Suggested reviewers

  • wmadden
  • aqrln

Poem

(_/)
I hopped through roots and schema trees,
with coord() crumbs upon the breeze.
children() rustled, policy bright,
and diffed-up carrots gleamed tonight. 🐰

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main change: a generic schema differ enabling offline RLS planning in migration plan.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch slice/entity-kind-migration-seam

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.

@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

npm i https://pkg.pr.new/@prisma-next/extension-supabase@868

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/config-loader

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

@prisma-next/emitter

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

@prisma-next/language-server

npm i https://pkg.pr.new/@prisma-next/language-server@868

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: b111bc3

@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 160.32 KB (+0.83% 🔺)
postgres / emit 147.5 KB (+16.46% 🔺)
mongo / no-emit 78 KB (0%)
mongo / emit 72.09 KB (0%)
cf-worker / no-emit 187.94 KB (+0.81% 🔺)
cf-worker / emit 173.57 KB (+15.3% 🔺)

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/1-framework/1-core/framework-components/src/control/schema-diff.ts (1)

27-29: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Fail loudly on non-unique coordinate keys.

stableKey() is a lossy serialization for a public EntityCoordinate, and both maps silently overwrite on duplicate keys. That means two distinct siblings can collapse into one entry, so diffSchema() can miss missing/extra/mismatch issues and downstream planners will emit an incomplete set of operations.

Suggested fix
 function stableKey(c: EntityCoordinate): string {
-  return `${c.plane}|${c.namespaceId}|${c.entityKind}|${c.entityName}`;
+  return JSON.stringify([c.plane, c.namespaceId, c.entityKind, c.entityName]);
 }
@@
   const expectedMap = new Map<string, DiffableNode>();
   for (const node of expected) {
-    expectedMap.set(stableKey(node.coord()), node);
+    const key = stableKey(node.coord());
+    if (expectedMap.has(key)) {
+      throw new Error(`diffSchema: duplicate expected coordinate ${key}`);
+    }
+    expectedMap.set(key, node);
   }
@@
   const actualMap = new Map<string, DiffableNode>();
   for (const node of actual) {
-    actualMap.set(stableKey(node.coord()), node);
+    const key = stableKey(node.coord());
+    if (actualMap.has(key)) {
+      throw new Error(`diffSchema: duplicate actual coordinate ${key}`);
+    }
+    actualMap.set(key, node);
   }

Also applies to: 57-64

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/1-core/framework-components/src/control/schema-diff.ts`
around lines 27 - 29, The coordinate keying used by stableKey() is lossy and can
silently collapse distinct EntityCoordinate values, causing diffSchema() to miss
differences. Update the coordinate-to-entry handling in stableKey() and the maps
used by diffSchema() to detect duplicate keys and fail loudly instead of
overwriting entries; if a collision is encountered, throw an explicit error that
includes the conflicting coordinates so the issue is visible during schema
diffing.
packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts (1)

63-69: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Include tableName in the policy coordinate.

diffSchema() keys nodes by stableKey(node.coord()). With only namespaceId + entityKind + name here, two tables in the same schema that reuse the same policy name collapse to one map entry, so the planner can miss or mispair a policy operation. Postgres policy identity is table-scoped, so the coordinate needs a table discriminator too.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts` around
lines 63 - 69, The policy coordinate is missing the table discriminator, so
stableKey(node.coord()) can collide for same-named policies on different tables.
Update PostgresRlsPolicy.coord() to include tableName alongside namespaceId,
entityKind, and name so each policy is uniquely keyed per table, and make sure
the table-scoped value is sourced from the policy’s existing table identifier in
the class.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/3-targets/3-targets/postgres/src/exports/control.ts`:
- Around line 70-77: Replace the bare production cast in the contract passed to
projectPostgresSchemaFromContract with the approved casting helper from
`@prisma-next/utils/casts`. Use blindCast with a clear reason string instead of
`as unknown as` in control.ts, keeping the existing control flow and the call to
projectPostgresSchemaFromContract unchanged except for the cast.

---

Outside diff comments:
In `@packages/1-framework/1-core/framework-components/src/control/schema-diff.ts`:
- Around line 27-29: The coordinate keying used by stableKey() is lossy and can
silently collapse distinct EntityCoordinate values, causing diffSchema() to miss
differences. Update the coordinate-to-entry handling in stableKey() and the maps
used by diffSchema() to detect duplicate keys and fail loudly instead of
overwriting entries; if a collision is encountered, throw an explicit error that
includes the conflicting coordinates so the issue is visible during schema
diffing.

In `@packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts`:
- Around line 63-69: The policy coordinate is missing the table discriminator,
so stableKey(node.coord()) can collide for same-named policies on different
tables. Update PostgresRlsPolicy.coord() to include tableName alongside
namespaceId, entityKind, and name so each policy is uniquely keyed per table,
and make sure the table-scoped value is sourced from the policy’s existing table
identifier in the class.
🪄 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: 385f2aeb-705a-41f0-86b5-d5484db155e0

📥 Commits

Reviewing files that changed from the base of the PR and between 78c39f4 and 18ecc16.

⛔ Files ignored due to path filters (3)
  • projects/postgres-rls/plan.md is excluded by !projects/**
  • projects/postgres-rls/slices/entity-kind-migration-seam/spec.md is excluded by !projects/**
  • projects/postgres-rls/specs/adr-schema-diff-over-structured-ir.md is excluded by !projects/**
📒 Files selected for processing (26)
  • packages/1-framework/1-core/framework-components/src/control/schema-diff.ts
  • packages/1-framework/1-core/framework-components/src/exports/control.ts
  • packages/1-framework/1-core/framework-components/test/rls-layer-invariant.test.ts
  • packages/1-framework/1-core/framework-components/test/schema-diff.test.ts
  • packages/3-extensions/pgvector/test/migrations/planner.behavior.test.ts
  • packages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.ts
  • packages/3-extensions/pgvector/test/migrations/planner.storage-types.test.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/project-postgres-schema-from-contract.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/verify-postgres-rls-policies.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-role.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-schema-ir.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/test/migrations/project-postgres-schema-from-contract.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.authoring-surface.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.codec-field-event.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.cross-space-fk-ddl.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.fk-config.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.referential-actions.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.semantic-satisfaction.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-migration-plan.integration.test.ts
  • test/integration/test/cross-package/postgres-control-policy-planner.test.ts

@wmadden-electric wmadden-electric changed the title TML-2931: entity-kind migration seam — schema diff over two derived IRs TML-2931: a generic tree-walking schema differ — RLS now plans in migration plan Jun 25, 2026
wmadden-electric and others added 2 commits June 25, 2026 13:32
…dExtraIssues

The tree-walking differ keys siblings by coordinate. A duplicate key silently
overwrote the first node, dropping a real missing/extra/mismatch issue. Throw on
a duplicate coordinate at both map-build sites so a future non-content-addressed
node kind fails loudly instead of swallowing data. Add unit tests for both sides.

Extract the owned-namespace filter as a generic, target-agnostic
dropUnownedExtraIssues(issues, isOwned) helper next to the framework
SchemaDiffIssue type, so issue-disposition lives in the framework control area
rather than inside a Postgres RLS function.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Rename the contract->IR derivation and the Postgres schema-diff strategy so the
names say what they do, paralleling the family contractToSchemaIR they wrap:

- projectPostgresSchemaFromContract -> contractToPostgresSchemaIR (file too)
- diffPostgresRlsPolicies -> diffPostgresSchema (it is the Postgres schema-diff
  strategy; policies are just the only node kind in it today) (file too)
- planRlsDiff -> planPostgresSchemaDiff

diffPostgresSchema now calls the framework dropUnownedExtraIssues helper; the
Postgres-specific UNBOUND->public namespace resolution stays in the caller,
which builds the ownership predicate. Un-export collectContractRoles (no
cross-module caller). Replace the bare contract narrowing cast in the
contractToSchema hook with blindCast. Drop "post-seam" jargon and the transient
"in this slice" phrasing from comments, stating the plain invariant instead.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts (1)

20-36: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: collapse the two near-identical namespace walks.

collectContractRoles and collectContractRlsPolicies differ only in the projected entry (ns.role vs ns.policy). A small shared traversal helper would remove the copy/paste, but this is a minor cleanup and fine to defer.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts`
around lines 20 - 36, The namespace traversal in collectContractRoles is
duplicated with collectContractRlsPolicies, so factor the shared walk over
contract.storage.namespaces into one helper and parameterize the extracted field
(ns.role versus ns.policy). Keep contractToPostgresSchemaIR using the same
helpers to build roles and rlsPolicies, but remove the copy/paste logic so the
two projections share the same traversal.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts`:
- Around line 20-36: The namespace traversal in collectContractRoles is
duplicated with collectContractRlsPolicies, so factor the shared walk over
contract.storage.namespaces into one helper and parameterize the extracted field
(ns.role versus ns.policy). Keep contractToPostgresSchemaIR using the same
helpers to build roles and rlsPolicies, but remove the copy/paste logic so the
two projections share the same traversal.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: b261265c-9b28-414d-8e55-7c2f4e0b180a

📥 Commits

Reviewing files that changed from the base of the PR and between 18ecc16 and 6903131.

📒 Files selected for processing (16)
  • packages/1-framework/1-core/framework-components/src/control/schema-diff.ts
  • packages/1-framework/1-core/framework-components/src/exports/control.ts
  • packages/1-framework/1-core/framework-components/test/schema-diff.test.ts
  • packages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/diff-postgres-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/src/exports/planner.ts
  • packages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/diff-postgres-schema.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-migration-plan.integration.test.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/3-targets/3-targets/postgres/src/exports/planner.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/1-framework/1-core/framework-components/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-migration-plan.integration.test.ts
  • packages/1-framework/1-core/framework-components/test/schema-diff.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.ts
  • packages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.ts

…gresSchemaIR

- Define PostgresContract in target-postgres (postgres-schema.ts) and export it
  from @prisma-next/target-postgres/types
- Re-export it from the adapter's types.ts instead of redefining it
- Narrow contractToPostgresSchemaIR's contract parameter from Contract<SqlStorage>
  to PostgresContract
- Update the blindCast in control.ts to target PostgresContract | null
- Update makeContract in the test to return PostgresContract so the type flows through

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/3-targets/6-adapters/postgres/src/core/types.ts (1)

34-34: 📐 Maintainability & Code Quality | 🔵 Trivial

Move the PostgresContract re‑export to the package's exports/ surface.

The project guidelines prohibit cross-file re-exports outside of exports/ folders. The file packages/3-targets/6-adapters/postgres/src/core/types.ts is an implementation file, yet it re-exports PostgresContract from @prisma-next/target-postgres/types. This export is then re-exported by packages/3-targets/6-adapters/postgres/src/exports/types.ts.

To comply with the guidelines, remove this re-export from core/types.ts and import/re-export PostgresContract directly within exports/types.ts.

Current structure

src/core/types.ts

export type { PostgresContract } from '`@prisma-next/target-postgres/types`';

src/exports/types.ts

// ... imports from ../core/types
Fix
  1. Remove the line from src/core/types.ts.
  2. Add the following to src/exports/types.ts:
import type { PostgresContract } from '`@prisma-next/target-postgres/types`';
export type { PostgresContract };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-targets/6-adapters/postgres/src/core/types.ts` at line 34, Move
the PostgresContract re-export out of the implementation layer and into the
exports surface: remove the export from core/types.ts, then in exports/types.ts
import type PostgresContract directly from `@prisma-next/target-postgres/types`
and re-export it there alongside the existing exports. Keep the change confined
to the core/types.ts and exports/types.ts symbols so the package only exposes
cross-file re-exports from the exports/ entrypoint.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/3-targets/6-adapters/postgres/src/core/types.ts`:
- Line 34: Move the PostgresContract re-export out of the implementation layer
and into the exports surface: remove the export from core/types.ts, then in
exports/types.ts import type PostgresContract directly from
`@prisma-next/target-postgres/types` and re-export it there alongside the existing
exports. Keep the change confined to the core/types.ts and exports/types.ts
symbols so the package only exposes cross-file re-exports from the exports/
entrypoint.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: c6ddd180-16e4-417a-9c19-b55055ad290f

📥 Commits

Reviewing files that changed from the base of the PR and between 6903131 and 43ca0d8.

📒 Files selected for processing (6)
  • packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/src/exports/types.ts
  • packages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/types.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/3-targets/3-targets/postgres/src/exports/types.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts
  • packages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts

…ration-seam

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 7 commits June 25, 2026 15:46
…ership; document coord() uniqueness

N1: dropUnownedExtraIssues -> filterSchemaIssuesByOwnership, with a doc
stating it filters only extra outcomes (missing/mismatch pass through
regardless of ownership).

N2: diffSchema -> diffSchemas (it compares two roots).

N3: document the coordinate-uniqueness invariant on DiffableNode.coord() -
coord() must be unique among siblings aligned at a level; the differ keys on
it and a collision is the same entity (enforced by the duplicate-key throw).
A kind unique only within a parent (a column within a table) folds its
parent into the coordinate.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…on; trim diff JSDoc

N4: move collectContractRlsPolicies/collectContractRoles out of the
projection file into collect-contract-postgres-nodes.ts, and fix their docs
to say "Collect" (they collect nodes, they do not project). Importers in
contract-to-postgres-schema-ir.ts, diff-postgres-schema.ts, and the test now
import from the new file. collectContractRlsPolicies stays cross-module;
collectContractRoles is only used within the migrations folder.

N5: trim the ~25-line JSDoc on diffPostgresSchema to one line on what it does
plus one line that ownership is applied to outcomes, not inputs.

N6/N7: extract one shared resolveNamespaceId (UNBOUND -> 'public') into
postgres-schema.ts and route diff-postgres-schema.ts through it, dropping the
local copy and POSTGRES_DEFAULT_NAMESPACE_ID. The annotations helper
(resolves to introspected pgSchemaName, not the literal 'public') and
resolveNamespaceIdForIssue (resolves to the unbound sentinel, used as a
namespace-map key) are different resolutions and are left as-is.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…iqueness note

Update diffSchema -> diffSchemas across the ADR and slice spec, and add the
coordinate-uniqueness sentence to the ADR near the coord()/walk description
(coord() must be unique among siblings aligned at a level; a kind unique only
within its parent folds the parent into the coordinate).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…string, stableKey comment (R02/R04/R05)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…database root

`diffSchemas` now takes two `DiffableNode`s (one per side) and calls
`diffPair(expected, actual)` — which checks `isEqualTo`, then recurses
into `diffChildren`. `DiffableRoot` is deleted; every node in the tree
(including the database root) implements `DiffableNode`.

`PostgresSchemaIR` gains `coord()` (database coordinate keyed on
`pgSchemaName`), `isEqualTo` (always true — no database-level attributes
yet), and `children()` (returns `rlsPolicies`). It now `implements
DiffableNode` instead of the deleted `DiffableRoot`.

`diffPostgresSchema` passes real `PostgresSchemaIR` nodes on both sides:
expected via `contractToPostgresSchemaIR`, actual from the introspected
`schema`. When `projectSchemaToSpace` returns a spread plain object (prototype
methods absent), it is reconstructed as a class instance before being
diffed. `collectContractRlsPolicies` is no longer imported at this call
site — it is consumed internally by `contractToPostgresSchemaIR`.

Slice spec and ADR updated to reflect the final single-node differ shape.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…cal keys

DiffableNode.coord(): EntityCoordinate → localKey(): string; a sibling-unique
path segment the differ accumulates into a readonly string[] path on each issue.
SchemaDiffIssue.coordinate → SchemaDiffIssue.path. filterSchemaIssuesByOwnership
gains a getNamespaceId callback so callers supply namespace from the node, not
the (now-removed) coordinate field.

Fixes a real bug: PostgresRlsPolicy.coord() omitted the table, so two policies
with the same prefix + body (same wire name) on different tables collided with
a duplicate-key throw. localKey() = namespace/tableName/wireName is table-scoped
and distinct. Regression test added to diff-postgres-schema.test.ts.

Consumer updates: planner reads namespaceId/tableName/name off issue.expected /
issue.actual (PostgresRlsPolicy nodes) instead of issue.coordinate; CLI tests
and combine-schema-results.test use issue.path. ADR updated to describe the
path-based model and record the EntityCoordinate alternative as rejected.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 4 commits June 26, 2026 17:04
The value is the node’s own identity among its siblings; the differ
concatenating identities into a path is the differ’s concern, not the
node’s. localKey/pathSegment encoded that consumer use; id() names the
intrinsic property on the DiffableNode interface (review comment #3).

Pure rename: same signature, same behavior, all impls and tests in
lockstep. Node key composition unchanged (separate task).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… caller-side whitelist

Policies now nest under a PostgresTableNode (database root → table → policy),
so a policy’s id() is just its wire name — unique among its table’s policies —
instead of folding namespace/table into the key. Same-wire-name policies on
different tables stay distinct via their table nodes.

The framework differ becomes total: an unmatched non-leaf node emits its own
issue and descends, emitting one per node in the missing/extra subtree. So an
initial migration (every table missing) still surfaces the policies beneath
the missing tables. Coalescing a parent change over its children is the
planner’s job.

Ownership and node-type selection leave the differ. diffPostgresSchema(expected,
actual) takes two built IRs, runs the total diff, whitelists policy-subject
issues (isPostgresRlsPolicy), and drops extra policies in namespaces expected
does not own. filterSchemaIssuesByOwnership is removed from framework
schema-diff.ts — the differ is pure.

namespaceId is resolved to its DDL schema name once, at derivation
(collectContractRlsPolicies), via the existing resolveDdlSchemaForNamespaceStorage,
so expected and actual table nodes pair by id(). The degraded resolveNamespaceId
duplicate is deleted.

Also completes the coordinate→path migration missed in 6bd0f25: the family-sql
filterSchemaDiffIssues test and the supabase skeleton test referenced the removed
.coordinate field (CI Test + Type Check were red on that tip).

Addresses review comments #2, #5, #6; #3 (id()) landed separately; #4 (rename the
root off "IR") deferred as its own leveling change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… spec reconcile

From the opus review of 5f16b73 (no correctness bugs found):
- planner.ts: comment that issue.{expected,actual}.namespaceId is already a
  resolved DDL schema name, so the resolveDdlSchemaForNamespaceStorage re-call
  is a tolerated no-op (correct while PostgresSchema.ddlSchemaName() === id).
- schema-diff.test.ts: rename the makeNode stub parameter localKey → nodeId so
  it does not read like a leftover of the renamed id() method.
- spec: owned namespaces include expected.existingSchemas (all declared
  namespaces), so a declared-but-policy-less namespace stays owned — matches the
  implementation, which is the better definition. Document the unbound-namespace
  + non-default-search_path non-idempotency as a pre-existing, narrowed limitation.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Postgres stamps a bare model into the explicit public namespace (the target
defaultNamespaceId), not the unbound one — bound namespaces diff correctly
regardless of search_path. The limitation applies only to the deliberate
Postgres late-binding (unbound keyword) opt-in under a non-public
current_schema(), and is partly inherent to late binding (schema unknown at
authoring). Doc-only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 3 commits June 26, 2026 18:57
…t back-threaded introspection

The fix for late-binding RLS is an authoring requirement: the unbound-namespace
RLS opt-in must require the user to name the schema to bind to. That name becomes
the expected IR; introspection is the actual; a mismatch is real drift. This keeps
both sides independently derived (expected never reaches into the live DB),
preserving the ADR separation — unlike threading introspected schema back into
the contract derivation. Doc-only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Branch was 8 commits behind main; the PR had no mergeable ref so CI would not
run. Conflicts were limited to 10 relational-planner test files, all in the
import block: the slice rewrote them to build a PostgresSchemaIR (the planner
now requires one as options.schema) while main refactored their namespace
construction (buildSqlNamespace → postgresCreateNamespace). Bodies auto-merged;
resolved each import block to the union of symbols the merged body uses.

pnpm install reconciled the new deps main added (e.g. apps/lsp-playground).
Full clean build + typecheck --force + the affected suites are green
(framework-components 437, family-sql 378, cli 1330, target-postgres 478,
adapter-postgres 660 +4 expected). No code-integration regressions — the
implementer-reported failures were stale-dist / uninstalled-deps in this
worktree, not the merge.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…uping

CI Lint (biome --error-on-warnings) flagged three noNonNullAssertion in the
table-node grouping. Restructure to a single Map<string, Group> keyed by
namespace/table whose values hold schemaName/tableName/policies; keep the
got-or-created group reference (no re-lookup) and map over Map.values()
(insertion order) — no `!`, no casts, same first-seen grouping behavior.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 2 commits June 26, 2026 19:45
CI check:upgrade-coverage requires a per-PR declaration in the user upgrade
skill when a PR touches examples/. The only examples/ change is the supabase
walking-skeleton test tracking the internal RLS schema-diff refactor
(coordinate→path, table nodes); the RLS diff surface is in development and the
authored feature behaviour is unchanged. Declared incidental (changes: []).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Addresses Will's round-5 review of PR #868.

Tree at derivation (was: flat rlsPolicies + regroup in children()):
- PostgresSchemaIR holds `tableNodes` built once at derivation; children()
  returns them directly. `rlsPolicies` is now a derived getter.
- `groupPoliciesIntoTableNodes` is the single grouping site, called by both the
  contract derivation (collectContractRlsTableNodes) and live introspection
  (all PostgresSchemaIR sites in control-adapter, incl. the multi-schema merge).

Ownership filtering leaves the differ (review): diffPostgresSchema runs the total
diff + whitelist + message render only; `dropUnownedExtraPolicyIssues` is applied
by the space-aware callers (planPostgresSchemaDiff, collectSchemaDiffIssues).

User-facing rendering: policy diff messages render `policy "name" on
"schema"."table"` (was a slash-joined path shown verbatim to users).

DiffableNode.id is a property (getter), not a method. Plus: assertPostgresSchemaIR
replaces the unreachable planner guard; redundant comment deleted; subtree emit
uses flatMap; supabase test reads the issue's node id, not the path tail.

Deferred (replied on thread): renaming PostgresSchemaIR off "IR" (61 refs;
needs the database-vs-schema leveling decided).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 2 commits June 27, 2026 12:12
…ic layer)

Round 4-5 synthesized a parallel `tableNodes` list by grouping policies, sitting
next to the real `tables`. That was the mistake: the schema IR is already a tree
and the table-IR instances are already the nodes — the PR only added the
DiffableNode interface to make that tree walkable.

- New `PostgresTableIR` (extends SqlSchemaIRNode, replicating SqlTableIR fields
  because SqlTableIR freezes in its constructor — same pattern as
  PostgresSchemaIR): carries `rlsPolicies`, `id` = table name, `children()` =
  its policies, `isEqualTo` trivially true (columns still diffed by the legacy
  relational path this round).
- `PostgresSchemaIR.tables` is `Record<string, PostgresTableIR>`; `children()`
  returns `Object.values(this.tables)`; `rlsPolicies` is a derived getter.
- The projection (contract + introspection) attaches each policy to its table,
  resolving the DDL schema name once per namespace.
- Deleted: `PostgresTableNode`, `groupPoliciesIntoTableNodes`, the `tableNodes`
  field, and the mislabeled `collect-contract-postgres-nodes.ts` (roles inlined).
- ifDefined for the policy normalization spreads.

Resolves the "RLS table nodes" / "why both tables and tableNodes" / collect-file
review comments: there is one table representation, and it is the node.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… filter; assert on table-less policy

Round-7 review cleanup (PR #868):
- Move the Postgres schema-IR node classes into src/core/schema-ir/
  (postgres-schema-ir, postgres-table-ir, postgres-rls-policy, postgres-role,
  postgres-schema-ir-annotations) so it reads as the schema-IR node family;
  postgres-schema.ts (the namespace facade) stays put. Imports updated.
- Rename dropUnownedExtraPolicyIssues → filterIssuesByOwnership; planner local
  diffIssues → filteredDiffIssues.
- contractToPostgresSchemaIR throws on a policy whose target table is absent
  from the schema IR (a malformed contract) instead of stubbing an empty table.
  The assert caught a malformed test fixture (a policy with no declared table) —
  fixed the fixture to declare its table.
- ifDefined for the policy normalization spreads (carried from r6 cleanup).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The differ and the schema-diff path are generic; the consumer side wrongly said
"RLS". Rename the planner locals rlsCalls -> schemaDiffCalls and rlsPartition ->
schemaDiffPartition; reword the "RLS policy drift" docs/comments to "schema
drift". Document the policy whitelist in diffPostgresSchema as transitional (the
generic differ walks the whole tree; non-policy issues are dropped only because
the legacy relational verifier still owns table/column drift). Note that the
display-only policy-reference render should route through the adapter SQL
renderer if it grows. Delete a useless doc comment. No behaviour change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden enabled auto-merge June 28, 2026 07:19
@wmadden
wmadden added this pull request to the merge queue Jun 28, 2026
Merged via the queue into main with commit a0ed104 Jun 28, 2026
20 checks passed
@wmadden
wmadden deleted the slice/entity-kind-migration-seam branch June 28, 2026 07: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.

2 participants