This repository was archived by the owner on Nov 25, 2026. It is now read-only.
Repository navigation
TML-2520: per-namespace storage IR + cross-namespace FKs - #534
Merged
Merged
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]>
…t-shape namespace work Cuts the namespace-exemplar work out of the giant target-extensible-ir PR2 umbrella where it self-contradicted itself (FR15 nested-by-namespace inverted FR13 namespace-as-container) and lay-and-pray nested it under the wrong axis end-to-end. This branch starts from ae7b759 — the last commit before the FR15-wrong-direction dual-shape introduction — and implements the substrate flip + cross-namespace FK feature in one pass against the correct shape. Spec: 6 acceptance criteria, internally consistent, At-a-glance JSON sample matches FR1/FR2 type expressions exactly, banned-pattern list names the dual-shape helpers that doomed the prior attempt. Plan: 12 dispatches across 5 phases (substrate flip, serialize+emit, consumer migration, FK feature, validation+PR). Every dispatch sized M (30-min time-box). Per-dispatch DoR/DoD/scope/banned-patterns. Failure- mode triggers with explicit intervention thresholds. Cherry-pick inventory for the three storage-shape-independent fixes pushed on the dead branch. Signed-off-by: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…r-schema database types (Namespace.types)
Codec type aliases (Embedding1536 = pgvector.Vector(1536)) are contract-
level naming conveniences with no database identity; they stay document-
scoped at storage.types. Per-schema database type entries (Postgres
enums today) are real database objects bound to a schema; they migrate
to Namespace.types. Same-name slot collision is acknowledged tech debt
scoped to TML-2563 follow-up rename.
Adds cross-namespace type references (column nativeType { namespaceId,
typeName }) symmetrically with cross-namespace FKs.
Updates D1, FR1, FR2, FR8, At-a-glance JSON sample for internal
consistency. Sample now demonstrates: tables nested under namespaces,
per-schema enum (user_type) under public.types, document-scoped codec
alias (Embedding1536) under storage.types, cross-namespace column type
reference (auth.user.kind references public.user_type), cross-namespace
FK (public.post.user_id references auth.user.id).
Signed-off-by: Will Madden <[email protected]>
Namespace and NamespaceBase now carry a tables map keyed by table name so family SQL IR can type storage without a flat storage.tables slot. Signed-off-by: Will Madden <[email protected]>
SqlStorage drops the flat tables map; StorageTable no longer stamps namespaceId. SqlUnboundNamespace exposes an empty tables map, and plain namespace envelopes hydrate via SqlNamespacePayload inside SqlStorage. Signed-off-by: Will Madden <[email protected]>
Arktype storage schema, semantic walkers, and index-type validation now read tables from storage.namespaces[*].tables; contract tests use the unbound helper envelope. Signed-off-by: Will Madden <[email protected]>
wmadden
added a commit
that referenced
this pull request
May 20, 2026
…ack mechanism Tighter rewrite focusing on the durable architectural decisions: - Decision 1: Two planes (domain, storage) - kept, lightly trimmed - Decision 2: Uniform <plane>.<ns>.<entityKind>.<entityName> shape - kept, updated example to include pack-contributed postgresEnums slot - Decision 3 (new): Canonical entity coordinate (namespaceId, entityKind, entityName) as the addressing primitive; explains the migration disjoint-calc dependency - Decision 4: Object-pair cross-references - kept - Decision 5 (new, was implicit): Pack-contributed entity-kind mechanism via AuthoringContributions.entityTypes; explicitly names the dual-surface (built-ins hardcoded + contributed kinds via descriptor) as deliberate paid debt - Decision 6: Narrowed framework Namespace interface - kept, trimmed Dropped: - Process-meta sections (D6 ADR-worthy, D7 scope-cleavage from PR #534) - these are project-shaping decisions, not architecture decisions; live in spec.md - "How the structural shape was chosen" narrative - chronology of design discussion doesn't belong in a durable architecture record - "Cleanup work absorbed by this project" section - this is project-scope detail; spec.md owns it Added alternatives G/H/I/J/K to cover the new design space the descriptor mechanism and entity-coordinate decisions opened up (hardcoded-per-pack, single generic entities slot, retrofit built-ins, pair-coordinate, string coordinate). This ADR is the durable artifact - migrates to docs/architecture docs/adrs/ at project close-out per PDoD9. The spec.md retains project-scope details (Tier 1 scope discipline, A1-A7 assumptions, OQ1-OQ5 degrees of freedom). Signed-off-by: Will Madden <[email protected]>
wmadden
added a commit
that referenced
this pull request
May 20, 2026
…-exemplar Both folders are superseded by the consolidated umbrella: - projects/target-extensible-ir/ — substrate predecessor, now rolled into projects/target-extensible-ir-namespaces/ (umbrella spec) + projects/contract-ir-planes/ (S1 sub-project) - projects/namespace-exemplar/ — TML-2520 / PR #534 shipping artifacts, now merged into main at commit 66da80f Their decision content is captured in the umbrella + sub-project specs and ADR. The transient working artifacts (slices/, reviews/, learnings, plans) live in wip/archived-projects-2026-05-20/ on this worktree only (wip/ is gitignored) for local reference if needed. Resolves the "consolidate the projects into one directory" motivation from the planning conversation: the on-disk projects/ tree now has one umbrella + one sub-project for this work, not five overlapping folders. Signed-off-by: Will Madden <[email protected]>
5 tasks done
wmadden
added a commit
that referenced
this pull request
May 22, 2026
Pre-flight grep inventory (postgres-enum in contract.json / *.json): - examples/prisma-next-demo/src/prisma/contract.json - examples/prisma-next-cloudflare-worker/src/prisma/contract.json - packages/3-targets/3-targets/postgres/test/fixtures/snapshot-read-shapes/postgres-enum.json - test/integration/test/authoring/parity/core-surface/expected.contract.json - examples/prisma-next-demo/migrations/app/20260422T0720_initial/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0742_migration/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0748_migration/end-contract.json - examples/prisma-next-demo/migrations/app/20260518T1701_namespaces_bookend/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0742_migration/start-contract.json - examples/prisma-next-demo/migrations/app/20260422T0748_migration/start-contract.json - examples/prisma-next-demo/migrations/app/20260518T1701_namespaces_bookend/start-contract.json Regenerated enum-bearing fixtures via pnpm fixtures:emit (and parity UPDATE_AUTHORING_PARITY_EXPECTED=1). postgres-enum.json via serializer round-trip. Reverted snapshot-read-shapes.test.ts D1 workaround. A4 PASS: pre-#534 bookends retain document-scoped storage.types enums; strict deserialize of bookends fails identically pre-D1 (0339f34^) and post-D2 — no replay regression from namespace enum slot migration. Bookends not regenerated. JSDoc: ir-node.ts uses 'pack-contributed-kind'; storage-type.ts uses '<kind>'. Signed-off-by: Will Madden <[email protected]>
Merged
5 tasks
wmadden
added a commit
that referenced
this pull request
May 26, 2026
…e PR D1 (M, Composer-2.5) hard-cuts the source surface: IR typing, validator, serializer hydration + folded TML-2658, verifier, emitter codegen, authoring lowering, and Postgres target read/write paths — document- scoped storage.types preserved as out-of-scope guard. fixtures:check is explicitly a non-gate for D1; expected to fail until D2 runs. Re- decomposition trigger at >25 package files or >30-file typecheck cascade splits into D1a (contract IR + family) + D1b (authoring + postgres target). D2 (M, Composer-2.5) grep-audits enum-bearing committed contracts, runs pnpm fixtures:emit, gates on pnpm fixtures:check, and runs the A4 migration-replay probe on pre-#534 bookends. Bookend regen is conditional on replay falsification; if A4 needs >3 source files the dispatch halts (promote per spec edge #12). D3 (S, Composer-2.5) closes the slice: PDoD3 grep gate, SDoD2 edge-case disposition audit, SDoD7 TML-2658 verification, and the full slice validation gate (typecheck, test:packages, test:integration, fixtures:check, lint:deps). No implementation changes expected; >3 straggler files routes failure back to D1 or D2 rather than band-aiding in D3. Risk #5 (Per-dispatch DoR overlay) is wired per-dispatch with explicit brief-assembly discipline drawn from drive/retro/findings.md 2026-05-21: do not lift spec table rows into a "do not relitigate" block without the (a) non-redundancy justification per row; default stance for S1.B is retire framework-encoded Postgres identity, do not add parallel slot registries; if (b) answer is "hydration/validation already enforce this", the dispatch must not introduce that structure. Each dispatch carries refusal triggers naming F1 (no read-fallback shim), F5 (no destructive git), F6 (no redundant descriptor fields), F7 (no unbriefed-blocker workarounds) from drive/calibration/ failure-modes.md. Hard-cut path is preserved. Refs TML-2623. Signed-off-by: Will Madden <[email protected]>
wmadden
added a commit
that referenced
this pull request
May 26, 2026
Pre-flight grep inventory (postgres-enum in contract.json / *.json): - examples/prisma-next-demo/src/prisma/contract.json - examples/prisma-next-cloudflare-worker/src/prisma/contract.json - packages/3-targets/3-targets/postgres/test/fixtures/snapshot-read-shapes/postgres-enum.json - test/integration/test/authoring/parity/core-surface/expected.contract.json - examples/prisma-next-demo/migrations/app/20260422T0720_initial/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0742_migration/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0748_migration/end-contract.json - examples/prisma-next-demo/migrations/app/20260518T1701_namespaces_bookend/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0742_migration/start-contract.json - examples/prisma-next-demo/migrations/app/20260422T0748_migration/start-contract.json - examples/prisma-next-demo/migrations/app/20260518T1701_namespaces_bookend/start-contract.json Regenerated enum-bearing fixtures via pnpm fixtures:emit (and parity UPDATE_AUTHORING_PARITY_EXPECTED=1). postgres-enum.json via serializer round-trip. Reverted snapshot-read-shapes.test.ts D1 workaround. A4 PASS: pre-#534 bookends retain document-scoped storage.types enums; strict deserialize of bookends fails identically pre-D1 (0339f34^) and post-D2 — no replay regression from namespace enum slot migration. Bookends not regenerated. JSDoc: ir-node.ts uses 'pack-contributed-kind'; storage-type.ts uses '<kind>'. Signed-off-by: Will Madden <[email protected]>
wmadden
added a commit
that referenced
this pull request
May 26, 2026
…e PR D1 (M, Composer-2.5) hard-cuts the source surface: IR typing, validator, serializer hydration + folded TML-2658, verifier, emitter codegen, authoring lowering, and Postgres target read/write paths — document- scoped storage.types preserved as out-of-scope guard. fixtures:check is explicitly a non-gate for D1; expected to fail until D2 runs. Re- decomposition trigger at >25 package files or >30-file typecheck cascade splits into D1a (contract IR + family) + D1b (authoring + postgres target). D2 (M, Composer-2.5) grep-audits enum-bearing committed contracts, runs pnpm fixtures:emit, gates on pnpm fixtures:check, and runs the A4 migration-replay probe on pre-#534 bookends. Bookend regen is conditional on replay falsification; if A4 needs >3 source files the dispatch halts (promote per spec edge #12). D3 (S, Composer-2.5) closes the slice: PDoD3 grep gate, SDoD2 edge-case disposition audit, SDoD7 TML-2658 verification, and the full slice validation gate (typecheck, test:packages, test:integration, fixtures:check, lint:deps). No implementation changes expected; >3 straggler files routes failure back to D1 or D2 rather than band-aiding in D3. Risk #5 (Per-dispatch DoR overlay) is wired per-dispatch with explicit brief-assembly discipline drawn from drive/retro/findings.md 2026-05-21: do not lift spec table rows into a "do not relitigate" block without the (a) non-redundancy justification per row; default stance for S1.B is retire framework-encoded Postgres identity, do not add parallel slot registries; if (b) answer is "hydration/validation already enforce this", the dispatch must not introduce that structure. Each dispatch carries refusal triggers naming F1 (no read-fallback shim), F5 (no destructive git), F6 (no redundant descriptor fields), F7 (no unbriefed-blocker workarounds) from drive/calibration/ failure-modes.md. Hard-cut path is preserved. Refs TML-2623. Signed-off-by: Will Madden <[email protected]>
wmadden
added a commit
that referenced
this pull request
May 26, 2026
Pre-flight grep inventory (postgres-enum in contract.json / *.json): - examples/prisma-next-demo/src/prisma/contract.json - examples/prisma-next-cloudflare-worker/src/prisma/contract.json - packages/3-targets/3-targets/postgres/test/fixtures/snapshot-read-shapes/postgres-enum.json - test/integration/test/authoring/parity/core-surface/expected.contract.json - examples/prisma-next-demo/migrations/app/20260422T0720_initial/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0742_migration/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0748_migration/end-contract.json - examples/prisma-next-demo/migrations/app/20260518T1701_namespaces_bookend/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0742_migration/start-contract.json - examples/prisma-next-demo/migrations/app/20260422T0748_migration/start-contract.json - examples/prisma-next-demo/migrations/app/20260518T1701_namespaces_bookend/start-contract.json Regenerated enum-bearing fixtures via pnpm fixtures:emit (and parity UPDATE_AUTHORING_PARITY_EXPECTED=1). postgres-enum.json via serializer round-trip. Reverted snapshot-read-shapes.test.ts D1 workaround. A4 PASS: pre-#534 bookends retain document-scoped storage.types enums; strict deserialize of bookends fails identically pre-D1 (0339f34^) and post-D2 — no replay regression from namespace enum slot migration. Bookends not regenerated. JSDoc: ir-node.ts uses 'pack-contributed-kind'; storage-type.ts uses '<kind>'. Signed-off-by: Will Madden <[email protected]>
wmadden
added a commit
that referenced
this pull request
May 27, 2026
…e PR D1 (M, Composer-2.5) hard-cuts the source surface: IR typing, validator, serializer hydration + folded TML-2658, verifier, emitter codegen, authoring lowering, and Postgres target read/write paths — document- scoped storage.types preserved as out-of-scope guard. fixtures:check is explicitly a non-gate for D1; expected to fail until D2 runs. Re- decomposition trigger at >25 package files or >30-file typecheck cascade splits into D1a (contract IR + family) + D1b (authoring + postgres target). D2 (M, Composer-2.5) grep-audits enum-bearing committed contracts, runs pnpm fixtures:emit, gates on pnpm fixtures:check, and runs the A4 migration-replay probe on pre-#534 bookends. Bookend regen is conditional on replay falsification; if A4 needs >3 source files the dispatch halts (promote per spec edge #12). D3 (S, Composer-2.5) closes the slice: PDoD3 grep gate, SDoD2 edge-case disposition audit, SDoD7 TML-2658 verification, and the full slice validation gate (typecheck, test:packages, test:integration, fixtures:check, lint:deps). No implementation changes expected; >3 straggler files routes failure back to D1 or D2 rather than band-aiding in D3. Risk #5 (Per-dispatch DoR overlay) is wired per-dispatch with explicit brief-assembly discipline drawn from drive/retro/findings.md 2026-05-21: do not lift spec table rows into a "do not relitigate" block without the (a) non-redundancy justification per row; default stance for S1.B is retire framework-encoded Postgres identity, do not add parallel slot registries; if (b) answer is "hydration/validation already enforce this", the dispatch must not introduce that structure. Each dispatch carries refusal triggers naming F1 (no read-fallback shim), F5 (no destructive git), F6 (no redundant descriptor fields), F7 (no unbriefed-blocker workarounds) from drive/calibration/ failure-modes.md. Hard-cut path is preserved. Refs TML-2623. Signed-off-by: Will Madden <[email protected]>
wmadden
added a commit
that referenced
this pull request
May 27, 2026
Pre-flight grep inventory (postgres-enum in contract.json / *.json): - examples/prisma-next-demo/src/prisma/contract.json - examples/prisma-next-cloudflare-worker/src/prisma/contract.json - packages/3-targets/3-targets/postgres/test/fixtures/snapshot-read-shapes/postgres-enum.json - test/integration/test/authoring/parity/core-surface/expected.contract.json - examples/prisma-next-demo/migrations/app/20260422T0720_initial/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0742_migration/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0748_migration/end-contract.json - examples/prisma-next-demo/migrations/app/20260518T1701_namespaces_bookend/end-contract.json - examples/prisma-next-demo/migrations/app/20260422T0742_migration/start-contract.json - examples/prisma-next-demo/migrations/app/20260422T0748_migration/start-contract.json - examples/prisma-next-demo/migrations/app/20260518T1701_namespaces_bookend/start-contract.json Regenerated enum-bearing fixtures via pnpm fixtures:emit (and parity UPDATE_AUTHORING_PARITY_EXPECTED=1). postgres-enum.json via serializer round-trip. Reverted snapshot-read-shapes.test.ts D1 workaround. A4 PASS: pre-#534 bookends retain document-scoped storage.types enums; strict deserialize of bookends fails identically pre-D1 (0339f34^) and post-D2 — no replay regression from namespace enum slot migration. Bookends not regenerated. JSDoc: ir-node.ts uses 'pack-contributed-kind'; storage-type.ts uses '<kind>'. Signed-off-by: Will Madden <[email protected]>
This was referenced May 29, 2026
This was referenced Jun 6, 2026
Merged
This was referenced Jun 26, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Linked issue
Refs TML-2520.
Supersedes #529 (closed). The original PR shipped a self-contradictory IR shape —
storage.tablesByNamespaceco-existed with the canonicalstorage.namespaces[id].tablesand ~80 follow-on commits were migrating consumers onto the wrong half. This branch was cut from the last commit before that wrong-direction commitment and re-implemented the storage shape correctly. Seeprojects/namespace-exemplar/spec.md§ "Why a fresh project".At a glance
A Postgres contract now declares its schemas inline, places models in them, and gets cross-schema foreign keys lowered end-to-end:
Emits as nested
storage.namespaces[id]:Decision
This PR ships three concrete things:
Per-namespace storage IR.
storage.tables(flat) andstorage.collections(Mongo) are gone. Every contract carriesstorage.namespaces[id]withtablesfor SQL families andcollectionsfor Mongo. The frameworkNamespaceinterface stays neutral — the SQL/Mongo split lives inSqlNamespace/MongoNamespace.Target-supplied namespace concretions, threaded end-to-end.
defineContract({ createNamespace })now actually does something: the SQL build path asks the target factory for a per-namespaceNamespaceconcretion (PostgresSchema,PostgresUnboundSchema,SqliteUnboundDatabase) instead of parking a family-shared payload.qualifyTable(name)is the rendering seam DDL emission walks.Cross-namespace FKs as first-class IR.
ForeignKeycarries explicit{ source: { namespaceId, tableName, columns }, target: { ... } }. The Postgres planner emitsALTER TABLE "public"."post" ADD CONSTRAINT … REFERENCES "auth"."user"("id"); the introspection verifier matches FKs by(namespaceId, tableName)instead of bare name.Plus three substrate gaps surfaced along the way and fixed inline:
tables: Record<string, never>(whosekeyofisstring), collapsing literal table-name inference at every DSL consumer. Nowtables: {}.sql-orm-client'sCollection<C, ModelName>looked tables up only under__unbound__, so once tables moved to named namespaces everyFieldTraitscollapsed toneverand trait-gated methods (eq,ilike,asc, …) disappeared. Now flattens across all storage namespaces.Db<C>similarly only walked__unbound__. Now flattens across all namespaces;db.userreachesauth.user.How it fits together
PSL grammar + parser —
namespace foo { … }blocks parse intoPslDocumentAst.namespaces[]buckets. Qualified field-type references parse too (auth.User,public.Post[]), decomposed intotypeName + typeNamespaceIdonPslField. The parser still rejects the parser-synthesised__unspecified__bucket name.Family-specific PSL interpreter — the SQL interpreter validates per-target: SQLite rejects any
namespace … { … }block withPSL_UNSUPPORTED_NAMESPACE_BLOCK; Postgres reservesnamespace unbound { … }alongside sibling named namespaces withPSL_RESERVED_NAMESPACE_NAME(the single-tenantunbound-only case stays legal — that's the multi-tenancy story). Top-level enums route tostorage.types; enums declared inside a named namespace route tostorage.namespaces[id].types(codec aliases vs per-schema database types stay split). The Mongo interpreter rejects all explicit namespace blocks.Builder normalisation —
buildSqlContractFromDefinitioncollects table coordinates per namespace, partitions enum storage entries into per-namespacetypesslots, and invokesdefinition.createNamespace?.({ id, tables, types })per declared namespace id. The factory returns the target's concreteNamespace; the family-shared payload is the fallback for targets without a factory (SQLite today).Rendering through
qualifier()/qualifyTable()— the planner now looks up the table's namespace bynamespaceId, asks it for the qualifier, and renders unqualified DDL when the namespace isPostgresUnboundSchema(sosearch_pathdecides at runtime) or fully qualified"<schema>"."<table>"otherwise. The single-tenant Postgres case (nounboundblock) continues to lower topublicand emit qualified DDL.Emitter + consumer types —
contract.d.tsreflects the canonical shape (storage.namespaces[id].tables[…]).Db<C>,Collection<C, Model>,BuiltStorageall reach across namespaces literal-key-preservingly.Behavior changes & evidence
2-namespace Postgres contracts emit cross-schema FK SQL. The demo's
Post.userIdreferencesauth.User.idand the planner rendersALTER TABLE "public"."post" ADD CONSTRAINT … REFERENCES "auth"."user"("id"). Implementation inpackages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts(qualified-reference resolution) andpackages/3-targets/3-targets/postgres/src/core/migrations/(qualified DDL). Evidence inpackages/2-sql/2-authoring/contract-psl/test/interpreter.namespaces.test.tsand the regeneratedexamples/prisma-next-demo/src/prisma/contract.json.Same contract authored via PSL and TS builder lowers to the same shape. Evidence:
packages/2-sql/2-authoring/contract-psl/test/psl-ts-namespace-parity.test.ts.SQLite + Mongo reject
namespace foo { … }with a target-named diagnostic. Implementation inpackages/2-sql/2-authoring/contract-psl/src/interpreter.ts(validateNamespaceBlocksForSqlTarget) and the Mongo interpreter. Evidence:packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.tsandpackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.ts.Postgres rejects
namespace unbound { … }next to sibling named namespaces. NewPSL_RESERVED_NAMESPACE_NAMEdiagnostic inpackages/2-sql/2-authoring/contract-psl/src/interpreter.ts. Evidence:packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts(negative + positive cases).namespace unbound { … }standalone lets the same plan land in different schemas viasearch_path. Live PGlite test: same plan applied twice, once withsearch_path=tenant_aand once withtenant_b; each tenant schema holds its owntenanttable;publicstays empty. Evidence:packages/3-targets/6-adapters/postgres/test/migrations/runner.unbound-namespace.integration.test.ts.db.<tableName>keeps literal-key inference across all namespaces. Empty namespaces emittables: {}sokeyofstaysnever;Db<C>andCollection<C, Model>walk every namespace. Implementation inpackages/2-sql/3-tooling/emitter/src/index.ts,packages/2-sql/4-lanes/sql-builder/src/types/db.ts,packages/3-extensions/sql-orm-client/src/types.ts,packages/2-sql/2-authoring/contract-ts/src/contract-types.ts.Reviewer notes
DCO sign-off carry-over. 12 commits inherited from the substrate retain on this branch are missing
Signed-off-by:. They land before the explicitgit commit -sretro applied to all newer work on this branch. The DCO check will flag them; happy togit rebase --signoff origin/main && git push --force-with-leaseif you'd prefer that done now (force-push intentionally not done unsolicited).createNamespacesignature widened. Was(id: string) => Namespace; now(input: SqlNamespaceTablesInput) => Namespace. The factory receives{ id, tables, types }in a single call so target concretions can attach tables in the constructor.PostgresUnboundSchema's constructor moved fromprivateto accessible for the same reason —postgresCreateNamespaceconstructs per-use instances with tables rather than returning the empty singleton. Identity comparison againstPostgresSchema.unboundis therefore only meaningful for the no-tables case; routing code keys offinstanceof PostgresUnboundSchemainstead.ForeignKeyIR shape changed. Old{ name, columns, references: { table, columns } }is gone; new{ source: { namespaceId, tableName, columns }, target: { namespaceId, tableName, columns }, name?, constraint, index }. The planner, the DDL renderer, the introspection verifier, the contract emitter and the validators all walk the new shape.Pre-existing flaky tests.
pnpm test:packagesshows one PostgresConnection terminated unexpectedlyinplanner.reconciliation.integration.test.tsand adb inithook timeout indb-init-update.cli.integration.test.ts— both reproduce onorigin/mainand are unrelated to this work. The new AC test inrunner.unbound-namespace.integration.test.tspasses in isolation (1/1).Skipped → unskipped.
packages/3-extensions/postgres/test/psl-namespace-qualifier-routing.test.tshad two cases skipped on the substrate gap. They're unskipped and passing now thatcreateNamespaceis plumbed.Project directory.
projects/namespace-exemplar/is intentionally left on disk for review (spec, plan, ADR drafts). Close-out PR will migrate finalised content intodocs/and delete the directory per.cursor/rules/drive-project-workflow.mdc.Verification
pnpm -w typecheck— 134/134 packages, exit 0.pnpm -w fixtures:check— exit 0 (clean re-emit).pnpm test:packages— 8722 tests pass, 4 expected fail, 5 skipped; 1 pre-existing Postgres connection flake unrelated.pnpm --filter @prisma-next/postgres test -- packages/3-extensions/postgres/test/psl-namespace-qualifier-routing.test.ts— 55/55.pnpm exec vitest run packages/3-targets/6-adapters/postgres/test/migrations/runner.unbound-namespace.integration.test.ts(in package dir) — 1/1.Follow-ups
projects/agile-agent-orchestration/calibration/documenting the FR15 wrong-direction commitment and dispatch-sizing learnings — will land in the close-out PR.projects/namespace-exemplar/content intodocs/architecture docs/— close-out PR.Alternatives considered
storage.tablesflat at the framework level and treat namespaces as a Postgres-only annotation. Rejected: forces every consumer that cares about namespaces (DDL emission, introspection, type-level Db inference) to special-case Postgres; loses the Mongo-side ability to talk about per-database collections; doesn't model the multi-tenantsearch_pathstory cleanly.storage.tablesByNamespacedual-shape view as a derived index. Rejected: the previous PR took this path and it produced ~80 commits of consumer migration onto a shape that contradicted the canonical one (FR15 vs FR13). Single canonical shape (storage.namespaces[id].tables) is the only sustainable answer.createNamespaceas a 1-arg(id) => Namespacefactory and attach tables via post-construction mutation. Rejected: IR nodes are frozen on construction (freezeNode(this)); the post-mutation path required either reflection (new (result.constructor)(…)) or unfreezing, both worse than widening the signature to take{ id, tables, types }directly.switch (id === UNBOUND_NAMESPACE_ID)in every renderer. Rejected: the AST/IR pattern is "ask the node", not "branch on a discriminator".Namespace.qualifyTableis the polymorphic seam;PostgresUnboundSchemaoverrides it to elide; renderers stay branch-free.Skill update
n/a — internal IR/substrate change. No CLI flags, no
prisma-next.config.tsfield, no error code surfaced to users.Checklist
TML-NNNN: <sentence-case title>form.Summary by CodeRabbit
Release Notes