Repository navigation
Config diagnostics by section, defineConfig version marker, ControlClient test double - #29936
Conversation
…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]>
|
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughThe 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. ChangesConfiguration and loader flow
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
prisma-next
@prisma/orm-extension-arktype-json
@prisma/orm-extension-middleware-cache
@prisma/orm-extension-paradedb
@prisma/orm-extension-pgvector
@prisma/orm-extension-postgis
@prisma/orm-extension-supabase
@prisma/orm-family-mongo
@prisma/orm-family-sql
@prisma/orm-framework
@prisma/orm-mongo
@prisma/orm-postgres
@prisma/orm-sqlite
@prisma/orm-target-mongo
@prisma/orm-target-postgres
@prisma/orm-target-sqlite
@prisma/orm-toolchain
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
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 valueMake the marker-serialization assertion version independent.
Line 145 hardcodes
'1'. The assertion passes for any version whose decimal form contains1, and it fails whenCONFIG_FORMAT_VERSIONbecomes2. 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 valueConsider 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.definePropertythrows aTypeErrorand the config fails to evaluate.CONFIG.EVALUATION_FAILEDwould 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
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (89)
.agents/rules/config-validation-and-normalization.mdcdocs/reference/error-reference.mdpackages/1-framework/1-core/config/src/config-errors.tspackages/1-framework/1-core/config/src/config-types.tspackages/1-framework/1-core/config/src/config-validation.tspackages/1-framework/1-core/config/src/exports/config-types.tspackages/1-framework/1-core/config/src/exports/config-validation.tspackages/1-framework/1-core/config/test/config-validation.test.tspackages/1-framework/1-core/config/test/define-config.test.tspackages/1-framework/1-core/errors/src/control.tspackages/1-framework/1-core/errors/src/exports/control.tspackages/1-framework/1-core/errors/test/control.test.tspackages/1-framework/3-tooling/cli-telemetry/src/enrich.tspackages/1-framework/3-tooling/cli/README.mdpackages/1-framework/3-tooling/cli/package.jsonpackages/1-framework/3-tooling/cli/src/commands/contract-emit.tspackages/1-framework/3-tooling/cli/src/commands/db-sign.tspackages/1-framework/3-tooling/cli/src/commands/db-verify.tspackages/1-framework/3-tooling/cli/src/commands/inspect-live-schema.tspackages/1-framework/3-tooling/cli/src/commands/migrate.tspackages/1-framework/3-tooling/cli/src/commands/migration-check.tspackages/1-framework/3-tooling/cli/src/commands/migration-graph.tspackages/1-framework/3-tooling/cli/src/commands/migration-list.tspackages/1-framework/3-tooling/cli/src/commands/migration-log.tspackages/1-framework/3-tooling/cli/src/commands/migration-show.tspackages/1-framework/3-tooling/cli/src/commands/migration-status.tspackages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.tspackages/1-framework/3-tooling/cli/src/control-api/operations/format.tspackages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.tspackages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.tspackages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.tspackages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.tspackages/1-framework/3-tooling/cli/src/control-api/operations/ref.tspackages/1-framework/3-tooling/cli/src/control-api/testing/fixture-client.tspackages/1-framework/3-tooling/cli/src/exports/control-api-testing.tspackages/1-framework/3-tooling/cli/src/migration-cli.tspackages/1-framework/3-tooling/cli/src/utils/framework-components.tspackages/1-framework/3-tooling/cli/src/utils/migration-command-scaffold.tspackages/1-framework/3-tooling/cli/test/commands/contract-emit.command.test.tspackages/1-framework/3-tooling/cli/test/commands/contract-infer.command.test.tspackages/1-framework/3-tooling/cli/test/commands/cross-consumer-integrity.test.tspackages/1-framework/3-tooling/cli/test/commands/db-schema.command.test.tspackages/1-framework/3-tooling/cli/test/commands/db-update-read-aggregate-json-golden.test.tspackages/1-framework/3-tooling/cli/test/commands/inspect-live-schema.test.tspackages/1-framework/3-tooling/cli/test/commands/migrate-show.test.tspackages/1-framework/3-tooling/cli/test/commands/migrate-to-contract.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-check-multi-space-command.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-check-path-target.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-check-ref-error.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-check-single-target-multi-space.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-graph.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-invariants.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-legend-commands.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-list-json-golden.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-log.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-plan-command.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-ref-error-mapping.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-show.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-status-missing-db.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-status.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-tamper.test.tspackages/1-framework/3-tooling/cli/test/commands/read-commands-json-golden.test.tspackages/1-framework/3-tooling/cli/test/commands/ref.test.tspackages/1-framework/3-tooling/cli/test/config-types.test.tspackages/1-framework/3-tooling/cli/test/control-api/contract-emit.test.tspackages/1-framework/3-tooling/cli/test/control-api/format.test.tspackages/1-framework/3-tooling/cli/test/control-api/migrate-show-plan.test.tspackages/1-framework/3-tooling/cli/test/control-api/migration-plan-prologue.test.tspackages/1-framework/3-tooling/cli/test/control-api/testing/fixture-client.test-d.tspackages/1-framework/3-tooling/cli/test/control-api/testing/fixture-client.test.tspackages/1-framework/3-tooling/cli/test/migration-cli.test.tspackages/1-framework/3-tooling/cli/tsdown.config.tspackages/1-framework/3-tooling/config-loader/src/exports/index.tspackages/1-framework/3-tooling/config-loader/src/load.tspackages/1-framework/3-tooling/config-loader/test/load.test.tspackages/1-framework/3-tooling/config-loader/test/section-requirements.test.tspackages/1-framework/3-tooling/config-loader/test/to-structured-config-error.test.tspackages/1-framework/3-tooling/language-server/src/config-resolution.tspackages/1-framework/3-tooling/language-server/test/config-resolution.test.tspackages/1-framework/3-tooling/vite-plugin-contract-emit/package.jsonpackages/1-framework/3-tooling/vite-plugin-contract-emit/src/plugin.tspackages/1-framework/3-tooling/vite-plugin-contract-emit/test/plugin.test.tspackages/9-public/@prisma/orm-toolchain/package.jsontest/integration/test/authoring/cli.emit-parity-fixtures.test.tstest/integration/test/cli.db-verify.e2e.test.tstest/integration/test/cli.emit-command.additional.test.tstest/integration/test/cli.emit-contract.test.tstest/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
…rker-and-control-client-double
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]>
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]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
test/integration/test/cli.config-section-requirements.test.ts (1)
110-134: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd 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 thatmigration logproceeds past malformedcontract.🤖 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
📒 Files selected for processing (22)
.agents/rules/config-validation-and-normalization.mdcpackages/1-framework/1-core/config/src/config-validation.tspackages/1-framework/1-core/config/test/config-validation.test.tspackages/1-framework/3-tooling/cli/README.mdpackages/1-framework/3-tooling/cli/src/commands/db-sign.tspackages/1-framework/3-tooling/cli/src/commands/db-verify.tspackages/1-framework/3-tooling/cli/src/commands/migrate.tspackages/1-framework/3-tooling/cli/src/commands/migration-check.tspackages/1-framework/3-tooling/cli/src/commands/migration-graph.tspackages/1-framework/3-tooling/cli/src/commands/migration-list.tspackages/1-framework/3-tooling/cli/src/commands/migration-log.tspackages/1-framework/3-tooling/cli/src/commands/migration-status.tspackages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.tspackages/1-framework/3-tooling/cli/src/control-api/operations/ref.tspackages/1-framework/3-tooling/cli/src/control-api/testing/fixture-client.tspackages/1-framework/3-tooling/cli/src/utils/migration-command-scaffold.tspackages/1-framework/3-tooling/cli/test/control-api/testing/fixture-client.test.tspackages/1-framework/3-tooling/config-loader/src/load.tspackages/1-framework/3-tooling/config-loader/test/load.test.tspackages/1-framework/3-tooling/language-server/src/config-resolution.tspackages/1-framework/3-tooling/language-server/test/config-resolution.test.tstest/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]>
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]>
## 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]>
Linked issue
Refs the CLI-consolidation follow-ups tracked in projects/consolidate-clis/plan.md ("config loading returns diagnostics", "export a fixture-backed
ControlClienttest double"). Linear was unreachable in the authoring session; the ticket link will be added when the PR is retitled.At a glance
Before this PR,
loadConfigthrew on the first problem it found, and ten commands (includingdb initanddb update) let that throw escape to commander — a raw stack trace and exit1. A config with a brokenformattersection blockeddb initeven thoughdb initnever readsformatter.Decision
This PR ships three deliverables:
loadConfignow returnsResult<{ config, diagnostics }, CliStructuredError>. Structural problems in an evaluated config becomeCONFIG.VALIDATION_FAILEDdiagnostics tagged with the config section they concern (meta.section,meta.field). A command fails (exit2, 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 codeCONFIG.EVALUATION_FAILED.defineConfigstamps a config-format version marker.defineConfigno longer validates or throws; it normalizes and stamps a non-enumerable version marker. The loader rejects configs whose export was not created by the currentdefineConfig— plain object exports, spread copies, or a config produced by a differentdefineConfig(a classic Prisma 7 file once the unified filename lands) — with the new registered codeCONFIG.VERSION_MARKER_MISSING. Fail-early; no best-effort reading of unmarked configs.ControlClienttest double.createFixtureControlClient()at@prisma/orm-toolchain/cli/control-api/testingcovers everyControlClientoperation 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
defineConfigstops throwing (config-types.ts). This is deliberate, not an oversight: a throw insidedefineConfighappens 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 incollectConfigIssues(config-validation.ts), which reports every problem instead of the first. Theconfig-validation-and-normalizationrulecard was rewritten to match.result.layers[*].configis the raw module export and preserves them.loadConfigcall 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 areload.ts,config-validation.ts,config-types.ts, and the per-command section lists (each command declares exactly the sections it reads).test/integration/test/cli.emit-command.additional.test.tspreviously asserted that a plain-object config withoutdefineConfigstill emitted (loader finalization). Under the accepted fail-early ruling, that fixture is now the negative case assertingCONFIG.VERSION_MARKER_MISSING.loadConfigForFilehad zero production call sites (language server usesfindNearestConfigPathForFile+loadConfig); it was converted to the Result API rather than removed, since hosts are expected to pick it up.issues-28192-pg-historical-datestimestamptz LMT-offset flake andinit-journey/init-skill-distributionafterAll 5s hook timeouts under parallel load. All pass in isolation.How it fits together
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 indefineConfig(formatter, migrations, contract source shapes) moved here as plain checks.defineConfignormalizes and stamps — it applies the contract-output default and stampsSymbol.for('prisma-next.config-format-version')(non-enumerable, value1). The marker deliberately does not survive spreads: configs must export thedefineConfigresult directly, which is what lets the future unified host loader distinguish a Prisma Nextprisma.config.tsfrom a classic Prisma 7 one by marker rather than misparse.NotOk(CONFIG.FILE_NOT_FOUND,CONFIG.EVALUATION_FAILED,CONFIG.VERSION_MARKER_MISSING) and wraps collector issues as section-taggedCliStructuredErrordiagnostics insideOk. Contract finalization is skipped when the contract section has diagnostics, so malformed values can't crash path resolution.requireConfigSectionsfails with the first diagnostic concerning a required section;loadConfigForSectionscomposes load + narrow for the common case. Every command's call site declares the sections it reads.ControlClient(compile-time conformance) over aControlClientFixturesrecord; the new./control-api/testingsubpath on@internal/cliflows into@prisma/orm-toolchain/cli/control-api/testingautomatically via the shell build.Behavior changes & evidence
db init,db update,migrate,migration status/log/show/new/list/graph,migrate --show) now render the structured envelope and exit2instead of printing a stack trace and exiting1. Implementation: migration-command-scaffold.ts, migration-graph.ts. Evidence: migration-cli.test.ts, pinned before/after--jsonenvelopes in the verification notes below.ref list --jsonsucceeds against a config with notarget, whilemigration list --jsonexits2with{ code: "CONFIG.VALIDATION_FAILED", meta: { field: "target", section: "target" } }. Implementation: load.ts. Evidence: section-requirements.test.ts, load.test.ts.CONFIG.EVALUATION_FAILEDwith the parser message inwhy, replacing the catch-allCLI.UNEXPECTED. Evidence: load.test.ts.defineConfigfails every command early withCONFIG.VERSION_MARKER_MISSING, whose fix text namesdefineConfig. Implementation: config-types.ts, load.ts. Evidence: define-config.test.ts, cli.emit-command.additional.test.ts.createFixtureControlClient({ dbInit: notOk({...}) })overrides one operation while the rest keep realistic defaults, andclient.callsrecords invocations. Implementation: fixture-client.ts. Evidence: fixture-client.test.ts, fixture-client.test-d.ts.CONFIG.EVALUATION_FAILEDandCONFIG.VERSION_MARKER_MISSING, andCONFIG.VALIDATION_FAILEDnow documentsmeta.field/meta.section: error-reference.md.Compatibility / migration / risk
loadConfig/loadConfigForFilechanged signature (throwing →Result). All in-repo consumers were converted;@internal/config-loaderis internal-only, so there is no external break.validateConfigwas replaced bycollectConfigIssues;configErrorand the internalconfig-errors.tsmodule were deleted (no external users).prisma-next.config.tsin the repo already routes throughdefineConfig(directly, via@internal/cli/config-types, or via facade wrappers), so marker enforcement required no fixture migrations outside dynamically-generated test configs.target/extensionsand stays silent on any invalidity.Testing performed
pnpm turbo build --filter=@internal/cli...plus a fullpnpm build— green.pnpm test,pnpm typecheck,pnpm lintinconfig,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/integrationtypecheck green.pnpm run check:error-reference— all 273 codes listed.pnpm lint:deps,pnpm lint:rules:symlinks,pnpm lint:rules:footprint— green.--jsonenvelopes before/after against the built CLI for: missing config, invalid plain-object config, syntax-error config, anddb initwith a bad config (previously exit1+ stack trace; now exit2+ envelope).Skill update
n/a — there is no
packages/0-shared/skills/tree in this revision; the user-facing deltas (new error codes,defineConfigmarker requirement) are documented indocs/reference/error-reference.mdand the rewrittenconfig-validation-and-normalizationrulecard.Follow-ups
@internal/config-loaderinto the calling context, leaving this package to evaluate file content passed in as a parameter.evaluateConfigModule-style separation insideload.tswas kept shallow deliberately.prisma.config.ts; no Prisma-7-filename discovery ships in this repo.Alternatives considered
Okwith a section-less diagnostic andconfig: undefined— rejected: every call site would re-implement the same undefined-check;NotOkgives all 21 call sites one uniform early exit with identical semantics.defineConfigvalidating and throwing — rejected: module-evaluation-time throws collapse every structural problem into an all-commands-fail evaluation error, defeating section-scoped diagnostics.Object.keys/JSON while still surviving loading; enumerability would leak the marker into every config consumer.CONFIG.VERSION_MARKER_MISSINGso the future unified loader can distinguish config formats by marker rather than misparse../control-api/testingsubpath on@internal/cliflows into@prisma/orm-toolchainautomatically via the shell build (ADR 242) and keeps the double versioned in lockstep with the client interface it must conform to.Checklist
git commit -s) per the DCO. The DCO status check will block merge if any commit is missing aSigned-off-by:trailer.TML-NNNN: <sentence-case title>form — pending: no Linear ticket was resolvable in the authoring session; will retitle once the ticket is named.Summary by CodeRabbit