Repository navigation
Conversation
PR2 design discussion settled on a single architectural shape across 15
decisions; spec.md and plan.md now reflect the agreed end-state.
Key decisions captured:
- IR sentinel renamed `__unspecified__` -> `__unbound__` (semantic
honesty: the slot is late-bound, not "no decl default"). Framework
constant becomes UNBOUND_NAMESPACE_ID; PSL AST identifier
`__unspecified__` stays as the syntactic-absence bucket name (two
layers, two concepts, two spellings).
- PSL AST collapses into PslDocumentAst.namespaces (the only models
container); top-level declarations are collected into the implicit
`__unspecified__` AST entry. No top-level models[] slot survives.
- PSL -> Contract IR lowering is per-target. Postgres maps implicit
`__unspecified__` -> IR `public` (single-tenant behaviour
preserved); explicit `namespace unbound { ... }` -> IR `__unbound__`
(late binding); named -> IR named schemas. SQLite + Mongo reject
all explicit `namespace { ... }` blocks today.
- Cross-namespace FK references use dot-qualified field types
(`auth.User` in the type position); `references:` list stays bare.
Framework parser regex extension is the only parser change needed.
- ForeignKey IR restructures: source/target separation;
ForeignKeyReferences (plural) -> ForeignKeyReference (singular).
- Storage shape pinned to nested map keyed by namespace id (Shape C).
- Future projects flagged as out of scope: target-contributed top-level
PSL block registry (RLS/roles/policies prep); @hint mechanism for
rebind intent (table renames and namespace rebinds with one syntax).
Plan changes:
- M5a Task 1 is now the mechanical rename (load-bearing prerequisite).
- M5a tasks reflect Reading D AST shape + per-target interpreter
dispatch.
- M5b expanded to include the FK IR restructuring + the
sqlSchemaIrToPslAst synthesizer update for namespace-qualified
inferred output.
ADR drafts under projects/target-extensible-ir/specs/ still reference
the old sentinel name; they will be updated as part of M5a Task 1
(mechanical rename) so the rename lands as one focused commit.
Signed-off-by: Will Madden <[email protected]>
The FR16c per-target dispatch table conflated "singleton slot" with an unnamed concept; clarify that SQLite and Mongo both use the framework UNBOUND_NAMESPACE_ID slot identity for their singleton storage. The framework constant names "the slot whose binding the target resolves at connection time" — Postgres uses it for search_path-resolved late binding; SQLite uses it for the trivial singleton; Mongo uses it for the connection-db binding. Same slot id, target-specific resolution semantics. Signed-off-by: Will Madden <[email protected]>
Consumer-cascade probe during PR2 shaping verified the plan is implementable on the existing substrate. Captured findings in a new M5a subsection with file-level anchors so the implementer knows what is already in place vs what needs new work. Notable observations: - The framework parser is line-regex-based and hardcoded for top-level keywords. New top-level keywords (namespace included) edit the framework parser directly; no pack-contributed top-level block mechanism exists today (this is a substrate gap covered by the separate follow-up project flagged in Non-goals). - Dotted field types are partially supported: the type-constructor regex accepts dot-separated identifiers; the bare-type fallback regex does not. One regex extension makes auth.User parse. - The PSL printer emits typeName verbatim, so dotted typeNames round-trip without changes; only a PslNamespace block emission case is new (~40-60 LOC). - The M3.5 entity-contribution mechanism is end-to-end-verified by the in-tree synthetic exemplar. PR2 just contributes helpers.namespace(...). - Per-family interpreters already have access to the active pack via entityContext; per-target namespace lowering is interpreter-internal, no new SPI surface. - Mongo namespace concretion is already structurally correct; M5a does rename + docstring refresh only. - SQL family placeholder is obsoleted by per-target concretions; M5a removes (or repurposes) it. - sqlSchemaIrToPslAst synthesizer is flat today; both the IR and the AST become nested under Reading D, requiring a synthesizer update in M5b alongside cross-namespace FK relation-rendering. No architectural surprises surfaced. Signed-off-by: Will Madden <[email protected]>
Pre-loop setup for drive-orchestrate-plan on the PR2 namespace work. Plan: write explicit validation gate commands into M5a and M5b (behavioural "ACs pass" lines were not actionable for the reviewer gate verification). M5a gate: typecheck + lint:deps + test:packages + test:integration. M5b gate adds build (for refreshed .d.mts after the ForeignKey IR restructuring exports new types) and test:e2e (for the FL-02 PGlite cross-namespace FK scenario). Each milestone also names a literal-search assertion the implementer runs post-rename to prevent stale call sites. Per-round code-review.md is scaffolded locally under projects/target-extensible-ir/reviews/ which is gitignored by repo convention; only the durable plan changes commit. Signed-off-by: Will Madden <[email protected]>
…(M5a Task 1) Renames the IR-layer namespace sentinel per spec FR16d: * framework constant `UNSPECIFIED_NAMESPACE_ID` → `UNBOUND_NAMESPACE_ID` (literal `__unspecified__` → `__unbound__` everywhere it surfaces as the IR sentinel: const value, JSON envelope keys, id discriminants on the per-target singleton subclasses) * family-layer placeholder class `SqlUnspecifiedNamespace` → `SqlUnboundNamespace` (file renamed via `git mv` for history) * target-layer concretion `MongoTargetUnspecifiedDatabase` → `MongoTargetUnboundDatabase` * forward-reference stubs in docstrings + plan-cited types: `PostgresUnspecifiedSchema` → `PostgresUnboundSchema`, `SqliteUnspecifiedDatabase` → `SqliteUnboundDatabase`, `PostgresSchema.unspecified` → `PostgresSchema.unbound` * generated artefacts regenerated through the normal emit pipeline: extension contract.json/.d.ts + migration metadata for pgvector, cipherstash, postgis, paradedb; SQL fixtures via `pnpm fixtures:emit` * ADR drafts under `projects/target-extensible-ir/specs/` and the project learnings doc refreshed to use the new spelling and the late-bound-slot framing for the IR sentinel Docstrings on the three core source files (the framework const, the family-layer placeholder, the Mongo target concretion) are refreshed around the late-bound-slot framing: the IR sentinel names the slot whose binding the target resolves at connection time (Postgres `search_path`, SQLite trivial singleton, Mongo connection `db`). The PSL AST identifier `__unspecified__` (the framework parser`s name for the syntactic-absence bucket) is deliberately NOT renamed — the two layers carry different concepts and the spellings reflect that (see spec FR14 / FR16a / FR16d). No PSL-parser references exist yet today; the rename validation excludes that path forward-looking. Signed-off-by: Will Madden <[email protected]>
… after IR sentinel rename (M5a Task 1) The rename of the IR namespace sentinel `__unspecified__` → `__unbound__` changes the storage hash of every contract that carries a namespace slot. Each in-tree extension contract-space package (pgvector, cipherstash, postgis, paradedb) carries a hand-authored migration.ts whose `describe()` pins the post-migration storage hash; bump those literals to the post-rename hash and re-emit the deterministic `migration.json` + `ops.json` artefacts so the migration hash chain is fully re-attested. Also refreshes the authoring-parity expected snapshots and the side-by-side Postgres contract fixture (storage hash + canonical JSON formatting) by running the existing `UPDATE_AUTHORING_PARITY_EXPECTED=1` / `UPDATE_SIDE_BY_SIDE_CONTRACTS=1` flows. Signed-off-by: Will Madden <[email protected]>
…ope decision
Audit: 16 consumer surfaces enumerated; flat-AST is load-bearing in 4
files plus 1 producer. SQL contract-psl interpreter is the largest piece
(~150-250 LOC). No new SPI required for per-family namespace dispatch.
Spec FR16a clarifies that types { … } blocks stay document-scoped (one
per document, outside any namespace block) — matches today's parser,
simplifies the grammar refactor.
Signed-off-by: Will Madden <[email protected]>
…` blocks (M5a Task 3 — framework grammar)
Collapse `PslDocumentAst.models`/`.enums`/`.compositeTypes` into a single
`namespaces: readonly PslNamespace[]` container and teach the framework
PSL parser to recognise top-level `namespace <name> { … }` blocks. The
parser collects out-of-block declarations into a synthesised
`__unspecified__` bucket (exported as `UNSPECIFIED_PSL_NAMESPACE_ID`),
reopen-merges blocks that share a name, and emits a parse diagnostic
for recursive nesting, for `types { … }` declared inside a namespace
body, and for user-authored namespaces named `__unspecified__`. The
framework parser reserves no other identifiers — `unbound`, `public`,
and `auth` remain plain strings; per-target interpreters decide which
names carry semantic weight.
The simple-type fallback regex now accepts dot-separated identifiers
so that bare dotted field types (e.g. `user auth.User`) parse via the
fallback path the same way the type-constructor path already did.
`flatPslModels` / `flatPslEnums` / `flatPslCompositeTypes` helpers are
added for consumers that do not yet need namespace-awareness.
Signed-off-by: Will Madden <[email protected]>
…r (M5a Task 3)
Restructure the print document around `PrintNamespaceSection` and
emit a `namespace <name> { … }` wrapper around each named namespace
section. The synthesised `__unspecified__` bucket prints at the
document top level with no wrapper so round-tripping leaves
top-level declarations untouched. FK-driven topological sort runs
across every namespace so cross-namespace ordering remains stable
when grouping is later introduced; the synthesised bucket sorts
first, then named namespaces alphabetically.
Adds parser→printer→parser round-trip coverage for a mixed
top-level + namespaced schema.
Signed-off-by: Will Madden <[email protected]>
…d inferred-PSL synthesizer (M5a Task 3)
Teach the SQL and Mongo PSL interpreters to walk
`PslDocumentAst.namespaces` instead of the removed
`models`/`enums`/`compositeTypes` slots. Per-target namespace dispatch
is not yet wired in either family — until it lands, every namespace
bucket is flattened into the same declaration set the interpreters
have always consumed, so existing single-namespace contracts behave
identically.
`sqlSchemaIrToPslAst` synthesises a single `__unspecified__` bucket
so the framework printer emits inferred PSL at the document top
level with no `namespace { … }` wrapper, preserving the existing
introspection output verbatim. Future cross-namespace synthesis
will produce one bucket per inferred storage namespace.
Fixture rewrites cover the CLI synthetic-AST helpers, the SQL
interpreter diagnostics test, the control-capabilities seed AST,
and the inferred-PSL synthesizer test.
Signed-off-by: Will Madden <[email protected]>
…atabase target concretions (M5a R4 Task 1)
Each target with native namespacing now ships its own `NamespaceBase`
concretion plus a singleton subclass bound to `UNBOUND_NAMESPACE_ID`:
- `PostgresSchema(id)` renders `"<schema>"` qualifiers and
`"<schema>"."<table>"` qualified table names; `PostgresUnboundSchema`
(singleton at `PostgresSchema.unbound`) overrides those to elide the
schema prefix so DDL resolved by the connection`s `search_path`
emits unqualified.
- `SqliteUnboundDatabase.instance` is the only SQLite namespace
concretion — SQLite has no native schema concept, so the singleton
always elides the qualifier. The SQLite PSL interpreter (in a
follow-on commit) rejects every explicit `namespace { … }` block.
Mirrors the existing `MongoTargetDatabase` / `MongoTargetUnboundDatabase`
pattern; consumers stay polymorphic at the namespace seam and never
branch on `id === UNBOUND_NAMESPACE_ID`.
Signed-off-by: Will Madden <[email protected]>
Captures the PR3 design discussion from PR2's design phase: lift the framework PSL parser to be extensible via target-pack contributions, and migrate enum from framework-parser to Postgres-pack contribution as the load-bearing proof-of-concept. Cross-links target-extensible-ir spec + plan to TML-2537 (replacing the prior "follow-up project" prose). PR4 (originally proposed: migrate namespace to pack-contributed) is recorded as DROPPED — namespace is a framework primitive every multi- storage target needs; per-target semantic interpretation already lives in per-family interpreters per PR2's FR16c. Signed-off-by: Will Madden <[email protected]>
…ask 2)
SQLite and Mongo PSL interpreters now emit a
`PSL_UNSUPPORTED_NAMESPACE_BLOCK` diagnostic for every explicit
`namespace { … }` block (including `namespace unbound { … }`). The
implicit `__unspecified__` bucket (top-level declarations) remains
the only namespace either target accepts:
- **SQLite** has no schema concept at the SQL level — emitted DDL is
always unqualified.
- **Mongo** binds the database via the connection string, not via
authoring-time PSL.
Postgres accepts every block; storage-side lowering of those buckets
to IR namespace slots is a follow-on commit. The dispatch helper is
sized as a tight per-target switch in each interpreter so the diagnostic
spans the offending namespace block in the original PSL source.
Tests cover the three Postgres-accepts / SQLite-rejects / Mongo-rejects
cases plus the explicit `unbound` rejection on the non-Postgres targets
(no late-binding namespace surface there).
Signed-off-by: Will Madden <[email protected]>
…validation (M5a R4 Task 3 partial)
Adds the FR16a authoring-surface entry point: `defineContract` accepts
an optional `namespaces: readonly string[]` field and runtime-rejects
reserved or malformed entries before any contract build proceeds.
Reserved-name rules:
- IR sentinels `__unbound__` / `__unspecified__` are reserved on every
SQL target (framework-reserved coordinates that must not appear as
user-declared namespaces).
- Postgres reserves bare `unbound` for the late-binding PSL opt-in
(`namespace unbound { … }`); declaring it as a regular schema in TS
is rejected with a diagnostic pointing at the PSL surface.
- SQLite rejects any non-empty list — SQLite has no schema concept and
emits unqualified DDL.
- Empty / whitespace-only entries and duplicates are rejected.
Per-model `namespace` field and storage-side wiring (populating
`SqlStorage.namespaces` from the declared list) land alongside the
FR15 storage rekey in the follow-on round. This commit ships the
declarative entry point + validation guards so consumers can write
code against the surface today.
Signed-off-by: Will Madden <[email protected]>
Adds the namespace coordinate to the SQL IR table node so each table can be assigned to an entry in the parent `SqlStorage.namespaces` map. The runtime property is always present (`UNBOUND_NAMESPACE_ID` when not explicitly set); the persisted JSON envelope only carries the field when its value is not the late-bound default, so every contract.json fixture written before this change stays byte-stable. This commit is data-only — no interpreter, builder, serializer, planner, or DDL emitter consumes the new field yet. Subsequent slices wire: 1. SQL interpreter: populate `StorageTable.namespaceId` from the resolved namespace bucket for each model. 2. SqlStorage: collect every distinct `namespaceId` and ensure the corresponding `Namespace` instance is in `storage.namespaces`. 3. Postgres DDL emitter: consume `storage.namespaces[table.namespaceId].qualifyTable(name)` instead of always emitting unqualified DDL. Signed-off-by: Will Madden <[email protected]>
… R4 FR15 slice 2)
Wires the per-target PSL namespace lowering through the contract
build pipeline: `ModelNode.namespaceId` carries the resolved
coordinate from the interpreter, `buildSqlContractFromDefinition`
threads it into each `StorageTable`, and the `SqlStorage` constructor
normalises into a frozen IR instance whose JSON envelope only carries
the field when it is not the late-bound default.
Resolution rules (Postgres only at this slice — SQLite has no
schema concept and SQLite-side validation already rejects every
explicit block):
- Implicit `__unspecified__` bucket: leaves the coordinate unset.
The runtime view resolves to `__unbound__`; the JSON envelope
omits the field. Keeps TS- and PSL-authored single-namespace
contracts byte-identical.
- Explicit `namespace unbound { … }`: resolves to `__unbound__`
(the late-binding sentinel; the connection`s `search_path`
decides where the table actually lives).
- Every other named bucket (e.g. `namespace auth { … }`,
`namespace public { … }`): resolves to its name.
Out of scope for this slice (deferred to slice 3): populating
`SqlStorage.namespaces` with the per-target `Namespace` concretions
the rendering seam needs, and the DDL emitter call to
`namespaces[table.namespaceId].qualifyTable(name)`. A future round
will also surface a target-default-namespace authoring option so
implicit declarations on Postgres can lower to `public` consistently
from both TS and PSL paths.
Signed-off-by: Will Madden <[email protected]>
…ce 1 fix) Adjusts the namespaceId coordinate added in slice 1 from "always-present at runtime with hidden enumerability" to a plain optional property — `undefined` when the table is on the late-bound default, populated when an explicit non-unbound coordinate is set. The original "always-present" shape forced downstream consumers that build raw `StorageTable`-shaped object literals (the ORM client tests, e2e fixtures) to add a `namespaceId` field everywhere to satisfy strict structural typing. Making the property optional keeps existing literals well-typed without the field, while preserving the byte-stable JSON envelope guarantee: undefined inputs and explicit `__unbound__` inputs both leave the property off the class (no enumerable entry → no JSON entry). Consumers that need a resolved coordinate read `table.namespaceId ?? UNBOUND_NAMESPACE_ID`. Signed-off-by: Will Madden <[email protected]>
…(M5a R5 FR15 slice 3) `buildSqlContractFromDefinition` now walks the contract`s declared namespace list together with every `StorageTable.namespaceId` referenced by a model and parks the resolved set of `Namespace` concretions in `SqlStorage.namespaces`. The framework `UNBOUND_NAMESPACE_ID` slot is always present so the late-bound default stays addressable regardless of authoring choices. Per-target concretions are supplied by a new `createNamespace: (id: string) => Namespace` factory threaded through `defineContract` and the SQL PSL interpreter. The SQL family layer stays target-agnostic and falls back to the family `SqlUnboundNamespace` singleton for single-namespace contracts that omit the factory; multi-namespace contracts now require the target to plumb its factory in (otherwise the family throws with an actionable diagnostic naming the missing factory). Two factories ship alongside the existing target concretions: - `postgresCreateNamespace(id)` → `PostgresSchema.unbound` for the sentinel, `new PostgresSchema(id)` otherwise. - `sqliteCreateNamespace(id)` → `SqliteUnboundDatabase.instance` for the sentinel; throws on any other coordinate (SQLite has no schema concept). Tests cover the family-layer population (declared/referenced/dedup walk, fallback for single-namespace, throw without factory for named coordinates) plus per-target factory behaviour. The Postgres DDL emitter still consults the planner`s `ctx.schemaName` flat string rather than `namespaces[id].qualifyTable(name)` — that refactor crosses ~28 call sites across the migration planner and is the natural slice for a follow-on round (the AC6 integration test depends on it). Signed-off-by: Will Madden <[email protected]>
…alidation (M5a R5 FR16a)
Extends `model(name, { namespace, fields })` so SQL contracts authored
through the TypeScript surface can pin a model to a declared
namespace. The value flows `model() → ContractModelBuilder.stageOne →
RuntimeModelSpec → ModelNode.namespaceId → StorageTable.namespaceId`,
mirroring the path the SQL PSL interpreter already uses for the
explicit `namespace { … }` block.
Defensive validation in `defineContract`:
- Per-model `namespace` must appear in the contract`s declared
`namespaces` list; otherwise the contract is rejected with a
diagnostic naming the unknown coordinate and listing the
declared options.
- Reserved IR sentinels (`__unbound__`, `__unspecified__`) are
rejected on every SQL target.
- The Postgres-specific keyword `unbound` is rejected on
Postgres and the diagnostic points authors at the PSL
`namespace unbound { … }` block (the only late-binding opt-in
surface today).
- SQLite contracts reject every per-model `namespace` outright
(SQLite has no schema concept).
The Mongo TS parity surface from the round spec is deferred:
Mongo`s per-model `namespace` semantics aren`t pinned down yet
(Mongo binds databases via connection string, not per-collection
schema), so adding the surface without a clear semantic mapping
would create authoring noise without value. The Mongo PSL
interpreter`s blanket rejection of `namespace { … }` blocks (from
R4) already covers the family today. Surfacing the TS surface is
tracked alongside the Mongo namespace-semantics design decision.
Signed-off-by: Will Madden <[email protected]>
…st (M5a R5 AC6 substrate) Signed-off-by: Will Madden <[email protected]>
…on (M5a R6 substrate)
Add `regclassLiteral(name)` and `schemaSqlExpression()` to PostgresSchema
with overrides on PostgresUnboundSchema (elide qualifier; fall back to
`current_schema()` for catalog-query nspname matchers). Refactor every
schema-aware helper in `planner-sql-checks.ts` to dispatch through
`postgresCreateNamespace(schema)` so the unbound branch lives in the
polymorphic override, not at any call site.
Helper signatures stay `(schema: string, …)` so existing call sites and
unit tests are unchanged for non-unbound schemas — `postgresCreateNamespace
("public").qualifyTable("user")` produces the same `"public"."user"` as
the previous `quoteIdentifier`-based composition. Adding the unbound
branch is the foundation the planner rewire (next slice) sits on.
Signed-off-by: Will Madden <[email protected]>
…ner (M5a R6 FR15)
Add `effectiveSchemaForTable(ctx, table)` to `planner-strategies.ts`.
Reads the table's `namespaceId` from `ctx.toContract.storage.tables`
and falls back to the global `ctx.schemaName` when absent. Threads the
result through every `*Call` constructor that emits per-table DDL —
both in the strategy layer and in `mapIssueToCall`. Tables declared
in `namespace unbound { … }` (or any named namespace) now drive their
own `*Call.schemaName` independently of the planner-wide default.
Single-namespace contracts stay byte-identical: every existing
`StorageTable` has `namespaceId === undefined`, so the helper falls
through to `ctx.schemaName` (typically `"public"`) — fixtures and
emitted contracts regenerate unchanged (`pnpm fixtures:check`
returned green).
The enum-rebuild recipe also routes column-altering ops through
`effectiveSchemaForTable` so a Postgres enum referenced by a
namespaced table renders against the table's namespace, not the
planner default.
Cross-namespace FK qualification stays scoped to "same-namespace FK"
for this round (FK target qualifier reuses the source table's
`schemaName`); cross-namespace FK plumbing lands with M5b's
`ForeignKey { source, target }` restructure.
Signed-off-by: Will Madden <[email protected]>
…in effectiveSchemaForTable (M5a R6 FR16c)
Strengthen `effectiveSchemaForTable` so the planner can resolve
per-table namespaces for contracts that explicitly populate
`SqlStorage.namespaces` with Postgres concretions (the FR16a
authoring path). When the table carries no explicit `namespaceId`,
inspect the contract's namespaces map:
- Family-default map (`{ __unbound__: SqlUnboundNamespace.instance }`):
legacy contract — keep falling back to `ctx.schemaName` so the 32
existing single-namespace fixtures stay byte-identical.
- Postgres-aware map (the unbound slot is a `PostgresSchema`): apply
FR16c — default to `'public'` if the contract declared one,
else to the framework `__unbound__` sentinel (the only other slot
the author chose to populate, so the contract's implicit default
is unbound).
This is the seam that lets a contract authored as
`new SqlStorage({ namespaces: { __unbound__: PostgresSchema.unbound } })`
emit unqualified DDL — every per-table call routes through the
unbound `Namespace` concretion and `search_path` resolves the
schema at runtime. AC6 multi-tenancy depends on this dispatch
shape; the next commit lands the live PGlite test that exercises
it end-to-end.
`pnpm fixtures:check` regenerates byte-identically; existing
adapter and target unit suites stay green (parallel-load flake in
`planner.reconciliation.integration.test.ts` reproduced on a full
package run, passes in isolation — known pre-existing flake).
Signed-off-by: Will Madden <[email protected]>
Plans an unbound contract (`namespaces: { __unbound__:
PostgresSchema.unbound }`) once and applies the *same* unqualified
DDL twice — once per tenant via session-scoped `search_path`. Each
apply lands in a different physical schema even though the operator
hands the runner identical SQL. Confirms:
- The plan's precheck / execute / postcheck SQL contains no
`"public"."tenant"` qualifier — qualifier dispatch through
`PostgresSchema.unbound` elided the schema prefix.
- After applying with `search_path=tenant_a` and again with
`search_path=tenant_b`, both schemas hold their own physical
`tenant` table; `public` stays empty (no leakage).
- Insert / select round-trips on each tenant remain isolated:
tenant_a sees only its row, tenant_b sees only its row.
Pairs with the R5 contract-side substrate test
(`packages/3-extensions/postgres/test/psl-namespace-qualifier-routing.test.ts`):
R5 proves PSL → `SqlStorage.namespaces` qualifier routing; this
test proves that routing carries through the planner and runtime
end-to-end against PGlite-backed Postgres.
Uses a single `PostgresControlDriver` and switches `search_path` per
operation (the dev-database harness enforces a single active
connection, so two independent tenant drivers would queue rather
than truly parallel-isolate — session-local `search_path` on a
single driver is the cleanest way to exercise the
`__unbound__` qualifier seam against a real Postgres backend).
Signed-off-by: Will Madden <[email protected]>
… R7 substrate) Adds the FR15 nested-by-namespace view to SqlStorage as tablesByNamespace alongside the existing flat tables field. Both views are populated at construction; constructor accepts either flat or nested input shape. Same dual-shape contract for types / typesByNamespace. New helpers (iterateAllTables, iterateTablesWithCoords, findTableByName, findTableByCoord, findTypeByName, findTypeByCoord, countAllTables, listAllTableNames) read the nested view, falling back to wrapping tables under the unbound namespace for type-shape consumers that satisfy SqlStorage structurally without round-tripping through the constructor. Signed-off-by: Will Madden <[email protected]>
…est (M5a R7 F1 test) The dual-shape view substrate (commit f19044664) populated tablesByNamespace enumerably; that leaked the derived nested projection into JSON.stringify and contract canonicalisation, breaking storage-hash byte-identity on existing single-namespace fixtures. Marking the property non-enumerable keeps the in-memory back-pointer accessible to the iterateTables* / findTableByCoord helpers while leaving the on-disk envelope identical to the legacy flat shape. Adds the cross-namespace same-named tables regression test FR15 + the reviewer F1 finding require: auth.User + public.User must coexist after construction, both addressable by (namespaceId, name), and findTableByName must throw on the ambiguous flat lookup. Signed-off-by: Will Madden <[email protected]>
AC4a calls for "round-trip preserves namespace assignments" across both
authoring surfaces. Each path independently had coverage that it lowered
namespace declarations to StorageTable.namespaceId, but nothing asserted
the two surfaces produced structurally-identical IR for the same logical
contract.
Adds a parity suite that authors the same two-namespace contract
(public.Post + auth.User) via PSL `namespace foo { … }` and the TS
`model(name, { namespace: "foo" })` field, then asserts namespace map
identity, per-table namespaceId agreement, and matching nested
(namespaceId, tableName) coordinates. The single-namespace case is
included as a smoke check that top-level declarations stay byte-stable
on both surfaces.
Signed-off-by: Will Madden <[email protected]>
Closes the remaining authoring → emit → validate → hydrate coverage gap for multi-namespace contracts. The flat JSON envelope carries each table's namespaceId back-pointer, so reconstructing a SqlStorage from a flat input map (the on-disk shape) recovers the same nested (namespaceId, name) coordinates the original nested input produced. Three cases pinned: - Multi-namespace, distinct table names: full stringify → parse → reconstruct round-trip yields identical coordinates. - Single-namespace: JSON envelope stays flat (no tablesByNamespace key) to anchor byte-identical hashes for the existing fixture corpus. - Multi-namespace: each table's namespaceId surfaces in the JSON envelope so downstream consumers can re-bucket without losing the namespace assignment. The same-named-table-across-namespaces collision case (auth.User + public.User) is the F1 regression covered separately in sql-storage-namespace-buckets.test.ts — the flat JSON envelope cannot carry both entries by design, and the constructor rejects flat input that names the same table twice within a single namespace. Signed-off-by: Will Madden <[email protected]>
…5a R7 F3) The flat JSON envelope cannot express two same-named tables in distinct namespaces — auth.User + public.User collide on the flat key and one entry is silently dropped on JSON.stringify. The runtime IR holds both via tablesByNamespace, but the persisted envelope until now lost half the data. SqlStorage.toJSON (installed non-enumerably on the prototype so BuiltStorage<Definition> stays structurally assignable) emits the legacy flat shape by default — preserving byte-identical hashes on the 32 single-namespace fixtures and on multi-namespace contracts whose table names are unique across namespaces — and escalates to the FR15 nested shape (Record<NamespaceId, Record<TableName, StorageTable>>) only when the flat shape would lose data, i.e. when any name appears in two or more namespace buckets. Same condition applies to the types slot. validateStorage / validateSqlContractFully discriminate the two shapes at the runtime entry point and route through the matching arktype schema (FlatStorageSchema vs NestedStorageSchema). StorageTableSchema gains an optional namespaceId so the flat envelope round-trips per-table back-pointers without rejection. Extends the multi-namespace round-trip test suite to cover both flat→nested-IR rehydration and nested→nested-IR rehydration via validateStorage, pinning the cross-namespace collision case (auth.User + public.User) end-to-end. Signed-off-by: Will Madden <[email protected]>
…to M5b plan M5a is SATISFIED on the local branch (cumulative reviewer round 2 verdict). Mark the 11 M5a tasks complete with status notes, document the FR15 envelope-shape carve-out R7 landed (flat by default for hash byte-identity, nested when names collide across namespaces; in-memory IR truth is the FR15 nested shape), and fold three new substrate items into M5b's plan: F4 (namespace-polymorphic dispatch for `effectiveSchemaForTable`), F5 (flat-view silent-drop footgun on `storage.tables[name]`), F6 (`sortIndexesAndUniques` no-op on nested envelope). Signed-off-by: Will Madden <[email protected]>
…ontract.d.ts
Migrate generateTablesType and generateStorageTypesType to emit the
canonical nested shape { [namespaceId]: { [tableName]: ... } } matching
the runtime SqlStorage IR. Previously emitted flat { [tableName]: ... }.
This closes the framework-level type invariant gap where the emitted
contract.d.ts Contract shape did not structurally match Contract<SqlStorage>.
Signed-off-by: Will Madden <[email protected]>
…les/types
Pure mechanical output from pnpm fixtures:emit after the emitter change.
All contract.d.ts files now emit storage.tables and storage.types in the
canonical nested-by-namespace shape: { [namespaceId]: { [name]: ... } }.
Signed-off-by: Will Madden <[email protected]>
…test
Update the test-inline Contract<SqlStorage> fixture to the canonical
nested-by-namespace shape (tables under public:{}, types under public:{})
matching the updated SqlStorage type constraint.
Signed-off-by: Will Madden <[email protected]>
…ted tables Add the same FlatTablesOf<C> bridge pattern from sql-builder to sql-orm-client type machinery (ResolvedStorageColumn, ModelStorageTableDef, IsToOneRelationNullable). Update runtime model-accessor to use findTableByName for nested table lookup. Migrate all test files from flat storage.tables access to canonical nested shape or findTableByName. TODO(TML-2550): remove bridge — redesign ORM types for namespace-aware access. Signed-off-by: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…gres PSL tests to nested access Implementer subagent's regen pass (817c41a0d) only covered the curated `fixtures:emit` filter and missed every other example app's generated contract.d.ts plus per-extension contracts. Direct typecheck across the monorepo failed for 13 packages, all with the same root cause — the generated Contract still declared flat-shape `storage.tables` while the runtime SqlStorage IR is nested. Regenerates the missed example contracts (paradedb-demo, prisma-next-demo-sqlite, prisma-next-postgis-demo, react-router-demo, cipherstash-integration, multi-extension-monorepo/audit, multi-extension-monorepo/feature-flags) via each app's local emit script. Three required a stub DATABASE_URL; the multi-extension-monorepo's `app` package still fails to emit due to a separate hash-mismatch propagation issue and is left for a follow-up. Migrates two Postgres PSL parity tests that used flat-shape `storage.tables['name']?.namespaceId` access to the canonical `findTableByName(storage, 'name')?.namespaceId` helper. The helper is the canonical accessor that walks the nested namespace buckets without leaking shape assumptions into call sites. After this commit `@prisma-next/postgres` typechecks clean. Remaining failures are concentrated in a small set of flat-shape consumers (`examples/prisma-next-demo/src/app/ContractView.tsx`, two test files, and one demo's auth-schema source) plus pre-existing baseline failures in `@prisma-next/adapter-postgres` `control-adapter.ts` that exist independent of this work. Signed-off-by: Will Madden <[email protected]>
…d storage.tables Partial cleanup of consumers that read storage.tables with flat-shape access patterns. The runtime IR + emitted contract.d.ts are now nested-by-namespace (817c41a0d, 848f10161, 0dfe862d0), so consumers must access tables[namespaceId][tableName] rather than tables[tableName]. Source consumers: - examples/prisma-next-demo/src/app/ContractView.tsx: nested flatMap iteration over (namespaceId, tableName) coordinates. Test consumers: - examples/prisma-next-demo/test/contract-authoring.test.ts: tables[public].post + tables[auth].user with defensive checks for strict-index-signature lint. - examples/prisma-next-demo/test/demo-dx.integration.test.ts: nested loop iterating namespace buckets. - examples/prisma-next-demo/test/demo-dx.types.test.ts: expectTypeOf assertions updated for nested namespace shape. - test/integration/test/authoring/paradedb-bm25-narrowing.test.ts: tables['__unbound__']?.doc lookup with defensive check. - test/integration/test/cli.emit-cli-process.e2e.test.ts: EmittedContract local type updated to nested shape; toMatchObject assertion updated to nest under __unbound__. Fixture regeneration: - test/e2e/framework/test/sqlite/fixtures/generated/: regenerated via the package's local `prisma-next contract emit --config test/sqlite/fixtures/prisma-next.config.ts` invocation. The framework e2e tests use this fixture path which is outside the curated fixtures:emit filter. After this commit @prisma-next/sql-orm-client, react-router-demo, examples/prisma-next-demo, test/e2e/framework all tsc-clean. Remaining typecheck failures concentrated in test/integration/test/contract-builder.test.ts (more flat-shape access sites to migrate) and pre-existing @prisma-next/adapter-postgres baseline failure unrelated to this PR. Signed-off-by: Will Madden <[email protected]>
…ubagent dies mid-dispatch Records the failure mode where a dead subagent's missing final report triggers "I'll just check the DoD myself" → implementation drift over 30+ minutes. Mitigation: hard rule that the orchestrator's very next action when a subagent terminates without report is to dispatch a finisher subagent, not to verify state and tidy up. Reference incident from this session's TML-2520 M5c Phase 3 work. Signed-off-by: Will Madden <[email protected]>
…tables
Migrate all remaining flat-shape contract.storage.tables access across
integration test files to the canonical nested-by-namespace shape:
- contract-builder.test.ts: runtime + type-level assertions
- contract-builder.types.test-d.ts: type-level table/column assertions
- dsl-type-inference.test-d.ts: literal type preservation tests
- family.schema-verify.{types,dependencies}.test.ts: fixture spreads
- extension-pgvector-scenario-a: nest fixture table under namespace
- value-objects sql-contract.d.ts: regenerate with nested tables type
Signed-off-by: Will Madden <[email protected]>
…xactOptionalPropertyTypes Signed-off-by: Will Madden <[email protected]>
…le workspace The previous fixtures:emit filter only included a curated subset of packages (sql-builder, sql-orm-client, e2e-tests, e2e-sqlite-tests [didn't exist], integration-tests, prisma-next-demo, prisma-next-cloudflare-worker). This missed every other example app and every per-extension contract.d.ts. That gap is the substrate behind the orchestrator drift recorded in projects/agile-agent-orchestration/calibration/prisma-next.md § 3.14: a substrate-shape change (storage.tables nested-by-namespace) regenerated only the curated set; the rest of the consumer surface stayed flat-shape and needed catch-up migration commits per-app. Changes: - fixtures:emit now uses path-based pnpm filters: ./examples/*, sql-builder, sql-orm-client, e2e-tests, integration-tests (run --if-present emit), plus ./packages/3-extensions/* (run --if-present build:contract-space). DATABASE_URL stub is inlined so cipherstash, paradedb, and postgis demos can emit without a real DB. - fixtures:check's git diff --exit-code path list expanded to cover every emit target. - Regenerated 3 extension contracts (cipherstash, pgvector, postgis) that were stale flat-shape because the previous filter never ran their emit. Packages now covered (per-area inventory): - 10 example apps (cipherstash-integration, mongo-blog-leaderboard, mongo-demo, paradedb-demo, prisma-next-cloudflare-worker, prisma-next-demo-sqlite, prisma-next-demo, prisma-next-postgis-demo, react-router-demo, retail-store) - 4 extensions with build:contract-space (cipherstash, paradedb, pgvector, postgis) - 4 packages with emit (sql-builder, sql-orm-client, e2e-tests, integration-tests) Out of scope (follow-ups): - @prisma-next/example-multi-extension-monorepo's build:contract-spaces chain fails at the aggregating app with 'Extension descriptor headRef.hash does not match its contractJson'. Structural hash-propagation issue; needs its own dispatch. - test/e2e/framework/test/sqlite/fixtures/ has a prisma-next.config.ts but no script that emits it (the e2e-tests package's emit script only targets test/fixtures/). Currently maintained manually; consider adding an emit step to the package script. Signed-off-by: Will Madden <[email protected]>
…cannot be relied on Records that backgrounded subagent dispatches (`run_in_background: true`) can complete successfully without ever delivering the completion notification to the orchestrator within the conversation window. Surfaced by two TML-2520 PR2 dispatches in this session where the user had to manually report "the subagent has finished" because the notification path was silent. Mitigation: triangulate from `git log --oneline + clean tree + wall-clock past budget+50%`, then use resume-as-probe (`Task(resume=id, ...)`) as the definitive aliveness check — it errors if the agent is alive, succeeds if it's done. Signed-off-by: Will Madden <[email protected]>
… namespace Migrate flat-shape storage.tables / storage.types assertions across the PSL interpreter and provider test suites to the canonical nested-by-namespace shape. Signed-off-by: Will Madden <[email protected]>
…pace Update the test-local `StorageView` helper plus its dotted-access sites to the canonical nested-by-namespace tables/types shape. Signed-off-by: Will Madden <[email protected]>
…space Migrate flat-shape `storage.tables as Record<string, ...>` casts to access the `__unbound__` namespace bucket, matching the canonical nested storage.tables shape. Signed-off-by: Will Madden <[email protected]>
…literals - emitter.test.ts inline contract fixtures wrap tables under __unbound__ - parameterized-types.test.ts storage.types assertions nest under __unbound__ - postgres-contract-serializer.test.ts storage.types access nests through __unbound__ to match the nested storage shape Signed-off-by: Will Madden <[email protected]>
…phan extractors storage.tables is now `Record<namespaceId, Record<tableName, ...>>`. The aggregate-loader's disjointness check and the verifier's orphan-elements walk previously read keys directly off `storage.tables`, which now yields namespace IDs instead of leaf table names. - `extractStorageElementNames`: walks two levels and collects leaf table names. Same fix applied for `collections` on the Mongo branch. - `detectOrphanElements` (verifier): reuses `extractStorageElementNames` instead of duplicating the flat walk, so the orphan computation stays correct. - Tests: nest test-only contract literals under `__unbound__` so the helpers under test get the canonical nested shape. Schema fixtures stay flat (introspected `SqlSchemaIR` is still flat-keyed by table name). Signed-off-by: Will Madden <[email protected]>
…gs baselines against new storage hash
The contract IR substrate change (nested-by-namespace tables) bumped every
contract's storageHash. The `audit` and `feature-flags` contract spaces in
this monorepo example track standalone, hand-authored baseline migrations
whose `describe().to` and `refs/head.json` were pinned to the pre-change
hashes — leaving them stale once the new contract IR landed.
For each package:
- Bump `migration.ts`'s `describe().to` to the freshly-emitted storage hash.
- Re-emit `ops.json` + `migration.json` via `tsx migration.ts`.
- Refresh `refs/head.json` to match.
- Copy the new `src/contract.{json,d.ts}` into the baseline's
`end-contract.{json,d.ts}`.
This unblocks the app's aggregate emit (which validates each extension
descriptor's `headRef.hash` against its `contractJson`) and lets the
multi-space e2e test reach a clean apply.
Signed-off-by: Will Madden <[email protected]>
…facts under nested storage shape
Re-emits `app/src/contract.{json,d.ts}` so the app's storage hash and `tables`
shape track the new nested-by-namespace IR alongside the upstream extension
contracts. Unblocks the example's e2e test and keeps the aggregate emit
output in sync with what `build:contract-spaces` produces.
Signed-off-by: Will Madden <[email protected]>
…riteria Signed-off-by: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughContracts and IR switch to namespace-scoped storage with source/target foreign keys. PSL AST/parser/printer become namespace-aware. Validators, factories, and tooling are updated. Examples and demos regenerate contracts; demo migrations rebaseline to auth/public and add pgvector. UI and tests adapt. Scripts and package fixtures updated. ChangesNamespace-aware refactor and consumers
Prisma Next demo migrations rebaseline (auth/public + pgvector)
Sequence Diagram(s)sequenceDiagram
participant AST as PSL Parser
participant IR as SqlStorage/ForeignKey
participant Emitter as Emitter/Validators
participant App as Examples/UI
AST->>AST: Build namespaced AST (namespaces[])
AST->>IR: Generate namespaced storage + FK source/target
IR->>Emitter: Validate schema (iterateTablesWithCoords/findTableByCoord)
Emitter->>App: Emit contract.{json,d.ts} with namespaces
App->>App: Render tables by namespace, show FK source→target
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Suggested reviewers
Poem
✨ Finishing Touches🧪 Generate unit tests (beta)
⚔️ Resolve merge conflicts
|
There was a problem hiding this comment.
Actionable comments posted: 13
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
packages/1-framework/1-core/framework-components/src/ir/storage.ts (1)
31-37:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winRemove transient planning IDs from this JSDoc block.
This comment still references transient artifacts (
F16,PR2). Please replace them with stable, behavior-focused wording.Suggested edit
- * them (Mongo). Future open (F16): extend the per-target + * them (Mongo). Future work can extend the per-target * `ContractSerializer` integration-test surface with an explicit * envelope-shape assertion for each target, so the strip-vs-pass-through * choice is locked at test time rather than implied by the override - * presence/absence. Earned by PR2's per-target namespace lift, when + * presence/absence. This became relevant after the per-target namespace lift, when * `PostgresSchema` / `SqliteUnboundDatabase` start carryingAs per coding guidelines, source-code comments must not reference transient project artifacts including milestone/task-style identifiers.
🤖 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/1-framework/1-core/framework-components/src/ir/storage.ts` around lines 31 - 37, Update the JSDoc block that currently mentions transient planning IDs ("F16", "PR2") and other project-tracking artifacts by removing those tokens and replacing them with stable, behavior-focused wording describing the intended future change: e.g., explain that tests should assert envelope shape per-target, and that once per-target schemas (PostgresSchema/SqliteUnboundDatabase) include target-specific fields the serializer test surface will be extended; ensure the JSDoc (the comment containing "extend the per-target `ContractSerializer` integration-test surface..." and references to "F16" and "PR2") no longer contains milestone/task identifiers and instead describes the expected behavior and conditions for the change.packages/2-sql/1-core/contract/src/factories.ts (1)
43-58:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
table()andfk()don't compose correctly for namespaced same-namespace relations.Right now
fk()resolves a missingopts.namespaceIdtoUNBOUND_NAMESPACE_IDbeforetable()has a chance to contribute its own namespace. Sotable(..., { namespaceId: 'auth', fks: [fk(['userId'], 'user', ['id'])] })emits a target in__unbound__instead ofauth. That silently mis-stamps ordinary same-namespace FKs unless every caller repeats the table namespace on each relation.Also applies to: 71-80
🤖 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/factories.ts` around lines 43 - 58, The ForeignKey factory is forcing opts.namespaceId to UNBOUND_NAMESPACE_ID too early, so fk(...) produces a target.namespaceId='__unbound__' before table(...) can supply its namespace; update the logic in the fk factory (the targetNamespaceId resolution used when constructing the new ForeignKey) to leave namespaceId undefined when opts.namespaceId is omitted (i.e., only use opts.namespaceId if present, do not substitute UNBOUND_NAMESPACE_ID here), and ensure the final namespace stamping still applies UNBOUND_NAMESPACE_ID later when fully resolving table namespaces; apply the same change to the analogous block referenced around lines 71–80 and keep applyFkDefaults, constraint/index handling and the rest of the ForeignKey construction unchanged.packages/2-sql/1-core/contract/src/index-type-validation.ts (1)
11-31:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winInclude namespace coordinates in validation errors.
With namespace-aware storage,
"Table \"${tableName}\""is ambiguous when multiple namespaces contain the same table name. IncludenamespaceIdin these messages so failures are actionable.Suggested patch
- for (const { name: tableName, table } of iterateTablesWithCoords(contract.storage)) { + for (const { namespaceId, name: tableName, table } of iterateTablesWithCoords(contract.storage)) { ... - `Table "${tableName}" index on columns [${index.columns.join(', ')}] has options without a type`, + `Table "${namespaceId}.${tableName}" index on columns [${index.columns.join(', ')}] has options without a type`, ... - `Table "${tableName}" index on columns [${index.columns.join(', ')}] uses unregistered index type "${index.type}"`, + `Table "${namespaceId}.${tableName}" index on columns [${index.columns.join(', ')}] uses unregistered index type "${index.type}"`, ... - `Table "${tableName}" index on columns [${index.columns.join(', ')}] has invalid options for type "${index.type}": ${result.summary}`, + `Table "${namespaceId}.${tableName}" index on columns [${index.columns.join(', ')}] has invalid options for type "${index.type}": ${result.summary}`,🤖 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/index-type-validation.ts` around lines 11 - 31, The validation messages in the loop over iterateTablesWithCoords(contract.storage) are ambiguous because they only mention tableName; update all ContractValidationError messages in this block (the throws that reference `Table "${tableName}" ...`) to also include the `namespaceId` from the iterated coords (e.g., `namespaceId: ${namespaceId}`) so errors show both namespace and table, including the throws for missing type with options, unregistered index type, and invalid options produced by `entry.options`; adjust the message templates that use `index.columns` and `index.type` accordingly to include namespace context.packages/2-sql/1-core/contract/src/validators.ts (1)
411-433:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winNamespace-aware checks should report namespace-aware table identifiers.
Errors still reference only
tableName, which is ambiguous once same table names exist across namespaces. IncludenamespaceIdin thrown messages throughout semantic/consistency validation.Also applies to: 615-700
🤖 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 411 - 433, The error messages use the ambiguous tableName; change them to a namespace-aware identifier by extracting the namespaceId from the iterateTablesWithCoords result (or table.namespaceId) and composing a single identifier (e.g., `${namespaceId}:${tableName}`) and use that identifier instead of tableName in the errors.push calls inside the namedObjects loop and the other validation blocks (including the similar checks around lines 615-700). Update all occurrences where tableName is interpolated in thrown/collected messages (e.g., the message in the loop that pushes `Table "${tableName}": ...`) to use the new namespace-aware identifier so messages uniquely identify tables across namespaces.packages/1-framework/2-authoring/psl-parser/src/parser.ts (1)
224-267:⚠️ Potential issue | 🟠 Major | ⚡ Quick winCheck named types against composite type names too.
compositeTypeNamesis collected here but never consulted, sotypes { Address = String }can coexist withtype Address { ... }without a diagnostic. The later field normalization already treats composite types as authoritative, so this silently changes whatAddressmeans instead of rejecting the collision.Suggested fix
if (enumNames.has(declaration.name)) { pushDiagnostic(context, { code: 'PSL_INVALID_TYPES_MEMBER', message: `Named type "${declaration.name}" conflicts with enum name "${declaration.name}"`, span: declaration.span, }); + continue; + } + if (compositeTypeNames.has(declaration.name)) { + pushDiagnostic(context, { + code: 'PSL_INVALID_TYPES_MEMBER', + message: `Named type "${declaration.name}" conflicts with composite type name "${declaration.name}"`, + span: declaration.span, + }); }🤖 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/1-framework/2-authoring/psl-parser/src/parser.ts` around lines 224 - 267, The types validation loop currently checks SCALAR_TYPES, modelNames, and enumNames but omits compositeTypeNames, so named types can silently collide with composite types; update the loop that iterates over typesBlock?.declarations (the block that already calls pushDiagnostic for scalar/model/enum collisions) to also check compositeTypeNames.has(declaration.name) and call pushDiagnostic with code 'PSL_INVALID_TYPES_MEMBER', an appropriate message like `Named type "<name>" conflicts with composite type "<name>"`, and span declaration.span so composite-type/name collisions are rejected the same way as models/enums.
🧹 Nitpick comments (2)
examples/prisma-next-demo/test/contract-authoring.test.ts (1)
6-10: ⚡ Quick winPrefer direct typed namespace access instead of optional chaining guard.
This test can rely on typed contract shape and use direct access/non-null assertions rather than defensive optional chaining + manual throw.
Suggested patch
- const postTable = contract.storage.tables['public']?.post; - const userTable = contract.storage.tables['auth']?.user; - if (!postTable || !userTable) throw new Error('expected post and user tables'); + const postTable = contract.storage.tables.public.post; + const userTable = contract.storage.tables.auth.user;As per coding guidelines: “Prefer assertions over defensive checks when data is guaranteed to be valid … Remove optional chaining … for properties that are guaranteed to exist after validation.”
🤖 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 `@examples/prisma-next-demo/test/contract-authoring.test.ts` around lines 6 - 10, The test uses optional chaining and a manual throw to guard contract.storage.tables lookups (postTable and userTable); replace the defensive checks with direct typed access/non-null assertions since the contract shape is guaranteed: access contract.storage.tables['public'].post and contract.storage.tables['auth'].user directly (or use ! after the access) and then read postTable.columns.userId and userTable.columns.id into userIdColumn and userIdTargetColumn without the runtime throw/optional chaining guard.packages/1-framework/2-authoring/psl-printer/src/ast-to-print-document.ts (1)
270-275: ⚡ Quick winPromote the inline
import(...)type to a top-level import.Keeping
PslAttributeNamedArgumentin the main import list makes this predicate easier to read and matches the repo rule for source files.Suggested cleanup
import type { PslAttribute, + PslAttributeNamedArgument, PslAttributeArgument, PslDocumentAst, PslEnum, PslField, @@ const named = Object.fromEntries( rel.args .filter( - (a): a is import('`@prisma-next/framework-components/psl-ast`').PslAttributeNamedArgument => - a.kind === 'named', + (a): a is PslAttributeNamedArgument => a.kind === 'named', ) .map((a) => [a.name, a.value.trim()]), );As per coding guidelines, "Prohibit inline type imports in source files; use top-level imports instead."
🤖 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/1-framework/2-authoring/psl-printer/src/ast-to-print-document.ts` around lines 270 - 275, The predicate currently uses an inline type import (import('...').PslAttributeNamedArgument) inside the filter for rel.args and should instead reference a top-level import; add PslAttributeNamedArgument to the module's import list and replace the inline type in the filter (the a is ... PslAttributeNamedArgument => a.kind === 'named') with that top-level symbol so the predicate reads simply (a): a is PslAttributeNamedArgument => a.kind === 'named' and conforms to the repo rule against inline type imports.
🤖 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 `@examples/prisma-next-demo/migrations/app/20260517T1323_initial/migration.ts`:
- Around line 23-24: The enum type created with createEnumType('public',
'user_type', ...) is referenced as typeSql: '"user_type"' in the auth.user table
creation; update that reference to schema-qualify the enum (e.g., use typeSql:
'"public"."user_type"') so the DDL does not depend on search_path. Locate the
auth user table creation in migration.ts (the createTable call that defines the
"user" table and the typeSql entry) and replace the unqualified type name with
the fully qualified "public"."user_type" identifier.
In `@examples/prisma-next-demo/src/app/ContractView.tsx`:
- Around line 72-77: The React key and displayed target info for foreign keys
only use foreignKey.source.columns and foreignKey.target.table, which can
collide or hide cross-namespace targets; update the key to include the target
namespace (e.g., combine foreignKey.source.columns with
foreignKey.target.namespaceId and foreignKey.target.table) and update the
rendered target text to show the namespaceId alongside the table (use
foreignKey.target.namespaceId + ':' + foreignKey.target.table and keep the
target.columns join as-is) so keys are unique and the UI clearly indicates
cross-namespace FKs.
In `@packages/1-framework/0-foundation/contract/src/canonicalization.ts`:
- Around line 93-97: Remove the transient FR identifier from the comment above
the isTableUniques declaration and rephrase it to describe the behavior directly
(e.g., explain that a nested envelope at depth 5 —
storage.tables.<namespaceId>.<tableName>.<field> — must preserve table-level
empty-defaults like uniques, indexes, and foreignKeys so the persisted shape
remains schema-valid); apply the same removal/rephrasing to the other comment
block currently containing an FR reference (the block around lines 234–238) so
no FR/spec decision IDs remain in source comments.
In `@packages/1-framework/2-authoring/psl-printer/src/ast-to-print-document.ts`:
- Around line 32-41: The code keys models by unqualified model.name causing
collisions and mismatches for dotted names (e.g., auth.User vs public.User) in
modelNamespaceIndex and the FK graph built by buildModelFkDeps, so update the
pipeline to use a fully-qualified identifier (namespace + '.' + model.name or
model.fullyQualifiedName) everywhere: change flatPslModels output lookup and
modelNamespaceIndex population to use the qualified key, ensure buildModelFkDeps
and topologicalSortModels accept and compare these qualified names when building
deps and sorting, and normalize incoming FK targets (dotted or unqualified) to
the same qualified-key form before matching against modelNames and
modelNamespaceIndex.
In `@packages/1-framework/2-authoring/psl-printer/src/print-document.ts`:
- Around line 17-20: PrintNamespaceSection currently omits compositeTypes so
namespaces with composite type declarations are dropped during printing; update
the PrintNamespaceSection type to include a readonly compositeTypes field whose
element type matches the printer-side composite type used elsewhere (i.e. the
same type as PslNamespace.compositeTypes expects for serialization), and then
thread that new field through the code paths that construct/consume
PrintNamespaceSection (notably printPslFromAst and any functions creating
PrinterModel/PrintEnumSection arrays) so composite types are preserved during
round-trip printing.
In
`@packages/1-framework/3-tooling/migration/src/aggregate/extract-storage-element-names.ts`:
- Around line 50-55: The code currently assumes every top-level object (value)
is a namespace bucket and blindly collects its keys into names; change the guard
in extract-storage-element-names to first verify the candidate bucket actually
looks like an element-bucket before adding keys: inside the loop over
Object.values(value) (variables value and bucket), add a predicate such as
checking that Object.values(bucket).every(v => typeof v === 'object' && v !==
null && !Array.isArray(v)) (or equivalently that none of the bucket's property
keys are known flat-map keys like 'columns'|'primaryKey'|'indexes') and only
then iterate Object.keys(bucket) to names.add(name); otherwise skip so
flat/legacy table maps don’t leak keys like columns/primaryKey into names.
In `@packages/2-mongo-family/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 53-60: Remove the transient project artifact token "FR16c" (and
any similar spec/decision IDs) from the top explanatory comment that begins
"Mongo FR16c validation..." in the PSL interpreter source; keep the rationale
text that Mongo's authoring DSL exposes only the database namespace and rejects
explicit namespace blocks (including `namespace unbound { … }`) but delete the
"(FR16c)" label and any other tracking IDs so the comment documents behavior
only, not project-tracking metadata.
In `@packages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts`:
- Line 1683: Rename the test suite title to remove the transient spec ID: update
the describe(...) that currently reads "per-target namespace dispatch (FR16c)"
to a stable, behavior-oriented name such as "per-target namespace dispatch"
(i.e., edit the describe string in the test suite declaration to drop the
"(FR16c)" suffix).
In `@packages/2-sql/1-core/contract/README.md`:
- Around line 83-86: Docs state namespaceId is optional but the validator
(ForeignKeyReferenceSchema) requires namespaceId as a string; update the README
docs for ForeignKeyReference to reflect that namespaceId is required (remove
"Optional" wording and document it as a required string that holds the target
table's namespace coord) so the documentation matches the contract shape
(referencing the namespaceId and table fields and ForeignKeyReferenceSchema).
In `@packages/2-sql/1-core/contract/src/ir/foreign-key-reference.ts`:
- Around line 44-47: The constructor for ForeignKeyReference currently assigns
this.columns = input.columns then calls freezeNode(this), which leaves the
caller-owned array mutable; fix it by cloning and freezing the columns array
before storing it: create a shallow copy of input.columns (e.g.,
[...input.columns] or input.columns.slice()) and then freeze that copy (and
optionally freeze each column element if they are nodes) so assign the
cloned/frozen array to this.columns prior to calling freezeNode(this) to prevent
external mutation of the instance.
In `@packages/2-sql/1-core/contract/src/ir/foreign-key.ts`:
- Around line 71-75: The wrapper freeze is insufficient because
input.source.columns remains mutable; update the ForeignKey construction so
source.columns gets an immutable copy instead of referencing
input.source.columns directly (e.g., create a shallow copy of
input.source.columns and freeze that) while keeping the existing logic that
wraps/uses input.target via ForeignKeyReference; ensure the field name source
and class ForeignKey (and the target handling that checks instanceof
ForeignKeyReference) are preserved when making this change.
In `@packages/2-sql/1-core/contract/src/ir/sql-storage.ts`:
- Around line 129-138: The constructor leaves input.namespaces unnormalized and
mutable and doesn't validate that every table namespace from
normaliseTablesInput is present; fix by normalising and freezing namespaces
(e.g. call a normaliseNamespacesInput and freezeNestedNamespaces or use
Object.defineProperty like for 'types') and assign to this.namespaces from that
frozen result (use input.namespaces ?? DEFAULT_NAMESPACES). After you set
this.tables (result of normaliseTablesInput/freezeNestedTables), validate that
every namespace key used by this.tables exists in the normalised namespaces map
and throw a clear error if any are missing to enforce the invariant (reference:
this.namespaces, input.namespaces, normaliseTablesInput, freezeNestedTables,
DEFAULT_NAMESPACES, and the constructor that defines 'types').
In `@packages/2-sql/1-core/contract/src/validators.ts`:
- Around line 663-668: Remove transient spec-ID references like "FR16b" and
"FR15" from inline comments in this module; edit the comment block around the
ForeignKeyReference handling (the comment preceding targetNamespaceId and the
nearby comment block around lines referencing FR15/FR16b) to preserve the
explanatory text but delete any parenthetical spec decision IDs. Keep the
semantic explanation about cross-namespace FK lookup and that
fk.target.namespaceId is used, but eliminate the "(FR...)" tags to comply with
doc-maintenance rules.
---
Outside diff comments:
In `@packages/1-framework/1-core/framework-components/src/ir/storage.ts`:
- Around line 31-37: Update the JSDoc block that currently mentions transient
planning IDs ("F16", "PR2") and other project-tracking artifacts by removing
those tokens and replacing them with stable, behavior-focused wording describing
the intended future change: e.g., explain that tests should assert envelope
shape per-target, and that once per-target schemas
(PostgresSchema/SqliteUnboundDatabase) include target-specific fields the
serializer test surface will be extended; ensure the JSDoc (the comment
containing "extend the per-target `ContractSerializer` integration-test
surface..." and references to "F16" and "PR2") no longer contains milestone/task
identifiers and instead describes the expected behavior and conditions for the
change.
In `@packages/1-framework/2-authoring/psl-parser/src/parser.ts`:
- Around line 224-267: The types validation loop currently checks SCALAR_TYPES,
modelNames, and enumNames but omits compositeTypeNames, so named types can
silently collide with composite types; update the loop that iterates over
typesBlock?.declarations (the block that already calls pushDiagnostic for
scalar/model/enum collisions) to also check
compositeTypeNames.has(declaration.name) and call pushDiagnostic with code
'PSL_INVALID_TYPES_MEMBER', an appropriate message like `Named type "<name>"
conflicts with composite type "<name>"`, and span declaration.span so
composite-type/name collisions are rejected the same way as models/enums.
In `@packages/2-sql/1-core/contract/src/factories.ts`:
- Around line 43-58: The ForeignKey factory is forcing opts.namespaceId to
UNBOUND_NAMESPACE_ID too early, so fk(...) produces a
target.namespaceId='__unbound__' before table(...) can supply its namespace;
update the logic in the fk factory (the targetNamespaceId resolution used when
constructing the new ForeignKey) to leave namespaceId undefined when
opts.namespaceId is omitted (i.e., only use opts.namespaceId if present, do not
substitute UNBOUND_NAMESPACE_ID here), and ensure the final namespace stamping
still applies UNBOUND_NAMESPACE_ID later when fully resolving table namespaces;
apply the same change to the analogous block referenced around lines 71–80 and
keep applyFkDefaults, constraint/index handling and the rest of the ForeignKey
construction unchanged.
In `@packages/2-sql/1-core/contract/src/index-type-validation.ts`:
- Around line 11-31: The validation messages in the loop over
iterateTablesWithCoords(contract.storage) are ambiguous because they only
mention tableName; update all ContractValidationError messages in this block
(the throws that reference `Table "${tableName}" ...`) to also include the
`namespaceId` from the iterated coords (e.g., `namespaceId: ${namespaceId}`) so
errors show both namespace and table, including the throws for missing type with
options, unregistered index type, and invalid options produced by
`entry.options`; adjust the message templates that use `index.columns` and
`index.type` accordingly to include namespace context.
In `@packages/2-sql/1-core/contract/src/validators.ts`:
- Around line 411-433: The error messages use the ambiguous tableName; change
them to a namespace-aware identifier by extracting the namespaceId from the
iterateTablesWithCoords result (or table.namespaceId) and composing a single
identifier (e.g., `${namespaceId}:${tableName}`) and use that identifier instead
of tableName in the errors.push calls inside the namedObjects loop and the other
validation blocks (including the similar checks around lines 615-700). Update
all occurrences where tableName is interpolated in thrown/collected messages
(e.g., the message in the loop that pushes `Table "${tableName}": ...`) to use
the new namespace-aware identifier so messages uniquely identify tables across
namespaces.
---
Nitpick comments:
In `@examples/prisma-next-demo/test/contract-authoring.test.ts`:
- Around line 6-10: The test uses optional chaining and a manual throw to guard
contract.storage.tables lookups (postTable and userTable); replace the defensive
checks with direct typed access/non-null assertions since the contract shape is
guaranteed: access contract.storage.tables['public'].post and
contract.storage.tables['auth'].user directly (or use ! after the access) and
then read postTable.columns.userId and userTable.columns.id into userIdColumn
and userIdTargetColumn without the runtime throw/optional chaining guard.
In `@packages/1-framework/2-authoring/psl-printer/src/ast-to-print-document.ts`:
- Around line 270-275: The predicate currently uses an inline type import
(import('...').PslAttributeNamedArgument) inside the filter for rel.args and
should instead reference a top-level import; add PslAttributeNamedArgument to
the module's import list and replace the inline type in the filter (the a is ...
PslAttributeNamedArgument => a.kind === 'named') with that top-level symbol so
the predicate reads simply (a): a is PslAttributeNamedArgument => a.kind ===
'named' and conforms to the repo rule against inline type imports.
🪄 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: 66bddc6d-3de7-4b88-a0e0-480e878452fe
⛔ Files ignored due to path filters (4)
packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.jsonis excluded by!**/generated/**packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.jsonis excluded by!**/generated/**
📒 Files selected for processing (296)
.agents/skills/drive-qa-plan/SKILL.md.agents/skills/drive-qa-run/SKILL.mdCHANGELOG.mdexamples/cipherstash-integration/src/prisma/contract.d.tsexamples/cipherstash-integration/src/prisma/contract.jsonexamples/multi-extension-monorepo/app/src/contract.d.tsexamples/multi-extension-monorepo/app/src/contract.jsonexamples/multi-extension-monorepo/packages/audit/migrations/20260601T0000_create_audit_event/end-contract.d.tsexamples/multi-extension-monorepo/packages/audit/migrations/20260601T0000_create_audit_event/end-contract.jsonexamples/multi-extension-monorepo/packages/audit/migrations/20260601T0000_create_audit_event/migration.jsonexamples/multi-extension-monorepo/packages/audit/migrations/20260601T0000_create_audit_event/migration.tsexamples/multi-extension-monorepo/packages/audit/migrations/refs/head.jsonexamples/multi-extension-monorepo/packages/audit/src/contract.d.tsexamples/multi-extension-monorepo/packages/audit/src/contract.jsonexamples/multi-extension-monorepo/packages/feature-flags/migrations/20260601T0000_create_feature_flag/end-contract.d.tsexamples/multi-extension-monorepo/packages/feature-flags/migrations/20260601T0000_create_feature_flag/end-contract.jsonexamples/multi-extension-monorepo/packages/feature-flags/migrations/20260601T0000_create_feature_flag/migration.jsonexamples/multi-extension-monorepo/packages/feature-flags/migrations/20260601T0000_create_feature_flag/migration.tsexamples/multi-extension-monorepo/packages/feature-flags/migrations/refs/head.jsonexamples/multi-extension-monorepo/packages/feature-flags/src/contract.d.tsexamples/multi-extension-monorepo/packages/feature-flags/src/contract.jsonexamples/paradedb-demo/src/prisma/contract.d.tsexamples/paradedb-demo/src/prisma/contract.jsonexamples/prisma-next-cloudflare-worker/src/prisma/contract.d.tsexamples/prisma-next-cloudflare-worker/src/prisma/contract.jsonexamples/prisma-next-demo-sqlite/src/prisma/contract.d.tsexamples/prisma-next-demo-sqlite/src/prisma/contract.jsonexamples/prisma-next-demo/migrations/app/20260422T0720_initial/end-contract.d.tsexamples/prisma-next-demo/migrations/app/20260422T0720_initial/end-contract.jsonexamples/prisma-next-demo/migrations/app/20260422T0742_migration/end-contract.d.tsexamples/prisma-next-demo/migrations/app/20260422T0742_migration/end-contract.jsonexamples/prisma-next-demo/migrations/app/20260422T0742_migration/migration.jsonexamples/prisma-next-demo/migrations/app/20260422T0742_migration/migration.tsexamples/prisma-next-demo/migrations/app/20260422T0742_migration/ops.jsonexamples/prisma-next-demo/migrations/app/20260422T0742_migration/start-contract.d.tsexamples/prisma-next-demo/migrations/app/20260422T0742_migration/start-contract.jsonexamples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.jsonexamples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.tsexamples/prisma-next-demo/migrations/app/20260422T0748_migration/ops.jsonexamples/prisma-next-demo/migrations/app/20260422T0748_migration/start-contract.d.tsexamples/prisma-next-demo/migrations/app/20260422T0748_migration/start-contract.jsonexamples/prisma-next-demo/migrations/app/20260517T1323_initial/end-contract.d.tsexamples/prisma-next-demo/migrations/app/20260517T1323_initial/end-contract.jsonexamples/prisma-next-demo/migrations/app/20260517T1323_initial/migration.jsonexamples/prisma-next-demo/migrations/app/20260517T1323_initial/migration.tsexamples/prisma-next-demo/migrations/app/20260517T1323_initial/ops.jsonexamples/prisma-next-demo/migrations/pgvector/20260601T0000_install_vector_extension/contract.jsonexamples/prisma-next-demo/migrations/pgvector/20260601T0000_install_vector_extension/migration.jsonexamples/prisma-next-demo/migrations/pgvector/20260601T0000_install_vector_extension/ops.jsonexamples/prisma-next-demo/migrations/pgvector/contract.d.tsexamples/prisma-next-demo/migrations/pgvector/contract.jsonexamples/prisma-next-demo/migrations/pgvector/refs/head.jsonexamples/prisma-next-demo/scripts/drop-db.tsexamples/prisma-next-demo/src/app/ContractView.tsxexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonexamples/prisma-next-demo/src/prisma/contract.prismaexamples/prisma-next-demo/test/contract-authoring.test.tsexamples/prisma-next-demo/test/control-client.integration.test.tsexamples/prisma-next-demo/test/demo-dx.integration.test.tsexamples/prisma-next-demo/test/demo-dx.types.test.tsexamples/prisma-next-postgis-demo/src/prisma/contract.d.tsexamples/prisma-next-postgis-demo/src/prisma/contract.jsonexamples/react-router-demo/src/prisma/contract.d.tsexamples/react-router-demo/src/prisma/contract.jsonpackage.jsonpackages/1-framework/0-foundation/contract/src/canonicalization.tspackages/1-framework/0-foundation/contract/test/canonicalization.test.tspackages/1-framework/1-core/framework-components/src/control/psl-ast.tspackages/1-framework/1-core/framework-components/src/exports/ir.tspackages/1-framework/1-core/framework-components/src/ir/namespace.tspackages/1-framework/1-core/framework-components/src/ir/storage.tspackages/1-framework/1-core/framework-components/test/control-capabilities.test.tspackages/1-framework/2-authoring/psl-parser/src/exports/index.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/src/print-document.tspackages/1-framework/2-authoring/psl-printer/src/serialize-print-document.tspackages/1-framework/2-authoring/psl-printer/test/print-psl-from-ast.test.tspackages/1-framework/3-tooling/cli/test/commands/contract-infer.command.test.tspackages/1-framework/3-tooling/cli/test/commands/inspect-live-schema.test.tspackages/1-framework/3-tooling/cli/test/control-api/client.test.tspackages/1-framework/3-tooling/emitter/test/canonicalization.test.tspackages/1-framework/3-tooling/emitter/test/emitter.roundtrip.test.tspackages/1-framework/3-tooling/emitter/test/emitter.test.tspackages/1-framework/3-tooling/migration/src/aggregate/extract-storage-element-names.tspackages/1-framework/3-tooling/migration/src/aggregate/verifier.tspackages/1-framework/3-tooling/migration/test/aggregate/loader.test.tspackages/1-framework/3-tooling/migration/test/aggregate/project-schema-to-space.test.tspackages/1-framework/3-tooling/migration/test/aggregate/strategies/synth.test.tspackages/1-framework/3-tooling/migration/test/aggregate/verifier.test.tspackages/1-framework/3-tooling/migration/test/deletable-node-modules.test.tspackages/2-mongo-family/1-foundation/mongo-contract/src/ir/mongo-storage.tspackages/2-mongo-family/2-authoring/contract-psl/src/interpreter.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.tspackages/2-mongo-family/9-family/src/core/ir/mongo-contract-serializer-base.tspackages/2-mongo-family/9-family/test/mongo-schema-verifier-base.test.tspackages/2-sql/1-core/contract/README.mdpackages/2-sql/1-core/contract/src/exports/types.tspackages/2-sql/1-core/contract/src/factories.tspackages/2-sql/1-core/contract/src/index-type-validation.tspackages/2-sql/1-core/contract/src/ir/foreign-key-reference.tspackages/2-sql/1-core/contract/src/ir/foreign-key-references.tspackages/2-sql/1-core/contract/src/ir/foreign-key.tspackages/2-sql/1-core/contract/src/ir/sql-storage.tspackages/2-sql/1-core/contract/src/ir/sql-unbound-namespace.tspackages/2-sql/1-core/contract/src/ir/storage-table.tspackages/2-sql/1-core/contract/src/types.tspackages/2-sql/1-core/contract/src/validators.tspackages/2-sql/1-core/contract/test/factories.test.tspackages/2-sql/1-core/contract/test/sql-storage-multi-namespace-round-trip.test.tspackages/2-sql/1-core/contract/test/sql-storage-namespace-buckets.test.tspackages/2-sql/1-core/contract/test/validators.test.tspackages/2-sql/1-core/schema-ir/src/ir/sql-foreign-key-ir.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/src/psl-field-resolution.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.cross-namespace-fk.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.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/provider.test.tspackages/2-sql/2-authoring/contract-ts/schemas/data-contract-sql-v1.jsonpackages/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/contract-types.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.constraints.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.contract-definition.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.cross-namespace-fk.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.helpers.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.portability.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.entrypoint.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.namespaces.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.normalization.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.per-model-namespace.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.value-objects.test.tspackages/2-sql/2-authoring/contract-ts/test/contract.edge-cases.test.tspackages/2-sql/2-authoring/contract-ts/test/contract.integration.test.tspackages/2-sql/2-authoring/contract-ts/test/contract.logic.test.tspackages/2-sql/2-authoring/contract-ts/test/contract.model-validation.test.tspackages/2-sql/2-authoring/contract-ts/test/contract.normalization.test.tspackages/2-sql/2-authoring/contract-ts/test/contract.parameterized-types.test.tspackages/2-sql/2-authoring/contract-ts/test/contract.structure.test.tspackages/2-sql/2-authoring/contract-ts/test/fixtures/contract.d.tspackages/2-sql/3-tooling/emitter/src/index.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.generation.advanced.test.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.generation.basic.test.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.parameterized-types.test.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.structure.test.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.typeref-resolver.test.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.types.test.tspackages/2-sql/4-lanes/query-builder/src/selection.tspackages/2-sql/4-lanes/relational-core/src/ast/types.tspackages/2-sql/4-lanes/relational-core/src/codec-ref-for-column.tspackages/2-sql/4-lanes/relational-core/test/codec-descriptor-registry.test.tspackages/2-sql/4-lanes/relational-core/test/fixtures/contract.d.tspackages/2-sql/4-lanes/sql-builder/src/runtime/mutation-impl.tspackages/2-sql/4-lanes/sql-builder/src/runtime/sql.tspackages/2-sql/4-lanes/sql-builder/src/runtime/table-proxy-impl.tspackages/2-sql/4-lanes/sql-builder/src/types/db.tspackages/2-sql/4-lanes/sql-builder/src/types/table-proxy.tspackages/2-sql/4-lanes/sql-builder/test/runtime/field-proxy.test.tspackages/2-sql/5-runtime/src/codecs/validation.tspackages/2-sql/5-runtime/src/sql-context.tspackages/2-sql/5-runtime/test/async-iterable-result.test.tspackages/2-sql/5-runtime/test/codec-integrity.test.tspackages/2-sql/5-runtime/test/context.types.test-d.tspackages/2-sql/5-runtime/test/contract-codec-registry.test.tspackages/2-sql/5-runtime/test/mutation-default-generators.test.tspackages/2-sql/5-runtime/test/parameterized-types.test.tspackages/2-sql/5-runtime/test/sql-context.codec-context.test.tspackages/2-sql/5-runtime/test/sql-context.test.tspackages/2-sql/5-runtime/test/sql-family-adapter.test.tspackages/2-sql/5-runtime/test/utils.tspackages/2-sql/9-family/src/core/control-instance.tspackages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.tspackages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.tspackages/2-sql/9-family/src/core/migrations/field-event-planner.tspackages/2-sql/9-family/src/core/psl-contract-infer/sql-schema-ir-to-psl-ast.tspackages/2-sql/9-family/src/core/schema-verify/verify-helpers.tspackages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.tspackages/2-sql/9-family/test/contract-to-schema-ir.test.tspackages/2-sql/9-family/test/control-instance.descriptor-self-consistency.test.tspackages/2-sql/9-family/test/field-event-planner.test.tspackages/2-sql/9-family/test/psl-contract-infer/print-psl/print-psl.naming-and-constraints.test.tspackages/2-sql/9-family/test/psl-contract-infer/print-psl/print-psl.relations.test.tspackages/2-sql/9-family/test/psl-contract-infer/relation-inference.test.tspackages/2-sql/9-family/test/psl-contract-infer/sql-schema-ir-to-psl-ast.test.tspackages/2-sql/9-family/test/schema-verify.basic.test.tspackages/2-sql/9-family/test/schema-verify.constraints.test.tspackages/2-sql/9-family/test/schema-verify.cross-namespace-fk.test.tspackages/2-sql/9-family/test/schema-verify.helpers.tspackages/2-sql/9-family/test/schema-verify.referential-actions.test.tspackages/2-sql/9-family/test/schema-verify.semantic-satisfaction.test.tspackages/3-extensions/cipherstash/migrations/20260601T0000_install_eql_bundle/end-contract.d.tspackages/3-extensions/cipherstash/migrations/20260601T0000_install_eql_bundle/end-contract.jsonpackages/3-extensions/cipherstash/migrations/20260601T0000_install_eql_bundle/migration.jsonpackages/3-extensions/cipherstash/migrations/20260601T0000_install_eql_bundle/migration.tspackages/3-extensions/cipherstash/migrations/refs/head.jsonpackages/3-extensions/cipherstash/src/contract.d.tspackages/3-extensions/cipherstash/src/contract.jsonpackages/3-extensions/cipherstash/test/cipherstash-codec.test.tspackages/3-extensions/cipherstash/test/descriptor.test.tspackages/3-extensions/cipherstash/test/helpers.test.tspackages/3-extensions/cipherstash/test/operator-lowering.helpers.tspackages/3-extensions/cipherstash/test/psl-interpretation-numeric.test.tspackages/3-extensions/cipherstash/test/psl-interpretation-other-types.test.tspackages/3-extensions/cipherstash/test/psl-interpretation.test.tspackages/3-extensions/paradedb/migrations/20260601T0000_install_pg_search_extension/end-contract.d.tspackages/3-extensions/paradedb/migrations/20260601T0000_install_pg_search_extension/end-contract.jsonpackages/3-extensions/paradedb/migrations/20260601T0000_install_pg_search_extension/migration.jsonpackages/3-extensions/paradedb/migrations/20260601T0000_install_pg_search_extension/migration.tspackages/3-extensions/paradedb/migrations/refs/head.jsonpackages/3-extensions/paradedb/src/contract.d.tspackages/3-extensions/paradedb/src/contract.jsonpackages/3-extensions/pgvector/migrations/20260601T0000_install_vector_extension/end-contract.d.tspackages/3-extensions/pgvector/migrations/20260601T0000_install_vector_extension/end-contract.jsonpackages/3-extensions/pgvector/migrations/20260601T0000_install_vector_extension/migration.jsonpackages/3-extensions/pgvector/migrations/20260601T0000_install_vector_extension/migration.tspackages/3-extensions/pgvector/migrations/refs/head.jsonpackages/3-extensions/pgvector/src/contract.d.tspackages/3-extensions/pgvector/src/contract.jsonpackages/3-extensions/pgvector/test/control-adapter-lower-parity.test.tspackages/3-extensions/pgvector/test/descriptor.test.tspackages/3-extensions/pgvector/test/migrations/planner.behavior.test.tspackages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.tspackages/3-extensions/pgvector/test/migrations/planner.storage-types.test.tspackages/3-extensions/pgvector/test/operation-lowering.test.tspackages/3-extensions/pgvector/test/rich-adapter.test.tspackages/3-extensions/pgvector/test/sql-renderer.cast-policy.test.tspackages/3-extensions/postgis/migrations/20260601T0000_install_postgis_extension/end-contract.d.tspackages/3-extensions/postgis/migrations/20260601T0000_install_postgis_extension/end-contract.jsonpackages/3-extensions/postgis/migrations/20260601T0000_install_postgis_extension/migration.jsonpackages/3-extensions/postgis/migrations/20260601T0000_install_postgis_extension/migration.tspackages/3-extensions/postgis/migrations/refs/head.jsonpackages/3-extensions/postgis/src/contract.d.tspackages/3-extensions/postgis/src/contract.jsonpackages/3-extensions/postgres/package.jsonpackages/3-extensions/postgres/src/config/define-config.tspackages/3-extensions/postgres/test/psl-namespace-qualifier-routing.test.tspackages/3-extensions/postgres/test/psl-ts-namespace-parity.test.tspackages/3-extensions/sql-orm-client/src/collection-contract.tspackages/3-extensions/sql-orm-client/src/model-accessor.tspackages/3-extensions/sql-orm-client/src/query-plan-aggregate.tspackages/3-extensions/sql-orm-client/src/query-plan-meta.tspackages/3-extensions/sql-orm-client/src/query-plan-mutations.tspackages/3-extensions/sql-orm-client/src/query-plan-select.tspackages/3-extensions/sql-orm-client/src/types.tspackages/3-extensions/sql-orm-client/src/where-binding.tspackages/3-extensions/sql-orm-client/test/collection-contract.test.tspackages/3-extensions/sql-orm-client/test/collection-fixtures.tspackages/3-extensions/sql-orm-client/test/collection-mutation-defaults.test.tspackages/3-extensions/sql-orm-client/test/create-input.test-d.tspackages/3-extensions/sql-orm-client/test/filters.test.tspackages/3-extensions/sql-orm-client/test/generated-contract-types.test-d.tspackages/3-extensions/sql-orm-client/test/helpers.tspackages/3-extensions/sql-orm-client/test/integration/upsert.test.tspackages/3-extensions/sql-orm-client/test/model-accessor.test.tspackages/3-extensions/sql-orm-client/test/mutation-executor.test.tspackages/3-extensions/sql-orm-client/test/query-plan-meta.test.tspackages/3-extensions/sql-orm-client/test/query-plan-mutations.test.tspackages/3-extensions/sql-orm-client/test/query-plan-select.test.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-target-contract-serializer.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-target-database.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-target-schema-verifier.tspackages/3-mongo-target/1-mongo-target/src/exports/control.tspackages/3-mongo-target/1-mongo-target/test/mongo-target-contract-serializer.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-target-database.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-target-schema-verifier.test.tspackages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/constraints.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/shared.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-ddl-builders.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-schema-lookup.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-sql-checks.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner.tspackages/3-targets/3-targets/postgres/src/core/postgres-schema.tspackages/3-targets/3-targets/postgres/src/exports/types.tspackages/3-targets/3-targets/postgres/test/migrations/issue-planner.test.tspackages/3-targets/3-targets/postgres/test/postgres-contract-serializer.test.tspackages/3-targets/3-targets/postgres/test/postgres-schema.test.tspackages/3-targets/3-targets/sqlite/src/core/migrations/issue-planner.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/shared.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/tables.tspackages/3-targets/3-targets/sqlite/src/core/migrations/planner-strategies.ts
💤 Files with no reviewable changes (15)
- examples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.json
- examples/prisma-next-demo/migrations/app/20260422T0742_migration/start-contract.json
- examples/prisma-next-demo/migrations/app/20260422T0748_migration/ops.json
- examples/prisma-next-demo/migrations/app/20260422T0748_migration/start-contract.json
- examples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.ts
- examples/prisma-next-demo/migrations/app/20260422T0742_migration/migration.json
- examples/prisma-next-demo/migrations/app/20260422T0742_migration/migration.ts
- packages/2-sql/1-core/contract/src/ir/foreign-key-references.ts
- examples/prisma-next-demo/migrations/app/20260422T0742_migration/start-contract.d.ts
- examples/prisma-next-demo/migrations/app/20260422T0742_migration/end-contract.json
- examples/prisma-next-demo/migrations/app/20260422T0742_migration/ops.json
- examples/prisma-next-demo/migrations/app/20260422T0748_migration/start-contract.d.ts
- examples/prisma-next-demo/migrations/app/20260422T0720_initial/end-contract.d.ts
- examples/prisma-next-demo/migrations/app/20260422T0720_initial/end-contract.json
- examples/prisma-next-demo/migrations/app/20260422T0742_migration/end-contract.d.ts
| createEnumType('public', 'user_type', ['admin', 'user']), | ||
| createTable('public', 'bug', [ |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n "createEnumType\\(|typeSql:\\s*'\"[A-Za-z0-9_]+\"'" \
examples/prisma-next-demo/migrations/app/20260517T1323_initial/migration.tsRepository: prisma/prisma-next
Length of output: 217
🏁 Script executed:
cat -n examples/prisma-next-demo/migrations/app/20260517T1323_initial/migration.ts | sed -n '70,100p'Repository: prisma/prisma-next
Length of output: 1437
🏁 Script executed:
rg -n "typeSql|createEnumType" examples/prisma-next-demo/migrations/app/20260517T1323_initial/migration.tsRepository: prisma/prisma-next
Length of output: 1834
Schema-qualify the enum type in auth.user table creation.
Line 87 uses typeSql: '"user_type"' while the enum is created in the public schema on line 23. This cross-schema reference is search_path-dependent and can fail or resolve incorrectly in environments where the default public schema isn't first in search_path.
🔧 Proposed fix
- { name: 'kind', typeSql: '"user_type"', defaultSql: '', nullable: false },
+ { name: 'kind', typeSql: '"public"."user_type"', defaultSql: '', nullable: false },🤖 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 `@examples/prisma-next-demo/migrations/app/20260517T1323_initial/migration.ts`
around lines 23 - 24, The enum type created with createEnumType('public',
'user_type', ...) is referenced as typeSql: '"user_type"' in the auth.user table
creation; update that reference to schema-qualify the enum (e.g., use typeSql:
'"public"."user_type"') so the DDL does not depend on search_path. Locate the
auth user table creation in migration.ts (the createTable call that defines the
"user" table and the typeSql entry) and replace the unqualified type name with
the fully qualified "public"."user_type" identifier.
| <div key={foreignKey.source.columns.join(',')} className="column"> | ||
| <span className="col-name"> | ||
| {'\u2192'} {foreignKey.columns.join(', ')} | ||
| {'\u2192'} {foreignKey.source.columns.join(', ')} | ||
| </span> | ||
| <span className="col-type"> | ||
| {'\u2192'} {foreignKey.references.table}({foreignKey.references.columns.join(', ')}) | ||
| {'\u2192'} {foreignKey.target.table}({foreignKey.target.columns.join(', ')}) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
find . -type f -name "ContractView.tsx" | head -20Repository: prisma/prisma-next
Length of output: 115
🏁 Script executed:
cat -n ./examples/prisma-next-demo/src/app/ContractView.tsx | sed -n '65,85p'Repository: prisma/prisma-next
Length of output: 901
🏁 Script executed:
rg "foreignKeys" ./examples/prisma-next-demo/src/app/ContractView.tsx -B 10 -A 5 | head -40Repository: prisma/prisma-next
Length of output: 813
🏁 Script executed:
rg "type.*ForeignKey|interface.*ForeignKey" --type ts --type tsxRepository: prisma/prisma-next
Length of output: 90
🏁 Script executed:
rg "type.*ForeignKey|interface.*ForeignKey" --type ts -A 10Repository: prisma/prisma-next
Length of output: 44969
🏁 Script executed:
cat -n packages/2-sql/1-core/contract/src/ir/foreign-key.tsRepository: prisma/prisma-next
Length of output: 4006
🏁 Script executed:
cat -n packages/2-sql/1-core/contract/src/ir/foreign-key-reference.tsRepository: prisma/prisma-next
Length of output: 2303
🏁 Script executed:
cat -n ./examples/prisma-next-demo/src/app/ContractView.tsx | sed -n '60,85p'Repository: prisma/prisma-next
Length of output: 1199
Include target namespace in React key and UI rendering to prevent collisions and clarify cross-namespace FKs.
The current key based only on foreignKey.source.columns can collide when a table has multiple FKs with the same source columns pointing to different targets (or different namespaces). Additionally, rendering only the table name in the UI omits the target.namespaceId, making cross-namespace foreign keys ambiguous.
Suggested patch
- {(table.foreignKeys ?? []).map((foreignKey) => (
- <div key={foreignKey.source.columns.join(',')} className="column">
+ {(table.foreignKeys ?? []).map((foreignKey) => (
+ <div
+ key={`${foreignKey.source.columns.join(',')}->${foreignKey.target.namespaceId}.${foreignKey.target.table}(${foreignKey.target.columns.join(',')})`}
+ className="column"
+ >
<span className="col-name">
{'\u2192'} {foreignKey.source.columns.join(', ')}
</span>
<span className="col-type">
- {'\u2192'} {foreignKey.target.table}({foreignKey.target.columns.join(', ')})
+ {'\u2192'} {foreignKey.target.namespaceId}.{foreignKey.target.table}(
+ {foreignKey.target.columns.join(', ')})
</span>
</div>
))}🤖 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 `@examples/prisma-next-demo/src/app/ContractView.tsx` around lines 72 - 77, The
React key and displayed target info for foreign keys only use
foreignKey.source.columns and foreignKey.target.table, which can collide or hide
cross-namespace targets; update the key to include the target namespace (e.g.,
combine foreignKey.source.columns with foreignKey.target.namespaceId and
foreignKey.target.table) and update the rendered target text to show the
namespaceId alongside the table (use foreignKey.target.namespaceId + ':' +
foreignKey.target.table and keep the target.columns join as-is) so keys are
unique and the UI clearly indicates cross-namespace FKs.
| // FR15 nested envelope: `storage.tables.<namespaceId>.<tableName>.<field>` | ||
| // sits at depth 5; the table-level required-empty defaults | ||
| // (`uniques`, `indexes`, `foreignKeys`) must survive at that | ||
| // depth so the persisted shape stays schema-valid. | ||
| const isTableUniques = |
There was a problem hiding this comment.
Avoid FR identifiers in source comments.
Comments now include FR15 references. Please reword to describe behavior directly without transient artifact IDs.
As per coding guidelines, source-code comments must not reference transient project artifacts such as FR/spec decision IDs.
Also applies to: 234-238
🤖 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/1-framework/0-foundation/contract/src/canonicalization.ts` around
lines 93 - 97, Remove the transient FR identifier from the comment above the
isTableUniques declaration and rephrase it to describe the behavior directly
(e.g., explain that a nested envelope at depth 5 —
storage.tables.<namespaceId>.<tableName>.<field> — must preserve table-level
empty-defaults like uniques, indexes, and foreignKeys so the persisted shape
remains schema-valid); apply the same removal/rephrasing to the other comment
block currently containing an FR reference (the block around lines 234–238) so
no FR/spec decision IDs remain in source comments.
| const allModels = flatPslModels(ast); | ||
| const modelNames = new Set(allModels.map((m) => m.name)); | ||
| const deps = buildModelFkDeps(allModels, modelNames); | ||
| const sortedModels = topologicalSortModels(allModels, deps); | ||
|
|
||
| const modelNamespaceIndex = new Map<string, string>(); | ||
| for (const namespace of ast.namespaces) { | ||
| for (const model of namespace.models) { | ||
| modelNamespaceIndex.set(model.name, namespace.name); | ||
| } |
There was a problem hiding this comment.
Namespace-qualified models need a qualified identity here.
This pipeline keys models by model.name in both modelNamespaceIndex and the FK dependency graph. That collapses auth.User and public.User into one entry, and dotted relation targets like auth.User never match modelNames at all. In practice the printer can drop one namespace's model or skip cross-namespace dependency ordering once duplicate names or dotted relations appear.
Also applies to: 246-290
🤖 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/1-framework/2-authoring/psl-printer/src/ast-to-print-document.ts`
around lines 32 - 41, The code keys models by unqualified model.name causing
collisions and mismatches for dotted names (e.g., auth.User vs public.User) in
modelNamespaceIndex and the FK graph built by buildModelFkDeps, so update the
pipeline to use a fully-qualified identifier (namespace + '.' + model.name or
model.fullyQualifiedName) everywhere: change flatPslModels output lookup and
modelNamespaceIndex population to use the qualified key, ensure buildModelFkDeps
and topologicalSortModels accept and compare these qualified names when building
deps and sorting, and normalize incoming FK targets (dotted or unqualified) to
the same qualified-key form before matching against modelNames and
modelNamespaceIndex.
| export type PrintNamespaceSection = { | ||
| readonly name: string; | ||
| readonly enums: readonly PrintEnumSection[]; | ||
| readonly models: readonly PrinterModel[]; |
There was a problem hiding this comment.
PrintNamespaceSection still has no place for composite types.
PslNamespace now includes compositeTypes, but this print-time shape only carries enums and models. Any AST with composite types in a namespace has to lose them before serialization, so printPslFromAst() still can't round-trip those declarations through the new namespace-aware path.
Also applies to: 23-26
🤖 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/1-framework/2-authoring/psl-printer/src/print-document.ts` around
lines 17 - 20, PrintNamespaceSection currently omits compositeTypes so
namespaces with composite type declarations are dropped during printing; update
the PrintNamespaceSection type to include a readonly compositeTypes field whose
element type matches the printer-side composite type used elsewhere (i.e. the
same type as PslNamespace.compositeTypes expects for serialization), and then
thread that new field through the code paths that construct/consume
PrintNamespaceSection (notably printPslFromAst and any functions creating
PrinterModel/PrintEnumSection arrays) so composite types are preserved during
round-trip printing.
| // Optional — same-namespace FKs may omit it; cross-namespace | ||
| // references populate this with the target table's namespace coord. | ||
| readonly namespaceId?: string; | ||
| readonly table: string; |
There was a problem hiding this comment.
ForeignKeyReference docs conflict with validator shape.
namespaceId is documented as optional here, but ForeignKeyReferenceSchema requires it (namespaceId: 'string'). Please align docs with the actual contract shape to avoid invalid contract authoring.
🤖 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/README.md` around lines 83 - 86, Docs state
namespaceId is optional but the validator (ForeignKeyReferenceSchema) requires
namespaceId as a string; update the README docs for ForeignKeyReference to
reflect that namespaceId is required (remove "Optional" wording and document it
as a required string that holds the target table's namespace coord) so the
documentation matches the contract shape (referencing the namespaceId and table
fields and ForeignKeyReferenceSchema).
| this.namespaceId = input.namespaceId; | ||
| this.table = input.table; | ||
| this.columns = input.columns; | ||
| freezeNode(this); |
There was a problem hiding this comment.
Clone/freeze columns before storing it.
freezeNode(this) only freezes the field reference. Because input.columns is reused directly, mutating the caller-owned array later will still mutate this ForeignKeyReference instance.
Suggested fix
- this.columns = input.columns;
+ this.columns = Object.freeze([...input.columns]);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| this.namespaceId = input.namespaceId; | |
| this.table = input.table; | |
| this.columns = input.columns; | |
| freezeNode(this); | |
| this.namespaceId = input.namespaceId; | |
| this.table = input.table; | |
| this.columns = Object.freeze([...input.columns]); | |
| freezeNode(this); |
🤖 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/ir/foreign-key-reference.ts` around lines
44 - 47, The constructor for ForeignKeyReference currently assigns this.columns
= input.columns then calls freezeNode(this), which leaves the caller-owned array
mutable; fix it by cloning and freezing the columns array before storing it:
create a shallow copy of input.columns (e.g., [...input.columns] or
input.columns.slice()) and then freeze that copy (and optionally freeze each
column element if they are nodes) so assign the cloned/frozen array to
this.columns prior to calling freezeNode(this) to prevent external mutation of
the instance.
| this.source = Object.freeze({ columns: input.source.columns }); | ||
| this.target = | ||
| input.target instanceof ForeignKeyReference | ||
| ? input.target | ||
| : new ForeignKeyReference(input.target); |
There was a problem hiding this comment.
source.columns is still externally mutable.
Object.freeze({ columns: input.source.columns }) freezes the wrapper, not the array. If the caller mutates input.source.columns later, the ForeignKey IR changes underneath you.
Suggested fix
- this.source = Object.freeze({ columns: input.source.columns });
+ this.source = Object.freeze({
+ columns: Object.freeze([...input.source.columns]),
+ });📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| this.source = Object.freeze({ columns: input.source.columns }); | |
| this.target = | |
| input.target instanceof ForeignKeyReference | |
| ? input.target | |
| : new ForeignKeyReference(input.target); | |
| this.source = Object.freeze({ | |
| columns: Object.freeze([...input.source.columns]), | |
| }); | |
| this.target = | |
| input.target instanceof ForeignKeyReference | |
| ? input.target | |
| : new ForeignKeyReference(input.target); |
🤖 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/ir/foreign-key.ts` around lines 71 - 75,
The wrapper freeze is insufficient because input.source.columns remains mutable;
update the ForeignKey construction so source.columns gets an immutable copy
instead of referencing input.source.columns directly (e.g., create a shallow
copy of input.source.columns and freeze that) while keeping the existing logic
that wraps/uses input.target via ForeignKeyReference; ensure the field name
source and class ForeignKey (and the target handling that checks instanceof
ForeignKeyReference) are preserved when making this change.
| this.storageHash = input.storageHash; | ||
| this.tables = Object.freeze( | ||
| Object.fromEntries( | ||
| Object.entries(input.tables).map(([name, t]) => [ | ||
| name, | ||
| t instanceof StorageTable ? t : new StorageTable(t), | ||
| ]), | ||
| ), | ||
| ); | ||
| this.tables = freezeNestedTables(normaliseTablesInput(input.tables)); | ||
| this.namespaces = input.namespaces ?? DEFAULT_NAMESPACES; | ||
| if (input.types !== undefined) { | ||
| this.types = Object.freeze( | ||
| Object.fromEntries( | ||
| Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(ti)]), | ||
| ), | ||
| ); | ||
| Object.defineProperty(this, 'types', { | ||
| value: freezeNestedTypes(normaliseTypesInput(input.types)), | ||
| enumerable: true, | ||
| writable: false, | ||
| configurable: false, | ||
| }); |
There was a problem hiding this comment.
Normalize and validate namespaces in the constructor.
tables/types are normalized into the new nested shape, but input.namespaces is passed through as-is. That means callers can still mutate storage.namespaces after construction, and new SqlStorage({ tables: { auth: ... } }) is currently allowed even when the namespaces map has no auth entry. Both cases break the namespace invariant this class now documents.
🤖 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/ir/sql-storage.ts` around lines 129 - 138,
The constructor leaves input.namespaces unnormalized and mutable and doesn't
validate that every table namespace from normaliseTablesInput is present; fix by
normalising and freezing namespaces (e.g. call a normaliseNamespacesInput and
freezeNestedNamespaces or use Object.defineProperty like for 'types') and assign
to this.namespaces from that frozen result (use input.namespaces ??
DEFAULT_NAMESPACES). After you set this.tables (result of
normaliseTablesInput/freezeNestedTables), validate that every namespace key used
by this.tables exists in the normalised namespaces map and throw a clear error
if any are missing to enforce the invariant (reference: this.namespaces,
input.namespaces, normaliseTablesInput, freezeNestedTables, DEFAULT_NAMESPACES,
and the constructor that defines 'types').
| // Cross-namespace FK lookup (FR16b): every `ForeignKeyReference` | ||
| // carries its own resolved namespace coordinate (the caller-normalises | ||
| // discipline stamps it at construction time), so the lookup is | ||
| // unambiguously namespace-aware whether the FK targets the same or a | ||
| // different namespace. | ||
| const targetNamespaceId = fk.target.namespaceId; |
There was a problem hiding this comment.
Remove transient FR references from source comments.
The inline comments reference FR16b/FR15, which violates the doc-maintenance rule for source-code comments.
As per coding guidelines, source-code comments must not reference transient project artifacts including spec decision IDs like (FR6)/similar FR tags.
Also applies to: 724-728
🤖 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 663 - 668,
Remove transient spec-ID references like "FR16b" and "FR15" from inline comments
in this module; edit the comment block around the ForeignKeyReference handling
(the comment preceding targetNamespaceId and the nearby comment block around
lines referencing FR15/FR16b) to preserve the explanatory text but delete any
parenthetical spec decision IDs. Keep the semantic explanation about
cross-namespace FK lookup and that fk.target.namespaceId is used, but eliminate
the "(FR...)" tags to comply with doc-maintenance rules.
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…act.*'
Replaces a hand-maintained 20-entry path list with a single recursive glob.
The old list silently missed any new emit-capable workspace (e.g. examples/multi-extension-monorepo,
where contract drift went undetected until a manual repro). The glob covers
every tracked contract.{d.ts,json,prisma,ts} under any depth; end-contract.*
and start-contract.* migration-baseline artefacts correctly fall outside it
since they are owned by 'migration plan', not 'contract emit'.
Signed-off-by: Will Madden <[email protected]>
|
Superseded by #534. The original PR2 shipped a self-contradictory IR shape ( See |
Linked issue
Refs TML-2520. Second of two PRs for the target-extensible-ir project; PR1 shipped the IR class-hierarchy substrate and the enum exemplar.
At a glance
PSL gains a single new top-level form — the
namespaceblock — and reuses@relationfor cross-namespace FKs via dot-qualified type references in the type position. Demo schema, lifted from this PR:The Postgres planner emits
CREATE SCHEMA "auth", fully-qualified DDL (CREATE TABLE "auth"."user" (...)), and cross-schema FKs (REFERENCES "auth"."user"("id")). Single-tenant Postgres schemas (top-level models, nonamespace { … }block) keep working unchanged — the framework parser collects them into an implicit bucket which the Postgres interpreter lowers to thepublicslot.Reviewer notes
This PR is big — 109 commits, ~20K insertions / 18K deletions across 401 files — because the namespace exemplar forced two cascading substrate moves that are inseparable from the feature:
SqlStorage.tablesflat → nested-by-namespace. Today every consumer (verifier, planner, introspector, hydrator, tests, fixtures) walked a flat{ tableName: StorageTable }map. Namespaces need to be the outer keying dimension to avoid table-name collisions across schemas (decision inprojects/target-extensible-ir/specs/m5a-namespace-exemplar-and-authoring-dsl.md— Shape C). The shift propagated through ~30 packages.__unspecified__→__unbound__at the IR layer. The PSL AST keeps__unspecified__(syntactic absence — what the parser sees when the user wrote no namespace block). The IR keeps__unbound__(semantic — "the connection resolves the namespace at runtime"). They were conflated before; the rename separates them. See FR14 in the spec.The biggest single commit is
55638ed06(kill dual-shape storage) — that's whereSqlStorage.tablesflipped to its canonical nested form, after the test-fixture migration commits had already worked all the consumers across. Spot-check there if you want the substrate edit in isolation.Things that look surprising on the diff but are deliberate:
FlatTablesOf<C>bridge insql-builder/sql-orm-client. The runtime IR is nested, but the DSL surface (db.user.create({...})) stays flat for now.FlatTablesOfflattens the nested type back for ergonomics. Deferred to TML-2550: namespace-aware DSL surface design (e.g.db.auth.user.create(...)) and removal of the bridge. The bridge is scoped to two packages and TODO-tagged.contract.d.tshad to follow the IR shape, otherwiseContract<SqlStorage>assignability broke across every consumer. The DSL redesign is the deferred part; the emitter alignment ships here so the type story is internally consistent.renderQualifiedTableschema param widened tostring | undefined. Adapter-postgres needed alignment withexactOptionalPropertyTypesafterTableSource.schemaevolved. In-scope substrate fix.Framework rough edges surfaced while repairing
examples/multi-extension-monorepo(NOT fixed here — will file follow-up tickets):prisma-next migration planis unusable in standalone single-space packages (walks a multi-space layout that the example doesn't have).build:contract-spacessilently allows extension contract /refs/head.jsondrift — emit bumpsstorageHashbuthead.jsonisn't refreshed, so the aggregate emit later fails withDESCRIPTOR_HEAD_HASH_MISMATCH. Either auto-deriveheadReffromcontractJsonat load time, or guard the helper.assertBookendsMatchMetamakes re-emittingmigration.jsonnon-idempotent acrossdescribe().tobumps — you must deletemigration.jsonfirst.fixtures:checkdidn't coverexamples/multi-extension-monorepo(its diff glob misses extension-monorepo emit outputs); the substrate-bump drift went undetected by the fixtures gate.node migration.tsdespite the script header claiming it does — must usetsx.Two project artefacts ride along on disk for review:
projects/target-extensible-ir/spec.mdandprojects/target-extensible-ir/plan.md. The project-close-out PR (after PR3 / TML-2537) deletes them and migrates the durable docs intodocs/architecture docs/.Decision
This PR ships three substantive things, any of which alone would be a substantial change:
namespace <name> { … }blocks, TS buildernamespaces: [...]+ per-modelnamespace: '…'field, IR__unbound__sentinel for late-bound slots, per-target lowering (Postgres named schemas +public+unbound; SQLite/Mongo reject explicit blocks). Demonstrated by theprisma-next-demoschema above and end-to-end via PGlite tests.@relation; no new syntax in the TS builder (the model handle carries its namespace coordinate).ForeignKeyIR restructured to separate source/target and renamedForeignKeyReferences→ForeignKeyReference. Postgres planner emits cross-schema FK DDL; verifier compares namespace-aware FK targets honestly (no wildcard / optionalnamespaceIdsmuggling).SqlStorage.tablescanonically nested-by-namespace. Both runtime IR and generatedcontract.d.tsuse{ tables: { [namespaceId]: { [tableName]: StorageTable } } }. The previous flat shape is gone; the dual-view helpers (nestedTablesView,tablesByNamespace) that briefly bridged the substrate during M5a are deleted. The DSL surface keeps a flat ergonomic view viaFlatTablesOf<C>until TML-2550 redesigns it.The IR rename
__unspecified__→__unbound__rides along inside (3): the framework parser still emits__unspecified__on the AST (syntactic absence), the IR uses__unbound__(semantic late-binding intent), and per-target interpreters bridge between them.How it fits together
namespace <name> { … }as a top-level form, rejects nested namespaces (namespace a { namespace b { … } }), and supports multiplenamespace foo { … }blocks merging into one logical namespace. The parser is purely syntactic —auth,public,unboundare all just identifiers. Top-level models without any namespace block are collected into the implicitPslNamespace { name: '__unspecified__', … }AST entry. Cross-namespace FK use dot-qualified type references in@relation(auth.User) — no new attribute, the parser already knows which model the columns belong to from the type position. Validated by AST shape tests in packages/2-sql/2-authoring/contract-psl/test/.defineContract's config gains anamespacesdeclaration list;model(name, config)accepts a per-modelnamespacefield defaulting to the implicit slot. Existing FK call sites need no new syntax — the model handle returned bymodel(...)carries its namespace coordinate, soconstraints.foreignKey(cols.userId, OtherModel.refs.id, …)andrel.belongsTo(OtherModel, …)automatically lower to cross-namespace IR when the referenced model lives in another namespace.__unspecified__→ IRpublic(single-tenant default preserved); explicitnamespace unbound { … }→ IR__unbound__(late binding viasearch_path); named blocks → IR named schemas. SQLite and Mongo: accept only the implicit entry, reject any explicitnamespace { … }block with a target-named diagnostic. Postgres also rejects user-declarednamespace unbound(reserved for the late-binding sentinel mapping).SqlStorage.tablesbecomesRecord<NamespaceId, Record<TableName, StorageTable>>end-to-end — JSON, in-memory class, generated.d.ts. The PostgresContractSerializerround-trips the nested shape; the__unbound__sentinel key is preserved through canonical-JSON serialization.CREATE SCHEMA "auth"when a contract introduces a new named namespace, then fully-qualifies every DDL statement (tables, indexes, FKs). Cross-schema FKs render asREFERENCES "auth"."user"("id"). The verifier compares contract FKs to introspected FKs honestly —namespaceIdis required (no optionality, no wildcard fallback), so an introspectedauth.userwon't silently match a contractpublic.user.storage.tables[tableName](verifier, planner, introspector, hydrator, ~30 packages of source + tests + fixtures) moved tofindTableByName(storage, tableName)or explicit nested accessstorage.tables[namespaceId][tableName]. The bulk of the diff is this sweep; the substrate flip itself (55638ed06) is a small commit.Behavior changes & evidence
namespace { … }blocks. Framework parser producesPslDocumentAst.namespaces: readonly PslNamespace[]as the only models container; top-level declarations are collected into an implicit__unspecified__entry.packages/2-sql/2-authoring/contract-psl/src/parser/,packages/2-sql/2-authoring/contract-psl/src/provider.ts.packages/3-extensions/postgres/test/psl-namespace-qualifier-routing.test.ts,packages/3-extensions/postgres/test/psl-ts-namespace-parity.test.ts.ALTER TABLE "public"."post" … REFERENCES "auth"."user"("id")is the emitted shape; verifier compares the namespace coordinate as a required field.packages/3-targets/6-adapters/postgres/src/core/sql-renderer.ts,packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts.examples/prisma-next-demo/src/prisma/contract.prisma(live cross-namespace schema) + its e2e PGlite test intest/integration/test/.SqlStorage.tablesis canonically nested. Both runtime class and generatedcontract.d.tsuse{ __unbound__: { tableName: ... } }(or other namespace keys). Dual-view helpers deleted.packages/2-sql/9-family/src/core/ir/,packages/2-sql/3-tooling/emitter/src/index.ts.examples/multi-extension-monorepo/app/src/contract.d.ts(nested-shape generated output),packages/2-sql/3-tooling/emitter/test/.namespace { … }blocks. Diagnostic names the target and points at the offending block span.packages/3-targets/3-targets/.packages/3-extensions/postgres/test/psl-ts-namespace-parity.test.ts.Compatibility / migration / risk
namespace { … }block continue to lower to thepublicslot and emit qualified DDL the same way as before.contract.d.tsshape changed. Any consumer that imported the precise nested-or-flat type from a project's generatedcontract.d.tsmust regenerate. The fixtures-emit pipeline regenerates all in-repo consumers; downstream consumers should re-runprisma-next contract emit.SqlStorage.tables[name]direct access is gone. UsefindTableByName(storage, name)(helper exported from@prisma-next/sql-runtime) or explicit nested accessstorage.tables[namespaceId][name]. The DSL surfacedb.<table>is unchanged by this PR (theFlatTablesOf<C>bridge preserves it).ForeignKeyReferences→ForeignKeyReferencerename. Type-level only; no runtime change.Verification
pnpm --filter @prisma-next/example-multi-extension-monorepo run build:contract-spaces— exits 0 (idempotent across re-runs)pnpm --filter @prisma-next/example-multi-extension-monorepo typecheck— cleanpnpm --filter @prisma-next/example-multi-extension-monorepo test— 4/4 greenpnpm fixtures:check— exits 0pnpm test:packagesfor SQL family + Postgres extension packages — green on final HEADpnpm typecheckacross the monorepo — cleanprojects/target-extensible-ir/manual-qa-reports/— passingPre-existing flakes that reproduced and were ruled non-regressions: PGlite worker-pool contention (
ECONNRESET) in adapter-postgres integration tests when run under high parallelism; reproduces onmainwithout these changes. Filed for separate investigation.Follow-ups
FlatTablesOf<C>bridge. Tracked from this PR.enum. Closes the "frameworks parser accepts target-specific syntax" hole the namespace exemplar surfaced (today the parser hard-codesnamespace; target-specific blocks like Postgrespolicywill need this).prisma-next migration planstandalone-package gap,headRef.hashauto-derivation,assertBookendsMatchMetanon-idempotency,fixtures:checkcoverage gap, Node 24 ESM import in the migration script).docs/in the orchestration project's own close-out.Alternatives considered
namespaceIdon IR nodes (M5a R7's original design). Made verifier comparators silently pass FK mismatches between an unspecified contract slot and an introspected named schema. Reversed —namespaceIdis required end-to-end; the__unbound__sentinel is the explicit late-binding opt-in.unbound { … }as a target-specific block (Postgres-contributed top-level keyword). Required PR3's target-contributed-block mechanism as a prerequisite. We chose to makenamespacea framework keyword now and defer target-contributed blocks to PR3; the framework parser accepts namespace declarations regardless of target, and each target's interpreter validates whether explicitnamespace { … }blocks are permitted.tableskeyed by qualified name (tables: { "public.user": ..., "auth.user": ... }). Avoided the substrate sweep but turned every consumer into a string-parsing site and broke the "JSON unambiguous to downstream tools" principle. Rejected — namespace is the natural outer dimension.__unspecified__→__unbound__rename to a follow-up. Considered but rejected — the conflation between syntactic absence (PSL AST) and late-binding semantics (IR) directly motivated the namespace verifier comparator bug (F01). Splitting the two concepts was load-bearing for the fix.FlatTablesOf<C>bridge as the temporary scaffold.Skill update
n/a — internal IR / authoring surface change; CLI commands and the user-facing
prisma-next.config.tsfields are unchanged. PSL gainsnamespace { … }blocks and dot-qualified type references in@relation; these are documented in the spec and demonstrated inexamples/prisma-next-demo.Checklist
git commit -s) per the DCO. The DCO status check will block merge if any commit is missing aSigned-off-by:trailer.TML-NNNN: <sentence-case title>form.Summary by CodeRabbit