Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

TML-2459: Plan Supabase integration as 6 sequenced projects - #460

Merged
wmadden merged 23 commits into
mainfrom
tml-2459-plan
May 13, 2026
Merged

wmadden merged 23 commits into
mainfrom
tml-2459-plan

Conversation

@wmadden

@wmadden wmadden commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

At a glance

What a user can write after all six projects in this PR ship — a Postgres app contract that namespaces models, FKs into Supabase's auth.User, declares row-level security policies, and consumes a role-bound runtime:

// app/prisma/schema.prisma
namespace public {
  model Profile {
    id       String @id @default(uuid())
    userId   String @unique
    username String

    // Cross-contract FK — `supabase:` resolves against extensionPacks
    // configured in prisma-next.config.ts. `userId` is @unique so the
    // relationship is 1:1 and the RLS policies below can't be bypassed
    // by re-attaching a profile row to another user.
    user     supabase:auth.User @relation(fields: [userId], references: [id])

    @@map("profile")
  }

  policy profiles_select_all {
    target    = Profile
    operation = select
    roles     = [anon, authenticated]
    using     = "true"
  }

  policy profiles_update_own {
    target    = Profile
    operation = update
    roles     = [authenticated]
    using     = "user_id = (auth.uid())::uuid"
    withCheck = "user_id = (auth.uid())::uuid"
  }
}
// app/handler.ts — per-request role binding
const session = req.jwt ? db.asUser(req.jwt) : db.asAnon();
return session.sql.from('profile').select({ id: true, username: true }).build().execute();

Today none of the highlighted surface exists. The IR cannot express a model in a non-public schema — neither PSL namespace blocks nor a TS namespace model option lower to anything. There is no extensionPacks-style resolution mechanism, no colon-prefixed PSL type identifier, no branded TS model handle, and no machinery anywhere that lets a model in one contract FK-reference a model in another. There is no authoring surface for row-level-security policies — no top-level PSL policy block, no .rls(…) builder stage — and no PostgresRlsPolicy IR kind for the verifier to compare against the database. There is no PostgresRuntime class to subclass, and no seam below the user middleware chain where a subclass can issue SET LOCAL role invisibly to user middleware. There is no framework primitive that says "this table's lifecycle is owned by an external system; don't try to migrate it."

This PR is the shaping artifact that makes that surface deliverable.

The decision

Deliver Supabase integration through six sequenced projects, not one bundled effort. Two framework foundations land architectural primitives that exist for reasons larger than Supabase; three capability primitives build on them; one integration project ships the user-facing package.

Project Linear What it adds
target-extensible-ir TML-2459 Polymorphic IR (framework interfaces → family abstract bases → target concrete classes); Namespace as a first-class framework concept; within-contract cross-namespace FKs
control-policy TML-2493 control: ControlPolicy field on every IR node (managed / tolerated / external / observed); verifier and planner dispatch tables
cross-contract-refs TML-2500 FK references across contract-space boundaries; model-handle brand machinery; PSL colon-prefixed dot-qualified syntax; dependency graph + ownership rules
postgres-rls TML-2501 RLS policies + Postgres roles as target-only IR; content-addressed wire names so the verifier never reparses predicates
runtime-target-layer TML-2502 Export SqlRuntime; new PostgresRuntime extends SqlRuntime; protected withRawConnection accessor below the user middleware chain; formalised transaction primitive
extension-supabase TML-2503 @prisma-next/extension-supabase package: shipped auth.* / storage.* contract, typed handles, pack descriptor, SupabaseRuntime extends PostgresRuntime, working example app

Dependency graph

            ┌─────────────────────────┐
            │ target-extensible-ir    │
            │ (TML-2459)              │
            └────────────┬────────────┘
                         │
            ┌────────────┴────────────┐
            │ control-policy          │
            │ (TML-2493)              │
            └────────────┬────────────┘
                         │
       ┌─────────────────┼─────────────────┐
       │                 │                 │
       ▼                 ▼                 ▼
┌─────────────┐  ┌─────────────┐  ┌────────────────────┐
│ cross-      │  │ postgres-   │  │ runtime-target-    │
│ contract-   │  │ rls         │  │ layer              │
│ refs        │  │ (TML-2501)  │  │ (TML-2502)         │
│ (TML-2500)  │  │             │  │                    │
└──────┬──────┘  └──────┬──────┘  └─────────┬──────────┘
       │                │                   │
       └────────────────┼───────────────────┘
                        ▼
            ┌─────────────────────────┐
            │ extension-supabase      │
            │ (TML-2503)              │
            └─────────────────────────┘

The three middle-tier projects can ship in any order once the two foundations land. extension-supabase consumes all three. May 18 is the integration-launch target.

Why this shape

Two questions drove the decomposition.

(a) What's actually Supabase-specific? Almost nothing. Multi-schema Postgres contracts unblock multi-tenant SaaS Postgres deployments (the __unspecified__ sentinel + connection search_path story is independent of Supabase). Cross-contract FK references are what any extension wants — CipherStash, PostGIS, pgvector, an internal-tools schema package — not just Supabase. RLS policies are a generic Postgres capability today written by hand without verifier coverage. The control: 'external' lifecycle marker applies to any externally-managed schema. The runtime target-layer hierarchy closes a long-standing symmetry gap that has nothing to do with Supabase.

If this work shipped as one bundle, every primitive would land Supabase-coloured and be harder to reuse later. Decomposed, each primitive ships as a focused, reviewable PR with its own consumers, tests, and ADR set.

(b) Where does the leverage sit? target-extensible-ir is the single biggest blocker. Today every dialect-specific concept (RLS, Postgres roles, namespaces, custom types) either gets smuggled through the untyped annotations: SqlAnnotations escape hatch, reconstructed outside the IR, or simply isn't supported. Once the polymorphic IR ships, the capability primitives are bounded feature work on a stable foundation rather than "feature + foundational refactor in disguise."

The two foundations have to land before the capability primitives can start. The capability primitives can then proceed in parallel.

What this PR contains

Project specs and plans for all six projects, each in projects/<name>/. Two ADR drafts for the load-bearing technical decisions:

The umbrella tracker under projects/supabase-integration/ ties them together:

  • decisions.md — canonical log of every design question settled during shaping (A1–A8, B1–B6, C1–C12, OC1–OC4); constituent specs cite this rather than restating
  • overview.md — end-to-end narrative of how the constituent projects compose into a Supabase-using app
  • example/ — design-artifact example app written against the target surface during shaping; surfaced 20 concrete design holes that informed every constituent spec
  • deferred.md — items explicitly scoped out of v0.1 (visibility/encapsulation, introspection-based emit, realtime)

Also on this branch: record-gotcha skill — a workflow for capturing consumer-perspective gotchas across Prisma Next, Compute, and Postgres. Not part of the Supabase shaping; rides this branch to keep the docs-only edits together.

What lands after this PR

Each constituent project's plan.md has its own milestone structure and Linear ticket. Implementation lands as one or more PRs per project, each individually reviewable. target-extensible-ir is sized at seven milestones (TML-2468 through TML-2474) and is the longest-running of the six; the other five are smaller.

Review here is on shape: are the project boundaries right, do the dependency arrows hold, do the foundational decisions (the ADRs, the umbrella decision log) capture what the team can live with for the next year?

Alternatives considered

  • One Supabase project, no decomposition. Rejected. The work spans five framework planes (IR, control plane, runtime, authoring DSL, integration). Bundled, every primitive lands Supabase-coloured and is hard to reuse; review scope explodes. Decomposed, the non-Supabase consumers (multi-tenant SaaS, future Postgres extensions, RLS users without Supabase) get each primitive without a Supabase dependency, and each PR is focused.
  • Skip the polymorphic IR refactor; ship Supabase through annotation shims. Rejected. The existing annotations: SqlAnnotations escape hatch is untyped and unverifiable. Every shimmed concept (RLS, multi-schema FK, custom types) becomes load-bearing in production and removing it later requires the IR refactor plus migration of every shimmed concept across the codebase. Pay the architecture tax once, now.
  • Bundle control-policy into target-extensible-ir. Rejected. The IR refactor and the per-node lifecycle primitive are orthogonal concerns living on different planes. The IR refactor is about polymorphism and class shape; control-policy is about verifier/planner dispatch tables. They land cleanest as siblings. (The field was originally called posture during shaping; renamed to control with type ControlPolicy after a naming pass.)
  • Cross-contract-space FKs in scope of target-extensible-ir. Rejected. Cross-contract reference semantics tangle with extensionPacks resolution and the dependency-graph machinery; they need their own design pass. Within-contract cross-namespace FKs (the immediate Supabase enabler) stay in TML-2459; cross-contract-space refs split out as TML-2500 with their own ownership and resolution rules.
  • Compose SupabaseRuntime instead of subclassing. Rejected. SupabaseRuntime genuinely IS-A PostgresRuntime — it issues SET LOCAL role below the middleware chain and otherwise behaves identically. Explicit forwarding via composition would require code changes every time the base runtime grew. Subclassing is the cheaper, more correct primitive, and it forces runtime-target-layer into existence as the runtime-plane sibling of TML-2459's IR target layer — closing a long-standing symmetry gap rather than working around it.

Test plan

Docs-only PR; reviewer-shaped verification:

  • Each constituent project's spec.md is internally consistent (FRs map to ACs, ACs map to milestones, sequencing notes match Linear blockedBy chains).
  • projects/supabase-integration/decisions.md covers every settled design question; constituent specs cite it rather than restating its content.
  • All cross-doc links resolve (ADRs, sibling project specs, reference implementations under packages/**).
  • Linear tickets exist with the correct blockedBy chain — TML-2459 and TML-2493 unblock TML-2500/TML-2501/TML-2502 which together unblock TML-2503.

Refs: TML-2459

@wmadden
wmadden requested a review from a team as a code owner May 10, 2026 15:52
@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a new "record-gotcha" skill document defining the canonical workflow for capturing product edge cases across Prisma Next, Compute, and Postgres, and a new design-doc rule preferring PSL examples when both PSL and TS authoring surfaces exist.

Changes

Record Gotcha Skill

Layer / File(s) Summary
Scope, role definition, and Linear MCP prerequisite
.agents/skills/record-gotcha/SKILL.md
Adds skill frontmatter, trigger/behavior, consumer vs maintainer boundary with example, default-to-capture rule, and a hard prerequisite requiring Linear MCP with operator-facing instructions and halt rules.
Product mapping, recording locations, and escalation modes
.agents/skills/record-gotcha/SKILL.md
Maps supported Prisma products to *-gotchas Linear projects, covers cross-product scope, recording locations, escalation selection by repo type, operator paths for product-team repos, and "When NOT to use" exclusions.
Numbered gotcha capture workflow
.agents/skills/record-gotcha/SKILL.md
Documents step-by-step workflow: verify Linear MCP, identify product, resolve escalation mode, search duplicates, draft and append entry, file Triage ticket with required fields, commit rules, and post-commit Source updates.
Alternate bug filing flow and complete templates
.agents/skills/record-gotcha/SKILL.md
Describes alternate "file a normal bug" flow for product-team repos and includes verbatim gotcha entry templates, Linear ticket description template (with required **Source:**), and gotchas.md bootstrap content with append-only guidance.
Examples, lifecycle markers, and anti-patterns
.agents/skills/record-gotcha/SKILL.md
Provides good vs bad entry examples, resolved/superseded handling (append-only markers), enumerates anti-patterns, and optional guidance for promoting operational lessons into skills.

Prefer PSL in Design Docs

Layer / File(s) Summary
PSL-first design-doc rule
.agents/rules/prefer-psl-in-design-docs.mdc
Adds a design-doc rule to prefer PSL examples when a feature exists in both PSL and TS authoring surfaces, clarifies TS-only examples and runtime-code treatment.

🎯 2 (Simple) | ⏱️ ~12 minutes

🐰 A skill to catch gotchas bright,
Where Prisma edge-cases take flight,
With Linear threads and templates clear,
We'll track each lesson, year by year,
And bounce back knowledge, skipping light! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title 'TML-2459: Plan Supabase integration as 6 sequenced projects' is misleading. The actual changes are two documentation files about recording gotchas and PSL design doc preferences, not Supabase integration planning. Update the PR title to accurately reflect the changes: consider 'Add skill documentation for recording gotchas and PSL-first design doc rule' or similar to match the actual file additions.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2459-plan

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented May 10, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-runtime@460

@prisma-next/family-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-mongo@460

@prisma-next/sql-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-runtime@460

@prisma-next/family-sql

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-sql@460

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-arktype-json@460

@prisma-next/extension-cipherstash

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-cipherstash@460

@prisma-next/middleware-telemetry

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/middleware-telemetry@460

@prisma-next/mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo@460

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-paradedb@460

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-pgvector@460

@prisma-next/extension-postgis

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-postgis@460

@prisma-next/postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/postgres@460

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-orm-client@460

@prisma-next/sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sqlite@460

@prisma-next/target-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-mongo@460

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-mongo@460

@prisma-next/driver-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-mongo@460

@prisma-next/contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract@460

@prisma-next/utils

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/utils@460

@prisma-next/config

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/config@460

@prisma-next/errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/errors@460

@prisma-next/framework-components

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/framework-components@460

@prisma-next/operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/operations@460

@prisma-next/ts-render

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ts-render@460

@prisma-next/contract-authoring

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-authoring@460

@prisma-next/ids

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ids@460

@prisma-next/psl-parser

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-parser@460

@prisma-next/psl-printer

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-printer@460

@prisma-next/cli

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli@460

@prisma-next/emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/emitter@460

@prisma-next/migration-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/migration-tools@460

prisma-next

npm i https://pkg.pr.new/prisma/prisma-next@460

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/vite-plugin-contract-emit@460

@prisma-next/mongo-codec

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-codec@460

@prisma-next/mongo-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract@460

@prisma-next/mongo-value

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-value@460

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-psl@460

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-ts@460

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-emitter@460

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-schema-ir@460

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-ast@460

@prisma-next/mongo-orm

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-orm@460

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-builder@460

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-lowering@460

@prisma-next/mongo-wire

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-wire@460

@prisma-next/sql-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract@460

@prisma-next/sql-errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-errors@460

@prisma-next/sql-operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-operations@460

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-schema-ir@460

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-psl@460

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-ts@460

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-emitter@460

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane-query-builder@460

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-relational-core@460

@prisma-next/sql-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-builder@460

@prisma-next/target-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-postgres@460

@prisma-next/target-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-sqlite@460

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-postgres@460

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-sqlite@460

@prisma-next/driver-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-postgres@460

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-sqlite@460

commit: f4829b7

@wmadden wmadden changed the title docs(projects): scope target-extensible-ir spec and plan (TML-2459) Scope target-extensible IR project: multi-schema Postgres, cross-namespace FKs, Supabase foundation (TML-2459) May 10, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
packages/2-sql/3-tooling/emitter/test/emitter-hook.generation.basic.test.ts (1)

954-957: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix generateContractDts argument placement in the execution-hash test

Line 954 is still using the old extra-array position, so hashes are not being passed in the same position as the rest of this file’s updated calls. This can make the test validate the wrong invocation path.

Suggested patch
-    const types = generateContractDts(ir, sqlEmission, [], [], {
-      ...testHashes,
-      executionHash: 'test-exec-hash',
-    });
+    const types = generateContractDts(ir, sqlEmission, [], {
+      ...testHashes,
+      executionHash: 'test-exec-hash',
+    });
🤖 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/3-tooling/emitter/test/emitter-hook.generation.basic.test.ts`
around lines 954 - 957, The test call to generateContractDts is passing hashes
in the old extra-array position; change the invocation so the hashes object is
the sixth argument (not the fifth) to match other calls—i.e., call
generateContractDts(ir, sqlEmission, [], [], {}, { ...testHashes, executionHash:
'test-exec-hash' }) so the fifth argument is an empty options object and the
sixth carries the hashes (update the call in the execution-hash test referencing
generateContractDts).
packages/2-sql/5-runtime/test/sql-family-adapter.test.ts (1)

26-48: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Delegation test is currently tautological.

Line 38–48 only verifies a constant return value; it does not prove markerReader.readMarker actually forwards to the profile method with the provided queryable.

Suggested test hardening
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
@@
-  it('delegates readMarker to adapter profile', async () => {
-    const adapter = new SqlFamilyAdapter(testContract, testProfile);
+  it('delegates readMarker to adapter profile', async () => {
+    const readMarker = vi.fn(async () => ({ kind: 'absent' as const }));
+    const adapter = new SqlFamilyAdapter(testContract, { ...testProfile, readMarker });
@@
     const result = await adapter.markerReader.readMarker(fakeQueryable);
 
+    expect(readMarker).toHaveBeenCalledWith(fakeQueryable);
     expect(result).toEqual({ kind: 'absent' });
   });
As per coding guidelines: "Avoid tautological tests that only restate fixture input - tests must verify behavior, not mirror object shape passed by the test itself."
🤖 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/5-runtime/test/sql-family-adapter.test.ts` around lines 26 -
48, The test is tautological because it only asserts the fixture return; modify
it so markerReader.readMarker actually delegates to the profile's
implementation: replace the current testProfile or stub its readMarker with a
spy/fixture that records the queryable argument and returns a distinct value
(e.g., { kind: 'some' }) and then assert that calling
adapter.markerReader.readMarker(fakeQueryable) returns that distinct value and
that the profile.readMarker spy was invoked with the exact fakeQueryable;
reference the SqlFamilyAdapter constructor, adapter.markerReader.readMarker, and
the testProfile/readMarker stub to locate where to change the test.
packages/2-sql/5-runtime/src/sql-runtime.ts (1)

404-411: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Set startup verification state in the optional-missing marker branch.

On Line 409, verified is set but startupVerified remains false. In mode: 'startup', that re-runs verifyMarker() on every execute instead of one startup check.

Suggested fix
   if (readResult.kind !== 'present') {
     if (this.verify.requireMarker) {
       throw runtimeError('CONTRACT.MARKER_MISSING', 'Contract marker not found in database');
     }

     this.verified = true;
+    this.startupVerified = true;
     return;
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/5-runtime/src/sql-runtime.ts` around lines 404 - 411, The
optional-missing marker branch sets this.verified but forgets to set
this.startupVerified, causing verifyMarker() to re-run in mode: 'startup';
update the non-present branch inside the readResult.kind !== 'present' path
(where verify.requireMarker is false) to also set this.startupVerified = true
(in the same place you set this.verified) so startup mode treats the check as
completed and won't re-run on every execute; refer to readResult,
verify.requireMarker, this.verified, this.startupVerified, and
verifyMarker()/execute to locate and adjust the logic.
packages/1-framework/3-tooling/cli/src/utils/formatters/migrations.ts (1)

11-12: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Replace transient spec/milestone references in inline comments.

These comments reference transient artifacts (spec OQ-4, M6 sub-spec, AC4/AC5). Please rephrase them to stable behavioral intent.

As per coding guidelines, source-code comments must not reference transient project artifacts such as sub-spec sections or milestone acceptance criteria.

Also applies to: 91-92, 168-169, 404-405, 419-420

🤖 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/3-tooling/cli/src/utils/formatters/migrations.ts` around
lines 11 - 12, Several inline comments in migrations.ts reference transient
artifacts (e.g., "spec OQ-4", "M6 sub-spec", "AC4/AC5"); update those comments
to state the stable behavioral intent instead (for example: describe the exact
rendering behavior, expected output format, or compatibility rationale). Locate
the commented lines mentioned (the block referencing legacy string[] renderer,
and the other occurrences around the indexes you saw) and replace the transient
labels with clear, version-agnostic descriptions of what the code must do or why
the special-case exists (e.g., "render byte-for-byte for legacy string[]
renderer", "preserve verbatim rendering for mongodb-shell", "ensure
backwards-compatible output formatting"), keeping the comment content focused on
behavior rather than milestones or acceptance criteria.
🟡 Minor comments (17)
docs/architecture docs/patterns/spi-at-lowest-consuming-layer.md-27-44 (1)

27-44: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add a language identifier to the fenced diagram block.

This code fence is missing a language tag and triggers MD040 in markdownlint.

Suggested patch
-```
+```text
 ┌────────────────────────────────────────────────────┐
 │ tooling / orchestration layer (the caller)         │
 │   imports the SPI; calls it; knows nothing about   │
@@
 └────────────────────────────────────────────────────┘
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @docs/architecture docs/patterns/spi-at-lowest-consuming-layer.md around
lines 27 - 44, The fenced diagram block in spi-at-lowest-consuming-layer.md is
missing a language tag causing markdownlint MD040; update the triple-backtick
that opens the ASCII diagram to include a language identifier (e.g., text) so the block becomes text ... ```; locate the ASCII diagram block shown in the
diff and add the language tag to the opening fence only.


</details>

</blockquote></details>
<details>
<summary>docs/architecture docs/patterns/json-canonical-class-in-memory.md-28-42 (1)</summary><blockquote>

`28-42`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Add a language identifier to the fenced structure diagram.**

This fence currently triggers MD040 (fenced code blocks should specify a language).

<details>
<summary>Suggested patch</summary>

```diff
-```
+```text
             authoring                      apply / consume
                 │                                 ▲
                 ▼                                 │
@@
        polymorphic                   reviewable, replayable
        dispatch                      across processes
 ```
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @docs/architecture docs/patterns/json-canonical-class-in-memory.md around
lines 28 - 42, The fenced diagram block uses a plain fence without a language tag (triggering MD040); update the opening fence to include a language identifier such as "text" (e.g., change to ```text) for the ASCII-art
diagram in the fenced structure diagram so the linter recognizes the language
and MD040 is satisfied; locate the triple-backtick fence surrounding the ASCII
diagram and add the language token to the opening fence (leave the closing fence
unchanged).


</details>

</blockquote></details>
<details>
<summary>docs/architecture docs/patterns/json-canonical-class-in-memory.md-49-53 (1)</summary><blockquote>

`49-53`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Reference links are accidentally code-formatted, so they won’t render as links.**

The `Path` cells wrap the entire markdown link in backticks (`` `[...](...)` ``), which turns them into code literals.

<details>
<summary>Suggested patch</summary>

```diff
-| Migration `ops.json` (Mongo)    | `[packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts](../../../packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts)`                     | `OpFactoryCall` classes serialise via `JSON.stringify` to `ops.json`; the runner rehydrates and walks the same class hierarchy at apply time.  |
-| Migration `ops.json` (Postgres) | `[packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts](../../../packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts)` | Same shape on the SQL side; demonstrates the pattern is target-agnostic.                                                                       |
-| Mongo wire commands             | `[packages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.ts](../../../packages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.ts)`                   | Wire commands round-trip natively because MongoDB commands *are* JSON; the canonical example of the pattern's "JSON is the contract" property. |
+| Migration `ops.json` (Mongo)    | [`packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts`](../../../packages/3-mongo-target/1-mongo-target/src/core/op-factory-call.ts)                     | `OpFactoryCall` classes serialise via `JSON.stringify` to `ops.json`; the runner rehydrates and walks the same class hierarchy at apply time.  |
+| Migration `ops.json` (Postgres) | [`packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts`](../../../packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts) | Same shape on the SQL side; demonstrates the pattern is target-agnostic.                                                                       |
+| Mongo wire commands             | [`packages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.ts`](../../../packages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.ts)                   | Wire commands round-trip natively because MongoDB commands *are* JSON; the canonical example of the pattern's "JSON is the contract" property. |
```
</details>

   
As per coding guidelines, "Keep docs current (READMEs, rules, links) (see `.cursor/rules/doc-maintenance.mdc`)."

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/architecture` docs/patterns/json-canonical-class-in-memory.md around
lines 49 - 53, The table in docs/architecture
docs/patterns/json-canonical-class-in-memory.md has its Path cells formatted as
code literals (backticked) so links won't render; edit the rows such as
"Migration `ops.json` (Mongo)", "Migration `ops.json` (Postgres)" and "Mongo
wire commands" and remove the surrounding backticks around the markdown links
(e.g. change `[...](...)` wrapped with backticks to plain `[...](...)`) so the
links render as clickable links while keeping the visible text and target
unchanged.
```

</details>

</blockquote></details>
<details>
<summary>docs/architecture docs/patterns/capability-gating.md-27-44 (1)</summary><blockquote>

`27-44`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Add a language identifier on the fenced example block.**

At Line 27, add a language tag (for example `ts`) to clear MD040.

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @docs/architecture docs/patterns/capability-gating.md around lines 27 - 44,
The fenced code block containing the example of capability objects and the
consumption-site check (showing symbols like contract.capabilities,
adapter.profile.capabilities, lowerWithLateral, lowerWithCorrelatedSubquery)
needs a language tag to satisfy MD040; update the opening triple-backtick to
include a language identifier such as ts (e.g., change tots) so the
block is marked as TypeScript.


</details>

</blockquote></details>
<details>
<summary>docs/architecture docs/patterns/frozen-class-ast.md-28-53 (1)</summary><blockquote>

`28-53`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Specify the code-fence language to satisfy markdown linting.**

At Line 28, add a language token (`ts`) so MD040 passes.

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @docs/architecture docs/patterns/frozen-class-ast.md around lines 28 - 53,
The code fence at the top of the snippet is missing a language token which
causes MD040; update the opening triple-backtick to include the TypeScript token
(i.e., change tots) so the fenced block containing the FooAstNode,
FooLiteral, FooVisitor, accept and rewrite examples is treated as TypeScript for
linting.


</details>

</blockquote></details>
<details>
<summary>docs/architecture docs/patterns/package-layering.md-35-49 (1)</summary><blockquote>

`35-49`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Add a language identifier to the fenced block.**

At Line 35, the code fence is missing a language tag, which will keep `markdownlint` warning MD040 active.

<details>
<summary>Suggested patch</summary>

```diff
-```
+```text
 packages/
 ├── 1-framework/        # Framework domain (target-agnostic)
 │   ├── 1-core/         # Lowest layer; foundational types
@@
 ├── 3-mongo-target/     # Mongo target
 └── 3-extensions/       # Extension packs (pgvector, sql-orm-client, …)
 ```
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @docs/architecture docs/patterns/package-layering.md around lines 35 - 49,
The fenced code block that starts with the "packages/" tree is missing a
language tag which triggers markdownlint MD040; update the opening
triple-backtick for that block to include a language identifier (e.g., change
totext) so the snippet is treated as plain text; locate the block that
begins with "packages/" and modify only the opening fence to add the language
identifier.


</details>

</blockquote></details>
<details>
<summary>docs/architecture docs/patterns/three-layer-polymorphic-ir.md-29-52 (1)</summary><blockquote>

`29-52`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Add a language tag to the fenced diagram block.**

Line 29 uses a plain fenced block; `markdownlint` (`MD040`) expects a language identifier, and this can break lint gates.

 
<details>
<summary>Suggested fix</summary>

```diff
-```
+```text
 ┌─────────────────────────────────────────────────────────────┐
 │ framework layer (target-agnostic)                           │
 ...
 └─────────────────────────────────────────────────────────────┘
 ```
```
</details>
As per coding guidelines, keep docs current and passing repository documentation standards.

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @docs/architecture docs/patterns/three-layer-polymorphic-ir.md around lines
29 - 52, The fenced ASCII diagram block starting with the "framework layer
(target-agnostic)" text is missing a language identifier which triggers
markdownlint MD040; fix it by adding a language tag (e.g., "text") to the
opening triple-backtick fence for that diagram block so the block becomes

examples/paradedb-demo/docker-compose.yaml-3-3 (1)

3-3: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Pin ParadeDB image to an immutable tag (or digest).

Using :latest makes local setup non-reproducible and can break example behavior unexpectedly when upstream updates.

🤖 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/paradedb-demo/docker-compose.yaml` at line 3, Replace the mutable
image tag "paradedb/paradedb:latest" with an immutable reference to make the
example reproducible; update the Docker Compose service image (the line
containing image: paradedb/paradedb:latest) to a specific version tag like
paradedb/paradedb:vX.Y.Z or a content-addressable digest form
paradedb/paradedb@sha256:<digest>, and document or pin the chosen tag/digest in
the example README so future runs use the exact same image.
packages/1-framework/3-tooling/migration/test/invariants.test.ts-62-66 (1)

62-66: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove transient sub-spec references from this inline comment.

Line 66 references sub-spec § 3, which violates the repo’s source-comment policy for transient artifacts. Reword this to describe behavior directly without spec-section pointers.

As per coding guidelines: "Source-code comments must not reference transient project artifacts ... and sub-spec section references (e.g., § 3.2)."

🤖 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/3-tooling/migration/test/invariants.test.ts` around
lines 62 - 66, Update the inline comment in invariants.test.ts (the block that
mentions Cipherstash's `installEqlBundle` and structural `create-*` ops) to
remove the transient reference "sub-spec § 3 / cipherstash-migration.spec.md"
and instead describe the behavior directly: state that those operations are the
canonical examples of additive operations that include invariantIds for marker
bookkeeping and replay tracking, and clarify the distinction between
operationClass (policy gating) and invariantId (replay tracking).
packages/1-framework/3-tooling/cli/test/commands/migration-show.test.ts-335-338 (1)

335-338: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove transient milestone/task identifiers from the inline comment.

Please avoid T6.6 / AC8 references in source comments and keep only behavior-focused wording.

Proposed edit
-    // M6 (T6.6 / AC8): operationClass tags no longer inlined in the
+    // Operation-class tags are no longer inlined in the
     // human-readable line. Destructive ops still render a "(destructive)"
     // marker (replaces the old "[destructive]" tag); additive/widening/
     // mutative/data render bare.

As per coding guidelines: "Source-code comments must not reference transient project artifacts including ... milestone-task IDs ... [and] milestone-named acceptance criteria."

🤖 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/3-tooling/cli/test/commands/migration-show.test.ts`
around lines 335 - 338, Remove the transient milestone/task identifiers "T6.6 /
AC8" from the inline comment that begins with "M6 (T6.6 / AC8): operationClass
tags no longer inlined..." in migration-show.test.ts and rewrite it to be
behavior-focused (e.g., "M6: operationClass tags no longer inlined in the
human-readable line. Destructive ops still render a '(destructive)' marker;
additive/widening/mutative/data render bare."). Ensure only the transient IDs
are removed and the comment still documents the expected behavior.
examples/paradedb-demo/prisma-next.config.ts-19-20 (1)

19-20: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove lint suppression and handle missing DATABASE_URL explicitly.

This bypasses the lint policy and hides a clearer config error path. Prefer resolving the env var once and throwing a direct error if absent, then pass a non-null value to connection.

As per coding guidelines: “Never suppress biome lints.”

🤖 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/paradedb-demo/prisma-next.config.ts` around lines 19 - 20, Remove
the biome lint suppression and stop using the non-null assertion on
process.env['DATABASE_URL']!; instead, read process.env['DATABASE_URL'] into a
local constant (e.g., const databaseUrl = process.env['DATABASE_URL']), verify
it is defined and throw a clear error if missing, then pass that validated
non-null value into the connection field (replace the use of
process.env['DATABASE_URL']! in the connection setting). Ensure the thrown error
message clearly states that DATABASE_URL is required.
packages/1-framework/3-tooling/migration/test/materialise-extension-migration-package-if-missing.test.ts-42-42 (1)

42-42: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove transient acceptance-criteria IDs from the comment.

Please reword this line to describe the invariant directly without AC-7 / AM12 identifiers.

As per coding guidelines: “Source-code comments must not reference transient project artifacts including milestone acceptance criteria.”

🤖 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/3-tooling/migration/test/materialise-extension-migration-package-if-missing.test.ts`
at line 42, Update the test title string in the it(...) call so it no longer
references transient IDs; replace "leaves on-disk content byte-identical when
the dir already exists (AC-7 / AM12)" with a direct invariant description such
as "leaves on-disk content byte-identical when the directory already exists" in
the test defined by the it(...) invocation to remove the acceptance-criteria
identifiers.
packages/1-framework/3-tooling/cli/test/output.migration-commands.test.ts-22-24 (1)

22-24: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Avoid transient milestone/spec references in test comments.

Please rewrite these comments to describe behavior directly (without M6, AC*, or sub-spec references), per repo doc-maintenance rules.

As per coding guidelines: “Source-code comments must not reference transient project artifacts including milestone-task IDs, milestone acceptance criteria, and sub-spec references.”

Also applies to: 57-57, 64-64

🤖 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/3-tooling/cli/test/output.migration-commands.test.ts`
around lines 22 - 24, The comment above the assertion
expect(stripped).toContain('Next: prisma-next migration status') (and similar
comments at the other noted locations) includes transient milestone/sub-spec
references (e.g., "M6 sub-spec § Output shape § footer"); replace those comments
with a concise description of the observable behavior being tested — for
example: state that a no-op apply still shows the canonical next-step hint so
the user knows where to verify state — and remove any mentions of milestone IDs,
acceptance criteria tags, or sub-spec references; update the comment text near
the assert in output.migration-commands.test.ts accordingly.
packages/3-extensions/cipherstash/DEVELOPING.md-57-58 (1)

57-58: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use consistent Arktype capitalization in docs.

Line 58 uses arktype; the rest of the repo/docs use Arktype. Aligning wording improves grep/search consistency.

✏️ Suggested doc fix
-- `RuntimeParameterizedCodecDescriptor<{ equality, freeTextSearch }>`
-  with arktype `paramsSchema` validated at the contract boundary.
+- `RuntimeParameterizedCodecDescriptor<{ equality, freeTextSearch }>`
+  with Arktype `paramsSchema` validated at the contract boundary.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-extensions/cipherstash/DEVELOPING.md` around lines 57 - 58, Change
the lowercase "arktype" to the project-standard "Arktype" in the docs where
`RuntimeParameterizedCodecDescriptor<{ equality, freeTextSearch }>` and
`paramsSchema` are described so the wording is consistent; update the phrase on
the line that currently reads "arktype `paramsSchema`" to "Arktype
`paramsSchema`" to match other docs and repo grep conventions.
examples/multi-extension-monorepo/test/multi-space.e2e.integration.test.ts-1-47 (1)

1-47: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Replace milestone/tracking IDs in comments with durable behavior wording.

The block comment currently includes transient identifiers (T4.4, TC-8, AC5, NFR6). Please keep only stable behavior descriptions.

As per coding guidelines, “Source-code comments must not reference transient project artifacts including milestone-task IDs and milestone acceptance criteria codes.”

🤖 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/multi-extension-monorepo/test/multi-space.e2e.integration.test.ts`
around lines 1 - 47, The top block comment in the test (the multi-extension
monorepo E2E description and the "Layers of coverage" numbered list) contains
transient milestone/tracking IDs (e.g., T4.4, TC-8, AC5, NFR6); remove those IDs
and rewrite any reference to them as stable behavioral descriptions only,
preserving the existing numbered coverage points and examples (the "Pinned
per-space artefacts on disk", "Multi-space planning", "Multi-space apply", and
"Order-independent" paragraphs) so the comment documents durable behavior rather
than project task identifiers.
packages/1-framework/3-tooling/cli/test/output.db-update.test.ts-82-83 (1)

82-83: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove transient milestone/acceptance references from inline comments.

These comments encode temporary tracking labels (M6, T6.6, AC*, spec/OQ) instead of durable behavior intent. Please rewrite them as plain behavior-focused notes.

As per coding guidelines, “Source-code comments must not reference transient project artifacts including milestone-task IDs and milestone acceptance criteria codes.”

Also applies to: 198-202, 300-303, 385-390

🤖 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/3-tooling/cli/test/output.db-update.test.ts` around
lines 82 - 83, Replace transient project-tracking labels in inline comments
(e.g. the comment starting "// M6 (T6.6 / AC8): inline operationClass tags
removed; destructive ops keep a "(destructive)" marker on the same line.") with
plain, behavior-focused notes that state the intent (for example: "Inline
operationClass tags are removed; destructive operations retain a '(destructive)'
marker on the same line."). Apply the same change to the other commented blocks
referenced (lines ~198-202, ~300-303, ~385-390), removing milestone/task/AC/spec
codes and keeping only durable descriptions of behavior or requirements.
packages/1-framework/3-tooling/cli/src/control-api/operations/migration-apply.ts-73-74 (1)

73-74: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove transient sub-spec references from source comments.

Comments now include Sub-spec § ... references; these are transient artifacts and should be rewritten as stable behavior descriptions.

As per coding guidelines, source-code comments must not reference transient artifacts such as sub-spec section references.

Also applies to: 113-114

🤖 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/3-tooling/cli/src/control-api/operations/migration-apply.ts`
around lines 73 - 74, Remove the transient "Sub-spec § ..." reference in the
comment containing "Sub-spec § `--ref <hash>` semantics under multi-space." and
rewrite it as a stable, descriptive sentence that explains the actual behavior
of the --ref option (e.g., that --ref accepts a migration hash to target a
specific migration across multiple spaces and how conflicts are resolved), and
make the same change for the other comment at the block referenced by lines
113-114; update the comment text near the migration-apply module (the comment
containing "`--ref <hash>` semantics under multi-space") so it documents
concrete behavior rather than a sub-spec pointer.
🧹 Nitpick comments (13)
.agents/rules/explicit-opt-in-over-diagnostics.mdc (1)

3-47: ⚡ Quick win

Trim or de-scope this as an always-applied rule.

Given alwaysApply: true, this is too long for an always-on rulecard. Keep a short always-on directive and move examples/rationale to a non-always rule (or docs), or set alwaysApply: false with scoped globs if this is domain-specific.

Proposed frontmatter-level adjustment
 ---
 description: Prefer requiring explicit opt-in over emitting diagnostics on intentional user paths
-alwaysApply: true
+alwaysApply: false
+globs:
+  - "**/*.{ts,tsx,js,md,mdc}"
 ---

Based on learnings: "Always-apply rules must be short, globally relevant, and stable; rules applying only to specific areas (SQL, CLI, tests) should set alwaysApply: false and use globs in frontmatter".

🤖 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 @.agents/rules/explicit-opt-in-over-diagnostics.mdc around lines 3 - 47, The
rule is too long and domain-specific to remain always-on; update the frontmatter
by either (A) trimming this card to a short, globally-relevant directive and
moving examples/rationale into a non-always rule or external docs, or (B) change
alwaysApply: true to alwaysApply: false and add targeted globs so it only runs
for relevant files (e.g., SQL/CLI/test paths); locate the top-level frontmatter
key alwaysApply and the rule body titled "Explicit opt-in over noisy
diagnostics" to make the change and move or reduce the examples accordingly.
.agents/skills/drive-create-spec/SKILL.md (1)

104-104: 💤 Low value

Consider consistent spelling: use "implementer" instead of "implementor".

Lines 104 and 112 use "implementor". The rest of the codebase consistently uses "implementer" (found in projects/oss-setup/spec.md and projects/extension-contract-spaces/spec.md). Standardizing on "implementer" aligns with the established codebase convention and modern technical writing usage.

🤖 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 @.agents/skills/drive-create-spec/SKILL.md at line 104, Replace the
nonstandard spelling "implementor" with the codebase-preferred "implementer"
wherever it appears in the SKILL.md requirement wording (the requirement
sentences that currently read "implementor"). Update both instances reported
(the two requirement lines) and run a quick grep/search for any other
occurrences to ensure consistency with projects/oss-setup/spec.md and
projects/extension-contract-spaces/spec.md; no behavioral changes required, just
textual replacement.
packages/2-sql/2-authoring/contract-psl/src/psl-attribute-parsing.ts (1)

209-243: 💤 Low value

Escape handling covers common cases.

The escape detection logic (line 219: body[index - 1] !== '\\') handles simple escaped quotes but wouldn't correctly handle edge cases like escaped backslashes followed by quotes ("value\\"). For V1 PSL string options this is acceptable, as the diagnostic message indicates this is a limited surface. The actual quote parsing/unescaping is delegated to parseQuotedStringLiteral which likely handles these cases properly.

💡 Future consideration for more robust escape handling

For completeness, counting consecutive backslashes would handle all escape sequences:

 function splitObjectLiteralEntries(body: string): readonly string[] {
   // ... existing setup ...
   for (let index = 0; index < body.length; index += 1) {
     const ch = body[index] ?? '';
     if (quote) {
-      if (ch === quote && body[index - 1] !== '\\') {
+      // Count consecutive backslashes before quote
+      let backslashCount = 0;
+      for (let j = index - 1; j >= 0 && body[j] === '\\'; j--) backslashCount++;
+      if (ch === quote && backslashCount % 2 === 0) {
         quote = null;
       }

Not needed for V1, but worth considering if PSL object literals expand beyond simple string options.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/2-authoring/contract-psl/src/psl-attribute-parsing.ts` around
lines 209 - 243, splitObjectLiteralEntries' quote-termination logic incorrectly
treats a quote as unescaped if the immediately preceding char is not a single
backslash; update the check inside the if (quote) block so you count consecutive
backslashes immediately before body[index] and only treat the quote as closing
when that count is even (i.e., not escaped). Modify the logic in
splitObjectLiteralEntries (the quote handling around body[index - 1] !== '\\')
to walk backward from index-1, count backslashes, and use count % 2 === 0 to
decide whether to clear quote, leaving the rest of the function intact.
packages/2-sql/4-lanes/relational-core/src/plan.ts (1)

24-40: ⚡ Quick win

Remove manual line wrapping from JSDoc.

The JSDoc comment spans multiple paragraphs with manual ~80-column line breaks. Per coding guidelines, JSDoc prose should avoid manual wrapping.

📝 Proposed fix
 /**
- * Wraps an `AnyQueryAst` (typically a `RawSqlExpr` constructed package-internally
- * by an extension's migration factory) in a fully-populated `SqlQueryPlan`
- * whose `meta` is sourced from the supplied contract.
+ * Wraps an `AnyQueryAst` (typically a `RawSqlExpr` constructed package-internally by an extension's migration factory) in a fully-populated `SqlQueryPlan` whose `meta` is sourced from the supplied contract.
  *
- * Centralising the envelope here means consumers (cipherstash migration
- * factories today; future raw-sql callers) cannot drift on `storageHash` /
- * `target` / `targetFamily`, which would otherwise surface as a subtle
- * `assertContractMatches` failure inside `dataTransform`. `params` defaults
- * to `[]` because parameters embedded in the AST as `ParamRef`s are resolved
- * at lowering time (`encodeParams` walks `plan.ast.collectParamRefs()`),
- * not at plan-construction time.
+ * Centralising the envelope here means consumers (cipherstash migration factories today; future raw-sql callers) cannot drift on `storageHash` / `target` / `targetFamily`, which would otherwise surface as a subtle `assertContractMatches` failure inside `dataTransform`. `params` defaults to `[]` because parameters embedded in the AST as `ParamRef`s are resolved at lowering time (`encodeParams` walks `plan.ast.collectParamRefs()`), not at plan-construction time.
  *
- * The default `laneId` of `'raw'` reflects raw-SQL plans' standard lane tag;
- * callers (e.g. a future `sql-raw-factory`) may override to differentiate
- * the plan's provenance.
+ * The default `laneId` of `'raw'` reflects raw-SQL plans' standard lane tag; callers (e.g. a future `sql-raw-factory`) may override to differentiate the plan's provenance.
  */
🤖 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/4-lanes/relational-core/src/plan.ts` around lines 24 - 40, The
JSDoc above the SqlQueryPlan wrapper contains manual ~80-column line breaks and
multi-paragraph wrapped text; reflow the comment into normal, unwrapped prose
(single or multiple paragraphs as appropriate) without manual line breaks,
preserving all original content and references to AnyQueryAst, RawSqlExpr,
SqlQueryPlan, params, storageHash/target/targetFamily, encodeParams, and the
default laneId 'raw' so the documentation reads naturally and adheres to the
project's JSDoc guidelines.
packages/2-sql/4-lanes/relational-core/src/ast/adapter-types.ts (1)

12-14: ⚡ Quick win

Remove manual line wrapping from JSDoc.

The JSDoc comment uses manual ~80-column line wraps. Per coding guidelines, JSDoc prose should avoid manual line breaks and allow the formatter/viewer to handle wrapping.

📝 Proposed fix
-/**
- * Outcome of an adapter's marker read. `no-table` means the marker storage itself is absent (e.g. attaching to a database that was never `db init`'d); `absent` means the storage exists but holds no row for the requested space; `present` carries the parsed record. Callers distinguish these so runtime telemetry and `requireMarker` policy can react to each case appropriately.
- */
+/** Outcome of an adapter's marker read. `no-table` means the marker storage itself is absent (e.g. attaching to a database that was never `db init`'d); `absent` means the storage exists but holds no row for the requested space; `present` carries the parsed record. Callers distinguish these so runtime telemetry and `requireMarker` policy can react to each case appropriately. */
🤖 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/4-lanes/relational-core/src/ast/adapter-types.ts` around lines
12 - 14, The JSDoc above the adapter marker read outcome is manually wrapped to
~80 columns; remove the manual line breaks so the comment becomes a single
unbroken paragraph (no hard line wraps) describing the three statuses
(`no-table`, `absent`, `present`) and their semantics; update the comment block
located above the adapter marker read type/definition in adapter-types.ts (the
JSDoc that begins "Outcome of an adapter's marker read") so formatting is
natural prose with no manual line wrapping.
packages/2-sql/5-runtime/src/codecs/alias-resolver.ts (1)

24-26: ⚡ Quick win

Remove manual line wrapping from inline comment.

The inline comment uses manual line breaks. Per coding guidelines, comments should avoid manual ~80-column wrapping.

📝 Proposed fix
   } else if (ast.kind === 'raw-sql') {
-    // Raw-SQL ASTs do not bind a single primary table — alias resolution
-    // is driven by inline `IdentifierRef`s the caller embedded directly.
+    // Raw-SQL ASTs do not bind a single primary table — alias resolution is driven by inline `IdentifierRef`s the caller embedded directly.
   } else {
🤖 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/5-runtime/src/codecs/alias-resolver.ts` around lines 24 - 26,
The inline comment inside the else if (ast.kind === 'raw-sql') branch contains
manual line breaks; replace it with a single unwrapped comment line (or let the
editor handle wrapping) so it reads continuously (e.g., "// Raw-SQL ASTs do not
bind a single primary table — alias resolution is driven by inline
`IdentifierRef`s the caller embedded directly.") while keeping the same wording
and meaning.
packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts (1)

699-706: ⚡ Quick win

Use ifDefined() for new conditional spreads in index().

Line 702–706 uses inline spread conditionals for name, type, and options; this should follow the project’s ifDefined() pattern for consistency.

♻️ Suggested refactor
   return {
     kind: 'index',
     fields: normalizeFieldRefInput(fields),
-    ...(options?.name !== undefined ? { name: options.name } : {}),
-    ...(options?.type !== undefined ? { type: options.type } : {}),
-    ...(options?.options !== undefined
-      ? { options: options.options as Record<string, unknown> }
-      : {}),
+    ...ifDefined('name', options?.name),
+    ...ifDefined('type', options?.type),
+    ...ifDefined('options', options?.options as Record<string, unknown>),
   };

As per coding guidelines, "{packages,examples,test}/**/*.{ts,tsx}: Use ifDefined() from @prisma-next/utils/defined for conditional object spreads instead of inline conditional spread patterns."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts` around lines 699
- 706, The index() return object uses inline conditional spreads for name, type,
and options; replace those with calls to ifDefined(...) from
'@prisma-next/utils/defined' to match project pattern. Import ifDefined at the
top if missing, then change the object to include ifDefined('name',
options?.name), ifDefined('type', options?.type), and ifDefined('options',
options?.options as Record<string, unknown>) while keeping the existing kind and
fields (normalizeFieldRefInput(fields)) intact. Ensure types remain the same and
remove the inline ...(condition ? { key: value } : {}) spreads.
packages/1-framework/3-tooling/cli/test/utils/extension-pack-inputs.test.ts (1)

25-31: 💤 Low value

Prefer double-cast pattern for test stub objects.

The empty-cast stubs use direct casts ({} as MigrationMetadata), but the test-mocking guideline recommends double casts (as unknown as X) for clarity and safety at mock boundaries.

♻️ Refactor to use double-cast pattern
-const STUB_METADATA = {} as MigrationMetadata;
-const STUB_OPS = {} as MigrationOps;
+const STUB_METADATA = {} as unknown as MigrationMetadata;
+const STUB_OPS = {} as unknown as MigrationOps;
 const migrationPkg: DescriptorMigrationPackage = {

As per coding guidelines, use double casts (as unknown as X) for mocks and dynamic proxies in tests instead of direct casts.

🤖 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/3-tooling/cli/test/utils/extension-pack-inputs.test.ts`
around lines 25 - 31, The test uses direct casts for stub objects
(STUB_METADATA, STUB_OPS) which should be replaced with the double-cast pattern;
update the declarations so the empty object is cast as unknown first and then to
the target type (e.g., STUB_METADATA and STUB_OPS should be created as {} as
unknown as MigrationMetadata and {} as unknown as MigrationOps) and ensure any
uses in migrationPkg remain unchanged.
packages/1-framework/3-tooling/cli/src/control-api/operations/apply-aggregate.ts (1)

206-211: ⚡ Quick win

Drop transient spec references in implementation comments.

Line 210 references M6 sub-spec § Required changes 1; please replace it with a behavior-focused comment only.

As per coding guidelines, source-code comments must not reference transient project artifacts such as sub-spec section pointers.

🤖 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/3-tooling/cli/src/control-api/operations/apply-aggregate.ts`
around lines 206 - 211, Update the implementation comment above the function
that projects planner per-space resolutions into
AggregatePerSpaceExecutionEntry[] (the comment that references "M6 sub-spec §
Required changes 1") to remove the transient sub-spec pointer and instead
describe the intended behavior: explain that for apply-mode (includeMarkers ===
true) the function should include marker-adjusted entries per space, and for
non-apply modes it should omit markers and only emit executed resolution data;
mention the relevant symbols AggregatePerSpaceExecutionEntry and includeMarkers
to make the behavioral intent clear.
packages/1-framework/3-tooling/cli/src/control-api/operations/db-apply-aggregate.ts (1)

130-134: ⚡ Quick win

Please replace transient planning references in comments with behavior-only wording.

Line 132 and Line 210 currently reference milestone/spec artifacts. Keep these comments implementation-focused so they remain stable as planning docs evolve.

As per coding guidelines, source-code comments must avoid transient artifacts like milestone references and sub-spec section pointers.

Also applies to: 206-210

🤖 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/3-tooling/cli/src/control-api/operations/db-apply-aggregate.ts`
around lines 130 - 134, Replace transient planning/spec references in the
comments around the orphan-marker pre-flight logic in db-apply-aggregate.ts (the
block mentioning "Orphan-marker pre-flight", "M2 marker-check", and the call
runContractSpaceVerifierMarkerCheck and references to `db init` / `db update`).
Reword those lines (including the ones around 206-210 and specifically the prior
mention at line ~132) to behavior-only wording: describe what the code does
(e.g., "refuse to apply when a marker row exists for a space that is not
declared in the aggregate; this mirrors the marker check performed by
runContractSpaceVerifierMarkerCheck and runs before planning to prevent applying
with orphaned markers") and remove any milestone/spec section references or
transient planning artifacts.
packages/1-framework/3-tooling/cli/src/control-api/types.ts (1)

319-323: ⚡ Quick win

Remove transient planning references from source comments.

Line 319, Line 540, and Line 628 include sub-spec § / F4/F7 style references. Please rewrite these comments to describe behavior directly without milestone/spec artifact pointers.

As per coding guidelines, source-code comments must not reference transient artifacts such as sub-spec sections or milestone acceptance identifiers.

Also applies to: 540-541, 628-633

🤖 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/3-tooling/cli/src/control-api/types.ts` around lines 319
- 323, Remove transient milestone/spec references from the inline comment that
currently begins "M6 sub-spec § Output shape contract — every space involved in
a run is observable in the success summary, including its post-apply marker, so
the per-space invariant is visible to the user (closing F4 / F7 from
`e2e-verification.md`)." and the other comment blocks that mention "sub-spec §"
/ "F4/F7"; instead rewrite each comment to state the behavior directly (for
example: "Output contract: the success summary must include every space involved
in a run along with its post-apply marker so users can observe the per-space
invariant") and apply the same treatment to the similar comments that reference
sub-specs or milestone IDs elsewhere in this file; keep the text focused on the
observed behavior and acceptance criteria without referencing spec sections or
milestone identifiers.
packages/1-framework/3-tooling/migration/src/aggregate/strategies/graph-walk.ts (1)

59-62: ⚡ Quick win

Use ifDefined() for conditional spread here.

Replace the inline conditional spread with the shared ifDefined() helper for consistency with repo conventions.

As per coding guidelines: “Use ifDefined() from @prisma-next/utils/defined for conditional object spreads instead of inline conditional spread patterns.”

🤖 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/3-tooling/migration/src/aggregate/strategies/graph-walk.ts`
around lines 59 - 62, The conditional spread when calling findPathWithDecision
should use the shared helper ifDefined from `@prisma-next/utils/defined` rather
than an inline ternary; update the call that constructs the options object (the
call assigning outcome via findPathWithDecision(graph, fromHash,
member.headRef.hash, { required, ...(refName !== undefined ? { refName } : {}),
})) to import and use ifDefined to include refName only when defined (e.g., {
required, ...ifDefined('refName', refName) } pattern), keeping the other
parameters (graph, fromHash, member.headRef.hash, required) unchanged and
ensuring the ifDefined helper is imported at the top of the file.
packages/1-framework/3-tooling/cli/src/control-api/operations/migration-apply.ts (1)

209-209: ⚡ Quick win

Use ifDefined() instead of ternary conditional spreads for optional fields.

This file mixes both patterns. Please switch these conditional spreads to ifDefined(...) for consistency with the repo standard.

Proposed refactor
-      ...(isAppMember && refName !== undefined ? { refName } : {}),
+      ...ifDefined('refName', isAppMember ? refName : undefined),

-        ...(isAppMember && refName !== undefined ? { refName } : {}),
+        ...ifDefined('refName', isAppMember ? refName : undefined),

-        ...(appPlan.pathDecision.refName !== undefined
-          ? { refName: appPlan.pathDecision.refName }
-          : {}),
+        ...ifDefined('refName', appPlan.pathDecision.refName),

-    ...(pathDecision !== undefined ? { pathDecision } : {}),
+    ...ifDefined('pathDecision', pathDecision),

Based on learnings, this repo prefers ifDefined for conditional object spreads instead of inline ternary spread patterns.

Also applies to: 234-234, 429-431, 450-450

🤖 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/3-tooling/cli/src/control-api/operations/migration-apply.ts`
at line 209, Replace the inline ternary spread patterns like ...(isAppMember &&
refName !== undefined ? { refName } : {}) with the repository-standard
ifDefined(...) helper; e.g. use ifDefined(refName, v => ({ refName: v })) (or
ifDefined(isAppMember && refName, v => ({ refName: v })) if the presence depends
on a separate boolean) and apply the same replacement for the other conditional
spreads mentioned (the similar ternary spreads at the other occurrences).

Comment thread examples/paradedb-demo/src/main.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 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 @.agents/skills/record-gotcha/SKILL.md:
- Around line 162-170: Add a language identifier to the fenced code block that
contains the commit message template (the triple-backtick block starting with
the commit template "docs(gotcha): record <one-line title>") to silence
markdownlint; update the opening fence from ``` to ```text so the block is
explicitly marked as plain text.
- Around line 62-64: Replace the three TODO placeholders in the table rows for
Prisma Next, Prisma Compute, and Prisma Postgres with the actual Linear project
keys for their main backlog projects (replace `TODO: confirm main PN project
key`, `TODO: confirm main Compute project key`, and `TODO: confirm main PPg
project key` with the correct keys for the `pn-gotchas`, `compute-gotchas`, and
`ppg-gotchas` projects), ensuring the values match what the "Filing a normal
bug" workflow expects so that the workflow (referenced as "Filing a normal bug")
can use those keys when creating tickets.
🪄 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: ec334591-68e2-4f6a-ac45-7cc1ee3a1b19

📥 Commits

Reviewing files that changed from the base of the PR and between 9edbeef and 0680d6a.

📒 Files selected for processing (1)
  • .agents/skills/record-gotcha/SKILL.md

Comment thread .agents/skills/record-gotcha/SKILL.md Resolved
Comment thread .agents/skills/record-gotcha/SKILL.md Resolved
@wmadden wmadden changed the title Scope target-extensible IR project: multi-schema Postgres, cross-namespace FKs, Supabase foundation (TML-2459) TML-2459: Plan target-extensible IR + Supabase integration May 13, 2026
@wmadden
wmadden force-pushed the tml-2459-plan branch 2 times, most recently from 71c7b01 to 3fd1ad7 Compare May 13, 2026 06:32
wmadden added a commit that referenced this pull request May 13, 2026
The commit-message template fenced block at lines 162-170 had no language
identifier, tripping markdownlint MD040. Tag it as text so the lint passes
and downstream renderers know not to attempt syntax highlighting.

Refs: PR #460 review (coderabbitai inline thread on .agents/skills/record-gotcha/SKILL.md).
Signed-off-by: Will Madden <[email protected]>
@wmadden wmadden changed the title TML-2459: Plan target-extensible IR + Supabase integration TML-2459: Plan Supabase integration as 6 sequenced projects May 13, 2026
wmadden added a commit that referenced this pull request May 13, 2026
`prisma` is the language identifier registered with the highlighters
that render the docs (GitHub, VSCode, the docs site); `psl` is not
and renders as plain text everywhere. The mistake is easy to make
because the surface is colloquially called "PSL" in prose, but the
fence has to say `prisma`.

Replaces every ```psl fence on this branch with ```prisma (12
occurrences across 7 doc files, plus the live PR #460 body) and adds
a "Code fencing for PSL" section to the prefer-psl-in-design-docs
agent rule so this convention is documented going forward.

Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
…mespace examples

Profile.user → auth.User is conceptually 1:1: at most one Profile row
per User. Without @unique on userId the FK admits 1:n, which (a)
misrepresents the modeling intent the example is meant to illustrate
and (b) lets a row's userId be re-attached to another user — defeating
any RLS policy that keys off 'this row's userId is the calling user'.

Affects two spec examples:
- cross-contract-refs/spec.md — PSL Profile gains @unique; the TS
  parallel form gains a .attributes({ uniques: [...] }) stage matching
  the .relations / .attributes / .sql / .rls order used elsewhere on
  the branch. Adds a short note explaining why.
- target-extensible-ir/spec.md — the namespace example's Profile gains
  @unique on userId for the same reason; no RLS here, but the 1:1
  intent is the same.

PR #460 body has the same fix applied separately.

Signed-off-by: Will Madden <[email protected]>
wmadden added 17 commits May 13, 2026 17:38
Adds projects/target-extensible-ir/ capturing the shaping work for
flipping Contract IR and Schema IR from flat data shapes to a
three-layer polymorphic class hierarchy (framework interfaces -> family
abstract bases -> target concrete classes), modelled on the existing
OpFactoryCall pattern (ADR 195) and Mongo Schema IR.

The spec covers: the JSON-canonical / class-in-memory round-trip
(ADR 192/196), domain-operation layering (verifier and hydrator follow
the same recipe), two structural exemplars (enums first as a refactor
of an existing hacked solution, namespace second as a new first-class
concept with the __unspecified__ sentinel), Mongo migration to the
3-layer split, and durable documentation deliverables (AGENTS.md rule
split, typescript-patterns.md sibling section, Architecture Overview
principles update, ADR drafts).

The plan is a stub awaiting a principal-engineer pass to size the
blast radius and decide infrastructure sequencing, Mongo timing, and
documentation timing.

Refs: TML-2459
Signed-off-by: Will Madden <[email protected]>
…e plan

Resolve PE-pass open questions inline and lift cross-namespace FK plus namespace authoring DSL into scope.

Spec:
- ContractSerializer SPI (deserializeContract + serializeContract); validateContract removed.
- HAS-A target facade with composed SPI implementers (target.contractSerializer, target.schemaVerifier, ...).
- Per-SPI family abstract bases preserved as the inheritance ramp for extension/target authors.
- New FR16a/FR16b plus AC4a covering namespace authoring DSL (PSL + TS builder) and cross-namespace FKs.
- AC4 restored to the FL-02 cross-namespace FK demonstration.
- Sequencing constraints documented: TML-2457, TML-2463, TML-2408 must precede; TML-2464 must follow.
- Open Questions section deleted; resolutions live in their proper homes.

Plan:
- Seven milestones M1 -> M2 -> M3 -> M4 -> M5a -> M5b -> M6 (foundation -> Mongo first consumer -> Postgres SPI shells -> enum exemplar -> namespace + DSL -> cross-namespace FK -> docs).
- M5b is the FL-02 fix that unblocks the Supabase project.
- Cross-project dependencies and sequencing recorded against the Linear ticket IDs.

Signed-off-by: Will Madden <[email protected]>
Tentative intentional design notes for the Supabase integration work,
captured before committing to a project shape. Eight focused docs covering:

- end-to-end user story with the canonical code sample
- modeled / tolerated / externally-managed / drift posture as a generic
  IR property, with verifier and planner dispatch
- cross-contract-space FK references (refIn) — TS surface, IR carrier
  shape, resolution against the loaded aggregate, extension publish
  pipeline (PSL surface flagged as open design question)
- PostgresRlsPolicy as a target-only IR kind, inline c.rlsPolicy DSL,
  plain-string predicates for v0.1, pg_policies-based verification
- @prisma-next/extension-supabase package shape, createSupabaseRuntime
  with role-binding / SET LOCAL story, pool footgun mitigations
- developer experience: scaffold, getting-started outline, migration
  story from @supabase/supabase-js
- explicit deferred / non-goals list (realtime, storage, introspection-
  based emit, PSL refIn, etc.)

Framed throughout as notes, not specs — open questions are explicit and
the project shape (one project vs foundation+supabase split) is
deliberately undecided. Builds on TML-2459 (target-extensible IR);
foundation already covered there is not redone here.

Signed-off-by: Will Madden <[email protected]>
- Promote function-level posture from open question to must-have:
  auth.uid(), auth.jwt(), auth.role() must be declarable as
  externally-managed in the Supabase contract so the verifier
  can resolve them in RLS predicates. Added FunctionDeclaration
  IR sketch and pg_proc verification note to posture.md.

- Promote example app (examples/supabase/) to must-have deliverable:
  the runnable end-to-end proof is the primary onboarding artifact.

- Add triggers/functions as stretch goal: the canonical "create
  profile on signup" pattern benefits from first-class IR but is
  not required for v0.1 (raw SQL migrations are the fallback).

- Collapse runtime to single supabase() facade (no baseDb):
  one factory, one returned object; asUser/asAnon/asServiceRole
  required before querying. Corrected serviceRoleKey to jwtSecret.

- Clarify RPC is not a gap (parity with status quo); CREATE
  EXTENSION already handled by existing pgvector extension.

Signed-off-by: Will Madden <[email protected]>
…ct refs

After discussing PSL and TS authoring with the architect and PE, this records the settled positions across both projects so implementers see one consistent design.

target-extensible-ir:
- Raise the PSL grammar into "At a glance" with a concrete example
- PSL: top-level `namespace { ... }` blocks; reopenable; namespaces do not recursively nest; backward-compatible default to `__unspecified__`
- Cross-namespace FKs: dot-qualified type references in `@relation`; no new attribute
- TS: zero new syntax for cross-namespace FKs (the model handle carries the namespace coordinate; existing `constraints.foreignKey` / `rel.belongsTo` call sites Just Work)
- Correct FR16: Postgres contracts default to `__unspecified__` (search_path resolves to `public` at the database level), not an explicit `public` namespace
- Tighten terminology: drop "nested namespace" framing, prefer "top-level namespace block"; lists recursive nesting as an explicit non-goal

supabase-integration:
- PSL: colon-prefixed dot-qualified cross-contract refs (`supabase:auth.User` in the type position); no `extension ... from "..."` directive in v0.1
- TS: unified surface — drop `refIn`. Cross-contract is inferred from the model handle’s brand; same `constraints.foreignKey` / `rel.belongsTo` call shape as local refs
- Implicit resolution via `extensionPacks`; commit publicly that any future `use ... as` form is purely additive aliasing
- Contract-space dependency graph: directional, acyclic, inferred from `extensionPacks`; reverse references are load-time errors
- Namespace ownership: namespaces are open for extension, primitives owned by their declaring contract; cross-contract name collisions are fail-fast load errors
- `__unspecified__` × cross-contract: emit unqualified REFERENCES, let `search_path` resolve at migration time (per-tenant FKs anchor by OID at constraint creation)
- Companion docs (overview, extension-package, developer-experience, README) updated to drop `refIn` and use the real `defineContract` DSL shape

Signed-off-by: Will Madden <[email protected]>
…tion

Adds projects/supabase-integration/example/ — a design-time TypeScript
sketch of the runnable example that will eventually live at examples/supabase/.
The code does not typecheck today; it is written against the design as it
stands in the surrounding notes.

Purpose:
- Forcing function. Writing the example against the design surfaces concrete
  design questions that topic-by-topic conversations would not have surfaced.
  Twenty are captured in design-holes.md, 10 of them marked blocking before
  this project can move to a spec.
- Spec anchor. AC1 for the eventual project spec becomes "this sketch
  typechecks against the live framework after milestones X / Y / Z ship."
- Onboarding artifact. At project close-out the directory migrates to
  examples/supabase/ and becomes the canonical onboarding sample.

Files:
- src/prisma/contract.ts — namespaces, cross-contract FK to auth.User,
  within-namespace FK Profile→Post, RLS policies on both tables, references
  auth.uid() as an externally-managed function.
- src/prisma/db.ts — supabase() facade with jwtSecret + middleware composition.
- src/handlers.ts — request handlers exercising asUser(jwt), asAnon(),
  asServiceRole(), plus multi-statement flows that force the transaction
  scoping story.
- migrations/supabase/contract.json + contract.d.ts — pinned mirror of the
  Supabase extension contract with externally-managed functions.
- prisma-next.config.ts — extensionPacks wiring.
- design-holes.md — every concrete decision the design did not yet cover,
  grouped by file and severity-tagged. The blocking holes are the canonical
  list of what the project spec must settle before execution begins.

The example will move into the project plan as the close-out deliverable and
the design-holes list becomes input for the next round of design work.

Signed-off-by: Will Madden <[email protected]>
Captures the design pass driven by the example-app forcing function:

- decisions.md: canonical decision log (A1-A7 TS authoring, B1-B6 PSL
  authoring, C1-C8 cross-cutting). Records the closes on holes #1, #2,
  #3, #4, #5, #15, #16, #17 and the elevation of roles/posture/extension
  structure to first-class concepts.

- design-holes.md: marks resolved holes against decisions, updates the
  blocking-holes summary table.

- rls.md: rewritten to the .rls([...]) array form (TS) and top-level
  policy <name> { key = value } blocks (PSL), with ref() helper semantics
  documented.

- overview.md: refreshed at-a-glance snippet, capability bullets, stretch
  goals to align with the array-of-descriptors RLS surface and the
  out-of-scope-for-v0.1 framing of functions-as-IR.

- example/src/prisma/contract.ts: rewritten to exercise the settled
  surface (composite uniques in .attributes(), .rls([...]) descriptor
  array, ref() helper for cross-model predicates, no capability flag).

- extension-package.md, posture.md, README.md: cross-reference updates
  pointing at decisions.md and reflecting the role IR + subpath
  entrypoint decisions.

Signed-off-by: Will Madden <[email protected]>
The (namespace.id, name) FK reference shape introduced by this project
is designed to extend additively to (spaceId, namespace.id, name) when
cross-contract refs land in a follow-up. Calls this out in FR16b and
in the Non-goals bullet so implementers do not fuse namespace.id + name
into a single composite key or bake single-contract-space assumptions
into the FK reference walk.

Signed-off-by: Will Madden <[email protected]>
Extract control-policy as its own project. It was originally shaped
inside projects/supabase-integration/posture.md but is a framework-level
primitive orthogonal to Supabase: a per-IR-node control field that
declares how much the framework control plane participates in an
objects migration lifecycle.

- ControlPolicy = managed | tolerated | external | observed
- Verifier dispatches per node on the four-value table
- Planner dispatches per node + cross-cutting safety check refusing
  to emit ops targeting an external namespace
- Naming follows the control-plane/runtime-plane axis already in
  the codebase. Field control on the wire, type ControlPolicy in
  signatures and prose.

Sequencing: blocked by TML-2459 (the verifier/planner SPIs are the
natural seam for the dispatch tables); blocks Supabase integration.

Linear: https://linear.app/prisma-company/issue/TML-2493
Signed-off-by: Will Madden <[email protected]>
…n project

The control-policy concept moved out of Supabase and into its own
project (projects/control-policy, TML-2493). Supabase consumes it,
does not introduce it.

Across all design notes:

- posture (field)            -> control (field)
- Posture (type/concept)     -> ControlPolicy (type)
- defaultPosture             -> defaultControl
- modeled                    -> managed
- externally-managed (value) -> external
- drift                      -> observed

Tolerated keeps its name.

Cross-references to projects/supabase-integration/posture.md now point
to projects/control-policy/spec.md. The posture.md file is deleted;
its content (rewritten in the new vocabulary and proper spec format)
landed in the previous commit as projects/control-policy/spec.md.

Also drops the functions block from the example contract artefacts
in line with decisions.md C4 (functions are not contract elements
in v0.1).

Signed-off-by: Will Madden <[email protected]>
Final pass before handing TML-2459 to the implementer.

Fixes three small handoff-readiness issues:

- Drop dangling "Open Question 1" reference in spec Cost section.
  The sequencing it pointed at is already resolved by the plan
  (M1 foundation, M2 Mongo, M3 Postgres + validateContract migration).

- Align stale m.constraints.ref(otherModel) prose in spec
  Approach section with the settled API in FR16b: existing
  constraints.foreignKey(cols.x, OtherModel.refs.y, ...) and
  rel.belongsTo(OtherModel, ...) reused; model handle carries
  the namespace coordinate; no new syntax.

- Mirror the same alignment in plan M5b authoring DSL tasks
  (TS + PSL).

Adds:

- Linear ticket link (TML-2459) in plan summary for handoff
  discoverability.

- Design-discipline note on M5b FK reference IR task: do not
  fuse namespace.id + name into a composite key so cross-contract
  refs can extend additively to (spaceId, namespace.id, name)
  in a follow-up project. Matches the extension-point contract
  added to spec FR16b in 9edbeef.

Signed-off-by: Will Madden <[email protected]>
Resolve the architectural questions raised during the pressure-test of TML-2459
before implementation begins:

- Drop the proposed Target<TContract, TSchema> aggregator interface in favour of
  extending the existing *ControlTargetDescriptor types with named SPI
  properties (contractSerializer, schemaVerifier) next to migrations.
- Introduce a framework SchemaNodeBase abstract class so SQL and Mongo IR nodes
  share the freeze-and-assign pattern already proven on OpFactoryCall and
  MongoSchemaNode.
- Pin Storage.namespaces: Record<string, Namespace> at the framework level so
  FR15 is enforced by the type system across every family.
- Strengthen ContractSerializer rationale: serializeContract returns JsonObject;
  the symmetric SPI is the named seam used by round-trip tests, drift detection,
  and future canonicalization.
- Keep todays SchemaIssue union as-is for this project; flag the layering
  observation as a forward concern rather than reshaping the type.
- Pin the __unspecified__ namespace as a target-specific singleton subclass
  (PostgresUnspecifiedSchema, etc.) that overrides qualifier emission, so call
  sites stay polymorphic instead of branching on id.
- Implement Mongo namespace semantics in M2 (database = namespace, default
  __unspecified__) so every family commits to the same Storage shape from the
  first consumer.
- Drop the M3a/M3b split possibility; Postgres and SQLite share family abstract
  bases and must flip together to satisfy NFR1.
- Add an M5a pre-flight task to audit PSL consumer cascade before lowering the
  grammar.
- Move the 3-layer-IR ADR draft into M1 (close-out at minimum is the
  convention; drafting earlier here is cheap context insurance).

Signed-off-by: Will Madden <[email protected]>
…dressed wire names

Settle the last blocking RLS design hole (#19 RLS verifier check
semantics) and three smaller working-assumption items.

Design choice: policy wire names carry an 8-hex SHA-256 suffix over the
canonical content tuple (using, withCheck, sort(roles), operation, as).
Predicate equivalence collapses to a name match; the verifier never
compares bodies for equivalence purposes. One body-level check remains
(the per-row tamper check that recomputes the suffix against the
introspected body).

Three structural wins:

- Predicate-equivalence false positives are eliminated by construction.
  Postgres-side expression-printer normalization (parens, whitespace,
  cast forms) no longer surfaces as policy_mismatch noise.
- Policy rename detection is structurally free (matching hash, different
  prefix → ALTER POLICY ... RENAME TO). Closes the earlier
  defer-and-ship-drop+create working assumption.
- No version marker needed; the contract storage hash already signals
  normalizer changes through VERIFY_CODE_HASH_MISMATCH (per ADR 004).

Pinned decisions:

- A8: TS as field, default permissive (mirrors PSL B2).
- C9: content-addressed policy wire names.
- C10: RLS verifier semantics built on C9 (rls_policy_renamed,
  rls_policy_tampered, rls_not_enabled issue kinds).
- C11: implicit ENABLE RLS via model-level rls: auto|enabled|disabled.
- OC4: content-addressed naming pattern as a future-project backport
  target for indexes, functions, views, check constraints.

Artifacts:

- New ADR draft at projects/supabase-integration/specs/ (promotes at
  close-out with assigned number).
- rls.md verifier section rewritten to the content-addressed model.
- design-holes.md #19 marked decided; verifier cluster closed.

Signed-off-by: Will Madden <[email protected]>
Closes design holes #7, #8, #11, #13, #14 with one architectural decision
(C12 in decisions.md): introduce the runtime target-layer class in v0.1
and have Supabase extend it.

The runtime layer was class-based but missing the target tier:
RuntimeCore (framework, abstract) <- SqlRuntimeImpl (sql family, internal).
This project lifts SqlRuntimeImpl -> SqlRuntime (exported), adds
PostgresRuntime (thin subclass, target-layer extension point), and lands
SupabaseRuntime as PostgresRuntime's subclass. SET LOCAL is issued by
SupabaseRuntime.execute() against the raw connection -- below the user
middleware chain, structurally non-bypassable. Implicit transaction
guarantees never-outlives-txn SET LOCAL state. JWT validation is eager
behind a uniformly async factory.

Mirrors TML-2459's three-layer IR pattern at the runtime axis. ~50 LOC
of framework refactor; rationale and implementation sketch in the new
ADR draft.

Signed-off-by: Will Madden <[email protected]>
Decisions C6 (subpath-only entrypoints) and C12 (subclass-based runtime
hierarchy) supersede earlier shapes that are still demonstrated across the
component docs. This sweep aligns every example, table description, and
prose reference with the canonical authoring + runtime surface:

- `supabase.contract<C>(json)` factory removed everywhere except the
  historical "closed by" notes in decisions.md / design-holes.md. Replaced
  with subpath imports from /contract.
- `supabase.pack()` callable replaced with value-imported `supabasePack`
  from /pack.
- `supabase.roles.*` rewritten as `supabaseRoles.*` with imports from
  /contract.
- `m.constraints.ref(otherModel)` stale syntax replaced with the settled
  `constraints.foreignKey()` / `rel.belongsTo()` API.
- Example app contract.ts and prisma-next.config.ts brought in line with
  the new import shapes.
- Per-doc Open Questions sections trimmed to remove items already closed
  by recent decisions; remaining entries are genuinely defaultable.
- design-holes #20 promoted from open to closed (C6 fully supersedes the
  earlier shorthand-vs-longhand framing).

No new decisions; this is housekeeping to make the docs internally
consistent ahead of the project spec/plan finalization pass.

Signed-off-by: Will Madden <[email protected]>
…projects

Split the Supabase integration umbrella into four framework-primitive
projects, each with its own spec and plan and its own Linear ticket:

- cross-contract-refs (TML-2500): FK references across contract-space
  boundaries; brand machinery; supabase:auth.User PSL grammar;
  dependency graph + namespace ownership.
- postgres-rls (TML-2501): RLS policies + Postgres roles as target-only
  IR; .rls(...) TS surface + policy <name> PSL surface;
  content-addressed wire names; verifier + planner.
- runtime-target-layer (TML-2502): export SqlRuntime; new
  PostgresRuntime extends SqlRuntime; protected withRawConnection
  below-middleware accessor; transaction primitive formalisation.
- extension-supabase (TML-2503): the user-facing
  @prisma-next/extension-supabase package + working example app
  (integration project; depends on all primitives).

The three middle-tier primitives can ship in parallel; extension-supabase
consumes all three. Together with target-extensible-ir (TML-2459) and
control-policy (TML-2493) they form the full dependency graph for the
May 18 launch.

projects/supabase-integration/ becomes an umbrella tracker. The umbrella
README, overview, and decisions log are kept and updated to point at the
new constituent specs. Three component design docs were migrated into
the constituent specs and removed:

- cross-contract-refs.md -> cross-contract-refs/spec.md
- rls.md -> postgres-rls/spec.md
- extension-package.md -> extension-supabase/spec.md

Two ADR drafts were moved alongside:

- specs/adr-content-addressed-policy-names.md -> postgres-rls/specs/
- specs/adr-runtime-target-layer.md -> runtime-target-layer/specs/

All stale cross-references across the umbrella docs and the design-hole
log were rewritten to point at the new locations.

Signed-off-by: Will Madden <[email protected]>
…esh-eyes readability

Restructure the ADR so a teammate without prior context can follow it:

- Lead with the decision (one paragraph + naming format).
- Follow with a worked example end-to-end: authored TS, IR shape after
  lowering, emitted CREATE POLICY, and verifier behavior under a rename.
- Build up the why via cast forms, outer parens, whitespace, keyword
  casing — concrete drift axes rather than a single parenthetical aside.
- Move the four rejected alternatives (verbatim, verbatim+normalizer,
  canonicalize-at-CREATE, JS-side parser) to the end so the reader is
  not loaded with rejected paths before the chosen one.
- Drop transient project state: Draft / promoted-at-close-out status,
  v0.1 framing, per-project decision pointers, Status notes section,
  OC4 / decisions-log cross-reference.
- Fold the redundant Future evolution and Consequences > Negative
  treatments of normalizer stability into a single section.
- Spell out the collision math (birthday paradox on 32 bits ~= 65k
  policies on the same table) rather than leaving the reader to do it.

Signed-off-by: Will Madden <[email protected]>
wmadden added 6 commits May 13, 2026 17:38
The commit-message template fenced block at lines 162-170 had no language
identifier, tripping markdownlint MD040. Tag it as text so the lint passes
and downstream renderers know not to attempt syntax highlighting.

Refs: PR #460 review (coderabbitai inline thread on .agents/skills/record-gotcha/SKILL.md).
Signed-off-by: Will Madden <[email protected]>
Mirror the TypeScript contract at projects/supabase-integration/example/src/prisma/contract.ts
in PSL form. Demonstrates the equivalent PSL surface across the four
framework primitives the umbrella project decomposes into:

- top-level namespace { ... } blocks
- cross-contract type references with the supabase:auth.User
  colon-prefixed syntax
- top-level policy <name> { ... } blocks for RLS, scoped to the
  surrounding namespace
- role identifiers (anon, authenticated) resolved against the
  supabase extensionPack

Function-form using/withCheck predicates from the TS surface
(({ ref }) => `... ${ref(Profile)} ...`) have no v0.1 PSL equivalent;
qualified table identifiers are hard-coded in the four posts_* policies
with an in-file comment pointing at the stretch goal for interpolation
tokens.

Signed-off-by: Will Madden <[email protected]>
PSL is the primary authoring surface; the at-a-glance sections in the
four project docs that show TS-first contract authoring now show PSL
first and TS second. Affected docs:

- cross-contract-refs/spec.md: PSL leads, then TS shows the equivalent
  cross-contract FK call shape.
- postgres-rls/spec.md: PSL leads with the namespace + model + policy
  blocks; TS follows and is now framed around its one differentiating
  capability (function-form using/withCheck with ref(modelHandle)
  interpolation).
- extension-supabase/spec.md: replaces the contract.ts code block with
  the equivalent schema.prisma; db.ts and handlers.ts stay TS (no PSL
  surface for runtime). A short note that the TS surface is parallel
  and the example app ships both forms.
- supabase-integration/overview.md: replaces contract.ts with PSL,
  updates prisma-next.config.ts to use prismaContract(...) instead of
  typescriptContract(...) for consistency; db.ts stays TS.

No other parts of the docs change. Three project docs left as-is on
purpose:

- control-policy/spec.md: at-a-glance shows the primitive (enum +
  dispatch table + JSON shape), not authoring DSL.
- runtime-target-layer/spec.md: at-a-glance shows runtime class
  hierarchy diagrams. Runtime classes are not authored in PSL.
- target-extensible-ir/spec.md: already leads with PSL in its
  authoring sub-section.

Signed-off-by: Will Madden <[email protected]>
Captures the position that emerged from the Supabase shaping pass:
PSL is the default authoring surface most users are expected to be
familiar with, and it is the more difficult surface for design work
(text-parser-bounded grammar; design pressure surfaces there first).
The TS authoring surface is a superset of PSL — it mirrors or
extends, never restricts. Design docs (project specs, ADRs,
architecture docs, package READMEs) should lead with PSL examples
and use TS examples only when the content is specifically about a
TS-only capability (model-handle brands, function-form predicates
with ref() interpolation, type-level inference). Runtime code stays
TS — the rule is about authoring surface examples, not runtime
usage.

Signed-off-by: Will Madden <[email protected]>
`prisma` is the language identifier registered with the highlighters
that render the docs (GitHub, VSCode, the docs site); `psl` is not
and renders as plain text everywhere. The mistake is easy to make
because the surface is colloquially called "PSL" in prose, but the
fence has to say `prisma`.

Replaces every ```psl fence on this branch with ```prisma (12
occurrences across 7 doc files, plus the live PR #460 body) and adds
a "Code fencing for PSL" section to the prefer-psl-in-design-docs
agent rule so this convention is documented going forward.

Signed-off-by: Will Madden <[email protected]>
…mespace examples

Profile.user → auth.User is conceptually 1:1: at most one Profile row
per User. Without @unique on userId the FK admits 1:n, which (a)
misrepresents the modeling intent the example is meant to illustrate
and (b) lets a row's userId be re-attached to another user — defeating
any RLS policy that keys off 'this row's userId is the calling user'.

Affects two spec examples:
- cross-contract-refs/spec.md — PSL Profile gains @unique; the TS
  parallel form gains a .attributes({ uniques: [...] }) stage matching
  the .relations / .attributes / .sql / .rls order used elsewhere on
  the branch. Adds a short note explaining why.
- target-extensible-ir/spec.md — the namespace example's Profile gains
  @unique on userId for the same reason; no RLS here, but the 1:1
  intent is the same.

PR #460 body has the same fix applied separately.

Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden merged commit 1dbdda1 into main May 13, 2026
15 checks passed
@wmadden
wmadden deleted the tml-2459-plan branch May 13, 2026 15:41
wmadden added a commit that referenced this pull request May 13, 2026
The commit-message template fenced block at lines 162-170 had no language
identifier, tripping markdownlint MD040. Tag it as text so the lint passes
and downstream renderers know not to attempt syntax highlighting.

Refs: PR #460 review (coderabbitai inline thread on .agents/skills/record-gotcha/SKILL.md).
Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
`prisma` is the language identifier registered with the highlighters
that render the docs (GitHub, VSCode, the docs site); `psl` is not
and renders as plain text everywhere. The mistake is easy to make
because the surface is colloquially called "PSL" in prose, but the
fence has to say `prisma`.

Replaces every ```psl fence on this branch with ```prisma (12
occurrences across 7 doc files, plus the live PR #460 body) and adds
a "Code fencing for PSL" section to the prefer-psl-in-design-docs
agent rule so this convention is documented going forward.

Signed-off-by: Will Madden <[email protected]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant