# schema

Derived additions: `has_*` presence facts, `*_json` literals, `fields[].storage.primary_key` and field-link `generated`. See [derived.md](/pack-builders/context/derived).

## Intent

A named structured semantic object used for entities, DTOs, requests/responses, persistence models, and reusable domain structures.

Exact selection subject:

```yaml
subject: schema
```

The current Runtime IR is evidence, not authority. Target improvements needed for a usable template contract are called out explicitly.

## Scope envelope

| Scope                 | Context                              |
| --------------------- | ------------------------------------ |
| `each`                | `schema: SchemaContext`              |
| `all`                 | `schemas: SchemaContext[]`           |
| collection candidates | `collects.group`, `collects.feature` |

For `collects.<dimension>`, the singular collector is added beside the plural selected-subject array. A collector is valid only when ownership is semantically provable.

## Context tree

This file defines only schema-local context. Shared/nested contexts are referenced, not duplicated.

| Context path                             | Type                                                                                   | Meaning / template use                                                                                                                                                                         |
| ---------------------------------------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `schema.id`                              | `string`                                                                               | Opaque stable semantic identity.                                                                                                                                                               |
| `schema.name`                            | `NameContext`                                                                          | See shared `NameContext` in [README.md](/pack-builders/context/overview).                                                                                                                      |
| `schema.description`                     | `string\|null`                                                                         | Human semantic description.                                                                                                                                                                    |
| `schema.tags`                            | `string[]`                                                                             | Semantic classifiers.                                                                                                                                                                          |
| `schema.explanations`                    | `ExplanationContext[]`                                                                 | See [README.md](/pack-builders/context/overview).                                                                                                                                              |
| `schema.group`                           | `SemanticLinkContext\|null`                                                            | Owning group link; see [README.md](/pack-builders/context/overview).                                                                                                                           |
| `schema.feature`                         | `SemanticLinkContext\|null`                                                            | Canonical owning feature, when present.                                                                                                                                                        |
| `schema.role`                            | `SchemaRole\|null`                                                                     | One of `entity`, `value`, `request`, `response`, `command`, `query`, `filter`, `event`, `view-model`, `config`.                                                                                |
| `schema.abstract`                        | `boolean`                                                                              | Whether the schema contributes meaning without direct concrete identity.                                                                                                                       |
| `schema.extends`                         | `SchemaContext\|null`                                                                  | Full context of the base schema from this file, demand-resolved.                                                                                                                               |
| `schema.source`                          | `SchemaSourceContext\|null`                                                            | The projection this schema derives from: `schema` link, `purpose` (`read\|create\|edit\|query\|custom`), `fields[]` as `{name, source}`, and `policies`. `null` for original schemas.          |
| `schema.fields`                          | `SchemaFieldContext[]`                                                                 | Effective fields ordered by name: local fields, projected fields (with their optional/nullable/array overrides) and fields inherited through `extends`.                                        |
| `schema.facets.storage`                  | `SchemaStorageContext\|null`                                                           | Storage semantics unique to schema.                                                                                                                                                            |
| `schema.facets.storage.namespace`        | `string\|null`                                                                         | Effective storage namespace: the schema's own, else the nearest group default.                                                                                                                 |
| `schema.invariants`                      | `SchemaInvariantContext[]`                                                             | Effective invariants: inherited, carried over from a projection source, then local.                                                                                                            |
| `schema.invariants[].name`               | `NameContext`                                                                          | Stable invariant name, for constraint names such as `chk_cart_item_quantity_positive`.                                                                                                         |
| `schema.invariants[].message`            | `string\|null`                                                                         | Optional error message.                                                                                                                                                                        |
| `schema.invariants[].rule`               | `ExpressionContext`                                                                    | The rule's full expression, demand-resolved.                                                                                                                                                   |
| `schema.invariants[].form.kind`          | `comparison\|all\|any\|opaque`                                                         | The rule's simplest fixed-depth shape, computed by the Engine. `opaque` means the rule has no simple form.                                                                                     |
| `schema.invariants[].form.comparisons[]` | `InvariantComparisonContext[]`                                                         | One entry for `comparison`, several for `all`/`any`, none for `opaque`.                                                                                                                        |
| `…comparisons[].operator`                | `equal\|not-equal\|less-than\|less-than-or-equal\|greater-than\|greater-than-or-equal` | Comparison operator.                                                                                                                                                                           |
| `…comparisons[].left` / `.right`         | `InvariantOperandContext`                                                              | `kind` is `field`, `literal` or `arithmetic`. `field` is a `NameContext` for a top-level field; `value` is the literal; `operator` and `terms[]` describe arithmetic over fields and literals. |
| `schema.examples`                        | `CanonicalValue[]`                                                                     | Whole-schema examples.                                                                                                                                                                         |

### SchemaFieldContext

| Context path                   | Type                        | Meaning / template use                                                                                    |
| ------------------------------ | --------------------------- | --------------------------------------------------------------------------------------------------------- |
| `schema.fields[].name`         | `NameContext`               | Field identity; shared context from [README.md](/pack-builders/context/overview).                         |
| `schema.fields[].value`        | `SemanticValueContext`      | Exact field-value contract from [shared/semantic-value.md](/pack-builders/context/shared-semantic-value). |
| `schema.fields[].optional`     | `boolean`                   | Field-local optional presence.                                                                            |
| `schema.fields[].nullable`     | `boolean`                   | Field-local nullable value.                                                                               |
| `schema.fields[].array`        | `ArrayBoundsContext\|null`  | Field-local array cardinality.                                                                            |
| `schema.fields[].default`      | `DefaultValueContext\|null` | Canonical value or expression default.                                                                    |
| `schema.fields[].mutation`     | `create-only\|system\|null` | Mutation rule.                                                                                            |
| `schema.fields[].query`        | `FieldQueryContext\|null`   | Filter/sort/search/nesting capabilities.                                                                  |
| `schema.fields[].sensitive`    | `boolean`                   | Sensitive-data marker.                                                                                    |
| `schema.fields[].policy.read`  | `PolicyContext\|null`       | Full policy context from [policy.md](/pack-builders/context/policy), demand-resolved.                     |
| `schema.fields[].policy.write` | `PolicyContext\|null`       | Full policy context from [policy.md](/pack-builders/context/policy), demand-resolved.                     |
| `schema.fields[].relation`     | `RelationContext\|null`     | Field-local relation semantics.                                                                           |
| `schema.fields[].related`      | `RelatedContext\|null`      | Derived/inverse relation semantics.                                                                       |
| `schema.fields[].sources`      | `FieldSourceContext[]`      | Field-local value/resolve/options source bindings.                                                        |

A reusable property's constraints are therefore reached naturally through the field value, for example:

```text
schema.fields[].value.property.primitive.constraints.length
schema.fields[].value.property.primitive.constraints.range
schema.fields[].value.property.primitive.constraints.precision
schema.fields[].value.property.primitive.constraints.scale

schema.fields[].value.property.enum.values

schema.fields[].value.property.temporal.constraints

schema.fields[].value.property.composite.fields
```

Those subtrees are not redefined here; they are the full matching property contexts from their subject files.

## Usage rules

- `fields` is the effective generation view; templates should not rebuild inheritance/derivation semantics.
- `role` says what the schema does; `source` says where its shape came from.
- Storage stays under `facets.storage`.

## Runtime IR implications to audit

- Resolve each field through `SemanticValueContext`; property/schema references must expose their authoritative full context contract without templates parsing pointer prefixes.

## Template example — Handlebars / TypeScript DTO

```hbs
{{#each file.dependencies}}
{{#if symbol}}
import { {{symbol}} } from "{{path.relative}}";
{{/if}}
{{/each}}

export interface {{file.symbol}} {
{{#each schema.fields}}
  {{name.camel}}{{#if optional}}?{{/if}}:
  {{renderFieldValue value ../file.dependencies}}{{#if nullable}} | null{{/if}};
{{/each}}
}
```

The example uses semantic context for field meaning and `file` metadata for exact generated representation identity. `renderFieldValue` is a pack-owned macro that resolves generated schema/property types through `file.dependencies` instead of guessing their symbols from semantic casing. Any `renderType`/`render_type` helper shown is a pack-owned macro/partial consuming the documented `TypeContext`, not hidden Dryv context.

## Audit questions

- Is `schema.source` clearer than the current `projection` concept?
- Do proof packs need roles beyond request/response?
- Do templates need declared-vs-effective fields, or is effective meaning enough?

## Facet cardinality

Initial storage cardinality is singular:

```text
schema.facets.storage  0..1
```

One schema has at most one canonical storage mapping in the initial contract. Multiple target-specific physical representations belong to pack generation, not multiple semantic storage facets.
