Repository navigation
TML-2804: declarative SPI for extension-contributed PSL blocks (Slice 1 — read side) - #753
Conversation
…pes (D1) AuthoringPslBlockDescriptor is data — keyword, discriminator, name, parameters map of the four-kind union PslBlockParam (ref/value/option/list). No parser/printer functions. Adds the uniform parsed-block node base (name + parameter map), the PslNamespace.extensionBlocks slot, AuthoringContributions.pslBlocks, and isAuthoringPslBlockDescriptor. PslPosition/PslSpan/PslDiagnosticCode move to the shared plane (re-exported from psl-ast) so the shared-plane descriptor can reference spans. Types + type tests only; runtime is D2-D6. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Adds a PSL-text -> literal parse/validate direction pairing with encodeJson: an optional parsePslLiteral(raw) on CodecDescriptor (rejecting default on CodecDescriptorImpl), surfaced via CodecLookup.parsePslLiteralFor(id, raw) (mirrors renderOutputTypeFor). String codecs (sql/pg/sqlite text/char/varchar) override it to accept double-quoted strings; shared parseStringPslLiteral, pg/sqlite delegate. Result {ok,value|error} feeds the D4 validator. Parse direction only — print-back is Slice 2 (TML-2854); Int deferred.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
On an unknown top-level keyword, the parser consults the pslBlocks registry and reads the block body GENERICALLY into a uniform PslExtensionBlock node (name + parameter map), capturing each parameter RHS by its declared kind: ref->identifier, value->raw text, option->token, list->bracketed items (recursive per element kind). Reuses #718 block-bounds/comment-strip/diagnostic; DROPS the contributed-parser failure isolation + per-extension SPI context (no contributed code runs). Unknown keys captured faithfully as raw values for D4 to report by key-set diff; built-in parsing unchanged. Validation, codec calls, ref resolution, printing, lowering are all out of scope (D4/D6). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
validateExtensionBlock(node, descriptor, sourceId, codecLookup, refCtx?) reports, with spans: unknown parameter (key-set diff, not by captured kind), missing required, option-not-in-set, value rejected by its codec (parsePslLiteralFor), and ref unresolved within scope (same-namespace/same-space resolved against the parsed namespaces; cross-space a documented pass-through per the spec first-consumer allowance); list recurses. Adds the PSL_EXTENSION_* diagnostic taxonomy incl. PSL_INVALID_EXTENSION_BLOCK_MEMBER, and re-points D3 two malformed-body-line parser sites to it. char/varchar length intentionally not enforced (unbounded text). Validator is exported; D6 wires it into the round-trip. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…s (D5) assembleAuthoringContributions rejects, naming the extension: within-namespace duplicate path (merge walker), duplicate discriminator within pslBlocks and within entityTypes (assertUniqueDiscriminators), a pslBlock with no matching entityTypes factory (assertPslBlocksHaveFactories), and a malformed declarative descriptor (re-keyed: isAuthoringPslBlockDescriptor rejects AND it looks descriptor-shaped). Standalone entityTypes factories stay allowed (one-directional check). Cherry-picked from #718 review-final; pslBlocks now a required field on AssembledAuthoringContributions (+ empty-namespace fixture updates). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…er round-trip (D6)
Slice-closing dispatch. A test-only declarative policy_select extension (descriptor + entityTypes factory + IR class, no parser/printer functions) round-trips parse -> validate -> lower -> IR. The factory reads the uniform node.parameters declaratively. validateExtensionBlock is wired into parsePslDocument: when pslBlocks are registered, each block is validated against its descriptor (resolved by discriminator) with refCtx={ownerNamespace,allNamespaces}; codecLookup defaults to emptyCodecLookup (fail-closed for value params). Adds optional codecLookup to ParsePslDocumentInput. Fixes the D4 stale JSDoc code. Print leg is Slice 2 (TML-2854).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds declarative PSL extension-block types and authoring descriptors, merges descriptors in control-stack assembly, implements an extension-block validator, extends the parser to detect/parse/validate extension blocks, exports validator/types, and adds comprehensive tests and a policy_select fixture for end-to-end coverage. ChangesExtension block pipeline and support
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 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/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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/1-core/framework-components/src/shared/framework-authoring.ts`:
- Around line 267-301: The current isAuthoringPslBlockDescriptor function only
checks that parameters is a non-null object, letting malformed parameter
descriptors slip through; update isAuthoringPslBlockDescriptor to fully validate
parameters by: confirming parameters is a plain object (not an array), iterating
Object.entries(parameters) and for each entry ensuring the key is a non-empty
string and the value is an object (not null/array) with the expected properties
(at minimum a boolean 'required' and a non-empty string 'type' or similar
parameter descriptor fields used elsewhere), returning false if any parameter
entry fails these checks; keep the changes inside isAuthoringPslBlockDescriptor
to locate via that function name.
In `@packages/1-framework/1-core/framework-components/test/control-stack.test.ts`:
- Around line 383-409: The test description claims to exercise pslBlocks but the
fixture populates authoring.entityTypes instead, so update the test to actually
exercise pslBlocks: change the fixture passed to
assembleAuthoringContributions/createDescriptor to place the nested namespaces
under authoring.pslBlocks (mirroring the existing kind/discriminator entries) or
alternatively adjust the test description to reference authoring.entityTypes;
ensure the symbols assembleAuthoringContributions, createDescriptor and the
nested keys kind/discriminator are used under authoring.pslBlocks so the
malformed-check path for pslBlocks is truly tested.
In `@packages/1-framework/2-authoring/psl-parser/src/parser.ts`:
- Around line 1656-1661: The loop that parses list segments currently skips
empty items (if itemRhs.length === 0) instead of reporting an error; change this
to emit a PSL_INVALID_EXTENSION_BLOCK_MEMBER diagnostic for empty list elements
(e.g., when encountering `[a,,b]` or `[a,]`) using the parser's existing
error/diagnostic API and the segment's location information (use the segment
token/span like segment.start/segment.end or whatever location fields exist)
rather than continuing; keep normal parsing for non-empty items (the code that
handles itemRhs should remain unchanged).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: cf839e2a-9f5d-4bb3-ab37-436d1b02bd25
📒 Files selected for processing (39)
packages/1-framework/1-core/framework-components/src/control/control-stack.tspackages/1-framework/1-core/framework-components/src/control/psl-ast.tspackages/1-framework/1-core/framework-components/src/control/psl-extension-block-validator.tspackages/1-framework/1-core/framework-components/src/exports/authoring.tspackages/1-framework/1-core/framework-components/src/exports/codec.tspackages/1-framework/1-core/framework-components/src/exports/psl-ast.tspackages/1-framework/1-core/framework-components/src/shared/codec-descriptor.tspackages/1-framework/1-core/framework-components/src/shared/codec-types.tspackages/1-framework/1-core/framework-components/src/shared/framework-authoring.tspackages/1-framework/1-core/framework-components/src/shared/psl-extension-block.tspackages/1-framework/1-core/framework-components/test/control-stack.test.tspackages/1-framework/1-core/framework-components/test/psl-block-descriptor.types.test.tspackages/1-framework/1-core/framework-components/test/psl-extension-block-validator.test.tspackages/1-framework/1-core/framework-components/test/psl-literal-parse.test.tspackages/1-framework/2-authoring/psl-parser/src/parser.tspackages/1-framework/2-authoring/psl-parser/test/parser.test.tspackages/1-framework/2-authoring/psl-printer/test/declarative-policy-select.round-trip.test.tspackages/1-framework/2-authoring/psl-printer/test/fixtures/declarative-policy-select-extension.tspackages/1-framework/3-tooling/cli/test/config-types.test.tspackages/1-framework/3-tooling/emitter/test/domain-type-generation.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/derive-json-schema.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/interpreter.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/provider.test.tspackages/2-mongo-family/2-authoring/contract-ts/test/config-types.test.tspackages/2-sql/2-authoring/contract-psl/test/fixtures.tspackages/2-sql/2-authoring/contract-psl/test/provider.test.tspackages/2-sql/2-authoring/contract-ts/test/config-types.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.contract-definition.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.value-objects.test.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.typeref-resolver.test.tspackages/2-sql/4-lanes/relational-core/src/ast/sql-codecs.tspackages/2-sql/4-lanes/relational-core/test/ast/sql-codecs.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-runner.polymorphism.integration.test.tspackages/3-targets/3-targets/postgres/src/core/codecs.tspackages/3-targets/3-targets/sqlite/src/core/codecs.tspackages/3-targets/6-adapters/postgres/test/raw-expr-lowering.test.tspackages/3-targets/6-adapters/postgres/test/sql-renderer-namespace-qualification.test.tspackages/3-targets/6-adapters/postgres/test/sql-renderer.cast-policy.test.ts
| export function isAuthoringPslBlockDescriptor( | ||
| value: unknown, | ||
| ): value is AuthoringPslBlockDescriptor { | ||
| if (typeof value !== 'object' || value === null) { | ||
| return false; | ||
| } | ||
| const record = blindCast< | ||
| Record<string, unknown>, | ||
| 'type-guard probing an unknown candidate-descriptor object for known property names' | ||
| >(value); | ||
| if (record['kind'] !== 'pslBlock') { | ||
| return false; | ||
| } | ||
| const keyword = record['keyword']; | ||
| if (typeof keyword !== 'string' || keyword.length === 0) { | ||
| return false; | ||
| } | ||
| const discriminator = record['discriminator']; | ||
| if (typeof discriminator !== 'string' || discriminator.length === 0) { | ||
| return false; | ||
| } | ||
| const name = record['name']; | ||
| if (typeof name !== 'object' || name === null) { | ||
| return false; | ||
| } | ||
| const nameRecord = blindCast< | ||
| Record<string, unknown>, | ||
| 'type-guard probing the name property of a candidate pslBlock descriptor' | ||
| >(name); | ||
| if (typeof nameRecord['required'] !== 'boolean') { | ||
| return false; | ||
| } | ||
| const parameters = record['parameters']; | ||
| return typeof parameters === 'object' && parameters !== null && !Array.isArray(parameters); | ||
| } |
There was a problem hiding this comment.
Tighten isAuthoringPslBlockDescriptor to reject malformed parameter descriptors.
At Line 299, the guard only verifies that parameters is an object. That lets malformed parameter entries pass as “valid” descriptors, which defeats load-time malformed-descriptor rejection and pushes failures to later parser/validator paths.
Proposed fix
+function isPslBlockParamDescriptor(value: unknown): value is PslBlockParam {
+ if (typeof value !== 'object' || value === null) {
+ return false;
+ }
+ const record = blindCast<
+ Record<string, unknown>,
+ 'type-guard probing pslBlock parameter descriptor candidate'
+ >(value);
+ const required = record['required'];
+ if (required !== undefined && typeof required !== 'boolean') {
+ return false;
+ }
+ switch (record['kind']) {
+ case 'ref':
+ return (
+ typeof record['refKind'] === 'string' &&
+ typeof record['scope'] === 'string' &&
+ ['same-namespace', 'same-space', 'cross-space'].includes(
+ blindCast<string, 'scope string check'>(record['scope']),
+ )
+ );
+ case 'value':
+ return typeof record['codecId'] === 'string';
+ case 'option':
+ return (
+ Array.isArray(record['values']) &&
+ record['values'].every((entry) => typeof entry === 'string')
+ );
+ case 'list':
+ return isPslBlockParamDescriptor(record['of']);
+ default:
+ return false;
+ }
+}
+
export function isAuthoringPslBlockDescriptor(
value: unknown,
): value is AuthoringPslBlockDescriptor {
@@
const parameters = record['parameters'];
- return typeof parameters === 'object' && parameters !== null && !Array.isArray(parameters);
+ if (typeof parameters !== 'object' || parameters === null || Array.isArray(parameters)) {
+ return false;
+ }
+ return Object.values(parameters).every(isPslBlockParamDescriptor);
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts`
around lines 267 - 301, The current isAuthoringPslBlockDescriptor function only
checks that parameters is a non-null object, letting malformed parameter
descriptors slip through; update isAuthoringPslBlockDescriptor to fully validate
parameters by: confirming parameters is a plain object (not an array), iterating
Object.entries(parameters) and for each entry ensuring the key is a non-empty
string and the value is an object (not null/array) with the expected properties
(at minimum a boolean 'required' and a non-empty string 'type' or similar
parameter descriptor fields used elsewhere), returning false if any parameter
entry fails these checks; keep the changes inside isAuthoringPslBlockDescriptor
to locate via that function name.
| const segments = splitTopLevelSegments(inner, ','); | ||
| for (const segment of segments) { | ||
| const itemRhs = segment.value.trim(); | ||
| if (itemRhs.length === 0) { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
Report empty list elements instead of silently dropping them.
Line 1659 currently continues on empty list items, so malformed input like [a,,b] or [a,] is accepted without PSL_INVALID_EXTENSION_BLOCK_MEMBER.
Proposed fix
if (inner.length > 0) {
const segments = splitTopLevelSegments(inner, ',');
for (const segment of segments) {
const itemRhs = segment.value.trim();
if (itemRhs.length === 0) {
- continue;
+ pushDiagnostic(context, {
+ code: 'PSL_INVALID_EXTENSION_BLOCK_MEMBER',
+ message: `Invalid empty list element in "${rhs}"`,
+ span,
+ });
+ continue;
}
const item = captureParamRhs(context, lineIndex, itemRhs, param.of);
if (item !== undefined) {
items.push(item);
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/1-framework/2-authoring/psl-parser/src/parser.ts` around lines 1656
- 1661, The loop that parses list segments currently skips empty items (if
itemRhs.length === 0) instead of reporting an error; change this to emit a
PSL_INVALID_EXTENSION_BLOCK_MEMBER diagnostic for empty list elements (e.g.,
when encountering `[a,,b]` or `[a,]`) using the parser's existing
error/diagnostic API and the segment's location information (use the segment
token/span like segment.start/segment.end or whatever location fields exist)
rather than continuing; keep normal parsing for non-empty items (the code that
handles itemRhs should remain unchanged).
…p bespoke PSL hook (D7) Post-design-review correction. PSL literals are handled generically and codecs already own value<->JSON (decodeJson/encodeJson), so a value parameter is interpreted as JSON through the codec existing decodeJson: the validator now does codecLookup.get(codecId).decodeJson(JSON.parse(raw)) — the same path that decodes literal column defaults — reporting a diagnostic when the literal is not valid JSON or the codec rejects it. Removes the bespoke parsePslLiteral hook (CodecDescriptor + PslLiteralParseResult + default), CodecLookup.parsePslLiteralFor + pslLiteralParsersById, the string-codec overrides + parseStringPslLiteral, 21 inline CodecLookup stubs, and psl-literal-parse.test.ts. Net 104+/383-. @default literal handling and the print side (Slice 2) untouched. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ispatch/ticket IDs (PR review) Review remediation on #753. (1) Renames the descriptor-registry surface pslBlocks -> pslBlockDescriptors (AuthoringContributions, ParsePslDocumentInput, AssembledAuthoringContributions, the parser input, type AuthoringPslBlockNamespace -> AuthoringPslBlockDescriptorNamespace, + fixtures) to disambiguate it from the parsed extensionBlocks slot; sharpens the docs contrasting the registry-of-descriptors vs parsed-nodes. (2) Strips transient dispatch/ticket breadcrumbs (Dn, TML-2804, TML-2500, PR refs) from this slice source + tests per the no-transient-project-ids rule, rewriting comments to be self-describing. No behavioral change. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…arative-block-descriptor-generic Signed-off-by: Will Madden <[email protected]> # Conflicts: # packages/1-framework/2-authoring/psl-parser/test/parser.test.ts
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts (1)
514-540:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRequire a factory-backed
entityTypesmatch here.
assertPslBlocksHaveFactoriescurrently treats anyentityTypesleaf with the same discriminator as sufficient. That lets a template-backed entity descriptor satisfy this check even though the extension-block path needsoutput.factory, so the bad contribution is accepted at load time and only breaks later during lowering.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts` around lines 514 - 540, assertPslBlocksHaveFactories currently only checks that an entityTypes leaf shares the discriminator with a pslBlock, allowing template-backed entity descriptors to pass; update the logic in assertPslBlocksHaveFactories (which iterates over blockEntries and uses entityEntries/entityDiscriminators from collectAuthoringLeafDiscriminators and isAuthoringEntityTypeDescriptor) to require that the matching entity entry actually exposes a factory (e.g., check the entity entry's descriptor/output.factory or equivalent factory flag on the entity entry) rather than just existence; if no factory-backed entity is found for a block.discriminator, throw the existing error message so extension-contributed PSL blocks cannot register without a corresponding factory-backed entityType.
🤖 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/1-core/framework-components/src/control/psl-ast.ts`:
- Around line 280-286: The doc for codecLookup is incorrect: when
pslBlockDescriptors is provided the parser still calls validateExtensionBlock
and will fall back to emptyCodecLookup (producing unknown-codec diagnostics for
value params) rather than skipping codec validation; update the comment for
codecLookup to state this exact contract and behavior—mention codecLookup,
pslBlockDescriptors, validateExtensionBlock, and emptyCodecLookup by name and
clearly document that omitting codecLookup only changes which lookup is used
(not whether validation runs).
---
Outside diff comments:
In
`@packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts`:
- Around line 514-540: assertPslBlocksHaveFactories currently only checks that
an entityTypes leaf shares the discriminator with a pslBlock, allowing
template-backed entity descriptors to pass; update the logic in
assertPslBlocksHaveFactories (which iterates over blockEntries and uses
entityEntries/entityDiscriminators from collectAuthoringLeafDiscriminators and
isAuthoringEntityTypeDescriptor) to require that the matching entity entry
actually exposes a factory (e.g., check the entity entry's
descriptor/output.factory or equivalent factory flag on the entity entry) rather
than just existence; if no factory-backed entity is found for a
block.discriminator, throw the existing error message so extension-contributed
PSL blocks cannot register without a corresponding factory-backed entityType.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 88fcc26b-8255-4078-8a76-39f6b0ae7f9d
📒 Files selected for processing (18)
packages/1-framework/1-core/framework-components/src/control/control-stack.tspackages/1-framework/1-core/framework-components/src/control/psl-ast.tspackages/1-framework/1-core/framework-components/src/control/psl-extension-block-validator.tspackages/1-framework/1-core/framework-components/src/exports/authoring.tspackages/1-framework/1-core/framework-components/src/shared/framework-authoring.tspackages/1-framework/1-core/framework-components/src/shared/psl-extension-block.tspackages/1-framework/1-core/framework-components/test/control-stack.test.tspackages/1-framework/1-core/framework-components/test/psl-block-descriptor.types.test.tspackages/1-framework/1-core/framework-components/test/psl-extension-block-validator.test.tspackages/1-framework/2-authoring/psl-parser/src/parser.tspackages/1-framework/2-authoring/psl-parser/test/parser.test.tspackages/1-framework/2-authoring/psl-printer/test/declarative-policy-select.round-trip.test.tspackages/1-framework/2-authoring/psl-printer/test/fixtures/declarative-policy-select-extension.tspackages/1-framework/3-tooling/cli/test/config-types.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/provider.test.tspackages/2-mongo-family/2-authoring/contract-ts/test/config-types.test.tspackages/2-sql/2-authoring/contract-psl/test/fixtures.tspackages/2-sql/2-authoring/contract-ts/test/config-types.test.ts
🚧 Files skipped from review as they are similar to previous changes (16)
- packages/1-framework/3-tooling/cli/test/config-types.test.ts
- packages/2-sql/2-authoring/contract-ts/test/config-types.test.ts
- packages/2-mongo-family/2-authoring/contract-psl/test/provider.test.ts
- packages/2-mongo-family/2-authoring/contract-ts/test/config-types.test.ts
- packages/1-framework/1-core/framework-components/test/psl-block-descriptor.types.test.ts
- packages/1-framework/1-core/framework-components/src/exports/authoring.ts
- packages/2-sql/2-authoring/contract-psl/test/fixtures.ts
- packages/1-framework/1-core/framework-components/src/control/control-stack.ts
- packages/1-framework/2-authoring/psl-printer/test/declarative-policy-select.round-trip.test.ts
- packages/1-framework/2-authoring/psl-parser/test/parser.test.ts
- packages/1-framework/1-core/framework-components/test/control-stack.test.ts
- packages/1-framework/2-authoring/psl-printer/test/fixtures/declarative-policy-select-extension.ts
- packages/1-framework/1-core/framework-components/src/shared/psl-extension-block.ts
- packages/1-framework/1-core/framework-components/test/psl-extension-block-validator.test.ts
- packages/1-framework/1-core/framework-components/src/control/psl-extension-block-validator.ts
- packages/1-framework/2-authoring/psl-parser/src/parser.ts
| * Codec lookup for validating `value`-kind extension block parameters. | ||
| * When provided alongside `pslBlockDescriptors`, the generic validator runs | ||
| * over every parsed extension block after the full AST is assembled, | ||
| * appending any diagnostics to the parse result. Absent or undefined means | ||
| * no codec validation runs; `ref` resolution still runs when namespace | ||
| * context is available (built from the assembled namespaces). | ||
| */ |
There was a problem hiding this comment.
codecLookup docs don't match the parser's fallback behavior.
When pslBlockDescriptors is present, the parser still runs validateExtensionBlock and falls back to emptyCodecLookup, so omitting codecLookup does not skip codec validation—it produces unknown-codec diagnostics for value params. Please update this comment to match the actual 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 `@packages/1-framework/1-core/framework-components/src/control/psl-ast.ts`
around lines 280 - 286, The doc for codecLookup is incorrect: when
pslBlockDescriptors is provided the parser still calls validateExtensionBlock
and will fall back to emptyCodecLookup (producing unknown-codec diagnostics for
value params) rather than skipping codec validation; update the comment for
codecLookup to state this exact contract and behavior—mention codecLookup,
pslBlockDescriptors, validateExtensionBlock, and emptyCodecLookup by name and
clearly document that omitting codecLookup only changes which lookup is used
(not whether validation runs).
…e threshold The generic extension-block parser (parseExtensionBlock / captureParamRhs) added branches that dropped psl-parser branch coverage to 80.81%, below the 81% threshold. Add three tests for genuinely-untested behaviour of the new code: a blank line inside a block body is skipped, a list parameter given a non-bracketed value emits PSL_INVALID_EXTENSION_BLOCK_MEMBER and drops the parameter, and empty segments in a list literal are skipped. Branch coverage now 81.49%. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Slice 1 (declarative PSL-block SPI, #753) renamed pslBlocks -> pslBlockDescriptors (and the namespace type to AuthoringPslBlockDescriptorNamespace) and removed the codec PSL hooks (parsePslLiteralFor/printPslLiteralFor) in favour of the codec's JSON medium. Rework the generic printer + contract-infer to match: renderValueParam now validates and renders a value param via codecLookup.get(id).decodeJson(JSON.parse(raw)) then JSON.stringify(encodeJson(...)), mirroring the parse-side validator. Sweep the pslBlocks -> pslBlockDescriptors rename across the printer and CLI, and drop the obsolete parsePslLiteral/printPslLiteral fixture overrides from the printer tests. The dropped P1 commit (codec PSL print-back hook) is superseded by this JSON-medium approach; only P2 (generic printer) and P3 (contract-infer) were replayed in the rebase. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Slice 1 (declarative PSL-block SPI, #753) renamed pslBlocks -> pslBlockDescriptors (and the namespace type to AuthoringPslBlockDescriptorNamespace) and removed the codec PSL hooks (parsePslLiteralFor/printPslLiteralFor) in favour of the codec's JSON medium. Rework the generic printer + contract-infer to match: renderValueParam now validates and renders a value param via codecLookup.get(id).decodeJson(JSON.parse(raw)) then JSON.stringify(encodeJson(...)), mirroring the parse-side validator. Sweep the pslBlocks -> pslBlockDescriptors rename across the printer and CLI, and drop the obsolete parsePslLiteral/printPslLiteral fixture overrides from the printer tests. The dropped P1 commit (codec PSL print-back hook) is superseded by this JSON-medium approach; only P2 (generic printer) and P3 (contract-infer) were replayed in the rebase. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Slice 1 (declarative PSL-block SPI, #753) renamed pslBlocks -> pslBlockDescriptors (and the namespace type to AuthoringPslBlockDescriptorNamespace) and removed the codec PSL hooks (parsePslLiteralFor/printPslLiteralFor) in favour of the codec's JSON medium. Rework the generic printer + contract-infer to match: renderValueParam now validates and renders a value param via codecLookup.get(id).decodeJson(JSON.parse(raw)) then JSON.stringify(encodeJson(...)), mirroring the parse-side validator. Sweep the pslBlocks -> pslBlockDescriptors rename across the printer and CLI, and drop the obsolete parsePslLiteral/printPslLiteral fixture overrides from the printer tests. The dropped P1 commit (codec PSL print-back hook) is superseded by this JSON-medium approach; only P2 (generic printer) and P3 (contract-infer) were replayed in the rebase. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ks (Slice 2 — write side) (#754) ## At a glance Slice 2 of 4 of **[Target-contributed top-level PSL blocks](https://linear.app/prisma-company/issue/TML-2854)** — the **write side** of the declarative SPI. Slice 1 ([#753](#753), merged) gave the framework a generic *read* path (parse → validate → lower an extension-contributed block from its descriptor). This PR adds the matching *write* path: one generic descriptor-driven printer renders any registered block back to PSL, and `contract infer` threads the registered descriptors through so an inferred contract prints its extension blocks. No extension-supplied printer code runs. ```prisma policy_select ProfilesSelect { target = Post using = "auth.uid() = author_id" } ``` The printer never learns the `policy_select` keyword — it reads the descriptor (keyword, `name`, typed `parameters`) and renders each parameter by its declared kind. ## What's in this PR - **Generic descriptor-driven printer** (`psl-printer`) — `serializePrintDocument` builds a discriminator-keyed dispatch map from the registered `pslBlockDescriptors` and renders each block's parameters by kind: `ref` → identifier, `option` → token, `list` → bracketed elements, `value` → the codec's JSON medium (below). An unregistered discriminator throws, naming it. - **`value` params are serialized *through the codec*, not echoed** — `renderValueParam` runs a value literal through `JSON.stringify(codec.encodeJson(codec.decodeJson(JSON.parse(raw))))`. This is the exact print-back mirror of Slice 1's parse-side validator (`codecLookup.get(codecId).decodeJson(JSON.parse(raw))`): a PSL value literal *is* the JSON serialization of the value, and the codec owns that medium. There is no bespoke codec PSL hook. - **`contract infer` threading** (`cli`) — the assembled `pslBlockDescriptors` namespace flows from `inspectLiveSchema` into `printPsl`, so an inferred contract can print extension blocks. - **Round-trip + codec-drives-output coverage** — the declarative `policy_select` fixture now round-trips the full pipeline (parse → validate → lower → IR → serialize → hydrate → IR → **print** → re-parse → structurally-equivalent AST), and a dedicated printer test proves the codec — not the captured raw text — produces the literal. ## A design decision worth a look **The codec owns the serialized form of a value parameter, on both sides.** The original cut of this slice shipped a bespoke codec PSL hook (`parsePslLiteral` / `printPslLiteral`); that was rejected in Slice 1 in favour of the codec's existing JSON medium, and this PR was **rebased onto `main`** with that hook commit dropped and the printer reworked to `encodeJson`/`decodeJson` + `JSON.parse`/`JSON.stringify`. The risk with that path is a test that can't tell "the codec serialized the value" apart from "the raw text passed through untouched" — an identity codec (`encodeJson(v) => v`) makes them indistinguishable. So the proof test uses a **non-identity** codec: `decodeJson` coerces a quoted `"42"` to the number `42`, `encodeJson` emits a bare JSON number, and the printed literal is `using = 42` (unquoted) — which can only come from the codec running on the value. Mutating `renderValueParam` to echo `raw` fails this test (`using = "42"` ≠ `using = 42`). This is also the exact value path an IR/value source would take, fabricated directly rather than waiting on a production block contributor. ## Out of scope (later slices / first consumer) - **`PslNamespace` → ADR 224 `entries` migration** — Slice 3, [TML-2849](https://linear.app/prisma-company/issue/TML-2849) ([#757](#757), to be rebased onto this). - **ADR 126 revision + three-layer ADR + close-out** — Slice 4, [TML-2806](https://linear.app/prisma-company/issue/TML-2806). - **A standalone `value → raw` lowering helper for IR-originated blocks** — deferred to the first real block-contributing extension. The print seam already routes through the codec and is proven; the node stores `raw`, and there is no production contributor yet to fix a helper's signature against. ## Verification | Gate | Result | |---|---| | `pnpm build` (framework-components → psl-parser → psl-printer) | clean | | `pnpm typecheck` (psl-printer / cli) | clean | | `pnpm test` — psl-printer / cli | 50 / 1317 pass | | `pnpm lint:deps` | clean | | `pnpm lint:casts` | `delta=0` (the one new cast is a `blindCast` with reason, not a bare `as`) | | `pnpm fixtures:check` | clean — except a pre-existing `supabase` example failure (`prisma-next: command not found`, an env/PATH issue in that example) that reproduces independently of this PR | ## Relationships - **[#753](#753) / TML-2804** — Slice 1, merged; this is its write-side mirror. Rebased onto `main`; the superseded codec-PSL-hook commit was dropped. - **[#757](#757) / TML-2849** — Slice 3, stacked; will be rebased onto this branch. Refs [TML-2854](https://linear.app/prisma-company/issue/TML-2854). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Extension blocks are now properly printed and serialized in PSL documents with support for codec-based parameter rendering and custom block descriptors. * **Tests** * Added comprehensive test coverage for extension block printing, round-trip validation, and command integration with extension blocks. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Will Madden <[email protected]> Co-authored-by: Will Madden <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]>
The entries migration (E1) was authored before Slice 1/2's later test additions landed on main, so the rebase surfaced readers/producers E1 could not have updated: the #753 generic-parser coverage tests read ns.extensionBlocks, and Slice 2's printer tests built inline old-shape namespace literals (models/enums/compositeTypes/extensionBlocks arrays). Route them through the namespacePslExtensionBlocks helper and the makeNs factory, matching the rest of the entries migration. No behaviour change; psl-parser 110, psl-printer 55. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
The entries migration (E1) was authored before Slice 1/2's later test additions landed on main, so the rebase surfaced readers/producers E1 could not have updated: the #753 generic-parser coverage tests read ns.extensionBlocks, and Slice 2's printer tests built inline old-shape namespace literals (models/enums/compositeTypes/extensionBlocks arrays). Route them through the namespacePslExtensionBlocks helper and the makeNs factory, matching the rest of the entries migration. No behaviour change; psl-parser 110, psl-printer 55. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
The entries migration (E1) was authored before Slice 1/2's later test additions landed on main, so the rebase surfaced readers/producers E1 could not have updated: the #753 generic-parser coverage tests read ns.extensionBlocks, and Slice 2's printer tests built inline old-shape namespace literals (models/enums/compositeTypes/extensionBlocks arrays). Route them through the namespacePslExtensionBlocks helper and the makeNs factory, matching the rest of the entries migration. No behaviour change; psl-parser 110, psl-printer 55. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
The entries migration (E1) was authored before Slice 1/2's later test additions landed on main, so the rebase surfaced readers/producers E1 could not have updated: the #753 generic-parser coverage tests read ns.extensionBlocks, and Slice 2's printer tests built inline old-shape namespace literals (models/enums/compositeTypes/extensionBlocks arrays). Route them through the namespacePslExtensionBlocks helper and the makeNs factory, matching the rest of the entries migration. No behaviour change; psl-parser 110, psl-printer 55. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
All four slices delivered (#753/#754/#757 + this PR); the durable architecture decisions landed in ADR 126/225 and the retro lessons in adr-writing.mdc + docs/Testing Guide.md. The transient project workspace (spec, plans, slice plans) drops with the close-out. No external references to scrub. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ecture docs Make the architecture record match what Slices 1-3 shipped (#753/#754/#757): - Rewrite ADR 126 from the superseded parseFn/validateFn/emitFn function SPI to the declarative AuthoringPslBlockDescriptor design: keyword + name + typed parameters (ref/value/option/list), interpreted by one generic framework parser/validator/printer; value rides the codec JSON medium; option is an authoring-token constraint, not a domain enum; the block lowers via the entityTypes factory. - Add ADR 225: how the three layers carry a pack-contributed entity kind, tied by its discriminator (IR class -> entityTypes lowering -> declarative parse+print). Subsystem doc 6 points at it. - Fix the AuthoringContributions.entities -> entityTypes doc-bug in AGENTS.md (CLAUDE.md symlinks it) and docs/reference/typescript-patterns.md. Markdown-only. Project close-out (project-dir deletion + retro) follows separately. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
All four slices delivered (#753/#754/#757 + this PR); the durable architecture decisions landed in ADR 126/225 and the retro lessons in adr-writing.mdc + docs/Testing Guide.md. The transient project workspace (spec, plans, slice plans) drops with the close-out. No external references to scrub. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
At a glance
Slice 1 of 4 of Target-contributed top-level PSL blocks — the read side of the declarative SPI. After this, an extension describes a new top-level PSL block as data (a descriptor of its keyword, name, and typed parameters), and the framework parses, validates, and lowers it to contract IR with one generic interpreter. No extension-supplied parse/print code runs.
This supersedes the function-based SPI built on #718 (now draft): that cut had each extension ship imperative
parser/printerfunctions. The mechanism is cherry-picked here; the functions are replaced by the descriptor + generic interpreter. Rationale + design are inprojects/target-contributed-psl-blocks/spec.md(landed via #749).The framework never learns the
policy_selectkeyword directly — the descriptor is data.What's in this PR
The parameter value-kind vocabulary and the generic read pipeline, built across seven dispatches:
framework-components) —AuthoringPslBlockDescriptoris data: keyword, discriminator,name, and aparametersmap of the four-kind unionPslBlockParam:ref(resolves to a declared entity;refKind+scope),value(codec-typed),option(a closed set of allowed literal tokens — an authoring constraint, not a domain enum),list(combinator). Noparser/printerfields. Plus the uniform parsed-node base ({ kind, name, parameters, span }) and thePslNamespace.extensionBlocksslot.valuevia the codec's existingdecodeJson— avalueliteral is interpreted as JSON through the codec the parameter declares:codecLookup.get(codecId).decodeJson(JSON.parse(raw))— the same path that decodes literal column defaults. There is no bespoke PSL codec hook; PSL literals are handled generically and codecs already own value↔JSON, sovaluerides that existing medium (and gets full codec expressiveness + correct JSON escaping for free). (@default's legacy literal handling is untouched — separate, future work.)psl-parser) — on an unknown top-level keyword, the parser reads any declared block into the uniform node, capturing each parameter's RHS by its declared kind. Built-in keywords stay framework-parsed; an unregistered keyword still gets the clean unknown-keyword diagnostic.refresolution — reports (with spans) unknown / missing-required parameters,option-not-in-set, codec-rejectedvalue, andrefunresolved within its scope (same-namespace/same-spaceresolved against the parsed namespaces;cross-spaceis a documented pass-through per the spec's first-consumer allowance, leaning on the merged TML-2500 (M1): cross-contract FK carrier + aggregate-load checks #745 coordinate model). A smallPSL_EXTENSION_*diagnostic taxonomy.assembleAuthoringContributionsrejects duplicate keyword, duplicate discriminator (withinpslBlocksand withinentityTypes), apslBlocksdescriptor with no matchingentityTypesfactory, and a malformed descriptor. StandaloneentityTypesfactories stay allowed.entityTypesfactory; a test-only declarativepolicy_selectfixture round-trips parse → validate → lower → IR.A design decision worth a look
Validation runs inside
parsePslDocumentwheneverpslBlocksare registered, joining the parser's existing diagnostics. Avalueparameter is validated by parsing its literal as JSON and running the codec's existingdecodeJson(codecLookup.get(codecId).decodeJson(JSON.parse(raw))); malformed JSON or a codec rejection surfaces a diagnostic. No production caller passespslBlocksyet — this is the read-side seam.Out of scope (later slices)
contract infer— Slice 2, TML-2854. This PR's round-trip stops at the lowered IR.PslNamespace→ ADR 224entriesmigration — Slice 3, TML-2849.numbervalue-kind / field-declaration block bodies (deferred to first consumer); real RLS (downstream).Relationships
refcross-spacescope builds on its coordinate model. Not a blocker.optionis not an enum,valueuses ordinary scalar codecs.Verification
pnpm typecheck(the four touched packages)pnpm test:packages(psl-parser / psl-printer / framework-components / cli, in isolation)pnpm lint:depspnpm lint:castsdelta=0(no regression)A monorepo-wide typecheck has pre-existing, unrelated worktree dist-not-built failures (migration-tools / mongo-contract / sql-schema-ir / emitter / mongo-lowering) — none introduced here; per-package typechecks for the touched packages are clean, and the changes don't alter a public export signature those packages consume.
Follow-ups recorded for downstream (not this slice)
ref-kindvsdiscriminatormismatch for a non-cross-spaceref to an extension-contributed entity (the first RLS-roles-style consumer must maprefKind→ discriminator).Refs TML-2804.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests
Chores