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

TML-2500(M2): reference another contract space in a foreign key — e.g. Profile.user → supabase:auth.User (TS + PSL authoring) - #752

Merged
wmadden merged 14 commits into
mainfrom
tml-2500-m2-authoring-surfaces
Jun 7, 2026
Merged

wmadden merged 14 commits into
mainfrom
tml-2500-m2-authoring-surfaces

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

At a glance

Today an app contract can only put a foreign key on its own tables. After this PR you can point a foreign key at a table owned by another contract — typically one shipped by an extension package. The motivating case is an app Profile that references Supabase's auth.User:

// app/contract.ts
import { AuthUser } from '@prisma-next/extension-supabase/contract';
import supabasePack from '@prisma-next/extension-supabase/pack';

export const contract = defineContract(
  {
    family: sqlFamily,
    target: postgresPack,
    namespaces: ['public'],
    extensionPacks: [supabasePack], // ← declares the dependency on the 'supabase' contract space
  },
  ({ field, model }) => {
    const Profile = model('Profile', {
      namespace: 'public',
      fields: { id: field.id.uuidv4(), userId: field.uuid() },
    });
    return {
      models: {
        Profile: Profile.relations({
          // same call shape as a local relation — AuthUser just happens to live in another space
          user: rel.belongsTo(AuthUser, { from: 'userId', to: 'id' }),
        }).sql(({ cols, constraints }) => ({
          table: 'profile',
          foreignKeys: [
            constraints.foreignKey(cols.userId, AuthUser.refs.id, { onDelete: 'cascade' }),
          ],
        })),
      },
    };
  },
);

The same thing in PSL, where a colon marks the cross-space reference:

namespace public {
  model Profile {
    id     String @id @default(uuid())
    userId String @unique
    user   supabase:auth.User @relation(fields: [userId], references: [id], onDelete: Cascade)
  }
}

Both forms lower to the IR carrier M1 introduced (a foreign-key reference whose spaceId records which contract space owns the target). This PR is the authoring → IR half only. Emitting the actual REFERENCES "auth"."users"("id") DDL, the verifier, and the live-database test are M3.

What this PR decides

Four decisions shape the surface; the rest of the description explains each one:

  1. Cross-contract FKs reuse the existing call shape. There is no refExt / belongsToExternal. You import a model handle from the extension and pass it to the same rel.belongsTo(...) / constraints.foreignKey(...) you already use. The framework tells local from cross-space by a brand on the imported handle, so the only visual signal a reader needs is the import line.
  2. PSL adds exactly one token: a colon prefix on the type (supabase:auth.User). @relation(...) is unchanged.
  3. A cross-space reference is a declared but non-navigable relationship. It is visible, it drives the FK, but traversing it from a query (include) is a compile-time error — we have not designed cross-space query traversal yet, and Supabase apps don't read auth.users directly anyway.
  4. Extensions expose their models through a small factory, not by leaking an internal builder class.

How it works, piece by piece

The carrier (recap from M1). A SQL foreign-key reference already carries { namespaceId, tableName, columns }. M1 added an optional spaceId: when it's present, the reference points into another contract space; when it's absent, it's an ordinary local FK and serializes byte-for-byte as before. Everything in this PR is about producing that spaceId from user-written code.

The brand (TypeScript). A model handle now carries a phantom type parameter recording its contract space — '<self>' for a model you declared locally, the extension's id ('supabase') for a handle imported from an extension. The brand rides on the Model.refs.field references the FK call consumes (AuthUser.refs.id is typed for the supabase space), so constraints.foreignKey / rel.belongsTo can read it at lowering time and emit the right carrier. The brand survives the builder chain (.relations().sql(...)), which matters because that's how real handles are constructed.

The non-navigable relation (decision 3, in detail). A cross-space reference is more than a column constraint — it's a relationship, authored with the same belongsTo / @relation surface as a local one, and it carries the foreign spaceId into the domain layer. But the contract emitter renders it as never in the generated relation types, so the ORM excludes it from the include surface: db.public.Profile.find({ include: { user: true } }) fails to type-check. The relationship is introspectable and drives the FK; only traversal is withheld. A negative type test pins this (the cross-space include is rejected while a local one still compiles).

Extension handles (decision 4, in detail). @prisma-next/extension-supabase gains a /contract entry point exporting AuthUser, AuthIdentity, StorageBucket, StorageObject as branded handles. These are built with a new extensionModel(name, { namespace, fields, table }, spaceId) factory; the underlying builder class stays a type-only export. A test checks the handles against the contract the package actually ships, so a handle can't silently drift from the real schema.

PSL grammar (decision 2, in detail). No tokenizer change is needed — : is already a token. The field-type parser learns to peel a leading <space>: prefix and store it on a new PslField.typeContractSpaceId, accepting supabase:auth.User and the no-namespace form supabase:User. The interpreter then threads that into the same carrier the TS path produces. A missing reference fails fast with PSL_UNKNOWN_CONTRACT_SPACE, naming the space and pointing at extensionPacks.

PSL printer round-trip. The printer now renders the qualified type back out (supabase:auth.User, auth.User, User). Doing so also fixes a pre-existing bug from the cross-namespace work: a plain auth.User field used to print back as bare User. The two render through the same code path, and AC2's round-trip depends on it.

Cascade and other referential actions. onDelete: 'cascade' (and the rest) is allowed on a cross-contract FK with no warning. The explicit opt-in at the call site is the record of intent; warning on every build would be noise.

Scope — deferred to M3

  • DDL emission and the verifier (qualified vs unqualified REFERENCES, checking against pg_constraint) and the PGlite integration test (AC7).
  • PSL physical table resolution. The PSL interpreter only receives the names of composed extension spaces, not their contracts, so it cannot resolve supabase:auth.User to the physical table users on its own. It carries the symbolic coordinate (space + namespace + columns) with the table held as modelName.toLowerCase(), and the authoritative model name survives on the relation. M3 resolves the real table against the loaded aggregate, where the extension contracts are available. A PSL↔TS parity test pins the interim user-vs-users divergence with an assertion M3 flips. (The TS path resolves eagerly because the extension author supplies the table in the handle.)
  • Walking-skeleton wiring. Adding the Profile.userId → auth.User.id FK to examples/supabase plus the cascade-delete test needs the planner, so it lands in M3.

Verification

Full local validation is green after a clean build: pnpm typecheck 138/138, pnpm lint 79/79, pnpm lint:deps clean, pnpm lint:casts delta 0 (no new bare casts), pnpm fixtures:check clean (no fixture churn). Package suites all pass: sql-contract-ts 295, emitter 165, sql-orm-client 514 (+3 skipped), extension-supabase 18, psl-parser 97, sql-contract-psl 222, psl-printer 32.

Acceptance criteria advanced: AC1 (TS cross-space FK + non-navigable relation, real supabase handles), AC2 (PSL form lowers + round-trips, symbolic coordinate), AC4 (cascade, no diagnostic), AC5 (missing-pack fail-fast, TS + PSL), plus AC9 (existing local-FK tests unchanged) and AC10 (no new layering / casts). AC3 authoring half is done; its DDL half and AC7 are M3.

Upgrade declaration

Per the in-repo record-upgrade-instructions skill: the substrate diff under packages/3-extensions/ is purely additive for extension authors (new extensionModel(...) factory, new optional fields on TargetFieldRef / CrossReference / PslField, new @prisma-next/extension-supabase/contract subpath; nothing removed or renamed). The per-PR declaration was recorded in skills/extension-author/prisma-next-extension-upgrade/upgrades/0.12-to-0.13/instructions.md — changes: [] (incidental), with a TML-2500-keyed note in the existing comment block describing why the substrate diff is no-op for existing extensions. pnpm check:upgrade-coverage --mode pr passes.

Alternatives considered

  • A separate refExt / belongsToExternal call instead of the brand. Rejected: it would duplicate the signal already carried by the import line and force users to learn a second ergonomics. The brand keeps one call shape.
  • Omitting cross-space relations from the generated types rather than typing them as never. Both make include impossible; never gives a clearer compiler error ("Type 'true' is not assignable to type 'never'") than a silently-missing key.
  • Exposing the ContractModelBuilder class as a value so extensions could new it directly (the first attempt did this). Rejected for the extensionModel(...) factory — it keeps the implementing class private and the public surface small, matching the interface-plus-factory convention.
  • Resolving the PSL target's physical table eagerly in the interpreter by plumbing the extension contracts in. Deferred to M3: resolution belongs at the loaded-aggregate boundary, and forcing it into the per-contract interpreter would widen this slice's scope into M3's.
  • A PSL use … as aliasing directive. Reserved as future-additive; implicit resolution via extensionPacks is the canonical path and ships now. Aliasing is added only if real name collisions appear.

Refs TML-2500.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Support for relations to models in other contract spaces via a colon-prefix (space:namespace.Model) syntax.
    • Supabase contract handles (AuthUser, AuthIdentity, StorageBucket, StorageObject) are now exported for reuse.
    • Parser and printer updated to preserve qualified field type references.
  • Improvements

    • Cross-space relations emit as non-navigable in the ORM client for safer includes/queries.
    • Contract builder and lowering now support cross-space foreign keys and relations with validation and clearer diagnostics.
  • Tests

    • Extensive test coverage added for parsing, printing, lowering, and cross-space FK/relation behaviors.

wmadden and others added 9 commits June 7, 2026 11:42
Author the M2 (Authoring surfaces) slice spec and 5-dispatch decomposition
from a fresh read-only investigation of the current authoring code. Carry the
post-compaction status section in plan.md.

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

- Add `TSpaceId` phantom brand to `ColumnRef` and `TargetFieldRef` so local
  model refs carry `'<self>'` and extension handles carry their `spaceId`.
- Add `spaceId` parameter to `ContractModelBuilder` constructor; token refs
  for cross-space handles include `spaceId`, `namespaceId`, and `tableName`.
- Add `targetSpaceId?`, `targetNamespaceId?`, `targetTableName?` to
  `ForeignKeyConstraint` and propagate from `normalizeTargetFieldRefInput`.
- Add `spaceId?` to `ForeignKeyNode.references` (contract-definition.ts).
- Relax local-model gates: `lowerCrossSpaceForeignKeyNode` handles cross-space
  FKs by carrying the brand coordinate through instead of requiring a local
  model lookup; `lowerLocalForeignKeyNode` is the renamed local path.
- Add `assertKnownExtensionPack` fail-fast: throws with the pack name and
  `extensionPacks` hint when a cross-space FK references an undeclared space.
- Thread `extensionPacks` from `buildContractDefinition` → `lowerModels` →
  `resolveModelNode` → `resolveForeignKeyNodes` so the check has access.
- Relax `assertKnownTargetModel` gate in `build-contract.ts` for cross-space
  FKs: when `fk.references.spaceId` is present, bypass the local model lookup
  and pass `spaceId` into the storage `ForeignKeyReference`.
- `onDelete:'cascade'` on a cross-space FK lowers without error (AC4).
- Local FKs are unchanged — no `spaceId` on their storage `ForeignKeyReference`
  (NFR2 byte-identity).
- 8 new tests in `test/cross-space-fk.test.ts`; all 286 package tests pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
F1 — brand survives chaining: forward `this.spaceId` and `this.tableName`
through `ContractModelBuilder.relations()`, `.attributes()`, and `.sql()`,
and propagate the `TSpaceId` type parameter on their return types. Two new
tests assert both runtime (`spaceId`/`tableName`) and type-level brand
after `.sql()` and `.relations().sql()` chains.

F3 — carry real tableName: thread `tableName` into the cross-space
coordinate in the constructor and extract it from the static sql spec in
`.sql()`. The `buildSyntheticSupabaseAuthUser` fixture now chains
`.sql({ table: 'users' })`, making the `tableName === 'users'` assertion
non-coincidental (model name `User` would lowercase to `user`).

F2 — remove dead ColumnRef brand: drop the `TSpaceId` type parameter and
`_spaceId?` property from `ColumnRef`. The functional brand lives entirely
on `TargetFieldRef` and is unchanged.

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

Thread spaceId/namespaceId through BelongsToRelation, RelationNode, and
CrossReference. Relax lowerBelongsToRelation for branded cross-space targets
(with assertKnownExtensionPack fail-fast). In build-contract, emit a cross-space
relation's CrossReference with the target spaceId. In the emitter, cross-space
relations (to.space present) are emitted as `never` in the .d.ts relations block
so that include() of them is a compile error. RelationNames in the ORM client
filters out never-typed entries to match.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Add the /contract subpath to @prisma-next/extension-supabase so apps can
import { AuthUser } from '@prisma-next/extension-supabase/contract' and use
the handle in rel.belongsTo and constraints.foreignKey.

- src/contract/handles.ts: branded ContractModelBuilder instances for
  AuthUser (auth/users), AuthIdentity (auth/identities), StorageBucket
  (storage/buckets), StorageObject (storage/objects) — each carrying
  spaceId:'supabase' and the real namespace, table, and columns.
- src/exports/contract.ts: re-export barrel consumed by the /contract dist.
- package.json exports: add ./contract entry with types+import pointing to
  dist/contract.{d.mts,mjs}.
- tsdown.config.ts: add contract entry to the build config.
- architecture.config.json: register src/contract/** and
  src/exports/contract.ts as extensions/adapters/shared so lint:deps passes.
- Move @prisma-next/sql-contract-ts from devDependencies to dependencies
  since handles.ts is a shipped public API that imports from it.
- Export ContractModelBuilder as a value (not just a type) from
  @prisma-next/sql-contract-ts/contract-builder so extension packages can
  instantiate it in their public handles files.
- Export TargetFieldRef as a type from the same public API.
- Test: 3 suites (16 tests) covering brand/coordinate assertions, lowering
  smoke test (AC1 — real supabasePack, FK + relation), and handle↔contract
  consistency.

Gate: build pass, 16/16 tests pass, typecheck clean (supabase + sql-ct;
adapter-sqlite/postgres pre-existing worktree misses not regressions),
lint 79/79, lint:deps pass, lint:casts delta=0, fixtures no-churn.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
F1 (must-fix): the four supabase handles declared modelName as
User/Identity/Bucket/Object, but the shipped contract uses AuthUser/
AuthIdentity/StorageBucket/StorageObject. This caused the cross-space
relation to lower to.model='User' — a model that does not exist in the
supabase space — and typed refs as TargetFieldRef<'User',…>.

Fix: rename all four modelName values to the real domain model names.
Extend the handle↔contract.json consistency test to also assert modelName
matches the contract.json key, so future drift is caught. Update the
TargetFieldRef type assertion and the lowering smoke test's to.model
assertion from 'User' to 'AuthUser'.

F2 (should-fix): handles were built via new ContractModelBuilder(…),
requiring the class to be a value export from the public contract-builder
entrypoint (against the interface-plus-factory rule and minimize-public-
surface convention).

Fix: add extensionModel(name, {namespace, fields, table}, spaceId) factory
to contract-dsl.ts. It constructs ContractModelBuilder internally with the
tableName threaded directly as the 5th constructor arg (no sql factory
needed, no cast). Export it as a value from contract-builder.ts and the
public exports/contract-builder.ts entrypoint. Route all four supabase
handles through it. Revert ContractModelBuilder to type-only on all three
export paths; the class remains an exported class from contract-dsl.ts for
internal package use.

Tests: 18/18 supabase (was 16 — 2 new factory tests added), 295/295
sql-contract-ts, 138/138 typecheck, 79/79 lint, lint:deps clean,
lint:casts delta=0, fixtures:check exit 0.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
- Add typeContractSpaceId? to PslField (psl-ast.ts) alongside existing typeNamespaceId
- Extend parseField to recognize <space>:<ns>.<Name> and <space>:<Name> forms
- Interpreter: emit PSL_UNKNOWN_CONTRACT_SPACE when space not in composedExtensionPacks (AC5)
- Interpreter: cross-space FK carries spaceId + namespaceId; target table is a symbolic
  fallback (fieldTypeName.toLowerCase()) pending M3 resolution against extension contract
- Interpreter: cross-space RelationNode bypasses local back-relation matching pipeline
- psl-field-resolution: skip cross-space @relation fields in collectResolvedFields
- Tests: 7 parser tests + 4 interpreter tests + 1 parity test covering happy path, no-ns form
  (namespaceId=__unbound__), missing-pack diagnostic, cascade, and PSL/TS divergence doc

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… (space:ns.Name)

Scope note: also fixes the pre-existing TML-2459 printer gap where fields with
typeNamespaceId (e.g. auth.User) round-tripped back to bare typeName (User) — the
same code path, and AC2 round-trip depends on the qualifier being preserved.

Add assembleQualifiedTypeName helper in ast-to-print-document.ts that builds the
four forms from the PslField qualifiers:
  - typeContractSpaceId + typeNamespaceId + typeName → space:ns.Name
  - typeContractSpaceId + typeName (no namespace) → space:Name
  - typeNamespaceId + typeName (no space) → ns.Name  ← TML-2459 fix
  - typeName only → Name

fieldToPrinterField now calls assembleQualifiedTypeName instead of using field.typeName
directly. typeConstructor rendering is unchanged. Line-wrap policy: keep the qualified
identifier on one line until the existing column limit (no special wrap at : or .;
project-spec open question; simplest readable default — noted in a comment).

Tests (TDD — written before the fix):
  - bare typeName: no qualifier (no regression)
  - typeNamespaceId=auth, typeName=User → auth.User (TML-2459 gap; was failing)
  - typeContractSpaceId=supabase + typeNamespaceId=auth → supabase:auth.User
  - typeContractSpaceId=supabase, no namespace → supabase:User
  - typeConstructor: unchanged (no regression)
  - parser→printer→parser round-trip for supabase:auth.User field (AC2)

Gate: build=pass, tests=32/32 (psl-printer), typecheck=pass (psl-printer +
framework-components + psl-parser direct; pre-existing Turbo cascade failure in
worktree unchanged), lint:deps=pass, lint:casts=delta=0 (1278), lint=79/79 tasks,
fixtures:check=no new churn (sql-builder failure pre-existing, confirmed by stash test).
No fixture churn from the typeNamespaceId fix — no existing fixture roundtrips
through the printer with a typeNamespaceId-bearing field.

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

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@wmadden-electric, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 18 minutes and 27 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: ea30b7c0-a1eb-4224-ac6d-b7bfccfa1680

📥 Commits

Reviewing files that changed from the base of the PR and between 6f3d19e and 0b42bb2.

📒 Files selected for processing (7)
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-definition.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-lowering.ts
  • packages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.ts
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.12-to-0.13/instructions.md
📝 Walkthrough

Walkthrough

This PR adds end-to-end cross-contract-space relation support: colon-prefixed space syntax parsing/printing, space-aware contract/AST types, emitter changes to mark cross-space relations non-navigable, TS DSL branding and extensionModel handles, lowering/build/runtime handling of cross-space FKs/relations with extensionPack validation, interpreter support, ORM type filtering, Supabase handles and packaging, and comprehensive tests.

Changes

Cross-Contract-Space Relations

Layer / File(s) Summary
Foundation: CrossReference and AST
packages/1-framework/0-foundation/contract/src/cross-reference.ts, packages/1-framework/1-core/framework-components/src/control/psl-ast.ts, packages/2-sql/2-authoring/contract-ts/src/contract-definition.ts
CrossReference gains optional space; PslField adds typeContractSpaceId; ForeignKeyNode/RelationNode gain optional spaceId/namespaceId for cross-space coordinates.
PSL parser: colon-prefix syntax
packages/1-framework/2-authoring/psl-parser/src/parser.ts, packages/1-framework/2-authoring/psl-parser/test/parser.test.ts
parseField supports space:... qualifiers, validates single-colon forms, and emits typeContractSpaceId in the AST; tests cover valid/invalid forms and list handling.
PSL printer: qualified type rendering
packages/1-framework/2-authoring/psl-printer/src/ast-to-print-document.ts, packages/1-framework/2-authoring/psl-printer/test/print-psl-from-ast.test.ts
New assembleQualifiedTypeName composes printed type qualifiers from typeContractSpaceId/typeNamespaceId/typeName; tests verify rendering and round-trip.
Emitter & ORM client types
packages/1-framework/3-tooling/emitter/src/domain-type-generation.ts, packages/3-extensions/sql-orm-client/src/types.ts, packages/1-framework/3-tooling/emitter/test/domain-type-generation.test.ts, packages/3-extensions/sql-orm-client/test/cross-space-relation.test-d.ts
Emitter includes optional space on cross references and emits never for cross-space relations; ORM RelationNames filters out never relations; tests validate emitted type behavior.
PSL interpreter: cross-space FK lowering
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts, packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts, packages/2-sql/2-authoring/contract-psl/test/interpreter.namespaces.test.ts
Interpreter skips cross-space relation fields during local field collection, validates extension packs for cross-space relations, emits FKs with spaceId and builds cross-space RelationNodes, rejects cross-space list relations, and merges cross-space relations into model relations; tests cover diagnostics and mappings.
TS DSL: extensionModel and cross-space branding
packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts, packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts, packages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.ts
Adds extensionModel factory, brands TargetFieldRef/ModelTokenRefs with TSpaceId, exposes physicalColumnName, threads spaceId/tableName through builders and belongsTo detection, and re-exports new API symbols.
TS lowering & build: cross-space branches
packages/2-sql/2-authoring/contract-ts/src/contract-lowering.ts, packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
Lowering and build detect spaceId on relations/FKs, validate extension packs, lower cross-space FKs/relations via specialized branches that preserve space/namespace coordinates and avoid local model/table validation.
Supabase extension: handles, exports, packaging
packages/3-extensions/supabase/src/contract/handles.ts, packages/3-extensions/supabase/src/exports/contract.ts, packages/3-extensions/supabase/package.json, packages/3-extensions/supabase/tsdown.config.ts, architecture.config.json
Adds branded Supabase extensionModel handles (AuthUser, AuthIdentity, StorageBucket, StorageObject), re-exports them at ./contract, updates package exports/deps and tsdown config, and maps sources in architecture config.
Comprehensive tests
multiple test files across parser/printer, emitter, PSL interpreter, TS DSL lowering, cross-space FK/relation suites, Supabase handle tests
Tests added/updated to cover parsing/printing, emitter type emission, interpreter lowering and diagnostics, TS DSL parity and lowering, cross-space FK behavior and validation, ORM typing, and Supabase handle consistency.

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • aqrln
  • wmadden

🐰 A space between models newfound so bright,
With colon-prefix syntax, cross-space in sight,
Relations leap across the contract bounds,
While nevered types keep safety sound,
Extension handles whisper: "welcome, friend!" ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.92% 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 and specifically describes the main feature: adding support for referencing another contract space in foreign keys using the colon-prefix syntax (e.g., supabase:auth.User), covering both TS and PSL authoring surfaces.
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 tml-2500-m2-authoring-surfaces

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

❤️ Share

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

wmadden and others added 2 commits June 7, 2026 14:30
The M2.3 supabase /contract handles moved @prisma-next/sql-contract-ts from
devDependencies to dependencies (handles instantiate at import time); regenerate
pnpm-lock.yaml so CI's --frozen-lockfile install passes.

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

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

# Conflicts:
#	pnpm-lock.yaml
@pkg-pr-new

pkg-pr-new Bot commented Jun 7, 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@752

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 0b42bb2

@github-actions

github-actions Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 146.89 KB (+0.52% 🔺)
postgres / emit 117.33 KB (+0.01% 🔺)
mongo / no-emit 76.11 KB (+0.03% 🔺)
mongo / emit 70.95 KB (+0.01% 🔺)
cf-worker / no-emit 176.75 KB (+0.48% 🔺)
cf-worker / emit 143.92 KB (+0.01% 🔺)

@wmadden-electric wmadden-electric changed the title TML-2500(M2): cross-contract-space FK references — authoring surfaces (TS brands + PSL grammar) TML-2500(M2): reference another contract space in a foreign key — e.g. Profile.user → supabase:auth.User (TS + PSL authoring) Jun 7, 2026

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

Caution

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

⚠️ Outside diff range comments (2)
packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts (1)

694-717: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate cross-space coordinates across compound target refs.

normalizeTargetFieldRefInput() only checks modelName. A compound FK target can therefore mix refs that share a model name but disagree on spaceId, namespaceId, or tableName, and this code will silently inherit the first ref's coordinates. That lowers an impossible foreign key instead of rejecting the input up front.

Suggested guard
   if (refs.some((ref) => ref.modelName !== first.modelName)) {
     throw new Error('All target refs in a foreign key must point to the same model');
   }
+  if (
+    refs.some(
+      (ref) =>
+        ref.spaceId !== first.spaceId ||
+        ref.namespaceId !== first.namespaceId ||
+        ref.tableName !== first.tableName,
+    )
+  ) {
+    throw new Error(
+      'All target refs in a foreign key must share the same contract-space coordinates.',
+    );
+  }
   return {
🤖 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/2-sql/2-authoring/contract-ts/src/contract-dsl.ts` around lines 694
- 717, normalizeTargetFieldRefInput currently only validates modelName across
refs but can silently accept conflicting coordinates; update the function to
validate that all refs also agree on spaceId, namespaceId, and tableName
(compare each ref's spaceId/namespaceId/tableName to
first.spaceId/first.namespaceId/first.tableName) and throw an Error with a clear
message if any mismatch is found, preserving the existing return shape
(modelName, fieldNames, source, spaceId, namespaceId, tableName).
packages/2-sql/2-authoring/contract-ts/src/contract-lowering.ts (1)

606-633: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Cross-space belongsTo().sql({ fk }) still falls back to the local-model path.

The new cross-space branch here only handles spec.sqlSpec?.foreignKeys. Relation-derived FKs are still built earlier via resolveRelationForeignKeys(), which requires the target model to exist in allSpecs. So rel.belongsTo(ExtUser, ...).sql({ fk: {...} }) still throws "unknown model" even when extensionPacks.supabase is declared. This path needs to stamp targetSpaceId / targetNamespaceId / targetTableName onto relation-derived FKs before they reach this lowering step.

🤖 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/2-sql/2-authoring/contract-ts/src/contract-lowering.ts` around lines
606 - 633, resolveRelationForeignKeys() produces relation-derived ForeignKey
objects without cross-space metadata, so resolveForeignKeyNodes() still treats
rel.belongsTo(...).sql({ fk }) as local and throws when the target model isn't
in allSpecs; fix by stamping cross-space fields onto relation-derived foreign
keys before lowering: when mapping the result of
resolveRelationForeignKeys(spec, allSpecs) check each foreignKey for a
cross-space reference (use extensionPacks and assertKnownExtensionPack with
foreignKey.targetModel or any ext-ref present on the relation), populate
targetSpaceId/targetNamespaceId/targetTableName on that ForeignKey object, and
then call lowerCrossSpaceForeignKeyNode(...) instead of
lowerLocalForeignKeyNode; update resolveForeignKeyNodes to branch on the
presence of targetSpaceId (same gating used for spec.sqlSpec?.foreignKeys) so
lowerLocalForeignKeyNode and lowerCrossSpaceForeignKeyNode are invoked
appropriately.
🧹 Nitpick comments (1)
packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts (1)

1126-1130: ⚡ Quick win

Replace the new bare casts with the repo-approved cast helpers.

These new cross-space builder paths add bare as casts in production code even though this file already imports blindCast. Please switch the added casts to blindCast(...)/castAs(...) so the no-bare-cast rule does not regress here.

As per coding guidelines, **/*.{ts,tsx} must avoid bare as in production code; based on learnings, use blindCast<T, "Reason"> or castAs<T> instead.

Also applies to: 1233-1239

🤖 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/2-sql/2-authoring/contract-ts/src/contract-dsl.ts` around lines 1126
- 1130, Replace the bare "as" casts added around the cross-space builder refs
with the repo-approved cast helpers: wrap the result of
createModelTokenRefs(...) in blindCast or castAs so you don't use a bare as on
this.refs; for example, convert the expression currently cast to ModelName
extends string ? ModelTokenRefs<ModelName, Fields, TSpaceId> to
blindCast<ModelTokenRefs<ModelName, Fields, TSpaceId>, "Cross-space refs">(...)
or castAs<ModelTokenRefs<ModelName, Fields, TSpaceId>>(...). Apply the same
replacement for the similar bare casts around the other occurrences (the block
around lines 1233-1239) referencing createModelTokenRefs, ModelTokenRefs,
ModelName, Fields, and TSpaceId.

Sources: Coding guidelines, Learnings

🤖 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/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 968-970: The branch that silently continues when
relationAttribute.field.list is true must instead detect cross-space relations
and reject them with a diagnostic: inside the block that currently does "if
(relationAttribute.field.list) { continue; }" (in interpreter.ts handling
relationAttribute), add a check for whether the relation is cross-space (use the
same cross-space condition used later in cross-space handling) and, if true,
emit a diagnostic/error (e.g. via the project’s diagnostic/reporting utility)
rejecting the authored cross-space list relation; only keep the early continue
for non-cross-space list relations after emitting the diagnostic.

In `@packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts`:
- Around line 917-950: The createModelTokenRefs function builds cross-space
TargetFieldRef objects but omits the resolved remote/physical column name,
causing FK lowering to target logical field names; update createModelTokenRefs
to capture and include the resolved remote column mapping (e.g., add a property
like remoteColumn or physicalColumn) onto each TargetFieldRef when
crossSpaceCoordinate is provided and when the field builder defines a custom
column/sql mapping; ensure the new property is present in the returned
ModelTokenRefs type so downstream lowering that reads targetFields ->
references.columns can use the physical column name instead of the logical
fieldName.
- Around line 1587-1599: The cross-space coordinate logic uses
isCrossSpaceHandle(toModel) but fails for lazy tokens (functions) like
rel.belongsTo(() => ExtUser, ...); resolve the lazy token first: if toModel is a
function, call it to get the actual model token, then run
isCrossSpaceHandle(resolvedModel) and extract spaceId/tableName/namespace from
that resolved token when computing crossSpaceCoordinate (update references to
use resolvedModel instead of raw toModel).

---

Outside diff comments:
In `@packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts`:
- Around line 694-717: normalizeTargetFieldRefInput currently only validates
modelName across refs but can silently accept conflicting coordinates; update
the function to validate that all refs also agree on spaceId, namespaceId, and
tableName (compare each ref's spaceId/namespaceId/tableName to
first.spaceId/first.namespaceId/first.tableName) and throw an Error with a clear
message if any mismatch is found, preserving the existing return shape
(modelName, fieldNames, source, spaceId, namespaceId, tableName).

In `@packages/2-sql/2-authoring/contract-ts/src/contract-lowering.ts`:
- Around line 606-633: resolveRelationForeignKeys() produces relation-derived
ForeignKey objects without cross-space metadata, so resolveForeignKeyNodes()
still treats rel.belongsTo(...).sql({ fk }) as local and throws when the target
model isn't in allSpecs; fix by stamping cross-space fields onto
relation-derived foreign keys before lowering: when mapping the result of
resolveRelationForeignKeys(spec, allSpecs) check each foreignKey for a
cross-space reference (use extensionPacks and assertKnownExtensionPack with
foreignKey.targetModel or any ext-ref present on the relation), populate
targetSpaceId/targetNamespaceId/targetTableName on that ForeignKey object, and
then call lowerCrossSpaceForeignKeyNode(...) instead of
lowerLocalForeignKeyNode; update resolveForeignKeyNodes to branch on the
presence of targetSpaceId (same gating used for spec.sqlSpec?.foreignKeys) so
lowerLocalForeignKeyNode and lowerCrossSpaceForeignKeyNode are invoked
appropriately.

---

Nitpick comments:
In `@packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts`:
- Around line 1126-1130: Replace the bare "as" casts added around the
cross-space builder refs with the repo-approved cast helpers: wrap the result of
createModelTokenRefs(...) in blindCast or castAs so you don't use a bare as on
this.refs; for example, convert the expression currently cast to ModelName
extends string ? ModelTokenRefs<ModelName, Fields, TSpaceId> to
blindCast<ModelTokenRefs<ModelName, Fields, TSpaceId>, "Cross-space refs">(...)
or castAs<ModelTokenRefs<ModelName, Fields, TSpaceId>>(...). Apply the same
replacement for the similar bare casts around the other occurrences (the block
around lines 1233-1239) referencing createModelTokenRefs, ModelTokenRefs,
ModelName, Fields, and TSpaceId.
🪄 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: 2f5d1b95-5914-4d7d-8c4d-e653aa913e3d

📥 Commits

Reviewing files that changed from the base of the PR and between 90574dc and b59f5e8.

⛔ Files ignored due to path filters (4)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/cross-contract-refs/plan.md is excluded by !projects/**
  • projects/cross-contract-refs/slices/M2/plan.md is excluded by !projects/**
  • projects/cross-contract-refs/slices/M2/spec.md is excluded by !projects/**
📒 Files selected for processing (28)
  • architecture.config.json
  • packages/1-framework/0-foundation/contract/src/cross-reference.ts
  • packages/1-framework/1-core/framework-components/src/control/psl-ast.ts
  • packages/1-framework/2-authoring/psl-parser/src/parser.ts
  • packages/1-framework/2-authoring/psl-parser/test/parser.test.ts
  • packages/1-framework/2-authoring/psl-printer/src/ast-to-print-document.ts
  • packages/1-framework/2-authoring/psl-printer/test/print-psl-from-ast.test.ts
  • packages/1-framework/3-tooling/emitter/src/domain-type-generation.ts
  • packages/1-framework/3-tooling/emitter/test/domain-type-generation.test.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.namespaces.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/psl-ts-namespace-parity.test.ts
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-definition.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-lowering.ts
  • packages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.ts
  • packages/2-sql/2-authoring/contract-ts/test/cross-space-fk.test.ts
  • packages/2-sql/2-authoring/contract-ts/test/cross-space-relation.test.ts
  • packages/3-extensions/sql-orm-client/src/types.ts
  • packages/3-extensions/sql-orm-client/test/cross-space-relation.test-d.ts
  • packages/3-extensions/supabase/package.json
  • packages/3-extensions/supabase/src/contract/handles.ts
  • packages/3-extensions/supabase/src/exports/contract.ts
  • packages/3-extensions/supabase/test/contract-handles.test.ts
  • packages/3-extensions/supabase/tsdown.config.ts

F-list (PSL): cross-space list relation fields (e.g. `posts supabase:auth.Post[]`)
were silently dropped. Now emits PSL_UNSUPPORTED_CROSS_SPACE_LIST diagnostic so
authors know the field was rejected rather than silently ignored.

F-col (TS): cross-space FK target columns used the logical field name instead of
the physical column name when the extension handle used `.column('name')`. Fixed by:
- adding `physicalColumnName` getter on ScalarFieldBuilder
- adding optional `columnName` field to TargetFieldRef
- populating `columnName` in createModelTokenRefs for cross-space coordinates
- using `columnName ?? fieldName` in normalizeTargetFieldRefInput

F-lazy (TS): `rel.belongsTo(() => ExtUser, …)` (lazy thunk form) did not detect
the cross-space brand because isCrossSpaceHandle checked the thunk function, not
what it returns. Fixed by resolving the thunk before the brand check.

F-compound (TS): compound FK refs mixing different spaceId/namespaceId/tableName
values (same modelName but different spaces) silently inherited the first ref's
coordinate. Fixed by validating all refs in normalizeTargetFieldRefInput share
the same cross-space coordinate.

F-relfk (TS): a belongsTo with .sql({ fk }) on a cross-space target threw
"unknown model" because resolveRelationForeignKeys only knew the local allSpecs
lookup. Fixed by: stamping targetSpaceId/namespaceId/tableName onto the FK when
relation.spaceId is set, and routing relation-derived cross-space FKs through
lowerCrossSpaceForeignKeyNode in resolveForeignKeyNodes.

F-casts (TS): two bare `as` casts added in M2.1 replaced with blindCast calls.
Cast delta: -2 (1276 vs 1278 at merge-base).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric

Copy link
Copy Markdown
Contributor Author

Addressed all six CodeRabbit findings in commit 6f3d19eb4 (M2.6 — cross-space coverage hardening). Each fix is TDD (failing test, then fix). Full gate green: typecheck 138/138, lint 79/79, lint:deps clean, lint:casts delta = −2 (the two new bare casts called out in the nitpick are now blindCast), fixtures:check no churn.

Inline threads (resolved on this PR):

  • F-list — PSL cross-space list relations now emit PSL_UNSUPPORTED_CROSS_SPACE_LIST instead of being silently dropped (interpreter.ts — cross-space check now runs before the field.list early-continue).
  • F-col — cross-space refs now carry the physical column name via new TargetFieldRef.columnName? + a minimal ScalarFieldBuilder.physicalColumnName getter; the lowering reader prefers columnName ?? fieldName. Non-coincidental test: logical userId vs physical physical_id.
  • F-lazy — rel.belongsTo(() => ExtUser, …) resolves the thunk before the brand check, so the lazy form keeps the cross-space brand.

Outside-diff comments (no thread to resolve — flagging here):

  • F-compound — normalizeTargetFieldRefInput now validates spaceId/namespaceId/tableName consistency across compound FK refs (was only checking modelName). Error message names the mismatched coordinate. Test: two handles with same modelName but different spaceIds.
  • F-relfk — rel.belongsTo(ExtUser, …).sql({ fk: {…} }) no longer falls through to the local lookup. resolveRelationForeignKeys stamps cross-space metadata when relation.spaceId !== undefined; resolveForeignKeyNodes routes via targetSpaceId !== undefined to assertKnownExtensionPack + lowerCrossSpaceForeignKeyNode. Test confirms the FK lowers with target.spaceId === 'supabase' and onDelete: 'cascade' survives.

Nitpick:

  • F-casts — the two new bare as casts in contract-dsl.ts are now blindCast<T, "reason">(…) with meaningful reason strings. Cast ratchet delta = −2.

All six fixes confined to contract-ts + contract-psl. No printer / planner / verifier / skeleton changes; no new public exports beyond the strict minimum each finding required.

wmadden and others added 2 commits June 7, 2026 16:26
The M2 substrate diff under packages/3-extensions/ (sql-orm-client RelationNames
filter + supabase /contract export with branded handles) is purely additive for
extension authors: no public API was removed or renamed; new factory + optional
fields on TargetFieldRef/CrossReference/PslField are opt-in; existing extensions
ship zero cross-space relations and are unaffected by the Option B emitter.
Recording the per-PR declaration so check:upgrade-coverage passes.

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

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

# Conflicts:
#	packages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.ts
@wmadden
wmadden merged commit 13cd3a3 into main Jun 7, 2026
20 checks passed
@wmadden
wmadden deleted the tml-2500-m2-authoring-surfaces branch June 7, 2026 14:40
wmadden-electric added a commit that referenced this pull request Jun 8, 2026
…orkspace (TML-2500 M4) (#770)

This is the documentation + close-out milestone (M4) for the
cross-contract-refs project. All four implementation milestones have
merged — M1 #745, M2 #752, M3a #756, M3b #765 — shipping
cross-contract-space foreign-key references end-to-end. This PR migrates
the project's durable knowledge into the canonical doc surfaces, records
the project as shipped in the umbrella tracker, lands the final-retro
lessons, and deletes the transient project workspace.

## What shipped (recap, for the reader without context)

An app contract can now declare a foreign key from a local model to a
model owned by an *extension's* contract space. The headline example,
live in `examples/supabase`:

```prisma
types {
  Uuid = String @db.Uuid
}

namespace public {
  model Profile {
    id     String @id @default(uuid())
    userId Uuid   @unique
    user   supabase:auth.AuthUser @relation(fields: [userId], references: [id], onDelete: Cascade)
    @@Map("profile")
  }
}
```

The planner lowers this to a real Postgres FK (`REFERENCES
"auth"."users"("id") ON DELETE CASCADE`), and a hermetic integration
test proves the cascade fires against a live database.

## Where the knowledge landed (M4.1)

The design knowledge that lived in the transient
`projects/cross-contract-refs/` workspace migrated to three canonical,
self-contained surfaces:

- **Subsystem doc** — a new "Cross-contract FK references" subsection in
`docs/architecture docs/subsystems/6. Ecosystem Extensions & Packs.md`
(the extension hub). Records the *current shape*: the presence-based
optional `spaceId` discriminator on `ForeignKeyReference`,
dependency-graph construction, namespace-ownership rules, the
aggregate-loader resolution rule, and the `__unbound__`
DDL-qualification consequence.
- **ADR 226** — `docs/architecture docs/adrs/ADR 226 - Cross-contract
foreign-key references.md`. Records the *decisions*: presence-based
discrimination (chosen so local-FK JSON stays byte-identical), implicit
`extensionPacks` resolution, the DAG + reverse-reference rejection,
namespace ownership, Option-B non-navigable relations, the colon-prefix
PSL grammar, and no-diagnostic cascade. Cross-links ADR 212 / 221 / 225.
- **Authoring rulecard** —
`.agents/rules/cross-contract-fk-authoring.mdc`. The actionable Do/Don't
for authoring a cross-contract FK, including the hard-won M3b lesson
that the FK source column must match the target's native type (`types {
Uuid = String @db.Uuid }`), and that `@db.X` is type-constructor syntax
(only valid inside a `types {}` block), not a field attribute.

## Bookkeeping (M4.2)

- The umbrella tracker (`projects/supabase-integration/README.md`)
status row flipped to ✅ **Done & closed** with the four PR links, and
its link repointed from the (now-deleted) project spec to the durable
subsystem doc.
- The one durable dangling link —
`packages/3-extensions/supabase/README.md` pointing into the project dir
— repointed to ADR 226 / the subsystem doc.

## Final retro (M4.3)

Per the mandatory-final-retro invariant, the process lessons from this
project's execution landed in durable `drive/` calibration surfaces:

- `drive/spec/README.md` — spec illustrative snippets (PSL grammar, IR
shapes) must be re-verified against shipped code before execution, not
copied as fact. (This project hit it four times.)
- `drive/calibration/model-tier.md` — a worked example confirming the
existing "pin the dispatch tier explicitly, don't inherit" rule.
- `drive/calibration/dod.md` — test-dispatch briefs need a "claims
preserved" acceptance criterion: state what the test proves, on the
right surface.

## Definition of Done — verified

| AC | Status | Evidence |
|----|--------|----------|
| AC1 (TS cross-contract ref, non-navigable) | ✅ | M2 #752 |
| AC2 (PSL cross-contract ref, round-trip) | ✅ | M2 #752 + M3a #756 |
| AC3 (`__unbound__` unqualified REFERENCES) | ✅ | M3a #756 |
| AC4 (cascade permitted, DDL has ON DELETE CASCADE) | ✅ | M2 #752 + M3b
#765 |
| AC5 (missing-pack diagnostic, both surfaces) | ✅ | M2 #752 |
| AC6 (primitive collision + cycle rejection) | ✅ | M1 #745 |
| AC7 (live FK in `pg_constraint`, verifier clean) | ✅ | M3a #756 + M3b
#765 |
| AC8 (round-trip property test) | ✅ | M1 #745 |
| AC9 (TML-2459 local FK tests unchanged) | ✅ | all milestones |
| AC10 (`pnpm lint:deps` clean) | ✅ | all milestones |

All slices merged; mandatory final retro complete; durable docs landed;
no open ADRs blocking.

## Deletion

`projects/cross-contract-refs/` is removed. Verified before deletion:
trace integrity passes (89 events, 9 dispatches, all round/dispatch
pairs matched); no durable file (`packages/`, `examples/`, `docs/`,
`.agents/`) references the deleted path; `pnpm build` + `pnpm typecheck`
unaffected (nothing imports from `projects/`). References to
cross-contract-refs that remain in *other* project workspaces
(`supabase-integration`, `postgres-rls`, etc.) are
transient-to-transient and get cleaned at those projects' own
close-outs.

## Validation

- `pnpm typecheck`: 138/138
- `pnpm lint`: 79/79
- `pnpm lint:rules:symlinks`: clean (the new rulecard wired)
- `pnpm build`: clean

Refs: TML-2500.

🤖 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 comprehensive guidance for cross-contract foreign-key
references, including authoring conventions and architectural design
decisions.
* Updated ecosystem extensions documentation with cross-contract
reference patterns and resolution behavior.
* Enhanced calibration and code verification documentation with improved
guidance for test authoring and snippet validation.

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

---------

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