Metadata-Version: 2.5
Name: dryv
Version: 0.1.0
Summary: The standalone Dryv generation engine
License: Apache-2.0
Requires-Python: >=3.11
Requires-Dist: pathspec<2,>=1.1
Requires-Dist: pydantic<3,>=2.11
Requires-Dist: pyyaml<7,>=6.0.3
Description-Content-Type: text/markdown

# Dryv Engine

The Dryv Engine is the standalone Python Runtime package that owns Canonical Dryv meaning, validation, planning, and generation behavior.

It operates on supplied project/runtime data rather than requiring direct access to a user's filesystem. Generation returns validation results, plans, diagnostics, traces, and generated artifact contents for a caller to inspect or apply.

## Architecture

```text
src/dryv/
├── contracts/
│   ├── authoring/
│   ├── engine/
│   ├── generation/
│   └── semantic/
└── modules/
    ├── authoring/
    ├── execution/
    ├── generation/
    └── semantic/
```

`contracts` defines the known strongly typed Dryv documents and public Engine boundaries.

- `contracts/authoring` owns Runtime-side Authoring Protocol contracts.
- `contracts/semantic` owns canonical `dryv.ir/v1alpha1` meaning.
- `contracts/generation` owns usage, pack, template, and projected-context contracts.
- `contracts/engine` owns typed Engine operations, workspaces, results, tracing, and environment protocols.

`modules` contains Runtime behavior:

- `modules/authoring` ingests and materializes authored Runtime IR.
- `modules/semantic` loads, validates, inspects, and serializes canonical meaning.
- `modules/generation` selects packs, plans artifacts, analyzes templates, projects requested context, and renders output.
- `modules/execution` handles explicit host environment requirements.

The Engine does not create a second semantic model outside canonical contracts. New root folders require a new high-level capability, not merely a new implementation stage.

## Typed-contract rule

Known Dryv structures must always be represented by explicit typed classes.

Free-form dictionaries such as `dict[str, object]` or `dict[str, Any]` must not represent known IR items, pack definitions, usage definitions, plans, artifacts, or established protocol shapes.

Untrusted YAML/JSON/JSONL/API data may be free data only at the parsing boundary. Successful parsing returns a known typed contract before the rest of Engine uses it.

Typed registries such as `dict[str, Schema]` remain valid because keys are dynamic authored identities while values have a closed contract.

## Engine connection contracts

A caller supplies a typed virtual workspace rather than granting Engine ambient filesystem authority:

```text
client files
    ↓
VirtualWorkspace
    ↓
EngineProject(entrypoint="dryv.yaml")
    ↓
ValidateRequest | PlanRequest | GenerateRequest
    ↓
Engine
```

A virtual workspace can contain usage, Runtime IR, packs, templates, and other explicit resources. Logical paths are project-relative and may not escape through traversal.

The API owns transport. Engine owns interpretation. The API must not independently reimplement Dryv loading, semantic selection, or planning rules.

Generation returns data rather than mutating a caller's real filesystem.

## Runtime IR contracts

`dryv.contracts.semantic` includes typed contracts for:

- document metadata and groups;
- portable internal JSON Pointer references;
- nine reusable Property registries: primitive, enum, composite, literal, union, record, tuple, generic, and temporal;
- direct `unknown` and `dynamic` field targets;
- a closed recursive `TypeExpression` model for nested semantic values;
- Schemas and single-parent inheritance;
- Policies, Failures, Events, and Operations;
- explicit execution semantics such as rate limits, cache, transactions, retries, idempotency, audit, and invalidation;
- neutral storage semantics;
- Sources;
- Views;
- Workflows;
- Exposures, Surfaces, Presentations, Features, and Applications.

The canonical Property registry has no generic `properties.types` bucket and no `properties.unknowns` / `properties.dynamics` registries.

### Primitive properties

Primitive reusable definitions are string, number, and boolean.

String meaning is explicit:

```yaml
Email:
  type: string
  kind: format
  format: email

DisplayName:
  type: string
  kind: text
  length:
    max: 120
```

Numeric integer/decimal intent is expressed under `type: number`:

```yaml
Count:
  type: number
  kind: integer
  format: non-negative-integer
  range:
    min: 0
```

`integer` is not a primitive `type`.

### Temporal properties

Temporal meaning is first-class under `properties.temporal` rather than encoded as a string format.

Canonical temporal kinds are:

```text
date
time
date-time
instant
zoned-date-time
duration
interval
year-month
month-day
```

Canonical examples:

```text
date              2026-09-11
time              12:30:00
date-time         2026-09-11T12:30:00
instant           2026-09-11T09:30:00.000Z
zoned-date-time   2026-09-11T12:30:00.000+03:00[Africa/Nairobi]
year-month        2026-09
month-day         --09-11
duration          PT90S
```

`date-time` is local civil time. `instant` is an absolute UTC instant. `zoned-date-time` preserves both numeric offset and IANA timezone identity and Runtime verifies that they agree.

`instant` and `zoned-date-time` require explicit precision.

Intervals reference another temporal point property and values use explicit `start`/`end` points. An interval range constrains elapsed duration. Fixed duration-range comparisons reject year/month components because their elapsed length depends on calendar context.

Dynamic `now`, relative temporal values, and past/future duration rules remain explicit typed structures. Temporal context uses canonical `time_zone` and IANA timezone identifiers.

Recurring civil schedules remain structural rather than being collapsed into UTC. For example, a daily schedule retains local `hour`, `minute`, and `time_zone`.

### Unknown and dynamic

`unknown` and `dynamic` are direct field targets only. They are not reusable properties and are not recursive `TypeExpression` variants.

```yaml
payload:
  kind: unknown
metadata:
  kind: dynamic
```

### Reusable unions

Reusable unions are named and explicitly discriminated:

```yaml
Identifier:
  discriminant: identifierKind
  members:
    byUuid:
      kind: reference
      $ref: "#/properties/primitives/Uuid"
    bySlug:
      kind: reference
      $ref: "#/properties/primitives/Slug"
```

The discriminant and member names are authored identifiers and are preserved exactly.

## Operations and interfaces

An Operation describes semantic behavior independently of transport:

```text
subjects
inputs
outputs
failures
emits
access
execution
```

HTTP, WebSocket, event, and schedule transport semantics are represented by typed Exposures. User-experience placement is represented by Surfaces and Presentations. Those interface contracts reference Operations rather than redefining Operation meaning.

Execution uses canonical snake_case fields such as `rate_limit` and `max_attempts`.

## Sources

A Source describes where reusable values are obtained. It identifies a source Operation, named output, value projection, and zero or more label projections.

Runtime validates the Operation/output relationship and validates projections when the output structure can be resolved statically.

## Views

Views can reference Schemas, Operations, Sources, Policies, and Events. Runtime validates their invocation and relationship contracts rather than relying on hidden UI conventions.

## Runtime semantic validation

Runtime validation includes recursive value semantics and cross-registry relationships.

It checks, among other things:

- unresolved and wrong-kind references;
- group and Schema cycles;
- unproductive reusable-property cycles;
- generic application targets and arity;
- invalid record key definitions;
- primitive and temporal constraints;
- invalid defaults and examples;
- discriminated reusable Union values;
- Property lifecycle references;
- Operation relationship references;
- Source Operation/output/projection relationships;
- View, Workflow, Exposure, Surface, Presentation, Feature, and Application relationships.

Validation is a gate. Planning and generation must not continue from invalid canonical meaning.

Warnings do not make Runtime IR invalid. Error diagnostics do.

## Authoring ingestion

The Runtime Authoring Ingestion module consumes the versioned Dryv Authoring Protocol and reconstructs the same `DryvIR` classes used for serialized IR.

Canonical streamed Property record kinds are:

```text
property-primitive
property-enum
property-composite
property-literal
property-union
property-record
property-tuple
property-generic
property-temporal
```

There are no dotted compatibility record names and no authoring-only Property semantic model.

Ingestion validates ordering, identity, sequence numbers, item counts, digests, protocol negotiation, and then performs full Runtime semantic validation before accepting a document.

## Pack contracts and planning

A pack explicitly declares renderer requirements, options, bindings, destinations, canonical selections, bounded context projections, templates, artifact paths, and dependencies.

Packs may select every explicit Runtime Property registry, including `properties.temporal`, as well as other canonical registries such as `schemas`, `operations`, `sources`, and `exposures`.

Context source values use canonical controlled vocabulary such as `selected` and `selected-id`.

Renderer context is a bounded semantic view over Runtime IR:

- canonical `$ref` values remain present for traceability;
- referenced targets are exposed through bounded `resolved` views;
- reference targets are cached per planning session;
- recursive reference expansion is cycle-safe and depth-limited;
- selected items and named children receive deterministic naming variants;
- the top-level `dryv` context field is reserved for Engine-owned artifact, symbol, and import metadata.

Pack artifact path and symbol templates can use selected naming variables such as
`{selected.name.kebab}`, `{selected.name.pascal}`, and
`{selected.name.groupKebab}`.

Artifacts may explicitly declare generated symbols and import requirements. The Engine
resolves those requirements into provider artifacts, relative module paths, collision-safe
local symbol names, and planned artifact dependencies. Target-language import/export
syntax remains the responsibility of the template.

No Runtime or pack data is injected through undocumented conventions. Engine-owned
renderer metadata is part of the pack context contract and remains inspectable.

## Usage contracts

Usage connects serialized Runtime IR or authored input with active packs, pack sources, options, bindings, logical destinations, and generation behavior.

Git credentials remain the responsibility of normal Git tooling and are not copied into Dryv contracts.

## Loader and serialization

`dryv.modules.semantic.loading` is the serialization boundary for known Dryv documents.

Successful loading returns typed contracts such as:

```text
DryvIR
DryvPack
DryvUsage
```

The loader detects document family from the explicit version field rather than filename.

Current contract versions include:

```text
dryv.ir/v1alpha1
dryv.pack/v1alpha1
dryv/v1alpha1
```

Canonical Runtime IR supports YAML/YML, JSON, and JSONL representations. JSONL uses the same canonical record vocabulary as Authoring ingestion.

Serialization uses canonical Dryv keys and reserved aliases such as `$ref`. Authored registry keys remain exactly authored.

## Current-version rewrite rule

This repository is still pre-release. The current `v1alpha1` contract is rewritten directly when the semantic model changes.

Runtime must not:

- accept retired Property registries as aliases;
- translate old primitive shapes into new ones;
- accept old camelCase canonical keys;
- accept dotted old Authoring/JSONL record kinds;
- preserve an old parser branch “for compatibility”.

Tests should assert rejection of obsolete shapes where the boundary is important.

## Authority boundary

Engine owns semantic authority but deliberately does not own ambient machine authority.

Engine must not:

- read arbitrary host filesystem paths;
- install packages;
- execute arbitrary shell commands;
- use caller Git credentials directly;
- mutate the user's real project;
- implement API HTTP/WebSocket transport;
- embed Jinja or Handlebars rendering implementations.

Those boundaries keep the same Engine usable by CLI, editor, web, agent, or remote clients.

## Development with uv

From `engine/python/engine/`:

```bash
uv sync
uv run ruff format .
uv run ruff check --fix .
uv run mypy
uv run pytest
uv build
```

After the fix-mode gate is clean, run:

```bash
uv run ruff check .
```

Do not bypass type/lint errors by replacing known contracts with free dictionaries or broad `Any` values.

## Public capability boundary

Conceptually:

```text
validate(ValidateRequest) -> ValidationResult
plan(PlanRequest) -> PlanResult
generate(GenerateRequest) -> GenerationResult
capabilities() -> EngineCapabilities
```

`EngineCapabilities.workflows` is the product-level semantic capability surface. It currently advertises:

```text
project.validate
project.plan
project.generate
```

Primitive operations, workspace file kinds, transport versions, and environment-operation support remain protocol negotiation facts. Clients must not present those primitives as the answer to “what can Dryv do?”.

The API may expose these capabilities over different transports, but Engine-facing semantics remain the same.

## Canonical sample Runtime IR

The Engine owns reusable semantic test input under `dryv.resources.canonical_ir`.

`load_canonical_ir_scenario("complete")` loads the packaged sample through the normal Runtime IR loader and runs normal semantic validation before returning it. `canonical_ir_coverage_gaps()` compares that sample against the current pack selection vocabulary so a newly added selectable subject, role, facet, or surface kind cannot silently remain absent from the canonical pack-test input.

This corpus exists so standalone pack validation/testing can use representative Engine-owned Runtime IR without requiring every pack author to maintain a separate `dryv.ir.yaml`.

## Applications, stores and migrations

Read the [execution cookbook](../../../../.tasks/docs/guide/applications-stores-and-evolution.md) for app-first composition, independent roots, selected generation, separate stores, explicit checkpoint approval and PostgreSQL releases. Code/docs and typecheck/formatting gates precede the separately recorded test/live validation phase.

## PostgreSQL placement

Schema storage facets declare typed `partitioning` as canonical Runtime IR meaning.
TypeScript and Python Author SDKs compile the same declaration, including composite keys
and bounded calendar partition series. Engine validates list, range and hash layouts and
key compatibility, projects layouts to explicitly capable persistence packs and tracks
partition topology in reviewed migration snapshots. Pack templates own SQL; the CLI
owns PostgreSQL observation and execution. See the [store/evolution guide](../../../../.tasks/docs/guide/applications-stores-and-evolution.md#postgresql-partition-layouts).

PostgreSQL descriptions travel in typed migration `comments` separately from structural
snapshots. The Engine plans `set-comment` changes, and SQL packs render them. Store namespace
metadata is explicit; schema/field/property/relation/index descriptions provide supported
object descriptions. The Client observes catalog comments and verification compares only
managed descriptions, including explicit null removals. See the repository migration cookbook
for ownership, drift behavior and advanced-constraint limitations.

## PostgreSQL integrity evolution

The migration adapter lowers homogeneous scalar enum properties to typed column mappings
and CHECK constraints. Nullable enum fields explicitly admit null. Schema invariants support
local fields, exact scalar literals, comparisons, arithmetic and nested AND/OR/NOT expressions.
Equality uses null-safe distinctness; ordering and nullable boolean predicates use explicit
false fallbacks so SQL UNKNOWN cannot silently bypass a rule. Clock-dependent or non-local
expressions remain rejected with a reviewed-mapping diagnostic.

Snapshots carry named `checks` with typed expression nodes and exact numeric literal text,
not unchecked SQL. Packs receive bounded flat tokens and own every SQL operator, literal and
identifier. Initial/additive check generation is deterministic. Removing or replacing a check
requires an explicit reviewed intervention; the resulting constraint is validated by PostgreSQL.
The Client parses the supported PostgreSQL catalog grammar into the same typed meaning,
rejecting unsupported casts, raw nullable comparisons and custom SQL instead of treating them
as equivalent. Verification detects changed rules, absent checks and unknown declarations.
Rules support at most 64 levels and 4096 nodes.

Named composite `references` and `same-as` constraints lower to foreign keys and required
unconditional target uniqueness. Required companion fields permit the composite key to enforce
the scalar relation as well as its route/owner; nullable companions never silently weaken that
relation. Declared lifecycle actions are preserved and conflicting actions fail explicitly.
TypeScript `.describeConstraint(name, text)` and Python constraint `description=` arguments
preserve meaningful descriptions; `.invariant(..., description=...)` describes its generated
CHECK constraint. Descriptions can change or be removed independently of structural checks.
Advanced exclusion and acyclic rules still require their existing explicit adapter mapping.

Partition observation includes per-default-child row presence as environment evidence,
separate from structural snapshots. Additive routes beside an observed empty default can be
generated directly. A populated default, or missing row evidence on a populated table, retains
the verified-relocation intervention gate. This does not authorize implicit data movement.

Persistence projections include typed preorder selections and mandatory composite join companions. Packs must preserve every companion when joining partitioned references. The optional `schema.entity.types` slot covers entity-role schemas owned by another type pack; general `schema.types` providers can consume it without generating duplicate entities.
