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

TML-2868: SELECT RLS policies, dependable end-to-end — authored in PSL, enforced, drift fails verify - #771

Merged
wmadden merged 154 commits into
mainfrom
worktree/charming-stonebraker-b0e449
Jun 24, 2026
Merged

wmadden merged 154 commits into
mainfrom
worktree/charming-stonebraker-b0e449

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

What this delivers

SELECT row-level security (RLS) policies for Postgres — authored in PSL and
dependable against a live database. A policy is created on migrate, edits replace
it, and any out-of-band change makes prisma db verify fail. Proven end-to-end
in the examples/supabase app.

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 db init      # ENABLE ROW LEVEL SECURITY + CREATE POLICY "profile_owner_read_dc40c58a"
$ # SET ROLE authenticated; SELECT * FROM profile  ->  only the caller's own rows
$ prisma-next db verify    # ok
$ psql -c 'DROP POLICY "profile_owner_read_dc40c58a" ON profile'   # out-of-band tamper
$ prisma-next db verify    # exits non-zero, naming the dropped policy

Scope — what works

  • Authoring: a policy_select block lowers, through the production
    contract emit path, into the contract as a first-class Postgres-target IR node.
  • db init / db update: the planner emits ENABLE ROW LEVEL SECURITY +
    CREATE POLICY; editing a predicate creates the new policy and drops the old
    (exactly one active afterward); a policy removed from the contract on a managed
    table is dropped (strict reconcile).
  • db verify: reports policy drift (missing, orphaned, or out-of-band
    changed) and exits non-zero, naming the policy.
  • Proven end-to-end against a live database in examples/supabase: rows are
    filtered under SET ROLE authenticated, and an out-of-band DROP POLICY fails
    verify.

Known limitation — disclosed, not silent

migration plan does not yet emit RLS. Generating a migration offline builds
the schema from contracts, and the contract→schema derivation does not yet carry
target-specific objects such as policies. Rather than silently produce a
migration with no RLS, migration plan fails with a clear error when the
contract declares policies, pointing you at db init / db update. The generic
seam that removes this limitation is the next slice (entity-kind-migration-seam,
"slice 1.5"); design seed in
projects/postgres-rls/specs/extension-migration-participation.md.

How it works

  • Generic schema diff — the framework never learns what a policy is.
    Verification and planning derive policy nodes from the contract, introspect the
    live database into the same node types, and compare them with a generic differ:
    nodes answer identity() / isEqualTo(), and the differ emits only
    { coordinate, outcome: missing | extra | changed }. No RLS symbol appears in
    the framework or SQL-family layers — enforced by a structural test, because
    import-direction linting can't catch this leak class.
  • Content-addressed policy names. You write a prefix (profile_owner_read);
    an 8-hex hash of the normalized policy body is appended
    (profile_owner_read_dc40c58a). Identity is name-equality, so Postgres
    reprinting a predicate never reads as drift; a real body change does. The
    normalizer collapses only reprint artifacts (casing, comments, ::text
    annotations, redundant parens) and is pinned by a counter-case corpus so two
    different predicates can't collide on one name.
  • Strict reconcile on managed tables. On a table the contract manages, any
    policy not present in the contract is dropped — there is no per-policy "is this
    ours" flag. (Table-level managed / external grading is slice 2.)

Deferred — tracked in projects/postgres-rls/plan.md

  • Slice 1.5 — entity-kind migration seam: the two-sided derivation
    contribution (project-from-contract + project-from-database) so a contributed
    kind works on every command, removing the migration plan limitation above.
  • Slice 2 — drift handled per variation + the policy→role dependency graph;
    managed/external table grading and DISABLE ROW LEVEL SECURITY on removal.
  • Slice 3 — INSERT / UPDATE / DELETE / ALL policy types.
  • Slice 4 — TypeScript authoring surface with PSL parity.

Verification

  • End-to-end (live DB, examples/supabase): authored PSL → db init → rows
    filtered under SET ROLE authenticated → db verify ok → out-of-band
    DROP POLICY → db verify exits non-zero naming the policy.
  • Adapter / unit (PGlite + unit): create, edit-replace (exactly one active),
    removal-and-drift fails verify; the content-addressing counter-case corpus; and
    a structural test asserting no RLS symbol in packages/1-framework /
    packages/2-sql.

🤖 Generated with Claude Code

wmadden and others added 14 commits June 8, 2026 15:29
…lates

Refresh the weeks-stale postgres-rls artifacts (TML-2501) against landed
dependencies and the current slice-based Drive layout:

- Reconcile every stale spec assumption to landed code (SchemaNodeBase->
  IRNodeBase/SqlNode; policies/roles on PostgresSchema.entries, not a table
  class; __unspecified__->__unbound__; entityTypes; control-policy two-layer
  dispatch). Findings in specs/reconciliation-2026-06-08.md.
- Settle the RLS authoring surface (D3) as a top-level Postgres-contributed
  helper (the enum mechanism), invisible off-Postgres, mirroring the PSL
  top-level shape — not a chained builder method. Rationale + rejected options
  in specs/design-rls-authoring-surface.md.
- Adopt per-operation PSL keywords (policy_select/...) to align with the
  landed target-contributed-psl-blocks substrate.
- Recompose into a 4-slice Sandwich diamond (foundation -> authoring ||
  migration-ops -> verifier+skeleton): TML-2868/2869/2870/2871.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…-2 scope

A policy_*'s `roles = [anon, authenticated]` are static references to declared
`role` entities, not strings — confirmed against the landed PSL-block substrate
(the `declarative-policy-select-extension` fixture already declares
`roles: { kind: list, of: { kind: ref, refKind: role, scope: cross-space } }`).

Fold the consequences into the plan + spec:
- Slice 1 must register `PostgresRole` as a `role` entity kind populating
  `entries[role]` (not just an IR class) — refs resolve by entries[refKind][name].
- Slice 2 owns cross-space role-ref resolution: the substrate defers cross-space
  ref enforcement to its first consumer (us), wired via the
  (spaceId, namespaceId, role, name) coordinate, reusing cross-contract-refs
  machinery. Same-space role refs resolve without it. Also adds the role-
  declaration authoring surface (TS RoleRef / PSL identifiers).
- Correct the spec's stale "cross-contract-refs is consumer-side only" claim:
  cross-space role resolution is integration work this project owns.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…-2868)

Slice 1 of 4. Chosen design grounded in the reconciliation anchors:
PostgresRlsPolicy/PostgresRole following the PostgresEnumType precedent
(entityTypes-registered, PostgresSchema.entries role/rlsPolicy slots);
StorageTable.rls; canonicalize.ts (normalizer + 8-hex content-hash);
serializer round-trip; SchemaIssue union widening. Four dispatches:
D1 IR+registration, D2 normalizer+hash, D3 serializer, D4 union widening.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…le.rls + entityTypes registration

Introduces the two Postgres-target-only RLS IR classes and the table-level
RLS toggle, following the PostgresEnumType precedent exactly. Reachable only
through synthetic test fixtures — no authoring helper, no planner, no verifier.

- packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts: new
  PostgresRlsPolicy class extending SqlNode, frozen, kind='postgres-rls-policy'
- packages/3-targets/3-targets/postgres/src/core/postgres-role.ts: new
  PostgresRole class extending SqlNode, frozen, kind='postgres-role'
- packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts: add role
  and rlsPolicy slots to PostgresSchema.entries and PostgresSchemaInput
- packages/3-targets/3-targets/postgres/src/core/authoring.ts: register role
  and rlsPolicy entity kinds in postgresAuthoringEntityTypes
- packages/2-sql/1-core/contract/src/ir/storage-table.ts: add rls?: RlsMode
  field (absent-when-default 'auto', mirrors control? discipline)
- packages/2-sql/1-core/contract/src/types.ts: export RlsMode
- packages/2-sql/1-core/contract/src/exports/types.ts: re-export RlsMode
- packages/3-targets/3-targets/postgres/src/exports/types.ts: export new classes
- packages/3-targets/3-targets/postgres/test/rls-ir-kinds.test.ts: synthetic
  fixture + freeze/immutability tests for all new surfaces

Gates: typecheck ✓, pnpm --filter target-postgres test (300 passed) ✓, lint:deps ✓

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…race

Dispatch D1 (IR kinds) of slice foundation: implementer commit 935d8a5,
reviewer verdict SATISFIED, zero findings. Records the dispatch brief, the
code-review round note + DC scoreboard (DC-3 lint:deps PASS), the persistent
implementer/reviewer subagent IDs, and the dispatch/round trace events.
Carry-forward: D3/slice-2 must decide validator schemas for the new entity kinds.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Edge-case corpus for normalizePredicate + computeContentHash covering:
whitespace variants, keyword lowercase, outer-paren trim, comment stripping
(line and block), string-literal data preservation, role ordering/dedup,
operation/permissive distinctness, and tuple encoding stability.

Red per TDD — implementation follows.

Signed-off-by: Will Madden <[email protected]>
normalizePredicate: char scanner strips line/block comments while
preserving string literals, then collapses whitespace, lowercases,
and trims fully-enclosing outer parens (repeated). No SQL grammar
parser — see normalizer stability notes in canonicalize.ts.

computeContentHash: SHA-256 over JSON-encoded tuple
[canonical(using), canonical(withCheck), sortedRoles, operation,
permissive] — first 8 lowercase hex chars. node:crypto only.

Also fixes tuple ordering in the stability-assertion test
(using is tuple position 0, not 1).

Signed-off-by: Will Madden <[email protected]>
The blanket .toLowerCase() at the end of normalizePredicate lowercased
the contents of single-quoted literals along with SQL keywords. This
collapsed 'Admin' and 'admin' to the same canonical form, producing
identical content hashes for semantically different predicates (Postgres
string comparison is case-sensitive).

Fold lowercasing into the char scanner (stripCommentsAndLowercase):
bytes outside literals are lowercased; bytes inside single-quoted
literals are copied verbatim. Remove the trailing .toLowerCase().

Tests updated:
- 'AND OR NOT NULL' inside a literal is now expected to preserve case.
- Added assertion that keyword lowercasing applies outside but not
  inside literals (WHERE x = 'Admin' → where x = 'Admin').
- Inverted the 'AND'/'and' hash test to assert they differ.
- Added 'Admin'/'admin' hash distinctness assertion.

Signed-off-by: Will Madden <[email protected]>
- Add rls? to StorageTableSchema so 'enabled'/'disabled' tables round-trip
- Add PostgresRoleSchema and PostgresRlsPolicySchema to validators.ts
- Extend createNamespaceEntrySchema entries to accept role? and rlsPolicy?
  slots with fragment-dispatched per-kind validation (same pattern as type?)
- Register the new schemas as validatorSchema on the role/rlsPolicy entries
  in postgresAuthoringEntityTypes

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…olicy slots

- serializePostgresNamespace emits role and rlsPolicy maps alongside table/type
- hydrateSqlNamespaceEntry extracts and factory-dispatches role/rlsPolicy entries
  from raw input; UNBOUND short-circuit now checks all four slots are empty
- Round-trip property tests: permissive + restrictive; using-only + using+withCheck;
  single + multi-role; frozen instances; rls omit-when-auto; negative tests for
  bad operation literal and missing permissive field

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Add RlsPolicyRenamedIssue, RlsPolicyTamperedIssue, and RlsNotEnabledIssue
payload interfaces to the framework SchemaIssue union, following the
EnumValuesChangedIssue precedent. Fix the one forced exhaustive switch
(classifySqlVerifierIssueKind) with provisional category assignments for
slice 4 to confirm. Add type-level tests asserting all three kinds are
members of SchemaIssue.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Extend the existing enum_values_changed guards in issueLocation, isMissing,
classifyIssue, and buildRecreatePostchecks to also exclude the three new RLS
kinds. These functions access BaseSchemaIssue fields (table, column, actual,
etc.) that the RLS interfaces do not carry; narrowing them out restores the
type invariant without adding any RLS-specific planner logic.

Export the three new payload interfaces from the framework-components control
entrypoint.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…near project

Drive build-loop artifacts for slice `foundation` (TML-2868): D2–D4 dispatch
briefs, the closed trace.jsonl (4 dispatches / 6 rounds / 6 briefs, backstop
green), and the spec/plan update pointing at the dedicated Postgres RLS Linear
project. D1 artifacts already committed in 1f4e81e.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 8, 2026 15:15
@coderabbitai

coderabbitai Bot commented Jun 8, 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

Adds end-to-end PostgreSQL Row-Level Security support: introduces a generic diffNodes/SchemaDiffIssue framework for schema drift detection, extends the PSL interpreter to lower policy_select blocks into PostgresRlsPolicy IR, implements predicate canonicalization and content hashing for deterministic policy wire names, adds RLS migration operations and planner diff integration with dependency ordering, extends the Postgres adapter to introspect and verify RLS policies, and propagates extensionIssues through CLI aggregation and output formatting.

Changes

PostgreSQL RLS end-to-end flow

Layer / File(s) Summary
Schema diff contracts and verify result integration
packages/1-framework/1-core/framework-components/src/control/schema-diff.ts, control-result-types.ts, exports/control.ts, packages/2-sql/9-family/src/core/control-adapter.ts, control-instance.ts, verify-sql-schema.ts, packages/2-mongo-family/9-family/src/core/schema-verify/verify-mongo-schema.ts, packages/1-framework/3-tooling/cli/src/utils/combine-schema-results.ts, formatters/verify.ts, control-api/operations/db-verify.ts, test/...
Introduces SchemaDiffOutcome, SchemaDiffIssue, DiffableNode, and diffNodes utility for stable identity-based diffing; adds extensionIssues to VerifyDatabaseSchemaResult; threads empty arrays through SQL/Mongo verify paths; adds optional collectExtensionIssues hook on SqlControlAdapter; wires aggregation and CLI formatting; adds structural invariant enforcement for shared layers.
Extension slot interpreter routing
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts, provider.ts, test/interpreter.extensions.test.ts
Updates createNamespace signature to accept optional enumTypes argument; adds buildEntityTypesByDiscriminator to map authoring entity types by discriminator; implements lowerExtensionBlocksForNamespace to parse and instantiate extension blocks per namespace; wraps namespace creation to inject lowered extension entities into entries before SQL contract build; passes codecLookup to PSL parser.
Postgres RLS authoring, IR, and canonicalization
packages/3-targets/3-targets/postgres/src/core/authoring.ts, postgres-rls-policy.ts, postgres-role.ts, postgres-validators.ts, rls/canonicalize.ts, descriptor-meta.ts, exports/rls-canonicalize.ts, exports/types.ts, tsdown.config.ts, package.json, test/rls-*.test.ts, psl-policy-authoring.test.ts, rls-ir-kinds.test.ts
Adds RlsPolicyExtensionBlock and postgresAuthoringPslBlockDescriptors for policy_select authoring; implements PostgresRole and PostgresRlsPolicy as DiffableNode classes with identity/equality semantics; adds normalizePredicate (comment/whitespace/paren/cast normalization) and computeContentHash (SHA-256 truncated to 8 hex) for deterministic wire names; extends authoring entity types with role/rlsPolicy helpers and descriptor meta configuration; validates with canonicalization, IR construction, diffable-node, and PSL authoring tests.
Postgres schema slots and contract serialization
postgres-schema.ts, postgres-contract-serializer.ts, test/postgres-contract-serializer.test.ts
Extends PostgresNamespaceEntries to include required role and rlsPolicy entry maps; updates PostgresSchema constructor to normalize raw inputs into PostgresRole/PostgresRlsPolicy instances and freeze maps; extends PostgresContractSerializer to register validator schemas, hydrate/serialize role and rlsPolicy slots, update unbound-namespace detection, and emit serialized entries.
RLS operations and planner integration
migrations/operations/rls.ts, op-factory-call.ts, issue-planner.ts, planner-target-details.ts, planner.ts, enum-planning.ts, test/migrations/rls-ops.test.ts, rls-planner.test.ts
Adds createRlsPolicy, dropRlsPolicy, enableRowLevelSecurity operations with SQL rendering, role validation, and precheck/postcheck assertions; implements corresponding call wrapper classes; extends OperationClass with rlsPolicy and rowLevelSecurity; adds rlsEnable/rlsPolicy/drop call categories and buckets to planner ordering (after table bucket); implements readExpectedRlsPolicies and buildRlsDiffCalls to generate RLS operations from diff results; wires via extraBucketableCalls into planIssues; updates schema IR annotations with RLS introspection fields.
Adapter introspection and verification extension issues
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts, package.json, test/migrations/rls-*.test.ts
Extends introspectSchema to query pg_policies, pg_roles (excluding system roles), and table relrowsecurity flag; maps pg_policies rows to canonical PostgresRlsPolicy instances via operation/role/predicate mapping and content-hash derivation; implements collectExtensionIssues filtering on prismaManaged flag and diffing via diffNodes; provides parsePgNameArray and mapPgCmd helpers; validates through collect-extension-issues, introspection, verify, lifecycle e2e, and walking-skeleton integration tests.
Supabase example RLS integration and bootstrap
packages/3-extensions/supabase/test/supabase-bootstrap.ts, examples/supabase/src/contract.prisma, handlers.ts, contract.json, test/skeleton.integration.test.ts
Updates Supabase test bootstrap to idempotently seed anon/authenticated/service_role roles and define auth.uid() function; adds owner_id field and policy_select profile_owner_read to Profile model; updates insertAndReadProfile handler to include owner_id parameter; extends skeleton integration test to verify RLS row filtering and detect out-of-band policy drift via extensionIssues.
Generated contract updates
examples/*/src/prisma/contract.d.ts, examples/*/src/prisma/contract.json
Updates generated contract type definitions and JSON metadata for examples as enum types are moved to codec representation and RLS policies are added to public schemas.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Poem

🐇 Hop, hop — the rows now hide behind a policy wall,
I auth.uid() myself before I dare to crawl.
A content hash is born, eight hex glyphs shine so bright,
CREATE POLICY, ENABLE RLS — the planner gets it right.
If a policy drifts away, extensionIssues will say so true,
This bunny guards your data rows — no unauthorized view! 🔒

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 39.76% 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
Title check ✅ Passed The title clearly describes the main change: implementing end-to-end Postgres SELECT RLS policies authored in PSL, with enforcement and drift detection.
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.

✏️ 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 worktree/charming-stonebraker-b0e449

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 8, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/config-loader

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

@prisma-next/emitter

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

@prisma-next/language-server

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: acade19

@github-actions

github-actions Bot commented Jun 8, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 158.28 KB (+2.01% 🔺)
postgres / emit 145.84 KB (+2.17% 🔺)
mongo / no-emit 78 KB (0%)
mongo / emit 72.09 KB (0%)
cf-worker / no-emit 185.59 KB (+1.68% 🔺)
cf-worker / emit 171.64 KB (+1.86% 🔺)

wmadden and others added 2 commits June 9, 2026 13:35
The shipped foundation slice (TML-2868) had no consumer — reachable only
through synthetic fixtures — so it proved layers in isolation, not that they
connect. Re-cut the remaining slices "tracer bullet first, then thicken":
slice 2 is now a thin vertical PSL→IR→CREATE POLICY→PGlite thread that
demonstrates RLS filtering rows, with breadth (full authoring; full ops +
verifier) and the Supabase walking skeleton + cross-space roles following.

Plan diagram/composition/sequencing updated; lesson captured in learnings.md
(L1). Linear slices re-scoped to match (TML-2869 tracer, 2870 authoring
breadth, 2871 migration+verifier breadth, 2876 supabase skeleton).

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Rewrite for a fresh implementer with no project context. Spec now leads with
six stated design decisions (data model, content-addressed naming, dual
authoring surfaces, roles-as-refs, planner/verifier) — each naming the
requirement it satisfies and giving one authoritative IR definition — instead
of making the reader reverse-engineer the design from functional requirements.
Alternatives (authoring-surface options, naming options, settled defaults,
still-open items) consolidated at the end. Inlined insider shorthand
(Option C, D1/D3, Q2-Q5, OC/C codes); removed slice-sequencing from the spec
(plan owns it) and stale "four slices" references. Plan de-jargoned and given
a slicing-alternatives section.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@wmadden-electric wmadden-electric changed the title TML-2868: postgres-rls slice 1 — RLS/role IR, content-addressed naming, serializer, SchemaIssue union TML-2868: model Postgres RLS policies & roles as content-addressed contract IR Jun 9, 2026
@wmadden-electric
wmadden-electric marked this pull request as draft June 9, 2026 12:31
wmadden and others added 8 commits June 9, 2026 15:56
…leton slice 1

Replace the leaky verifier design (framework SchemaIssue widening +
StorageTable.rls in SQL core) with a generic SchemaIR<->SchemaIR differ:
issues become {coordinate, outcome}, node identity()/isEqualTo() are virtual
methods, planning is per-node create/delete/update -> OpFactoryCall. The
framework/SQL-family never reference RLS. Spec D5 rewritten; D1 drops the
StorageTable.rls leak; layering invariant tightened; alternatives record the
union-widening and cross-hierarchy-diff rejections.

Plan merged to four slices: slice 1 is the RLS walking skeleton (thin PSL
policy_select through the new differ to PGlite row-filtering, stripping the
foundation leaks as part of building the right path), then authoring breadth,
verify/plan breadth, supabase skeleton. The 25-kind relational port and
dependency-aware planner ordering are named independent follow-on projects
that never gate RLS.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Durable record of the design discussion: the leak and its root cause, the
generic SchemaIR<->SchemaIR differ, identity-vs-equality as node virtual
methods, derivation-holds-the-smarts, per-node planner dispatch, coarse-vs-
dependency ordering, scope (top-level layer for RLS; relational port +
dependency planner deferred), and the ground-truth research anchors.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ive)

File-by-file slice spec for slice 1 (the generic-differ walking skeleton):
the leak-removal manifest (exact file:line), the framework SchemaDiffIssue +
DiffableNode + diffNodes design, PostgresRlsPolicy/Role implementing
DiffableNode, pg_policies/pg_roles introspection into annotations.pg, per-node
CreateRlsPolicy/EnableRowLevelSecurity ops mirrored on AddForeignKeyCall, the
policy_select PSL descriptor from the landed fixture, the verify extension
channel, and the end-to-end PGlite SET-ROLE row-filtering test. Binary ACs +
halt conditions. Pinned to real seams via the integration-seam research.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…brief

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rs to postgres target

- Remove RlsPolicyRenamedIssue, RlsPolicyTamperedIssue, RlsNotEnabledIssue interfaces and their SchemaIssue union members from framework-components
- Remove their exports from control.ts
- Remove the three RLS case arms from classifySqlVerifierIssueKind in verifier-disposition.ts
- Remove RLS narrowing guards from SQLite planner (issue-planner.ts, planner-strategies.ts, operations/tables.ts) and Postgres planner (issue-planner.ts)
- Remove StorageTable.rls / RlsMode from storage-table.ts, types.ts, exports/types.ts, and StorageTableSchema in validators.ts
- Move PostgresRoleSchema and PostgresRlsPolicySchema into packages/3-targets/3-targets/postgres/src/core/postgres-validators.ts
- Add entrySlotName to AuthoringEntityTypeDescriptor so targets declare their own namespace entry slots
- Wire postgres role/rlsPolicy descriptors with entrySlotName via the entityTypes fragment channel
- Generalize createNamespaceEntrySchema and createSqlContractSchema to accept validatorEntrySlots, removing hardcoded role/rlsPolicy slots from SQL family core
- Update tests to remove assertions for deleted features

Co-Authored-By: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…tch)

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Adds `schema-diff.ts` to the framework with `SchemaDiffOutcome`, `SchemaDiffIssue`,
`DiffableNode`, and `diffNodes` — fully RLS-agnostic; no Postgres imports.
Exports all three from `exports/control.ts`.

`PostgresRlsPolicy` and `PostgresRole` implement `DiffableNode`: `identity()`
returns an `EntityCoordinate` with the appropriate `entityKind` (`rlsPolicy` /
`role`) and the wire name as `entityName`; `isEqualTo` compares by name.
Both methods are prototype-defined so they survive `freezeNode`. The policy node
gains a nullable `namespaceId` field (defaults to `UNBOUND_NAMESPACE_ID`) to
populate the coordinate.

Unit tests cover: missing/extra/mismatch/clean + deterministic order for the
differ; identity/isEqualTo/freeze survival for both Postgres node types.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ovider

The interpreter no longer falls back to target.authoring.createNamespace
(removed when the target type narrowed to the framework TargetPackRef during
the #851 merge). That broke the PSL emit path for configs that lower extension
entities (e.g. examples/supabase RLS policy) without explicitly passing
createNamespace, surfacing as 'extension entities lowered but the target
supplies no createNamespace factory'.

Restore the fallback in the PSL provider: read createNamespace off the target
pack's authoring descriptor (a typed view via blindCast, since the framework
AuthoringContributions type does not declare this SQL-specific field) and pass
it to the interpreter when the caller does not supply one explicitly.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Multi-space db verify runs per space, each with its own contract, but the live
schema introspection returns RLS policies across every DB schema. Without
scoping, a space that owns only auth/storage (the supabase extension space)
reported the application space's public.* policies as extra and failed verify.

Filter the introspected policies to the namespaces the verified contract
declares before diffing. Cross-space / external policies are ignored; a genuine
extra in an owned namespace still surfaces, and a missing owned policy still
fails (covered by the supabase drift-fails-verify e2e).

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

The previous scoping commit compared raw namespace slot keys, but a
single-namespace contract carries the late-bound `__unbound__` id while its
introspected policies (and the migration planner's schema IR) may carry either
`__unbound__` or the resolved `public` schema name. Comparing raw ids filtered
out owned policies, regressing rls-collect-extension-issues and rls-planner
(extra/missing/edit cases).

Normalize both the owned-namespace set and each introspected policy's
namespaceId through the same unbound -> public resolution before the ownership
check. Cross-space policies (e.g. the app's `public.*` seen by the supabase
space that owns only auth/storage) are still ignored; owned-namespace
extra/missing still surface.

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

`biome check --error-on-warnings` flagged 11 `noNonNullAssertion` warnings in
the RLS predicate canonicalizer (`sql[i]!`, `out[out.length-1]!`), failing
`pnpm lint:packages` for @prisma-next/target-postgres. These indexed reads are
inside `while (i < length)` guards, so String.prototype.charAt(i) is an exact
equivalent that returns `string` without the assertion. No behavior change;
all 479 target-postgres tests pass.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ross-ns test

`pnpm lint:packages` (biome --error-on-warnings) flagged two warnings in
@prisma-next/adapter-postgres RLS code:
- control-adapter.ts: noNonNullAssertion on the policy-name regex match group —
  replace `hashSuffixMatch[1]!` with `hashSuffixMatch?.[1] ?? row.policyname`
- cross-namespace-fk.integration.test.ts: useIndexOf — replace
  `findIndex((id) => id === 'schema.auth')` with `indexOf('schema.auth')`
No behavior change.

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

The alwaysApply rule added in this PR pushed the rules footprint over three
thresholds (main left them right at the limit). Trim the rule from 43 to ~18
lines — keep the essence (missing @prisma-next/* is a build/install-state issue;
verify with require.resolve since pnpm links per-consumer, not at repo root; then
pnpm build for stale dist / pnpm install for a new dep), drop the long
sub-sections. Bump the three exceeded thresholds in rules-footprint.config.json
minimally with small headroom for the trimmed rule (sanctioned for intentional
additions per the check message).

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…nges: [])

check:upgrade-coverage requires a per-PR declaration whenever the PR touches
examples/ or packages/3-extensions/. This PR's touches there are the additive
Postgres RLS demo (supabase contract re-emit, profile-queries, skeleton test,
bootstrap helper) plus merge regeneration — no downstream breaking change.

Keep changes: [] in both 0.14-to-0.15 instruction files and add an HTML-comment
note (matching the existing TML-2787/2929/2794 style) recording the TML-2868
incidental diff: RLS is opt-in, existing schemas emit/verify unchanged, no user
or extension-author action — re-emit absorbs the contract shape.

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

Revert the earlier threshold bump (back to alwaysApply 605 lines / 33000 bytes,
total 203500 bytes) and instead cut always-loaded rule content to fit. main left
the always-loaded footprint at the limit with zero headroom, so the new
workspace-package-not-found rule overflowed; keeping it requires cutting
equivalent content.

- workspace-package-not-found-run-pnpm-install.mdc: 18 -> ~13 lines (bare steps)
- prefer-psl-in-design-docs.mdc: 70 -> ~28 lines (drop worked examples, keep the
  lead-with-PSL guidance, the prisma-not-psl fence rule, and the superset/design
  rationale)
- no-transient-project-ids-in-code.mdc: 68 -> ~40 lines (condense the
  forbidden/allowed lists and how-to-comply; keep the grep check)

Footprint now: alwaysApply 522 lines / 27.6 KB, total 194.4 KB — all under the
original thresholds with headroom. No rule guidance lost, only verbose prose and
restated examples.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…r blindCast

The PSL provider read the target's createNamespace through a blindCast over the
framework AuthoringContributions (which doesn't declare the SQL-specific field).
Replace it with a real SQL-family type:

- Add SqlNamespaceFactory + SqlAuthoringContributions (extends the framework
  AuthoringContributions with the optional createNamespace) and a
  isSqlAuthoringContributions type predicate to @prisma-next/sql-contract's
  sql-storage module; export both. createNamespace stays out of the framework
  AuthoringContributions (SQL-specific).
- The predicate narrows cast-free via Object.hasOwn + Reflect.get.
- provider.targetCreateNamespace now narrows target.authoring with the predicate
  and returns createNamespace — no blindCast, no bare as.

supabase emit still resolves createNamespace via the target fallback (config
does not pass it explicitly); build, typecheck, contract-psl/sql-contract tests,
lint:packages, lint:casts, lint:deps all green.

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

Operator decision: there is no tamper detection. The content hash exists to
avoid comparing predicate bodies — the wire name (prefix + 8-hex hash) is the
only equivalence relation, and the hash is never recomputed from an introspected
body. So the reprint-matching normalization had no purpose.

Cut canonicalize.ts from 445 to 48 lines: keep ContentHashParts,
RlsPolicyOperation, computeContentHash, and a minimal normalizePredicate that
only trims and collapses internal whitespace of the authored predicate. Remove
stripCommentsAndLowercase, normalizeCastAliases, stripRedundantCastParens,
stripTopLevelAndParens, isOuterParenWrapped, and the hasTopLevel* helpers.
Minimal normalization is also safer for the no-collision property — it never
collapses two distinct predicates onto one hash.

Tests: drop the reprint-equivalence cases (lowercasing, paren-strip, comment-
strip, cast-alias, ::text) that asserted a Postgres-reprinted form hashes the
same as the authored form — that scenario no longer exists. Keep the
distinct-predicate counter-corpus and the whitespace-equivalence + role
order/dedup cases.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The minimal predicate normalizer changes the content hash, so the example's RLS
policy wire name re-suffixes (profile_owner_read_3486711c → _9f8e536e). Slice 1
hasn't shipped, so there is no compat concern. Regenerated via prisma-next
contract emit.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Reflect the operator decision that there is no tamper detection. The content
hash addresses the authored predicate and the wire name is the only equivalence
relation; the framework never recomputes the hash from an introspected body and
never compares predicate bodies.

- spec.md: normalizer description → minimal (collapse internal whitespace +
  trim); drop the "tamper detection is cheap / recompute from introspected row"
  bullet; rewrite the no-false-drift blockquote to justify content addressing
  without claiming the normalizer matches Postgres's reprint; drop the
  recomputed-hash-mismatch acceptance clause and the rls_policy_tampered issue
  kind; add an explicit non-goal that out-of-band ALTER POLICY on a hashed
  policy is unsupported (surfaces as an ordinary extra → drop, not a tamper
  signal). Rename handling kept throughout.
- adr-content-addressed-policy-names.md: hash-input + cross-kind normalizer
  descriptions → minimal; verifier semantics use the generic differ outcomes
  (rename/missing/extra/mismatch) instead of framework rls_* issue kinds; remove
  the tamper issue kind and the "cheap tamper detection" benefit.
- plan.md: slice 2 drops the tamper variation (rename, role traversal,
  managed/external kept).

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Per review: type guards must narrow structurally, not by instanceof, and take
the abstract base type as input.

- isPostgresSchemaIR(schema: SqlSchemaIR): schema is PostgresSchemaIR — input is
  the base SqlSchemaIR (was unknown); narrows on the postgres-only own field
  rlsPolicies via 'rlsPolicies' in schema + Array.isArray (cast-free). Removed
  the instanceof branch. Still narrows the projectSchemaToSpace spread-into-
  plain-object case (the field is enumerable so it survives the spread; the
  family kind discriminator is shared and non-enumerable, so unusable).
- PostgresRlsPolicy.isEqualTo now guards with the structural isPostgresRlsPolicy
  instead of `other instanceof PostgresRlsPolicy`.
- Simplified isPostgresRlsPolicy + assertPostgresRlsPolicy to read node.kind
  cast-free after the 'kind' in node narrow, dropping the blindCast + its import.

No instanceof in these guards; no bare as. build/typecheck/target-postgres(446)/
adapter-postgres(648) + multi-space scoping path green.

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

Per review: the 'rlsPolicies' in schema duck-type is brittle (breaks if
rlsPolicies is ever made optional). Replace it with a reliable target
discriminant.

- Add SqlSchemaTarget = 'sql' | 'postgres' and an enumerable readonly
  nodeTarget field on the schema-root IR: SqlSchemaIR carries 'sql' (optional on
  the type so existing plain-data SqlSchemaIR literals still satisfy it without
  restating the field), PostgresSchemaIR carries 'postgres'. nodeTarget is a
  plain class-field initializer (enumerable, unlike the shared non-enumerable
  kind), so it survives the projectSchemaToSpace spread the multi-space verify
  path relies on.
- isPostgresSchemaIR(schema: SqlSchemaIR): schema is PostgresSchemaIR now returns
  schema.nodeTarget === 'postgres' — no 'rlsPolicies' in …, no instanceof, no
  cast. Export SqlSchemaTarget from both schema-ir type barrels.

build/typecheck/target-postgres(446)/adapter-postgres(648, incl multi-space
scoping)/lint:packages/fixtures:check all green. No snapshot churn from the new
field.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden added this pull request to the merge queue Jun 24, 2026
Merged via the queue into main with commit 2b11248 Jun 24, 2026
20 checks passed
@wmadden
wmadden deleted the worktree/charming-stonebraker-b0e449 branch June 24, 2026 09:22
tensordreams pushed a commit to prisma/orm that referenced this pull request Jul 28, 2026
…ject artifacts (#979)

## Linked issue

Refs [TML-2501](https://linear.app/prisma-company/issue/TML-2501) —
close-out of the [Postgres
RLS](https://linear.app/prisma-company/project/postgres-rls-b7329340dbb2)
Linear project (now Completed).

## At a glance

All eight postgres-rls slices are merged (final:
[#959](prisma/prisma-next#959), TS RLS
authoring). Per the [`projects/` lifecycle](projects/README.md), this PR
performs the close-out: promote the long-lived docs into `docs/`, strip
the one repo reference into the project directory, and delete
`projects/postgres-rls/`.

Three commits, in lifecycle order:

1. **Promote** — ADR 234 (content-addressed wire names), ADR 235 (schema
differ over two derived IRs), ADR 236 (target-contributed model
attributes, the ADR the project DoD deferred to close-out), and a new
RLS section in the Adapters & Targets subsystem doc.
2. **Strip** — the supabase README pointer into `projects/postgres-rls/`
re-pointed at ADR 234 + the subsystem section (it also named the
pre-decision `.rls(...)` surface; now names the shipped one).
3. **Delete** — `projects/postgres-rls/` (spec, plan, handoff, slice
specs/plans, dispatches, trace).

## Project DoD verification

| DoD item (spec § Definition of Done) | Status | Evidence |
| --- | --- | --- |
| TS + PSL author the same policies to structurally identical IR with
identical wire names; helpers invisible off-Postgres | Met |
[#959](prisma/prisma-next#959):
`ts-psl-rls-parity.test.ts`, byte-identical parity fixture,
`rls-helper-invisibility.test.ts` |
| TS `ref()` predicate helper | Struck | Operator veto at slice-5 review
(2026-07-13): predicates are opaque strings on both surfaces; recorded
in the spec before deletion |
| Full lifecycle on live PGlite through the generic differ (create /
drop / rename via `ALTER POLICY … RENAME TO` / enable) | Met |
[#771](prisma/prisma-next#771) (lifecycle),
[#921](prisma/prisma-next#921) (one differ),
[#945](prisma/prisma-next#945) (rename, `@@rls`,
grading) |
| Declared role absent from `pg_roles` fails verify even under `control:
'external'` | Met |
[#950](prisma/prisma-next#950);
`examples/supabase/test/skeleton.integration.test.ts` case G |
| Walking skeleton: `examples/supabase` Profile policies filter rows
under `SET ROLE`, verifier diffs clean | Met |
[#950](prisma/prisma-next#950) capstone +
[#959](prisma/prisma-next#959) TS-authored
skeleton (`rls-ts-walking-skeleton.integration.test.ts`) |
| Zero RLS vocabulary in framework / SQL-family layers | Met |
`lint:deps` + `lint:framework-vocabulary` green on every slice;
structural invariant test |
| Content-addressed-naming ADR promoted to `docs/architecture
docs/adrs/`; adapter subsystem doc gains an RLS section | Met | **This
PR** — ADR 234 + § Row-Level Security in `5. Adapters & Targets.md` |
| ADR for the slice-3 authoring SPIs (`modelAttributes`,
`requiresModelAttribute`) | Met | **This PR** — ADR 236 |

## Final retro (mandatory at close)

- **Held:** the content-addressed-naming thesis survived every slice
unchanged — the wire name stayed the only equivalence relation, and
rename detection fell out free. One lowering (predicate matrix + hash
assembly) now serves both authoring surfaces.
- **Surprised:** the project spent slices 1.5–2.6 rebuilding the
diff/verify substrate it needed to stack on — the RLS features
themselves (3, 4, 5) were small once the substrate held. Review
repeatedly caught new mechanisms duplicating existing capability
(opRender vs CodecRegistry, coordinate structs, per-factory validation);
the standing probe is now "grep for the existing primitive before
accepting a new one".
- **Lessons landed:** `docs/onboarding/fixtures-emit-and-check.md`
(fixtures:check does not cover planner ops); the per-factory PSL
validation gaps became
[TML-3023](https://linear.app/prisma-company/issue/TML-3023) instead of
a fourth patch.
- **Deferred scope, all ticketed or assigned:**
[TML-3023](https://linear.app/prisma-company/issue/TML-3023)
(block-descriptor validator + PSL prefix cap),
[TML-2958](https://linear.app/prisma-company/issue/TML-2958)
(PSL-inference tree-walk),
[TML-2936](https://linear.app/prisma-company/issue/TML-2936)
(annotations bag),
[TML-2974](https://linear.app/prisma-company/issue/TML-2974) (native
per-space verify render); dependency-aware planner ordering and
codec-ops-on-the-differ get tickets when prioritized.

## Classification (audit trail)

- **Long-lived, migrated with rewrite:**
`specs/adr-content-addressed-policy-names.md` → ADR 234 (authoring
examples updated from the rejected `.rls([...])` surface to the shipped
`policyUpdate(...)` / `policy_update` forms);
`specs/adr-schema-diff-over-structured-ir.md` → ADR 235 (differ
vocabulary updated to the shipped `not-found | not-expected | not-equal`
reasons, property-form `DiffableNode`, the real node tree with roles on
the database root; superseded "table nodes are groupers only" section
dropped).
- **Long-lived, authored at close:** ADR 236 (per the DoD item deferred
from the PR #945 review).
- **Transient, deleted:** `spec.md`, `plan.md`, `HANDOFF.md`,
`trace.jsonl`, `slices/**` (per-slice specs/plans/dispatches), and the
remaining `specs/*` shaping docs (`design-*`, `brief-*`,
`reconciliation-*`, `extension-migration-participation.md`) —
shaping/coordination artifacts whose surviving content is the shipped
state and the promoted ADRs.

## Reference strip

One external reference existed
(`packages/3-extensions/supabase/README.md`); re-pointed. Post-delete
rescan of tracked files for `projects/postgres-rls` is empty.

## Checklist

- [x] Every commit is DCO signed-off
- [x] Docs-only — no behavior change
- [x] Linear project referenced (TML-2501)
🤖 Generated with [Claude Code](https://claude.com/claude-code)


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

## Summary by CodeRabbit

* **Documentation**
* Added architecture guidance for comparing schema representations and
reporting structured differences.
* Documented target-contributed model attributes and declarative
validation rules.
* Expanded PostgreSQL Row-Level Security documentation, including policy
naming, verification, and SQL migration actions.
* Updated Supabase documentation and RLS examples to reflect current
authoring conventions.

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

---------

Signed-off-by: willbot <[email protected]>
Signed-off-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