Repository navigation
TML-2500(M2): reference another contract space in a foreign key — e.g. Profile.user → supabase:auth.User (TS + PSL authoring) - #752
Conversation
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]>
Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
|
Warning Review limit reached
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 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 configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (7)
📝 WalkthroughWalkthroughThis 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. ChangesCross-Contract-Space Relations
🎯 4 (Complex) | ⏱️ ~60 minutes Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
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
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
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 winValidate cross-space coordinates across compound target refs.
normalizeTargetFieldRefInput()only checksmodelName. A compound FK target can therefore mix refs that share a model name but disagree onspaceId,namespaceId, ortableName, 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 winCross-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 viaresolveRelationForeignKeys(), which requires the target model to exist inallSpecs. Sorel.belongsTo(ExtUser, ...).sql({ fk: {...} })still throws"unknown model"even whenextensionPacks.supabaseis declared. This path needs to stamptargetSpaceId/targetNamespaceId/targetTableNameonto 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 winReplace the new bare casts with the repo-approved cast helpers.
These new cross-space builder paths add bare
ascasts in production code even though this file already importsblindCast. Please switch the added casts toblindCast(...)/castAs(...)so the no-bare-cast rule does not regress here.As per coding guidelines,
**/*.{ts,tsx}must avoid bareasin production code; based on learnings, useblindCast<T, "Reason">orcastAs<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
⛔ Files ignored due to path filters (4)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/cross-contract-refs/plan.mdis excluded by!projects/**projects/cross-contract-refs/slices/M2/plan.mdis excluded by!projects/**projects/cross-contract-refs/slices/M2/spec.mdis excluded by!projects/**
📒 Files selected for processing (28)
architecture.config.jsonpackages/1-framework/0-foundation/contract/src/cross-reference.tspackages/1-framework/1-core/framework-components/src/control/psl-ast.tspackages/1-framework/2-authoring/psl-parser/src/parser.tspackages/1-framework/2-authoring/psl-parser/test/parser.test.tspackages/1-framework/2-authoring/psl-printer/src/ast-to-print-document.tspackages/1-framework/2-authoring/psl-printer/test/print-psl-from-ast.test.tspackages/1-framework/3-tooling/emitter/src/domain-type-generation.tspackages/1-framework/3-tooling/emitter/test/domain-type-generation.test.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.namespaces.test.tspackages/2-sql/2-authoring/contract-psl/test/psl-ts-namespace-parity.test.tspackages/2-sql/2-authoring/contract-ts/src/build-contract.tspackages/2-sql/2-authoring/contract-ts/src/contract-builder.tspackages/2-sql/2-authoring/contract-ts/src/contract-definition.tspackages/2-sql/2-authoring/contract-ts/src/contract-dsl.tspackages/2-sql/2-authoring/contract-ts/src/contract-lowering.tspackages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.tspackages/2-sql/2-authoring/contract-ts/test/cross-space-fk.test.tspackages/2-sql/2-authoring/contract-ts/test/cross-space-relation.test.tspackages/3-extensions/sql-orm-client/src/types.tspackages/3-extensions/sql-orm-client/test/cross-space-relation.test-d.tspackages/3-extensions/supabase/package.jsonpackages/3-extensions/supabase/src/contract/handles.tspackages/3-extensions/supabase/src/exports/contract.tspackages/3-extensions/supabase/test/contract-handles.test.tspackages/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]>
|
Addressed all six CodeRabbit findings in commit Inline threads (resolved on this PR):
Outside-diff comments (no thread to resolve — flagging here):
Nitpick:
All six fixes confined to |
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
…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]>
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
Profilethat references Supabase'sauth.User:The same thing in PSL, where a colon marks the cross-space reference:
Both forms lower to the IR carrier M1 introduced (a foreign-key reference whose
spaceIdrecords which contract space owns the target). This PR is the authoring → IR half only. Emitting the actualREFERENCES "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:
refExt/belongsToExternal. You import a model handle from the extension and pass it to the samerel.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 theimportline.supabase:auth.User).@relation(...)is unchanged.include) is a compile-time error — we have not designed cross-space query traversal yet, and Supabase apps don't readauth.usersdirectly anyway.How it works, piece by piece
The carrier (recap from M1). A SQL foreign-key reference already carries
{ namespaceId, tableName, columns }. M1 added an optionalspaceId: 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 thatspaceIdfrom 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 theModel.refs.fieldreferences the FK call consumes (AuthUser.refs.idis typed for thesupabasespace), soconstraints.foreignKey/rel.belongsTocan 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/@relationsurface as a local one, and it carries the foreignspaceIdinto the domain layer. But the contract emitter renders it asneverin the generated relation types, so the ORM excludes it from theincludesurface: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-spaceincludeis rejected while a local one still compiles).Extension handles (decision 4, in detail).
@prisma-next/extension-supabasegains a/contractentry point exportingAuthUser,AuthIdentity,StorageBucket,StorageObjectas branded handles. These are built with a newextensionModel(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 newPslField.typeContractSpaceId, acceptingsupabase:auth.Userand the no-namespace formsupabase:User. The interpreter then threads that into the same carrier the TS path produces. A missing reference fails fast withPSL_UNKNOWN_CONTRACT_SPACE, naming the space and pointing atextensionPacks.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 plainauth.Userfield used to print back as bareUser. 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
REFERENCES, checking againstpg_constraint) and the PGlite integration test (AC7).supabase:auth.Userto the physical tableuserson its own. It carries the symbolic coordinate (space + namespace + columns) with the table held asmodelName.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 interimuser-vs-usersdivergence with an assertion M3 flips. (The TS path resolves eagerly because the extension author supplies the table in the handle.)Profile.userId → auth.User.idFK toexamples/supabaseplus the cascade-delete test needs the planner, so it lands in M3.Verification
Full local validation is green after a clean build:
pnpm typecheck138/138,pnpm lint79/79,pnpm lint:depsclean,pnpm lint:castsdelta 0 (no new bare casts),pnpm fixtures:checkclean (no fixture churn). Package suites all pass:sql-contract-ts295,emitter165,sql-orm-client514 (+3 skipped),extension-supabase18,psl-parser97,sql-contract-psl222,psl-printer32.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-instructionsskill: the substrate diff underpackages/3-extensions/is purely additive for extension authors (newextensionModel(...)factory, new optional fields onTargetFieldRef/CrossReference/PslField, new@prisma-next/extension-supabase/contractsubpath; nothing removed or renamed). The per-PR declaration was recorded inskills/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 prpasses.Alternatives considered
refExt/belongsToExternalcall instead of the brand. Rejected: it would duplicate the signal already carried by theimportline and force users to learn a second ergonomics. The brand keeps one call shape.never. Both makeincludeimpossible;nevergives a clearer compiler error ("Type 'true' is not assignable to type 'never'") than a silently-missing key.ContractModelBuilderclass as a value so extensions couldnewit directly (the first attempt did this). Rejected for theextensionModel(...)factory — it keeps the implementing class private and the public surface small, matching the interface-plus-factory convention.use … asaliasing directive. Reserved as future-additive; implicit resolution viaextensionPacksis 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
Improvements
Tests