@sumrco/cli 0.3.8 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/ARTIFACT-MANIFEST.json +18 -0
  2. package/README.md +12 -0
  3. package/THIRD_PARTY_NOTICES.md +1119 -0
  4. package/ai/modules/kontract/resources/api-generation-standards.rf.md +18 -5
  5. package/ai/modules/kontract/resources/authoring/configuration.rf.md +568 -12
  6. package/ai/modules/kontract/resources/authoring/schema-reuse.rf.md +25 -4
  7. package/ai/modules/kontract/resources/authoring/scope-and-splitting.rf.md +8 -6
  8. package/ai/modules/kontract/resources/authoring/spec-layout.rf.md +4 -0
  9. package/ai/modules/kontract/resources/generated-output.rf.md +712 -44
  10. package/ai/modules/kontract/resources/nestjs-eslint.rf.md +153 -0
  11. package/ai/modules/kontract/resources/openapi-sdk-generator-research.rf.md +177 -0
  12. package/ai/modules/kontract/resources/overview.md +70 -8
  13. package/ai/modules/kontract/resources/performance.rf.md +11 -2
  14. package/ai/modules/kontract/sumr.module.yaml +15 -14
  15. package/ai/modules/mission/resources/flow-config.rf.md +2 -2
  16. package/ai/modules/mission/resources/overview.md +42 -35
  17. package/ai/modules/mission/resources/stage-closeout.rf.md +5 -5
  18. package/ai/modules/mission/resources/stage-delivery.rf.md +5 -5
  19. package/ai/modules/mission/resources/stage-intake.rf.md +2 -2
  20. package/ai/modules/mission/resources/stage-planning.rf.md +43 -4
  21. package/ai/modules/mission/resources/stage-pull-request.rf.md +2 -2
  22. package/ai/modules/mission/resources/stage-quality.rf.md +8 -8
  23. package/ai/modules/mission/resources/team-members/planner.tm.md +17 -5
  24. package/ai/modules/mission/resources/workflows/daily-triage.cmd.md +5 -1
  25. package/ai/modules/mission/resources/workflows/mission-cycle.cmd.md +7 -5
  26. package/ai/modules/mission/resources/workflows/planning-only.cmd.md +8 -3
  27. package/ai/modules/mission/sumr.module.yaml +20 -16
  28. package/ai/modules/playbook/resources/authoring/extraction.rf.md +28 -1
  29. package/ai/modules/playbook/resources/authoring/frontmatter.rf.md +7 -0
  30. package/ai/modules/playbook/resources/authoring/overview.md +33 -2
  31. package/ai/modules/playbook/resources/authoring/patterns.rf.md +21 -0
  32. package/ai/modules/playbook/resources/team-members/technical-writer.tm.md +5 -1
  33. package/ai/modules/playbook/sumr.module.yaml +13 -12
  34. package/ai/registry.json +3 -3
  35. package/bin/sumr +18 -3
  36. package/eslint/index.mjs +2 -0
  37. package/eslint/kontract/index.mjs +22 -0
  38. package/eslint/kontract/rules/typescript-nestjs/operation-contract.mjs +656 -0
  39. package/index.js +3060 -458
  40. package/package.json +26 -23
  41. package/sbom.cdx.json +5111 -0
@@ -14,6 +14,11 @@ Generated files are deterministic outputs. Import them; never edit them.
14
14
  Every generated TypeScript file starts with an `<auto-generated>` comment that
15
15
  warns users not to edit the file directly.
16
16
 
17
+ Generated `index.ts` files are generator-owned contract entry points. Their namespace
18
+ and wildcard re-exports are part of the documented generated consumer API; they are not
19
+ a precedent for authored package source. Kontract files under `src/` import concrete
20
+ owner modules, and the curated package `src/index.ts` publishes explicit named exports.
21
+
17
22
  ## HTTP output — one folder per API schema service
18
23
 
19
24
  For an API schema service such as `recipes.api.yml`, the NestJS target
@@ -26,10 +31,23 @@ contracts/recipes/
26
31
  index.ts
27
32
  enums/
28
33
  models/
29
- zod/ # when zod generation is enabled
30
- dto/ # when dtos generation is enabled
34
+ zod/ # when zod schemas or Zod DTOs are enabled
35
+ dto/ # when dto is class-validator or both
31
36
  sdk/ # when sdk generation is enabled
32
37
  swagger.ts # when swagger generation is enabled
38
+ operations.ts # when operationContract is enabled
39
+ foundation.ts # when foundation is enabled
40
+ multipart.ts # when an operation declares multipart/form-data
41
+ ports.ts
42
+ controllers.ts
43
+ feature.module.ts # when controllers are enabled
44
+ errors.ts # when errors are enabled
45
+ mappers.ts # when mappers are enabled
46
+ testing.ts
47
+ contract-test-manifest.ts
48
+ contract-test-schemas.ts
49
+ openapi-parity.ts # when tests are enabled
50
+ bruno/ # when bruno is enabled
33
51
 
34
52
  contracts/shared/
35
53
  http/
@@ -38,8 +56,38 @@ contracts/shared/
38
56
  ```
39
57
 
40
58
  Shared `$ref` components keep the source spec DRY and semantically consistent.
41
- Today, supported `allOf` object composition is flattened in the generated
42
- service output, so some concrete response DTOs may still repeat envelope fields.
59
+ External `$ref` documents are bundled before extraction, not blindly
60
+ dereferenced, so they become stable local component-owned definitions.
61
+ For both one-root and grouped services, Kontract retains every supported named
62
+ component from the traversed local `$ref` graph. This includes a handler payload
63
+ component that is not itself selected by an operation, such as an `allOf`
64
+ paginated `{ data, meta }` payload declared beside the operation's final wire
65
+ envelope. The payload therefore still emits its model, Zod contract/Zod DTO,
66
+ class-validator DTO when enabled, and barrel exports; consuming server code
67
+ imports those generated symbols directly instead of recreating the shape.
68
+ Files outside the traversed graph are not scanned or exported. A same-name
69
+ component alias that resolves to the canonical shared component, or the same
70
+ component reached through root and normalized-dependency paths, emits once.
71
+ Operation references, Swagger metadata, models, class-validator DTOs, Zod
72
+ contracts/Zod DTOs, and barrels all reuse that authored canonical symbol;
73
+ Kontract does not retain bundler-generated `Name-2` aliases for an identical
74
+ definition. Root-owned component references win over normalized dependency
75
+ copies, and equivalent synthetic bundle aliases are rewritten to the canonical
76
+ component before extraction.
77
+ Two traversed documents that declare genuinely different definitions under the
78
+ same component name fail generation with both source locations rather than
79
+ selecting one by discovery order or keeping a numeric suffix. Retaining a named
80
+ payload does not make it
81
+ the operation's wire response—the operation contract continues to own the
82
+ separately documented envelope.
83
+ Supported `allOf` object composition is flattened in the generated service
84
+ output while preserving the four-way required/nullable matrix, so some concrete
85
+ response DTOs may still repeat envelope fields.
86
+ An OpenAPI 3.0 single-part `allOf` wrapper around a scalar/enum `$ref` is also
87
+ normalized when it carries `nullable: true` or annotations. A required nullable
88
+ enum therefore emits the referenced enum type unioned with `null` and the
89
+ referenced Zod enum schema followed by `.nullable()`; a plain optional `$ref`
90
+ remains optional and non-null.
43
91
  Do not fix that by hand-editing generated files. If generated code repeats too
44
92
  much, first improve the spec with shared components; then consider a Kontract
45
93
  generator improvement such as preserved composition or shared external
@@ -67,18 +115,40 @@ Use the namespace exports or import from the leaf folder.
67
115
  import { z } from 'zod';
68
116
  import { createZodDto } from 'nestjs-zod';
69
117
 
70
- export const RecipeSchema = z.object({
118
+ export const RecipeInputSchema = z.object({
119
+ name: z.string().min(1).max(255),
120
+ status: z.enum(['draft', 'published', 'archived']),
121
+ }).meta({ id: 'RecipeInput' });
122
+
123
+ export const RecipeOutputSchema = z.object({
71
124
  id: z.string().uuid(),
72
125
  name: z.string().min(1).max(255),
73
126
  status: z.enum(['draft', 'published', 'archived']),
74
- });
127
+ }).meta({ id: 'RecipeOutput' });
75
128
 
76
- export class RecipeDto extends createZodDto(RecipeSchema) {}
77
- export type Recipe = z.infer<typeof RecipeSchema>;
129
+ export const RecipeSchema = RecipeOutputSchema.meta({ id: 'Recipe' });
130
+ export class RecipeDto extends createZodDto(RecipeInputSchema) {}
131
+ export type RecipeInput = z.input<typeof RecipeInputSchema>;
132
+ export type RecipeOutput = z.output<typeof RecipeOutputSchema>;
133
+ export type Recipe = RecipeOutput;
78
134
  ```
79
135
 
80
- Every generated Zod contract yields `${Name}Schema` + `${Name}Dto` +
81
- `type ${Name}`.
136
+ Every generated Zod contract yields directional `${Name}InputSchema` and
137
+ `${Name}OutputSchema` plus input/output types. `${Name}Schema` and `${Name}`
138
+ remain output-compatible aliases. Request schemas exclude API schema
139
+ `readOnly` fields; output schemas exclude `writeOnly` fields. A NestJS
140
+ `${Name}Dto` is emitted only for `dto: zod` or `dto: both` and wraps the input
141
+ schema. Framework-neutral standalone schemas never import `nestjs-zod`.
142
+
143
+ Stable Zod metadata IDs are required by the pinned
144
+ Zod/nestjs-zod/Swagger cleanup path; do not remove them or replace them with a
145
+ separate global-registry side effect.
146
+
147
+ `oneOf` and `anyOf` emit Zod unions and matching TypeScript unions. A
148
+ discriminator with a complete mapping emits `z.discriminatedUnion()`;
149
+ class-validator object properties receive the same `oneOf`/`anyOf`,
150
+ `discriminator`, `getSchemaPath()`, `ApiExtraModels`, and transformer subtype
151
+ metadata. Invalid or incomplete discriminator mappings fail generation.
82
152
 
83
153
  ## Model interfaces and named aliases
84
154
 
@@ -107,14 +177,27 @@ signatures may continue to show the structurally equivalent underlying type, suc
107
177
 
108
178
  Map-shaped schemas follow API schema `additionalProperties` semantics:
109
179
 
110
- - map-only schemas generate index signatures such as `[key: string]: string`;
180
+ - map-only schemas with an explicit value schema generate index signatures such
181
+ as `[key: string]: string`;
182
+ - omitting `additionalProperties` does not synthesize a TypeScript index
183
+ signature, so named properties remain usable through `Pick`, `Omit`, and
184
+ `Partial`; the corresponding Zod object accepts then strips undeclared keys;
185
+ - `additionalProperties: false` emits no index signature and a strict Zod
186
+ object;
111
187
  - named properties with `additionalProperties: true` preserve the named fields
112
188
  and use `[key: string]: unknown`;
113
189
  - named properties with typed `additionalProperties` preserve named fields and
114
190
  widen the index signature with known property value types, matching the
115
191
  practical TypeScript approach used by current API schema TypeScript generators.
116
192
 
117
- ## Class-validator DTO — when `dtos: true`
193
+ These rules compose through referenced, nested, inline, and outer `allOf`
194
+ members. If multiple typed declarations cannot be represented by one safe
195
+ catch-all value schema, generation fails instead of silently dropping one.
196
+ Named empty components still emit an empty model and Zod schemas when operations
197
+ reference them directly; omission does not turn them into
198
+ `Record<string, unknown>`.
199
+
200
+ ## Class-validator DTO — when `dto: class-validator` or `dto: both`
118
201
 
119
202
  ```typescript
120
203
  // contracts/recipes/http/dto/recipe.dto.ts
@@ -140,6 +223,19 @@ properties include `@Expose()` so they remain compatible with class-transformer
140
223
  serializers that use `excludeExtraneousValues: true`. Do not hand-write parallel
141
224
  DTOs for schemas Kontract owns.
142
225
 
226
+ Top-level and nested DTO classes declare a matching index signature only when
227
+ the schema explicitly uses `additionalProperties: true` or a typed
228
+ additional-properties schema. They then remain structurally assignable to the
229
+ generated model interface. That signature is TypeScript-only. A consuming
230
+ `ValidationPipe({ whitelist: true, forbidNonWhitelisted: true })` still rejects
231
+ undeclared keys because an index signature is not a class-validator property
232
+ decorator. This stricter application policy is supported and must not be
233
+ weakened. When that closed runtime behavior is the intended API contract,
234
+ declare `additionalProperties: false` explicitly in the source request schema;
235
+ Kontract then emits no catch-all/index signature. Omission also avoids an index
236
+ signature, but its Zod object accepts and strips undeclared keys rather than
237
+ failing strictly.
238
+
143
239
  ## Swagger operation metadata — when `swagger: true`
144
240
 
145
241
  ```typescript
@@ -159,7 +255,8 @@ export const SWG_LIST_RECIPES = {
159
255
  } as const;
160
256
  ```
161
257
 
162
- `swagger: true` works with either `zod: true` or `dtos: true`. Generated
258
+ `swagger: true` works with Zod schemas and either supported DTO technology.
259
+ Generated
163
260
  metadata preserves operation IDs, paths, summaries, descriptions, params, query
164
261
  params, body DTOs, response DTOs, success response status, `x-kontract-surface`,
165
262
  and standard API schema `security`.
@@ -191,6 +288,370 @@ async listRecipes() {
191
288
  Generated `ApiDoc` depends only on NestJS and `@nestjs/swagger`; it does not
192
289
  import Kontract at runtime.
193
290
 
291
+ ## Generated operation contracts — when `operationContract: true`
292
+
293
+ The NestJS target emits `http/operations.ts`. Each constant owns one operation's
294
+ identity, route, selected success status, transport, request Zod DTO, and JSON
295
+ response Zod DTO/schema. The adjacent machine-readable
296
+ `@kontract-operation` marker records the same import identities for the public
297
+ Kontract ESLint rule.
298
+
299
+ ```typescript
300
+ import {
301
+ Operation,
302
+ GetRecipe,
303
+ type GetRecipePayload,
304
+ } from 'SUMR Schemas module/recipes/http';
305
+
306
+ @Get(':recipeId')
307
+ @Operation(GetRecipe)
308
+ getRecipe(): Promise<GetRecipePayload> {
309
+ // controller implementation
310
+ }
311
+ ```
312
+
313
+ For managed JSON responses, `Operation` invokes native `nestjs-zod`
314
+ `ZodResponse` metadata at runtime and exposes the same typed descriptor
315
+ constraint in its generated overload. One decorator therefore owns operation
316
+ identity, parameters, security, errors, Swagger metadata, success status,
317
+ response DTO, runtime serialization, and the handler-return constraint.
318
+ Compile-fail fixtures protect the overload from being widened to a broad
319
+ `MethodDecorator`. Do not add a sibling `@ZodResponse`,
320
+ `@ZodSerializerDto`, manual response serializer, or library-mode `@Res()`.
321
+ No-content, file, raw, stream, SSE, and explicit application-owned passthrough
322
+ contracts use the same operation decorator without installing JSON
323
+ serialization.
324
+
325
+ The operation descriptor also records all success statuses, request and
326
+ response media types, path/query/header/cookie parameters, documented error
327
+ responses, response headers and named examples, callbacks, handler and wire
328
+ schemas, source provenance (including its JSON Pointer), security scopes, and
329
+ validated `x-kontract-cache`
330
+ and `x-kontract-rate-limit` metadata.
331
+ Generation fails when multiple successful schemas or an absent body cannot be
332
+ classified safely.
333
+
334
+ Transport classification has one normalized intermediate-representation (IR)
335
+ owner reused by controllers, lint metadata, runtime descriptors, and test
336
+ manifests. The IR is internal generator state, not an emitted consumer file or
337
+ wire format. JSON, no-content, file,
338
+ SSE, stream, and
339
+ raw responses are distinct; multipart request bodies are distinct request
340
+ metadata. Named scalar, array, nullable, and union JSON schemas receive Zod DTO
341
+ constructor constants (object schemas retain DTO classes) and remain
342
+ JSON responses; they are not treated as no-content. File, stream, SSE, and raw
343
+ responses never pass through JSON serialization.
344
+
345
+ Generated Zod DTO constructor constants have a deterministic runtime class name
346
+ matching the exported symbol. Operation response codec DTOs therefore remain
347
+ distinct to NestJS and Swagger instead of all appearing under nestjs-zod's
348
+ internal factory class name.
349
+
350
+ Inline OpenAPI callbacks emit exact `@ApiCallbacks` metadata and a typed
351
+ `OperationCallbackSender` over `HttpService`. The caller supplies the callback
352
+ URL; signing, retries, persistence, and delivery policy remain application
353
+ owned. Callback request bodies must reference a generated component DTO and
354
+ must declare a concrete 2xx acknowledgement.
355
+
356
+ OpenAPI 3.1 top-level `webhooks` also participate in the operation spine. A
357
+ webhook key beginning with `/` is its receiver path; otherwise its Path Item
358
+ must declare `x-kontract-webhook-path`. The generated receiver is marked with
359
+ `@WebhookReceiver`, and the shared policy guard fails closed unless the
360
+ application supplies `WEBHOOK_SIGNATURE_VERIFIER`. Kontract never
361
+ generates signing algorithms or secrets.
362
+
363
+ ## Generated controller and application port — opt-in
364
+
365
+ With `foundation: true` and `controllers: true`, Kontract emits a thin,
366
+ regeneration-safe controller, a `HttpPort`, its injection token, and a
367
+ dynamic feature module. The controller owns only transport wiring and delegates
368
+ each operation to the injected port. Application business logic implements the
369
+ port outside the generated tree and is never overwritten.
370
+
371
+ Parameter bindings use schema-derived Nest pipes where supported, including
372
+ UUID, integer, boolean, enum, array, and default-value handling. Supported
373
+ array styles retain their exact OpenAPI wire behavior: repeated values for
374
+ query `form` with `explode: true`, comma-delimited values for
375
+ `form` with `explode: false` and `simple`, and the declared delimiter for
376
+ `pipeDelimited` or `spaceDelimited`. The generated parameter runtime converts
377
+ only declared boolean, integer, number, and array wire strings before applying
378
+ the authoritative Zod constraints. Strings—including `date` and `date-time`
379
+ formats—remain strings. Invalid numeric syntax, unknown aggregate query/path
380
+ keys, and values outside schema constraints produce the canonical 400 response.
381
+
382
+ Application controllers may bind each parameter separately:
383
+
384
+ ```typescript
385
+ @Query(
386
+ 'limit',
387
+ operationParameterPipe(ClubsFindAll, '<parameter name>'),
388
+ )
389
+ limit: number | undefined
390
+ ```
391
+
392
+ or bind the exact operation-owned aggregate:
393
+
394
+ ```typescript
395
+ import {
396
+ ClubsFindAll,
397
+ type ClubsFindAllQuery,
398
+ } from 'SUMR Schemas module/clubs/http';
399
+
400
+ @Query(new OperationParameterBagPipe(ClubsFindAll, 'query'))
401
+ query: ClubsFindAllQuery
402
+ ```
403
+
404
+ The same aggregate form is available for `path`, `header`, and `cookie`.
405
+ Header lookup is case-insensitive. Aggregate header/cookie validation selects
406
+ only fields declared by the operation because ambient HTTP headers and
407
+ unrelated cookies are valid; aggregate query/path validation remains strict.
408
+ The consumer must install its framework's cookie parser when using Nest's
409
+ cookie decorator—the generated pipe validates parsed cookie values but does
410
+ not own application middleware.
411
+
412
+ Object parameters, array cookies, and unsupported styles fail controller
413
+ generation with an application-adapter diagnostic instead of silently
414
+ guessing framework decoding. Cookie parameters are also emitted into the live
415
+ Swagger operation metadata. Static routes
416
+ are emitted before parameter routes. URI/header/media-type versioning is enabled
417
+ only by explicit generator configuration and is never inferred from
418
+ `info.version`.
419
+
420
+ Request bodies bind through
421
+ `@Body(new ZodValidationPipe(Operation.requestBodyDto))` and use the
422
+ operation-owned `OperationRequest` input type. Required and optional bodies,
423
+ including scalar, array, union, nullable, and referenced schemas, therefore use
424
+ the same exact runtime schema as the operation descriptor instead of depending
425
+ on reflected class metadata.
426
+
427
+ Multipart generation supports component-backed object request bodies with
428
+ single binary files, bounded arrays of files, multiple named file fields, and
429
+ mixed text/JSON fields. Schema `maxLength` is enforced as the per-file byte
430
+ limit; file arrays and repeated non-file arrays require finite `maxItems`
431
+ bounds. Multipart encoding `contentType` (or OpenAPI 3.1
432
+ `contentMediaType`) becomes the file-type or field-decoding contract.
433
+
434
+ Express controllers select `FileInterceptor`, `FilesInterceptor`,
435
+ `FileFieldsInterceptor`, or `NoFilesInterceptor` from the exact operation
436
+ shape. Fastify controllers use generated `@fastify/multipart` registration and
437
+ an operation-owned buffered interceptor. Both profiles validate non-file parts
438
+ with a Zod schema picked from the authoritative request contract, reject
439
+ undeclared parts, validate file count/type/size before delegation, and pass the
440
+ same `UploadedMultipartFile` shape to the application port.
441
+
442
+ Required request bodies must carry one of the operation's declared media
443
+ types. An absent optional body does not represent any media type, so it reaches
444
+ the operation-owned optional schema as `undefined` without requiring a
445
+ `Content-Type`. Once body bytes are present, a missing or mismatched
446
+ `Content-Type` is rendered through the declared 415 contract. The boundary uses
447
+ both the parsed body and HTTP length/transfer headers so an unsupported body
448
+ cannot evade media enforcement merely because the host adapter left it
449
+ unparsed. A selected response header with a schema `const` (or one enum value)
450
+ is unambiguous and becomes a generated `@Header`; dynamic response header
451
+ values remain application-owned while their schema stays in Swagger and the
452
+ operation descriptor.
453
+
454
+ Buffered upload adapters intentionally require finite limits and are not
455
+ streaming upload APIs. Generation fails for missing file `maxLength`, unbounded
456
+ file/field arrays, non-component request bodies, unsupported part schemas, and
457
+ optional multipart bodies whose children are still required. Applications that
458
+ need streaming storage, virus scanning, or application-specific file policy
459
+ must own that transport adapter outside the generated tree.
460
+
461
+ ## Shared NestJS foundation — opt-in
462
+
463
+ `foundation: true` emits one target-wide
464
+ `shared/http/foundation.ts` with a DI-preserving `OperationsModule.register()`
465
+ using `APP_PIPE`, `APP_INTERCEPTOR`, `APP_FILTER`, and `APP_GUARD`. Generated
466
+ test applications import this same shared boundary. Per-service
467
+ `http/foundation.ts` files retain the service-owned Swagger
468
+ configuration/cleanup surface and compatible adapter exports. The shared
469
+ filter reads the exact operation descriptor attached to each handler, so it
470
+ does not select an arbitrary service copy of a common error DTO.
471
+
472
+ Application-facing generated identifiers describe what each symbol is, never
473
+ the generator brand and never a noun a customer's own domain plausibly owns.
474
+ Operation-scoped runtime symbols use the `Operation` family: `@Operation(OP)`,
475
+ `OperationsModule`, `OperationsController`, `OperationsFeatureModule`,
476
+ `OperationInterceptor`, `OperationExceptionFilter`, `OperationPolicyGuard`,
477
+ `OperationParameterPipe`, `OperationParameterBagPipe`,
478
+ `OperationCallbackSender`, `OperationErrorObserver`, and
479
+ `OperationErrorDiagnostic`. DI and metadata tokens are the SCREAMING_SNAKE
480
+ form of the seam they provide: `OPERATION_POLICY`, `OPERATION_ERROR_OBSERVER`,
481
+ `DOMAIN_ERROR_MAPPER`, `WEBHOOK_SIGNATURE_VERIFIER`, `HTTP_PORT`. Symbols
482
+ scoped to another concern carry that concern's name instead: `HttpPort`,
483
+ `WebhookSignatureVerifier`, `DomainErrorMapper`, the `Multipart*` pipes and
484
+ interceptors with `UploadedMultipartFile`, and `EnvelopeContext` with
485
+ `runWithEnvelopeContext()` and `requireEnvelopeContext()`. Contract-test
486
+ artifacts keep the industry term (`createContractTestApplication`,
487
+ `CONTRACT_TEST_MANIFEST`), and `*Contract` remains as a role suffix
488
+ (`HttpOperationContract`, `OPERATION_CONTRACTS`). Global symbol-registry keys
489
+ use the `kontract.*` namespace because that surface is tool-owned end to end.
490
+ Kontract does not emit deprecated compatibility aliases.
491
+
492
+ The foundation also emits:
493
+
494
+ - `configureApp(app)`, used by production and generated test factories;
495
+ - `buildOpenApiConfig()` and `cleanupOpenApiDoc()`; cleanup normalizes
496
+ nestjs-zod output and overlays only source-owned schema component names
497
+ (needed for scalar, array, and nullable DTO constructors), while preserving
498
+ other live components. It also restores operation-owned parameter schemas
499
+ after Nest reflection, which cannot retain array item constraints and has no
500
+ cookie method decorator. Parity still compares live operation metadata and
501
+ every source-owned schema/security component;
502
+ - a redacting canonical exception filter;
503
+ - operation-identity observation that reports only redacted diagnostics
504
+ (`operationId`, route/provenance, error category/name, status, and schema
505
+ references)—never raw errors, exception messages, Zod inputs, or payloads;
506
+ - `@Public()`, declared-scope metadata, a fail-closed authorization hook, and a
507
+ typed cookie decorator.
508
+
509
+ Only an operation-level explicit `security: []` emits `@Public()`. Inherited or
510
+ absent security remains fail-closed. Generated security metadata retains
511
+ OpenAPI's alternatives (OR) and combined schemes (AND) rather than flattening
512
+ them into a single scope list.
513
+
514
+ Applications supply authorization decisions and logging hooks. Generated code
515
+ does not verify tokens, contain secrets, make record-level authorization
516
+ decisions, or own `main.ts`.
517
+
518
+ Application bootstrap and root-module wiring import the target-wide surface:
519
+
520
+ ```typescript
521
+ import {
522
+ OperationsModule,
523
+ configureApp,
524
+ } from 'SUMR Schemas module/shared/http';
525
+ ```
526
+
527
+ Operation-specific `buildOpenApiConfig()` and `cleanupOpenApiDoc()` remain
528
+ available from each service's `http/foundation.ts`, because their source-owned
529
+ components and security schemes are document-specific.
530
+
531
+ The live docs page has a mandatory wiring step. A document created by
532
+ `SwaggerModule.createDocument` gains DTO and component schemas only through the
533
+ generated cleanup; serving it raw renders dangling `$ref` text in Swagger UI
534
+ without failing any request. An application serving every generated service
535
+ behind one docs page uses the target-wide composition from
536
+ `shared/http/openapi-doc.ts`, which applies each service's cleanup and then
537
+ throws if any local `$ref` remains unresolved:
538
+
539
+ ```typescript
540
+ import { cleanupOpenApiDoc } from 'SUMR Schemas module/shared/http';
541
+
542
+ const document = cleanupOpenApiDoc(SwaggerModule.createDocument(app, config));
543
+ SwaggerModule.setup(route, app, document);
544
+ ```
545
+
546
+ The application keeps its own `DocumentBuilder` for title, description, and
547
+ auth schemes. An application mounting only a subset of services composes that
548
+ subset from the per-service foundations instead, because each service's cleanup
549
+ requires its operations to be present in the document.
550
+
551
+ Unit-test the served document with `assertOpenApiDocumentResolves(document)`,
552
+ exported by every service foundation and by `shared/http/openapi-doc.ts`: build
553
+ the document exactly as bootstrap does, run it through cleanup, and assert. The
554
+ assertion names every unresolved pointer, so a skipped or partial cleanup fails
555
+ in CI instead of in the docs UI.
556
+
557
+ The generated foundation checks that the source documents every status its own
558
+ infrastructure can produce: 400 for validated input, 403 for fail-closed
559
+ security, 415 for declared request media enforcement, and 500 for JSON
560
+ output/unexpected failures. One compatible `default` error response may cover
561
+ these statuses. Generation fails early rather than turning an undeclared
562
+ boundary error into a misleading internal error.
563
+
564
+ Application-owned implementations are passed as providers to
565
+ `OperationsModule.register([...])` using the exported `OPERATION_POLICY`,
566
+ `OPERATION_ERROR_OBSERVER`, and `WEBHOOK_SIGNATURE_VERIFIER` tokens.
567
+ This keeps extension providers in the same Nest module scope as the global
568
+ guard/filter instead of relying on `useGlobal*` or parent-module lookup.
569
+ `DOMAIN_ERROR_MAPPER` is the application-owned seam for translating a
570
+ domain failure into a declared status/body; mapping decisions are never
571
+ generated.
572
+
573
+ When `envelope` is configured, `dataKey` describes the bare handler payload.
574
+ Kontract emits a Zod codec DTO: the handler stays typed to that bare payload,
575
+ runtime encoding produces the final wire envelope once, and Swagger describes
576
+ the wire schema. Literal `staticFields` and request-derived timestamp/path
577
+ fields can satisfy additional required schema properties. Request context is
578
+ carried through `AsyncLocalStorage` by the generated interceptor, so business
579
+ ports remain transport-neutral.
580
+
581
+ If a response schema also declares the configured `metaKey`, its port returns
582
+ `{ data, meta }` and the codec places both fields at the wire envelope root.
583
+ Schemas without that property still return their bare payload. The generator
584
+ rejects required fields it cannot derive and does not guess business envelope
585
+ values. `envelopeDataKey` remains a deprecated single-key compatibility option.
586
+
587
+ An operation marked `x-response-mode: passthrough` explicitly makes the
588
+ application responsible for its complete response transport: status, headers,
589
+ cookies, body, serialization, and documented errors. `Operation`
590
+ continues to install operation identity and Swagger metadata, but does not
591
+ install `ZodResponse`; the generated response interceptor and canonical error
592
+ filter do not alter that operation. Target-wide `errorEnvelope` compatibility
593
+ preflight therefore applies only to managed operations. A passthrough
594
+ controller may use library-mode `@Res()` and return `void`; it must catch and
595
+ render its documented failures itself.
596
+
597
+ The operation descriptor records `responseMode: 'passthrough'` so the public
598
+ ESLint rule and every emitter make the same deterministic decision. Sibling
599
+ managed operations keep exact handler typing, runtime serialization, canonical
600
+ error rendering, and bare-payload-to-envelope encoding. Generated Fetch,
601
+ Axios, Angular, and React Query clients still validate the passthrough
602
+ operation's raw documented success and error bodies at their client boundary.
603
+
604
+ ## Errors, mappings, and contract tests — opt-in
605
+
606
+ `errors: true` emits typed exception helpers only for documented non-success
607
+ JSON responses. Exception constructors parse their body with the exact
608
+ generated response schema. Repeated component reachability across service
609
+ bundles does not create competing runtime filters: the one target-wide filter
610
+ selects the documented status/default contract from the active operation,
611
+ validates the final body with that operation-owned schema, preserves declared
612
+ status/code/details, and redacts unexpected or output-validation failures
613
+ before rendering the documented 500/default shape. Application code should
614
+ throw a generated declared exception when a documented error body must pass
615
+ through unchanged.
616
+ Applications still decide when domain failures become transport errors.
617
+
618
+ `errorEnvelope` configures that generated rendering without owning application
619
+ error decisions. It supports flat or nested error bodies, literal outer fields,
620
+ status/message/type/code/details keys, request path/timestamp fields, and
621
+ redacted internal defaults. Validation details may use the default
622
+ `issues-object` projection or the explicit `raw` projection. Generation fails
623
+ when a documented required error field cannot be produced. The default policy
624
+ is flat; nested/custom contracts must explicitly map `bodyKey`, `staticFields`,
625
+ and core field keys. `sumr kontract validate` checks that mapping against the
626
+ selected operation schemas, and `generate --clean` repeats the write-free
627
+ preflight before removing generated output.
628
+
629
+ `mappers: true` emits explicit 1:1 structural projections. It does not infer
630
+ computed values, relations, units, timezone semantics, state transitions, or
631
+ authorization-dependent masking.
632
+
633
+ `tests: true` emits a Bun-test-compatible operation manifest, named-example
634
+ validation, normalized OpenAPI parity helpers, and a TestingModule factory that
635
+ uses the same `configureApp()` boundary as production. It also emits a
636
+ `supertest` HTTP driver, required-input/malformed-output test-case metadata, and
637
+ parameter fixtures only when the source supplies an example, default, or enum
638
+ value. Inline examples and local `#/components/examples/*` references are
639
+ validated; `externalValue` examples fail deterministic generation rather than
640
+ escaping validation. Mock ports and boundary providers remain overridable. Consumers enabling
641
+ this test output provide `supertest` and its TypeScript declarations as
642
+ development dependencies. `bruno: true` emits one request per operation plus a
643
+ coverage manifest keyed by operation identity; Kontract does not invent
644
+ business fixture values.
645
+
646
+ Generated-consumer dependencies—including NestJS, Fastify/Express, RxJS,
647
+ class-validator, and test runners—belong to the consuming project or an isolated
648
+ technology/version test matrix—not Kontract's root development dependencies.
649
+ Kontract verifies NestJS 11 Express and Fastify output in an exact-version
650
+ Docker consumer matrix. Future NestJS, Java, C#, or other generator versions
651
+ receive independent manifests and images so their dependency graphs cannot
652
+ conflict. Bun lockfiles are generated only inside disposable Docker image
653
+ layers, not committed under `tests/consumer-matrices/`.
654
+
194
655
  ## NestJS-composed SDK — when `sdk: true`
195
656
 
196
657
  ```typescript
@@ -214,13 +675,22 @@ export class RecipesFetchClient {
214
675
  ```
215
676
 
216
677
  The composed SDK is for NestJS services that call another generated HTTP API.
217
- It emits `http/sdk/runtime.ts`, `http/sdk/api.ts`, and a local barrel, but it
678
+ It emits `http/sdk/runtime.ts`, `http/sdk/api.ts`, and a generator-owned SDK entry point, but it
218
679
  does not duplicate the target's models. Component schema references import from
219
680
  `http/models/`; component enum references import from `http/enums/`; inline
220
681
  operation enums remain local literal unions.
221
682
 
222
- Use standalone `typescript-fetch`, `typescript-axios`, or `typescript-angular`
223
- targets when a frontend/admin application should own a separate SDK package.
683
+ When the Nest target has both `sdk: true` and `zod: true`, `http/sdk/` also
684
+ emits the frontend operation registry and fixture validators, importing the
685
+ already-owned `http/zod/` contracts rather than duplicating a second schema
686
+ tree. If the target also declares `envelope`, that SDK consumes the same
687
+ Contract IR projection as the server codec: server output is encoded once,
688
+ then the nested SDK validates the complete wire response and returns the bare
689
+ payload or `{ data, meta }`.
690
+
691
+ Use standalone `typescript-fetch`, `typescript-axios`, `typescript-angular`,
692
+ or `react-query-hooks` targets when a frontend/admin application should own a
693
+ separate SDK package.
224
694
 
225
695
  ## Frontend SDKs — React and Angular apps
226
696
 
@@ -233,26 +703,106 @@ apps:
233
703
  axios interceptors or shared axios instances.
234
704
  - `typescript-angular` emits an Angular service that uses `HttpClient` and
235
705
  returns `Observable<T>`.
706
+ - `typescript-models` emits model-only output and optional framework-neutral
707
+ schemas.
708
+ - `react-query-hooks` emits the validated Fetch SDK plus TanStack Query keys,
709
+ option factories, and configurable direct hooks.
710
+
711
+ With `zod: true`, a standalone SDK service folder contains:
712
+
713
+ ```text
714
+ catalog/
715
+ index.ts
716
+ models.ts
717
+ runtime.ts
718
+ api.ts
719
+ operations.ts
720
+ fixtures.ts
721
+ schemas/
722
+ query-keys.ts # react-query-hooks only
723
+ react-query.ts # react-query-hooks only
724
+ ```
236
725
 
237
726
  Example React usage with the fetch SDK:
238
727
 
239
728
  ```typescript
240
729
  import { ProductsFetchClient } from './generated/api';
241
- import { decodeProductApiJson } from './product-api-decoder';
242
730
 
243
731
  const api = new ProductsFetchClient({
244
732
  baseUrl: '/api',
245
- decodeJson: decodeProductApiJson,
733
+ credentials: 'include',
734
+ authHeaders: async (operationId, security) =>
735
+ tokenStore.headersFor(operationId, security),
246
736
  });
247
737
 
248
738
  export async function loadProduct(id: string) {
249
- return api.getProduct({ id });
739
+ return api.getProduct(
740
+ { id },
741
+ { signal: AbortSignal.timeout(10_000) },
742
+ );
250
743
  }
251
744
  ```
252
745
 
253
- Use an application-owned decoder such as a generated Zod schema, Valibot schema,
254
- or reviewed type guard at the `decodeJson` boundary. Do not cast unknown JSON in
255
- consumer code.
746
+ `authHeaders` is operation-aware. Fetch, Axios, and Angular clients call it only
747
+ when the operation has an effective OpenAPI security requirement, passing the
748
+ stable operation ID and the structured alternatives/scopes. An explicit
749
+ operation-level `security: []` bypasses the callback; inherited root security
750
+ continues to invoke it. The operation registry exposes the same effective
751
+ `security` value plus `securityIsExplicit`. Consumer-owned static headers and
752
+ transport interceptors remain outside this generated decision. Grouped
753
+ multi-file services retain the root default from the operation's owning source
754
+ file after local-reference aggregation.
755
+
756
+ With `zod: true`, the client parses requests and selects response schemas by
757
+ operation ID, status/default, and content type before returning. Declared error
758
+ bodies are parsed before `HttpError`; transport, abort, and validation failures
759
+ remain distinct. Request serialization consumes the parsed output for body,
760
+ path, query, header, and cookie values; it never validates one value and sends
761
+ the original caller value. With Zod disabled, Fetch retains the explicit
762
+ consumer `decodeJson` seam and Axios/Angular retain target-native typed
763
+ transports; those modes are compile-time contracts, not runtime proof.
764
+
765
+ For a selected response declared as `type: string`, `format: binary`, or with a
766
+ binary media type such as `application/pdf` or `application/octet-stream`, the
767
+ generated browser-facing result is `Blob`. Fetch calls `response.blob()`;
768
+ Axios and Angular force `responseType: 'blob'`; React Query option factories and
769
+ hooks inherit `Blob` from the Fetch client. The operation registry records the
770
+ binary content types and validates that the decoded value is a `Blob`; it does
771
+ not run the component's string-shaped Zod schema against the transport value.
772
+ JSON and `+json` error bodies declared on the same operation are decoded
773
+ separately—even when Axios or Angular surfaces the error as a `Blob`—then
774
+ validated before `HttpError`. Zero-byte binary responses remain valid `Blob`
775
+ values. Mixed binary and non-binary representations for one response fail
776
+ generation instead of producing an unstable union runtime type.
777
+
778
+ When a Zod-enabled Fetch, Axios, Angular, or React Query target declares
779
+ `envelope`, the generated operation registry first validates the complete
780
+ documented success response. It then returns the configured `dataKey` payload,
781
+ or `{ data, meta }` when the selected response schema declares the configured
782
+ `metaKey`. Every JSON-compatible successful status that references that same
783
+ envelope component uses the same validation and projection, so operations
784
+ declaring equivalent 200 and 201 responses expose one client payload type.
785
+ Shared-envelope statuses declared with an incompatible media decoder fail
786
+ generation rather than producing a partially projected union. Error responses
787
+ are not projected and remain available as their documented wire body on
788
+ `HttpError`.
789
+
790
+ For `x-response-mode: passthrough`, the registry omits the target-wide success
791
+ projection and validates/returns the selected raw documented response instead.
792
+ The override is operation-local: enveloped and passthrough operations can share
793
+ one source and one generated Fetch/React Query client. Security requirements,
794
+ request validation, binary media handling, and typed error bodies remain
795
+ operation-owned and unchanged.
796
+
797
+ The generated registry exposes separate wire and client paths:
798
+
799
+ - `parseOperationWireResponse` validates and returns the documented wire body;
800
+ - `parseOperationResponse` validates and then applies the configured success
801
+ projection.
802
+
803
+ `fixtures.ts` uses the wire path, so response fixtures keep the envelope a mock
804
+ server must send. Clients and React Query option factories use the projected
805
+ path. No target infers or silently unwraps an undocumented envelope.
256
806
 
257
807
  Example Angular usage:
258
808
 
@@ -270,9 +820,123 @@ export class ProductPage {
270
820
  }
271
821
  ```
272
822
 
273
- The generated SDK owns path interpolation, query serialization, request body
274
- encoding, response typing, and generated model imports. Consumers call methods
275
- instead of rewriting API URLs and `fetch`/`HttpClient` calls by hand.
823
+ React Query consumers can use generated option factories directly:
824
+
825
+ ```typescript
826
+ import { QueryClient } from '@tanstack/react-query';
827
+ import {
828
+ getProductQueryOptions,
829
+ ProductsFetchClient,
830
+ } from './generated/query-api';
831
+
832
+ const client = new ProductsFetchClient({ baseUrl: '/api' });
833
+ const queryClient = new QueryClient();
834
+
835
+ await queryClient.prefetchQuery(
836
+ getProductQueryOptions(client, { id: 'product-1' }),
837
+ );
838
+ ```
839
+
840
+ The same output can generate `useGetProduct` and suspense/infinite/mutation
841
+ hooks. Pagination is explicit per operation; Kontract never guesses its cursor.
842
+ Tag/surface key predicates support technical cache selection, while feature
843
+ invalidation, retries, optimistic updates, and `select` transformations remain
844
+ application-owned.
845
+
846
+ The generated SDK owns path/query/header/body serialization, declared request
847
+ media handling, operation-aware response validation, failure categories,
848
+ cancellation, per-call transport options, and generated model imports.
849
+ Consumers call methods instead of rewriting API URLs and transport code.
850
+
851
+ ```mermaid
852
+ flowchart LR
853
+ A["API operationId + path + schemas"] --> B["Generated models"]
854
+ A --> C["Generated operation methods"]
855
+ C --> D["Configured application transport"]
856
+ D --> E["Unknown network response"]
857
+ E --> F["Generated operation registry"]
858
+ F --> G["Zod schema by status + content type"]
859
+ G --> H["Optional documented success-envelope projection"]
860
+ H --> J["Validated application data"]
861
+ G --> I["Typed HTTP/transport/abort/contract failure"]
862
+ ```
863
+
864
+ The operation registry is frontend/framework-neutral. It is deliberately
865
+ separate from the NestJS `operationContract`, which imports server DTOs and
866
+ decorators.
867
+
868
+ Dates/date-times and money remain contract wire values. Kontract does not
869
+ coerce defaults, convert timezones, unwrap undocumented envelopes, or generate
870
+ view/form/optimistic-update state. Recursive Zod component cycles currently
871
+ fail with an explicit lazy-schema limitation.
872
+
873
+ ## Transport-neutral async contract — `asyncapi-models`
874
+
875
+ `asyncapi-models` emits one transport-independent `async/` surface per AsyncAPI
876
+ service:
877
+
878
+ ```text
879
+ contracts/realtime/
880
+ index.ts # exports AsyncContracts
881
+ async/
882
+ index.ts # production messages, registry/parsers, and enums
883
+ messages.ts # Zod v4 schemas + input/output types
884
+ registry.ts # names, direction maps, schemas, parsers, failures
885
+ fixtures.ts # opt-in fixture validators; not barrel-exported
886
+ enums/
887
+ ```
888
+
889
+ Channel addresses are the runtime event names; channel message IDs are the
890
+ message registry names. `send` and `receive` remain relative to the application
891
+ described by AsyncAPI:
892
+
893
+ ```typescript
894
+ import {
895
+ EVENT_NAMES,
896
+ MessageContractValidationError,
897
+ parseReceiveMessage,
898
+ } from './contracts/realtime/async';
899
+
900
+ const booking = parseReceiveMessage(EVENT_NAMES.BOOKING_UPDATED, socketPayload);
901
+ // booking is validated before application code sees it.
902
+ ```
903
+
904
+ Generated `EventPayloadMap`, `SendEventPayloadMap`, and
905
+ `ReceiveEventPayloadMap` map event-name literals to validated output types.
906
+ `EventPayloadInputMap` describes values accepted by the schemas, while
907
+ `MessageEvent` is a discriminated `{ eventName, payload }` union.
908
+ `eventRegistry` exposes the operation IDs, channel IDs, message names,
909
+ directions, reply ownership, and executable schema for adapter code.
910
+
911
+ `parseMessage()` accepts transport data as `unknown`. It returns validated data
912
+ or throws `UnknownMessageEventError` /
913
+ `MessageContractValidationError`. It accepts arbitrary runtime string event
914
+ names so unknown transport events fail through the typed error category rather
915
+ than requiring an unsafe cast. For duplex addresses, use
916
+ `parseSendMessage()` / `parseReceiveMessage()` to select the direction-specific
917
+ message subset; the generated send and receive maps never widen each other.
918
+ `defineMessageFixture()` and `defineNamedMessageFixture()` reuse the same
919
+ schemas so mock payloads cannot silently drift. Fixture helpers are deliberately
920
+ excluded from the primary production barrel and remain available through an
921
+ explicit test-only import:
922
+
923
+ ```typescript
924
+ import { defineMessageFixture } from './contracts/realtime/async/fixtures';
925
+ ```
926
+
927
+ The target supports required/optional and nullable/non-null fields, enums,
928
+ string formats including UUID/date/date-time, arrays, object `allOf`,
929
+ additional-properties policies, and local/multi-file `$ref` graphs covered by
930
+ the normalized AsyncAPI path. Numeric- or punctuation-leading authored keys
931
+ receive deterministic valid TypeScript identifiers without changing their wire
932
+ event/message names. Channel-based replies preserve explicit message subsets
933
+ or default to all messages on the reply channel. Dynamic reply addresses fail
934
+ generation with an explicit limitation because they do not identify one stable
935
+ registry event. Generated code imports only `zod/v4`; it has no
936
+ Socket.IO, WebSocket, NATS, NestJS, RxJS, React, or TanStack dependency.
937
+
938
+ Use `asyncapi-nats` instead when the generated consumer also needs NATS
939
+ subjects, request/reply interfaces, and client/server adapters.
276
940
 
277
941
  ## NATS contract — one `nats/index.ts` per async schema service
278
942
 
@@ -349,8 +1013,8 @@ Each named enum file exports:
349
1013
  importable source of truth. This also works for multi-file specs and external
350
1014
  `$ref` fragments: bundling runs with `--xOrigin`, and the generator resolves
351
1015
  dereferenced copies back to their named component.
352
- - `nats/index.ts` re-exports the folder (`export * from './enums';`); import
353
- constants from the service NATS barrel instead of deriving them from Zod
1016
+ - The generated `nats/index.ts` entry point re-exports the enum contract
1017
+ (`export * from './enums';`); import constants from that service entry point instead of deriving them from Zod
354
1018
  internals such as `Schema.shape.field.enum`.
355
1019
  - Anonymous inline property enums stay inline `z.enum([...])`. Promote an enum
356
1020
  to `components/schemas` when services need its constants.
@@ -368,9 +1032,9 @@ contracts/shared/
368
1032
  ```
369
1033
 
370
1034
  Generated schemas are strict wire schemas: `createdAt: z.string().datetime()`
371
- expects an ISO string, and nullable columns are `.optional()`, which accepts
372
- `undefined` but not `null`. A raw `RecipeSchema.parse(entity)` therefore throws
373
- on a real `Date` and on a `null` database column. `toContract` normalizes an
1035
+ expects an ISO string, and nullable fields accept `null` only when the source
1036
+ contract declares them nullable. A raw `RecipeSchema.parse(entity)` therefore
1037
+ throws on a real `Date` or an undeclared `null`. `toContract` normalizes an
374
1038
  already-contract-shaped object, then validates it:
375
1039
 
376
1040
  ```typescript
@@ -379,31 +1043,33 @@ export function toContract<Schema extends z.ZodTypeAny>(
379
1043
  schema: Schema,
380
1044
  source: unknown,
381
1045
  ): z.infer<Schema> {
382
- // Reads only the schema's own keys (so entity getters are honoured), converts
383
- // Date -> ISO string, drops nullish at every depth (so nullable columns satisfy
384
- // .optional()), then parses.
1046
+ // Reads only the schema's own keys (so entity getters are honoured), omits
1047
+ // only undefined, preserves explicit null, and then parses.
385
1048
  }
386
1049
  ```
387
1050
 
388
- Use it in a service so the response mapper is a one-liner:
1051
+ Use it after an application-owned projector has made temporal and semantic
1052
+ decisions explicit:
389
1053
 
390
1054
  ```typescript
391
1055
  import { HttpSchemas } from 'SUMR Schemas module/recipes';
392
1056
  import { toContract } from 'SUMR Schemas module/shared';
393
1057
 
394
1058
  toResponse(recipe: Recipe): RecipeResponse {
395
- return toContract(HttpSchemas.ZodContracts.RecipeSchema, recipe);
1059
+ return toContract(HttpSchemas.ZodContracts.RecipeSchema, {
1060
+ ...recipe,
1061
+ createdAt: recipe.createdAt.toISOString(),
1062
+ });
396
1063
  }
397
1064
  ```
398
1065
 
399
- `toContract` is the send-side counterpart to the SDK's receive-side `decodeJson`
400
- seam: Kontract owns the mechanical wire transform in both directions, so
401
- consumers stop rewriting it.
1066
+ `toContract` owns only structural contract validation. It does not own temporal
1067
+ or business conversion.
402
1068
 
403
1069
  Keep domain knowledge in your code. `toContract` is a pure function of the
404
- schema; renamed fields, computed/projected fields, enum-case translation, and
405
- non-`Date` custom types (`Decimal`, `bigint`, ...) are not derivable from the
406
- wire schema and stay in the entity. Expose computed fields as entity getters —
1070
+ schema; renamed fields, computed/projected fields, enum-case translation,
1071
+ temporal conversion, and custom types (`Date`, `Decimal`, `bigint`, ...) are not
1072
+ derivable from the wire schema and stay in the application projector. Expose computed fields as entity getters —
407
1073
  `toContract` triggers top-level getters by property access, and nested
408
1074
  projections must be returned as plain objects by the parent getter:
409
1075
 
@@ -424,8 +1090,9 @@ not per-schema code. NATS consumers on the same output root import the same
424
1090
 
425
1091
  ## Consuming in NestJS
426
1092
 
427
- - Use `http/zod` `${Name}Dto` classes when you want `nestjs-zod` request/response
428
- validation.
1093
+ - Use `http/zod` `${Name}Dto` constructors when you want `nestjs-zod`
1094
+ request/response validation. Object outputs are classes; non-object, union,
1095
+ alias, and nullable outputs are constructor constants.
429
1096
  - Use per-service `http/swagger.ts` and the shared
430
1097
  `shared/http/decorators/api-doc.ts` helper when a controller should prove
431
1098
  runtime Swagger/API schema behavior from generated metadata.
@@ -436,7 +1103,8 @@ not per-schema code. NATS consumers on the same output root import the same
436
1103
  without a separate frontend SDK target.
437
1104
  - Use the generated `*Client` classes and `SUBJECTS` for NATS — do not
438
1105
  hand-write subjects or message shapes.
439
- - Each generated directory has a barrel `index.ts` for local aggregation only.
1106
+ - Kontract creates generator-owned `index.ts` entry points for local aggregation. These generated
1107
+ contract surfaces do not permit authored internal barrels or wildcard exports under `src/`.
440
1108
  - Regenerate (`sumr kontract generate`) after any spec change; unchanged
441
1109
  work items are skipped with `.sumr-cache/kontract` manifests when source,
442
1110
  config, generator, and output hashes still match.