# Packs reference

A pack selects IR subjects, discovers templates from its filesystem, and declares generated identity: names, paths, symbols, imports and exports. Working examples: `sdk/_examples/packs/fastapi-backend`, `sdk/_examples/packs/nestjs`, `sdk/_examples/packs/dart-client-sdk`.

Editor validation:

```yaml
# yaml-language-server: $schema=../../../schemas/dryv.pack.schema.json
```

## Document

```yaml
version: dryv.pack/v1alpha1
key: examples.fastapi-backend # [A-Za-z0-9][A-Za-z0-9._-]*
source: templates # template root: a directory, or "."
info:
  title: FastAPI Backend
  version: 0.1.0
  description: …
  purpose: backend # optional discovery metadata
  summary: FastAPI routes and models.
  languages: [python]
  frameworks: [fastapi]
  tags: [api]
plugins: # renderer providers only
  - name: jinja
    version: ^1.0 # optional
    extensions: [.j2] # optional; defaults to what the provider advertises
inputs: {} # typed project configuration
selections: {} # what drives generation
templates: {} # what gets generated
```

`info` also feeds pack discovery, such as the catalogue the `dryvcode/packs`
repository publishes. It may hold `purpose`, `summary`, `languages`,
`frameworks` and `tags`, all lowercase words except `summary`. The Engine
validates the manifest itself; no selection, binding, context or rendering
depends on a separate catalogue block.

External tools such as formatters, package managers and runtimes are **not** renderer/plugin requirements. Pack and project dependency/action behavior is defined by generation actions.

## Inputs

```yaml
inputs:
  package_name: { type: string, required: true, description: Package name }
  emit_validation: { type: boolean, default: true }
  tags: { type: "string[]", default: [] }
```

The types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`. A project sets values in `dryv.yaml` under `packs.<name>.inputs`. Unknown keys, type mismatches and missing required values fail before planning. Templates read only `pack.inputs.<key>`.

Dryv-owned YAML keys and pack input names use `snake_case`. User-authored
template, selection and destination keys should preferably be one word, or
kebab-case when two words are needed, such as `entity-index`. This recommendation
improves readability but is not enforced; Dryv preserves those identifiers.

## Selections

```yaml
selections:
  publicCreates:
    subject: operation
    filter:
      all: { tags: [public] }
      any: { role: [create, update] }
      not: { tags: [deprecated] }
    scope: each
```

**Subjects:** `property.{primitive,enum,composite,literal,union,record,tuple,generic,temporal}`, `schema`, `expression`, `policy`, `failure`, `event`, `operation`, `view`, `view.part`, `workflow`, `surface`. `application`, `group` and `feature` are not subjects; they're bounded metadata.

**Filters** decide membership only (decision 0006). `all` means every predicate matches, `any` means at least one does, `not` means none do. `role`, `facet` and `kind` take a single value or a list. `tags` is a non-empty list.

| Classifier | Contract allows                                                                                                                                                                                                                                                                                                                                                                                                  | Implemented today |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |
| `tags`     | all subjects                                                                                                                                                                                                                                                                                                                                                                                                     | yes               |
| `role`     | `schema`: entity, value, request, response, command, query, filter, event, view-model, config. `operation`: create, update, delete, detail, list, search, validate, transform, action. `view`: list, detail, form, dashboard, wizard, search. `policy`: authentication, authorization, ownership, rate, feature-flag. `event`: domain, integration, notification. `workflow`: saga, process, approval, scheduled | yes               |
| `facet`    | `schema`: storage. `operation`: http, websocket, schedule                                                                                                                                                                                                                                                                                                                                                        | All listed facets |
| `kind`     | `surface`: web, mobile, desktop, cli, embedded                                                                                                                                                                                                                                                                                                                                                                   | yes               |

An unsupported classifier fails planning with `planner.selection.classifier_unavailable`. It never silently matches nothing.

Filters never support IDs, include/exclude, IR paths, names, counts, comparisons or structural inspection.

**Scopes** decide how matches become invocations:

| Scope              | Invocations                | With 0 matches        |
| ------------------ | -------------------------- | --------------------- |
| `each`             | one per subject            | 0                     |
| `all`              | one, holding every subject | 1, with an empty list |
| `collects.feature` | one per owning feature     | 0                     |
| `collects.group`   | one per owning group       | 0                     |

## Templates

The kind of template is inferred from its shape. There's no `mode` field.

```yaml
templates:
  model: # selection-driven: top-level $ref → #/selections/*
    $ref: "#/selections/models"
    output:
      name: $(subject.name.snake)
      path: [$(feature.name.kebab)]
      symbol: $(subject.name.pascal) # primary symbol
      symbols: { model: …, identifier: … } # optional named symbols
    imports:
      - $ref: "#/templates/enum" # producers that may satisfy references

  package: {} # global: no $ref and no exports

  models-index: # export/barrel: has exports
    barrel: all # default; or `each`
    exports:
      - $ref: "#/templates/enum"
      - $ref: "#/templates/model"
```

- A top-level `$ref` and `exports` can't appear together. `output.symbol` names the primary symbol and `output.symbols` names additional keyed symbols; a template may declare both. A template that `provides` a slot must declare `output.symbol`.
- **Interpolation** is finite: `$(subject|feature|group.name.<variant>)`, where the variant is one of `raw`, `local`, `qualified`, `camel`, `pascal`, `snake`, `kebab`, `constant`, `title`. A root must be structurally available for the scope. For example, `feature` doesn't exist under `scope: all`.
- `output.destination` names an output slot. Usage maps it with `packs.<key>.destinations.<slot>`; templates without one write to the activation's `destination`. A slot no template declares (`usage.pack.destinations.unknown`) or a declared slot left unmapped (`usage.pack.destinations.missing`) fails planning. Actions run on each file in the destination it is written to; the pack's dependencies install in its default destination.
- `output.name` must be dynamic; a static value only warns. Filenames use it through `$(name)`. `output.path` holds dynamic directory segments, one segment per item. `output.symbol(s)` can be static or dynamic, and must be declared, because rendered code is never parsed.
- `imports` lists _eligible producers_. A dependency is created only when a consumer subject references a subject that the producer represents. An aggregate adds `members: true` to also depend on the producer files that represent its own subjects, for example a group module importing its feature modules: `imports: [{ $ref: '#/templates/feature', members: true }]`. `members` is rejected on `exports`. `transitive: true` (on template or `#/needs/<slot>` imports) links every subject the consumer's references reach, following schemas and projection sources, for example a use case reaching the entity behind its response's read projection; a transitive slot import links what the bound pack represents and does not require it to cover every reached subject.
- `exports` consumes already-planned producer artifacts. `barrel: all` produces one aggregate. `barrel: each` keeps the producers' existing partitions and never creates a new grouping.

## Ownership: managed and scaffold

Ownership is decided per resource by the template filename, not in `dryv.pack.yaml`. A terminal `.sf` control suffix, after the renderer suffix is removed, marks the file as a scaffold; everything else is managed:

```text
templates/src/{usecase}/$(name).usecase.ts.sf.hbs   -> scaffold  src/<feature>/<name>.usecase.ts
templates/src/{entity}/$(name).entity.ts.hbs        -> managed   src/<feature>/<name>.entity.ts
templates/README.md.sf                              -> scaffold  README.md
```

One selection or template can therefore produce both managed and scaffold files. A template-level `ownership:` key is rejected.

| Ownership           | Behaviour                                                                                                                                                                                                          |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `managed` (default) | Dryv owns the file and rewrites it on every generate.                                                                                                                                                              |
| `scaffold`          | The client writes the file only when it's missing. Once it exists, it belongs to the project: Dryv never edits or deletes it, and the client reports it as `SKIP … scaffold already exists; owned by the project`. |

Planned and generated artifacts carry `ownership`, so the client decides with the file on disk as the only state. Because there's no record of which files Dryv once scaffolded, orphaned scaffolds (whose meaning was removed) aren't reported yet; that waits on lock state.

## Commands

A pack can declare actions around generation, such as formatting. A code destination can override or disable them. See actions.

## Composition: `provides`, `needs` and `bind`

Packs compose through capability **slots** (decision 0014). A pack that produces something other packs import declares `provides`. A pack that imports it declares `needs`. The project decides who fills each need.

| Slot                       | Covers                                                                                                                                                         | A provider exports                                                                                                               |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `schema.types`             | `schema`                                                                                                                                                       | one type symbol per schema                                                                                                       |
| `schema.entity.types`      | `schema`                                                                                                                                                       | externally owned stored-entity type; lets a general type pack import entity declarations without providing the same entity twice |
| `schema.validation`        | `schema`                                                                                                                                                       | one validating symbol per schema (class, zod schema, joi schema)                                                                 |
| `schema.persistence`       | `schema`                                                                                                                                                       | one entity symbol per persisted schema                                                                                           |
| `schema.examples`          | `schema`                                                                                                                                                       | one valid example (and its field spec) per schema, for generated tests                                                           |
| `property.enum.types`      | `property.enum`                                                                                                                                                | one symbol per enum                                                                                                              |
| `property.types`           | `property.primitive`, `property.composite`, `property.literal`, `property.union`, `property.record`, `property.tuple`, `property.generic`, `property.temporal` | one type symbol per property, from one template per kind                                                                         |
| `operation.client`         | `operation`                                                                                                                                                    | one callable per operation                                                                                                       |
| `operation.server`         | `operation`                                                                                                                                                    | one server-side entrypoint per operation                                                                                         |
| `operation.implementation` | `operation`                                                                                                                                                    | one handwritten implementation per operation (for example a feature `ServiceImpl` covering its operations)                       |
| `operation.usecase`        | `operation`                                                                                                                                                    | one use case per operation                                                                                                       |

```yaml
# class-validator/dryv.pack.yaml
provides:
  schema.validation:
    $ref: "#/templates/dto" # a selection template over schemas, with output.symbol

# nestjs/dryv.pack.yaml
needs:
  schema.validation: required
templates:
  controller:
    $ref: "#/selections/controllers"
    imports:
      - $ref: "#/needs/schema.validation"

# project dryv.yaml
packs:
  dtos: { source: … }
  server:
    source: …
    bind:
      schema.validation: { $ref: "#/packs/dtos" }
```

Rules:

- The slot list is closed. A providing template must be a selection template whose subject the slot covers, and it must declare `output.symbol`. A slot that covers one subject takes one `$ref`; `property.types` takes a list with at most one template per property kind:

  ```yaml
  provides:
    property.enum.types: { $ref: "#/templates/enum" }
    property.types:
      - $ref: "#/templates/union"
      - $ref: "#/templates/generic"
  ```

  A pack can't both provide and need the same slot.

- Imports may reference `#/needs/<slot>` only for slots the pack declares under `needs`.
- The project lists every pack; nothing is activated implicitly. Each consumer binds its own providers, so one project can bind zod for one pack and class-validator for another.
- A provider covers whatever its selection matches.
- Barrels never export another pack's files.
- Planning diagnostics: `usage.bind.missing` (required need not bound), `usage.bind.unknown_pack`, `usage.bind.slot_not_provided`, `usage.bind.unexpected` (bound a slot the pack doesn't need), `usage.bind.self`, `planner.bind.cycle`. Providers are planned before their consumers.

Resolution: the planner plans providers before consumers. A consumer's `#/needs/<slot>` import resolves each referenced subject of the slot's kind to the bound provider's file and symbol, and appears in `file.dependencies[]` with `pack` and `slot`. If a referenced subject isn't generated by the provider (or by a same-pack import), planning fails with `planner.bind.uncovered_subject`. An optional need the project leaves unbound contributes nothing. The public plan lists cross-pack dependencies with their `pack` and `slot`.

## Rendering invariants

Templates can't recurse, so they render `schema.invariants[].form`, never the raw expression tree:

| Form                              | Example rule                  | TypeORM                                         | class-validator / zod / joi                                  |
| --------------------------------- | ----------------------------- | ----------------------------------------------- | ------------------------------------------------------------ |
| `comparison`, field vs literal    | `quantity > 0`                | `@Check("quantity > 0")`                        | field-level check, e.g. `z.number().gt(0)` via refine        |
| `comparison`, field vs field      | `confirmPassword == password` | `@Check(...)`                                   | cross-field rule (`Match`, `superRefine`, `Joi.ref`)         |
| `comparison`, field vs arithmetic | `total == unit * quantity`    | `@Check("total_price = unit_price * quantity")` | cross-field rule computing the terms                         |
| `all` / `any`                     | `a > 0 and b > 0`             | one check joined with `AND` / `OR`              | one rule per comparison (`all`) or one combined rule (`any`) |
| `opaque`                          | anything else                 | skip, with a comment naming the invariant       | a custom validator, or skip and document it                  |

Field names come from `field.snake`, `field.camel` and the other name variants, so each target applies its own naming. Use the invariant `name` for constraint names and `message` for errors.

## Developing and testing a pack

The CLI can treat a pack directory as a standalone Dryv artifact:

```text
dryv pack init .
dryv pack inspect .
dryv pack validate .
dryv pack doctor .
dryv pack test .
```

`pack validate` loads `dryv.pack.yaml`, discovers the actual pack filesystem and then uses the Engine-owned `complete` Runtime IR scenario. Manifest references, markers, selections, slots, interpolation, planning collisions, renderer analysis and typed context requests are checked through the ordinary Engine contracts. A normal reusable pack does not need to maintain its own `dryv.ir.yaml`.

`pack doctor` adds machine/runtime readiness checks: connected Template Servers, declared renderer versions and explicitly declared action executables.

`pack test` runs the normal generation lifecycle and writes only to an isolated temporary workspace under the system temporary directory (`/tmp/dryv/...` on typical Linux systems). Engine-resolved file actions run against staged generated files, artifacts are then applied to that temporary workspace, and final actions run from the generated destination. `--no-actions` keeps the lifecycle render-only.

The official catalogue remains a separate concern. Its validation command is:

```text
dryv pack catalog validate
```

The standalone developer harness uses Dryv's Engine-owned canonical scenario and synthetic activation/bindings. It is intentionally independent of normal project authoring/build/server configuration; project workflows reuse the same Engine contracts separately.

`pack inspect` also reports the Engine-discovered resource map: source/output paths, template key, renderer mode, ownership, byte length and ignored resources. Filesystem diagnostics include structured source locations when an offending resource is known. See developer artifact workflows.

## Template filesystem

```text
templates/
├── README.md                    # global static file, copied as-is
└── src/
    └── {model}/                 # binds this subtree to templates.model
        └── $(name).py.j2        # rendered by Jinja → <name>.py
```

- A `{key}` directory marks a registry boundary. It disappears from the output. Each key has exactly one marker, and markers can't nest.
- The last registered extension picks the renderer (`.j2` → Jinja, `.hbs` → Handlebars), and that suffix is stripped from the output name. Any other file is copied byte-for-byte, once per invocation of its template.
- Dynamic directories go in `output.path`, never in physical directory names.
- `.dryvignore` uses gitignore syntax. Default ignores cover `.git`, `node_modules`, `.venv`, `dist`, `build`, `.env` and similar. `dryv.pack.yaml`, `dryv.yaml`, `dryv.lock.yaml` and `.dryvignore` are never emitted.

## Validation split

The JSON Schema checks shapes, reference _kinds_, enums, interpolation syntax and path segments. The Engine checks everything that needs the whole pack: that references exist, that roots are available per scope, that markers are unique, extension conflicts, barrel compatibility, import ambiguity and path collisions.

## Relationship to the old template generator

An older, separate template generator was used as a usability benchmark only. Dryv makes no compatibility promise for its `paths.yaml`, selectors, template variables or `meta`/`lang`/`emit` model.
