Repository navigation
TML-2500(M3a): cross-contract-space FK references — planner + verifier + PSL aggregate resolution + AC7 PGlite test - #756
Conversation
Author the M3a (planner + verifier + PSL aggregate resolution + AC7 integration test) slice spec and 4-dispatch decomposition from a fresh read-only investigation of the planner / verifier / aggregate-loader substrate. Records the operator decision to split M3 into two PRs (M3a framework substrate, M3b user-visible glue). M3b's deferred items are recorded in the slice plan's open-items section so M3b can resume cold. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
At load time the CLI's aggregate loader now patches cross-space FK `target.tableName`s in the app contract with the real table names from the corresponding extension contracts. The PSL interpreter stored a symbolic `modelName.toLowerCase()` fallback (e.g. `'user'` for `supabase:auth.User`); the TS builder carried the real table name already. Both paths are now normalised to the real table name before the aggregate is handed to the planner / verifier / runtime. New pieces: - `resolve-cross-space-fk.ts` in migration-tools: exports `resolveCrossSpaceFkTableName` using only framework-level types (no SQL imports), two-step lookup: exact `storage.table` match (TS path) then `modelName.toLowerCase()` match (PSL path). - `contract-space-aggregate-loader.ts`: `resolveAppContractCrossSpaceFks` walks the app contract JSON after the integrity gate, patches any FK with `target.spaceId`, re-deserialises via `inputs.deserializeContract` to produce proper IR class instances. - Parity test flip (option a): `psl-ts-namespace-parity.test.ts:209-215` divergence assertion replaced — both PSL and TS resolve to `'users'` via a direct call to `resolveCrossSpaceFkTableName` with a synthetic extension contract (`User → table 'users'`). - 9 new unit tests for `resolveCrossSpaceFkTableName` covering exact match, model-name-lowercase match, namespace miss, and model miss diagnostics. Gate: migration-tools=567/567, psl=223/223, cli=1316/1316 (vitest direct; pnpm wrapper is pre-existing flaky), typecheck=135/138 (3 pre-existing adapter-postgres/sqlite/postgres worktree misses), lint=79/79, lint:deps=pass, lint:casts=delta0, fixtures:check=no-churn. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…tion test F-M3a.1-1: extend `resolveCrossSpaceFkTableName` with a 5th parameter `targetColumns: readonly string[]`. After resolving the table name, each column is checked against the storage namespace's column set. A missing column throws: `column "<col>" not found on target model "<name>" in space "<spaceId>" namespace "<nsId>"; available columns: <list>`. Empty `targetColumns` skips the check. The storage access uses `blindCast` (no bare `as`). The loader call site passes `fk.target.columns` via Array.isArray + blindCast filter. Five new unit tests in `resolve-cross-space-fk.test.ts` cover: all columns present, single missing column diagnostic, available-columns list in diagnostic, first-missing-column ordering, and empty-array skip. F-M3a.1-2: new test file `contract-space-aggregate-loader.cross-space-fk-resolution.test.ts` calls the real `buildContractSpaceAggregate` with a synthetic two-member aggregate and asserts: (1) the patching site resolves `tableName` from `'user'` to `'users'`; (2) the early-return path returns the same aggregate reference when there are no cross-space FKs. The `as unknown as` chain replaced with `blindCast`. Gate: build=pass, migration-tools=572/572, cli=1318/1318 (control-api flakiness is pre-existing, unrelated), psl=223/223, typecheck=138/138, lint=79/79, lint:deps=pass, lint:casts=delta0(1275), fixtures:check=exit0, upgrade-coverage=exit0. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Audit result: buildForeignKeySql (planner-ddl-builders.ts) is dead on the
production hot path — exported but uncalled. The live path is
issue-planner → AddForeignKeyCall → addForeignKey → renderForeignKeySql
which reads fk.references.schema (the target namespace) and is correct.
Changes:
- Add dead-path comment to buildForeignKeySql documenting the cross-schema
REFERENCES bug and the fact that no production code calls this path.
- New test file planner.cross-space-fk-ddl.test.ts pinning the correct
path's output: qualified REFERENCES "auth"."users"("id") for a named
target namespace, unqualified REFERENCES "users"("id") for __unbound__,
and a local-FK regression guard.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Three tests confirm verifyForeignKeys handles cross-space FKs identically to local ones — no production code change needed. The comparison block at verify-helpers.ts:196-212 was already target-table-agnostic: when referencedSchema and namespaceId are both set it compares the full (schema, table) pair; when either is absent it falls back to table-name-only comparison. - Happy path: public.profile.user_id → auth.users.id, matching introspected pg_constraint row → zero issues. - Mismatch: wrong referencedColumns → foreign_key_mismatch issue. - No missing_table for auth.users: the app verifier walks only contract.storage.namespaces (the app's namespace), so auth.users is never inspected and no MISSING_TABLE is emitted. Extended createSchemaTable helper with optional referencedSchema on foreignKeys entries so tests can represent cross-schema introspected FKs without constructing SqlForeignKeyIR directly. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…nt + dbVerify Closes AC7: a PGlite-backed integration test proves a cross-schema FK from public.profile.user_id → auth.users.id reaches PostgreSQL as a real constraint, is discoverable in pg_constraint, and the verifier returns zero issues. New test: packages/3-extensions/supabase/test/cross-contract-fk.integration.test.ts - Builds a synthetic app contract in-test with the TS builder (defineContract + Profile model + belongsTo(AuthUser) + constraints.foreignKey with onDelete: 'cascade') - Materialises supabase extension space + app space artefacts on disk - Bootstraps auth.* + storage.* external tables via bootstrapSupabaseShim - Runs CLI dbInit (apply mode) through the full planner pipeline - Queries pg_constraint cross-joined with pg_namespace/pg_class to assert the cross-schema FK exists, target column is 'id', confdeltype = 'c' - Runs dbVerify and asserts zero issues across both spaces Also fixes a pre-existing gap in validate-domain.ts: validateRelationTargets now skips cross-space relations (relation.to.space !== undefined) because their target models live in a different contract space and are absent from the local domain index by design. The aggregate verifier checks them at deploy time. 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]>
📝 WalkthroughWalkthroughThis PR implements cross-space foreign key resolution across the Prisma Next framework. The core change is replacing heuristic fallback (lowercasing model names) with explicit contract lookup: the PSL interpreter now requires a ChangesCross-space FK resolution integration
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
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 docstrings
🧪 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 |
@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: 2
🧹 Nitpick comments (1)
packages/3-extensions/supabase/test/cross-contract-fk.integration.test.ts (1)
28-28: ⚡ Quick winPrefer
patheovernode:pathfor path operations.Based on learnings, the repo prefers
pathefor path operations in all TypeScript files including tests. Replace this import with:-import { join } from 'node:path'; +import { join } from 'pathe';🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-extensions/supabase/test/cross-contract-fk.integration.test.ts` at line 28, The import currently brings join from node:path; replace that with pathe's API by importing join from 'pathe' instead (update the import statement that references join so tests use pathe's join). Ensure any usages of join in this file (e.g., in cross-contract-fk.integration.test.ts) continue to work with the pathe import.Source: 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
`@skills/extension-author/prisma-next-extension-upgrade/upgrades/0.12-to-0.13/instructions.md`:
- Around line 84-85: The test file path is split across lines
(`packages/3-extensions/supabase/test/cross-contract-fk.integration.` +
`test.ts`); update the line in instructions.md to contain the full filename as
one contiguous string (e.g.,
`packages/3-extensions/supabase/test/cross-contract-fk.integration.test.ts`) so
the referenced path is copy/paste-safe and matches the README/doc-maintenance
guidelines.
In `@wip/heartbeats/implementer.txt`:
- Around line 15-16: The two heartbeat entries for M3a.1 are out of
chronological order: the 2026-06-07T20:00:00Z "phase: exploration" entry
currently precedes the 2026-06-07T17:45:00Z "phase: gate-done" entry; reorder
these lines so the 17:45:00Z gate-done entry comes before the 20:00:00Z
exploration entry (or correct the 17:45:00Z timestamp if it was meant to be
later) to restore proper chronological sequencing in the heartbeat log.
---
Nitpick comments:
In `@packages/3-extensions/supabase/test/cross-contract-fk.integration.test.ts`:
- Line 28: The import currently brings join from node:path; replace that with
pathe's API by importing join from 'pathe' instead (update the import statement
that references join so tests use pathe's join). Ensure any usages of join in
this file (e.g., in cross-contract-fk.integration.test.ts) continue to work with
the pathe import.
🪄 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: ad3337ce-7593-403c-9356-040277cf1078
⛔ Files ignored due to path filters (5)
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/M3a/plan.mdis excluded by!projects/**projects/cross-contract-refs/slices/M3a/spec.mdis excluded by!projects/**
📒 Files selected for processing (15)
packages/1-framework/0-foundation/contract/src/validate-domain.tspackages/1-framework/3-tooling/cli/src/utils/contract-space-aggregate-loader.tspackages/1-framework/3-tooling/cli/test/utils/contract-space-aggregate-loader.cross-space-fk-resolution.test.tspackages/1-framework/3-tooling/migration/src/aggregate/resolve-cross-space-fk.tspackages/1-framework/3-tooling/migration/src/exports/aggregate.tspackages/1-framework/3-tooling/migration/test/resolve-cross-space-fk.test.tspackages/2-sql/2-authoring/contract-psl/package.jsonpackages/2-sql/2-authoring/contract-psl/test/psl-ts-namespace-parity.test.tspackages/2-sql/9-family/test/schema-verify.constraints.test.tspackages/2-sql/9-family/test/schema-verify.helpers.tspackages/3-extensions/supabase/test/cross-contract-fk.integration.test.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-ddl-builders.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.cross-space-fk-ddl.test.tsskills/extension-author/prisma-next-extension-upgrade/upgrades/0.12-to-0.13/instructions.mdwip/heartbeats/implementer.txt
…rpreter The CLI aggregate loader was patching cross-space FK tableName values via a JSON round-trip workaround (resolveAppContractCrossSpaceFks). This commit moves that resolution into the PSL interpreter, which is the correct site. Changes: - Add composedExtensionContracts input to interpretPslDocumentToSqlContract; when a space's contract is in the map, the interpreter resolves tableName directly from the extension contract instead of using the symbolic modelName.toLowerCase() fallback - Emit PSL_UNKNOWN_CROSS_SPACE_TARGET when the contract is provided but the referenced model is not found in that contract - Delete resolve-cross-space-fk.ts and its test - Remove resolveCrossSpaceFkTableName export from migration/src/exports/aggregate.ts - Delete resolveAppContractCrossSpaceFks + asRecord + the orphan docblock from contract-space-aggregate-loader.ts; buildContractSpaceAggregate now returns ok(loaded.value) directly - Delete contract-space-aggregate-loader.cross-space-fk-resolution.test.ts - Remove @prisma-next/migration-tools devDependency from contract-psl/package.json - Rewrite psl-ts-namespace-parity.test.ts second test to pass composedExtensionContracts and assert byte-identical FK carriers Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…t files Remove references to M3a.X, M2.X, M2.3, post-M3a, after M3a, M3a end-to-end, and the 2026-06-07 datestamp from comments and doc strings in packages and test files. These were project-tracking annotations tied to TML-2500 milestones that do not belong in the codebase. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ions Remove the draft HTML comment blocks (TML-2808, TML-2817, TML-2683, TML-2834, TML-2500 M2, TML-2500 M3a) and the placeholder body sentence from skills/extension-author/prisma-next-extension-upgrade/upgrades/0.12-to-0.13/instructions.md. The file is now just the frontmatter and the section heading, ready for the real release notes to be written when 0.13 ships. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
R2 removed @prisma-next/migration-tools from sql-contract-psl/package.json (the bridge dep was no longer needed after deleting the resolver). 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]>
…s required, no fallback F1 from reviewer finding on PR #756. The public InterpretPslDocumentToSqlContractInput.composedExtensionContracts field is now required (non-optional). The cross-space FK production site uses composedExtensionContracts.get() and emits PSL_UNKNOWN_CONTRACT_SPACE immediately when the space is absent — the fieldTypeName.toLowerCase() fallback is deleted. ContractSourceContext gains composedExtensionContracts. Both the CLI emit path (contract-emit.ts) and the client emit path (client.ts) build the map from stack.extensionPacks at emit time. All cascade callers updated to pass an empty Map() as the now-required argument. Fail-fast test added to psl-ts-namespace-parity.test.ts: cross-space FK through the interpreter without the extension contract in the map emits PSL_UNKNOWN_CONTRACT_SPACE instead of silently producing a wrong table name. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
F2 from reviewer finding on PR #756. buildForeignKeySql was documented as dead on the hot path (no production caller; the live FK path is AddForeignKeyCall → addForeignKey() → renderForeignKeySql()). Delete it entirely: - Function + JSDoc removed from planner-ddl-builders.ts - Dead constants and imports cleaned up: REFERENTIAL_ACTION_SQL, ReferentialAction, ForeignKey, qualifyTableName (all were only used by buildForeignKeySql) - Barrel export in exports/planner-ddl-builders.ts: buildForeignKeySql line removed - describe('buildForeignKeySql', ...) block deleted from planner-ddl-builders.test.ts; ForeignKey, asNamespaceId, UNBOUND_NAMESPACE_ID imports cleaned up - JSDoc in planner.cross-space-fk-ddl.test.ts rewritten to not name the deleted function Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts (1)
1007-1013:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUpdate the unknown-space diagnostic to match the new fail-fast mechanism.
The check now fails when
composedExtensionContractshas no entry for the space, but the message still says the space is “not declared in extensionPacks.” That guidance is inaccurate when the pack is present but contract composition is missing.💡 Suggested patch
- message: `Relation field "${model.name}.${relationAttribute.field.name}" references contract space "${fieldTypeContractSpaceId}" which is not declared in extensionPacks. Add "${fieldTypeContractSpaceId}" to extensionPacks in prisma-next.config.ts.`, + message: + `Relation field "${model.name}.${relationAttribute.field.name}" references contract space "${fieldTypeContractSpaceId}" ` + + `but no composed extension contract was found for that space. Ensure the space is composed and that its contract is present in composedExtensionContracts.`,🤖 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-psl/src/interpreter.ts` around lines 1007 - 1013, The diagnostic for code 'PSL_UNKNOWN_CONTRACT_SPACE' is misleading: the check fails when composedExtensionContracts has no entry for the space but the message still claims the space is "not declared in extensionPacks"; update the diagnostics.push that constructs this error (look for diagnostics.push with code 'PSL_UNKNOWN_CONTRACT_SPACE' and references to relationAttribute.field and fieldTypeContractSpaceId) to produce a fail-fast message that covers both cases (space missing from extensionPacks OR present but missing from composedExtensionContracts), e.g. say the contract space is not available/has no composed contracts and suggest adding the space to extensionPacks or composing contracts for that space, keeping sourceId, span, and data fields intact (including suggestedPack).
🤖 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.
Outside diff comments:
In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 1007-1013: The diagnostic for code 'PSL_UNKNOWN_CONTRACT_SPACE' is
misleading: the check fails when composedExtensionContracts has no entry for the
space but the message still claims the space is "not declared in
extensionPacks"; update the diagnostics.push that constructs this error (look
for diagnostics.push with code 'PSL_UNKNOWN_CONTRACT_SPACE' and references to
relationAttribute.field and fieldTypeContractSpaceId) to produce a fail-fast
message that covers both cases (space missing from extensionPacks OR present but
missing from composedExtensionContracts), e.g. say the contract space is not
available/has no composed contracts and suggest adding the space to
extensionPacks or composing contracts for that space, keeping sourceId, span,
and data fields intact (including suggestedPack).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 0b99835b-71d8-47f1-aced-e8c443231f25
⛔ Files ignored due to path filters (1)
projects/target-contributed-psl-blocks/spec.mdis excluded by!projects/**
📒 Files selected for processing (44)
packages/1-framework/1-core/config/src/contract-source-types.tspackages/1-framework/2-authoring/psl-printer/test/print-psl-from-ast.test.tspackages/1-framework/3-tooling/cli/src/control-api/client.tspackages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.tspackages/1-framework/3-tooling/cli/test/config-types.test.tspackages/1-framework/3-tooling/migration/test/emit-contract-space-artefacts.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/provider.test.tspackages/2-mongo-family/2-authoring/contract-ts/test/config-types.test.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/provider.tspackages/2-sql/2-authoring/contract-psl/test/composed-mutation-defaults.test.tspackages/2-sql/2-authoring/contract-psl/test/fixtures.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.control-policy.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.defaults.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.extensions.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.namespaces.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.types.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.value-objects.test.tspackages/2-sql/2-authoring/contract-psl/test/psl-ts-namespace-parity.test.tspackages/2-sql/2-authoring/contract-psl/test/ts-psl-parity.test.tspackages/2-sql/2-authoring/contract-ts/test/config-types.test.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/postgres/test/psl-namespace-qualifier-routing.test.tspackages/3-extensions/sql-orm-client/test/cross-space-relation.test-d.tspackages/3-extensions/supabase/test/contract-handles.test.tspackages/3-extensions/supabase/test/cross-contract-fk.integration.test.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-ddl-builders.tspackages/3-targets/3-targets/postgres/src/exports/planner-ddl-builders.tspackages/3-targets/6-adapters/postgres/test/migrations/planner-ddl-builders.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.cross-space-fk-ddl.test.tsskills/extension-author/prisma-next-extension-upgrade/upgrades/0.12-to-0.13/instructions.mdtest/integration/test/authoring/cli.emit-parity-fixtures.test.tstest/integration/test/authoring/parity/ts-psl-parity.real-packs.test.tstest/integration/test/authoring/psl-index-type-options.integration.test.tstest/integration/test/authoring/psl.pgvector-dbinit.test.tstest/integration/test/authoring/side-by-side-contracts.test.tstest/integration/test/cli.emit-command.additional.test.tstest/integration/test/cli.emit-contract.test.tstest/integration/test/value-objects/value-objects.integration.test.ts
💤 Files with no reviewable changes (3)
- packages/3-targets/3-targets/postgres/src/exports/planner-ddl-builders.ts
- skills/extension-author/prisma-next-extension-upgrade/upgrades/0.12-to-0.13/instructions.md
- packages/3-targets/3-targets/postgres/src/core/migrations/planner-ddl-builders.ts
✅ Files skipped from review due to trivial changes (10)
- packages/3-extensions/sql-orm-client/test/cross-space-relation.test-d.ts
- packages/2-sql/2-authoring/contract-psl/test/fixtures.ts
- packages/2-sql/2-authoring/contract-ts/test/config-types.test.ts
- packages/1-framework/2-authoring/psl-printer/test/print-psl-from-ast.test.ts
- packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
- packages/2-mongo-family/2-authoring/contract-ts/test/config-types.test.ts
- packages/1-framework/3-tooling/migration/test/emit-contract-space-artefacts.test.ts
- packages/3-extensions/supabase/test/contract-handles.test.ts
- packages/2-sql/2-authoring/contract-ts/test/cross-space-relation.test.ts
- packages/2-sql/2-authoring/contract-ts/test/cross-space-fk.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/3-targets/6-adapters/postgres/test/migrations/planner.cross-space-fk-ddl.test.ts
- packages/3-extensions/supabase/test/cross-contract-fk.integration.test.ts
…s required, no fallback F1 from reviewer finding on PR #756. The public InterpretPslDocumentToSqlContractInput.composedExtensionContracts field is now required (non-optional). The cross-space FK production site uses composedExtensionContracts.get() and emits PSL_UNKNOWN_CONTRACT_SPACE immediately when the space is absent — the fieldTypeName.toLowerCase() fallback is deleted. ContractSourceContext gains composedExtensionContracts. Both the CLI emit path (contract-emit.ts) and the client emit path (client.ts) build the map from stack.extensionPacks at emit time. All cascade callers updated to pass an empty Map() as the now-required argument. Fail-fast test added to psl-ts-namespace-parity.test.ts: cross-space FK through the interpreter without the extension contract in the map emits PSL_UNKNOWN_CONTRACT_SPACE instead of silently producing a wrong table name. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…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
After M2, an app contract could declare
Profile.userId → supabase:auth.User.idand the carrier reached the storage IR — but the rest of the pipeline didn't yet know what to do with it. This PR closes that loop: an app contract with a cross-contract FK now produces a real cross-schema constraint in PostgreSQL.After
dbInit, the database holds:A new PGlite-backed integration test proves this end-to-end: it builds a synthetic app contract, runs the CLI's
dbInit, queriespg_constraintcross-joined withpg_namespace+pg_classfor both source and target, asserts the FK exists with targetauth.users(id)andconfdeltype='c'(cascade declared), then runs the verifier and gets zero issues across both contract spaces.This is the framework substrate half of M3. The walking-skeleton wiring in
examples/supabase+ the cascade-delete runtime test + theBuiltStorageTables.spaceIdtype-surface cleanup are the next PR (M3b). Splitting it keeps each PR reviewable in one sitting.What this PR decides
Four decisions shape the implementation; the rest of the description explains each one:
users), not the PSL symbolic fallback (user).tableNameis resolved.validateRelationTargetswalk — their targets live in another contract space and were always meant to be checked at the aggregate boundary, not at parse time. A six-line guard closes a pre-existing M2 gap that no prior test had reached.How it works, piece by piece
The resolution gap (recap). M2.4 left the PSL cross-space FK carrier with a symbolic table name —
tableName = modelName.toLowerCase(), sosupabase:auth.Userlowered totableName: 'user'. The PSL interpreter only sees aSet<string>of composed extension names; it doesn't have the extension contracts, so it can't resolve the real table (users). The carrier still held the authoritative model name (User), and the PSL↔TS parity test pinned the divergence with a failing-on-resolution assertion that this PR was meant to flip.Resolution at the loader (decision 1, in detail). The CLI's
contract-space-aggregate-loader.tsis the natural seam: when it composes[app, ...extensions]it already has every extension'scontract()available, so a lookup against the target extension'sdomain.namespacesis local and cheap. A new helperresolveCrossSpaceFkTableName(contract, spaceId, namespaceId, tableName, targetColumns)lives inmigration-tools(target-agnostic). It does a two-step lookup — exact-table match first (handles the TS path where the branded handle already supplies the real name) thenmodelName.toLowerCase()(the PSL symbolic fallback) — and validates that every referenced target column exists on the resolved table. The result is patched in-place on the app contract before handoff to the planner. Resolution is in-memory only; the emittedcontract.jsonon disk keeps the symbolic value, which is fine because every downstream consumer (planner, verifier, runtime) flows through the loader. With the resolver wired up, the parity test now asserts byte-identical PSL↔TS carriers — closing AC2.Planner audit and the dead path (decision 2, in detail). The Postgres planner ships with two FK DDL emitters.
renderForeignKeySql(the op-factory path) correctly readsfk.references.schemafor the REFERENCES target.buildForeignKeySql(a lower-level helper) uses the source table's schema for both sides — a pre-existing bug that would emitREFERENCES "public"."users"("id")frompublic.profile, never reachingauth. A grep of every.tsoutside test files turned up zero production callers of the buggy emitter; the FK-add hot path runsAddForeignKeyCall.toOp() → addForeignKey() → renderForeignKeySql(), which is correct. This PR documentsbuildForeignKeySqlas dead-on-hot-path with a JSDoc that names the live alternative and warns against wiring it up without fixing the schema argument; aggressive deletion is left as a follow-up. Three new tests pin the live path's output for both__bound__(qualified"auth"."users") and__unbound__(unqualified"users") target namespaces, plus a local-FK regression — closing AC3 planner half.Verifier confirmation (decision 3, in detail).
verifyForeignKeyscompares contract FK metadata to introspectedpg_constraintrows by(referencedSchema, referencedTable, referencedColumns). The comparison never tries to look up the target table in the app contract's own namespaces — it just trusts the introspected row. So once the loader resolvestableNameto the realusers, the verifier walks a cross-space FK identically to a local one. Three new tests prove this: a happy-path zero-issues case, a mismatch case that emits the expectedFOREIGN_KEY_MISMATCH, and a negative assertion that noMISSING_TABLEissue ever mentionsauth.users(because the app verifier never iterates theauthnamespace).Cross-space relations in
validateRelationTargets(decision 4, in detail). M2.2 added an optionalspacefield toCrossReferenceso the domain-plane relation could carry the foreignspaceId. ButvalidateRelationTargets(which walks every relation and confirms its target exists in the local domain index) was never updated. The reason this slipped past M2 review: no M2 test deserialized a cross-space-relation-bearing contract throughvalidateContract. The M3a.4 integration test is the first to do so — and tripped the validator. The fix is six lines (one logic line + a five-line comment): skip cross-space relations in this walk. Their target existence is checked at the aggregate-loader resolver instead (M3a.1). Cross-space relations without an accompanying FK have no existence check anywhere, but those are non-navigable by design (Option B from M2), so a typo in the model name is type-erased and runtime-inert.The AC7 deliverable (the integration test). Lives at
packages/3-extensions/supabase/test/cross-contract-fk.integration.test.ts. Builds a synthetic app contract with the TS builder (extensionModel(AuthUser)/belongsTo/constraints.foreignKey({onDelete: 'cascade'})), materializes both contract spaces on disk, seeds the externalauth.*/storage.*tables viabootstrapSupabaseShim, runs the CLI'sdbInitin apply mode, queriespg_constraintcross-joined withpg_namespace+pg_classon both sides for the cross-schema FK, asserts the constraint exists withconfkeypointing at columnidofauth.usersandconfdeltype='c'(cascade declared), then runsdbVerifyand asserts zero issues across both per-space results. This is the end-to-end proof that everything M1+M2+M3a built actually composes.Scope — deferred to M3b
examples/supabase/src/contract.prismaaddsuserId+ the cross-contract relation; regeneratecontract.json/contract.d.ts/migration files.auth.users+public.profile,DELETE FROM auth.users, assert the dependent profile row is gone (proves runtime cascade semantics, not just the DDL declaration).BuiltStorageTables.spaceIdtype-surface cleanup. The runtime FK carrier emitsspaceId, but the loweredBuiltStorageTables<Definition>type still omits it on the FK target; M2.3's reviewer noted that tests had to use a record cast to read it. A one-line addition closes the gap.Verification
Full local validation is green:
pnpm typecheck138/138,pnpm lint79/79,pnpm lint:depsclean,pnpm lint:castsdelta 0,pnpm fixtures:checkclean (no churn),pnpm check:upgrade-coverage --mode prclean (the upgrade-instructions file carries a TML-2500 (M3a) HTML comment block documenting the substrate diff is no-op for extension authors). Package suites:migration-tools572 (5 new resolver tests),cli1318 (2 new loader tests),contract168 (the validator's tests still pass with the new branch),target-postgres299,adapter-postgres569 (3 new planner-DDL tests),family-sql351 (3 new verifier tests),sql-contract-psl223 (the flipped parity test),extension-supabase19 (the new AC7 integration test) — all green.Acceptance criteria advanced: AC2 (PSL↔TS parity on
tableNamenow byte-identical), AC3 (planner emits qualified and unqualifiedREFERENCEScorrectly through the live path), AC7 (live-DB cross-schema FK + verifier-clean), plus AC9 (no regression in M1/M2 tests) and AC10 (no new layering / casts).Alternatives considered
tableNameto the emittedcontract.json. Considered. Rejected for now: the on-disk symbolic value is unreachable except through the loader-patched in-memory aggregate (every consumer flows through the loader), and persisting would force fixture churn for every existing contract with a cross-space FK. Future-proofing note: ifmigration-show/migration-new/migration-checkever start reading FKtableNamedirectly, the resolver call needs to migrate toloadContractSpaceAggregate.buildForeignKeySql(the dead path's REFERENCES bug) in this PR. Rejected as scope creep: it isn't called from production, and fixing dead code carries no immediate user impact. Documented as a follow-up.validate-domain.tsfix. Rejected: the fix is six lines, scoped exactly to the cross-space case the test surfaced, and trivially related to the feature M3a is delivering. The orchestrator's standing instruction is "trivial-and-related fixes that serve the goal go in the same dispatch with a one-line note."Refs TML-2500.
🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
Tests