Repository navigation
TML-2500 (M1): cross-contract FK carrier + aggregate-load checks - #745
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds extension dependency ordering and namespace ownership collision detection; represents cross-space foreign keys with optional spaceId, updates validators and tests; adds runtime check rejecting cross-space FKs that point against declared extension dependencies; integrates collision reporting into migration integrity and CLI failure mapping. ChangesCross-Space Foreign Keys with Dependency and Collision Validation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 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)
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: 1
🤖 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/1-framework/1-core/framework-components/src/control/control-stack.ts`:
- Around line 526-528: The call to buildExtensionLoadOrder(extensionPacks) is
only validating but its result isn't used, so allDescriptors (and subsequent
assembly) still uses the original extensionPacks order; update the code to
capture and use the computed ordered list (e.g., const orderedExtensionPacks =
buildExtensionLoadOrder(extensionPacks) or overwrite extensionPacks) and then
build allDescriptors from that ordered list (use orderedExtensionPacks in place
of extensionPacks) so dependency-respecting ordering is applied during control
stack assembly.
🪄 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: 3c723d7f-9e0e-454a-b622-a9dadd95ce63
⛔ Files ignored due to path filters (4)
projects/cross-contract-refs/plan.mdis excluded by!projects/**projects/cross-contract-refs/rollups/2026-06-05-opening.mdis excluded by!projects/**projects/cross-contract-refs/slices/M1/plan.mdis excluded by!projects/**projects/cross-contract-refs/spec.mdis excluded by!projects/**
📒 Files selected for processing (13)
packages/1-framework/1-core/framework-components/src/control/control-stack.tspackages/1-framework/1-core/framework-components/src/exports/control.tspackages/1-framework/1-core/framework-components/test/control-stack.test.tspackages/1-framework/3-tooling/cli/src/commands/migration-check.tspackages/1-framework/3-tooling/cli/src/utils/integrity-violation-to-check-failure.tspackages/1-framework/3-tooling/migration/src/aggregate/check-integrity.tspackages/1-framework/3-tooling/migration/src/integrity-violation.tspackages/1-framework/3-tooling/migration/test/aggregate/check-integrity.test.tspackages/2-sql/1-core/contract/src/ir/foreign-key-reference.tspackages/2-sql/1-core/contract/src/validators.tspackages/2-sql/1-core/contract/test/foreign-key-cross-space.test.tspackages/2-sql/9-family/src/core/control-instance.tspackages/2-sql/9-family/test/cross-contract-validation.test.ts
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/1-core/contract/src/validators.ts (1)
156-158:⚠️ Potential issue | 🟠 Major | ⚡ Quick winReject
spaceIdon FK sources.Line 157 reuses
ForeignKeyReferenceSchemaforsource, so structural validation now accepts{ source: { ..., spaceId } }even though the owning table is always local.validateSqlStorageConsistency()never rejects that extra coordinate, and the duplicate-definition signature later in this file hashessourceverbatim, so malformed and canonical versions of the same FK can slip through as distinct entries.Suggested fix
+const LocalForeignKeyReferenceSchema = type({ + '+': 'reject', + namespaceId: 'string', + tableName: 'string', + columns: type.string.array().readonly(), +}) satisfies Type<ForeignKeyReferenceInput>; + export const ForeignKeySchema = type({ - source: ForeignKeyReferenceSchema, + source: LocalForeignKeyReferenceSchema, target: ForeignKeyReferenceSchema, 'name?': 'string', 'onDelete?': ReferentialActionSchema, 'onUpdate?': ReferentialActionSchema, constraint: 'boolean', index: 'boolean', }) satisfies Type<ForeignKeyInput>;🤖 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/1-core/contract/src/validators.ts` around lines 156 - 158, ForeignKeySchema currently reuses ForeignKeyReferenceSchema for source which allows a spaceId on FK sources; change the source to a schema that forbids/omits spaceId (e.g., create ForeignKeySourceSchema or use an omit/refine of ForeignKeyReferenceSchema that rejects spaceId) and update anywhere using ForeignKeySchema (including validateSqlStorageConsistency() and the duplicate-definition hashing logic) so the source is validated/hashed without a spaceId coordinate.
🤖 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/1-core/contract/src/validators.ts`:
- Around line 156-158: ForeignKeySchema currently reuses
ForeignKeyReferenceSchema for source which allows a spaceId on FK sources;
change the source to a schema that forbids/omits spaceId (e.g., create
ForeignKeySourceSchema or use an omit/refine of ForeignKeyReferenceSchema that
rejects spaceId) and update anywhere using ForeignKeySchema (including
validateSqlStorageConsistency() and the duplicate-definition hashing logic) so
the source is validated/hashed without a spaceId coordinate.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 09561a8d-aa5e-4098-b781-3f1ce4e61d2d
⛔ Files ignored due to path filters (1)
projects/cross-contract-refs/slices/M1/plan.mdis excluded by!projects/**
📒 Files selected for processing (5)
packages/2-sql/1-core/contract/src/ir/foreign-key-reference.tspackages/2-sql/1-core/contract/src/validators.tspackages/2-sql/1-core/contract/test/foreign-key-cross-space.test.tspackages/2-sql/9-family/src/core/control-instance.tspackages/2-sql/9-family/test/cross-contract-validation.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/2-sql/9-family/src/core/control-instance.ts
- packages/2-sql/9-family/test/cross-contract-validation.test.ts
- packages/2-sql/1-core/contract/test/foreign-key-cross-space.test.ts
|
Done (A-002). Introduced |
…cision Planning + design artifacts for cross-contract-space FK references: - reconcile spec/plan against the now-landed TML-2459/TML-2493 substrate - record Option B (declared, non-navigable cross-space relations) - defer runtime cross-space query/traversal to a future project (Non-goals) - add M1 dispatch decomposition + opening health rollup Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Extend ForeignKeyReference with an optional origin/'space' discriminator so an FK target can identify a cross-contract-space reference: - origin absent or 'local': local reference (same contract-space). No change to JSON shape — backward-compatible with all existing contracts. - origin: 'space' + spaceId: string: cross-space reference. Both fields appear in JSON so round-trips are lossless. ForeignKeyReferenceInput becomes a discriminated union of LocalForeignKeyReferenceInput | SpaceForeignKeyReferenceInput. ForeignKeyReferenceSchema is updated to match: a union of the two shapes. ForeignKeySchema drops the type.declare<ForeignKeyInput>() wrapper (incompatible with union-typed property schemas in ArkType). validateSqlStorageConsistency skips the target-namespace table-existence check for cross-space FKs (the referenced table lives in a foreign contract-space, not in this contract's storage). No authoring DSL, domain plane, or planner/verifier changes — storage plane and IR only. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Add import of ForeignKeyReferenceInput and ForeignKeyInput from ./types, and apply `satisfies Type<T>` guards to ForeignKeyReferenceSchema and ForeignKeySchema. Both guards compile successfully — ArkType's union output type for the discriminated .or() is assignable to the TypeScript input union, so no comment is needed. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…tract aggregate Add buildExtensionLoadOrder() to framework-components/control-stack.ts. The function performs a Kahn topological sort over extension descriptors, reading each descriptor's contractSpace.contractJson.extensionPacks via structural duck-typing to discover declared dependencies (including transitive ones from extensions that themselves declare extensionPacks). A cycle throws with an error message that names every member of the cycle (FR12/FR13). The check runs inside createControlStack() so it fires at stack-assembly time for all families that use the framework stack. buildExtensionLoadOrder is exported from @prisma-next/framework-components/control so callers can invoke it independently. Tests cover: empty input, single extension, linear A→B→C chain, multi-dependency, transitive discovery, 2-cycle, 3-cycle, extensions without contractSpace, and createControlStack end-to-end cycle rejection. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…bare cast Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ection at aggregate load Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…e integrity check Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…orphan Extract `findNamespaceOwnershipCollisions` as the canonical pure detector in framework-components (control-stack.ts + exports/control barrel). Remove the dead throwing `assertNoNamespaceOwnershipCollisions` wrapper, repoint its unit tests to the pure function. Wire migration-tools check-integrity.ts to call the shared detector, eliminating the duplicated algorithm. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ice plan Captures the round-2/3 decisions: dependency-graph + cycle detection run over the listed pack set (error on an unlisted declared dependency; transitive auto-loading deferred), and the namespace-ownership collision check lands at the migration-tools aggregate integrity layer (where the app contract is available), while reverse-reference rejection stays in the SQL family. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…e on spaceId presence Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ce plan Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
buildExtensionLoadOrder returned the dependency-sorted IDs but the caller discarded them, so allDescriptors and the returned extensionPacks were assembled in original input order. Capture the ordered ID list, map it back to descriptors, and use the ordered packs throughout. A test asserts that when a dependent pack is listed before its dependency in the input, the assembled stack has them in dependency order. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
ForeignKeySchema.source was reusing ForeignKeyReferenceSchema which permits spaceId. An FK source is always the owning (local) table and must never carry spaceId. Introduce ForeignKeySourceSchema with '+': 'reject' and no spaceId field, and use it for source. Target keeps ForeignKeyReferenceSchema (spaceId legitimately permitted there). Tests assert: source carrying spaceId is rejected, target carrying spaceId is still accepted, local + cross-space cases pass unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…omments/tests Removed (NFR2) from ForeignKeyReferenceInput JSDoc, (NFR2) section header and describe label in foreign-key-cross-space.test.ts, (AC8) describe label in the same file, (FR14, AC6) section comment in cross-contract-validation.test.ts, and (FR15/FR16, AC6 collision half) section comment in control-stack.test.ts. Kept all explanatory prose; only the transient label tokens were removed. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
ForeignKeySchema now uses type.declare<ForeignKeyInput>().type({...})
instead of a bare type({...}) satisfies cast. ForeignKeyReferenceSchema
and ForeignKeySourceSchema keep satisfies because they include
'+': 'reject' — a meta-key ArkType's .declare<T> constraint rejects
when T has no '+' property. This is the same limitation that prevented
.declare on those schemas before M1.4; the source type would need a '+'
index signature to allow it, which would widen the contract type.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ure envelope origin/main (TML-2836) renamed CheckFailure.pnCode -> code and added a space field. Update the namespaceOwnershipCollision case to the new shape (space: "app", code: ...), matching the sibling cross-space disjointness case. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ullAssertion) buildExtensionLoadOrder and findNamespaceOwnershipCollisions used queue.shift()! and collisions.get(key)!; restructured to a guarded shift and an entries() walk so biome check --error-on-warnings passes. Behavior unchanged (framework-components 350 + migration-tools 548 green). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…load order Applying buildExtensionLoadOrder (review fix A-001) composes extension codec types in dependency/alphabetical order, so CodecTypes is now PgTypes & ArktypeJsonTypes & PgVectorTypes. Regenerated via pnpm fixtures:emit (not hand-edited). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ying)
Key on ${namespaceId}:${entityKind}:${entityName} so auth.users and
public.users are distinct; element is now the readable qualified form
e.g. public.users. Remove the redundant namespaceOwnershipCollision
violation kind and its helpers (findNamespaceOwnershipCollisions,
PN-MIG-CHECK-017) now that disjointness covers the same ground correctly.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…to disjointness Remove the findNamespaceOwnershipCollisions describe block from control-stack.test.ts and replace the namespaceOwnershipCollision describe block in check-integrity.test.ts with disjointness tests, including a no-false-positive case (same name in different namespaces → no violation) and a true-collision case (same coordinate → one violation with qualified element like public.users). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…tion Record Decision D-recon (fix disjointness namespace-awareness, remove namespaceOwnershipCollision) and the walking-skeleton obligation (FK deferred to M2/M3). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
4a70ecd to
7d5ecac
Compare
… 1 — read side) (#753) ## At a glance Slice 1 of 4 of **[Target-contributed top-level PSL blocks](https://linear.app/prisma-company/issue/TML-2804)** — the **read side** of the declarative SPI. After this, an extension describes a new top-level PSL block **as data** (a descriptor of its keyword, name, and typed parameters), and the framework **parses, validates, and lowers it to contract IR** with one generic interpreter. No extension-supplied parse/print code runs. This supersedes the function-based SPI built on [#718](#718) (now draft): that cut had each extension ship imperative `parser`/`printer` functions. The mechanism is cherry-picked here; the functions are replaced by the descriptor + generic interpreter. Rationale + design are in `projects/target-contributed-psl-blocks/spec.md` (landed via #749). ```prisma namespace public { model Profile { id String @id userId String @unique } policy_select profiles_select_anon { target = Profile // ref (same-namespace) as = permissive // option: permissive | restrictive roles = [anon, authenticated] // list of ref (cross-space) using = "auth.uid() = user_id"// value (codec-typed) } } ``` The framework never learns the `policy_select` keyword directly — the descriptor is data. ## What's in this PR The parameter value-kind vocabulary and the generic read pipeline, built across seven dispatches: - **Declarative descriptor + vocabulary** (`framework-components`) — `AuthoringPslBlockDescriptor` is data: keyword, discriminator, `name`, and a `parameters` map of the four-kind union `PslBlockParam`: **`ref`** (resolves to a declared entity; `refKind` + `scope`), **`value`** (codec-typed), **`option`** (a closed set of allowed literal tokens — an authoring constraint, *not* a domain enum), **`list`** (combinator). No `parser`/`printer` fields. Plus the uniform parsed-node base (`{ kind, name, parameters, span }`) and the `PslNamespace.extensionBlocks` slot. - **Codec-typed `value` via the codec's existing `decodeJson`** — a `value` literal is interpreted as JSON through the codec the parameter declares: `codecLookup.get(codecId).decodeJson(JSON.parse(raw))` — the same path that decodes literal column defaults. There is no bespoke PSL codec hook; PSL literals are handled generically and codecs already own value↔JSON, so `value` rides that existing medium (and gets full codec expressiveness + correct JSON escaping for free). (`@default`'s legacy literal handling is untouched — separate, future work.) - **Generic parser** (`psl-parser`) — on an unknown top-level keyword, the parser reads any declared block into the uniform node, capturing each parameter's RHS by its declared kind. Built-in keywords stay framework-parsed; an unregistered keyword still gets the clean unknown-keyword diagnostic. - **Generic validator + `ref` resolution** — reports (with spans) unknown / missing-required parameters, `option`-not-in-set, codec-rejected `value`, and `ref` unresolved within its scope (`same-namespace`/`same-space` resolved against the parsed namespaces; `cross-space` is a documented pass-through per the spec's first-consumer allowance, leaning on the merged #745 coordinate model). A small `PSL_EXTENSION_*` diagnostic taxonomy. - **Load-time validation** — `assembleAuthoringContributions` rejects duplicate keyword, duplicate discriminator (within `pslBlocks` and within `entityTypes`), a `pslBlocks` descriptor with no matching `entityTypes` factory, and a malformed descriptor. Standalone `entityTypes` factories stay allowed. - **Lowering + fixture + round-trip** — the uniform node lowers to IR via the matching `entityTypes` factory; a test-only declarative `policy_select` fixture round-trips **parse → validate → lower → IR**. ## A design decision worth a look Validation runs **inside `parsePslDocument`** whenever `pslBlocks` are registered, joining the parser's existing diagnostics. A `value` parameter is validated by parsing its literal as JSON and running the codec's existing `decodeJson` (`codecLookup.get(codecId).decodeJson(JSON.parse(raw))`); malformed JSON or a codec rejection surfaces a diagnostic. No production caller passes `pslBlocks` yet — this is the read-side seam. ## Out of scope (later slices) - **Generic printer + `contract infer`** — Slice 2, [TML-2854](https://linear.app/prisma-company/issue/TML-2854). This PR's round-trip stops at the lowered IR. - **`PslNamespace` → ADR 224 `entries` migration** — Slice 3, [TML-2849](https://linear.app/prisma-company/issue/TML-2849). - **ADR 126 revision + three-layer ADR + close-out** — Slice 4, [TML-2806](https://linear.app/prisma-company/issue/TML-2806). - A `number` value-kind / field-declaration block bodies (deferred to first consumer); real RLS (downstream). ## Relationships - **[#718](#718 — superseded function-SPI cut; draft; mechanism cherry-picked; branch preserved. - **[#745](#745) / TML-2500** — merged; `ref` `cross-space` scope builds on its coordinate model. Not a blocker. - **[#748](#748) / enums-as-domain** — independent; `option` is not an enum, `value` uses ordinary scalar codecs. ## Verification | Gate | Result | |---|---| | `pnpm typecheck` (the four touched packages) | clean | | `pnpm test:packages` (psl-parser / psl-printer / framework-components / cli, in isolation) | pass — 100 / 34 / 395 / 1316 | | `pnpm lint:deps` | clean | | `pnpm lint:casts` | `delta=0` (no regression) | A monorepo-wide typecheck has pre-existing, unrelated worktree dist-not-built failures (migration-tools / mongo-contract / sql-schema-ir / emitter / mongo-lowering) — none introduced here; per-package typechecks for the touched packages are clean, and the changes don't alter a public export signature those packages consume. ## Follow-ups recorded for downstream (not this slice) - `ref-kind` vs `discriminator` mismatch for a non-`cross-space` ref to an extension-contributed entity (the first RLS-roles-style consumer must map `refKind` → discriminator). - Duplicate-*keyword-string* across different namespace keys isn't caught at assembly (duplicate-*path* is); harden in the keyword-dispatch index if it matters. Refs [TML-2804](https://linear.app/prisma-company/issue/TML-2804). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Support for PSL extension blocks: parsing, validation, diagnostics, namespace-aware reference resolution, and codec-backed value checks. * Authoring API expanded so contributors can declare/register extension-block descriptors that integrate into parse/validation and cross-registry consistency checks. * **Tests** * Extensive unit and round‑trip tests and fixtures covering parsing, validation, diagnostics, lowering, and reference/codec behaviors. * **Chores** * Test fixtures and tooling adjusted to include the new authoring contributions shape. <!-- 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 Opus 4.8 <[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]>
Summary
First slice (M1 — Foundation) of TML-2500, cross-contract-space FK references. It lands the storage-plane IR carrier and the aggregate-load-time validations. No authoring surface yet — the TS brand surface and PSL colon-prefix grammar are M2; planner/verifier wiring and the PGlite e2e are M3.
This is the substrate that lets an app contract reference a table owned by another contract space (the canonical case being
Profile.user → supabase:auth.User).What's in this PR
ForeignKeyReferencecarries an optionalspaceId; its presence is the discriminator (absent ⇒ local, present ⇒ cross-space) — no separate tag field. A cross-space reference carriesspaceIdplus the full coordinate (namespace admitting the__unbound__sentinel + table + column), so the target resolves without lexical context. Local FKs serialize byte-identically to before (NFR2). The ArkType schema rejects an unknownorigin-style key; round-trip property test over a mix of local/cross-space carriers (AC8).buildExtensionLoadOrderderives a load order from each pack's declaredextensionPacksand rejects cycles at load time, naming the cycle members (FR12/FR13).main's existingdisjointnessintegrity check namespace-aware (FR15/FR16).disjointnesspreviously keyed on the bare entity name (elementCoordinatesyields the full coordinate but it was discarded), so it would have false-positived on same-named tables in different namespaces across spaces — e.g.auth.users(supabase space) vspublic.users(app space), the exact multi-namespace scenario this project enables. It now keys on(namespaceId, entityKind, entityName)and reports a readablenamespace.nameelement. Two spaces declaring the same primitive fail load naming both contributors.M1 acceptance criteria: AC6 (collision + cycle), AC8 (round-trip), AC10 (
lint:deps+ cast ratchet clean). AC9 regression: targeted suites green; no TML-2459 local-FK test modified.Design notes (v0.1 scope)
extensionPacks; a pack that declares a dependency on a space not in the set fails load with a clear "add it toextensionPacks" diagnostic. Transitive auto-loading of unlisted packs is deferred — it needs aspaceId → descriptorresolver that doesn't exist yet, and the canonical one-hopapp → supabasecase never needs it.includewould require a runtime contract-space aggregate (undesigned); deferred to a future project.Validation
Targeted suites at HEAD, all green:
@prisma-next/sql-contract146,@prisma-next/framework-components349,@prisma-next/family-sql334,@prisma-next/migration-tools548.pnpm typecheck,pnpm lint:deps, andpnpm lint:casts(delta=0) all clean. One pre-existing@prisma-next/adapter-sqliteTurbo-cascade typecheck artifact (present onmain, unrelated).Walking skeleton
The
examples/supabasewalking skeleton (landed onmain) composes the app space + the@prisma-next/supabaseextension space and runsdb init/db verifythrough the now-reconciled integrity checks. M1's obligation is that it stays green against these checks. The headlineProfile.userId → auth.User.idcross-contract FK + cascade-delete step is deferred to M2 (authoring surface) + M3 (planner/verifier) — it cannot be authored at M1's foundation level.Scope discipline
Storage-plane IR + aggregate-load validation only — no authoring DSL, planner, verifier, or Mongo changes. Those land in M2/M3.
Refs TML-2500.
🤖 Generated with Claude Code