Skip to content

Config diagnostics by section, defineConfig version marker, ControlClient test double - #29936

Merged
wmadden-electric merged 13 commits into
mainfrom
config-diagnostics-marker-and-control-client-double
Aug 11, 2026
Merged

wmadden-electric merged 13 commits into
mainfrom
config-diagnostics-marker-and-control-client-double

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Refs the CLI-consolidation follow-ups tracked in projects/consolidate-clis/plan.md ("config loading returns diagnostics", "export a fixture-backed ControlClient test double"). Linear was unreachable in the authoring session; the ticket link will be added when the PR is retitled.

At a glance

// packages/1-framework/3-tooling/cli/src/utils/migration-command-scaffold.ts
const configResult = await loadConfigForSections(options.config, [
  'family',
  'target',
  'adapter',
  'driver',
  'extensions',
  'db',
  'contract',
]);
if (!configResult.ok) {
  return configResult;
}
const config = configResult.value;

Before this PR, loadConfig threw on the first problem it found, and ten commands (including db init and db update) let that throw escape to commander — a raw stack trace and exit 1. A config with a broken formatter section blocked db init even though db init never reads formatter.

Decision

This PR ships three deliverables:

  1. Config loading returns diagnostics instead of throwing. loadConfig now returns Result<{ config, diagnostics }, CliStructuredError>. Structural problems in an evaluated config become CONFIG.VALIDATION_FAILED diagnostics tagged with the config section they concern (meta.section, meta.field). A command fails (exit 2, rendering the diagnostic) only when a diagnostic concerns a section it reads; commands not touching that section proceed. A module that cannot be evaluated at all fails the load with the new registered code CONFIG.EVALUATION_FAILED.
  2. defineConfig stamps a config-format version marker. defineConfig no longer validates or throws; it normalizes and stamps a non-enumerable version marker. The loader rejects configs whose export was not created by the current defineConfig — plain object exports, spread copies, or a config produced by a different defineConfig (a classic Prisma 7 file once the unified filename lands) — with the new registered code CONFIG.VERSION_MARKER_MISSING. Fail-early; no best-effort reading of unmarked configs.
  3. A published fixture-backed ControlClient test double. createFixtureControlClient() at @prisma/orm-toolchain/cli/control-api/testing covers every ControlClient operation with realistic target-neutral fixtures (the framework domain is family-blind, so the defaults name no target), overridable per test, with call recording. It imports no driver or database code.

Reviewer notes

  • defineConfig stops throwing (config-types.ts). This is deliberate, not an oversight: a throw inside defineConfig happens at module-evaluation time, so every structural problem would surface as an all-commands-fail evaluation error and per-section diagnostics could never fire. All validation now lives in collectConfigIssues (config-validation.ts), which reports every problem instead of the first. The config-validation-and-normalization rulecard was rewritten to match.
  • The marker is read from c12's raw layer, not the merged config (load.ts). Verified empirically: c12's merge drops both non-enumerable properties and symbol keys, but result.layers[*].config is the raw module export and preserves them.
  • The largest diff is mechanical call-site rewiring — 21 production loadConfig call sites across CLI commands, control-api operations, the language server, the Vite plugin, and cli-telemetry, plus their test mocks. The files that carry the design are load.ts, config-validation.ts, config-types.ts, and the per-command section lists (each command declares exactly the sections it reads).
  • One behavioral test was inverted by design: test/integration/test/cli.emit-command.additional.test.ts previously asserted that a plain-object config without defineConfig still emitted (loader finalization). Under the accepted fail-early ruling, that fixture is now the negative case asserting CONFIG.VERSION_MARKER_MISSING.
  • loadConfigForFile had zero production call sites (language server uses findNearestConfigPathForFile + loadConfig); it was converted to the Result API rather than removed, since hosts are expected to pick it up.
  • Two pre-existing flakes reproduced during full-suite runs and were ruled out as unrelated: the issues-28192-pg-historical-dates timestamptz LMT-offset flake and init-journey/init-skill-distribution afterAll 5s hook timeouts under parallel load. All pass in isolation.

How it fits together

  1. Validation becomes a collector — collectConfigIssues (packages/1-framework/1-core/config/src/config-validation.ts) walks every section (family, target, adapter, driver, extensions, contract, migrations, formatter) and returns { section, field, message } issues instead of throwing on the first. The arktype checks that lived in defineConfig (formatter, migrations, contract source shapes) moved here as plain checks.
  2. defineConfig normalizes and stamps — it applies the contract-output default and stamps Symbol.for('prisma-next.config-format-version') (non-enumerable, value 1). The marker deliberately does not survive spreads: configs must export the defineConfig result directly, which is what lets the future unified host loader distinguish a Prisma Next prisma.config.ts from a classic Prisma 7 one by marker rather than misparse.
  3. The loader assembles the Result — load.ts maps evaluation failures to NotOk (CONFIG.FILE_NOT_FOUND, CONFIG.EVALUATION_FAILED, CONFIG.VERSION_MARKER_MISSING) and wraps collector issues as section-tagged CliStructuredError diagnostics inside Ok. Contract finalization is skipped when the contract section has diagnostics, so malformed values can't crash path resolution.
  4. Commands narrow to their sections — requireConfigSections fails with the first diagnostic concerning a required section; loadConfigForSections composes load + narrow for the common case. Every command's call site declares the sections it reads.
  5. The double closes the seam for hosts — fixture-client.ts implements ControlClient (compile-time conformance) over a ControlClientFixtures record; the new ./control-api/testing subpath on @internal/cli flows into @prisma/orm-toolchain/cli/control-api/testing automatically via the shell build.

Behavior changes & evidence

  • Config errors in ten previously-leaking commands (db init, db update, migrate, migration status/log/show/new/list/graph, migrate --show) now render the structured envelope and exit 2 instead of printing a stack trace and exiting 1. Implementation: migration-command-scaffold.ts, migration-graph.ts. Evidence: migration-cli.test.ts, pinned before/after --json envelopes in the verification notes below.
  • A marked config with a broken section only blocks commands that read that section: ref list --json succeeds against a config with no target, while migration list --json exits 2 with { code: "CONFIG.VALIDATION_FAILED", meta: { field: "target", section: "target" } }. Implementation: load.ts. Evidence: section-requirements.test.ts, load.test.ts.
  • A config file with a syntax error (or a module that throws) now reports CONFIG.EVALUATION_FAILED with the parser message in why, replacing the catch-all CLI.UNEXPECTED. Evidence: load.test.ts.
  • A config not created by defineConfig fails every command early with CONFIG.VERSION_MARKER_MISSING, whose fix text names defineConfig. Implementation: config-types.ts, load.ts. Evidence: define-config.test.ts, cli.emit-command.additional.test.ts.
  • Hosts can drive the control-api surface without a database: createFixtureControlClient({ dbInit: notOk({...}) }) overrides one operation while the rest keep realistic defaults, and client.calls records invocations. Implementation: fixture-client.ts. Evidence: fixture-client.test.ts, fixture-client.test-d.ts.
  • The error registry gained CONFIG.EVALUATION_FAILED and CONFIG.VERSION_MARKER_MISSING, and CONFIG.VALIDATION_FAILED now documents meta.field/meta.section: error-reference.md.

Compatibility / migration / risk

  • loadConfig / loadConfigForFile changed signature (throwing → Result). All in-repo consumers were converted; @internal/config-loader is internal-only, so there is no external break.
  • validateConfig was replaced by collectConfigIssues; configError and the internal config-errors.ts module were deleted (no external users).
  • Every tracked prisma-next.config.ts in the repo already routes through defineConfig (directly, via @internal/cli/config-types, or via facade wrappers), so marker enforcement required no fixture migrations outside dynamically-generated test configs.
  • cli-telemetry's best-effort config read intentionally does not enforce the marker — it only needs target/extensions and stays silent on any invalidity.

Testing performed

  • pnpm turbo build --filter=@internal/cli... plus a full pnpm build — green.
  • pnpm test, pnpm typecheck, pnpm lint in config, errors, config-loader, cli (120 files / 1433 tests), language-server, vite-plugin-contract-emit, cli-telemetry — all green.
  • pnpm test:packages — green on final HEAD.
  • pnpm test:integration — green except the two pre-existing flakes noted in reviewer notes (both pass in isolation); test/integration typecheck green.
  • pnpm run check:error-reference — all 273 codes listed. pnpm lint:deps, pnpm lint:rules:symlinks, pnpm lint:rules:footprint — green.
  • Pinned --json envelopes before/after against the built CLI for: missing config, invalid plain-object config, syntax-error config, and db init with a bad config (previously exit 1 + stack trace; now exit 2 + envelope).

Skill update

n/a — there is no packages/0-shared/skills/ tree in this revision; the user-facing deltas (new error codes, defineConfig marker requirement) are documented in docs/reference/error-reference.md and the rewritten config-validation-and-normalization rulecard.

Follow-ups

  • The next refactor lifts config loading out of @internal/config-loader into the calling context, leaving this package to evaluate file content passed in as a parameter. evaluateConfigModule-style separation inside load.ts was kept shallow deliberately.
  • The future unified host loader will use the version marker to claim prisma.config.ts; no Prisma-7-filename discovery ships in this repo.

Alternatives considered

  • Encode "config cannot be evaluated" as Ok with a section-less diagnostic and config: undefined — rejected: every call site would re-implement the same undefined-check; NotOk gives all 21 call sites one uniform early exit with identical semantics.
  • Keep defineConfig validating and throwing — rejected: module-evaluation-time throws collapse every structural problem into an all-commands-fail evaluation error, defeating section-scoped diagnostics.
  • Make the marker enumerable so it survives c12's merge — rejected: reading the raw c12 layer keeps the marker invisible to Object.keys/JSON while still surviving loading; enumerability would leak the marker into every config consumer.
  • Best-effort reading of unmarked configs — explicitly ruled out by the operator: unmarked configs fail early with CONFIG.VERSION_MARKER_MISSING so the future unified loader can distinguish config formats by marker rather than misparse.
  • A separate published package for the test double — rejected: a ./control-api/testing subpath on @internal/cli flows into @prisma/orm-toolchain automatically via the shell build (ADR 242) and keeps the double versioned in lockstep with the client interface it must conform to.

Checklist

  • All commits are signed off (git commit -s) per the DCO. The DCO status check will block merge if any commit is missing a Signed-off-by: trailer.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern.
  • Tests are updated.
  • The PR title is in TML-NNNN: <sentence-case title> form — pending: no Linear ticket was resolvable in the authoring session; will retitle once the ticket is named.

Summary by CodeRabbit

  • New Features
    • Added section-specific configuration loading with detailed, section-scoped diagnostics.
    • Added clear errors for configuration evaluation failures and missing version markers.
    • Added configuration format markers to detect unsupported or manually defined configurations.
    • Added a fixture-based control client for database-free testing.
  • Bug Fixes
    • Improved configuration errors with causes, paths, and actionable metadata.
    • Commands now validate only the configuration sections they use.
  • Documentation
    • Updated CLI guidance and error references for the new configuration workflow.

wmadden-electric and others added 2 commits August 9, 2026 13:30
…ion marker

Config loading no longer fails wholesale on the first structural problem.

- loadConfig now returns Result<{ config, diagnostics }, CliStructuredError>.
  Structural problems in an evaluated config become CONFIG.VALIDATION_FAILED
  diagnostics tagged with the config section they concern (meta.section,
  meta.field). Commands fail (exit 2, rendering the diagnostic) only when a
  diagnostic concerns a section they read, via requireConfigSections /
  loadConfigForSections; commands not touching that section proceed.
- A config module that cannot be evaluated at all fails the load with the
  new CONFIG.EVALUATION_FAILED (previously surfaced as CLI.UNEXPECTED).
- defineConfig stops validating and throwing: a throw there happens at
  module-evaluation time and would turn every structural problem into an
  all-commands-fail evaluation error. Validation moved to the loader via
  collectConfigIssues, which reports every problem instead of the first.
- defineConfig now normalizes and stamps a non-enumerable config-format
  version marker; the loader rejects configs that were not created by the
  current defineConfig with the new CONFIG.VERSION_MARKER_MISSING (fail
  early, no best-effort reading of unmarked configs). The marker is read
  from c12's raw layer because the c12 merge drops non-enumerable
  properties.
- All production call sites (CLI commands and operations, language server,
  Vite plugin, cli-telemetry) consume the new API. Ten commands that
  previously leaked config errors as unhandled throws (stack trace,
  exit 1) — including db init and db update — now render the structured
  envelope and exit 2.
- Error registry: CONFIG.EVALUATION_FAILED and CONFIG.VERSION_MARKER_MISSING
  added; CONFIG.VALIDATION_FAILED updated with the new meta shape and
  producing sites.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…sting

Adds createFixtureControlClient, a ControlClient double for host and
product tests: every operation resolves realistic postgres-flavored
fixture payloads without touching a database or driver, each fixture is
overridable per test, and every call is recorded for assertions.

The implementing class `implements ControlClient` and a type test asserts
the double stays in sync with the real client, so an interface change
fails compilation here. Published via the @internal/cli
./control-api/testing subpath, which the shell build maps to
@prisma/orm-toolchain/cli/control-api/testing automatically.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric requested a review from a team as a code owner August 9, 2026 11:34
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 0bbac857-d3e9-400c-981f-2f134b6c985e

📥 Commits

Reviewing files that changed from the base of the PR and between 8a4114b and 49c927c.

📒 Files selected for processing (2)
  • packages/1-framework/3-tooling/cli/src/control-api/testing/fixture-client.ts
  • packages/1-framework/3-tooling/cli/test/control-api/testing/fixture-client.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/1-framework/3-tooling/cli/test/control-api/testing/fixture-client.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/testing/fixture-client.ts

📝 Walkthrough

Walkthrough

The PR separates configuration normalization, validation, loading, and command requirements. It adds format-marker checks, section-scoped diagnostics, evaluation errors, result-based loading, and a fixture-backed control client for tests.

Changes

Configuration and loader flow

Layer / File(s) Summary
Configuration contracts and diagnostics
packages/1-framework/1-core/config/*, packages/1-framework/1-core/errors/*, docs/reference/error-reference.md
defineConfig now stamps a format marker without structural validation. collectConfigIssues returns section-tagged issues. New errors cover evaluation failures and missing markers.
Result-based loading
packages/1-framework/3-tooling/config-loader/*
The loader returns Result values, preserves diagnostics, and supports section-specific loading through loadConfigForSections and requireConfigSections.
CLI and tooling adoption
packages/1-framework/3-tooling/cli/*, language-server/*, vite-plugin-contract-emit/*, packages/1-framework/3-tooling/cli-telemetry/*
Commands and tooling request required sections and propagate loader failures.
Testing and public fixtures
packages/1-framework/3-tooling/*/test/*, packages/1-framework/3-tooling/cli/src/control-api/testing/*, test/integration/*, scripts/regen-example-migrations.mjs
Tests adopt result-shaped loader mocks and cover markers, diagnostics, section filtering, evaluation failures, and fixture-backed control-client operations.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the PR’s three primary changes: section-scoped config diagnostics, the defineConfig version marker, and the ControlClient test double.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch config-diagnostics-marker-and-control-client-double

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@pkg-pr-new

pkg-pr-new Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

prisma-next

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

@prisma/orm-extension-arktype-json

npm i https://pkg.pr.new/@prisma/orm-extension-arktype-json@29936

@prisma/orm-extension-middleware-cache

npm i https://pkg.pr.new/@prisma/orm-extension-middleware-cache@29936

@prisma/orm-extension-paradedb

npm i https://pkg.pr.new/@prisma/orm-extension-paradedb@29936

@prisma/orm-extension-pgvector

npm i https://pkg.pr.new/@prisma/orm-extension-pgvector@29936

@prisma/orm-extension-postgis

npm i https://pkg.pr.new/@prisma/orm-extension-postgis@29936

@prisma/orm-extension-supabase

npm i https://pkg.pr.new/@prisma/orm-extension-supabase@29936

@prisma/orm-family-mongo

npm i https://pkg.pr.new/@prisma/orm-family-mongo@29936

@prisma/orm-family-sql

npm i https://pkg.pr.new/@prisma/orm-family-sql@29936

@prisma/orm-framework

npm i https://pkg.pr.new/@prisma/orm-framework@29936

@prisma/orm-mongo

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

@prisma/orm-postgres

npm i https://pkg.pr.new/@prisma/orm-postgres@29936

@prisma/orm-sqlite

npm i https://pkg.pr.new/@prisma/orm-sqlite@29936

@prisma/orm-target-mongo

npm i https://pkg.pr.new/@prisma/orm-target-mongo@29936

@prisma/orm-target-postgres

npm i https://pkg.pr.new/@prisma/orm-target-postgres@29936

@prisma/orm-target-sqlite

npm i https://pkg.pr.new/@prisma/orm-target-sqlite@29936

@prisma/orm-toolchain

npm i https://pkg.pr.new/@prisma/orm-toolchain@29936

commit: 49c927c

@github-actions

github-actions Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size
postgres / no-emit 170.11 KB (0%)
postgres / emit 147.84 KB (-0.01% 🔽)
mongo / no-emit 100.41 KB (-0.01% 🔽)
mongo / emit 90.25 KB (0%)
cf-worker / no-emit 194.31 KB (0%)
cf-worker / emit 169.66 KB (+0.01% 🔺)

@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: 8

🧹 Nitpick comments (2)
packages/1-framework/1-core/config/test/define-config.test.ts (1)

140-149: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Make the marker-serialization assertion version independent.

Line 145 hardcodes '1'. The assertion passes for any version whose decimal form contains 1, and it fails when CONFIG_FORMAT_VERSION becomes 2. It also duplicates the version check already made on Line 129. Line 146 carries the real intent of this test.

♻️ Proposed change
     expect(Object.getOwnPropertyDescriptor(result, markerSymbol)?.enumerable).toBe(false);
-    expect(JSON.stringify({ marker: readConfigFormatVersion(result) })).toContain('1');
+    expect(JSON.stringify(result)).not.toContain('config-format-version');
     expect(JSON.stringify(defineConfig(createValidConfig({ contract: undefined })))).not.toContain(
       'config-format-version',
     );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/1-core/config/test/define-config.test.ts` around lines
140 - 149, Update the JSON serialization assertion in the test “keeps the marker
out of enumeration and JSON serialization” to avoid hardcoding the version
string or duplicating the format-version check; retain the symbol
non-enumerability assertion and keep line 146’s verification that the marker is
excluded from serialized config output.
packages/1-framework/1-core/config/src/config-types.ts (1)

168-176: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Consider stamping a copy instead of the caller's object.

Line 176 defines a non-configurable, non-writable property on the object the caller passed in. If a user passes a frozen or sealed object, Object.defineProperty throws a TypeError and the config fails to evaluate. CONFIG.EVALUATION_FAILED would then report a confusing cause. A shallow copy avoids the mutation and still preserves literal types.

♻️ Proposed change
-  // Return config as-is if no contract (preserve literal types)
-  return stampConfigFormatVersion(config);
+  return stampConfigFormatVersion({ ...config });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/1-core/config/src/config-types.ts` around lines 168 -
176, Update the no-contract path in the config evaluation flow to pass a shallow
copy of config into stampConfigFormatVersion instead of stamping the caller’s
object directly. Preserve literal types and the existing contract-normalization
path, while ensuring frozen or sealed caller objects remain unchanged and do not
cause Object.defineProperty to throw.
🤖 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/rules/config-validation-and-normalization.mdc:
- Around line 40-46: Update the “Default Path Resolution” example to demonstrate
the instructed pathe-based handling: import dirname and join, derive configDir
from configPath, and resolve the default or configured contract output through
join(configDir, ...), replacing the standalone string fallback.

In `@packages/1-framework/1-core/config/src/config-validation.ts`:
- Around line 42-46: Replace the bare Record casts in validateFamily,
validateTarget, and the adapter and driver branches of collectConfigIssues with
isObject narrowing. Ensure non-object sections such as family: 'sql' produce one
object-type issue and skip descriptor walks, while valid objects retain the
existing validation behavior.

In `@packages/1-framework/3-tooling/cli/src/commands/migrate.ts`:
- Around line 338-346: Update the loadConfigForSections call in the migration
command to include the contract section alongside the existing sections,
ensuring contract configuration is validated before the contract path is
resolved during migration execution.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 269-281: Add 'contract' to the section list passed by the
migration-status command’s loadConfigForSections call so contract validation
occurs during configuration loading. Preserve the existing configResult error
return and downstream uses by buildReadAggregate, readContractEnvelope, and
loadContractRawSafely.

In
`@packages/1-framework/3-tooling/cli/src/control-api/testing/fixture-client.ts`:
- Around line 227-299: Update the fixture client’s connection lifecycle: have
connect() initialize the underlying client via init() and track the
initialized/connected state, then make the database operation methods (including
verify, schemaVerify, sign, dbInit, dbUpdate, dbVerify, marker/ledger reads,
migrate, introspect, schema conversion, PSL inference, descriptor/preview
generation, and emit) reject calls made before connect(). Preserve the existing
fixture recording and return behavior after a successful connection.

In `@packages/1-framework/3-tooling/config-loader/src/load.ts`:
- Around line 136-145: Update the error classification in the load failure
handling block to use the Node error code rather than message substring checks.
In the Error branch, return errorConfigFileNotFound only for the missing-file
code (such as ENOENT), while keeping ERR_MODULE_NOT_FOUND and other errors on
errorConfigEvaluationFailed with the existing details.
- Around line 187-194: Update the marker validation around markerCarrier so it
examines only the layer whose configFile matches result.configFile, rather than
accepting markers from extends or rc layers; require the current format marker
on that primary layer and preserve the existing CONFIG.VERSION_MARKER_MISSING
return when it is absent.

In `@packages/1-framework/3-tooling/language-server/src/config-resolution.ts`:
- Around line 30-44: Update resolveConfigInputs() so the TypeScript
contract-project branch loads only the contract section before resolving
contract.source.inputs, allowing invalid unrelated control sections to be
ignored; retain loading family, target, adapter, driver, and extensions for the
PSL branch. Add a regression test covering a TypeScript contract source with an
invalid control section and asserting resolution proceeds with the contract
inputs.

---

Nitpick comments:
In `@packages/1-framework/1-core/config/src/config-types.ts`:
- Around line 168-176: Update the no-contract path in the config evaluation flow
to pass a shallow copy of config into stampConfigFormatVersion instead of
stamping the caller’s object directly. Preserve literal types and the existing
contract-normalization path, while ensuring frozen or sealed caller objects
remain unchanged and do not cause Object.defineProperty to throw.

In `@packages/1-framework/1-core/config/test/define-config.test.ts`:
- Around line 140-149: Update the JSON serialization assertion in the test
“keeps the marker out of enumeration and JSON serialization” to avoid hardcoding
the version string or duplicating the format-version check; retain the symbol
non-enumerability assertion and keep line 146’s verification that the marker is
excluded from serialized config output.
🪄 Autofix

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 Plus

Run ID: 2cd6330c-4856-4528-ba6e-77561f938d14

📥 Commits

Reviewing files that changed from the base of the PR and between 92b6ee3 and 6bf68c1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (89)
  • .agents/rules/config-validation-and-normalization.mdc
  • docs/reference/error-reference.md
  • packages/1-framework/1-core/config/src/config-errors.ts
  • packages/1-framework/1-core/config/src/config-types.ts
  • packages/1-framework/1-core/config/src/config-validation.ts
  • packages/1-framework/1-core/config/src/exports/config-types.ts
  • packages/1-framework/1-core/config/src/exports/config-validation.ts
  • packages/1-framework/1-core/config/test/config-validation.test.ts
  • packages/1-framework/1-core/config/test/define-config.test.ts
  • packages/1-framework/1-core/errors/src/control.ts
  • packages/1-framework/1-core/errors/src/exports/control.ts
  • packages/1-framework/1-core/errors/test/control.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/enrich.ts
  • packages/1-framework/3-tooling/cli/README.md
  • packages/1-framework/3-tooling/cli/package.json
  • packages/1-framework/3-tooling/cli/src/commands/contract-emit.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-sign.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-verify.ts
  • packages/1-framework/3-tooling/cli/src/commands/inspect-live-schema.ts
  • packages/1-framework/3-tooling/cli/src/commands/migrate.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-list.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-log.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-show.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/format.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref.ts
  • packages/1-framework/3-tooling/cli/src/control-api/testing/fixture-client.ts
  • packages/1-framework/3-tooling/cli/src/exports/control-api-testing.ts
  • packages/1-framework/3-tooling/cli/src/migration-cli.ts
  • packages/1-framework/3-tooling/cli/src/utils/framework-components.ts
  • packages/1-framework/3-tooling/cli/src/utils/migration-command-scaffold.ts
  • packages/1-framework/3-tooling/cli/test/commands/contract-emit.command.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/contract-infer.command.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/cross-consumer-integrity.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/db-schema.command.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/db-update-read-aggregate-json-golden.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/inspect-live-schema.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migrate-show.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migrate-to-contract.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-multi-space-command.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-path-target.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-ref-error.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-single-target-multi-space.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-graph.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-invariants.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-legend-commands.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-list-json-golden.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-log.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-command.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref-error-mapping.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-show.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-status-missing-db.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-tamper.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/read-commands-json-golden.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/ref.test.ts
  • packages/1-framework/3-tooling/cli/test/config-types.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-emit.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/format.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migrate-show-plan.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migration-plan-prologue.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/testing/fixture-client.test-d.ts
  • packages/1-framework/3-tooling/cli/test/control-api/testing/fixture-client.test.ts
  • packages/1-framework/3-tooling/cli/test/migration-cli.test.ts
  • packages/1-framework/3-tooling/cli/tsdown.config.ts
  • packages/1-framework/3-tooling/config-loader/src/exports/index.ts
  • packages/1-framework/3-tooling/config-loader/src/load.ts
  • packages/1-framework/3-tooling/config-loader/test/load.test.ts
  • packages/1-framework/3-tooling/config-loader/test/section-requirements.test.ts
  • packages/1-framework/3-tooling/config-loader/test/to-structured-config-error.test.ts
  • packages/1-framework/3-tooling/language-server/src/config-resolution.ts
  • packages/1-framework/3-tooling/language-server/test/config-resolution.test.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/package.json
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.ts
  • packages/1-framework/3-tooling/vite-plugin-contract-emit/test/plugin.test.ts
  • packages/9-public/@prisma/orm-toolchain/package.json
  • test/integration/test/authoring/cli.emit-parity-fixtures.test.ts
  • test/integration/test/cli.db-verify.e2e.test.ts
  • test/integration/test/cli.emit-command.additional.test.ts
  • test/integration/test/cli.emit-contract.test.ts
  • test/integration/test/fixtures/cli/cli-integration-test-app/fixtures/emit-command/prisma-next.config.missing-output.ts
💤 Files with no reviewable changes (2)
  • packages/1-framework/1-core/config/src/config-errors.ts
  • packages/1-framework/3-tooling/config-loader/test/to-structured-config-error.test.ts

wmadden-electric and others added 5 commits August 11, 2026 08:39
The framework domain is family-blind, and `lint:framework-vocabulary`
counted seven new SQL/target-vocabulary lines: six in the fixture
ControlClient defaults and one in the `CONFIG.VERSION_MARKER_MISSING`
fix text.

The fixture defaults now report neutral `FIXTURE_TARGET_ID` /
`FIXTURE_FAMILY_ID` ids (both exported so tests can assert them), an
operation label that names the model rather than the DDL, and an empty
introspection payload. The marker error points at the target package
config entrypoint without naming a target; the error reference keeps the
concrete example.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The example-migration regen writes a temporary config that spreads the
example's real config. The version marker is non-enumerable, so the
spread dropped it and every emit failed with
CONFIG.VERSION_MARKER_MISSING. Passing the spread result through
defineConfig re-stamps it.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…tion

src/load.ts sat below the package coverage thresholds: loadConfigForSections
had no test at all, and none of the toConfigLoadFailure arms were exercised
beyond the plain-Error case.

Adds tests for loadConfigForSections (clean, blocking diagnostic, and load
failure), for a config module that throws a CliStructuredError, a plain
structured error, a non-Error value, or fails to resolve an import, and for
a contract that declares no inputs.

finalizeConfig grew a finalizeContractConfig half that takes a contract
section directly, so the loader no longer re-checks a contract it has
already narrowed.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
`lint:legacy-name` rejects `prisma-next` outside the allowed uses, and the
unresolvable-import test used it in a made-up package name. Any
unresolvable specifier works.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 5 commits August 11, 2026 16:49
The four `as Record<string, unknown>` casts in `config-validation.ts` broke
the repo rule against bare `as` in production code, and they also hid a
reporting wart: a section holding a non-object (`family: 'sql'`) walked the
descriptor fields anyway and produced one issue per missing field instead
of one clear "must be an object" issue.

`isObject` already narrows to `Record<string, unknown>` without a cast, so
`validateFamily`, `validateTarget`, and the `adapter`/`driver` walks now
use it and report a single object-type issue per malformed section.

Also rewrites the rulecard's "Default Path Resolution" example, which told
authors to use `pathe` but then showed only a bare string fallback. It now
shows what the loader actually does: resolve the config-relative default
against the config file's directory.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Two defects in `loadConfig`, both reported against the wrong file.

First, load failures were classified by searching the error message for
'not found', 'Cannot find' or 'ENOENT'. A config that imports a missing
package throws `Cannot find module 'x'`, so the user was told their config
file did not exist when it did. Verified against c12: a missing config
file never throws — c12 resolves nothing and returns an empty config,
which `loadConfig` already maps to CONFIG.FILE_NOT_FOUND on the
non-throwing path. So everything reaching this catch came from evaluating
a file that exists, and all of it is now CONFIG.EVALUATION_FAILED.

Second, the version-marker check accepted the marker from any c12 layer,
including `extends` bases and rc files. A config that does not itself go
through `defineConfig` passed as long as some base did. c12 puts the
requested config file first in `layers` (we pass no `overrides`), so the
check now reads only that layer.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
A command that reads a section it did not declare bypasses section-scoped
diagnostics: the malformed value flows into execution and fails later as
something else. `migration status` turned a malformed `contract` section
into a CONTRACT.UNREADABLE warning; `migrate` failed while resolving the
contract path.

Swept all 21 `loadConfigForSections` call sites against the sections each
one reads, directly or through a helper (`resolveContractPath`,
`readContractEnvelope`, `loadContractRawSafely`, `buildReadAggregate`,
`loadAggregateIntegrityViolations` read `contract`; `resolveMigrationPaths`
reads `migrations`). Eleven were short:

- `contract` added to migrate, migration status, migration list,
  migration graph, migration check, migration ref set, migrate --show
- `migrations` added to migration log, db sign, db verify, and the shared
  migration-command scaffold (db init, db update)

`driver` is deliberately not added to the read-only commands that build a
control stack. `createControlStack` stores the descriptor but only
database operations use it, and every command that connects already
declares `driver`; requiring it everywhere would defeat section scoping.

The regression test lives in the integration suite rather than the CLI
package: the CLI suite runs with `isolate: false`, so a new file importing
command modules collides with the per-file `@internal/config-loader` mocks
its neighbours already register. The integration test drives the real
commands against a real malformed config and covers the command handlers
that are module-private.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ycle

The double served every operation from fixtures whether or not `connect()`
had been awaited, so a caller that forgot to connect passed its tests and
then failed against the real client.

It now tracks initialization the way `ControlClientImpl` does: `init()` is
idempotent, `connect()` calls it, and the eleven operations the real
client routes through `ensureConnected` (verify, schemaVerify, sign,
dbInit, dbUpdate, dbVerify, readMarker, readAllMarkers, readLedger,
migrate, introspect) reject with DRIVER.NOT_CONNECTED while disconnected.
The five that only need `init()` in the real client (toSchemaView,
inferPslContract, getPslBlockDescriptors, toOperationPreview, emit) keep
working without a connection.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…s from

`resolveConfigInputs` required family, target, adapter, driver and
extensions before it knew whether the project was PSL or TypeScript. A
TypeScript contract project derives its inputs from `contract.source`
alone and never builds a control stack, so a diagnostic on an unrelated
control section stopped formatting and analysis for it.

It now loads once and narrows twice: `contract` and `formatter` for every
project, and the control sections only on the PSL branch that actually
assembles the stack.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>

@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: 1

🧹 Nitpick comments (1)
test/integration/test/cli.config-section-requirements.test.ts (1)

110-134: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add unrelated-section regression cases.

These cases prove that commands reject malformed sections they read. They do not prove that commands ignore malformed sections they do not read. A command can require every section and still pass this suite.

Add inverse cases. For example, verify that a contract-only command proceeds past malformed migrations, and that migration log proceeds past malformed contract.

🤖 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 `@test/integration/test/cli.config-section-requirements.test.ts` around lines
110 - 134, Add inverse regression cases alongside the existing readsContract and
readsMigrations tests: verify a contract-only command succeeds with
brokenMigrationsConfig, and migration log succeeds with brokenContractConfig.
Reuse the existing command factories, envelopeFor helper, malformed configs, and
expected successful envelope assertions to confirm unread sections are ignored.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/1-framework/3-tooling/cli/src/control-api/testing/fixture-client.ts`:
- Around line 237-244: Update recordConnected and the affected operation methods
around it to inspect options.connection before rejecting for a disconnected
client, connect using that supplied connection, then record and return the
fixture result. Preserve the existing not-connected error when no
operation-level connection is provided, and add coverage for an affected
operation invoked with connection options without a prior connect() call.

---

Nitpick comments:
In `@test/integration/test/cli.config-section-requirements.test.ts`:
- Around line 110-134: Add inverse regression cases alongside the existing
readsContract and readsMigrations tests: verify a contract-only command succeeds
with brokenMigrationsConfig, and migration log succeeds with
brokenContractConfig. Reuse the existing command factories, envelopeFor helper,
malformed configs, and expected successful envelope assertions to confirm unread
sections are ignored.
🪄 Autofix

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 Plus

Run ID: d9345b2d-a1ea-4960-9d70-936057cc1f58

📥 Commits

Reviewing files that changed from the base of the PR and between 3d03d74 and 8a4114b.

📒 Files selected for processing (22)
  • .agents/rules/config-validation-and-normalization.mdc
  • packages/1-framework/1-core/config/src/config-validation.ts
  • packages/1-framework/1-core/config/test/config-validation.test.ts
  • packages/1-framework/3-tooling/cli/README.md
  • packages/1-framework/3-tooling/cli/src/commands/db-sign.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-verify.ts
  • packages/1-framework/3-tooling/cli/src/commands/migrate.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-list.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-log.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref.ts
  • packages/1-framework/3-tooling/cli/src/control-api/testing/fixture-client.ts
  • packages/1-framework/3-tooling/cli/src/utils/migration-command-scaffold.ts
  • packages/1-framework/3-tooling/cli/test/control-api/testing/fixture-client.test.ts
  • packages/1-framework/3-tooling/config-loader/src/load.ts
  • packages/1-framework/3-tooling/config-loader/test/load.test.ts
  • packages/1-framework/3-tooling/language-server/src/config-resolution.ts
  • packages/1-framework/3-tooling/language-server/test/config-resolution.test.ts
  • test/integration/test/cli.config-section-requirements.test.ts
🚧 Files skipped from review as they are similar to previous changes (15)
  • packages/1-framework/3-tooling/cli/src/commands/migration-list.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-log.ts
  • packages/1-framework/3-tooling/cli/test/control-api/testing/fixture-client.test.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-sign.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-verify.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref.ts
  • packages/1-framework/3-tooling/cli/src/utils/migration-command-scaffold.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-check.ts
  • packages/1-framework/3-tooling/cli/README.md
  • packages/1-framework/1-core/config/src/config-validation.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/commands/migrate.ts
  • packages/1-framework/3-tooling/config-loader/src/load.ts

The real client connects from options.connection before it checks for
a driver, so an operation that supplies one needs no prior connect().
The double rejected first, failing calls production accepts.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric added this pull request to the merge queue Aug 11, 2026
Merged via the queue into main with commit 15308c6 Aug 11, 2026
16 of 17 checks passed
@wmadden-electric
wmadden-electric deleted the config-diagnostics-marker-and-control-client-double branch August 11, 2026 16:04
wmadden-electric added a commit that referenced this pull request Aug 11, 2026
Every conflict is the same shape: main carries the squash-merged #29936 work,
this branch carries the same work plus the port's refactor on top, so ours is
strictly newer on every conflicted file. Verified that main and the #29936
branch tip are byte-identical across the CLI, config, config-loader and
integration paths before resolving in favour of ours.

Three things the merge could not settle on its own:

- `config-loader/src/load.ts` keeps the three `/* v8 ignore */` annotations.
  Main does not have them, and without them `src/load.ts` drops to 94% branch
  coverage. Also keeps the port's `cwd` option on `loadConfig`.
- `executeRefDeleteCommand` had main's `loadConfigForSections(options.config,
  ...)` left behind by a clean auto-merge, where `options.config` is now a
  loaded config object rather than a path. Dropped it; the caller loads.
- Three test files kept an `ok` import that only main's config-loader mock
  used.

The lockfile takes main's wholesale, then `pnpm install` re-adds the
`@prisma/cli-engine` pin.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Thegreatsura pushed a commit to Thegreatsura/prisma that referenced this pull request Aug 14, 2026
## Linked issue

n/a — operator bug report (no ticket). `npx @prisma/cli@next init` fails
at the emit step on a freshly scaffolded project.

## At a glance

```
▸ Emit the contract
✘ Emit the contract
✘ [CLI.INIT_EMIT_FAILED] Failed to emit contract
  why: `prisma-next contract emit` failed: Config is not a defineConfig result
```

That is what every `init` run against the published packages produced
(reproduced with `@prisma/[email protected]` on 2026-08-13). With this PR,
the emit step runs the scaffolded project's own CLI, and the same
scenario completes with `contractEmitted: true`.

## Decision

`init`'s contract-emit step now runs the **project-local `@prisma/cli`
binary** that `init` itself just installed, as a captured subprocess —
instead of loading the scaffolded config in-process with the running
CLI's bundled config-loader. Two smaller fixes ride along:

1. The schema-path prompt shows its default as placeholder text
(previously the prompt looked blank until a keypress).
2. `init`'s failure message for a failed emit now carries the redacted
tail of the child's stderr, so the real cause is visible.

## How it fits together

1. The scaffolded config's `defineConfig` imports come from the packages
`init` installs from the registry (`@prisma/cli-engine` for the outer
config, the ORM facade for the `orm` section). Since prisma#29936,
`defineConfig` stamps a config-format version marker and the config
loader rejects configs without it.
2. `init` used to evaluate that config **in-process**, so the marker was
checked by the *running CLI's* bundled loader against a marker stamped
by the *project's installed* `defineConfig`. Any skew between the two
turns a perfectly good scaffold into `CONFIG.VERSION_MARKER_MISSING`.
The skew is real: npm's `@prisma/[email protected]` was built five days
after (and from a much newer commit than) the `8.0.0-rc.1` ORM packages,
so the CLI checked a marker the installed `defineConfig` never wrote.
3.
[init-emit.ts](packages/1-framework/3-tooling/cli/src/orm/init-emit.ts)
now resolves the scaffolded project's `@prisma/cli` package with
`createRequire` from the scaffold directory (same pattern as the
`--probe-db` driver resolution), reads its `prisma-cli` bin entry, and
spawns `process.execPath <bin> contract emit` in the project. Loader and
`defineConfig` now always come from the same installed release, so the
marker check cannot skew.
4. Prompt fix:
[init-inputs.ts](packages/1-framework/3-tooling/cli/src/orm/init-inputs.ts)
passes `placeholder` alongside `default`, so the engine renders the
default as ghost text and an empty submit accepts it.

## Reviewer notes

- Child stdio is captured (`['ignore','pipe','pipe']`), never inherited,
so `--json` envelopes on stdout stay parseable; the child is spawned on
`process.execPath` with the resolved bin script (no `node_modules/.bin`
shims, Windows-safe), and failure text passes through `redactSecrets`
before entering the structured error (connection strings can appear in
emit output).
- Resolving via the `@prisma/cli` package manifest (not `.bin`) keeps
the resolution unambiguous regardless of what bins other installed
packages declare.
- `emitScaffoldedContract` gained an optional test-only
`resolveFromBaseDir` seam: vitest wraps `createRequire` so
registry-resolution failures cannot be produced under the runner (a
plain `node` process fails correctly). Same precedent as `probe-db.ts`'s
`requireFromBaseDir`.
- A side effect worth knowing: the scaffolded project's module graph
(dotenv, target package, driver) no longer executes inside the CLI
process. This also removes the lingering-handle behaviour observed in
the original report, where the CLI did not exit after the failed emit.
- Deliberately out of scope: pinning the scaffold's dependency versions
to the CLI's baked version (the outer `@prisma/cli` reuses version
strings across different builds, so a pin can resolve to the wrong
artifact), any change to the marker-check semantics, and the
publish-cadence skew between `@prisma/cli` and this repo's packages
(different repo; that skew is what shipped the bug).

## Testing performed

- Package gates in `packages/1-framework/3-tooling/cli`: `pnpm
typecheck`, `pnpm test`, `pnpm build`, `pnpm lint`; repo-root `pnpm
lint:deps`; e2e workspace `pnpm typecheck` + full `pnpm test` (21 files,
115 tests).
- New unit tests:
[init-emit.test.ts](packages/1-framework/3-tooling/cli/test/orm/init-emit.test.ts)
(spawn args/cwd against a fixture project with a fake `@prisma/cli`,
stderr-tail + redaction on failure, stdout fallback, signal-kill
message, not-installed, no-bin, string-form bin, corrupt manifest) and
[init-inputs.test.ts](packages/1-framework/3-tooling/cli/test/orm/init-inputs.test.ts)
(placeholder + default).
- **E2E regression proof**:
[init-emit-subprocess.test.ts](test/e2e/framework/test/init-emit-subprocess.test.ts)
runs the real built CLI's `init` in a temp project pre-seeded with a
fake project-local `@prisma/cli` whose bin records its invocation. It
asserts the emit ran the project-local bin (`contract emit`, correct
cwd, `contractEmitted: true`) and that a failing child surfaces
`CLI.INIT_EMIT_FAILED` with the child's stderr and exit code. Reverting
to in-process emit makes both cases fail (verified by simulating the
revert).
- Manual end-to-end: ran the built CLI's `init --target postgres
--authoring typescript` in a fresh directory against the **published**
registry packages (the exact failing scenario) — exit 0,
`contractEmitted: true`, clean process exit.

## Skill update

n/a — no user-facing surface changes (same commands, flags, and error
codes; the emit step's failure text now carries the child's stderr
tail).

## Alternatives considered

- **Pin the installed packages to the CLI's own version.** Rejected: the
outer `@prisma/cli` is published from a different repo and has reused
the `8.0.0-rc.1` version string for a build five days newer than this
repo's `8.0.0-rc.1` packages, so a pin derived from the baked version
can resolve to the wrong (older) artifact and reintroduce the same
failure.
- **Relax the version-marker check.** Rejected: a config stamped by a
pre-marker `defineConfig` is indistinguishable from a plain object or a
classic-Prisma config, which is exactly what the check exists to reject.

## Checklist

- [x] All commits are signed off (`git commit -s`) per the
[DCO](../CONTRIBUTING.md#developer-certificate-of-origin-dco). The DCO
status check will block merge if any commit is missing a
`Signed-off-by:` trailer.
- [x] I read [CONTRIBUTING.md](../CONTRIBUTING.md) and the change is
scoped to one logical concern.
- [x] Tests are updated (or `n/a` if the change is doc-only / refactor
with no behavioural delta).
- [ ] The PR title is in `TML-NNNN: <sentence-case title>` form — no
Linear ticket exists for this operator-reported bug; title is
descriptive instead.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* ORM initialization now runs contract generation using the project’s
local Prisma CLI.
* Improved diagnostics report actionable details when contract
generation fails.
  * Schema prompts now show authoring-specific default paths.

* **Bug Fixes**
* Improved handling of CLI output, errors, exit codes, signals, and
credential redaction.

* **Tests**
* Added coverage for successful generation, failures, schema defaults,
and local CLI setup.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants