diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md
index 94060bc6f1..130ea4c8da 100644
--- a/.claude/rules/cross-language-porting.md
+++ b/.claude/rules/cross-language-porting.md
@@ -26,7 +26,7 @@ Preserve the following contracts exactly across all language ports:
- Relationship subtypes: `association`, `aggregation`, `composition`. Cardinality via `@cardinality: one|many`; target via `@objectRef`. **M:N (FR-018) slim vocabulary:** `@cardinality: "many"` + `@objectRef` (target) + `@through` (the junction/through entity — a third entity that MUST declare two `identity.reference` children, one per FK side). The relationship's FK fields are **derived** from those references (the `identity.reference` SSOT for FK direction), never restated. `@sourceRefField` (optional) disambiguates a *directed* self-join by naming the source-side FK field on the junction (the other reference is the target side); on a `@cardinality: one` relationship it instead names which of several `identity.reference` nodes onto the same target this relationship navigates, short-circuiting the unique-candidate/`@sourceRefField`/name-pairing ladder (#368, [ADR-0029](spec/decisions/ADR-0029-entity-child-extends-and-via-inference.md) Amendment 1) — an unresolvable 1:N reference set is `ERR_INVALID_RELATIONSHIP` at load. `@symmetric` (optional boolean) marks an *undirected* self-join (union-on-read) — valid only when `@objectRef` == the declaring entity, and mutually exclusive with `@sourceRefField`. The pre-FR-018 `@joinEntity`/`@joinFields` attrs are REMOVED. Validation errors: symmetric-on-hetero / symmetric+sourceRefField → `ERR_BAD_ATTR_VALUE`; junction-missing-two-references / sourceRefField-not-matching / M:N-attr-on-1:N / **junction-unpairable** → `ERR_INVALID_RELATIONSHIP`. **Unpairable means the junction declares its two references but neither resolves to the navigating entity, or neither to the `@objectRef` target** — declaring two references is NOT enough, and the loader now checks WHAT they point at (owner ruling 2026-09-20). It does so by running the real FK derivation and converting its failure, never a parallel re-implementation, so the loader and the derivation cannot drift; scope mirrors codegen's own iteration exactly — every CONCRETE, non-projection object crossed with its EFFECTIVE relationships, NOT deduped by declaration, because pairing is a property of the navigating entity and an inherited M:N can pair from one subtype and not another. Before the ruling this loaded clean and then diverged: TS and C# warned and emitted no traversal route (a silent 404), while Java, Kotlin and Python failed the build. Gated by `fixtures/conformance/error-relationship-m2m-junction-unpairable/`.
- Index subtypes: `index.lookup` (non-unique retrieval index; uniqueness is encoded in the **type**: `identity.secondary` = unique alternate key, `index.lookup` = non-unique; `@unique` is REMOVED from `identity.secondary` — `ERR_UNKNOWN_ATTR` on any legacy `@unique`). RDB-physical escapes `@using`/`@expr`/`@where`/`@orders` are registered by the db provider on **both** `identity.secondary` and `index.lookup`. `index.fulltext` / `index.vector` / `index.spatial` are reserved on the subtype axis — documented, NOT registered (YAGNI + 1.0 vocab freeze). See [ADR-0040](spec/decisions/ADR-0040-index-type-and-secondary-key-purity.md).
- Layout subtypes: `dataGrid`
-- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#; the TypeScript `service`, `service-routes` and `service-routes-hono` for derived CRUD, transitions, declared operations and the rules' checks).
+- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`), `binding.messaging` and `binding.file`; `grpc` reserved). `api.eventing` (`operation.event` + `binding.messaging`) and `api.batch` (`operation.export`/`.import` + `binding.file`) are registered since 1.4.0, experimental: only O1 and the delivery rules D1 to D3 read them, and every port's API generators select `binding.rest` by subtype and skip them. Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#; the TypeScript `service`, `service-routes` and `service-routes-hono` for derived CRUD, transitions, declared operations and the rules' checks).
- Transition subtypes: `transition.action` (a child of `field.enum` on an `object.entity`: `@from`, `@to`, `@condition` in the validators' grammar, `@permission`, `@public`); `transition.base` is the abstract root and `transition.timed` is reserved, not registered. An enum with a transition IS a lifecycle — states, initial state (`@default`), terminal states and each unclaimed transition's command are derived, never declared (ADR-0066). A transition's `@from` lists enum members, not object references: every port's ref-bearing-attr check excludes `transition.*` nodes. A lifecycle belongs to the declaring entity and its `extends` descendants, NEVER to an entity whose field merely `extends` the lifecycle field (filter by the declaring field's owner); a command claims a transition NODE for its target and every entity extending it. Transition and operation names compare case-insensitively; operation names are unique per PACKAGE across its APIs, except one operation declared identically in two APIs (a versioned API). A lifecycle on an entity with no source loads and is inert (no derived command, no permission checks); the writable-source check applies once a source exists. A `@permission` is a dotted identifier path (a package prefix may use `::`); an absent one derives `.` for an operation and `..` for a transition's command.
- Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47)
- Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values)
diff --git a/AGENTS.md b/AGENTS.md
index 354172e3ff..b355f8ed81 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken.
- **Kotlin** — `codegen-kotlin` (laid out by `KotlinWriter`, ADR-0063, on the JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres.
**Cross-port conformance corpora** (every port runs the shared corpus):
-- Metamodel: `fixtures/conformance/` (614 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
+- Metamodel: `fixtures/conformance/` (622 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
- Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python / C# / Rust byte-identical; the C# and Rust drift ledgers are empty (`docs/CONFORMANCE.md`).
- Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (the Node reference helper writes them; a native tool is equally first-class, ADR-0015 Amendment 2). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".)
- API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived.
diff --git a/changelog.d/api-eventing-and-batch.md b/changelog.d/api-eventing-and-batch.md
new file mode 100644
index 0000000000..01675e6ae8
--- /dev/null
+++ b/changelog.d/api-eventing-and-batch.md
@@ -0,0 +1,47 @@
+- **Eventing and batch APIs, what a resource carries and what an app provides, in every port
+ (experimental).** Two API kinds join `api.operational`, registered in TypeScript, C#, Java
+ and Kotlin, Python and Rust. An `api.eventing` holds `operation.event` children (`@outputRef`,
+ the payload; `@key`, the field whose events stay in order), each with an optional `binding.messaging`
+ (`@protocol` of `kafka`, `amqp`, `mqtt` or `sqs`). An `api.batch` holds `operation.export`
+ (`@outputRef`, one row of the file; `@frequency` of `hourly`, `daily`, `weekly` or `monthly`;
+ `@availableBy`, when the file is ready, in UTC) and `operation.import` (`@inputRef`,
+ `@frequency`), each with an optional `binding.file`: `@transport` (`sftp` or `objectStore`),
+ `@path`, `@fileName`, `@format` (`csv`, `jsonLines` or `parquet`), `@compression`,
+ `@completion` and `@encryption`. The file conventions are pinned: `{date}` is the run's
+ start date as `YYYY-MM-DD` and `{timestamp}` is `YYYYMMDDTHHMMSSZ`, both UTC, and are the only
+ placeholders; a `marker` completion is an empty file named the data file's name plus `.done`;
+ `csv` is RFC 4180 with a header row, an empty string always quoted so it differs from null, an
+ object, map or array as its JSON text, and every other value in the REST wire contract's
+ canonical form, whatever the project's `wire` setting. `@availableBy` is written `:MM` for an hourly file,
+ `HH:MM` for daily, `Ddd HH:MM` for weekly and `D HH:MM` (day 1 to 28) for monthly; another form
+ is `ERR_BAD_ATTR_VALUE` (`error-api-export-available-by-weekly-no-day`), and so is any other
+ `@fileName` placeholder (`error-api-binding-file-unknown-placeholder`), and an event `@key` that
+ is not a field of its `@outputRef` (`error-api-event-key-not-a-field`, rule D3). An event, export or
+ import under an `api.operational`, or a command or query under the new kinds, is
+ `ERR_CHILD_NOT_ALLOWED` (`error-api-event-under-operational`), and so is a `binding.rest` on
+ them. In a system, `resource.stream` and `resource.queue` take `@carries` naming eventing APIs
+ and `resource.objectStore` names batch APIs; a resource carrying the other kind is
+ `ERR_REF_WRONG_KIND` (`error-ref-wrong-kind-carries-batch-on-stream`). `app.service` and
+ `app.job` take `@provides` naming the APIs they host, and `app.job` takes `@extracts` naming
+ the entity or projection it reads (`systems-api-eventing-batch`).
+ Nothing is generated from the new kinds yet. The operation rules of ADR-0066 (claims,
+ transitions, permissions, errors and routes) apply to an `api.operational` only, and every
+ generator that reads operations reads only those and takes an operation's `binding.rest` by
+ subtype, so a model gains no output from an eventing or batch API
+ (`fixtures/codegen-noop/rules/with-delivery/`, held in every port's inert-codegen test).
+ `metamodelVersion` stays at `1.4`.
+
+ Upgrading: `operation.base` no longer declares attributes; a command and a query declare the
+ same ones themselves, so a model loads as before. A project provider's own operation subtype no
+ longer inherits `@inputRef`, `@outputRef`, `@objectRef`, `@permission`, `@public` or binding
+ children from `operation.base`, and is not admitted under `api.operational`, which now takes
+ `operation.command` and `operation.query` only; such a provider declares those attributes itself
+ and places its subtype under its own API type. Permission names, transition claims, `verify`'s
+ rules check and every generator that reads operations read those under `api.operational` only,
+ so they do not read an operation under a provider's own API type; of the operation rules, the
+ shape check O1 still applies to it. Java and Kotlin now refuse an attribute value
+ outside its registered closed set (`ERR_BAD_ATTR_VALUE`, with the TypeScript message), as the
+ other ports already did, so `binding.file @format: fixedWidth`
+ (`error-api-binding-file-format-fixed-width`) and `operation.export @frequency: yearly`
+ (`error-api-export-frequency-unknown`) fail there too; no shipped model or fixture needed a change. The `ERR_TRANSITION_NOT_ON_ENTITY` message in
+ C#, Java and Kotlin, Python and Rust now reads as the TypeScript one does.
diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md
index 9908b0257f..e29f4df7b9 100644
--- a/docs/CONFORMANCE.md
+++ b/docs/CONFORMANCE.md
@@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor
| Corpus | Fixtures | TS | Java | Kotlin | C# | Python | Rust |
|---|---|---|---|---|---|---|---|
-| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 614 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (614 / 614, empty ledger) |
+| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 622 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (622 / 622, empty ledger) |
| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 19 / 19 |
| [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ |
| [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | — |
@@ -82,7 +82,7 @@ and render ledgers; the api-contract runner's list of sub-corpora not built yet)
shrink, and the corpora without one assert each case outright. A new fixture that fails in
Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard
failure when ADR-0065 turns the warning off. A regression still fails: the ledger's
-`minPassing` (614) is the number of fixtures known to pass, and the run fails when fewer do.
+`minPassing` (622) is the number of fixtures known to pass, and the run fails when fewer do.
Beside the corpora it runs the codegen-compile gate (below) with every shipped generator, a
scale gate over twenty copies of the fitness model, and `examples/rust-service/`'s HTTP test.
[The Rust port page](ports/rust.md#conformance) has the detail.
@@ -445,7 +445,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack
## Fixture-to-doc mapping
-### `fixtures/conformance/` — metamodel loader + canonical serializer (614)
+### `fixtures/conformance/` — metamodel loader + canonical serializer (622)
| Fixture prefix | Feature doc |
|---|---|
@@ -468,8 +468,9 @@ carry it, and a model that uses it fails there by name. There is no row per pack
| `origin-*`, `error-origin-*` | [features/templates-and-payloads.md](features/templates-and-payloads.md) (payload origins) |
| `projection-*`, `error-projection-*`, `field-readonly-on-view-projection` | [features/source-kinds.md](features/source-kinds.md) (projections + the object taxonomy, ADR-0028) |
| `requirement-*`, `error-unknown-attr-requirement` | [features/requirements.md](features/requirements.md) (vocabulary only — the gate has its own corpus, `requirement-check-conformance/`; see "Split coverage" above) |
-| `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited`, `systems-grants-and-sources`, `error-ref-unresolved-grant-resource`, `error-ref-wrong-kind-grant-rdb-on-queue`, `error-ref-wrong-kind-source-rdb-on-document`, `error-ref-wrong-kind-grant-stream-on-other-system-queue`, `error-grant-crosses-system`, `error-runsas-other-system`, `error-duplicate-name-in-system`, `systems-duplicate-name-overlay-in-system`, `error-ref-ambiguous-heldby-bare-name`, `systems-rdb-with-search-copy`, `systems-role-grants-across-files`, `systems-document-only-lifecycle-inert`, `systems-sql-view-with-search-copy`, `systems-payload-ref-search-only-projection` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, an app's one build, counting a build it inherits, the grants and their same-system rule, `@resource` on a source, one name per type within a system, a role redeclared in a second file keeping every grant, a search copy beside a SQL view leaving its columns unchecked, a lifecycle that stays inert when its entity has no relational source, and a projection kept only in a search index still serving as a template payload) |
+| `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited`, `systems-grants-and-sources`, `error-ref-unresolved-grant-resource`, `error-ref-wrong-kind-grant-rdb-on-queue`, `error-ref-wrong-kind-source-rdb-on-document`, `error-ref-wrong-kind-grant-stream-on-other-system-queue`, `error-grant-crosses-system`, `error-runsas-other-system`, `error-duplicate-name-in-system`, `systems-duplicate-name-overlay-in-system`, `error-ref-ambiguous-heldby-bare-name`, `systems-rdb-with-search-copy`, `systems-role-grants-across-files`, `systems-document-only-lifecycle-inert`, `systems-sql-view-with-search-copy`, `systems-payload-ref-search-only-projection`, `error-ref-wrong-kind-carries-batch-on-stream` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, an app's one build, counting a build it inherits, the grants and their same-system rule, `@resource` on a source, one name per type within a system, a role redeclared in a second file keeping every grant, a search copy beside a SQL view leaving its columns unchecked, a lifecycle that stays inert when its entity has no relational source, and a projection kept only in a search index still serving as a template payload) |
| `reporting-*`, `error-dimension-*`, `error-measure-*`, `error-ratio-*`, `error-segment-*`, `error-report-*`, `error-relative-date-*` | [features/reporting.md](features/reporting.md) (the `dimension` / `measure` / `segment` / `object.report` vocabulary and its load-time rules; design in the [FR-044 spec](superpowers/specs/2026-10-02-fr-044-core-reporting-design.md)) |
+| `systems-api-eventing-batch`, `error-api-export-available-by-weekly-no-day`, `error-api-binding-file-unknown-placeholder`, `error-api-event-under-operational`, `error-api-event-key-not-a-field`, `error-api-binding-file-format-fixed-width`, `error-api-export-frequency-unknown` | [features/business-rules.md](features/business-rules.md) ("Eventing and batch APIs": `api.eventing` and `api.batch`, their operations and bindings, what a resource carries and an app provides, and the `@availableBy` and `@fileName` rules D1 and D2, and the event `@key` rule D3) |
| `rules-*`, `error-rules-*` | [features/business-rules.md](features/business-rules.md) (operations, permission names and lifecycles: the vocabulary and its load-time rules, ADR-0066; the `verify` gate has its own corpus, `rules-check-conformance/`) |
| `provider-extension-*`, `provider-custom-vocabulary-*` | [features/extending-with-providers.md](features/extending-with-providers.md) (a project's own provider: a new subtype plus attributes on an existing type load with it and are refused without it, every port writing the provider in its own language) |
| `error-packs-left-out-*` | [features/extending-with-providers.md](features/extending-with-providers.md) ([Where vocabulary lives](features/extending-with-providers.md#where-vocabulary-lives): a model that uses a left-out pack's type fails to load, naming the unknown type or subtype) |
@@ -961,7 +962,7 @@ shared input.
## Orphaned fixtures (tested but not yet documented)
-The fixtures in the nine corpora mapped above (metamodel 614 + yaml 19 + verify 45
+The fixtures in the nine corpora mapped above (metamodel 622 + yaml 19 + verify 45
+ render 26 + persistence 68 + api-contract 191 + source-resolution 30 + scope 10 +
dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the
`cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining
diff --git a/docs/compatibility-policy.md b/docs/compatibility-policy.md
index 53e1c9f4c7..ae3fd0b65d 100644
--- a/docs/compatibility-policy.md
+++ b/docs/compatibility-policy.md
@@ -88,8 +88,8 @@ work*. A release can move one without the other, and most releases move neither.
[own-your-codegen](features/own-your-codegen.md).
- **Runtime-library helper internals.** Idiomatic per port; best-effort, not promised.
- **Anything explicitly marked experimental or reserved** and not yet in the registry
- (e.g. the reserved lifecycle subtype `transition.timed`, the reserved event and streaming
- sibling of `api.operational`, and reserved index subtypes `index.fulltext`/`vector`/`spatial`).
+ (e.g. the reserved lifecycle subtype `transition.timed` and reserved index subtypes
+ `index.fulltext`/`vector`/`spatial`).
- **The business-rules vocabulary, which is experimental.** `api.*`, `operation.*`,
`binding.*`, lifecycles (`transition.action` and what it derives) and the permission points
(`@permission`, `@public`) are registered since 1.3.0 (ADR-0066), together with their loader
diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md
index 989b965c9b..a7f1d82d71 100644
--- a/docs/features/business-rules.md
+++ b/docs/features/business-rules.md
@@ -132,6 +132,67 @@ binding:
Most models never write a binding.
+## Eventing and batch APIs
+
+Two more API kinds sit beside `api.operational`, experimental since 1.4.0. The `api` subtype is
+the interaction model and the binding is the protocol (ADR-0030). None of the operation rules
+above, except O1, reads them: an event, export or import is not a command or a query, has no
+target entity, claims no transition and derives no permission name. Nothing is generated from
+them yet, and every port's API generators skip them.
+
+| API | Operations | Binding |
+|---|---|---|
+| `api.eventing`: the provider publishes that something happened | `operation.event` (`outputRef` is the payload; `key` is the payload field whose events stay in order) | `binding.messaging` (`protocol`, optional: `kafka`, `amqp`, `mqtt`, `sqs`) |
+| `api.batch`: a dataset delivered as a file on a schedule | `operation.export` (`outputRef`, `frequency`, `availableBy`), `operation.import` (`inputRef`, `frequency`) | `binding.file` |
+
+An app names the APIs it hosts with `provides`. A `resource.stream` or `resource.queue` names the
+eventing APIs that travel on it with `carries`, and a `resource.objectStore` names the batch APIs
+whose files it holds; a `carries` that names the other kind is `ERR_REF_WRONG_KIND`. An `app.job`
+names the entity or projection it reads its rows from with `extracts`.
+
+`frequency` is `hourly`, `daily`, `weekly` or `monthly`. `availableBy` is the UTC time each new
+file is in place by, and its form follows the frequency:
+
+| `frequency` | `availableBy` | Example |
+|---|---|---|
+| `hourly` | `:MM`, minutes past each hour | `:15` |
+| `daily` | `HH:MM` | `03:00` |
+| `weekly` | `Ddd HH:MM`, the day one of `Mon` to `Sun` | `Mon 06:00` |
+| `monthly` | `D HH:MM`, the day of the month from 1 to 28 | `1 06:00` |
+
+**The file conventions of `binding.file`.** No standard covers them, so they are pinned here:
+
+- `transport`: `sftp` or `objectStore`. The provider always hosts the files, in the object store
+ that carries the API; the transport is how the other party reaches them. `path` is the folder.
+- `fileName` may hold two placeholders. `{date}` is the UTC date on which the run that writes
+ the file started, `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time that run started,
+ to the second, `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses
+ that day's date.
+- `format`: `csv`, `jsonLines` or `parquet`. A CSV file is RFC 4180: a comma between fields, CRLF
+ after every line, UTF-8 with no byte order mark, and a first line of field names. A field is
+ quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled.
+ An empty string is the one exception: it is always quoted (`""`), so that it differs from null,
+ which is an empty field. An object, a map and any array is its JSON text, quoted by the same
+ rule. Every other value is written in the canonical form of the REST wire contract
+ ([api-contract.md](api-contract.md) and
+ [`normalization.md`](../../fixtures/persistence-conformance/normalization.md)), whatever the
+ project's `wire` setting. Among that contract's forms: a timestamp ends in `Z` and one with
+ `@localTime` has no zone suffix; a time or timestamp carries a fraction of a second only when it
+ is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the
+ canonical string of
+ [ADR-0019 Amendment 1](../../spec/decisions/ADR-0019-runtime-return-type-contract.md) (plain
+ notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer
+ in minor units.
+ `jsonLines` is one JSON object per line, UTF-8, LF after each.
+- `compression`: `none` (the default) or `gzip`.
+- `completion`: how a reader knows a file is whole. `rename`: it appears under its final name
+ only once complete. `marker`: an empty object named the file's name plus `.done` is put beside
+ it afterwards. `none` (the default): nothing.
+- `encryption`: `none` (the default) or `pgp`.
+
+A fixed-width format is not offered: nothing can yet state a column's width, padding or
+alignment.
+
## Lifecycles
A `transition.action` is a child of a `field.enum` on an `object.entity`. An enum field with at
@@ -185,7 +246,7 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa
| Rule | Code | When |
|---|---|---|
| L1 | `ERR_TRANSITION_NOT_ON_ENTITY` | A transition on a field that is not a field of an `object.entity`: a document-root field, or a field of a value, projection or report. |
-| L2 | `ERR_TRANSITION_NOT_ON_ENTITY` | A concrete entity has a lifecycle and a source, but no writable one. An entity with no source is not refused: its lifecycle is inert. |
+| L2 | `ERR_TRANSITION_NOT_ON_ENTITY` | A concrete entity has a lifecycle and a source, but no writable one. An entity with no relational source (none, or only `source.document` / `source.search`) is not refused: its lifecycle is inert. |
| L3 | `ERR_LIFECYCLE_NO_INITIAL` | An enum field with transitions has no `default`. |
| L4 | `ERR_TRANSITION_UNKNOWN_STATE` | A `from` or `to` value is not one of the enum's `values`. |
| L5, O0 | `ERR_TRANSITION_NAME_COLLISION` | A transition or an operation is named `create`, `get`, `list`, `update` or `delete`, in any case. |
@@ -205,6 +266,9 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa
| P3 | `ERR_TRANSITION_NAME_COLLISION` | Two permission points ask about one permission name and at least one name is derived: an operation named `Order.open`, or one declaring `permission: p.Order.open`, beside the `open` transition of `Order` in `p`. Names are compared exactly as the policy receives them: `::` and `.` are different things in the metadata, so an `open` operation in package `p::Order` (`p::Order.open`) does not collide with that transition (`p.Order.open`). Two declared `permission` values may be equal. |
| B1 | `ERR_BINDING_PATH_MISMATCH` | A `binding.rest` `path` has the wrong placeholders. |
| B2 | `ERR_BINDING_PATH_MISMATCH` | Two declared bindings of one API have the same method (declared or derived) and the same path, ignoring placeholder names. |
+| D1 | `ERR_BAD_ATTR_VALUE` | An `operation.export` `availableBy` does not have the form its `frequency` gives. |
+| D2 | `ERR_BAD_ATTR_VALUE` | A `binding.file` `fileName` holds a placeholder other than `{date}` or `{timestamp}`, or an unmatched brace. |
+| D3 | `ERR_BAD_ATTR_VALUE` | An `operation.event` `key` is not a field of the object its `outputRef` names (inherited fields count). |
Names are compared without case (L5 and O0, L6, O6) because each one becomes a command, a permission
constant and a file, and those collide on a case-folding target. P3 compares permission names
diff --git a/docs/features/stability-labels.md b/docs/features/stability-labels.md
index d71df1683c..aaed28e6e1 100644
--- a/docs/features/stability-labels.md
+++ b/docs/features/stability-labels.md
@@ -25,7 +25,7 @@ the [compatibility policy](../compatibility-policy.md), which stands as written.
| Library `iam` | preview | [Libraries](libraries.md) |
| Angular packages | source-only, on their own `0.6` line, not published | ADR-0048 |
| Business-rules vocabulary: `api.*`, `operation.*`, `binding.*`, `transition.*`, `@permission`, `@public`, and the `rules` and `verify.lifecycle` settings | experimental | [Business rules](business-rules.md), ADR-0066 |
-| Reserved names (`transition.timed`, the event and streaming sibling of `api.operational`, `index.fulltext`, `index.vector`, `index.spatial`) | reserved: not in the registry | [Compatibility policy](../compatibility-policy.md) |
+| Reserved names (`transition.timed`, `index.fulltext`, `index.vector`, `index.spatial`) | reserved: not in the registry | [Compatibility policy](../compatibility-policy.md) |
## What is not here yet
diff --git a/docs/recipes/document-graph-and-wide-column-stores.md b/docs/recipes/document-graph-and-wide-column-stores.md
index fb31793bb0..18c448c811 100644
--- a/docs/recipes/document-graph-and-wide-column-stores.md
+++ b/docs/recipes/document-graph-and-wide-column-stores.md
@@ -132,11 +132,16 @@ exists, because the two records live in different stores.
## Why this is not new vocabulary
-ADR-0007 designs `source.document`, `source.graph` and the other paradigm subtypes. Core's
-systems provider registers `source.document` and `source.search` (ADR-0070), so an object can
-name its document store or search index, but no generator writes from them yet. `source.graph`
-and the rest stay unregistered until a shipping consumer dispatches on them. That is the bar ADR-0007 Amendment 2 set for `@role` members, applied to
-paradigms. Registering one today would make `Order` persistable to
-every tier in all five ports, and each tier would then need to learn to skip it. A
-sourceless entity with a property bag gives an adopter everything a store-specific
-generator needs, and it changes nothing in the metamodel.
+ADR-0007 designs `source.document`, `source.graph` and the other paradigm subtypes. The
+systems provider (`metaobjects-systems-core`, ADR-0070) registers `source.document` and
+`source.search`; core's type provider (`metaobjects-core-types`) does not. An object can name its
+document store or search index with them, but no generator writes from them yet. `source.graph`
+and the rest stay unregistered until a shipping consumer dispatches on them. That is the bar
+ADR-0007 Amendment 2 set for `@role` members, applied to paradigms.
+
+Registering a paradigm subtype does not make an object persistable. Every tier in all five ports
+decides that from `source.rdb` alone, so an entity whose only sources are `source.document` or
+`source.search` is treated like a sourceless one: it gets no table, no migration and no
+relational routes, and a lifecycle on it is inert. A sourceless entity with a property bag still
+gives an adopter everything a store-specific generator needs, and it changes nothing in the
+metamodel.
diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json
index a001915d05..cf83537150 100644
--- a/examples/showcase/site-payload.json
+++ b/examples/showcase/site-payload.json
@@ -7,7 +7,7 @@
"metamodel": "1.4"
},
"counts": {
- "fixtures": 614,
+ "fixtures": 622,
"corpora": 49,
"baseTypes": 28
},
diff --git a/explorer-app/assets/explorer-app.js b/explorer-app/assets/explorer-app.js
index a2681492a9..ec81740b86 100644
--- a/explorer-app/assets/explorer-app.js
+++ b/explorer-app/assets/explorer-app.js
@@ -265,5 +265,5 @@
`);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(`
`)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",`
`,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(`${tag}>`)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(`
-`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(`
`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
`}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`
${cols.map((o)=>`
${this.link(from,o.id)}
`).join("")}
`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`
`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`
`,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
None.
');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
None.
')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
Not scanned.
');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
No prompt text was read.
':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
None.
':`
${items.map((i)=>`
${i}
`).join("")}
`}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found
No such page
${escapeHtml2(r.path)} is not a page of this model.
`,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="
No model yet
The explorer is waiting for the running application's docs view.
";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="
explorer-model.js did not load. Run meta gen to write it beside this page.
";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})();
diff --git a/fixtures/codegen-noop/rules/README.md b/fixtures/codegen-noop/rules/README.md
index b5920bc3c8..374dbcd455 100644
--- a/fixtures/codegen-noop/rules/README.md
+++ b/fixtures/codegen-noop/rules/README.md
@@ -58,3 +58,17 @@ something half-built; these tests are what notice:
Regenerate `without/` from `with/` by deleting every `transition.*` child and the
`api.operational` node, nothing else.
+
+## The eventing and batch APIs (1.4.0)
+
+`with-delivery/meta.purchasing.json` is `with/` plus an `api.eventing` (`PurchasingEvents`, one
+`operation.event` with a `binding.messaging`) and an `api.batch` (`PurchasingFeeds`, an
+`operation.export` and an `operation.import`, each with a `binding.file`). Their operations
+reference the same `DecisionInput` and `RequestSummary` the operational API does, so a generator
+that read every `api` or took an operation's first binding whatever its subtype would derive a
+target and emit a route for them. Nothing is generated from these two API kinds yet, so every
+generator in every port, the rules-layer and service generators included, writes for
+`with-delivery/` exactly what it writes for `with/`. The model explorer (`docs-site`) is the one
+exception, as above, because it lists every node. Each port's test named above holds that too.
+
+Regenerate `with-delivery/` from `with/` by appending those two API nodes, nothing else.
diff --git a/fixtures/codegen-noop/rules/with-delivery/meta.purchasing.json b/fixtures/codegen-noop/rules/with-delivery/meta.purchasing.json
new file mode 100644
index 0000000000..7e342f4516
--- /dev/null
+++ b/fixtures/codegen-noop/rules/with-delivery/meta.purchasing.json
@@ -0,0 +1,251 @@
+{
+ "metadata.root": {
+ "package": "acme::purchasing",
+ "children": [
+ {
+ "object.entity": {
+ "name": "PurchaseRequest",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "purchase_requests"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "field.string": {
+ "name": "title"
+ }
+ },
+ {
+ "field.long": {
+ "name": "amountCents"
+ }
+ },
+ {
+ "field.enum": {
+ "name": "status",
+ "@values": [
+ "draft",
+ "submitted",
+ "approved",
+ "rejected"
+ ],
+ "@default": "draft",
+ "children": [
+ {
+ "transition.action": {
+ "name": "submit",
+ "@from": [
+ "draft"
+ ],
+ "@to": "submitted"
+ }
+ },
+ {
+ "transition.action": {
+ "name": "approve",
+ "@from": [
+ "submitted"
+ ],
+ "@to": "approved",
+ "@condition": {
+ "op": "gt",
+ "left": {
+ "field": "amountCents"
+ },
+ "right": {
+ "value": 0
+ }
+ }
+ }
+ },
+ {
+ "transition.action": {
+ "name": "reject",
+ "@from": [
+ "submitted"
+ ],
+ "@to": "rejected",
+ "@permission": "purchasing.review"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.value": {
+ "name": "DecisionInput",
+ "children": [
+ {
+ "field.long": {
+ "name": "requestId",
+ "extends": "PurchaseRequest.id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "comment"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.projection": {
+ "name": "RequestSummary",
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_request_summary"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id",
+ "extends": "PurchaseRequest.id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "title",
+ "extends": "PurchaseRequest.title"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "extends": "PurchaseRequest.pk"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "api.operational": {
+ "name": "Purchasing",
+ "children": [
+ {
+ "operation.command": {
+ "name": "decide",
+ "@inputRef": "DecisionInput",
+ "@transitions": [
+ "approve",
+ "reject"
+ ],
+ "@permission": "purchasing.decide",
+ "@errors": [
+ "over_budget",
+ "already_decided"
+ ],
+ "children": [
+ {
+ "binding.rest": {
+ "@method": "PUT",
+ "@path": "/purchase-requests/{id}/decision"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "operation.query": {
+ "name": "openRequests",
+ "@outputRef": "RequestSummary",
+ "@many": true,
+ "@public": true
+ }
+ },
+ {
+ "operation.query": {
+ "name": "requestSummary",
+ "@outputRef": "RequestSummary"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "api.eventing": {
+ "name": "PurchasingEvents",
+ "children": [
+ {
+ "operation.event": {
+ "name": "requestDecided",
+ "@outputRef": "DecisionInput",
+ "@key": "requestId",
+ "children": [
+ {
+ "binding.messaging": {
+ "@protocol": "kafka"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "api.batch": {
+ "name": "PurchasingFeeds",
+ "children": [
+ {
+ "operation.export": {
+ "name": "dailyRequests",
+ "@outputRef": "RequestSummary",
+ "@frequency": "daily",
+ "@availableBy": "03:00",
+ "children": [
+ {
+ "binding.file": {
+ "@transport": "sftp",
+ "@path": "requests/",
+ "@fileName": "requests-{date}.csv",
+ "@format": "csv",
+ "@completion": "rename"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "operation.import": {
+ "name": "decisions",
+ "@inputRef": "DecisionInput",
+ "@frequency": "hourly",
+ "children": [
+ {
+ "binding.file": {
+ "@transport": "objectStore",
+ "@path": "decisions/",
+ "@fileName": "decisions-{timestamp}.jsonl",
+ "@format": "jsonLines",
+ "@completion": "marker"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-api-binding-file-format-fixed-width/expected-errors.json b/fixtures/conformance/error-api-binding-file-format-fixed-width/expected-errors.json
new file mode 100644
index 0000000000..4376672f1f
--- /dev/null
+++ b/fixtures/conformance/error-api-binding-file-format-fixed-width/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_BAD_ATTR_VALUE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.ledger.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['api.batch'].children[0]['operation.export'].children[0]['binding.file']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-api-binding-file-format-fixed-width/input/meta.ledger.json b/fixtures/conformance/error-api-binding-file-format-fixed-width/input/meta.ledger.json
new file mode 100644
index 0000000000..df0d59e0bc
--- /dev/null
+++ b/fixtures/conformance/error-api-binding-file-format-fixed-width/input/meta.ledger.json
@@ -0,0 +1,25 @@
+{
+ "metadata.root": {
+ "package": "acme::ledger",
+ "children": [
+ { "object.value": { "name": "SettlementLine", "children": [ { "field.string": { "name": "reference" } } ] } },
+ {
+ "api.batch": {
+ "name": "SettlementFeed",
+ "children": [
+ {
+ "operation.export": {
+ "name": "dailySettlement",
+ "@outputRef": "SettlementLine",
+ "@frequency": "daily",
+ "children": [
+ { "binding.file": { "@transport": "sftp", "@fileName": "settlement-{date}.txt", "@format": "fixedWidth" } }
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-api-binding-file-unknown-placeholder/expected-errors.json b/fixtures/conformance/error-api-binding-file-unknown-placeholder/expected-errors.json
new file mode 100644
index 0000000000..756c138ee9
--- /dev/null
+++ b/fixtures/conformance/error-api-binding-file-unknown-placeholder/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_BAD_ATTR_VALUE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['api.batch'].children[0]['operation.import'].children[0]['binding.file']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-api-binding-file-unknown-placeholder/input/meta.parcels.json b/fixtures/conformance/error-api-binding-file-unknown-placeholder/input/meta.parcels.json
new file mode 100644
index 0000000000..1ed0b157ab
--- /dev/null
+++ b/fixtures/conformance/error-api-binding-file-unknown-placeholder/input/meta.parcels.json
@@ -0,0 +1,25 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ { "object.value": { "name": "ScanRecord", "children": [ { "field.string": { "name": "trackingNumber" } } ] } },
+ {
+ "api.batch": {
+ "name": "ScanIntake",
+ "children": [
+ {
+ "operation.import": {
+ "name": "scans",
+ "@inputRef": "ScanRecord",
+ "@frequency": "hourly",
+ "children": [
+ { "binding.file": { "@transport": "sftp", "@fileName": "scans-{hour}.jsonl", "@format": "jsonLines" } }
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-api-event-key-not-a-field/expected-errors.json b/fixtures/conformance/error-api-event-key-not-a-field/expected-errors.json
new file mode 100644
index 0000000000..cec7564865
--- /dev/null
+++ b/fixtures/conformance/error-api-event-key-not-a-field/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_BAD_ATTR_VALUE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['api.eventing'].children[1]['operation.event']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-api-event-key-not-a-field/input/meta.parcels.json b/fixtures/conformance/error-api-event-key-not-a-field/input/meta.parcels.json
new file mode 100644
index 0000000000..c12069fb3f
--- /dev/null
+++ b/fixtures/conformance/error-api-event-key-not-a-field/input/meta.parcels.json
@@ -0,0 +1,18 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ { "object.value": { "name": "ParcelEvent", "abstract": true, "children": [ { "field.string": { "name": "trackingNumber" } } ] } },
+ { "object.value": { "name": "ParcelScanned", "extends": "ParcelEvent", "children": [ { "field.string": { "name": "depot" } } ] } },
+ {
+ "api.eventing": {
+ "name": "ParcelEvents",
+ "children": [
+ { "operation.event": { "name": "parcelScanned", "@outputRef": "ParcelScanned", "@key": "trackingNumber" } },
+ { "operation.event": { "name": "parcelRescanned", "@outputRef": "ParcelScanned", "@key": "trackingNumbr" } }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-api-event-under-operational/expected-errors.json b/fixtures/conformance/error-api-event-under-operational/expected-errors.json
new file mode 100644
index 0000000000..ecd3e5e39d
--- /dev/null
+++ b/fixtures/conformance/error-api-event-under-operational/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_CHILD_NOT_ALLOWED",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['api.operational']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-api-event-under-operational/input/meta.parcels.json b/fixtures/conformance/error-api-event-under-operational/input/meta.parcels.json
new file mode 100644
index 0000000000..b32fcc1324
--- /dev/null
+++ b/fixtures/conformance/error-api-event-under-operational/input/meta.parcels.json
@@ -0,0 +1,16 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ { "object.value": { "name": "ShipmentPlaced", "children": [ { "field.string": { "name": "trackingNumber" } } ] } },
+ {
+ "api.operational": {
+ "name": "ShipmentApi",
+ "children": [
+ { "operation.event": { "name": "shipmentPlaced", "@outputRef": "ShipmentPlaced" } }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-api-export-available-by-weekly-no-day/expected-errors.json b/fixtures/conformance/error-api-export-available-by-weekly-no-day/expected-errors.json
new file mode 100644
index 0000000000..42917cd350
--- /dev/null
+++ b/fixtures/conformance/error-api-export-available-by-weekly-no-day/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_BAD_ATTR_VALUE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.ledger.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['api.batch'].children[0]['operation.export']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-api-export-available-by-weekly-no-day/input/meta.ledger.json b/fixtures/conformance/error-api-export-available-by-weekly-no-day/input/meta.ledger.json
new file mode 100644
index 0000000000..575a3f84f0
--- /dev/null
+++ b/fixtures/conformance/error-api-export-available-by-weekly-no-day/input/meta.ledger.json
@@ -0,0 +1,16 @@
+{
+ "metadata.root": {
+ "package": "acme::ledger",
+ "children": [
+ { "object.value": { "name": "SettlementLine", "children": [ { "field.string": { "name": "reference" } } ] } },
+ {
+ "api.batch": {
+ "name": "SettlementFeed",
+ "children": [
+ { "operation.export": { "name": "weeklySettlement", "@outputRef": "SettlementLine", "@frequency": "weekly", "@availableBy": "06:00" } }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-api-export-frequency-unknown/expected-errors.json b/fixtures/conformance/error-api-export-frequency-unknown/expected-errors.json
new file mode 100644
index 0000000000..42917cd350
--- /dev/null
+++ b/fixtures/conformance/error-api-export-frequency-unknown/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_BAD_ATTR_VALUE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.ledger.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['api.batch'].children[0]['operation.export']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-api-export-frequency-unknown/input/meta.ledger.json b/fixtures/conformance/error-api-export-frequency-unknown/input/meta.ledger.json
new file mode 100644
index 0000000000..6d97446597
--- /dev/null
+++ b/fixtures/conformance/error-api-export-frequency-unknown/input/meta.ledger.json
@@ -0,0 +1,16 @@
+{
+ "metadata.root": {
+ "package": "acme::ledger",
+ "children": [
+ { "object.value": { "name": "SettlementLine", "children": [ { "field.string": { "name": "reference" } } ] } },
+ {
+ "api.batch": {
+ "name": "SettlementFeed",
+ "children": [
+ { "operation.export": { "name": "yearlySettlement", "@outputRef": "SettlementLine", "@frequency": "yearly" } }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/expected-errors.json b/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/expected-errors.json
new file mode 100644
index 0000000000..78c913b08f
--- /dev/null
+++ b/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_REF_WRONG_KIND",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['system.software'].children[0]['resource.stream']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/input/meta.parcels.json b/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/input/meta.parcels.json
new file mode 100644
index 0000000000..50560eb9bc
--- /dev/null
+++ b/fixtures/conformance/error-ref-wrong-kind-carries-batch-on-stream/input/meta.parcels.json
@@ -0,0 +1,24 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ { "object.value": { "name": "ManifestLine", "children": [ { "field.string": { "name": "trackingNumber" } } ] } },
+ {
+ "api.batch": {
+ "name": "ManifestFeed",
+ "children": [
+ { "operation.export": { "name": "dailyManifest", "@outputRef": "ManifestLine", "@frequency": "daily", "@availableBy": "03:00" } }
+ ]
+ }
+ },
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ { "resource.stream": { "name": "events", "@carries": ["ManifestFeed"] } }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/systems-api-eventing-batch/expected.json b/fixtures/conformance/systems-api-eventing-batch/expected.json
new file mode 100644
index 0000000000..2e35c69448
--- /dev/null
+++ b/fixtures/conformance/systems-api-eventing-batch/expected.json
@@ -0,0 +1,291 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Shipment",
+ "children": [
+ {
+ "source.rdb": {
+ "@resource": "acme::parcels::Parcels.db",
+ "@table": "shipments"
+ }
+ },
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ },
+ {
+ "field.date": {
+ "name": "shippedOn"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "@fields": [
+ "trackingNumber"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.projection": {
+ "name": "DailyManifestLine",
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "materializedView",
+ "@materializedView": "daily_manifest_lines",
+ "@resource": "acme::parcels::Parcels.db"
+ }
+ },
+ {
+ "field.string": {
+ "name": "trackingNumber",
+ "extends": "acme::parcels::Shipment.trackingNumber"
+ }
+ },
+ {
+ "field.date": {
+ "name": "shippedOn",
+ "extends": "acme::parcels::Shipment.shippedOn"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "extends": "acme::parcels::Shipment.pk"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.value": {
+ "name": "ShipmentPlaced",
+ "children": [
+ {
+ "field.string": {
+ "name": "trackingNumber",
+ "extends": "acme::parcels::Shipment.trackingNumber"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.value": {
+ "name": "ManifestLine",
+ "children": [
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ },
+ {
+ "field.date": {
+ "name": "shippedOn"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.value": {
+ "name": "ScanRecord",
+ "children": [
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ },
+ {
+ "field.timestamp": {
+ "name": "scannedAt"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "api.eventing": {
+ "name": "ShipmentEvents",
+ "children": [
+ {
+ "operation.event": {
+ "name": "shipmentPlaced",
+ "@key": "trackingNumber",
+ "@outputRef": "acme::parcels::ShipmentPlaced",
+ "children": [
+ {
+ "binding.messaging": {
+ "@protocol": "kafka"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "api.eventing": {
+ "name": "LabelRequests",
+ "children": [
+ {
+ "operation.event": {
+ "name": "labelRequested",
+ "@outputRef": "acme::parcels::ShipmentPlaced"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "api.batch": {
+ "name": "ManifestFeed",
+ "children": [
+ {
+ "operation.export": {
+ "name": "dailyManifest",
+ "@availableBy": "03:00",
+ "@frequency": "daily",
+ "@outputRef": "acme::parcels::ManifestLine",
+ "children": [
+ {
+ "binding.file": {
+ "@completion": "rename",
+ "@compression": "gzip",
+ "@fileName": "manifest-{date}.csv",
+ "@format": "csv",
+ "@path": "manifests/",
+ "@transport": "sftp"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "operation.export": {
+ "name": "weeklyManifest",
+ "@availableBy": "Mon 06:00",
+ "@frequency": "weekly",
+ "@outputRef": "acme::parcels::ManifestLine",
+ "children": [
+ {
+ "binding.file": {
+ "@completion": "marker",
+ "@encryption": "pgp",
+ "@fileName": "manifest-week-{date}.jsonl",
+ "@format": "jsonLines",
+ "@path": "weekly/",
+ "@transport": "objectStore"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "operation.export": {
+ "name": "monthlyManifest",
+ "@availableBy": "1 06:00",
+ "@frequency": "monthly",
+ "@outputRef": "acme::parcels::ManifestLine"
+ }
+ },
+ {
+ "operation.import": {
+ "name": "scans",
+ "@frequency": "hourly",
+ "@inputRef": "acme::parcels::ScanRecord",
+ "children": [
+ {
+ "binding.file": {
+ "@completion": "rename",
+ "@fileName": "scans-{timestamp}.jsonl",
+ "@format": "jsonLines",
+ "@path": "scans/",
+ "@transport": "sftp"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ {
+ "resource.rdb": {
+ "name": "db"
+ }
+ },
+ {
+ "resource.stream": {
+ "name": "events",
+ "@carries": [
+ "acme::parcels::ShipmentEvents"
+ ]
+ }
+ },
+ {
+ "resource.objectStore": {
+ "name": "drops",
+ "@carries": [
+ "acme::parcels::ManifestFeed"
+ ]
+ }
+ },
+ {
+ "resource.queue": {
+ "name": "labelJobs",
+ "@carries": [
+ "acme::parcels::LabelRequests"
+ ]
+ }
+ },
+ {
+ "app.service": {
+ "name": "api",
+ "@provides": [
+ "acme::parcels::ShipmentEvents"
+ ],
+ "@runsAs": "acme::parcels::Parcels.api"
+ }
+ },
+ {
+ "app.job": {
+ "name": "manifestExport",
+ "@extracts": "acme::parcels::DailyManifestLine",
+ "@provides": [
+ "acme::parcels::ManifestFeed"
+ ],
+ "@runsAs": "acme::parcels::Parcels.exporter",
+ "@schedule": "0 2 * * *"
+ }
+ },
+ {
+ "role.service": {
+ "name": "api"
+ }
+ },
+ {
+ "role.service": {
+ "name": "exporter"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
+
diff --git a/fixtures/conformance/systems-api-eventing-batch/input/meta.parcels.json b/fixtures/conformance/systems-api-eventing-batch/input/meta.parcels.json
new file mode 100644
index 0000000000..6d3f800cb1
--- /dev/null
+++ b/fixtures/conformance/systems-api-eventing-batch/input/meta.parcels.json
@@ -0,0 +1,142 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Shipment",
+ "children": [
+ { "source.rdb": { "@table": "shipments", "@resource": "Parcels.db" } },
+ { "field.string": { "name": "trackingNumber" } },
+ { "field.date": { "name": "shippedOn" } },
+ { "identity.primary": { "name": "pk", "@fields": ["trackingNumber"] } }
+ ]
+ }
+ },
+ {
+ "object.projection": {
+ "name": "DailyManifestLine",
+ "children": [
+ { "source.rdb": { "@kind": "materializedView", "@materializedView": "daily_manifest_lines", "@resource": "Parcels.db" } },
+ { "field.string": { "name": "trackingNumber", "extends": "Shipment.trackingNumber" } },
+ { "field.date": { "name": "shippedOn", "extends": "Shipment.shippedOn" } },
+ { "identity.primary": { "name": "pk", "extends": "Shipment.pk" } }
+ ]
+ }
+ },
+ {
+ "object.value": {
+ "name": "ShipmentPlaced",
+ "children": [
+ { "field.string": { "name": "trackingNumber", "extends": "Shipment.trackingNumber" } }
+ ]
+ }
+ },
+ {
+ "object.value": {
+ "name": "ManifestLine",
+ "children": [
+ { "field.string": { "name": "trackingNumber" } },
+ { "field.date": { "name": "shippedOn" } }
+ ]
+ }
+ },
+ {
+ "object.value": {
+ "name": "ScanRecord",
+ "children": [
+ { "field.string": { "name": "trackingNumber" } },
+ { "field.timestamp": { "name": "scannedAt" } }
+ ]
+ }
+ },
+ {
+ "api.eventing": {
+ "name": "ShipmentEvents",
+ "children": [
+ {
+ "operation.event": {
+ "name": "shipmentPlaced",
+ "@outputRef": "ShipmentPlaced",
+ "@key": "trackingNumber",
+ "children": [
+ { "binding.messaging": { "@protocol": "kafka" } }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "api.eventing": {
+ "name": "LabelRequests",
+ "children": [
+ { "operation.event": { "name": "labelRequested", "@outputRef": "ShipmentPlaced" } }
+ ]
+ }
+ },
+ {
+ "api.batch": {
+ "name": "ManifestFeed",
+ "children": [
+ {
+ "operation.export": {
+ "name": "dailyManifest",
+ "@outputRef": "ManifestLine",
+ "@frequency": "daily",
+ "@availableBy": "03:00",
+ "children": [
+ { "binding.file": { "@transport": "sftp", "@path": "manifests/", "@fileName": "manifest-{date}.csv", "@format": "csv", "@compression": "gzip", "@completion": "rename" } }
+ ]
+ }
+ },
+ {
+ "operation.export": {
+ "name": "weeklyManifest",
+ "@outputRef": "ManifestLine",
+ "@frequency": "weekly",
+ "@availableBy": "Mon 06:00",
+ "children": [
+ { "binding.file": { "@transport": "objectStore", "@path": "weekly/", "@fileName": "manifest-week-{date}.jsonl", "@format": "jsonLines", "@completion": "marker", "@encryption": "pgp" } }
+ ]
+ }
+ },
+ {
+ "operation.export": {
+ "name": "monthlyManifest",
+ "@outputRef": "ManifestLine",
+ "@frequency": "monthly",
+ "@availableBy": "1 06:00"
+ }
+ },
+ {
+ "operation.import": {
+ "name": "scans",
+ "@inputRef": "ScanRecord",
+ "@frequency": "hourly",
+ "children": [
+ { "binding.file": { "@transport": "sftp", "@path": "scans/", "@fileName": "scans-{timestamp}.jsonl", "@format": "jsonLines", "@completion": "rename" } }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ { "resource.rdb": { "name": "db" } },
+ { "resource.stream": { "name": "events", "@carries": ["ShipmentEvents"] } },
+ { "resource.objectStore": { "name": "drops", "@carries": ["ManifestFeed"] } },
+ { "resource.queue": { "name": "labelJobs", "@carries": ["LabelRequests"] } },
+ { "app.service": { "name": "api", "@runsAs": "api", "@provides": ["ShipmentEvents"] } },
+ { "app.job": { "name": "manifestExport", "@runsAs": "exporter", "@schedule": "0 2 * * *", "@provides": ["ManifestFeed"], "@extracts": "DailyManifestLine" } },
+ { "role.service": { "name": "api" } },
+ { "role.service": { "name": "exporter" } }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/metamodel-docs/data/INDEX.md.json b/fixtures/metamodel-docs/data/INDEX.md.json
index ce382588ab..d17396ad11 100644
--- a/fixtures/metamodel-docs/data/INDEX.md.json
+++ b/fixtures/metamodel-docs/data/INDEX.md.json
@@ -5,6 +5,16 @@
"description": "Registry anchor for the declared API surface (ADR-0030, ADR-0054): not authorable. The `api` subtype axis is the interaction model, never the protocol; protocol lives in `binding.*` on each operation.",
"page": "types/api.md#apibase"
},
+ {
+ "typeSubType": "api.batch",
+ "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "page": "types/api.md#apibatch"
+ },
+ {
+ "typeSubType": "api.eventing",
+ "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "page": "types/api.md#apieventing"
+ },
{
"typeSubType": "api.operational",
"description": "A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (`v1`, `v2`) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
@@ -90,6 +100,16 @@
"description": "Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable.",
"page": "types/binding.md#bindingbase"
},
+ {
+ "typeSubType": "binding.file",
+ "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "page": "types/binding.md#bindingfile"
+ },
+ {
+ "typeSubType": "binding.messaging",
+ "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "page": "types/binding.md#bindingmessaging"
+ },
{
"typeSubType": "binding.rest",
"description": "The HTTP method and path of an operation, declared only to override the derived ones. A query is `GET`, a command `POST`; the path is `//{id}/` for an operation with a target key and `//` without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
@@ -332,7 +352,7 @@
},
{
"typeSubType": "operation.base",
- "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.",
+ "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.",
"page": "types/operation.md#operationbase"
},
{
@@ -340,6 +360,21 @@
"description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
"page": "types/operation.md#operationcommand"
},
+ {
+ "typeSubType": "operation.event",
+ "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "page": "types/operation.md#operationevent"
+ },
+ {
+ "typeSubType": "operation.export",
+ "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "page": "types/operation.md#operationexport"
+ },
+ {
+ "typeSubType": "operation.import",
+ "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "page": "types/operation.md#operationimport"
+ },
{
"typeSubType": "operation.query",
"description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
diff --git a/fixtures/metamodel-docs/data/providers.md.json b/fixtures/metamodel-docs/data/providers.md.json
index 5331ee28e9..810c784910 100644
--- a/fixtures/metamodel-docs/data/providers.md.json
+++ b/fixtures/metamodel-docs/data/providers.md.json
@@ -468,25 +468,41 @@
"hasDescription": true,
"description": "Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).",
"hasOwns": true,
- "owns": "`api.base`, `api.operational`, `binding.base`, `binding.rest`, `operation.base`, `operation.command`, `operation.query`, `transition.action`, `transition.base`",
+ "owns": "`api.base`, `api.batch`, `api.eventing`, `api.operational`, `binding.base`, `binding.file`, `binding.messaging`, `binding.rest`, `operation.base`, `operation.command`, `operation.event`, `operation.export`, `operation.import`, `operation.query`, `transition.action`, `transition.base`",
"hasUniversal": false,
"hasContributes": true,
"contributes": [
+ {
+ "typeSubType": "binding.file",
+ "attrs": "`@completion`, `@compression`, `@encryption`, `@fileName`, `@format`, `@path`, `@transport`"
+ },
+ {
+ "typeSubType": "binding.messaging",
+ "attrs": "`@protocol`"
+ },
{
"typeSubType": "binding.rest",
"attrs": "`@method`, `@path`"
},
{
- "typeSubType": "operation.base",
- "attrs": "`@inputRef`, `@objectRef`, `@outputRef`, `@permission`, `@public`"
+ "typeSubType": "operation.command",
+ "attrs": "`@errors`, `@inputRef`, `@objectRef`, `@outputRef`, `@permission`, `@public`, `@transitions`"
},
{
- "typeSubType": "operation.command",
- "attrs": "`@errors`, `@transitions`"
+ "typeSubType": "operation.event",
+ "attrs": "`@key`, `@outputRef`"
+ },
+ {
+ "typeSubType": "operation.export",
+ "attrs": "`@availableBy`, `@frequency`, `@outputRef`"
+ },
+ {
+ "typeSubType": "operation.import",
+ "attrs": "`@frequency`, `@inputRef`"
},
{
"typeSubType": "operation.query",
- "attrs": "`@many`"
+ "attrs": "`@inputRef`, `@many`, `@objectRef`, `@outputRef`, `@permission`, `@public`"
},
{
"typeSubType": "transition.action",
@@ -517,11 +533,11 @@
},
{
"typeSubType": "app.job",
- "attrs": "`@schedule`"
+ "attrs": "`@extracts`, `@provides`, `@schedule`"
},
{
"typeSubType": "app.service",
- "attrs": "`@public`"
+ "attrs": "`@provides`, `@public`"
},
{
"typeSubType": "build.image",
@@ -569,16 +585,20 @@
},
{
"typeSubType": "resource.objectStore",
- "attrs": "`@publicRead`"
+ "attrs": "`@carries`, `@publicRead`"
},
{
"typeSubType": "resource.queue",
- "attrs": "`@deadLetter`, `@ordered`"
+ "attrs": "`@carries`, `@deadLetter`, `@ordered`"
},
{
"typeSubType": "resource.rdb",
"attrs": "`@schemas`"
},
+ {
+ "typeSubType": "resource.stream",
+ "attrs": "`@carries`"
+ },
{
"typeSubType": "role.base",
"attrs": "`@credential`, `@memberOf`"
diff --git a/fixtures/metamodel-docs/data/types/api.md.json b/fixtures/metamodel-docs/data/types/api.md.json
index 1f0de15905..4e89daec08 100644
--- a/fixtures/metamodel-docs/data/types/api.md.json
+++ b/fixtures/metamodel-docs/data/types/api.md.json
@@ -17,6 +17,47 @@
"children": [],
"hasParents": false
},
+ {
+ "typeSubType": "api.batch",
+ "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "hasOwner": true,
+ "owner": "metaobjects-rules",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": true,
+ "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.",
+ "hasWhenToUse": true,
+ "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.",
+ "hasExample": false,
+ "hasAttrs": false,
+ "attrs": [],
+ "hasChildren": true,
+ "children": [
+ "`operation.export` — 0..*",
+ "`operation.import` — 0..*"
+ ],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "api.eventing",
+ "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "hasOwner": true,
+ "owner": "metaobjects-rules",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": true,
+ "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.",
+ "hasWhenToUse": true,
+ "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.",
+ "hasExample": false,
+ "hasAttrs": false,
+ "attrs": [],
+ "hasChildren": true,
+ "children": [
+ "`operation.event` — 0..*"
+ ],
+ "hasParents": false
+ },
{
"typeSubType": "api.operational",
"description": "A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (`v1`, `v2`) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
@@ -33,7 +74,8 @@
"attrs": [],
"hasChildren": true,
"children": [
- "`operation.*` — 0..*"
+ "`operation.command` — 0..*",
+ "`operation.query` — 0..*"
],
"hasParents": false
}
diff --git a/fixtures/metamodel-docs/data/types/app.md.json b/fixtures/metamodel-docs/data/types/app.md.json
index 66b0ed7eff..b4d6e774fb 100644
--- a/fixtures/metamodel-docs/data/types/app.md.json
+++ b/fixtures/metamodel-docs/data/types/app.md.json
@@ -80,6 +80,24 @@
"hasExample": false,
"hasAttrs": true,
"attrs": [
+ {
+ "name": "extracts",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object."
+ },
+ {
+ "name": "provides",
+ "type": "string[]",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND."
+ },
{
"name": "runsAs",
"type": "string",
@@ -118,6 +136,15 @@
"hasExample": false,
"hasAttrs": true,
"attrs": [
+ {
+ "name": "provides",
+ "type": "string[]",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND."
+ },
{
"name": "public",
"type": "boolean",
diff --git a/fixtures/metamodel-docs/data/types/binding.md.json b/fixtures/metamodel-docs/data/types/binding.md.json
index 22527891db..d5ef5f1263 100644
--- a/fixtures/metamodel-docs/data/types/binding.md.json
+++ b/fixtures/metamodel-docs/data/types/binding.md.json
@@ -17,6 +17,114 @@
"children": [],
"hasParents": false
},
+ {
+ "typeSubType": "binding.file",
+ "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "hasOwner": true,
+ "owner": "metaobjects-rules",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": false,
+ "hasWhenToUse": true,
+ "whenToUse": "Every export and import whose file conventions two parties must agree on.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "completion",
+ "type": "string",
+ "required": "no",
+ "default": "`none`",
+ "allowed": "`rename`, `marker`, `none`",
+ "provider": "metaobjects-rules",
+ "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing."
+ },
+ {
+ "name": "compression",
+ "type": "string",
+ "required": "no",
+ "default": "`none`",
+ "allowed": "`none`, `gzip`",
+ "provider": "metaobjects-rules",
+ "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk."
+ },
+ {
+ "name": "encryption",
+ "type": "string",
+ "required": "no",
+ "default": "`none`",
+ "allowed": "`none`, `pgp`",
+ "provider": "metaobjects-rules",
+ "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key."
+ },
+ {
+ "name": "fileName",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-rules",
+ "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE."
+ },
+ {
+ "name": "format",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "`csv`, `jsonLines`, `parquet`",
+ "provider": "metaobjects-rules",
+ "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet."
+ },
+ {
+ "name": "path",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-rules",
+ "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store."
+ },
+ {
+ "name": "transport",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "`sftp`, `objectStore`",
+ "provider": "metaobjects-rules",
+ "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "binding.messaging",
+ "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "hasOwner": true,
+ "owner": "metaobjects-rules",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": false,
+ "hasWhenToUse": true,
+ "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "protocol",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "`kafka`, `amqp`, `mqtt`, `sqs`",
+ "provider": "metaobjects-rules",
+ "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
{
"typeSubType": "binding.rest",
"description": "The HTTP method and path of an operation, declared only to override the derived ones. A query is `GET`, a command `POST`; the path is `//{id}/` for an operation with a target key and `//` without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
diff --git a/fixtures/metamodel-docs/data/types/operation.md.json b/fixtures/metamodel-docs/data/types/operation.md.json
index 689bebf30d..d1275f21d4 100644
--- a/fixtures/metamodel-docs/data/types/operation.md.json
+++ b/fixtures/metamodel-docs/data/types/operation.md.json
@@ -3,7 +3,7 @@
"sections": [
{
"typeSubType": "operation.base",
- "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.",
+ "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.",
"hasOwner": true,
"owner": "metaobjects-rules",
"hasImplementedIn": false,
@@ -11,8 +11,34 @@
"hasRules": false,
"hasWhenToUse": false,
"hasExample": false,
+ "hasAttrs": false,
+ "attrs": [],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "operation.command",
+ "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "hasOwner": true,
+ "owner": "metaobjects-rules",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": false,
+ "hasWhenToUse": true,
+ "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.",
+ "hasExample": false,
"hasAttrs": true,
"attrs": [
+ {
+ "name": "errors",
+ "type": "string[]",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-rules",
+ "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE."
+ },
{
"name": "inputRef",
"type": "string",
@@ -57,94 +83,143 @@
"allowed": "",
"provider": "metaobjects-rules",
"description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT."
+ },
+ {
+ "name": "transitions",
+ "type": "string[]",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-rules",
+ "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)."
}
],
"hasChildren": true,
"children": [
- "`binding.*` — 0..*"
+ "`binding.rest` — 0..*"
],
"hasParents": false
},
{
- "typeSubType": "operation.command",
- "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "typeSubType": "operation.event",
+ "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
"hasOwner": true,
"owner": "metaobjects-rules",
"hasImplementedIn": false,
"hasPorts": false,
"hasRules": false,
"hasWhenToUse": true,
- "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.",
+ "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.",
"hasExample": false,
"hasAttrs": true,
"attrs": [
{
- "name": "errors",
- "type": "string[]",
+ "name": "key",
+ "type": "string",
"required": "no",
"default": "",
"allowed": "",
"provider": "metaobjects-rules",
- "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE."
+ "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised."
},
{
- "name": "inputRef",
+ "name": "outputRef",
"type": "string",
- "required": "no",
+ "required": "yes",
"default": "",
"allowed": "",
"provider": "metaobjects-rules",
- "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE."
- },
+ "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE."
+ }
+ ],
+ "hasChildren": true,
+ "children": [
+ "`binding.messaging` — 0..*"
+ ],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "operation.export",
+ "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "hasOwner": true,
+ "owner": "metaobjects-rules",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": false,
+ "hasWhenToUse": true,
+ "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
{
- "name": "objectRef",
+ "name": "availableBy",
"type": "string",
"required": "no",
"default": "",
"allowed": "",
"provider": "metaobjects-rules",
- "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)."
+ "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised."
},
{
- "name": "outputRef",
+ "name": "frequency",
"type": "string",
- "required": "no",
+ "required": "yes",
"default": "",
- "allowed": "",
+ "allowed": "`hourly`, `daily`, `weekly`, `monthly`",
"provider": "metaobjects-rules",
- "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE."
+ "description": "How often a new file appears: hourly, daily, weekly or monthly."
},
{
- "name": "permission",
+ "name": "outputRef",
"type": "string",
- "required": "no",
+ "required": "yes",
"default": "",
"allowed": "",
"provider": "metaobjects-rules",
- "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one."
- },
+ "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE."
+ }
+ ],
+ "hasChildren": true,
+ "children": [
+ "`binding.file` — 0..*"
+ ],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "operation.import",
+ "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "hasOwner": true,
+ "owner": "metaobjects-rules",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": false,
+ "hasWhenToUse": true,
+ "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
{
- "name": "public",
- "type": "boolean",
- "required": "no",
+ "name": "frequency",
+ "type": "string",
+ "required": "yes",
"default": "",
- "allowed": "",
+ "allowed": "`hourly`, `daily`, `weekly`, `monthly`",
"provider": "metaobjects-rules",
- "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT."
+ "description": "How often a new file is expected: hourly, daily, weekly or monthly."
},
{
- "name": "transitions",
- "type": "string[]",
- "required": "no",
+ "name": "inputRef",
+ "type": "string",
+ "required": "yes",
"default": "",
"allowed": "",
"provider": "metaobjects-rules",
- "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)."
+ "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE."
}
],
"hasChildren": true,
"children": [
- "`binding.*` — 0..*"
+ "`binding.file` — 0..*"
],
"hasParents": false
},
@@ -218,7 +293,7 @@
],
"hasChildren": true,
"children": [
- "`binding.*` — 0..*"
+ "`binding.rest` — 0..*"
],
"hasParents": false
}
diff --git a/fixtures/metamodel-docs/data/types/resource.md.json b/fixtures/metamodel-docs/data/types/resource.md.json
index 9bea5586f7..2583c18967 100644
--- a/fixtures/metamodel-docs/data/types/resource.md.json
+++ b/fixtures/metamodel-docs/data/types/resource.md.json
@@ -103,6 +103,15 @@
"hasExample": false,
"hasAttrs": true,
"attrs": [
+ {
+ "name": "carries",
+ "type": "string[]",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`."
+ },
{
"name": "publicRead",
"type": "boolean",
@@ -139,6 +148,15 @@
"hasExample": false,
"hasAttrs": true,
"attrs": [
+ {
+ "name": "carries",
+ "type": "string[]",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`."
+ },
{
"name": "deadLetter",
"type": "boolean",
@@ -247,6 +265,15 @@
"hasExample": false,
"hasAttrs": true,
"attrs": [
+ {
+ "name": "carries",
+ "type": "string[]",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`."
+ },
{
"name": "residency",
"type": "string",
diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md
index 800c390301..49591af340 100644
--- a/fixtures/metamodel-docs/expected/INDEX.md
+++ b/fixtures/metamodel-docs/expected/INDEX.md
@@ -16,6 +16,8 @@ children and the cardinality of that subtype. Documentation attributes
| Type.subType | Description | Page |
| --- | --- | --- |
| `api.base` | Registry anchor for the declared API surface (ADR-0030, ADR-0054): not authorable. The `api` subtype axis is the interaction model, never the protocol; protocol lives in `binding.*` on each operation. | [types/api.md#apibase](types/api.md#apibase) |
+| `api.batch` | A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/api.md#apibatch](types/api.md#apibatch) |
+| `api.eventing` | A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/api.md#apieventing](types/api.md#apieventing) |
| `api.operational` | A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (`v1`, `v2`) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/api.md#apioperational](types/api.md#apioperational) |
| `app.base` | Abstract app base: the attributes every app.* shares. Not authored directly: an `app.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED). | [types/app.md#appbase](types/app.md#appbase) |
| `app.client` | Code that runs on the user's device: a single-page web app, a static site, a mobile app. It calls services; it serves nothing itself. | [types/app.md#appclient](types/app.md#appclient) |
@@ -33,6 +35,8 @@ children and the cardinality of that subtype. Documentation attributes
| `attr.properties` | A key/value map attribute (a bag of arbitrary author-supplied properties). Object-shaped value; the registered escape hatch for author-supplied properties (exempt from the strict-attr check, ADR-0023). | [types/attr.md#attrproperties](types/attr.md#attrproperties) |
| `attr.string` | A string-valued metadata attribute. Coerces to and validates as text; the default value-type for inline @-syntax attrs (array-of-string is the same subtype with isArray). | [types/attr.md#attrstring](types/attr.md#attrstring) |
| `binding.base` | Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable. | [types/binding.md#bindingbase](types/binding.md#bindingbase) |
+| `binding.file` | How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/binding.md#bindingfile](types/binding.md#bindingfile) |
+| `binding.messaging` | How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/binding.md#bindingmessaging](types/binding.md#bindingmessaging) |
| `binding.rest` | The HTTP method and path of an operation, declared only to override the derived ones. A query is `GET`, a command `POST`; the path is `//{id}/` for an operation with a target key and `//` without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/binding.md#bindingrest](types/binding.md#bindingrest) |
| `build.base` | Abstract build base: how an app's deployable is made, the same in every environment. A build is a child of an app. Not authored directly: a `build.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED). | [types/build.md#buildbase](types/build.md#buildbase) |
| `build.image` | The app is shipped as a prebuilt container image that its publisher keeps in a registry. The tag deployed is a setting, never an attribute here. | [types/build.md#buildimage](types/build.md#buildimage) |
@@ -81,8 +85,11 @@ children and the cardinality of that subtype. Documentation attributes
| `object.projection` | A derived read-only representation of entities. Its fields are extends-bound / origin-derived / self-declared-under-external-assembly, all read-only at the subtype level. Identity is optional and MUST extend an entity identity; sources are restricted to read-only @kinds. The declared field set IS the exposure (inclusive, fail-closed). | [types/object.md#objectprojection](types/object.md#objectprojection) |
| `object.report` | A declared report (FR-044): a fixed combination of dimensions and measures of ONE entity (@from), compiled to a read-only view. One row per distinct dimension tuple; no dimensions means exactly one row. Fields are DERIVED, not declared: one per dimension (a time dimension's field is , e.g. purchasedAtDay) and one per measure. Every measure must belong to @from (two fact tables are two reports). @filter and @segment scope rows before grouping and combine by AND. Read-only: no writes, no get-by-id. | [types/object.md#objectreport](types/object.md#objectreport) |
| `object.value` | A value object — pure shape with NO identity and NO source, ever. Constructed (by caller / embedding), never populated from a store. May `extends` an entity's fields to reuse shape. Equality is by content. | [types/object.md#objectvalue](types/object.md#objectvalue) |
-| `operation.base` | Registry anchor for the attributes every operation shares (ADR-0054): not authorable. | [types/operation.md#operationbase](types/operation.md#operationbase) |
+| `operation.base` | Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes. | [types/operation.md#operationbase](types/operation.md#operationbase) |
| `operation.command` | A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/operation.md#operationcommand](types/operation.md#operationcommand) |
+| `operation.event` | Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/operation.md#operationevent](types/operation.md#operationevent) |
+| `operation.export` | A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/operation.md#operationexport](types/operation.md#operationexport) |
+| `operation.import` | A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/operation.md#operationimport](types/operation.md#operationimport) |
| `operation.query` | A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/operation.md#operationquery](types/operation.md#operationquery) |
| `organization.base` | Abstract organization base: the shared root of organization.company and organization.unit (ADR-0070, call 2). Not authored directly: an `organization.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED). | [types/organization.md#organizationbase](types/organization.md#organizationbase) |
| `organization.company` | A legal entity: it can own systems, operate environments and be handed credentials. Declared once, by the company itself, under its own package, and imported by everyone else. There is no vendor or customer kind: whether a company is one is a fact about the reader, not the company. | [types/organization.md#organizationcompany](types/organization.md#organizationcompany) |
diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md
index 24e2d772b7..ae60534939 100644
--- a/fixtures/metamodel-docs/expected/providers.md
+++ b/fixtures/metamodel-docs/expected/providers.md
@@ -160,14 +160,18 @@ Requirements: requirement.functional and requirement.architectural, declared at
Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).
-**Owns (registers):** `api.base`, `api.operational`, `binding.base`, `binding.rest`, `operation.base`, `operation.command`, `operation.query`, `transition.action`, `transition.base`
+**Owns (registers):** `api.base`, `api.batch`, `api.eventing`, `api.operational`, `binding.base`, `binding.file`, `binding.messaging`, `binding.rest`, `operation.base`, `operation.command`, `operation.event`, `operation.export`, `operation.import`, `operation.query`, `transition.action`, `transition.base`
**Contributes attributes:**
+- `binding.file`: `@completion`, `@compression`, `@encryption`, `@fileName`, `@format`, `@path`, `@transport`
+- `binding.messaging`: `@protocol`
- `binding.rest`: `@method`, `@path`
-- `operation.base`: `@inputRef`, `@objectRef`, `@outputRef`, `@permission`, `@public`
-- `operation.command`: `@errors`, `@transitions`
-- `operation.query`: `@many`
+- `operation.command`: `@errors`, `@inputRef`, `@objectRef`, `@outputRef`, `@permission`, `@public`, `@transitions`
+- `operation.event`: `@key`, `@outputRef`
+- `operation.export`: `@availableBy`, `@frequency`, `@outputRef`
+- `operation.import`: `@frequency`, `@inputRef`
+- `operation.query`: `@inputRef`, `@many`, `@objectRef`, `@outputRef`, `@permission`, `@public`
- `transition.action`: `@condition`, `@from`, `@to`
- `transition.base`: `@permission`, `@public`
@@ -181,8 +185,8 @@ Systems (ADR-0070): organization, system.software, app (service, client, job), b
- `app.base`: `@runsAs`
- `app.client`: `@shell`
-- `app.job`: `@schedule`
-- `app.service`: `@public`
+- `app.job`: `@extracts`, `@provides`, `@schedule`
+- `app.service`: `@provides`, `@public`
- `build.image`: `@repository`
- `grant.api`: `@api`, `@credential`, `@operations`
- `grant.document`: `@access`, `@collection`, `@resource`
@@ -194,9 +198,10 @@ Systems (ADR-0070): organization, system.software, app (service, client, job), b
- `grant.stream`: `@access`, `@resource`
- `resource.base`: `@residency`
- `resource.keyValue`: `@volatile`
-- `resource.objectStore`: `@publicRead`
-- `resource.queue`: `@deadLetter`, `@ordered`
+- `resource.objectStore`: `@carries`, `@publicRead`
+- `resource.queue`: `@carries`, `@deadLetter`, `@ordered`
- `resource.rdb`: `@schemas`
+- `resource.stream`: `@carries`
- `role.base`: `@credential`, `@memberOf`
- `role.token`: `@heldBy`
- `source.document`: `@collection`, `@resource`
diff --git a/fixtures/metamodel-docs/expected/types/api.md b/fixtures/metamodel-docs/expected/types/api.md
index 63febeb56f..7e05f6781c 100644
--- a/fixtures/metamodel-docs/expected/types/api.md
+++ b/fixtures/metamodel-docs/expected/types/api.md
@@ -24,6 +24,43 @@ _No subtype-specific attributes._
_No structural children._
+### api.batch
+
+A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
+**Owning provider:** metaobjects-rules
+
+**Rules:** Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.
+
+**When to use:** A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.
+
+**Attributes**
+
+_No subtype-specific attributes._
+
+**Allowed children**
+
+- `operation.export` — 0..*
+- `operation.import` — 0..*
+
+### api.eventing
+
+A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
+**Owning provider:** metaobjects-rules
+
+**Rules:** Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.
+
+**When to use:** Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.
+
+**Attributes**
+
+_No subtype-specific attributes._
+
+**Allowed children**
+
+- `operation.event` — 0..*
+
### api.operational
A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (`v1`, `v2`) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
@@ -40,5 +77,6 @@ _No subtype-specific attributes._
**Allowed children**
-- `operation.*` — 0..*
+- `operation.command` — 0..*
+- `operation.query` — 0..*
diff --git a/fixtures/metamodel-docs/expected/types/app.md b/fixtures/metamodel-docs/expected/types/app.md
index 926cdfd6e2..9cd3ff6c01 100644
--- a/fixtures/metamodel-docs/expected/types/app.md
+++ b/fixtures/metamodel-docs/expected/types/app.md
@@ -57,6 +57,8 @@ Work that runs to completion and exits: a scheduled task, a migration, a one-off
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
+| `@extracts` | string | no | | | metaobjects-systems-core | The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object. |
+| `@provides` | string[] | no | | | metaobjects-systems-core | The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. |
| `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system). |
| `@schedule` | string | no | | | metaobjects-systems-core | When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered. |
@@ -76,6 +78,7 @@ A long-running process that answers requests: a web server, an API, a socket ser
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
+| `@provides` | string[] | no | | | metaobjects-systems-core | The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. |
| `@public` | boolean | no | | | metaobjects-systems-core | The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names. |
| `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system). |
diff --git a/fixtures/metamodel-docs/expected/types/binding.md b/fixtures/metamodel-docs/expected/types/binding.md
index c7b5fa826e..71555f3893 100644
--- a/fixtures/metamodel-docs/expected/types/binding.md
+++ b/fixtures/metamodel-docs/expected/types/binding.md
@@ -24,6 +24,48 @@ _No subtype-specific attributes._
_No structural children._
+### binding.file
+
+How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
+**Owning provider:** metaobjects-rules
+
+**When to use:** Every export and import whose file conventions two parties must agree on.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@completion` | string | no | `none` | `rename`, `marker`, `none` | metaobjects-rules | How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing. |
+| `@compression` | string | no | `none` | `none`, `gzip` | metaobjects-rules | none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk. |
+| `@encryption` | string | no | `none` | `none`, `pgp` | metaobjects-rules | none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key. |
+| `@fileName` | string | yes | | | metaobjects-rules | The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE. |
+| `@format` | string | yes | | `csv`, `jsonLines`, `parquet` | metaobjects-rules | How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`""`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet. |
+| `@path` | string | no | | | metaobjects-rules | The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store. |
+| `@transport` | string | yes | | `sftp`, `objectStore` | metaobjects-rules | How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product. |
+
+**Allowed children**
+
+_No structural children._
+
+### binding.messaging
+
+How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
+**Owning provider:** metaobjects-rules
+
+**When to use:** Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@protocol` | string | no | | `kafka`, `amqp`, `mqtt`, `sqs` | metaobjects-rules | The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks. |
+
+**Allowed children**
+
+_No structural children._
+
### binding.rest
The HTTP method and path of an operation, declared only to override the derived ones. A query is `GET`, a command `POST`; the path is `//{id}/` for an operation with a target key and `//` without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
diff --git a/fixtures/metamodel-docs/expected/types/operation.md b/fixtures/metamodel-docs/expected/types/operation.md
index 65b92ceb9e..7ff5ec3446 100644
--- a/fixtures/metamodel-docs/expected/types/operation.md
+++ b/fixtures/metamodel-docs/expected/types/operation.md
@@ -12,23 +12,17 @@ documentation attributes are omitted here (see [providers.md](../providers.md)).
### operation.base
-Registry anchor for the attributes every operation shares (ADR-0054): not authorable.
+Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.
**Owning provider:** metaobjects-rules
**Attributes**
-| Attribute | Type | Required | Default | Allowed values | Provider | Description |
-| --- | --- | --- | --- | --- | --- | --- |
-| `@inputRef` | string | no | | | metaobjects-rules | The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE. |
-| `@objectRef` | string | no | | | metaobjects-rules | The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED). |
-| `@outputRef` | string | no | | | metaobjects-rules | The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE. |
-| `@permission` | string | no | | | metaobjects-rules | The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one. |
-| `@public` | boolean | no | | | metaobjects-rules | The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT. |
+_No subtype-specific attributes._
**Allowed children**
-- `binding.*` — 0..*
+_No structural children._
### operation.command
@@ -52,7 +46,65 @@ A named operation that changes state. Takes an `object.value` (ADR-0030). Its bo
**Allowed children**
-- `binding.*` — 0..*
+- `binding.rest` — 0..*
+
+### operation.event
+
+Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
+**Owning provider:** metaobjects-rules
+
+**When to use:** Each distinct fact a consumer may react to: placed, delivered, cancelled.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@key` | string | no | | | metaobjects-rules | The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised. |
+| `@outputRef` | string | yes | | | metaobjects-rules | The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE. |
+
+**Allowed children**
+
+- `binding.messaging` — 0..*
+
+### operation.export
+
+A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
+**Owning provider:** metaobjects-rules
+
+**When to use:** A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@availableBy` | string | no | | | metaobjects-rules | The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised. |
+| `@frequency` | string | yes | | `hourly`, `daily`, `weekly`, `monthly` | metaobjects-rules | How often a new file appears: hourly, daily, weekly or monthly. |
+| `@outputRef` | string | yes | | | metaobjects-rules | The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE. |
+
+**Allowed children**
+
+- `binding.file` — 0..*
+
+### operation.import
+
+A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
+**Owning provider:** metaobjects-rules
+
+**When to use:** A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@frequency` | string | yes | | `hourly`, `daily`, `weekly`, `monthly` | metaobjects-rules | How often a new file is expected: hourly, daily, weekly or monthly. |
+| `@inputRef` | string | yes | | | metaobjects-rules | The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE. |
+
+**Allowed children**
+
+- `binding.file` — 0..*
### operation.query
@@ -75,5 +127,5 @@ A named operation that reads. Returns an `object.projection` (or an entity or va
**Allowed children**
-- `binding.*` — 0..*
+- `binding.rest` — 0..*
diff --git a/fixtures/metamodel-docs/expected/types/resource.md b/fixtures/metamodel-docs/expected/types/resource.md
index 1063ea9314..24c769589d 100644
--- a/fixtures/metamodel-docs/expected/types/resource.md
+++ b/fixtures/metamodel-docs/expected/types/resource.md
@@ -75,6 +75,7 @@ Files and blobs addressed by key.
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
+| `@carries` | string[] | no | | | metaobjects-systems-core | The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`. |
| `@publicRead` | boolean | no | | | metaobjects-systems-core | Anyone may read the objects without a credential. Absent means every read needs a grant. |
| `@residency` | string | no | `free` | `free`, `confined` | metaobjects-systems-core | Where the data may be kept. confined: every copy of this data, in any one provision, stays inside one jurisdiction, and only apps running inside it may reach it directly. free (the default): no such limit. |
@@ -94,6 +95,7 @@ A message queue: each message is handed to one consumer and gone once it is hand
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
+| `@carries` | string[] | no | | | metaobjects-systems-core | The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`. |
| `@deadLetter` | boolean | no | | | metaobjects-systems-core | A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting. |
| `@ordered` | boolean | no | | | metaobjects-systems-core | Messages with the same key are delivered in the order they were sent. Absent means no order is promised. |
| `@residency` | string | no | `free` | `free`, `confined` | metaobjects-systems-core | Where the data may be kept. confined: every copy of this data, in any one provision, stays inside one jurisdiction, and only apps running inside it may reach it directly. free (the default): no such limit. |
@@ -151,6 +153,7 @@ A retained, ordered log that many consumers read, each at its own position. A me
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
+| `@carries` | string[] | no | | | metaobjects-systems-core | The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`. |
| `@residency` | string | no | `free` | `free`, `confined` | metaobjects-systems-core | Where the data may be kept. confined: every copy of this data, in any one provision, stays inside one jurisdiction, and only apps running inside it may reach it directly. free (the default): no such limit. |
**Allowed children**
diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json
index 5706cbd3a3..88ce79c87c 100644
--- a/fixtures/registry-conformance/expected-registry.json
+++ b/fixtures/registry-conformance/expected-registry.json
@@ -8,6 +8,47 @@
"attrs": [],
"children": []
},
+ {
+ "type": "api",
+ "subType": "batch",
+ "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.",
+ "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.",
+ "attrs": [],
+ "children": [
+ {
+ "childType": "operation",
+ "childSubType": "export",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ },
+ {
+ "childType": "operation",
+ "childSubType": "import",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ }
+ ]
+ },
+ {
+ "type": "api",
+ "subType": "eventing",
+ "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.",
+ "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.",
+ "attrs": [],
+ "children": [
+ {
+ "childType": "operation",
+ "childSubType": "event",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ }
+ ]
+ },
{
"type": "api",
"subType": "operational",
@@ -18,7 +59,14 @@
"children": [
{
"childType": "operation",
- "childSubType": "*",
+ "childSubType": "command",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ },
+ {
+ "childType": "operation",
+ "childSubType": "query",
"childName": "*",
"min": 0,
"max": null
@@ -101,6 +149,30 @@
"description": "Work that runs to completion and exits: a scheduled task, a migration, a one-off batch. It may run on a schedule (@schedule) or when something triggers it.",
"whenToUse": "A cron job, a nightly import, a queue drain that is not a long-running service.",
"attrs": [
+ {
+ "name": "extracts",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "ref": {
+ "targetType": "object",
+ "targetSubTypes": [
+ "entity",
+ "projection"
+ ]
+ },
+ "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object."
+ },
+ {
+ "name": "provides",
+ "valueType": "string",
+ "isArray": true,
+ "required": false,
+ "ref": {
+ "targetType": "api"
+ },
+ "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND."
+ },
{
"name": "runsAs",
"valueType": "string",
@@ -140,6 +212,16 @@
"description": "A long-running process that answers requests: a web server, an API, a socket server.",
"whenToUse": "Anything that listens on a port and stays up.",
"attrs": [
+ {
+ "name": "provides",
+ "valueType": "string",
+ "isArray": true,
+ "required": false,
+ "ref": {
+ "targetType": "api"
+ },
+ "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND."
+ },
{
"name": "public",
"valueType": "boolean",
@@ -257,6 +339,108 @@
"attrs": [],
"children": []
},
+ {
+ "type": "binding",
+ "subType": "file",
+ "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Every export and import whose file conventions two parties must agree on.",
+ "attrs": [
+ {
+ "name": "completion",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "allowedValues": [
+ "rename",
+ "marker",
+ "none"
+ ],
+ "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing."
+ },
+ {
+ "name": "compression",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "allowedValues": [
+ "none",
+ "gzip"
+ ],
+ "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk."
+ },
+ {
+ "name": "encryption",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "allowedValues": [
+ "none",
+ "pgp"
+ ],
+ "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key."
+ },
+ {
+ "name": "fileName",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE."
+ },
+ {
+ "name": "format",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "allowedValues": [
+ "csv",
+ "jsonLines",
+ "parquet"
+ ],
+ "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet."
+ },
+ {
+ "name": "path",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store."
+ },
+ {
+ "name": "transport",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "allowedValues": [
+ "sftp",
+ "objectStore"
+ ],
+ "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product."
+ }
+ ],
+ "children": []
+ },
+ {
+ "type": "binding",
+ "subType": "messaging",
+ "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.",
+ "attrs": [
+ {
+ "name": "protocol",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "allowedValues": [
+ "kafka",
+ "amqp",
+ "mqtt",
+ "sqs"
+ ],
+ "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks."
+ }
+ ],
+ "children": []
+ },
{
"type": "binding",
"subType": "rest",
@@ -4553,8 +4737,23 @@
{
"type": "operation",
"subType": "base",
- "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.",
+ "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.",
+ "attrs": [],
+ "children": []
+ },
+ {
+ "type": "operation",
+ "subType": "command",
+ "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.",
"attrs": [
+ {
+ "name": "errors",
+ "valueType": "string",
+ "isArray": true,
+ "required": false,
+ "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE."
+ },
{
"name": "inputRef",
"valueType": "string",
@@ -4589,12 +4788,19 @@
"isArray": false,
"required": false,
"description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT."
+ },
+ {
+ "name": "transitions",
+ "valueType": "string",
+ "isArray": true,
+ "required": false,
+ "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)."
}
],
"children": [
{
"childType": "binding",
- "childSubType": "*",
+ "childSubType": "rest",
"childName": "*",
"min": 0,
"max": null
@@ -4603,64 +4809,110 @@
},
{
"type": "operation",
- "subType": "command",
- "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
- "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.",
+ "subType": "event",
+ "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.",
"attrs": [
{
- "name": "errors",
+ "name": "key",
"valueType": "string",
- "isArray": true,
+ "isArray": false,
"required": false,
- "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE."
+ "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised."
},
{
- "name": "inputRef",
+ "name": "outputRef",
"valueType": "string",
"isArray": false,
- "required": false,
- "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE."
- },
+ "required": true,
+ "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE."
+ }
+ ],
+ "children": [
{
- "name": "objectRef",
+ "childType": "binding",
+ "childSubType": "messaging",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ }
+ ]
+ },
+ {
+ "type": "operation",
+ "subType": "export",
+ "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.",
+ "attrs": [
+ {
+ "name": "availableBy",
"valueType": "string",
"isArray": false,
"required": false,
- "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)."
+ "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised."
},
{
- "name": "outputRef",
+ "name": "frequency",
"valueType": "string",
"isArray": false,
- "required": false,
- "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE."
+ "required": true,
+ "allowedValues": [
+ "hourly",
+ "daily",
+ "weekly",
+ "monthly"
+ ],
+ "description": "How often a new file appears: hourly, daily, weekly or monthly."
},
{
- "name": "permission",
+ "name": "outputRef",
"valueType": "string",
"isArray": false,
- "required": false,
- "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one."
- },
+ "required": true,
+ "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE."
+ }
+ ],
+ "children": [
{
- "name": "public",
- "valueType": "boolean",
+ "childType": "binding",
+ "childSubType": "file",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ }
+ ]
+ },
+ {
+ "type": "operation",
+ "subType": "import",
+ "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.",
+ "attrs": [
+ {
+ "name": "frequency",
+ "valueType": "string",
"isArray": false,
- "required": false,
- "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT."
+ "required": true,
+ "allowedValues": [
+ "hourly",
+ "daily",
+ "weekly",
+ "monthly"
+ ],
+ "description": "How often a new file is expected: hourly, daily, weekly or monthly."
},
{
- "name": "transitions",
+ "name": "inputRef",
"valueType": "string",
- "isArray": true,
- "required": false,
- "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)."
+ "isArray": false,
+ "required": true,
+ "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE."
}
],
"children": [
{
"childType": "binding",
- "childSubType": "*",
+ "childSubType": "file",
"childName": "*",
"min": 0,
"max": null
@@ -4719,7 +4971,7 @@
"children": [
{
"childType": "binding",
- "childSubType": "*",
+ "childSubType": "rest",
"childName": "*",
"min": 0,
"max": null
@@ -5519,6 +5771,19 @@
"description": "Files and blobs addressed by key.",
"whenToUse": "Uploaded images, exports, static assets kept outside the app.",
"attrs": [
+ {
+ "name": "carries",
+ "valueType": "string",
+ "isArray": true,
+ "required": false,
+ "ref": {
+ "targetType": "api",
+ "targetSubTypes": [
+ "batch"
+ ]
+ },
+ "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`."
+ },
{
"name": "publicRead",
"valueType": "boolean",
@@ -5546,6 +5811,19 @@
"description": "A message queue: each message is handed to one consumer and gone once it is handled.",
"whenToUse": "Work handed from one app to another to run later.",
"attrs": [
+ {
+ "name": "carries",
+ "valueType": "string",
+ "isArray": true,
+ "required": false,
+ "ref": {
+ "targetType": "api",
+ "targetSubTypes": [
+ "eventing"
+ ]
+ },
+ "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`."
+ },
{
"name": "deadLetter",
"valueType": "boolean",
@@ -5627,6 +5905,19 @@
"description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.",
"whenToUse": "Events several consumers read independently, or read again.",
"attrs": [
+ {
+ "name": "carries",
+ "valueType": "string",
+ "isArray": true,
+ "required": false,
+ "ref": {
+ "targetType": "api",
+ "targetSubTypes": [
+ "eventing"
+ ]
+ },
+ "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`."
+ },
{
"name": "residency",
"valueType": "string",
diff --git a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs
index 96381f0178..81476bd085 100644
--- a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs
+++ b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (160 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into C#'s own suite and write the assertion the
@@ -52,10 +52,26 @@ public void declare_attributeValueTypes_attrProperties() { /* metaobjects.declar
[Fact(Skip = "unfilled slot — write an assertion that fails when: A number written where a name belongs, coerced to text, and emitted into generated code as a name.")]
public void declare_attributeValueTypes_attrString() { /* metaobjects.declare.attributeValueTypes.attrString */ }
+ // Batch API — A batch API is a named surface at the top of a document whose children are the files a provider publishes or accepts on a schedule; the operation rules of an operational API do not apply to it, and no generator writes from it yet.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A nightly file described only in a runbook, so the consumer learns its columns from the first file that arrives.")]
+ public void declare_businessRules_apiBatch() { /* metaobjects.declare.businessRules.apiBatch */ }
+
+ // Eventing API — An eventing API is a named surface at the top of a document whose children are the events a provider publishes; the operation rules of an operational API do not apply to it, and no generator writes from it yet.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: An event declared as a command, so a generated route accepts a POST for something the provider only ever emits.")]
+ public void declare_businessRules_apiEventing() { /* metaobjects.declare.businessRules.apiEventing */ }
+
// Operational API — An operational API is a named surface at the top of a document whose children are the package's declared operations.
[Fact(Skip = "unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.")]
public void declare_businessRules_apiOperational() { /* metaobjects.declare.businessRules.apiOperational */ }
+ // File binding — A file binding names how the file is moved, how its name is formed from the run's UTC date or time and nothing else, and its format. It may name the folder the file is put in, its compression, its encryption and how a reader knows the file is whole; each of the last three is none when not named.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.")]
+ public void declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ }
+
+ // Messaging binding — A messaging binding may name the protocol an event is published over.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.")]
+ public void declare_businessRules_bindingMessaging() { /* metaobjects.declare.businessRules.bindingMessaging */ }
+
// REST binding — A REST binding overrides an operation's derived method or path, and a path addressing one row names exactly its target's key fields.
[Fact(Skip = "unfilled slot — write an assertion that fails when: A path whose placeholder names a field the target does not key on, so the route resolves the wrong row.")]
public void declare_businessRules_bindingRest() { /* metaobjects.declare.businessRules.bindingRest */ }
@@ -64,6 +80,18 @@ public void declare_businessRules_bindingRest() { /* metaobjects.declare.busines
[Fact(Skip = "unfilled slot — write an assertion that fails when: A command whose declared target disagrees with the key its input carries, so the permission check guards one entity and the write touches another.")]
public void declare_businessRules_operationCommand() { /* metaobjects.declare.businessRules.operationCommand */ }
+ // Event — An event names the declared shape of its payload and may name the field whose events must stay in order.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.")]
+ public void declare_businessRules_operationEvent() { /* metaobjects.declare.businessRules.operationEvent */ }
+
+ // Export — An export names the shape of one row of the file and how often the file is written, and may name by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.")]
+ public void declare_businessRules_operationExport() { /* metaobjects.declare.businessRules.operationExport */ }
+
+ // Import — An import names the declared value one row of the file must match and how often the file arrives.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A file of rows the provider cannot read, discovered when the first scheduled run fails.")]
+ public void declare_businessRules_operationImport() { /* metaobjects.declare.businessRules.operationImport */ }
+
// Query — A query declares what it returns, an entity, a projection or a value, and whether it returns a list.
[Fact(Skip = "unfilled slot — write an assertion that fails when: A query that returns a list on one port and a single row on another because nothing said which.")]
public void declare_businessRules_operationQuery() { /* metaobjects.declare.businessRules.operationQuery */ }
diff --git a/fixtures/requirement-harness/java/RequirementHarnessTest.java b/fixtures/requirement-harness/java/RequirementHarnessTest.java
index d00ac8bd42..bdc7be6561 100644
--- a/fixtures/requirement-harness/java/RequirementHarnessTest.java
+++ b/fixtures/requirement-harness/java/RequirementHarnessTest.java
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (160 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into Java's own suite and write the assertion the
@@ -62,11 +62,31 @@ void declare_attributeValueTypes_attrProperties() { /* metaobjects.declare.attri
@Disabled("unfilled slot — write an assertion that fails when: A number written where a name belongs, coerced to text, and emitted into generated code as a name.")
void declare_attributeValueTypes_attrString() { /* metaobjects.declare.attributeValueTypes.attrString */ }
+ // Batch API — A batch API is a named surface at the top of a document whose children are the files a provider publishes or accepts on a schedule; the operation rules of an operational API do not apply to it, and no generator writes from it yet.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A nightly file described only in a runbook, so the consumer learns its columns from the first file that arrives.")
+ void declare_businessRules_apiBatch() { /* metaobjects.declare.businessRules.apiBatch */ }
+
+ // Eventing API — An eventing API is a named surface at the top of a document whose children are the events a provider publishes; the operation rules of an operational API do not apply to it, and no generator writes from it yet.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: An event declared as a command, so a generated route accepts a POST for something the provider only ever emits.")
+ void declare_businessRules_apiEventing() { /* metaobjects.declare.businessRules.apiEventing */ }
+
// Operational API — An operational API is a named surface at the top of a document whose children are the package's declared operations.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.")
void declare_businessRules_apiOperational() { /* metaobjects.declare.businessRules.apiOperational */ }
+ // File binding — A file binding names how the file is moved, how its name is formed from the run's UTC date or time and nothing else, and its format. It may name the folder the file is put in, its compression, its encryption and how a reader knows the file is whole; each of the last three is none when not named.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.")
+ void declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ }
+
+ // Messaging binding — A messaging binding may name the protocol an event is published over.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.")
+ void declare_businessRules_bindingMessaging() { /* metaobjects.declare.businessRules.bindingMessaging */ }
+
// REST binding — A REST binding overrides an operation's derived method or path, and a path addressing one row names exactly its target's key fields.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A path whose placeholder names a field the target does not key on, so the route resolves the wrong row.")
@@ -77,6 +97,21 @@ void declare_businessRules_bindingRest() { /* metaobjects.declare.businessRules.
@Disabled("unfilled slot — write an assertion that fails when: A command whose declared target disagrees with the key its input carries, so the permission check guards one entity and the write touches another.")
void declare_businessRules_operationCommand() { /* metaobjects.declare.businessRules.operationCommand */ }
+ // Event — An event names the declared shape of its payload and may name the field whose events must stay in order.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.")
+ void declare_businessRules_operationEvent() { /* metaobjects.declare.businessRules.operationEvent */ }
+
+ // Export — An export names the shape of one row of the file and how often the file is written, and may name by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.")
+ void declare_businessRules_operationExport() { /* metaobjects.declare.businessRules.operationExport */ }
+
+ // Import — An import names the declared value one row of the file must match and how often the file arrives.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A file of rows the provider cannot read, discovered when the first scheduled run fails.")
+ void declare_businessRules_operationImport() { /* metaobjects.declare.businessRules.operationImport */ }
+
// Query — A query declares what it returns, an entity, a projection or a value, and whether it returns a list.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A query that returns a list on one port and a single row on another because nothing said which.")
diff --git a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt
index b298440758..a4915a8c9b 100644
--- a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt
+++ b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (160 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into Kotlin's own suite and write the assertion the
@@ -62,11 +62,31 @@ class RequirementHarnessTest {
@Disabled("unfilled slot — write an assertion that fails when: A number written where a name belongs, coerced to text, and emitted into generated code as a name.")
fun declare_attributeValueTypes_attrString() { /* metaobjects.declare.attributeValueTypes.attrString */ }
+ // Batch API — A batch API is a named surface at the top of a document whose children are the files a provider publishes or accepts on a schedule; the operation rules of an operational API do not apply to it, and no generator writes from it yet.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A nightly file described only in a runbook, so the consumer learns its columns from the first file that arrives.")
+ fun declare_businessRules_apiBatch() { /* metaobjects.declare.businessRules.apiBatch */ }
+
+ // Eventing API — An eventing API is a named surface at the top of a document whose children are the events a provider publishes; the operation rules of an operational API do not apply to it, and no generator writes from it yet.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: An event declared as a command, so a generated route accepts a POST for something the provider only ever emits.")
+ fun declare_businessRules_apiEventing() { /* metaobjects.declare.businessRules.apiEventing */ }
+
// Operational API — An operational API is a named surface at the top of a document whose children are the package's declared operations.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.")
fun declare_businessRules_apiOperational() { /* metaobjects.declare.businessRules.apiOperational */ }
+ // File binding — A file binding names how the file is moved, how its name is formed from the run's UTC date or time and nothing else, and its format. It may name the folder the file is put in, its compression, its encryption and how a reader knows the file is whole; each of the last three is none when not named.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.")
+ fun declare_businessRules_bindingFile() { /* metaobjects.declare.businessRules.bindingFile */ }
+
+ // Messaging binding — A messaging binding may name the protocol an event is published over.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.")
+ fun declare_businessRules_bindingMessaging() { /* metaobjects.declare.businessRules.bindingMessaging */ }
+
// REST binding — A REST binding overrides an operation's derived method or path, and a path addressing one row names exactly its target's key fields.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A path whose placeholder names a field the target does not key on, so the route resolves the wrong row.")
@@ -77,6 +97,21 @@ class RequirementHarnessTest {
@Disabled("unfilled slot — write an assertion that fails when: A command whose declared target disagrees with the key its input carries, so the permission check guards one entity and the write touches another.")
fun declare_businessRules_operationCommand() { /* metaobjects.declare.businessRules.operationCommand */ }
+ // Event — An event names the declared shape of its payload and may name the field whose events must stay in order.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.")
+ fun declare_businessRules_operationEvent() { /* metaobjects.declare.businessRules.operationEvent */ }
+
+ // Export — An export names the shape of one row of the file and how often the file is written, and may name by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.")
+ fun declare_businessRules_operationExport() { /* metaobjects.declare.businessRules.operationExport */ }
+
+ // Import — An import names the declared value one row of the file must match and how often the file arrives.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A file of rows the provider cannot read, discovered when the first scheduled run fails.")
+ fun declare_businessRules_operationImport() { /* metaobjects.declare.businessRules.operationImport */ }
+
// Query — A query declares what it returns, an entity, a projection or a value, and whether it returns a list.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A query that returns a list on one port and a single row on another because nothing said which.")
diff --git a/fixtures/requirement-harness/python/test_requirement_harness.py b/fixtures/requirement-harness/python/test_requirement_harness.py
index b72aed7396..24afe5e6da 100644
--- a/fixtures/requirement-harness/python/test_requirement_harness.py
+++ b/fixtures/requirement-harness/python/test_requirement_harness.py
@@ -1,6 +1,6 @@
# @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
#
-# One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them).
+# One slot per authored promise in metaobjects/meta.requirements.yaml (160 of them).
# Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
# claim that nothing is verified — the conformance corpora already check many of
# these. To FILL one, move it into Python's own suite and write the assertion the
@@ -57,11 +57,31 @@ def test_declare_attributeValueTypes_attrProperties():
def test_declare_attributeValueTypes_attrString():
"""metaobjects.declare.attributeValueTypes.attrString"""
+# Batch API — A batch API is a named surface at the top of a document whose children are the files a provider publishes or accepts on a schedule; the operation rules of an operational API do not apply to it, and no generator writes from it yet.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A nightly file described only in a runbook, so the consumer learns its columns from the first file that arrives.")
+def test_declare_businessRules_apiBatch():
+ """metaobjects.declare.businessRules.apiBatch"""
+
+# Eventing API — An eventing API is a named surface at the top of a document whose children are the events a provider publishes; the operation rules of an operational API do not apply to it, and no generator writes from it yet.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: An event declared as a command, so a generated route accepts a POST for something the provider only ever emits.")
+def test_declare_businessRules_apiEventing():
+ """metaobjects.declare.businessRules.apiEventing"""
+
# Operational API — An operational API is a named surface at the top of a document whose children are the package's declared operations.
@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.")
def test_declare_businessRules_apiOperational():
"""metaobjects.declare.businessRules.apiOperational"""
+# File binding — A file binding names how the file is moved, how its name is formed from the run's UTC date or time and nothing else, and its format. It may name the folder the file is put in, its compression, its encryption and how a reader knows the file is whole; each of the last three is none when not named.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.")
+def test_declare_businessRules_bindingFile():
+ """metaobjects.declare.businessRules.bindingFile"""
+
+# Messaging binding — A messaging binding may name the protocol an event is published over.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.")
+def test_declare_businessRules_bindingMessaging():
+ """metaobjects.declare.businessRules.bindingMessaging"""
+
# REST binding — A REST binding overrides an operation's derived method or path, and a path addressing one row names exactly its target's key fields.
@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A path whose placeholder names a field the target does not key on, so the route resolves the wrong row.")
def test_declare_businessRules_bindingRest():
@@ -72,6 +92,21 @@ def test_declare_businessRules_bindingRest():
def test_declare_businessRules_operationCommand():
"""metaobjects.declare.businessRules.operationCommand"""
+# Event — An event names the declared shape of its payload and may name the field whose events must stay in order.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.")
+def test_declare_businessRules_operationEvent():
+ """metaobjects.declare.businessRules.operationEvent"""
+
+# Export — An export names the shape of one row of the file and how often the file is written, and may name by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.")
+def test_declare_businessRules_operationExport():
+ """metaobjects.declare.businessRules.operationExport"""
+
+# Import — An import names the declared value one row of the file must match and how often the file arrives.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A file of rows the provider cannot read, discovered when the first scheduled run fails.")
+def test_declare_businessRules_operationImport():
+ """metaobjects.declare.businessRules.operationImport"""
+
# Query — A query declares what it returns, an entity, a projection or a value, and whether it returns a list.
@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A query that returns a list on one port and a single row on another because nothing said which.")
def test_declare_businessRules_operationQuery():
diff --git a/fixtures/requirement-harness/typescript/requirement-harness.test.ts b/fixtures/requirement-harness/typescript/requirement-harness.test.ts
index f5c2733810..bcfaa5a649 100644
--- a/fixtures/requirement-harness/typescript/requirement-harness.test.ts
+++ b/fixtures/requirement-harness/typescript/requirement-harness.test.ts
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (160 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into TypeScript's own suite and write the assertion the
@@ -57,11 +57,31 @@ test.skip("metaobjects.declare.attributeValueTypes.attrString", () => {
// unfilled slot — write an assertion that fails when: A number written where a name belongs, coerced to text, and emitted into generated code as a name.
});
+// Batch API — A batch API is a named surface at the top of a document whose children are the files a provider publishes or accepts on a schedule; the operation rules of an operational API do not apply to it, and no generator writes from it yet.
+test.skip("metaobjects.declare.businessRules.apiBatch", () => {
+ // unfilled slot — write an assertion that fails when: A nightly file described only in a runbook, so the consumer learns its columns from the first file that arrives.
+});
+
+// Eventing API — An eventing API is a named surface at the top of a document whose children are the events a provider publishes; the operation rules of an operational API do not apply to it, and no generator writes from it yet.
+test.skip("metaobjects.declare.businessRules.apiEventing", () => {
+ // unfilled slot — write an assertion that fails when: An event declared as a command, so a generated route accepts a POST for something the provider only ever emits.
+});
+
// Operational API — An operational API is a named surface at the top of a document whose children are the package's declared operations.
test.skip("metaobjects.declare.businessRules.apiOperational", () => {
// unfilled slot — write an assertion that fails when: A command declared inside an entity, where a versioned second surface has nowhere to put it.
});
+// File binding — A file binding names how the file is moved, how its name is formed from the run's UTC date or time and nothing else, and its format. It may name the folder the file is put in, its compression, its encryption and how a reader knows the file is whole; each of the last three is none when not named.
+test.skip("metaobjects.declare.businessRules.bindingFile", () => {
+ // unfilled slot — write an assertion that fails when: A reader that opens a file still being written because nothing said the writer renames it when done.
+});
+
+// Messaging binding — A messaging binding may name the protocol an event is published over.
+test.skip("metaobjects.declare.businessRules.bindingMessaging", () => {
+ // unfilled slot — write an assertion that fails when: An event published over one broker protocol while its consumer is built for another.
+});
+
// REST binding — A REST binding overrides an operation's derived method or path, and a path addressing one row names exactly its target's key fields.
test.skip("metaobjects.declare.businessRules.bindingRest", () => {
// unfilled slot — write an assertion that fails when: A path whose placeholder names a field the target does not key on, so the route resolves the wrong row.
@@ -72,6 +92,21 @@ test.skip("metaobjects.declare.businessRules.operationCommand", () => {
// unfilled slot — write an assertion that fails when: A command whose declared target disagrees with the key its input carries, so the permission check guards one entity and the write touches another.
});
+// Event — An event names the declared shape of its payload and may name the field whose events must stay in order.
+test.skip("metaobjects.declare.businessRules.operationEvent", () => {
+ // unfilled slot — write an assertion that fails when: Two consumers that assume different ordering keys for one stream, and each processes some events out of order.
+});
+
+// Export — An export names the shape of one row of the file and how often the file is written, and may name by when in UTC it is ready, in the one form its frequency allows; a weekly or monthly file names its day.
+test.skip("metaobjects.declare.businessRules.operationExport", () => {
+ // unfilled slot — write an assertion that fails when: A weekly file promised at 06:00 with no day, so the consumer polls every morning and alarms six days a week.
+});
+
+// Import — An import names the declared value one row of the file must match and how often the file arrives.
+test.skip("metaobjects.declare.businessRules.operationImport", () => {
+ // unfilled slot — write an assertion that fails when: A file of rows the provider cannot read, discovered when the first scheduled run fails.
+});
+
// Query — A query declares what it returns, an entity, a projection or a value, and whether it returns a list.
test.skip("metaobjects.declare.businessRules.operationQuery", () => {
// unfilled slot — write an assertion that fails when: A query that returns a list on one port and a single row on another because nothing said which.
diff --git a/metaobjects/meta.requirements.yaml b/metaobjects/meta.requirements.yaml
index 49a9767153..68edf25a9f 100644
--- a/metaobjects/meta.requirements.yaml
+++ b/metaobjects/meta.requirements.yaml
@@ -1616,6 +1616,92 @@ metadata.root:
counterexample: >-
A path whose placeholder names a field the target does not
key on, so the route resolves the wrong row.
+ - requirement.functional:
+ name: apiEventing
+ title: Eventing API
+ level: 4
+ status: live
+ statement: >-
+ An eventing API is a named surface at the top of a document
+ whose children are the events a provider publishes; the
+ operation rules of an operational API do not apply to it, and
+ no generator writes from it yet.
+ counterexample: >-
+ An event declared as a command, so a generated route accepts a
+ POST for something the provider only ever emits.
+ - requirement.functional:
+ name: apiBatch
+ title: Batch API
+ level: 4
+ status: live
+ statement: >-
+ A batch API is a named surface at the top of a document whose
+ children are the files a provider publishes or accepts on a
+ schedule; the operation rules of an operational API do not
+ apply to it, and no generator writes from it yet.
+ counterexample: >-
+ A nightly file described only in a runbook, so the consumer
+ learns its columns from the first file that arrives.
+ - requirement.functional:
+ name: operationEvent
+ title: Event
+ level: 4
+ status: live
+ statement: >-
+ An event names the declared shape of its payload and may name
+ the field whose events must stay in order.
+ counterexample: >-
+ Two consumers that assume different ordering keys for one
+ stream, and each processes some events out of order.
+ - requirement.functional:
+ name: operationExport
+ title: Export
+ level: 4
+ status: live
+ statement: >-
+ An export names the shape of one row of the file and how often
+ the file is written, and may name by when in UTC it is ready,
+ in the one form its frequency allows; a weekly or monthly file
+ names its day.
+ counterexample: >-
+ A weekly file promised at 06:00 with no day, so the consumer
+ polls every morning and alarms six days a week.
+ - requirement.functional:
+ name: operationImport
+ title: Import
+ level: 4
+ status: live
+ statement: >-
+ An import names the declared value one row of the file must
+ match and how often the file arrives.
+ counterexample: >-
+ A file of rows the provider cannot read, discovered when the
+ first scheduled run fails.
+ - requirement.functional:
+ name: bindingMessaging
+ title: Messaging binding
+ level: 4
+ status: live
+ statement: >-
+ A messaging binding may name the protocol an event is published
+ over.
+ counterexample: >-
+ An event published over one broker protocol while its consumer
+ is built for another.
+ - requirement.functional:
+ name: bindingFile
+ title: File binding
+ level: 4
+ status: live
+ statement: >-
+ A file binding names how the file is moved, how its name is
+ formed from the run's UTC date or time and nothing else, and
+ its format. It may name the folder the file is put in, its
+ compression, its encryption and how a reader knows the file
+ is whole; each of the last three is none when not named.
+ counterexample: >-
+ A reader that opens a file still being written because nothing
+ said the writer renames it when done.
- requirement.functional:
name: transitionAction
title: Transition
diff --git a/scripts/check-metamodel-version.mjs b/scripts/check-metamodel-version.mjs
index 211602f688..28f2982b2b 100755
--- a/scripts/check-metamodel-version.mjs
+++ b/scripts/check-metamodel-version.mjs
@@ -53,6 +53,7 @@ import { fileURLToPath } from "node:url";
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const MANIFEST = "fixtures/registry-conformance/expected-registry.json";
+const EXCEPTIONS = "scripts/metamodel-version-exceptions.json";
/**
* Every site that declares the metamodel version. The manifest is the one the
@@ -282,6 +283,34 @@ function diffChildren(baseKids, curKids, where, breaking, additive) {
const git = (...args) =>
execFileSync("git", args, { cwd: REPO, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
+/**
+ * The exceptions ledger: a breaking finding excused against one baseline tag, with its reason.
+ * Throws when an entry lacks a baseline, a finding or a reason, so no exception is unexplained.
+ */
+export function readExceptions(ledger) {
+ const entries = ledger?.exceptions ?? [];
+ for (const [i, e] of entries.entries()) {
+ for (const key of ["baseline", "finding", "reason"]) {
+ if (typeof e?.[key] !== "string" || !e[key].trim()) {
+ throw new Error(`exception ${i} has no ${key}; every exception names its baseline, finding and reason`);
+ }
+ }
+ }
+ return entries;
+}
+
+/** Split breaking findings into those still breaking and the exceptions that excused the rest.
+ * An exception applies only when `against` is exactly its baseline tag. */
+export function applyExceptions(breaking, exceptions, against) {
+ const applied = [];
+ const kept = breaking.filter((f) => {
+ const e = exceptions.find((x) => x.baseline === against && x.finding === f);
+ if (e) applied.push(e);
+ return !e;
+ });
+ return { kept, applied };
+}
+
/** The highest published STABLE release tag on the npm/PyPI/NuGet line (`v0.*` / `v1.*` …).
* The four registries cut together, so any one line dates the metamodel baseline.
*
@@ -442,7 +471,21 @@ function main() {
const baseVer = parseVersion(baseline.metamodelVersion, against);
const curVer = parseVersion(current.metamodelVersion, "working tree");
- const { breaking, additive, prose } = classify(baseline, current);
+ const classified = classify(baseline, current);
+ const { additive, prose } = classified;
+ let exceptions;
+ try {
+ exceptions = readExceptions(JSON.parse(readFileSync(resolve(REPO, EXCEPTIONS), "utf8")));
+ } catch (e) {
+ fail(`${EXCEPTIONS}: ${e.message}`);
+ }
+ const { kept: breaking, applied } = applyExceptions(classified.breaking, exceptions, against);
+ if (applied.length) {
+ process.stdout.write(
+ ` metamodel-version: ${applied.length} breaking finding(s) excused against ${against} by ${EXCEPTIONS}:\n` +
+ `${bullets(applied.map((e) => e.finding))}\n`,
+ );
+ }
let severity = "none";
if (breaking.length) severity = "breaking";
else if (additive.length) severity = "additive";
diff --git a/scripts/check-requirements-ledger.ts b/scripts/check-requirements-ledger.ts
index 463535a3d3..9ef8d1ce25 100644
--- a/scripts/check-requirements-ledger.ts
+++ b/scripts/check-requirements-ledger.ts
@@ -48,7 +48,7 @@ const EXPECTED_WARNING = "WARN_REQUIREMENT_NOTHING_IMPLEMENTS";
* the neighbour — became `Number("metaobjects")`, i.e. NaN. Every comparison against
* NaN is unequal, so the gate failed reporting "expected NaN" and a remedy paragraph
* about updating the pin. */
-const DEFAULT_EXPECTED_WARNING_COUNT = 187;
+const DEFAULT_EXPECTED_WARNING_COUNT = 194;
function expectedWarnings(argv: readonly string[]): number {
const flag = argv.find((a) => a.startsWith("--expect-warnings="));
diff --git a/scripts/metamodel-version-exceptions.json b/scripts/metamodel-version-exceptions.json
new file mode 100644
index 0000000000..89d7f92f81
--- /dev/null
+++ b/scripts/metamodel-version-exceptions.json
@@ -0,0 +1,50 @@
+{
+ "$comment": "Breaking findings excused against ONE baseline tag, each with its reason. An entry applies only when that tag is the baseline being compared, so it expires at the next release. Read by scripts/check-metamodel-version.mjs.",
+ "exceptions": [
+ {
+ "baseline": "v1.3.1",
+ "finding": "child rule removed: api.operational ← operation.*/*",
+ "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change."
+ },
+ {
+ "baseline": "v1.3.1",
+ "finding": "attr removed: operation.base @inputRef",
+ "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change."
+ },
+ {
+ "baseline": "v1.3.1",
+ "finding": "attr removed: operation.base @objectRef",
+ "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change."
+ },
+ {
+ "baseline": "v1.3.1",
+ "finding": "attr removed: operation.base @outputRef",
+ "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change."
+ },
+ {
+ "baseline": "v1.3.1",
+ "finding": "attr removed: operation.base @permission",
+ "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change."
+ },
+ {
+ "baseline": "v1.3.1",
+ "finding": "attr removed: operation.base @public",
+ "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change."
+ },
+ {
+ "baseline": "v1.3.1",
+ "finding": "child rule removed: operation.base ← binding.*/*",
+ "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change."
+ },
+ {
+ "baseline": "v1.3.1",
+ "finding": "child rule removed: operation.command ← binding.*/*",
+ "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change."
+ },
+ {
+ "baseline": "v1.3.1",
+ "finding": "child rule removed: operation.query ← binding.*/*",
+ "reason": "operation.base is an abstract anchor nobody can author; operation.command and operation.query declare the same attrs and a binding.rest themselves; and in v1.3.1 operation.command and operation.query were the only operation subtypes and binding.rest the only binding subtype, so no document that uses only the core subtypes loses anything. A project provider's own operation subtype does lose these attrs, binding children and its place under api.operational; the upgrade note in changelog.d/api-eventing-and-batch.md says what to change."
+ }
+ ]
+}
diff --git a/scripts/test-metamodel-version.mjs b/scripts/test-metamodel-version.mjs
index 19190074cd..d41281c5f1 100755
--- a/scripts/test-metamodel-version.mjs
+++ b/scripts/test-metamodel-version.mjs
@@ -10,7 +10,15 @@
//
// node scripts/test-metamodel-version.mjs
-import { classify, requiredBump, satisfies, parseVersion, pickBaselineTag } from "./check-metamodel-version.mjs";
+import {
+ applyExceptions,
+ classify,
+ parseVersion,
+ pickBaselineTag,
+ readExceptions,
+ requiredBump,
+ satisfies,
+} from "./check-metamodel-version.mjs";
let fails = 0;
const ok = (m) => console.log(`ok: ${m}`);
@@ -266,6 +274,40 @@ check(
{ prose: 1 },
);
+// ---------------------------------------------------------------------------
+// The exceptions ledger: a breaking finding excused against one baseline tag only
+// ---------------------------------------------------------------------------
+
+{
+ const removed = classify(
+ manifest({ types: [type("thing", "a", { attrs: [attr("x"), attr("y")] })] }),
+ manifest({ types: [type("thing", "a")] }),
+ ).breaking;
+ const ledger = readExceptions({
+ exceptions: [{ baseline: "v1.3.1", finding: "attr removed: thing.a @x", reason: "nobody could set it" }],
+ });
+ const same = applyExceptions(removed, ledger, "v1.3.1");
+ if (same.kept.length === 1 && same.kept[0] === "attr removed: thing.a @y" && same.applied.length === 1) {
+ ok("a listed finding against its baseline is excused, and an unlisted one still breaks");
+ } else {
+ bad(`exceptions against their baseline: ${JSON.stringify(same)}`);
+ }
+ const other = applyExceptions(removed, ledger, "v1.4.0");
+ if (other.kept.length === 2 && other.applied.length === 0) {
+ ok("a listed finding compared against a different baseline still breaks");
+ } else {
+ bad(`exceptions against another baseline: ${JSON.stringify(other)}`);
+ }
+ let refused = false;
+ try {
+ readExceptions({ exceptions: [{ baseline: "v1.3.1", finding: "attr removed: thing.a @x", reason: " " }] });
+ } catch {
+ refused = true;
+ }
+ if (refused) ok("a ledger entry with no reason is refused");
+ else bad("a ledger entry with no reason was accepted");
+}
+
// ---------------------------------------------------------------------------
// Required bump + satisfaction
// ---------------------------------------------------------------------------
diff --git a/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs b/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs
index 66f183696b..aa222c581b 100644
--- a/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs
+++ b/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs
@@ -154,4 +154,48 @@ public void The_documentation_generators_are_among_those_compared()
var files = Emit(Load("with"), [Build(GeneratorRegistry.Entries["api-docs"])]);
Assert.Contains(files.Keys, k => k.StartsWith("api/", StringComparison.Ordinal));
}
+
+ // 1.4.0 — api.eventing and api.batch (operation.event / .export / .import, binding.messaging / .file) are
+ // registered and nothing is generated from them yet. with-delivery/ is with/ plus one API of each kind. Every
+ // generator but the model explorer (it lists every node) writes for it exactly what it writes for with/,
+ // the rules-layer and service generators included: they read only api.operational and pick the binding.rest
+ // by subtype.
+ private static IEnumerable> AllButExplorer() =>
+ GeneratorRegistry.Entries.Where(e => e.Key != "docs-site");
+
+ public static TheoryData DeliveryGeneratorNames()
+ {
+ var data = new TheoryData();
+ foreach (var name in AllButExplorer().Select(e => e.Key).Where(n => n != SharedModelTestSupport.Name)) data.Add(name);
+ return data;
+ }
+
+ [Fact]
+ public void The_with_delivery_model_really_carries_an_eventing_and_a_batch_api()
+ {
+ var kinds = Load("with-delivery").Root().Children()
+ .Where(c => c.Type == TYPE_API).Select(c => c.SubType).OrderBy(k => k, StringComparer.Ordinal).ToList();
+ Assert.Equal(new List { "batch", "eventing", "operational" }, kinds);
+ }
+
+ [Theory]
+ [MemberData(nameof(DeliveryGeneratorNames))]
+ public void Generator_emits_the_same_files_with_and_without_the_delivery_apis(string name)
+ {
+ var entry = GeneratorRegistry.Entries[name];
+ AssertSame(Emit(Load("with"), [Build(entry)]), Emit(Load("with-delivery"), [Build(entry)]), name);
+ }
+
+ [Fact]
+ public void Every_runnable_generator_in_one_run_emits_the_same_files_with_the_delivery_apis()
+ {
+ var runnable = AllButExplorer()
+ .Where(e => !Emit(Load("without"), [Build(e.Value)]).ContainsKey(""))
+ .ToList();
+ var expected = Emit(Load("with"), runnable.Select(e => Build(e.Value)).ToList());
+ var actual = Emit(Load("with-delivery"), runnable.Select(e => Build(e.Value)).ToList());
+ Assert.False(actual.ContainsKey(""), actual.GetValueOrDefault(""));
+ Assert.True(expected.Count > 10, $"only {expected.Count} files — the suite barely ran");
+ AssertSame(expected, actual, "one run");
+ }
}
diff --git a/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js b/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js
index a2681492a9..ec81740b86 100644
--- a/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js
+++ b/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js
@@ -265,5 +265,5 @@
`);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(`
`)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",`
`,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(`${tag}>`)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(`
-`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(`
`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
`}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`
${cols.map((o)=>`
${this.link(from,o.id)}
`).join("")}
`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`
`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`
`,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
None.
');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
None.
')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
Not scanned.
');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
No prompt text was read.
':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
None.
':`
${items.map((i)=>`
${i}
`).join("")}
`}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found
No such page
${escapeHtml2(r.path)} is not a page of this model.
`,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="
No model yet
The explorer is waiting for the running application's docs view.
";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="
explorer-model.js did not load. Run meta gen to write it beside this page.
";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})();
diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs
index 892cb79ce8..5e6e3afc84 100644
--- a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs
+++ b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs
@@ -284,6 +284,9 @@ public void The_reader_carries_a_facet_on_a_types_entry_attr()
"app.base @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM",
"app.client @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM",
"app.job @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM",
+ "app.job @extracts object/entity|projection False ",
+ "app.job @provides api False ",
+ "app.service @provides api False ",
"app.service @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM",
"grant.api @api api False ",
"grant.rdb @resource resource/rdb False sameSystem ERR_GRANT_CROSSES_SYSTEM",
@@ -299,6 +302,9 @@ public void The_reader_carries_a_facet_on_a_types_entry_attr()
"role.token @heldBy organization|system False ",
"role.token @memberOf role/group False ",
"role.user @memberOf role/group False ",
+ "resource.objectStore @carries api/batch False ",
+ "resource.queue @carries api/eventing False ",
+ "resource.stream @carries api/eventing False ",
"source.document @resource resource/document False ",
"source.rdb @resource resource/rdb False ",
"source.search @resource resource/search False ",
@@ -327,7 +333,7 @@ public void The_core_definitions_declare_exactly_the_four_core_references()
foreach (var a in registry.AttrsOf(id.Type, id.SubType))
{
if (a.Ref is not { } f) continue;
- if (id.Type is "app" or "role" or "system" or "grant" or "source")
+ if (id.Type is "app" or "role" or "system" or "grant" or "source" or "resource")
{
// The systems vocabulary: the grants and @runsAs stay inside their system,
// each with its own wrong-system code; the other references do not.
diff --git a/server/csharp/MetaObjects/Core/Api/ApiConstants.cs b/server/csharp/MetaObjects/Core/Api/ApiConstants.cs
index 5ac913fcba..ca9cbbb5a1 100644
--- a/server/csharp/MetaObjects/Core/Api/ApiConstants.cs
+++ b/server/csharp/MetaObjects/Core/Api/ApiConstants.cs
@@ -15,17 +15,35 @@ public static partial class ApiConstants
/// A request/response surface whose children are operations. The axis is the
/// interaction model, never the protocol (ADR-0030).
public const string API_SUBTYPE_OPERATIONAL = "operational";
- public static readonly string[] API_SUBTYPES = [API_SUBTYPE_OPERATIONAL];
+ /// Events the provider publishes; children are operation.event.
+ public const string API_SUBTYPE_EVENTING = "eventing";
+ /// Datasets delivered as files on a schedule; children are operation.export / .import.
+ public const string API_SUBTYPE_BATCH = "batch";
+ public static readonly string[] API_SUBTYPES = [API_SUBTYPE_OPERATIONAL, API_SUBTYPE_EVENTING, API_SUBTYPE_BATCH];
/// Changes state; takes an object.value.
public const string OPERATION_SUBTYPE_COMMAND = "command";
/// Reads; returns a projection, entity or value.
public const string OPERATION_SUBTYPE_QUERY = "query";
- public static readonly string[] OPERATION_SUBTYPES = [OPERATION_SUBTYPE_COMMAND, OPERATION_SUBTYPE_QUERY];
+ /// Something that happened; the payload is its @outputRef.
+ public const string OPERATION_SUBTYPE_EVENT = "event";
+ /// A file the provider publishes on a schedule; rows are its @outputRef.
+ public const string OPERATION_SUBTYPE_EXPORT = "export";
+ /// A file the provider accepts on a schedule; rows are its @inputRef.
+ public const string OPERATION_SUBTYPE_IMPORT = "import";
+ public static readonly string[] OPERATION_SUBTYPES =
+ [
+ OPERATION_SUBTYPE_COMMAND, OPERATION_SUBTYPE_QUERY,
+ OPERATION_SUBTYPE_EVENT, OPERATION_SUBTYPE_EXPORT, OPERATION_SUBTYPE_IMPORT,
+ ];
/// The HTTP binding of an operation (overrides the derived method and path).
public const string BINDING_SUBTYPE_REST = "rest";
- public static readonly string[] BINDING_SUBTYPES = [BINDING_SUBTYPE_REST];
+ /// How an event travels (optionally pinning the wire protocol).
+ public const string BINDING_SUBTYPE_MESSAGING = "messaging";
+ /// How an export's or import's file is delivered.
+ public const string BINDING_SUBTYPE_FILE = "file";
+ public static readonly string[] BINDING_SUBTYPES = [BINDING_SUBTYPE_REST, BINDING_SUBTYPE_MESSAGING, BINDING_SUBTYPE_FILE];
// Attrs on operation.* (and @permission / @public on transition.* too)
public const string OPERATION_ATTR_INPUT_REF = "inputRef";
@@ -42,6 +60,48 @@ public static partial class ApiConstants
public const string BINDING_ATTR_PATH = "path";
public static readonly string[] HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
+ // Attrs on operation.event / .export / .import
+ public const string OPERATION_ATTR_KEY = "key";
+ public const string OPERATION_ATTR_FREQUENCY = "frequency";
+ public const string OPERATION_ATTR_AVAILABLE_BY = "availableBy";
+ public const string FREQUENCY_HOURLY = "hourly";
+ public const string FREQUENCY_DAILY = "daily";
+ public const string FREQUENCY_WEEKLY = "weekly";
+ public const string FREQUENCY_MONTHLY = "monthly";
+ public static readonly string[] FREQUENCIES = [FREQUENCY_HOURLY, FREQUENCY_DAILY, FREQUENCY_WEEKLY, FREQUENCY_MONTHLY];
+
+ /// The form of @availableBy for each @frequency: hourly :MM, daily HH:MM,
+ /// weekly Ddd HH:MM, monthly D HH:MM with the day 1 to 28. Anchored with \z.
+ public static readonly IReadOnlyDictionary AVAILABLE_BY_PATTERNS = new Dictionary
+ {
+ [FREQUENCY_HOURLY] = new(@"^:[0-5][0-9]\z", RegexOptions.CultureInvariant),
+ [FREQUENCY_DAILY] = new(@"^(?:[01][0-9]|2[0-3]):[0-5][0-9]\z", RegexOptions.CultureInvariant),
+ [FREQUENCY_WEEKLY] = new(@"^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]\z", RegexOptions.CultureInvariant),
+ [FREQUENCY_MONTHLY] = new(@"^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]\z", RegexOptions.CultureInvariant),
+ };
+
+ /// An example of each @availableBy form, for messages.
+ public static readonly IReadOnlyDictionary AVAILABLE_BY_EXAMPLES = new Dictionary
+ {
+ [FREQUENCY_HOURLY] = ":15",
+ [FREQUENCY_DAILY] = "03:00",
+ [FREQUENCY_WEEKLY] = "Mon 06:00",
+ [FREQUENCY_MONTHLY] = "1 06:00",
+ };
+
+ // Attrs on binding.messaging / binding.file
+ public const string BINDING_ATTR_PROTOCOL = "protocol";
+ public const string BINDING_ATTR_TRANSPORT = "transport";
+ public const string BINDING_ATTR_FILE_NAME = "fileName";
+ public const string BINDING_ATTR_FORMAT = "format";
+ public const string BINDING_ATTR_COMPRESSION = "compression";
+ public const string BINDING_ATTR_COMPLETION = "completion";
+ public const string BINDING_ATTR_ENCRYPTION = "encryption";
+ /// The placeholders a binding.file @fileName may hold.
+ public static readonly string[] FILE_NAME_PLACEHOLDERS = ["date", "timestamp"];
+ /// The suffix of the marker object completion: marker puts beside a finished file.
+ public const string COMPLETION_MARKER_SUFFIX = ".done";
+
/// Names a declared operation or a transition may not take: they are the derived
/// CRUD verbs of the same service (ERR_TRANSITION_NAME_COLLISION).
public static readonly string[] RESERVED_OPERATION_NAMES = ["create", "get", "list", "update", "delete"];
diff --git a/server/csharp/MetaObjects/Core/Api/ApiSchema.cs b/server/csharp/MetaObjects/Core/Api/ApiSchema.cs
index a761c2c47d..3b576c3ffe 100644
--- a/server/csharp/MetaObjects/Core/Api/ApiSchema.cs
+++ b/server/csharp/MetaObjects/Core/Api/ApiSchema.cs
@@ -17,7 +17,13 @@ private static AttrSchema Str(string name, bool isArray = false, IReadOnlyList
new(Name: name, ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, Required: false);
- /// The attrs every operation shares (operation.base).
+ private static AttrSchema Req(string name, IReadOnlyList
*
- *
Java addition: {@code .withEnum} is decorative on attr children in this port (see
- * {@code validateRequirementStatus}), so the closed {@code @agg} / {@code @grains} sets the
- * TS registry enforces generically are checked here as {@code ERR_BAD_ATTR_VALUE}.
+ *
The closed {@code @agg} / {@code @grains} sets are checked by ValidationPhase's generic
+ * closed-set pass ({@code validateAllowedValues}), as the TS registry does, not here.
*
*
A fractional measure {@code @default}: the TypeScript reference refuses it here, in
* {@code checkMeasure}, because its generic attr.int check lets a fraction through. This
@@ -166,8 +165,6 @@ static List validate(MetaRoot root) {
// F1 on every host that is not a reporting host.
checkNoRelativeDates(root, root, sink);
- // Java-only: closed-set membership the TS registry enforces generically.
- checkClosedSets(root, sink);
return sink.errors;
}
@@ -375,7 +372,7 @@ private static String displayName(MetaData node) {
}
/** {@code . ''}, or just {@code .} for an unnamed node. */
- private static String childLabel(MetaData node) {
+ static String childLabel(MetaData node) {
String head = node.getType() + "." + node.getSubType();
String name = displayName(node);
return name.isEmpty() ? head : head + " '" + name + "'";
@@ -1418,46 +1415,4 @@ && filterContainsRelativeValue(((MetaAttribute>) c).getValue())) {
if (!(c instanceof MetaAttribute)) checkNoRelativeDates(root, c, sink);
}
}
-
- // ---------------------------------------------------------------------------
- // Closed sets (Java: the registry's allowedValues are not enforced generically)
- // ---------------------------------------------------------------------------
-
- /**
- * {@code measure.aggregate @agg} and {@code dimension.time @grains} hold members of their
- * closed sets ({@code ERR_BAD_ATTR_VALUE}, one error per offending value, as the TS
- * attr-schema check reports them).
- */
- private static void checkClosedSets(MetaData node, ErrorSink sink) {
- if (node instanceof MetaMeasure && ReportingConstants.MEASURE_SUBTYPE_AGGREGATE.equals(node.getSubType())) {
- // ADR-0039: own — an attr rule validates the attr on the node that DECLARES it.
- String agg = node.hasMetaAttr(ReportingConstants.ATTR_AGG, false)
- ? stringAttr(node, ReportingConstants.ATTR_AGG) : null;
- if (agg != null && !ReportingConstants.MEASURE_AGGS.contains(agg)) {
- pushBadValue(node, ReportingConstants.ATTR_AGG, agg, ReportingConstants.MEASURE_AGGS, sink);
- }
- }
- if (node instanceof MetaDimension && ((MetaDimension) node).isTime()
- // ADR-0039: own — an attr rule validates the attr on the node that DECLARES it.
- && node.hasMetaAttr(ReportingConstants.ATTR_GRAINS, false)) {
- Object v = node.getMetaAttr(ReportingConstants.ATTR_GRAINS, false).getValue();
- List> items = v instanceof List ? (List>) v : v == null ? List.of() : List.of(v);
- for (Object g : items) {
- if (!ReportingConstants.TIME_GRAINS.contains(String.valueOf(g))) {
- pushBadValue(node, ReportingConstants.ATTR_GRAINS, String.valueOf(g), ReportingConstants.TIME_GRAINS, sink);
- }
- }
- }
- // ADR-0039: own — a tree walk; each declared node is visited once, at its declaration.
- for (MetaData c : node.getChildren(MetaData.class, false)) {
- if (!(c instanceof MetaAttribute)) checkClosedSets(c, sink);
- }
- }
-
- private static void pushBadValue(MetaData node, String attr, String value, List allowed, ErrorSink sink) {
- // The TS attr-schema check's short label (`type.subType 'name'`, no parent chain).
- sink.push(node, ErrorCode.ERR_BAD_ATTR_VALUE, childLabel(node),
- " attribute '@" + attr + "' has value '" + value + "' which is not one of the allowed values: "
- + String.join(", ", allowed));
- }
}
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java
index b4f8dac5c7..30c35593b1 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java
@@ -256,7 +256,7 @@ private static void checkEntityLifecycles(MetaData entity, Sink sink) {
sink.add(entity, ErrorCode.ERR_TRANSITION_NOT_ON_ENTITY,
"object.entity \"" + entity.getShortName() + "\" has a lifecycle (transitions on " + quoteList(fields)
+ ") and a source, but no writable one; a transition is a guarded update of a stored row. "
- + "(An entity with no source at all may carry a lifecycle: it is inert until a source is added.)");
+ + "(An entity with no relational source may carry a lifecycle: it is inert until a source.rdb is added.)");
}
}
@@ -298,41 +298,7 @@ private static void checkOperation(MetaData op, Sink sink) {
sink.add(op, ErrorCode.ERR_BAD_ATTR_VALUE, head + " @errors: " + why + ".");
}
- // Java addition: .withEnum is decorative on attr children in this port, so the closed
- // @method set the TS registry enforces generically is checked here.
- // ADR-0039: own — a binding is checked on the operation that declares it.
- for (MetaData b : op.getChildren(MetaData.class, false)) {
- if (!ApiConstants.TYPE_BINDING.equals(b.getType()) || !b.hasMetaAttr(ApiConstants.ATTR_METHOD, false)) continue;
- String method = Lifecycles.stringValue(b, ApiConstants.ATTR_METHOD);
- if (method != null && !ApiConstants.BINDING_METHODS.contains(method)) {
- sink.add(b, ErrorCode.ERR_BAD_ATTR_VALUE,
- b.getType() + "." + b.getSubType() + " attribute '@" + ApiConstants.ATTR_METHOD + "' has value '" + method
- + "' which is not one of the allowed values: " + String.join(", ", ApiConstants.BINDING_METHODS));
- }
- }
-
- // O1 — shapes.
- String inputRef = Lifecycles.stringValue(op, ApiConstants.ATTR_INPUT_REF);
- if (inputRef != null) {
- MetaData input = Lifecycles.resolveObjectOn(op, inputRef);
- if (input == null || !MetaObject.SUBTYPE_VALUE.equals(input.getSubType())) {
- sink.add(op, ErrorCode.ERR_OPERATION_SHAPE,
- head + " @inputRef \"" + inputRef + "\" " + objectKind(input) + "; an operation's input is an object.value.");
- return;
- }
- }
- String outputRef = Lifecycles.stringValue(op, ApiConstants.ATTR_OUTPUT_REF);
- if (outputRef != null) {
- MetaData output = Lifecycles.resolveObjectOn(op, outputRef);
- boolean legal = output != null && Arrays.asList(MetaObject.SUBTYPE_ENTITY, MetaObject.SUBTYPE_PROJECTION,
- MetaObject.SUBTYPE_VALUE).contains(output.getSubType());
- if (!legal) {
- sink.add(op, ErrorCode.ERR_OPERATION_SHAPE,
- head + " @outputRef \"" + outputRef + "\" " + objectKind(output)
- + "; an operation returns an object.entity, object.projection or object.value.");
- return;
- }
- }
+ if (!checkShapes(op, sink)) return;
// O2, O3 — the target.
Lifecycles.DerivedTarget derivedTarget = Lifecycles.deriveOperationTarget(op);
@@ -401,6 +367,85 @@ private static void checkOperation(MetaData op, Sink sink) {
}
}
+ /** O1 — an operation's {@code @inputRef} and {@code @outputRef} shapes. False when one is wrong. */
+ private static boolean checkShapes(MetaData op, Sink sink) {
+ String head = "operation." + op.getSubType() + " \"" + label(op) + "\"";
+ String inputRef = Lifecycles.stringValue(op, ApiConstants.ATTR_INPUT_REF);
+ if (inputRef != null) {
+ MetaData input = Lifecycles.resolveObjectOn(op, inputRef);
+ if (input == null || !MetaObject.SUBTYPE_VALUE.equals(input.getSubType())) {
+ sink.add(op, ErrorCode.ERR_OPERATION_SHAPE,
+ head + " @inputRef \"" + inputRef + "\" " + objectKind(input) + "; an operation's input is an object.value.");
+ return false;
+ }
+ }
+ String outputRef = Lifecycles.stringValue(op, ApiConstants.ATTR_OUTPUT_REF);
+ if (outputRef != null) {
+ MetaData output = Lifecycles.resolveObjectOn(op, outputRef);
+ boolean legal = output != null && Arrays.asList(MetaObject.SUBTYPE_ENTITY, MetaObject.SUBTYPE_PROJECTION,
+ MetaObject.SUBTYPE_VALUE).contains(output.getSubType());
+ if (!legal) {
+ sink.add(op, ErrorCode.ERR_OPERATION_SHAPE,
+ head + " @outputRef \"" + outputRef + "\" " + objectKind(output)
+ + "; an operation returns an object.entity, object.projection or object.value.");
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * The checks for one operation of an api.eventing or api.batch: its shapes (O1), the form of an
+ * export's {@code @availableBy} (D1), the placeholders of each binding.file {@code @fileName} (D2) and an
+ * event's {@code @key} (D3).
+ */
+ private static void checkDeliveryOperation(MetaData op, Sink sink) {
+ if (!checkShapes(op, sink)) return;
+ String key = Lifecycles.stringValue(op, ApiConstants.ATTR_KEY);
+ String outputRef = Lifecycles.stringValue(op, ApiConstants.ATTR_OUTPUT_REF);
+ MetaData output = ApiConstants.OPERATION_SUBTYPE_EVENT.equals(op.getSubType()) && key != null && outputRef != null
+ ? Lifecycles.resolveObjectOn(op, outputRef) : null;
+ if (output != null && output.getChildren(MetaData.class, true).stream()
+ .noneMatch(c -> MetaField.TYPE_FIELD.equals(c.getType()) && c.getShortName().equals(key))) {
+ sink.add(op, ErrorCode.ERR_BAD_ATTR_VALUE,
+ "operation.event \"" + label(op) + "\" @key \"" + key + "\" is not a field of \"" + output.getShortName()
+ + "\"; @key names the payload field whose events stay in order.");
+ }
+ String frequency = Lifecycles.stringValue(op, ApiConstants.ATTR_FREQUENCY);
+ String availableBy = Lifecycles.stringValue(op, ApiConstants.ATTR_AVAILABLE_BY);
+ if (availableBy != null && frequency != null && ApiConstants.FREQUENCIES.contains(frequency)
+ && !ApiConstants.AVAILABLE_BY_PATTERNS.get(frequency).matcher(availableBy).matches()) {
+ sink.add(op, ErrorCode.ERR_BAD_ATTR_VALUE,
+ "operation." + op.getSubType() + " \"" + label(op) + "\" @availableBy \"" + availableBy + "\" is not a "
+ + frequency + " time; a " + frequency + " file's @availableBy is written like \""
+ + ApiConstants.AVAILABLE_BY_EXAMPLES.get(frequency) + "\" (UTC).");
+ }
+ // ADR-0039: own — a binding is checked on the operation that declares it.
+ for (MetaData b : op.getChildren(MetaData.class, false)) {
+ if (!ApiConstants.TYPE_BINDING.equals(b.getType()) || !ApiConstants.BINDING_SUBTYPE_FILE.equals(b.getSubType())) continue;
+ String fileName = Lifecycles.stringValue(b, ApiConstants.ATTR_FILE_NAME);
+ if (fileName == null) continue;
+ String bad = fileNamePlaceholderProblem(fileName);
+ if (bad != null) {
+ sink.add(b, ErrorCode.ERR_BAD_ATTR_VALUE,
+ "binding.file on \"" + label(b) + "\" @fileName \"" + fileName + "\" " + bad
+ + "; the placeholders are {" + String.join("} and {", ApiConstants.FILE_NAME_PLACEHOLDERS) + "}.");
+ }
+ }
+ }
+
+ private static final Pattern FILE_NAME_PLACEHOLDER = Pattern.compile("\\{([^{}]*)\\}");
+
+ /** What is wrong with a {@code @fileName}'s placeholders, or null when nothing is. */
+ private static String fileNamePlaceholderProblem(String fileName) {
+ java.util.regex.Matcher m = FILE_NAME_PLACEHOLDER.matcher(fileName);
+ while (m.find()) {
+ if (!ApiConstants.FILE_NAME_PLACEHOLDERS.contains(m.group(1))) return "holds the placeholder {" + m.group(1) + "}";
+ }
+ String rest = FILE_NAME_PLACEHOLDER.matcher(fileName).replaceAll("");
+ return rest.indexOf('{') >= 0 || rest.indexOf('}') >= 0 ? "has an unmatched brace" : null;
+ }
+
/** ADR-0066 — the rules pass. Runs after reference-bearing validation. */
static List validate(MetaRoot root) {
Sink sink = new Sink();
@@ -416,6 +461,10 @@ static List validate(MetaRoot root) {
for (MetaData op : api.getChildren(MetaData.class, true)) {
if (ApiConstants.TYPE_OPERATION.equals(op.getType())) ops.add(op);
}
+ if (!ApiConstants.API_SUBTYPE_OPERATIONAL.equals(api.getSubType())) {
+ for (MetaData op : ops) checkDeliveryOperation(op, sink);
+ continue;
+ }
for (MetaData op : ops) checkOperation(op, sink);
for (MetaData op : ops) {
String pkg = References.effectivePackageOf(api);
@@ -455,7 +504,7 @@ private static void checkPermissionNames(MetaRoot root, Sink sink) {
}
}
for (MetaData api : root.getChildren(MetaData.class, true)) {
- if (!ApiConstants.TYPE_API.equals(api.getType())) continue;
+ if (!ApiConstants.TYPE_API.equals(api.getType()) || !ApiConstants.API_SUBTYPE_OPERATIONAL.equals(api.getSubType())) continue;
for (MetaData op : api.getChildren(MetaData.class, true)) {
if (ApiConstants.TYPE_OPERATION.equals(op.getType())) {
registerPermissionPoint(op, api, op.getShortName(), byName, sink);
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java
index 6ccb0a9a2f..44a82f1055 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java
@@ -117,7 +117,7 @@
* ({@code @through}/{@code @sourceRefField}/{@code @objectRef}/{@code @cardinality}/
* {@code @symmetric}) and the junction's {@code identity.reference} view, the
* {@code layout.dataGrid} lookup + its {@code @defaultSortField}/{@code @filter}, and
- * the {@code template.*} attrs ({@code @format}/{@code @promptStyle}/{@code @kind}/
+ * the {@code template.*} attrs ({@code @kind}/
* part-refs — templates CAN extend) — are flipped to the resolving accessor inline and
* marked "ADR-0039: resolving" (mirrors the TS reference and the C# ValidationPasses
* fix). Declaration-layer markers ({@code @isAbstract}, TPH {@code @discriminator}/
@@ -137,14 +137,8 @@ private ValidationPhase() {
*
@@ -187,13 +181,21 @@ public static void run(MetaRoot root, MetaDataLoader loader) {
// ERR_TOO_MANY_OCCURRENCES (e.g. two identity.primary on one object).
pass(collected, () -> validateMaxOccurs(root, loader));
validateChildRuleMax(root, loader, collected);
- // The closed set of resource.* @residency (ADR-0070): the attr builder's enum is not
- // enforced on an attribute, so the loader checks it here.
- pass(collected, () -> validateResidency(root));
+ // Findings a pass reports several of per node (code + envelope alike), deduped on their
+ // MESSAGE too, so only a true repeat collapses.
+ java.util.Set keyedByMessage =
+ java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
+ // Every attribute's registered closed set (the registry manifest's allowedValues):
+ // one finding per offending value.
+ pass(collected, () -> {
+ List badValues = new ArrayList<>();
+ validateAllowedValues(root, loader != null ? loader.getTypeRegistry() : null, badValues);
+ keyedByMessage.addAll(badValues);
+ collected.addAll(badValues);
+ });
pass(collected, () -> validateEnumValues(root));
pass(collected, () -> validateFieldDefaults(root));
pass(collected, () -> validateDbColumnType(root));
- pass(collected, () -> validateSourceAttrs(root));
pass(collected, () -> validateSourcePhysicalNames(root, loader));
// FR-013 — field-level @readOnly cross-attribute rules.
pass(collected, () -> validateFieldMutability(root, loader));
@@ -214,7 +216,6 @@ public static void run(MetaRoot root, MetaDataLoader loader) {
// #208 — DDL-ownership escape valves (@sql/@unmanaged on source.rdb).
// Sibling of the source-role pass above; must run after it.
pass(collected, () -> validateSourceEscapes(root, loader));
- pass(collected, () -> validateRelationshipReferentialActions(root));
// Pass 14 (FR-017): M:N relationship slim-vocabulary validation — collects
// EVERY violation across the effective relationship set (own + inherited via
// extends), deduped by the relationship node's own identity (#368 / ADR-0039).
@@ -282,7 +283,7 @@ public static void run(MetaRoot root, MetaDataLoader loader) {
loader != null && loader.getLoaderOptions() != null && loader.getLoaderOptions().isStrict());
validateDbCheck(root, collected);
pass(collected, () -> validateFieldMap(root));
- pass(collected, () -> validateIdentityFieldsAndGeneration(root));
+ pass(collected, () -> validateIdentityFields(root));
// FR-024 B3/B4a — subtype rules (identity-name, value purity, projection licensing).
pass(collected, () -> validateSubtypeRules(root));
// FR-024 B3 — projection identity pass-through + key correspondence.
@@ -301,11 +302,9 @@ public static void run(MetaRoot root, MetaDataLoader loader) {
// so its findings are deduped on their MESSAGE too: two distinct reporting failures
// on one node (two unresolved @dimensions items, two inheritors breaking one
// inherited dimension) share code + envelope but are two errors in every port.
- java.util.Set reportingFindings =
- java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
pass(collected, () -> {
List reporting = validateReporting(root);
- reportingFindings.addAll(reporting);
+ keyedByMessage.addAll(reporting);
collected.addAll(reporting);
});
pass(collected, () -> validateTemplates(root));
@@ -318,22 +317,19 @@ public static void run(MetaRoot root, MetaDataLoader loader) {
// once); keyed by message like the reporting pass, since they share code + envelope.
pass(collected, () -> {
List collisions = validateColumnNameCollisions(root);
- reportingFindings.addAll(collisions);
+ keyedByMessage.addAll(collisions);
collected.addAll(collisions);
});
// FR-039 — a retired requirement carries no @implementedBy (refused, not exempted,
// so the dangling-ref class is unreachable) and @supersededBy is legal only there.
pass(collected, () -> validateRetiredRequirementLinks(root));
- // The capability ledger's closed status enum (requirements-as-metadata
- // ruling, Amendment 3) — the loader owns what is UNCONDITIONAL.
- pass(collected, () -> validateRequirementStatus(root));
warnFilterableWithoutIndex(root, loader); // warnings only — never throws
// The SAME defect can be flagged by more than one pass (e.g. a missing required attr
// caught by both the generic required-attr pass and a subtype-specific pass) — that is
// one finding, not two, and the envelope (code + source) is identical. Dedupe on it so
// a defect is reported once, while genuinely-distinct findings stay separate.
- java.util.List findings = dedupe(collected, reportingFindings);
+ java.util.List findings = dedupe(collected, keyedByMessage);
// Surface ALL findings: record every error but the last on the loader (source order),
// then throw the last so the load still fails. Single error → records nothing, throws
@@ -425,14 +421,14 @@ public static void run(MetaRoot root) {
//
// Only requirements whose expectedType is "attr" are enforced here. Other
// required-child kinds (fields / identities) have their own bespoke checks
- // already (validateEnumValues, validateIdentityFieldsAndGeneration) that
+ // already (validateEnumValues, validateIdentityFields) that
// carry semantic context this pass does not.
//
// Loader nullness: when the loader handle is unavailable (legacy two-arg
// entry point that passes null), this pass is a no-op — the registry
// is reached via the loader, and absent that handle there is nowhere
// safe to look up TypeDefinitions. The downstream subtype passes
- // (validateEnumValues, validateIdentityFieldsAndGeneration) continue to
+ // (validateEnumValues, validateIdentityFields) continue to
// run regardless and catch the previously-enforced cases.
// =========================================================================
@@ -624,33 +620,50 @@ private static void validateChildRuleMaxNode(MetaData parent, MetaDataRegistry r
}
// =========================================================================
- // resource.* @residency validation (ADR-0070)
+ // Closed attribute value sets (ADR-0036 Wave 1, decision 5)
//
- // @residency is a closed set (free | confined) on every concrete resource kind.
- // Own attribute only: an inherited value was checked on its declaring node.
+ // For each OWN attribute whose registered definition declares a non-empty closed set
+ // (the registry manifest's allowedValues), the value must be a member; an array attr
+ // checks each element. An inherited value was checked on its declaring node.
+ // @dbColumnType is exempt: its (subtype x value) pairing check reports instead.
+ // Mirrors TS attr-schema-validate Check 3, one ERR_BAD_ATTR_VALUE per offending value.
// =========================================================================
- static void validateResidency(MetaRoot root) {
- walkResidency(root);
- }
-
- private static void walkResidency(MetaData node) {
- if (SystemsNode.TYPE_RESOURCE.equals(node.getType())
- && SystemsNode.RESOURCE_KINDS.contains(node.getSubType())
- && node.hasMetaAttr(SystemsNode.ATTR_RESIDENCY, false)) {
- String residency = node.getMetaAttr(SystemsNode.ATTR_RESIDENCY, false).getValueAsString();
- if (!SystemsNode.RESIDENCIES.contains(residency)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": " + node.getType() + "." + node.getSubType() + " '" + node.getName()
- + "' @" + SystemsNode.ATTR_RESIDENCY + " '" + residency
- + "' is not a valid value; allowed: "
- + String.join(", ", SystemsNode.RESIDENCIES),
- ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource());
+ static void validateAllowedValues(MetaRoot root, MetaDataRegistry registry, List out) {
+ if (registry != null) walkAllowedValues(root, registry, out);
+ }
+
+ private static void walkAllowedValues(MetaData node, MetaDataRegistry registry, List out) {
+ TypeDefinition def = node.getType() == null || node.getSubType() == null
+ ? null : registry.getTypeDefinition(node.getType(), node.getSubType());
+ // ADR-0039: own — an attr is checked on the node that declares it; the walk visits each node once.
+ List own = node.getChildren(MetaData.class, false);
+ if (def != null) {
+ Map> allowedByName = new java.util.HashMap<>();
+ for (ChildRequirement req : def.getChildRequirements()) {
+ if (!MetaAttribute.TYPE_ATTR.equals(req.getExpectedType()) || req.isWildcard()) continue;
+ List allowed = req.getAllowedValues();
+ if (allowed != null && !allowed.isEmpty()) allowedByName.putIfAbsent(req.getName(), allowed);
+ }
+ for (MetaData c : own) {
+ if (!(c instanceof MetaAttribute attr)) continue;
+ String name = attr.getShortName();
+ List allowed = allowedByName.get(name);
+ if (allowed == null || MetaField.ATTR_DB_COLUMN_TYPE.equals(name)) continue;
+ Object value = attr.getValue();
+ List> items = value instanceof java.util.Collection> coll ? new ArrayList<>(coll) : java.util.Arrays.asList(value);
+ for (Object item : items) {
+ String text = String.valueOf(item);
+ if (allowed.contains(text)) continue;
+ out.add(new MetaDataException(
+ ReportingValidation.childLabel(node) + " attribute '@" + name + "' has value '" + text
+ + "' which is not one of the allowed values: " + String.join(", ", allowed),
+ ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()));
+ }
}
}
- for (MetaData child : node.getChildren(MetaData.class, false)) {
- walkResidency(child);
+ for (MetaData child : own) {
+ if (!(child instanceof MetaAttribute)) walkAllowedValues(child, registry, out);
}
}
@@ -1154,8 +1167,6 @@ private static void validateEnumStringValueMap(MetaData node) {
*
*
{@code @coerceDefault} (own) must be a member of the EFFECTIVE {@code @values}
* (own or inherited via {@code extends:}) → {@code ERR_BAD_ATTR_VALUE}.
- *
{@code @normalize} (own) must be one of {@code none|collapse|strip}
- * → {@code ERR_BAD_ATTR_VALUE} (belt-and-braces with the registered withEnum).
*
*
*
Own-only policy: only checks attrs declared on THIS node, matching the {@code @values}
@@ -1191,19 +1202,6 @@ private static void validateEnumFr011Attrs(MetaData node) {
ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource());
}
}
-
- // @normalize closed-enum membership.
- if (node.hasMetaAttr(EnumField.ATTR_NORMALIZE, false)) {
- String mode = node.getMetaAttr(EnumField.ATTR_NORMALIZE, false).getValueAsString();
- if (mode != null && !EnumField.NORMALIZE_MODES.contains(mode)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": field.enum '" + node.getName()
- + "' @" + EnumField.ATTR_NORMALIZE + " '" + mode
- + "' is not a valid value; allowed: none, collapse, strip",
- ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource());
- }
- }
}
/**
@@ -1393,86 +1391,6 @@ private static void validateDbColumnTypeNode(MetaData node) {
}
}
- // =========================================================================
- // Source @kind / @role enum validation
- //
- // Applied to every source.* node after the full tree is built (attrs are set
- // post-placement, so we cannot validate at addChild time via the constraint
- // framework — same reason field.enum uses a post-load pass).
- //
- // @kind must be one of: table / view / materializedView / storedProc / tableFunction
- // @role must be one of MetaSource.VALID_ROLES: primary / replica
- //
- // Missing attrs are fine (defaults apply); only explicitly-set bad values fail.
- // =========================================================================
-
- /**
- * Walk the full tree and validate {@code @kind} and {@code @role} on every
- * {@code source.*} node.
- *
- * @param root the root node to walk
- * @throws MetaDataException on the first error found
- */
- static void validateSourceAttrs(MetaRoot root) {
- walkSourceAttrs(root);
- }
-
- private static void walkSourceAttrs(MetaData node) {
- validateSourceNode(node);
- for (MetaData child : node.getChildren(MetaData.class, false)) {
- walkSourceAttrs(child);
- }
- }
-
- /**
- * Validate {@code @kind} and {@code @role} on a single node if it is a {@code source.*}.
- *
- * @param node the node to inspect
- * @throws MetaDataException if {@code @kind} or {@code @role} is set to an invalid value
- */
- private static void validateSourceNode(MetaData node) {
- if (!MetaSource.TYPE_SOURCE.equals(node.getType())) {
- return;
- }
- // Only validate on instances of MetaSource (skip the abstract base type itself at
- // registration time — it will never appear in a loaded document tree).
- if (!(node instanceof MetaSource)) {
- return;
- }
- MetaSource src = (MetaSource) node;
-
- // Validate @kind (own attribute only — defaults are fine)
- if (node.hasMetaAttr(MetaSource.ATTR_KIND, false)) {
- String kind = src.getEffectiveKind();
- if (!MetaSource.VALID_KINDS.contains(kind)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": source '" + node.getName()
- + "' @kind '" + kind
- + "' is not a valid value; allowed: table, view, materializedView,"
- + " storedProc, tableFunction",
- ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource());
- }
- }
-
- // Validate @role (own attribute only — defaults are fine)
- if (node.hasMetaAttr(MetaSource.ATTR_ROLE, false)) {
- String role = src.getRole();
- if (!MetaSource.VALID_ROLES.contains(role)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": source '" + node.getName()
- + "' @role '" + role
- // Derived from the registered set (sorted for a deterministic
- // message — Set.of iteration order is unspecified) so the
- // diagnostic can never drift from MetaSource.VALID_ROLES again.
- + "' is not a valid value; allowed: "
- + String.join(", ", new TreeSet<>(MetaSource.VALID_ROLES)),
- ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource());
- }
- }
- }
-
// =========================================================================
// FR-016 / ADR-0018 — per-kind physical-name alias validation
//
@@ -1831,126 +1749,6 @@ private static void validateObjectSourceEscapes(MetaObject obj, MetaDataLoader l
}
}
- // =========================================================================
- // Relationship @onDelete / @onUpdate enum validation
- //
- // Applied to every relationship.* node after the full tree is built.
- // The .withEnum() constraint registered on relationship.base does not fire
- // eagerly at addChild time (the CustomConstraint applicability test checks
- // the container node's own type/subtype, which is attr.string for the attr
- // child, not relationship.base) — so we use this post-load pass instead,
- // mirroring the pattern for source @kind/@role.
- //
- // @onDelete must be one of: cascade / set-null / restrict / no-action
- // @onUpdate must be one of: cascade / set-null / restrict / no-action
- //
- // Missing attrs are fine (defaults apply per subtype in consumer code);
- // only explicitly-set bad values fail.
- // =========================================================================
-
- /**
- * Walk the full tree and validate {@code @onDelete} and {@code @onUpdate} on every
- * {@code relationship.*} node.
- *
- * @param root the root node to walk
- * @throws MetaDataException on the first error found
- */
- static void validateRelationshipReferentialActions(MetaRoot root) {
- walkRelationshipReferentialActions(root);
- }
-
- private static void walkRelationshipReferentialActions(MetaData node) {
- validateRelationshipNode(node);
- validateReferenceIdentityActions(node);
- for (MetaData child : node.getChildren(MetaData.class, false)) {
- walkRelationshipReferentialActions(child);
- }
- }
-
- /**
- * ADR-0047 — validate {@code @onDelete} / {@code @onUpdate} declared directly on an
- * {@code identity.reference} (the explicit per-FK override). Same closed value set
- * as the relationship-level attrs ({@link MetaRelationship#REFERENTIAL_ACTIONS});
- * an out-of-set value throws {@code ERR_BAD_ATTR_VALUE}, matching the other ports'
- * generic allowedValues enforcement.
- */
- private static void validateReferenceIdentityActions(MetaData node) {
- if (!(node instanceof ReferenceIdentity)) {
- return;
- }
- ReferenceIdentity ref = (ReferenceIdentity) node;
-
- if (node.hasMetaAttr(MetaIdentity.ATTR_ON_DELETE, false)) {
- String onDelete = ref.getOnDeleteRaw();
- if (!MetaRelationship.REFERENTIAL_ACTIONS.contains(onDelete)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": identity.reference '" + node.getName()
- + "' @onDelete '" + onDelete
- + "' is not a valid value; allowed: cascade, set-null, restrict, no-action",
- ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource());
- }
- }
-
- if (node.hasMetaAttr(MetaIdentity.ATTR_ON_UPDATE, false)) {
- String onUpdate = ref.getOnUpdateRaw();
- if (!MetaRelationship.REFERENTIAL_ACTIONS.contains(onUpdate)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": identity.reference '" + node.getName()
- + "' @onUpdate '" + onUpdate
- + "' is not a valid value; allowed: cascade, set-null, restrict, no-action",
- ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource());
- }
- }
- }
-
- /**
- * Validate {@code @onDelete} and {@code @onUpdate} on a single node if it is a
- * {@code relationship.*} instance.
- *
- * @param node the node to inspect
- * @throws MetaDataException if {@code @onDelete} or {@code @onUpdate} is set to an
- * invalid value (not in {@link MetaRelationship#REFERENTIAL_ACTIONS})
- */
- private static void validateRelationshipNode(MetaData node) {
- if (!MetaRelationship.TYPE_RELATIONSHIP.equals(node.getType())) {
- return;
- }
- // Only validate concrete MetaRelationship instances — skip the abstract base type
- // itself at registration time; it will never appear in a loaded document tree.
- if (!(node instanceof MetaRelationship)) {
- return;
- }
- MetaRelationship rel = (MetaRelationship) node;
-
- // Validate @onDelete (own attribute only — absent is fine)
- if (node.hasMetaAttr(MetaRelationship.ATTR_ON_DELETE, false)) {
- String onDelete = rel.getOnDeleteRaw();
- if (!MetaRelationship.REFERENTIAL_ACTIONS.contains(onDelete)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": relationship '" + node.getName()
- + "' @onDelete '" + onDelete
- + "' is not a valid value; allowed: cascade, set-null, restrict, no-action",
- ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource());
- }
- }
-
- // Validate @onUpdate (own attribute only — absent is fine)
- if (node.hasMetaAttr(MetaRelationship.ATTR_ON_UPDATE, false)) {
- String onUpdate = rel.getOnUpdateRaw();
- if (!MetaRelationship.REFERENTIAL_ACTIONS.contains(onUpdate)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": relationship '" + node.getName()
- + "' @onUpdate '" + onUpdate
- + "' is not a valid value; allowed: cascade, set-null, restrict, no-action",
- ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource());
- }
- }
- }
-
// =========================================================================
// FR-017 — M:N relationship validation (slim vocabulary)
//
@@ -3527,17 +3325,11 @@ private static void validateOriginNode(MetaRoot root, MetaObject obj,
if (AggregateOrigin.SUBTYPE_AGGREGATE.equals(subType)) {
com.metaobjects.source.ErrorSource src = origin.getSource();
- // Re-check @agg vocabulary — the .withEnum constraint on the base
- // can be subverted by inline attribute parsing paths; mirror the
- // belt-and-braces approach used for relationship referential actions.
+ // An @agg outside the closed set is reported by the closed-set pass; the
+ // rules below depend on the function, so they are not checked for it.
String agg = origin.getAgg();
if (agg != null && !agg.isEmpty() && !MetaOrigin.AGGREGATE_FUNCTIONS.contains(agg)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": origin.aggregate on " + obj.getName() + "." + field.getName()
- + " @agg '" + agg + "' is not a valid value; allowed: "
- + "count, sum, avg, min, max, any, all, collect",
- ErrorCode.ERR_BAD_ATTR_VALUE, src);
+ return;
}
String of = origin.getOf();
@@ -4226,34 +4018,24 @@ private static void checkObjectIdentity(MetaObject obj, MetaDataLoader loader) {
}
// =========================================================================
- // Identity @fields (required) + @generation (enum) validation
- //
- // The unified registry exposes withEnum() but the runtime doesn't currently
- // walk those constraints post-load (only validators with side-effect passes
- // do). For cross-port parity (TS / C# both throw on these shapes) we run a
- // dedicated pass here.
+ // Identity @fields (required) validation
//
// @fields is required on every identity.* node → ERR_MISSING_REQUIRED_ATTR
- // @generation, if present, must be one of increment / uuid / assigned →
- // ERR_BAD_ATTR_VALUE
// =========================================================================
- static void validateIdentityFieldsAndGeneration(MetaRoot root) {
- walkIdentityFieldsAndGeneration(root);
+ static void validateIdentityFields(MetaRoot root) {
+ walkIdentityFields(root);
}
- private static void walkIdentityFieldsAndGeneration(MetaData node) {
+ private static void walkIdentityFields(MetaData node) {
if (node instanceof MetaIdentity) {
validateIdentityNode((MetaIdentity) node);
}
for (MetaData child : node.getChildren(MetaData.class, false)) {
- walkIdentityFieldsAndGeneration(child);
+ walkIdentityFields(child);
}
}
- private static final java.util.Set VALID_IDENTITY_GENERATIONS =
- java.util.Set.of("increment", "uuid", "assigned");
-
private static void validateIdentityNode(MetaIdentity identity) {
// FR-024 (ADR-0029): an identity with a resolved extends (identity
// pass-through, e.g. a projection identity extending an entity identity)
@@ -4282,18 +4064,6 @@ && hasNonBlankAttr(identity, SecondaryIdentity.ATTR_EXPR)) {
+ "' is missing required @fields attribute",
ErrorCode.ERR_MISSING_REQUIRED_ATTR, identity.getSource());
}
- if (identity.hasMetaAttr(MetaIdentity.ATTR_GENERATION, false)) {
- Object v = identity.getMetaAttr(MetaIdentity.ATTR_GENERATION, false).getValue();
- String gen = v == null ? null : v.toString();
- if (gen != null && !VALID_IDENTITY_GENERATIONS.contains(gen)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": identity '" + identity.getName()
- + "' @generation '" + gen + "' is not a valid value;"
- + " allowed: increment, uuid, assigned",
- ErrorCode.ERR_BAD_ATTR_VALUE, identity.getSource());
- }
- }
}
// =========================================================================
@@ -4973,8 +4743,6 @@ static boolean isAbstract(MetaData node) {
// object.value at root → ERR_INVALID_TEMPLATE
// R3: template.prompt @requiredSlots members must each be a field on the
// resolved payload VO → ERR_INVALID_TEMPLATE
- // R4: @format (if present) must be a member of TemplateConstants.ALLOWED_FORMATS
- // → ERR_BAD_ATTR_VALUE
//
// Templates always live at the document root. We walk root children only.
// =========================================================================
@@ -4996,64 +4764,8 @@ private static void validateTemplateNode(MetaRoot root, MetaTemplate template) {
String subType = template.getSubType();
String payloadRef = template.getPayloadRef();
- // R4 — @format (if present) must be in the closed allowed set
- // (text|html|xml|csv|json|markdown|spreadsheet).
- // ADR-0039: resolving — a template may inherit @format via extends
- // (templates CAN extend; consistent with the merged codegen template
- // decision). TS handles @format via the resolving generic schema pass.
- if (template.hasMetaAttr(TemplateConstants.ATTR_FORMAT)) {
- String fmt = template.getMetaAttr(TemplateConstants.ATTR_FORMAT).getValueAsString();
- if (fmt != null && !TemplateConstants.ALLOWED_FORMATS.contains(fmt)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": template '" + template.getName()
- + "' @format '" + fmt
- + "' is not a valid value; allowed: "
- + TemplateConstants.ALLOWED_FORMATS,
- ErrorCode.ERR_BAD_ATTR_VALUE, template.getSource());
- }
- }
-
- // R5 — @promptStyle (template.prompt only since ADR-0052, FR-010) must be in
- // the closed set (guide|inline|exampleOnly). Absent is fine; default is "guide".
- // ADR-0039: resolving — a template may inherit @promptStyle via extends.
- if (template.hasMetaAttr(TemplateConstants.ATTR_PROMPT_STYLE)) {
- String style = template.getMetaAttr(TemplateConstants.ATTR_PROMPT_STYLE)
- .getValueAsString();
- if (style != null && !TemplateConstants.ALLOWED_PROMPT_STYLES.contains(style)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": template '" + template.getName()
- + "' @promptStyle '" + style
- + "' is not a valid value; allowed: "
- + TemplateConstants.ALLOWED_PROMPT_STYLES,
- ErrorCode.ERR_BAD_ATTR_VALUE, template.getSource());
- }
- }
-
- // R5b — @responseFormat (template.prompt only, ADR-0053) must be in the closed
- // set (json|xml). Absent is fine; default is "json". Deliberately NOT
- // ALLOWED_FORMATS: a reply is only ever parsed as JSON or XML, and registering
- // members nothing dispatches on is what ADR-0007 Amendment 2 forbids.
- // ADR-0039: resolving — a template may inherit @responseFormat via extends.
- if (template.hasMetaAttr(TemplateConstants.ATTR_RESPONSE_FORMAT)) {
- String respFmt = template.getMetaAttr(TemplateConstants.ATTR_RESPONSE_FORMAT)
- .getValueAsString();
- if (respFmt != null
- && !TemplateConstants.ALLOWED_RESPONSE_FORMATS.contains(respFmt)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": template '" + template.getName()
- + "' @responseFormat '" + respFmt
- + "' is not a valid value; allowed: "
- + TemplateConstants.ALLOWED_RESPONSE_FORMATS,
- ErrorCode.ERR_BAD_ATTR_VALUE, template.getSource());
- }
- }
-
- // R6 — @kind (template.output only, Task 1) closed-enum + conditional
- // ref requirements. @kind is a closed set (document|email); an email
- // requires @subjectRef + @htmlBodyRef; a document (or absent @kind)
+ // R6 — @kind (template.output only, Task 1) conditional ref requirements.
+ // An email requires @subjectRef + @htmlBodyRef; a document (or absent @kind)
// requires @textRef. template.prompt always requires @textRef (its
// renderable body). Mirrors TS validateTemplatePayloadRefs.
if (TemplateConstants.SUBTYPE_OUTPUT.equals(subType)) {
@@ -5063,16 +4775,6 @@ private static void validateTemplateNode(MetaRoot root, MetaTemplate template) {
String kind = template.hasMetaAttr(TemplateConstants.ATTR_KIND)
? template.getMetaAttr(TemplateConstants.ATTR_KIND).getValueAsString()
: null;
- // Closed-enum membership (absent → default "document").
- if (kind != null && !TemplateConstants.ALLOWED_KINDS.contains(kind)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": template '" + template.getName()
- + "' @kind '" + kind
- + "' is not a valid value; allowed: "
- + TemplateConstants.ALLOWED_KINDS,
- ErrorCode.ERR_BAD_ATTR_VALUE, template.getSource());
- }
if (TemplateConstants.KIND_EMAIL.equals(kind)) {
if (!template.hasMetaAttr(TemplateConstants.ATTR_SUBJECT_REF)) {
throw new MetaDataException(
@@ -5090,7 +4792,8 @@ private static void validateTemplateNode(MetaRoot root, MetaTemplate template) {
}
} else {
// @kind absent or "document" → require @textRef so a document is
- // never bodyless. (An out-of-enum @kind already threw above.)
+ // never bodyless. (An out-of-enum @kind is reported by the closed-set
+ // pass; @textRef is still required, as in TS.)
if (!template.hasMetaAttr(TemplateConstants.ATTR_TEXT_REF)) {
throw new MetaDataException(
ErrorMessageConstants.ERR_INVALID_TEMPLATE
@@ -7084,60 +6787,4 @@ private static boolean hasNonBlankAttr(MetaData node, String name) {
return v != null && !v.trim().isEmpty();
}
- // =========================================================================
- // requirement.* @status enum validation
- //
- // Applied to every requirement.* node after the full tree is built (attrs are
- // set post-placement, so the registered .withEnum() CustomConstraint cannot
- // fire at addChild time — its applicability test sees the ATTR node's own
- // type/subtype, not the container's; same reason source @kind/@role and
- // relationship @onDelete/@onUpdate use post-load passes).
- //
- // @status must be one of: planned / live / partial
- //
- // This is the mechanism the capability ledger was made registered vocabulary
- // FOR (requirements-as-metadata ruling, Amendment 3): a typo'd status is
- // refused by the LOADER, not by a hand-written string comparison in one CLI.
- // ERR_BAD_ATTR_VALUE is the existing cross-port code for an out-of-set
- // allowedValues member — no new error code.
- // =========================================================================
-
- /**
- * Walk the full tree and validate {@code @status} on every {@code requirement.*} node.
- *
- * @param root the root node to walk
- * @throws MetaDataException when {@code @status} carries a value outside the closed set
- */
- static void validateRequirementStatus(MetaRoot root) {
- walkRequirementStatus(root);
- }
-
- private static void walkRequirementStatus(MetaData node) {
- validateRequirementStatusNode(node);
- for (MetaData child : node.getChildren(MetaData.class, false)) {
- walkRequirementStatus(child);
- }
- }
-
- private static void validateRequirementStatusNode(MetaData node) {
- if (!(node instanceof MetaRequirement)) {
- return;
- }
- // Own attribute only — an inherited @status was already validated on its declaring
- // node, matching the source @kind/@role and relationship @onDelete/@onUpdate passes.
- if (!node.hasMetaAttr(MetaRequirement.ATTR_STATUS, false)) {
- return;
- }
- String status = ((MetaRequirement) node).getStatus();
- if (!MetaRequirement.STATUSES.contains(status)) {
- throw new MetaDataException(
- ErrorMessageConstants.ERR_BAD_ATTR_VALUE
- + ": requirement '" + node.getName()
- + "' @" + MetaRequirement.ATTR_STATUS + " '" + status
- + "' is not a valid value; allowed: "
- + String.join(", ", MetaRequirement.STATUSES),
- ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource());
- }
- }
-
}
diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java b/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java
index f72f68be3a..274ee57a2d 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java
@@ -1632,10 +1632,11 @@ private static String directKey(ChildRequirement req) {
}
/**
- * Put the reference facet the spec definitions declare onto each attr requirement, direct
- * and inherited, of every registered type — and nothing else. The core bootstrap runs this
- * so a registry that never goes through {@link #applySpecDescriptions} (the SPI singleton,
- * {@link #createWithCoreProviders()}) still enforces the core references, and
+ * Put the reference facet and the closed value set the spec definitions declare onto each
+ * attr requirement, direct and inherited, of every registered type — and nothing else. The
+ * core bootstrap runs this so a registry that never goes through {@link #applySpecDescriptions}
+ * (the SPI singleton, {@link #createWithCoreProviders()}) still enforces the core references
+ * and closed sets, and
* {@link #applySpecDescriptions} runs it last so every path ends the same.
*
*
An extension subtype the spec does not declare inherits its parent's definition data,
@@ -1702,10 +1703,17 @@ private static ChildRequirement withSpecRef(ChildRequirement req, MetaDataTypeId
}
com.metaobjects.registry.spec.SpecMetamodelReader.AttrEntry doc =
reader.attrDoc(id.type(), id.subType(), req.getName());
- if (doc == null || doc.ref() == null || doc.ref().equals(req.getRef())) {
+ if (doc == null) {
return req;
}
- return req.withRef(doc.ref());
+ ChildRequirement out = req;
+ if (doc.ref() != null && !doc.ref().equals(req.getRef())) {
+ out = out.withRef(doc.ref());
+ }
+ if (doc.allowedValues() != null && !doc.allowedValues().equals(req.getAllowedValues())) {
+ out = out.withAllowedValues(doc.allowedValues());
+ }
+ return out;
}
/**
diff --git a/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java
index 7ff113668c..12351e01ab 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java
@@ -61,9 +61,16 @@ public void registerTypes(MetaDataRegistry registry) {
str(d, "runsAs");
d.optionalChild("build", "*", "*");
});
- sub(registry, "app", "service", d -> bool(d, "public"));
+ sub(registry, "app", "service", d -> {
+ bool(d, "public");
+ strArray(d, "provides");
+ });
sub(registry, "app", "client", d -> str(d, "shell"));
- sub(registry, "app", "job", d -> str(d, "schedule"));
+ sub(registry, "app", "job", d -> {
+ str(d, "schedule");
+ strArray(d, "provides");
+ str(d, "extracts");
+ });
// build
base(registry, "build", d -> { });
@@ -77,14 +84,18 @@ public void registerTypes(MetaDataRegistry registry) {
sub(registry, "resource", "rdb", d ->
d.optionalAttributeWithConstraints("schemas").ofType(StringAttribute.SUBTYPE_STRING).asArray());
sub(registry, "resource", "keyValue", d -> bool(d, "volatile"));
- sub(registry, "resource", "objectStore", d -> bool(d, "publicRead"));
+ sub(registry, "resource", "objectStore", d -> {
+ bool(d, "publicRead");
+ strArray(d, "carries");
+ });
sub(registry, "resource", "document", d -> { });
sub(registry, "resource", "search", d -> { });
sub(registry, "resource", "queue", d -> {
bool(d, "ordered");
bool(d, "deadLetter");
+ strArray(d, "carries");
});
- sub(registry, "resource", "stream", d -> { });
+ sub(registry, "resource", "stream", d -> strArray(d, "carries"));
sub(registry, "resource", "volume", d -> { });
// role
@@ -165,6 +176,10 @@ private static void str(TypeDefinitionBuilder d, String name) {
d.optionalAttributeWithConstraints(name).ofType(StringAttribute.SUBTYPE_STRING).asSingle();
}
+ private static void strArray(TypeDefinitionBuilder d, String name) {
+ d.optionalAttributeWithConstraints(name).ofType(StringAttribute.SUBTYPE_STRING).asArray();
+ }
+
private static void required(TypeDefinitionBuilder d, String name) {
d.requiredAttributeWithConstraints(name).ofType(StringAttribute.SUBTYPE_STRING).asSingle();
}
diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/ClosedSetValuesLoadTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/ClosedSetValuesLoadTest.java
new file mode 100644
index 0000000000..0c7de6ab0d
--- /dev/null
+++ b/server/java/metadata/src/test/java/com/metaobjects/loader/ClosedSetValuesLoadTest.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2026 Doug Mealing LLC dba Meta Objects
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.metaobjects.loader;
+
+import com.metaobjects.ErrorCode;
+import com.metaobjects.MetaDataException;
+import com.metaobjects.registry.SharedRegistryTestBase;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Two out-of-set values on ONE node are two findings through the full loader, as in the
+ * TypeScript reference (attr-schema-validate Check 3): the closed-set findings share code and
+ * source envelope, so the load-level dedupe must keep them apart by message.
+ */
+public class ClosedSetValuesLoadTest extends SharedRegistryTestBase {
+
+ private static List loadFindings(String json) {
+ MetaDataLoader loader = new MetaDataLoader(
+ LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "closed-set-values");
+ loader.setSourceURIs(java.util.Collections.emptyList());
+ loader.init();
+ List found = new ArrayList<>();
+ try {
+ loader.load(List.of(new InMemoryStringSource(json, "meta.ledger.json")));
+ } catch (MetaDataException thrown) {
+ found.addAll(loader.getErrors());
+ found.add(thrown);
+ }
+ return found;
+ }
+
+ private static List messages(List found) {
+ List out = new ArrayList<>();
+ for (MetaDataException e : found) {
+ assertEquals(e.getMessage(), ErrorCode.ERR_BAD_ATTR_VALUE, e.getCode().orElseThrow());
+ out.add(e.getMessage());
+ }
+ return out;
+ }
+
+ @Test
+ public void twoBadAttrsOnOneBindingAreTwoErrors() {
+ String json = "{ \"metadata.root\": { \"package\": \"acme::ledger\", \"children\": ["
+ + "{ \"object.value\": { \"name\": \"SettlementLine\", \"children\": [ { \"field.string\": { \"name\": \"reference\" } } ] } },"
+ + "{ \"api.batch\": { \"name\": \"SettlementFeed\", \"children\": [ { \"operation.export\": {"
+ + " \"name\": \"dailySettlement\", \"@outputRef\": \"SettlementLine\", \"@frequency\": \"daily\", \"children\": ["
+ + " { \"binding.file\": { \"@transport\": \"sftp\", \"@fileName\": \"settlement-{date}.csv\","
+ + " \"@format\": \"fixedWidth\", \"@encryption\": \"rot13\" } } ] } } ] } } ] } }";
+ assertEquals(List.of(
+ "binding.file attribute '@format' has value 'fixedWidth' which is not one of the allowed values: "
+ + "csv, jsonLines, parquet",
+ "binding.file attribute '@encryption' has value 'rot13' which is not one of the allowed values: "
+ + "none, pgp"),
+ messages(loadFindings(json)));
+ }
+
+ @Test
+ public void twoBadElementsOfOneArrayAttrAreTwoErrors() {
+ String json = "{ \"metadata.root\": { \"package\": \"acme::ledger\", \"children\": ["
+ + "{ \"object.entity\": { \"name\": \"Purchase\", \"children\": ["
+ + " { \"field.long\": { \"name\": \"id\" } },"
+ + " { \"field.timestamp\": { \"name\": \"purchasedAt\" } },"
+ + " { \"identity.primary\": { \"@fields\": [\"id\"] } },"
+ + " { \"dimension.time\": { \"name\": \"purchasedAt\", \"@of\": \"Purchase.purchasedAt\", \"@grains\": [\"day\", \"fortnight\", \"decade\"] } }"
+ + "] } } ] } }";
+ assertEquals(List.of(
+ "dimension.time 'purchasedAt' attribute '@grains' has value 'fortnight' which is not one of the "
+ + "allowed values: hour, day, week, month, quarter, year",
+ "dimension.time 'purchasedAt' attribute '@grains' has value 'decade' which is not one of the "
+ + "allowed values: hour, day, week, month, quarter, year"),
+ messages(loadFindings(json)));
+ }
+}
diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java
index 333081e3ba..8521f89ba7 100644
--- a/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java
+++ b/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java
@@ -439,14 +439,17 @@ public void aFieldNamedNowIsAFieldNotARelativeDate() throws IOException {
}
// ---------------------------------------------------------------------------
- // Closed sets (Java: .withEnum is decorative, so the pass enforces them)
+ // Closed sets (the loader's generic allowed-values pass; none is reported by the reporting pass)
// ---------------------------------------------------------------------------
@Test
public void aggOutsideTheClosedSetIsABadAttrValue() throws IOException {
JsonObject doc = cleanModel();
member(doc, "Purchase", "measure.aggregate", "revenue").addProperty("@agg", "median");
- List got = ValidationPhase.validateReporting(loadJson(doc));
+ MetaRoot root = loadJson(doc);
+ assertEquals(List.of(), ValidationPhase.validateReporting(root));
+ List got = new java.util.ArrayList<>();
+ ValidationPhase.validateAllowedValues(root, sharedRegistry, got);
assertEquals(List.of("ERR_BAD_ATTR_VALUE"), codes(got));
// Byte-identical to the TS attr-schema check (attr-schema-validate.ts, Check 3).
assertEquals("measure.aggregate 'revenue' attribute '@agg' has value 'median' which is not one of "
@@ -458,7 +461,10 @@ public void grainOutsideTheClosedSetIsABadAttrValue() throws IOException {
JsonObject doc = cleanModel();
member(doc, "Purchase", "dimension.time", "purchasedAt").add("@grains",
JsonParser.parseString("[\"day\", \"fortnight\"]"));
- List got = ValidationPhase.validateReporting(loadJson(doc));
+ MetaRoot root = loadJson(doc);
+ assertEquals(List.of(), ValidationPhase.validateReporting(root));
+ List got = new java.util.ArrayList<>();
+ ValidationPhase.validateAllowedValues(root, sharedRegistry, got);
assertEquals(List.of("ERR_BAD_ATTR_VALUE"), codes(got));
// An isArray attr reports each offending ELEMENT, as TS does.
assertEquals("dimension.time 'purchasedAt' attribute '@grains' has value 'fortnight' which is not one "
diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/RulesValidationMethodOrderTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/RulesValidationMethodOrderTest.java
index 23058c7bf5..40bdf892ee 100644
--- a/server/java/metadata/src/test/java/com/metaobjects/loader/RulesValidationMethodOrderTest.java
+++ b/server/java/metadata/src/test/java/com/metaobjects/loader/RulesValidationMethodOrderTest.java
@@ -17,7 +17,6 @@
import com.metaobjects.ErrorCode;
import com.metaobjects.MetaDataException;
-import com.metaobjects.MetaRoot;
import com.metaobjects.registry.SharedRegistryTestBase;
import org.junit.Test;
@@ -53,14 +52,15 @@ public void badMethodIsReportedAlongsideAnO1Failure() throws Exception {
LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "rules-method-order");
loader.setSourceURIs(java.util.Collections.emptyList());
loader.init();
+ MetaDataException thrown = null;
try {
loader.load(List.of(new InMemoryStringSource(broken, "meta.purchasing.json")));
} catch (MetaDataException expected) {
- // the load fails on the rules; the tree is still built
+ thrown = expected;
}
- MetaRoot root = loader.getRoot();
- List codes = RulesValidation.validate(root).stream()
- .map(e -> e.getCode().orElseThrow()).collect(Collectors.toList());
+ List codes = new java.util.ArrayList<>(loader.getErrors().stream()
+ .map(e -> e.getCode().orElseThrow()).collect(Collectors.toList()));
+ if (thrown != null) codes.add(thrown.getCode().orElseThrow());
assertTrue(codes.toString(), codes.contains(ErrorCode.ERR_OPERATION_SHAPE));
assertTrue(codes.toString(), codes.contains(ErrorCode.ERR_BAD_ATTR_VALUE));
}
diff --git a/server/java/metadata/src/test/java/com/metaobjects/template/PromptStyleAttrTest.java b/server/java/metadata/src/test/java/com/metaobjects/template/PromptStyleAttrTest.java
index 05ae1a532b..99dfc78c77 100644
--- a/server/java/metadata/src/test/java/com/metaobjects/template/PromptStyleAttrTest.java
+++ b/server/java/metadata/src/test/java/com/metaobjects/template/PromptStyleAttrTest.java
@@ -187,12 +187,10 @@ public void rejectsUnknownResponseFormatValue() {
try {
load(json, "bad-response-format.json");
fail("an out-of-set @responseFormat must be rejected");
- } catch (RuntimeException e) {
- boolean messageMatches = e.getMessage() != null
- && e.getMessage().contains("ERR_BAD_ATTR_VALUE");
- assertTrue(
+ } catch (MetaDataException e) {
+ assertEquals(
"Exception must signal ERR_BAD_ATTR_VALUE: " + e.getMessage(),
- messageMatches);
+ java.util.Optional.of(ErrorCode.ERR_BAD_ATTR_VALUE), e.getCode());
}
}
}
diff --git a/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java b/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java
index f2bdf4a0b2..f27ac4497f 100644
--- a/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java
+++ b/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java
@@ -323,13 +323,15 @@ public void theReaderCarriesATargetTypeListAsWritten() {
"relationship.base @objectRef object false ERR_INVALID_RELATIONSHIP",
"relationship.composition @objectRef object false ERR_INVALID_RELATIONSHIP");
- /** The systems vocabulary's four references (ADR-0070), each written on every subtype that
+ /** The systems vocabulary's references (ADR-0070), each written on every subtype that
* inherits it. They name a target subtype or a system boundary, which core's four do not. */
private static final List SYSTEMS_FACETS = List.of(
- "app.base @runsAs", "app.client @runsAs", "app.job @runsAs", "app.service @runsAs",
+ "app.base @runsAs", "app.client @runsAs", "app.job @extracts", "app.job @provides", "app.job @runsAs",
+ "app.service @provides", "app.service @runsAs",
"grant.api @api", "grant.document @resource", "grant.keyValue @resource",
"grant.objectStore @resource", "grant.queue @resource", "grant.rdb @resource",
"grant.search @resource", "grant.stream @resource",
+ "resource.objectStore @carries", "resource.queue @carries", "resource.stream @carries",
"role.base @memberOf", "role.group @memberOf", "role.service @memberOf",
"role.token @heldBy", "role.token @memberOf", "role.user @memberOf",
"source.document @resource", "source.rdb @resource", "source.search @resource",
diff --git a/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js b/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js
index a2681492a9..ec81740b86 100644
--- a/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js
+++ b/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js
@@ -265,5 +265,5 @@
`);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(`
`)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",`
`,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(`${tag}>`)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(`
-`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(`
`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
`}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`
${cols.map((o)=>`
${this.link(from,o.id)}
`).join("")}
`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`
`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`
`,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
None.
');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
None.
')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
Not scanned.
');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
No prompt text was read.
':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
None.
':`
${items.map((i)=>`
${i}
`).join("")}
`}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found
No such page
${escapeHtml2(r.path)} is not a page of this model.
`,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="
No model yet
The explorer is waiting for the running application's docs view.
";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="
explorer-model.js did not load. Run meta gen to write it beside this page.
";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})();
diff --git a/server/python/src/metaobjects/loader/validate_rules.py b/server/python/src/metaobjects/loader/validate_rules.py
index ead5659bd2..16830de5f9 100644
--- a/server/python/src/metaobjects/loader/validate_rules.py
+++ b/server/python/src/metaobjects/loader/validate_rules.py
@@ -17,8 +17,8 @@
Rules:
L1 ERR_TRANSITION_NOT_ON_ENTITY a transition under an enum field not declared on an object.entity
L2 ERR_TRANSITION_NOT_ON_ENTITY a concrete entity with a lifecycle and a source, none of them writable
- (on the entity). An entity with no source at all is inert: its
- lifecycle loads and derives nothing (lifecycle_is_live).
+ (on the entity). An entity with no relational source (none, or
+ only source.document / source.search) is inert: its lifecycle loads and derives nothing (lifecycle_is_live).
L3 ERR_LIFECYCLE_NO_INITIAL an enum field declaring transitions has no @default
L4 ERR_TRANSITION_UNKNOWN_STATE a @from or @to value is not one of the enum's @values
L5 ERR_TRANSITION_NAME_COLLISION a transition named create/get/list/update/delete, in any case
@@ -55,12 +55,22 @@
from ..errors import ErrorCode, MetaError
from ..meta.core.api.api_constants import (
+ API_SUBTYPE_OPERATIONAL,
+ AVAILABLE_BY_EXAMPLES,
+ AVAILABLE_BY_PATTERNS,
+ BINDING_ATTR_FILE_NAME,
BINDING_ATTR_METHOD,
BINDING_ATTR_PATH,
+ BINDING_SUBTYPE_FILE,
BINDING_SUBTYPE_REST,
+ FILE_NAME_PLACEHOLDERS,
+ FREQUENCIES,
+ OPERATION_ATTR_AVAILABLE_BY,
+ OPERATION_ATTR_FREQUENCY,
BUSINESS_ERROR_CODE_PATTERN,
OPERATION_ATTR_ERRORS,
OPERATION_ATTR_INPUT_REF,
+ OPERATION_ATTR_KEY,
OPERATION_ATTR_MANY,
OPERATION_ATTR_OBJECT_REF,
OPERATION_ATTR_OUTPUT_REF,
@@ -69,6 +79,7 @@
OPERATION_ATTR_TRANSITIONS,
PERMISSION_NAME_PATTERN,
OPERATION_SUBTYPE_COMMAND,
+ OPERATION_SUBTYPE_EVENT,
RESERVED_ERROR_CODES,
RESERVED_OPERATION_NAMES,
)
@@ -324,7 +335,7 @@ def _check_entity_lifecycles(entity: MetaData, sink: _Sink) -> None:
ErrorCode.ERR_TRANSITION_NOT_ON_ENTITY,
f'object.entity "{entity.name}" has a lifecycle (transitions on {_quote_list(owners)}) and a '
"source, but no writable one; a transition is a guarded update of a stored row. (An entity "
- "with no source at all may carry a lifecycle: it is inert until a source is added.)",
+ "with no relational source may carry a lifecycle: it is inert until a source.rdb is added.)",
)
@@ -359,34 +370,8 @@ def _check_operation(op: MetaData, sink: _Sink) -> None:
)
sink.add(op, ErrorCode.ERR_BAD_ATTR_VALUE, f'operation.{op.sub_type} "{_label(op)}" @errors: {why}.')
- # O1 — shapes.
- input_ref = op.get_meta_attr(OPERATION_ATTR_INPUT_REF)
- if isinstance(input_ref, str):
- inp = resolve_object_on(op, input_ref)
- if inp is None or inp.sub_type != OBJECT_SUBTYPE_VALUE:
- what = "names no object" if inp is None else f"is an object.{inp.sub_type}"
- sink.add(
- op,
- ErrorCode.ERR_OPERATION_SHAPE,
- f'operation.{op.sub_type} "{_label(op)}" @inputRef "{input_ref}" {what}; '
- "an operation's input is an object.value.",
- )
- return
- output_ref = op.get_meta_attr(OPERATION_ATTR_OUTPUT_REF)
- if isinstance(output_ref, str):
- out = resolve_object_on(op, output_ref)
- legal = out is not None and out.sub_type in (
- OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE,
- )
- if not legal:
- what = "names no object" if out is None else f"is an object.{out.sub_type}"
- sink.add(
- op,
- ErrorCode.ERR_OPERATION_SHAPE,
- f'operation.{op.sub_type} "{_label(op)}" @outputRef "{output_ref}" {what}; '
- "an operation returns an object.entity, object.projection or object.value.",
- )
- return
+ if not _check_shapes(op, sink):
+ return
# O2, O3 — the target.
derived_target = derive_operation_target(op)
@@ -462,6 +447,95 @@ def _check_operation(op: MetaData, sink: _Sink) -> None:
)
+def _check_shapes(op: MetaData, sink: _Sink) -> bool:
+ """O1 — an operation's @inputRef and @outputRef shapes. False when one is wrong."""
+ input_ref = op.get_meta_attr(OPERATION_ATTR_INPUT_REF)
+ if isinstance(input_ref, str):
+ inp = resolve_object_on(op, input_ref)
+ if inp is None or inp.sub_type != OBJECT_SUBTYPE_VALUE:
+ what = "names no object" if inp is None else f"is an object.{inp.sub_type}"
+ sink.add(
+ op,
+ ErrorCode.ERR_OPERATION_SHAPE,
+ f'operation.{op.sub_type} "{_label(op)}" @inputRef "{input_ref}" {what}; '
+ "an operation's input is an object.value.",
+ )
+ return False
+ output_ref = op.get_meta_attr(OPERATION_ATTR_OUTPUT_REF)
+ if isinstance(output_ref, str):
+ out = resolve_object_on(op, output_ref)
+ legal = out is not None and out.sub_type in (
+ OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE,
+ )
+ if not legal:
+ what = "names no object" if out is None else f"is an object.{out.sub_type}"
+ sink.add(
+ op,
+ ErrorCode.ERR_OPERATION_SHAPE,
+ f'operation.{op.sub_type} "{_label(op)}" @outputRef "{output_ref}" {what}; '
+ "an operation returns an object.entity, object.projection or object.value.",
+ )
+ return False
+ return True
+
+
+def _file_name_placeholder_problem(file_name: str) -> str | None:
+ """What is wrong with a @fileName's placeholders, or None when nothing is."""
+ for m in re.finditer(r"\{([^{}]*)\}", file_name):
+ if m.group(1) not in FILE_NAME_PLACEHOLDERS:
+ return f"holds the placeholder {{{m.group(1)}}}"
+ if re.search(r"[{}]", re.sub(r"\{[^{}]*\}", "", file_name)):
+ return "has an unmatched brace"
+ return None
+
+
+def _check_delivery_operation(op: MetaData, sink: _Sink) -> None:
+ """O1, D1, D2 and D3 for one operation of an api.eventing or api.batch: its shapes, the form of an
+ export's @availableBy, the placeholders of each binding.file @fileName and an event's @key."""
+ if not _check_shapes(op, sink):
+ return
+ key = op.get_meta_attr(OPERATION_ATTR_KEY)
+ output_ref = op.get_meta_attr(OPERATION_ATTR_OUTPUT_REF)
+ if op.sub_type == OPERATION_SUBTYPE_EVENT and isinstance(key, str) and isinstance(output_ref, str):
+ output = resolve_object_on(op, output_ref)
+ if output is not None and not any(c.type == TYPE_FIELD and c.name == key for c in output.children()):
+ sink.add(
+ op,
+ ErrorCode.ERR_BAD_ATTR_VALUE,
+ f'operation.event "{_label(op)}" @key "{key}" is not a field of "{output.name}"; '
+ "@key names the payload field whose events stay in order.",
+ )
+ frequency = op.get_meta_attr(OPERATION_ATTR_FREQUENCY)
+ available_by = op.get_meta_attr(OPERATION_ATTR_AVAILABLE_BY)
+ if (
+ isinstance(available_by, str)
+ and isinstance(frequency, str)
+ and frequency in FREQUENCIES
+ and AVAILABLE_BY_PATTERNS[frequency].fullmatch(available_by) is None
+ ):
+ sink.add(
+ op,
+ ErrorCode.ERR_BAD_ATTR_VALUE,
+ f'operation.{op.sub_type} "{_label(op)}" @availableBy "{available_by}" is not a {frequency} time; '
+ f'a {frequency} file\'s @availableBy is written like "{AVAILABLE_BY_EXAMPLES[frequency]}" (UTC).',
+ )
+ # ADR-0039 sanctioned own: a binding is checked on the operation that declares it.
+ for b in op.own_children():
+ if b.type != TYPE_BINDING or b.sub_type != BINDING_SUBTYPE_FILE:
+ continue
+ file_name = b.get_meta_attr(BINDING_ATTR_FILE_NAME)
+ if not isinstance(file_name, str):
+ continue
+ bad = _file_name_placeholder_problem(file_name)
+ if bad is not None:
+ sink.add(
+ b,
+ ErrorCode.ERR_BAD_ATTR_VALUE,
+ f'binding.file on "{_label(b)}" @fileName "{file_name}" {bad}; '
+ f"the placeholders are {{{'} and {'.join(FILE_NAME_PLACEHOLDERS)}}}.",
+ )
+
+
def validate_rules(root: MetaData, errors: list[MetaError]) -> None:
"""ADR-0066 — the rules pass. Runs after reference-bearing validation, before freeze."""
sink = _Sink(errors)
@@ -476,6 +550,10 @@ def validate_rules(root: MetaData, errors: list[MetaError]) -> None:
if api.type != TYPE_API:
continue
ops = [c for c in api.children() if c.type == TYPE_OPERATION]
+ if api.sub_type != API_SUBTYPE_OPERATIONAL:
+ for op in ops:
+ _check_delivery_operation(op, sink)
+ continue
for op in ops:
_check_operation(op, sink)
for op in ops:
@@ -556,7 +634,7 @@ def register(node: MetaData, owner: MetaData, path: str) -> None:
for t in entity_transitions(entity):
register(t, entity, f"{entity.name}.{t.name}")
for api in root.children():
- if api.type != TYPE_API:
+ if api.type != TYPE_API or api.sub_type != API_SUBTYPE_OPERATIONAL:
continue
for op in api.children():
if op.type == TYPE_OPERATION:
diff --git a/server/python/src/metaobjects/meta/core/api/api_constants.py b/server/python/src/metaobjects/meta/core/api/api_constants.py
index 8e24c45146..a07ea3fef0 100644
--- a/server/python/src/metaobjects/meta/core/api/api_constants.py
+++ b/server/python/src/metaobjects/meta/core/api/api_constants.py
@@ -6,15 +6,35 @@
# A request/response surface whose children are operations. The axis is the interaction
# model, never the protocol (ADR-0030).
API_SUBTYPE_OPERATIONAL = "operational"
-API_SUBTYPES = (API_SUBTYPE_OPERATIONAL,)
+# Events the provider publishes; children are operation.event.
+API_SUBTYPE_EVENTING = "eventing"
+# Datasets delivered as files on a schedule; children are operation.export / .import.
+API_SUBTYPE_BATCH = "batch"
+API_SUBTYPES = (API_SUBTYPE_OPERATIONAL, API_SUBTYPE_EVENTING, API_SUBTYPE_BATCH)
OPERATION_SUBTYPE_COMMAND = "command"
OPERATION_SUBTYPE_QUERY = "query"
-OPERATION_SUBTYPES = (OPERATION_SUBTYPE_COMMAND, OPERATION_SUBTYPE_QUERY)
+# Something that happened; the payload is its @outputRef.
+OPERATION_SUBTYPE_EVENT = "event"
+# A file the provider publishes on a schedule; rows are its @outputRef.
+OPERATION_SUBTYPE_EXPORT = "export"
+# A file the provider accepts on a schedule; rows are its @inputRef.
+OPERATION_SUBTYPE_IMPORT = "import"
+OPERATION_SUBTYPES = (
+ OPERATION_SUBTYPE_COMMAND,
+ OPERATION_SUBTYPE_QUERY,
+ OPERATION_SUBTYPE_EVENT,
+ OPERATION_SUBTYPE_EXPORT,
+ OPERATION_SUBTYPE_IMPORT,
+)
# The HTTP binding of an operation (overrides the derived method and path).
BINDING_SUBTYPE_REST = "rest"
-BINDING_SUBTYPES = (BINDING_SUBTYPE_REST,)
+# How an event travels (optionally pinning the wire protocol).
+BINDING_SUBTYPE_MESSAGING = "messaging"
+# How an export's or import's file is delivered.
+BINDING_SUBTYPE_FILE = "file"
+BINDING_SUBTYPES = (BINDING_SUBTYPE_REST, BINDING_SUBTYPE_MESSAGING, BINDING_SUBTYPE_FILE)
# Attrs on operation.* (@permission / @public are on transition.* too).
OPERATION_ATTR_INPUT_REF = "inputRef"
@@ -31,6 +51,51 @@
BINDING_ATTR_PATH = "path"
HTTP_METHODS = ("GET", "POST", "PUT", "PATCH", "DELETE")
+# Attrs on operation.event / .export / .import.
+OPERATION_ATTR_KEY = "key"
+OPERATION_ATTR_FREQUENCY = "frequency"
+OPERATION_ATTR_AVAILABLE_BY = "availableBy"
+FREQUENCY_HOURLY = "hourly"
+FREQUENCY_DAILY = "daily"
+FREQUENCY_WEEKLY = "weekly"
+FREQUENCY_MONTHLY = "monthly"
+FREQUENCIES = (FREQUENCY_HOURLY, FREQUENCY_DAILY, FREQUENCY_WEEKLY, FREQUENCY_MONTHLY)
+# The form of @availableBy for each @frequency: hourly :MM, daily HH:MM, weekly Ddd HH:MM,
+# monthly D HH:MM with the day 1 to 28 (every month has it). Matched with ``fullmatch``.
+AVAILABLE_BY_PATTERNS = {
+ FREQUENCY_HOURLY: re.compile(r":[0-5][0-9]"),
+ FREQUENCY_DAILY: re.compile(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]"),
+ FREQUENCY_WEEKLY: re.compile(r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]"),
+ FREQUENCY_MONTHLY: re.compile(r"(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]"),
+}
+# An example of each form, for messages.
+AVAILABLE_BY_EXAMPLES = {
+ FREQUENCY_HOURLY: ":15",
+ FREQUENCY_DAILY: "03:00",
+ FREQUENCY_WEEKLY: "Mon 06:00",
+ FREQUENCY_MONTHLY: "1 06:00",
+}
+
+# Attrs on binding.messaging / binding.file.
+BINDING_ATTR_PROTOCOL = "protocol"
+BINDING_ATTR_TRANSPORT = "transport"
+BINDING_ATTR_FILE_NAME = "fileName"
+BINDING_ATTR_FORMAT = "format"
+BINDING_ATTR_COMPRESSION = "compression"
+BINDING_ATTR_COMPLETION = "completion"
+BINDING_ATTR_ENCRYPTION = "encryption"
+MESSAGING_PROTOCOLS = ("kafka", "amqp", "mqtt", "sqs")
+FILE_TRANSPORTS = ("sftp", "objectStore")
+FILE_FORMATS = ("csv", "jsonLines", "parquet")
+FILE_COMPRESSIONS = ("none", "gzip")
+FILE_COMPLETIONS = ("rename", "marker", "none")
+FILE_ENCRYPTIONS = ("none", "pgp")
+# The placeholders a binding.file @fileName may hold: the UTC start of the run, as
+# YYYY-MM-DD and YYYYMMDDTHHMMSSZ.
+FILE_NAME_PLACEHOLDERS = ("date", "timestamp")
+# The suffix of the marker object ``completion: marker`` puts beside a finished file.
+COMPLETION_MARKER_SUFFIX = ".done"
+
# Names a declared operation or a transition may not take: they are the derived CRUD verbs
# of the same service (ERR_TRANSITION_NAME_COLLISION).
RESERVED_OPERATION_NAMES = ("create", "get", "list", "update", "delete")
diff --git a/server/python/src/metaobjects/meta/core/rules/rules_provider.py b/server/python/src/metaobjects/meta/core/rules/rules_provider.py
index a7f2a11857..957f91784a 100644
--- a/server/python/src/metaobjects/meta/core/rules/rules_provider.py
+++ b/server/python/src/metaobjects/meta/core/rules/rules_provider.py
@@ -30,11 +30,35 @@
)
from ...provider_extends import register_extends
from ..api.api_constants import (
+ API_SUBTYPE_BATCH,
+ API_SUBTYPE_EVENTING,
API_SUBTYPE_OPERATIONAL,
+ BINDING_ATTR_COMPLETION,
+ BINDING_ATTR_COMPRESSION,
+ BINDING_ATTR_ENCRYPTION,
+ BINDING_ATTR_FILE_NAME,
+ BINDING_ATTR_FORMAT,
BINDING_ATTR_METHOD,
BINDING_ATTR_PATH,
+ BINDING_ATTR_PROTOCOL,
+ BINDING_ATTR_TRANSPORT,
+ BINDING_SUBTYPE_FILE,
+ BINDING_SUBTYPE_MESSAGING,
BINDING_SUBTYPE_REST,
+ FILE_COMPLETIONS,
+ FILE_COMPRESSIONS,
+ FILE_ENCRYPTIONS,
+ FILE_FORMATS,
+ FILE_TRANSPORTS,
+ FREQUENCIES,
HTTP_METHODS,
+ MESSAGING_PROTOCOLS,
+ OPERATION_ATTR_AVAILABLE_BY,
+ OPERATION_ATTR_FREQUENCY,
+ OPERATION_ATTR_KEY,
+ OPERATION_SUBTYPE_EVENT,
+ OPERATION_SUBTYPE_EXPORT,
+ OPERATION_SUBTYPE_IMPORT,
OPERATION_ATTR_ERRORS,
OPERATION_ATTR_INPUT_REF,
OPERATION_ATTR_MANY,
@@ -73,8 +97,6 @@
type=TYPE_OPERATION,
sub_type=SUBTYPE_BASE,
factory=MetaOperation,
- attrs=list(_OPERATION_COMMON_ATTRS),
- child_rules=[ChildRule(TYPE_BINDING, "*")],
)
)
rules_provider.add(TypeDefinition(type=TYPE_BINDING, sub_type=SUBTYPE_BASE, factory=MetaBinding))
@@ -94,7 +116,29 @@
type=TYPE_API,
sub_type=API_SUBTYPE_OPERATIONAL,
factory=MetaApi,
- child_rules=[ChildRule(TYPE_OPERATION, "*")],
+ child_rules=[
+ ChildRule(TYPE_OPERATION, OPERATION_SUBTYPE_COMMAND),
+ ChildRule(TYPE_OPERATION, OPERATION_SUBTYPE_QUERY),
+ ],
+ )
+)
+rules_provider.add(
+ TypeDefinition(
+ type=TYPE_API,
+ sub_type=API_SUBTYPE_EVENTING,
+ factory=MetaApi,
+ child_rules=[ChildRule(TYPE_OPERATION, OPERATION_SUBTYPE_EVENT)],
+ )
+)
+rules_provider.add(
+ TypeDefinition(
+ type=TYPE_API,
+ sub_type=API_SUBTYPE_BATCH,
+ factory=MetaApi,
+ child_rules=[
+ ChildRule(TYPE_OPERATION, OPERATION_SUBTYPE_EXPORT),
+ ChildRule(TYPE_OPERATION, OPERATION_SUBTYPE_IMPORT),
+ ],
)
)
rules_provider.add(
@@ -107,7 +151,7 @@
AttrSchema(name=OPERATION_ATTR_TRANSITIONS, value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True),
AttrSchema(name=OPERATION_ATTR_ERRORS, value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True),
],
- child_rules=[ChildRule(TYPE_BINDING, "*")],
+ child_rules=[ChildRule(TYPE_BINDING, BINDING_SUBTYPE_REST)],
)
)
rules_provider.add(
@@ -119,7 +163,98 @@
*_OPERATION_COMMON_ATTRS,
AttrSchema(name=OPERATION_ATTR_MANY, value_type=ATTR_SUBTYPE_BOOLEAN, required=False),
],
- child_rules=[ChildRule(TYPE_BINDING, "*")],
+ child_rules=[ChildRule(TYPE_BINDING, BINDING_SUBTYPE_REST)],
+ )
+)
+rules_provider.add(
+ TypeDefinition(
+ type=TYPE_OPERATION,
+ sub_type=OPERATION_SUBTYPE_EVENT,
+ factory=MetaOperation,
+ attrs=[
+ AttrSchema(name=OPERATION_ATTR_OUTPUT_REF, value_type=ATTR_SUBTYPE_STRING, required=True),
+ AttrSchema(name=OPERATION_ATTR_KEY, value_type=ATTR_SUBTYPE_STRING, required=False),
+ ],
+ child_rules=[ChildRule(TYPE_BINDING, BINDING_SUBTYPE_MESSAGING)],
+ )
+)
+rules_provider.add(
+ TypeDefinition(
+ type=TYPE_OPERATION,
+ sub_type=OPERATION_SUBTYPE_EXPORT,
+ factory=MetaOperation,
+ attrs=[
+ AttrSchema(name=OPERATION_ATTR_OUTPUT_REF, value_type=ATTR_SUBTYPE_STRING, required=True),
+ AttrSchema(
+ name=OPERATION_ATTR_FREQUENCY, value_type=ATTR_SUBTYPE_STRING, required=True, allowed_values=FREQUENCIES
+ ),
+ AttrSchema(name=OPERATION_ATTR_AVAILABLE_BY, value_type=ATTR_SUBTYPE_STRING, required=False),
+ ],
+ child_rules=[ChildRule(TYPE_BINDING, BINDING_SUBTYPE_FILE)],
+ )
+)
+rules_provider.add(
+ TypeDefinition(
+ type=TYPE_OPERATION,
+ sub_type=OPERATION_SUBTYPE_IMPORT,
+ factory=MetaOperation,
+ attrs=[
+ AttrSchema(name=OPERATION_ATTR_INPUT_REF, value_type=ATTR_SUBTYPE_STRING, required=True),
+ AttrSchema(
+ name=OPERATION_ATTR_FREQUENCY, value_type=ATTR_SUBTYPE_STRING, required=True, allowed_values=FREQUENCIES
+ ),
+ ],
+ child_rules=[ChildRule(TYPE_BINDING, BINDING_SUBTYPE_FILE)],
+ )
+)
+rules_provider.add(
+ TypeDefinition(
+ type=TYPE_BINDING,
+ sub_type=BINDING_SUBTYPE_MESSAGING,
+ factory=MetaBinding,
+ attrs=[
+ AttrSchema(
+ name=BINDING_ATTR_PROTOCOL,
+ value_type=ATTR_SUBTYPE_STRING,
+ required=False,
+ allowed_values=MESSAGING_PROTOCOLS,
+ ),
+ ],
+ )
+)
+rules_provider.add(
+ TypeDefinition(
+ type=TYPE_BINDING,
+ sub_type=BINDING_SUBTYPE_FILE,
+ factory=MetaBinding,
+ attrs=[
+ AttrSchema(
+ name=BINDING_ATTR_TRANSPORT, value_type=ATTR_SUBTYPE_STRING, required=True, allowed_values=FILE_TRANSPORTS
+ ),
+ AttrSchema(name=BINDING_ATTR_PATH, value_type=ATTR_SUBTYPE_STRING, required=False),
+ AttrSchema(name=BINDING_ATTR_FILE_NAME, value_type=ATTR_SUBTYPE_STRING, required=True),
+ AttrSchema(
+ name=BINDING_ATTR_FORMAT, value_type=ATTR_SUBTYPE_STRING, required=True, allowed_values=FILE_FORMATS
+ ),
+ AttrSchema(
+ name=BINDING_ATTR_COMPRESSION,
+ value_type=ATTR_SUBTYPE_STRING,
+ required=False,
+ allowed_values=FILE_COMPRESSIONS,
+ ),
+ AttrSchema(
+ name=BINDING_ATTR_COMPLETION,
+ value_type=ATTR_SUBTYPE_STRING,
+ required=False,
+ allowed_values=FILE_COMPLETIONS,
+ ),
+ AttrSchema(
+ name=BINDING_ATTR_ENCRYPTION,
+ value_type=ATTR_SUBTYPE_STRING,
+ required=False,
+ allowed_values=FILE_ENCRYPTIONS,
+ ),
+ ],
)
)
rules_provider.add(
diff --git a/server/python/src/metaobjects/rules_check.py b/server/python/src/metaobjects/rules_check.py
index 0488e7cfde..079b188eea 100644
--- a/server/python/src/metaobjects/rules_check.py
+++ b/server/python/src/metaobjects/rules_check.py
@@ -57,6 +57,7 @@
from metaobjects.naming_refs import effective_package_of, top_level_node_of
from metaobjects.requirement_check import SEVERITY_ERROR, SEVERITY_WARN, Diagnostic
from metaobjects.rules_settings import RulesSettings
+from metaobjects.meta.core.api.api_constants import API_SUBTYPE_OPERATIONAL
from metaobjects.shared.base_types import TYPE_API, TYPE_OBJECT, TYPE_OPERATION
from metaobjects.shared.separators import PACKAGE_SEP
@@ -126,7 +127,7 @@ def _operations(root: MetaData) -> list[MetaData]:
return [
op
for api in root.children()
- if api.type == TYPE_API
+ if api.type == TYPE_API and api.sub_type == API_SUBTYPE_OPERATIONAL
for op in api.children()
if op.type == TYPE_OPERATION
]
diff --git a/server/python/src/metaobjects/spec_metamodel/api.json b/server/python/src/metaobjects/spec_metamodel/api.json
index 6c803bfba0..79f2e2cb08 100644
--- a/server/python/src/metaobjects/spec_metamodel/api.json
+++ b/server/python/src/metaobjects/spec_metamodel/api.json
@@ -15,22 +15,39 @@
"whenToUse": "The application does something beyond derived CRUD: a named command (approve, cancel, import) or a named query (my open requests). Declare it here so its input, output, permission and business errors are part of the model. A plain lifecycle needs no api.operational at all: a transition nobody claims is held to derive its own command once a shell is generated, and no shell is generated yet.",
"rules": "Children are `operation.command` and `operation.query`. Lives at the document root. Declares no fields, sources or identities: shapes are referenced, never defined, by the surface. Operation names are compared without case, are unique across every API of one package, except one operation declared identically in two APIs, such as a versioned API beside its successor (one operation declared twice in one API merges), and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). Two declared bindings of one API may not share a method and path (ERR_BINDING_PATH_MISMATCH).",
"children": [
- { "type": "operation", "subType": "*", "name": "*", "min": 0, "max": null, "description": "The operations this surface exposes." }
+ { "type": "operation", "subType": "command", "name": "*", "min": 0, "max": null, "description": "The commands this surface exposes." },
+ { "type": "operation", "subType": "query", "name": "*", "min": 0, "max": null, "description": "The queries this surface exposes." }
]
},
{
- "type": "operation",
- "subType": "base",
- "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.",
+ "type": "api",
+ "subType": "eventing",
+ "extendsBase": true,
+ "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.",
+ "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.",
"children": [
- { "type": "binding", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Optional protocol bindings. Only needed to override the derived method and path." },
- { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." },
- { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." },
- { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." },
- { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." },
- { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }
+ { "type": "operation", "subType": "event", "name": "*", "min": 0, "max": null, "description": "The events this surface publishes." }
+ ]
+ },
+ {
+ "type": "api",
+ "subType": "batch",
+ "extendsBase": true,
+ "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.",
+ "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.",
+ "children": [
+ { "type": "operation", "subType": "export", "name": "*", "min": 0, "max": null, "description": "The datasets the provider publishes." },
+ { "type": "operation", "subType": "import", "name": "*", "min": 0, "max": null, "description": "The datasets the provider accepts." }
]
},
+ {
+ "type": "operation",
+ "subType": "base",
+ "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.",
+ "children": []
+ },
{
"type": "operation",
"subType": "command",
@@ -38,6 +55,12 @@
"description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
"whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.",
"children": [
+ { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." },
+ { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." },
+ { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." },
+ { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." },
{ "type": "attr", "subType": "string", "name": "transitions", "isArray": true, "min": 0, "max": 1, "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." },
{ "type": "attr", "subType": "string", "name": "errors", "isArray": true, "min": 0, "max": 1, "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." }
]
@@ -49,9 +72,52 @@
"description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
"whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.",
"children": [
+ { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." },
+ { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." },
+ { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." },
+ { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." },
{ "type": "attr", "subType": "boolean", "name": "many", "min": 0, "max": 1, "description": "The query returns a list and takes the filter, sort and paging contract. Not implied by the projection, so declared. Absent means one row. Legal on a query only." }
]
},
+ {
+ "type": "operation",
+ "subType": "event",
+ "extendsBase": true,
+ "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.",
+ "children": [
+ { "type": "binding", "subType": "messaging", "name": "*", "min": 0, "max": null, "description": "Optional messaging bindings: how the event travels." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "key", "min": 0, "max": 1, "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised." }
+ ]
+ },
+ {
+ "type": "operation",
+ "subType": "export",
+ "extendsBase": true,
+ "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.",
+ "children": [
+ { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is and how it is written." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file appears: hourly, daily, weekly or monthly." },
+ { "type": "attr", "subType": "string", "name": "availableBy", "min": 0, "max": 1, "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised." }
+ ]
+ },
+ {
+ "type": "operation",
+ "subType": "import",
+ "extendsBase": true,
+ "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.",
+ "children": [
+ { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is delivered and how it is written." },
+ { "type": "attr", "subType": "string", "name": "inputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file is expected: hourly, daily, weekly or monthly." }
+ ]
+ },
{
"type": "binding",
"subType": "base",
@@ -68,6 +134,32 @@
{ "type": "attr", "subType": "string", "name": "method", "min": 0, "max": 1, "allowedValues": ["GET", "POST", "PUT", "PATCH", "DELETE"], "description": "The HTTP method. Absent: GET for a query, POST for a command." },
{ "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "A path template. Its `{name}` placeholders must be exactly the target's primary key fields when the operation is keyed, and there must be none when it is not; two declared bindings of one API may not share the method and path (ERR_BINDING_PATH_MISMATCH)." }
]
+ },
+ {
+ "type": "binding",
+ "subType": "messaging",
+ "extendsBase": true,
+ "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "protocol", "min": 0, "max": 1, "allowedValues": ["kafka", "amqp", "mqtt", "sqs"], "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks." }
+ ]
+ },
+ {
+ "type": "binding",
+ "subType": "file",
+ "extendsBase": true,
+ "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Every export and import whose file conventions two parties must agree on.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." },
+ { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." },
+ { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." },
+ { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." },
+ { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." },
+ { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." },
+ { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." }
+ ]
}
],
"extends": [
diff --git a/server/python/src/metaobjects/spec_metamodel/systems.json b/server/python/src/metaobjects/spec_metamodel/systems.json
index cb6b7da4ed..189eaf4c5e 100644
--- a/server/python/src/metaobjects/spec_metamodel/systems.json
+++ b/server/python/src/metaobjects/spec_metamodel/systems.json
@@ -64,7 +64,8 @@
"description": "A long-running process that answers requests: a web server, an API, a socket server.",
"whenToUse": "Anything that listens on a port and stays up.",
"children": [
- { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." }
+ { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." },
+ { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } }
]
},
{
@@ -84,7 +85,9 @@
"description": "Work that runs to completion and exits: a scheduled task, a migration, a one-off batch. It may run on a schedule (@schedule) or when something triggers it.",
"whenToUse": "A cron job, a nightly import, a queue drain that is not a long-running service.",
"children": [
- { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." }
+ { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." },
+ { "type": "attr", "subType": "string", "name": "extracts", "min": 0, "max": 1, "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object.", "ref": { "targetType": "object", "targetSubTypes": ["entity", "projection"] } },
+ { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } }
]
},
{
@@ -137,7 +140,8 @@
"description": "Files and blobs addressed by key.",
"whenToUse": "Uploaded images, exports, static assets kept outside the app.",
"children": [
- { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." }
+ { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." },
+ { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`.", "ref": { "targetType": "api", "targetSubTypes": ["batch"] } }
]
},
{
@@ -162,7 +166,8 @@
"whenToUse": "Work handed from one app to another to run later.",
"children": [
{ "type": "attr", "subType": "boolean", "name": "ordered", "min": 0, "max": 1, "description": "Messages with the same key are delivered in the order they were sent. Absent means no order is promised." },
- { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." }
+ { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." },
+ { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } }
]
},
{
@@ -170,7 +175,10 @@
"subType": "stream",
"extendsBase": true,
"description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.",
- "whenToUse": "Events several consumers read independently, or read again."
+ "whenToUse": "Events several consumers read independently, or read again.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } }
+ ]
},
{
"type": "resource",
diff --git a/server/python/tests/test_rules_inert.py b/server/python/tests/test_rules_inert.py
index 52fb39e780..da753775c0 100644
--- a/server/python/tests/test_rules_inert.py
+++ b/server/python/tests/test_rules_inert.py
@@ -6,7 +6,7 @@
must generate exactly what the same model without it generates, byte for byte, through every
registered generator and every documentation generator.
-The model pair is ``fixtures/codegen-noop/rules/{with,without}`` (see its README), shared with
+The model set is ``fixtures/codegen-noop/rules/{with,without,with-delivery}`` (see its README), shared with
the other ports' copies of this test. A generator that started reading an operation or a
transition by accident would emit something half-built; this test is what notices.
@@ -159,3 +159,50 @@ def test_exactly_these_generators_cannot_run_from_a_bare_model(tmp_path: Path) -
if THREW in _emit("without", [e], tmp_path / f"probe-{i}")
)
assert threw == []
+
+
+# 1.4.0 — ``api.eventing`` and ``api.batch`` (``operation.event`` / ``.export`` / ``.import``,
+# ``binding.messaging`` / ``.file``) are registered and nothing is generated from them yet. The
+# ``with-delivery`` model is ``with`` plus one API of each kind; every generator but the model
+# explorer must write for it exactly what it writes for ``with``.
+def test_the_with_delivery_model_really_carries_an_eventing_and_a_batch_api() -> None:
+ kinds = sorted(c.sub_type for c in _load("with-delivery").children() if c.type == TYPE_API)
+ assert kinds == ["batch", "eventing", "operational"]
+
+
+@pytest.mark.parametrize("entry", _inert_generators(), ids=lambda e: e.name)
+def test_generator_emits_the_same_files_for_with_delivery_as_for_with(
+ entry: GeneratorEntry, tmp_path: Path
+) -> None:
+ expected = _emit("with", [entry], tmp_path / "a")
+ actual = _emit("with-delivery", [entry], tmp_path / "b")
+ assert actual == expected
+
+
+def test_every_runnable_generator_in_one_run_emits_the_same_files_for_with_delivery(tmp_path: Path) -> None:
+ runnable = [
+ e for i, e in enumerate(_inert_generators())
+ if THREW not in _emit("with", [e], tmp_path / f"probe-{i}")
+ ]
+ expected = _emit("with", runnable, tmp_path / "a")
+ actual = _emit("with-delivery", runnable, tmp_path / "b")
+ assert THREW not in expected, expected.get(THREW)
+ assert actual == expected
+
+
+def test_api_docs_are_byte_identical_for_with_delivery() -> None:
+ assert _api_docs("with-delivery") == _api_docs("with")
+
+
+def test_the_rules_check_sees_the_same_operations_for_with_delivery_as_for_with() -> None:
+ # `verify`'s rules check walks every operation; only an api.operational's are commands or
+ # queries, so an event, export or import must add no summary count and no diagnostic.
+ from metaobjects.rules_check import check_rules
+ from metaobjects.rules_settings import RulesSettings
+
+ settings = RulesSettings(permission_names="require")
+ expected = check_rules(_load("with"), settings)
+ actual = check_rules(_load("with-delivery"), settings)
+ assert expected.summary is not None and expected.summary.operations > 0
+ assert actual.summary == expected.summary
+ assert [d.message for d in actual.diagnostics] == [d.message for d in expected.diagnostics]
diff --git a/server/python/tests/unit/test_reference_facet.py b/server/python/tests/unit/test_reference_facet.py
index 971407925e..68f9772d4e 100644
--- a/server/python/tests/unit/test_reference_facet.py
+++ b/server/python/tests/unit/test_reference_facet.py
@@ -720,7 +720,7 @@ def test_an_attribute_with_no_facet_writes_no_ref_key() -> None:
assert manifest.count('"ref"') == len(_CORE_FACETS)
-def test_the_shipped_systems_definition_declares_the_four_systems_references() -> None:
+def test_the_shipped_systems_definition_declares_the_systems_references() -> None:
registry = compose_registry(list(core_providers))
found = sorted(
{
@@ -732,7 +732,10 @@ def test_the_shipped_systems_definition_declares_the_four_systems_references() -
}
)
assert found == [
+ ("app", "extracts", "object"),
+ ("app", "provides", "api"),
("app", "runsAs", "role"),
+ ("resource", "carries", "api"),
("role", "heldBy", ("organization", "system")),
("role", "memberOf", "role"),
("system", "owner", "organization"),
diff --git a/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js b/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js
index a2681492a9..ec81740b86 100644
--- a/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js
+++ b/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js
@@ -265,5 +265,5 @@
`);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(`
`)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",`
`,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(`${tag}>`)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(`
-`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(`
`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
`}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`
${cols.map((o)=>`
${this.link(from,o.id)}
`).join("")}
`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`
`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`
`,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
None.
');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
None.
')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
Not scanned.
');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
No prompt text was read.
':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
None.
':`
${items.map((i)=>`
${i}
`).join("")}
`}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found
No such page
${escapeHtml2(r.path)} is not a page of this model.
`,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="
No model yet
The explorer is waiting for the running application's docs view.
";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="
explorer-model.js did not load. Run meta gen to write it beside this page.
";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})();
diff --git a/server/rust/metaobjects-codegen/src/service_routes.rs b/server/rust/metaobjects-codegen/src/service_routes.rs
index 766729139d..b89b33e53a 100644
--- a/server/rust/metaobjects-codegen/src/service_routes.rs
+++ b/server/rust/metaobjects-codegen/src/service_routes.rs
@@ -64,6 +64,7 @@ const ATTR_FORM_EXCLUDE: &str = "formExclude";
const ATTR_METHOD: &str = "method";
const ATTR_PATH: &str = "path";
const TYPE_BINDING: &str = "binding";
+const SUBTYPE_REST: &str = "rest";
const ORDER_DESC: &str = "desc";
/// The `axum` the transport crates are written for.
@@ -341,11 +342,9 @@ pub fn routes_packages(ctx: &GenContext<'_>) -> Result, GenEr
},
None => String::new(),
};
- let binding = tree
- .children(o.names.node)
- .iter()
- .copied()
- .find(|&c| tree.node(c).type_name == TYPE_BINDING);
+ let binding = tree.children(o.names.node).iter().copied().find(|&c| {
+ tree.node(c).type_name == TYPE_BINDING && tree.node(c).sub_type == SUBTYPE_REST
+ });
let declared =
|attr| binding.and_then(|b| tree.attr(b, attr)?.as_str().map(str::to_string));
let method = declared(ATTR_METHOD).map_or_else(
diff --git a/server/rust/metaobjects-codegen/tests/rules_inert.rs b/server/rust/metaobjects-codegen/tests/rules_inert.rs
index 506fb9d05c..af3df9b6e1 100644
--- a/server/rust/metaobjects-codegen/tests/rules_inert.rs
+++ b/server/rust/metaobjects-codegen/tests/rules_inert.rs
@@ -73,6 +73,11 @@ fn pick_of(name: &str) -> Pick {
/// Every file the picked shipped generators write for one variant: path to contents.
fn emit(variant: &str, pick: Pick) -> BTreeMap {
+ emit_where(variant, |name| pick_of(name) == pick)
+}
+
+/// Every file the shipped generators `keep` selects write for one variant: path to contents.
+fn emit_where(variant: &str, keep: impl Fn(&str) -> bool) -> BTreeMap {
let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../../fixtures/codegen-noop/rules")
.join(variant)
@@ -98,7 +103,7 @@ fn emit(variant: &str, pick: Pick) -> BTreeMap {
.into_iter()
.filter(|g| g.name() != "shared-model")
{
- if pick_of(g.name()) != pick {
+ if !keep(g.name()) {
continue;
}
let emitted = g
@@ -253,3 +258,23 @@ fn the_transport_writes_the_same_files_and_changes_only_its_manifest_and_router(
}
}
}
+
+/// 1.4.0: `api.eventing` and `api.batch` (with `operation.event`, `.export` and `.import`, and
+/// `binding.messaging` and `binding.file`) are registered and nothing is generated from them.
+/// `with-delivery` is `with` plus one API of each kind; every generator but the model explorer
+/// writes exactly what it writes for `with`, the service generators included: they read only
+/// `api.operational` and select its `binding.rest` by subtype.
+#[test]
+fn eventing_and_batch_apis_generate_what_the_model_without_them_does() {
+ let every = |name: &str| name != "docs-site";
+ let with = emit_where("with", every);
+ let delivery = emit_where("with-delivery", every);
+ assert!(with.len() > 10, "the model generates something");
+ assert_eq!(
+ delivery.keys().collect::>(),
+ with.keys().collect::>()
+ );
+ for (path, text) in &with {
+ assert_eq!(&delivery[path], text, "{path}");
+ }
+}
diff --git a/server/rust/metaobjects/data/metamodel/api.json b/server/rust/metaobjects/data/metamodel/api.json
index 6c803bfba0..79f2e2cb08 100644
--- a/server/rust/metaobjects/data/metamodel/api.json
+++ b/server/rust/metaobjects/data/metamodel/api.json
@@ -15,22 +15,39 @@
"whenToUse": "The application does something beyond derived CRUD: a named command (approve, cancel, import) or a named query (my open requests). Declare it here so its input, output, permission and business errors are part of the model. A plain lifecycle needs no api.operational at all: a transition nobody claims is held to derive its own command once a shell is generated, and no shell is generated yet.",
"rules": "Children are `operation.command` and `operation.query`. Lives at the document root. Declares no fields, sources or identities: shapes are referenced, never defined, by the surface. Operation names are compared without case, are unique across every API of one package, except one operation declared identically in two APIs, such as a versioned API beside its successor (one operation declared twice in one API merges), and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). Two declared bindings of one API may not share a method and path (ERR_BINDING_PATH_MISMATCH).",
"children": [
- { "type": "operation", "subType": "*", "name": "*", "min": 0, "max": null, "description": "The operations this surface exposes." }
+ { "type": "operation", "subType": "command", "name": "*", "min": 0, "max": null, "description": "The commands this surface exposes." },
+ { "type": "operation", "subType": "query", "name": "*", "min": 0, "max": null, "description": "The queries this surface exposes." }
]
},
{
- "type": "operation",
- "subType": "base",
- "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.",
+ "type": "api",
+ "subType": "eventing",
+ "extendsBase": true,
+ "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.",
+ "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.",
"children": [
- { "type": "binding", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Optional protocol bindings. Only needed to override the derived method and path." },
- { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." },
- { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." },
- { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." },
- { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." },
- { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }
+ { "type": "operation", "subType": "event", "name": "*", "min": 0, "max": null, "description": "The events this surface publishes." }
+ ]
+ },
+ {
+ "type": "api",
+ "subType": "batch",
+ "extendsBase": true,
+ "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.",
+ "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.",
+ "children": [
+ { "type": "operation", "subType": "export", "name": "*", "min": 0, "max": null, "description": "The datasets the provider publishes." },
+ { "type": "operation", "subType": "import", "name": "*", "min": 0, "max": null, "description": "The datasets the provider accepts." }
]
},
+ {
+ "type": "operation",
+ "subType": "base",
+ "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.",
+ "children": []
+ },
{
"type": "operation",
"subType": "command",
@@ -38,6 +55,12 @@
"description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
"whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.",
"children": [
+ { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." },
+ { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." },
+ { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." },
+ { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." },
{ "type": "attr", "subType": "string", "name": "transitions", "isArray": true, "min": 0, "max": 1, "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." },
{ "type": "attr", "subType": "string", "name": "errors", "isArray": true, "min": 0, "max": 1, "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." }
]
@@ -49,9 +72,52 @@
"description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
"whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.",
"children": [
+ { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." },
+ { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." },
+ { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." },
+ { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." },
{ "type": "attr", "subType": "boolean", "name": "many", "min": 0, "max": 1, "description": "The query returns a list and takes the filter, sort and paging contract. Not implied by the projection, so declared. Absent means one row. Legal on a query only." }
]
},
+ {
+ "type": "operation",
+ "subType": "event",
+ "extendsBase": true,
+ "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.",
+ "children": [
+ { "type": "binding", "subType": "messaging", "name": "*", "min": 0, "max": null, "description": "Optional messaging bindings: how the event travels." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "key", "min": 0, "max": 1, "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised." }
+ ]
+ },
+ {
+ "type": "operation",
+ "subType": "export",
+ "extendsBase": true,
+ "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.",
+ "children": [
+ { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is and how it is written." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file appears: hourly, daily, weekly or monthly." },
+ { "type": "attr", "subType": "string", "name": "availableBy", "min": 0, "max": 1, "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised." }
+ ]
+ },
+ {
+ "type": "operation",
+ "subType": "import",
+ "extendsBase": true,
+ "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.",
+ "children": [
+ { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is delivered and how it is written." },
+ { "type": "attr", "subType": "string", "name": "inputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file is expected: hourly, daily, weekly or monthly." }
+ ]
+ },
{
"type": "binding",
"subType": "base",
@@ -68,6 +134,32 @@
{ "type": "attr", "subType": "string", "name": "method", "min": 0, "max": 1, "allowedValues": ["GET", "POST", "PUT", "PATCH", "DELETE"], "description": "The HTTP method. Absent: GET for a query, POST for a command." },
{ "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "A path template. Its `{name}` placeholders must be exactly the target's primary key fields when the operation is keyed, and there must be none when it is not; two declared bindings of one API may not share the method and path (ERR_BINDING_PATH_MISMATCH)." }
]
+ },
+ {
+ "type": "binding",
+ "subType": "messaging",
+ "extendsBase": true,
+ "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "protocol", "min": 0, "max": 1, "allowedValues": ["kafka", "amqp", "mqtt", "sqs"], "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks." }
+ ]
+ },
+ {
+ "type": "binding",
+ "subType": "file",
+ "extendsBase": true,
+ "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Every export and import whose file conventions two parties must agree on.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." },
+ { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." },
+ { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." },
+ { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." },
+ { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." },
+ { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." },
+ { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." }
+ ]
}
],
"extends": [
diff --git a/server/rust/metaobjects/data/metamodel/systems.json b/server/rust/metaobjects/data/metamodel/systems.json
index cb6b7da4ed..189eaf4c5e 100644
--- a/server/rust/metaobjects/data/metamodel/systems.json
+++ b/server/rust/metaobjects/data/metamodel/systems.json
@@ -64,7 +64,8 @@
"description": "A long-running process that answers requests: a web server, an API, a socket server.",
"whenToUse": "Anything that listens on a port and stays up.",
"children": [
- { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." }
+ { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." },
+ { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } }
]
},
{
@@ -84,7 +85,9 @@
"description": "Work that runs to completion and exits: a scheduled task, a migration, a one-off batch. It may run on a schedule (@schedule) or when something triggers it.",
"whenToUse": "A cron job, a nightly import, a queue drain that is not a long-running service.",
"children": [
- { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." }
+ { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." },
+ { "type": "attr", "subType": "string", "name": "extracts", "min": 0, "max": 1, "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object.", "ref": { "targetType": "object", "targetSubTypes": ["entity", "projection"] } },
+ { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } }
]
},
{
@@ -137,7 +140,8 @@
"description": "Files and blobs addressed by key.",
"whenToUse": "Uploaded images, exports, static assets kept outside the app.",
"children": [
- { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." }
+ { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." },
+ { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`.", "ref": { "targetType": "api", "targetSubTypes": ["batch"] } }
]
},
{
@@ -162,7 +166,8 @@
"whenToUse": "Work handed from one app to another to run later.",
"children": [
{ "type": "attr", "subType": "boolean", "name": "ordered", "min": 0, "max": 1, "description": "Messages with the same key are delivered in the order they were sent. Absent means no order is promised." },
- { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." }
+ { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." },
+ { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } }
]
},
{
@@ -170,7 +175,10 @@
"subType": "stream",
"extendsBase": true,
"description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.",
- "whenToUse": "Events several consumers read independently, or read again."
+ "whenToUse": "Events several consumers read independently, or read again.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } }
+ ]
},
{
"type": "resource",
diff --git a/server/rust/metaobjects/src/rules_check.rs b/server/rust/metaobjects/src/rules_check.rs
index c0c0c30436..a11d7e01a0 100644
--- a/server/rust/metaobjects/src/rules_check.rs
+++ b/server/rust/metaobjects/src/rules_check.rs
@@ -56,6 +56,7 @@ pub const WARN_DERIVED_COMMAND_BYPASSES_DECLARED: &str = "WARN_DERIVED_COMMAND_B
const T_API: &str = "api";
const T_OPERATION: &str = "operation";
+const SUB_OPERATIONAL: &str = "operational";
const SUB_ENTITY: &str = "entity";
const SUB_ENUM: &str = "enum";
const SUB_COMMAND: &str = "command";
@@ -186,7 +187,7 @@ pub(crate) fn operations(tree: &Tree, root: NodeId) -> Vec {
tree.children(root)
.iter()
.copied()
- .filter(|&a| tree.node(a).type_name == T_API)
+ .filter(|&a| is_a(tree, a, T_API, SUB_OPERATIONAL))
.flat_map(|api| {
tree.children(api)
.iter()
diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs
index bfa8773398..94232f87d4 100644
--- a/server/rust/metaobjects/src/validate/rules.rs
+++ b/server/rust/metaobjects/src/validate/rules.rs
@@ -44,6 +44,15 @@
//! B1 ERR_BINDING_PATH_MISMATCH a binding.rest @path's placeholders are not the target's key
//! fields (keyed) or are not empty (unkeyed)
//! B2 ERR_BINDING_PATH_MISMATCH two bindings of one API share a method and a path
+//!
+//! Operations of an api.eventing or api.batch (event, export, import) are not commands or
+//! queries: only O1 applies to them, with three rules of their own:
+//! D1 ERR_BAD_ATTR_VALUE an operation.export @availableBy lacks the form its
+//! @frequency gives
+//! D2 ERR_BAD_ATTR_VALUE a binding.file @fileName holds a placeholder other than
+//! {date} or {timestamp}, or an unclosed brace
+//! D3 ERR_BAD_ATTR_VALUE an operation.event @key is not an effective field of
+//! the object its @outputRef names
//! ```
//!
//! Everything a lifecycle has beyond its transitions is derived, with no vocabulary of
@@ -89,6 +98,9 @@ const SUB_ACTION: &str = "action";
const SUB_COMMAND: &str = "command";
const SUB_QUERY: &str = "query";
const SUB_REST: &str = "rest";
+const SUB_OPERATIONAL: &str = "operational";
+const SUB_FILE: &str = "file";
+const SUB_EVENT: &str = "event";
const SUB_PRIMARY: &str = "primary";
const A_DEFAULT: &str = "default";
@@ -107,6 +119,23 @@ const A_MANY: &str = "many";
const A_METHOD: &str = "method";
const A_PATH: &str = "path";
const A_FIELDS: &str = "fields";
+const A_FREQUENCY: &str = "frequency";
+const A_AVAILABLE_BY: &str = "availableBy";
+const A_FILE_NAME: &str = "fileName";
+const A_KEY: &str = "key";
+
+/// The placeholders a binding.file `@fileName` may hold.
+const FILE_NAME_PLACEHOLDERS: [&str; 2] = ["date", "timestamp"];
+
+/// How an export's `@availableBy` is written for each `@frequency`: `(frequency, example)`.
+const AVAILABLE_BY_EXAMPLES: [(&str, &str); 4] = [
+ ("hourly", ":15"),
+ ("daily", "03:00"),
+ ("weekly", "Mon 06:00"),
+ ("monthly", "1 06:00"),
+];
+
+const WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const METHOD_POST: &str = "POST";
const METHOD_GET: &str = "GET";
@@ -772,7 +801,7 @@ fn check_entity_lifecycles(tree: &Tree, entity: NodeId, sink: &mut Sink<'_>) {
entity,
ERR_TRANSITION_NOT_ON_ENTITY,
format!(
- "object.entity \"{}\" has a lifecycle (transitions on {}) and a source, but no writable one; a transition is a guarded update of a stored row. (An entity with no source at all may carry a lifecycle: it is inert until a source is added.)",
+ "object.entity \"{}\" has a lifecycle (transitions on {}) and a source, but no writable one; a transition is a guarded update of a stored row. (An entity with no relational source may carry a lifecycle: it is inert until a source.rdb is added.)",
enode.name,
quote_list(&fields)
),
@@ -791,6 +820,185 @@ fn declared_paths(tree: &Tree, op: NodeId) -> Vec<(NodeId, &str)> {
.collect()
}
+/// What a reference found: nothing, or the subtype of the object it names.
+fn found_shape(tree: &Tree, target: Option) -> String {
+ match target {
+ None => "names no object".to_string(),
+ Some(t) => format!("is an object.{}", tree.node(t).sub_type),
+ }
+}
+
+/// O1: an operation's `@inputRef` and `@outputRef` shapes. False when one is wrong.
+fn check_shapes(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) -> bool {
+ let tree = ctx.tree;
+ let sub = tree.node(op).sub_type.as_str();
+ let op_label = label(tree, op);
+ if let Some(input_ref) = str_attr(tree, op, A_INPUT_REF) {
+ let input = resolve_object_on(&ctx.env(), op, input_ref);
+ if input.is_none_or(|i| tree.node(i).sub_type != SUB_VALUE) {
+ sink.add(
+ op,
+ ERR_OPERATION_SHAPE,
+ format!(
+ "operation.{sub} \"{op_label}\" @inputRef \"{input_ref}\" {}; an operation's input is an object.value.",
+ found_shape(tree, input)
+ ),
+ );
+ return false;
+ }
+ }
+ if let Some(output_ref) = str_attr(tree, op, A_OUTPUT_REF) {
+ let output = resolve_object_on(&ctx.env(), op, output_ref);
+ let legal = output.is_some_and(|o| {
+ [SUB_ENTITY, SUB_PROJECTION, SUB_VALUE].contains(&tree.node(o).sub_type.as_str())
+ });
+ if !legal {
+ sink.add(
+ op,
+ ERR_OPERATION_SHAPE,
+ format!(
+ "operation.{sub} \"{op_label}\" @outputRef \"{output_ref}\" {}; an operation returns an object.entity, object.projection or object.value.",
+ found_shape(tree, output)
+ ),
+ );
+ return false;
+ }
+ }
+ true
+}
+
+/// `[0-5][0-9]`.
+fn is_minute(s: &str) -> bool {
+ let b = s.as_bytes();
+ b.len() == 2 && (b'0'..=b'5').contains(&b[0]) && b[1].is_ascii_digit()
+}
+
+/// `(?:[01][0-9]|2[0-3])`.
+fn is_hour(s: &str) -> bool {
+ let b = s.as_bytes();
+ b.len() == 2
+ && b[1].is_ascii_digit()
+ && (b[0] == b'0' || b[0] == b'1' || (b[0] == b'2' && b[1] <= b'3'))
+}
+
+/// `HH:MM`.
+fn is_clock(s: &str) -> bool {
+ s.split_once(':')
+ .is_some_and(|(h, m)| is_hour(h) && is_minute(m))
+}
+
+/// `(?:[1-9]|1[0-9]|2[0-8])`.
+fn is_month_day(s: &str) -> bool {
+ s.parse::().is_ok_and(|d| (1..=28).contains(&d))
+ && s.bytes().all(|c| c.is_ascii_digit())
+ && !s.starts_with('0')
+}
+
+/// Whether `value` has the form `frequency` gives (the reference's AVAILABLE_BY_PATTERNS).
+fn available_by_matches(frequency: &str, value: &str) -> bool {
+ match frequency {
+ "hourly" => value.strip_prefix(':').is_some_and(is_minute),
+ "daily" => is_clock(value),
+ "weekly" => value
+ .split_once(' ')
+ .is_some_and(|(d, t)| WEEKDAYS.contains(&d) && is_clock(t)),
+ "monthly" => value
+ .split_once(' ')
+ .is_some_and(|(d, t)| is_month_day(d) && is_clock(t)),
+ _ => true,
+ }
+}
+
+/// What is wrong with a `@fileName`'s placeholders, or `None` when nothing is.
+fn file_name_placeholder_problem(file_name: &str) -> Option {
+ let mut rest = String::new();
+ let mut i = 0;
+ let bytes = file_name.as_bytes();
+ // Scan for `{[^{}]*}` the way the reference's /\{([^{}]*)\}/g does.
+ while i < bytes.len() {
+ if bytes[i] == b'{'
+ && let Some(len) = file_name[i + 1..].find(['{', '}'])
+ && bytes[i + 1 + len] == b'}'
+ {
+ let name = &file_name[i + 1..i + 1 + len];
+ if !FILE_NAME_PLACEHOLDERS.contains(&name) {
+ return Some(format!("holds the placeholder {{{name}}}"));
+ }
+ i += len + 2;
+ continue;
+ }
+ let ch = file_name[i..].chars().next().unwrap_or(' ');
+ rest.push(ch);
+ i += ch.len_utf8();
+ }
+ rest.contains(['{', '}'])
+ .then(|| "has an unmatched brace".to_string())
+}
+
+/// The checks for one operation of an api.eventing or api.batch: its shapes (O1), the form of
+/// an export's `@availableBy` (D1), the placeholders of each binding.file `@fileName` (D2) and
+/// an event's `@key` (D3).
+fn check_delivery_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) {
+ if !check_shapes(ctx, op, sink) {
+ return;
+ }
+ let tree = ctx.tree;
+ let sub = tree.node(op).sub_type.as_str();
+ let op_label = label(tree, op);
+ if sub == SUB_EVENT
+ && let Some(key) = str_attr(tree, op, A_KEY)
+ && let Some(output) =
+ str_attr(tree, op, A_OUTPUT_REF).and_then(|r| resolve_object_on(&ctx.env(), op, r))
+ && !tree.children(output).iter().any(|&c| {
+ let n = tree.node(c);
+ n.type_name == TYPE_FIELD && n.name == key
+ })
+ {
+ sink.add(
+ op,
+ ERR_BAD_ATTR_VALUE,
+ format!(
+ "operation.event \"{op_label}\" @key \"{key}\" is not a field of \"{}\"; @key names the payload field whose events stay in order.",
+ tree.node(output).name
+ ),
+ );
+ }
+ if let (Some(by), Some(freq)) = (
+ str_attr(tree, op, A_AVAILABLE_BY),
+ str_attr(tree, op, A_FREQUENCY),
+ ) && let Some((_, example)) = AVAILABLE_BY_EXAMPLES.iter().find(|(f, _)| *f == freq)
+ && !available_by_matches(freq, by)
+ {
+ sink.add(
+ op,
+ ERR_BAD_ATTR_VALUE,
+ format!(
+ "operation.{sub} \"{op_label}\" @availableBy \"{by}\" is not a {freq} time; a {freq} file's @availableBy is written like \"{example}\" (UTC)."
+ ),
+ );
+ }
+ // ADR-0039: own — a binding is checked on the operation that declares it.
+ for &b in tree.own_children(op) {
+ if !is_a(tree, b, T_BINDING, SUB_FILE) {
+ continue;
+ }
+ let Some(file_name) = str_attr(tree, b, A_FILE_NAME) else {
+ continue;
+ };
+ if let Some(problem) = file_name_placeholder_problem(file_name) {
+ sink.add(
+ b,
+ ERR_BAD_ATTR_VALUE,
+ format!(
+ "binding.file on \"{}\" @fileName \"{file_name}\" {problem}; the placeholders are {{{}}}.",
+ label(tree, b),
+ FILE_NAME_PLACEHOLDERS.join("} and {")
+ ),
+ );
+ }
+ }
+}
+
/// O0 to O5, P1, P2 and B1 for one operation.
fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) {
let tree = ctx.tree;
@@ -867,40 +1075,8 @@ fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) {
}
// O1 — shapes.
- let found = |target: Option| match target {
- None => "names no object".to_string(),
- Some(t) => format!("is an object.{}", tree.node(t).sub_type),
- };
- if let Some(input_ref) = str_attr(tree, op, A_INPUT_REF) {
- let input = resolve_object_on(&ctx.env(), op, input_ref);
- if input.is_none_or(|i| tree.node(i).sub_type != SUB_VALUE) {
- sink.add(
- op,
- ERR_OPERATION_SHAPE,
- format!(
- "operation.{sub} \"{op_label}\" @inputRef \"{input_ref}\" {}; an operation's input is an object.value.",
- found(input)
- ),
- );
- return;
- }
- }
- if let Some(output_ref) = str_attr(tree, op, A_OUTPUT_REF) {
- let output = resolve_object_on(&ctx.env(), op, output_ref);
- let legal = output.is_some_and(|o| {
- [SUB_ENTITY, SUB_PROJECTION, SUB_VALUE].contains(&tree.node(o).sub_type.as_str())
- });
- if !legal {
- sink.add(
- op,
- ERR_OPERATION_SHAPE,
- format!(
- "operation.{sub} \"{op_label}\" @outputRef \"{output_ref}\" {}; an operation returns an object.entity, object.projection or object.value.",
- found(output)
- ),
- );
- return;
- }
+ if !check_shapes(ctx, op, sink) {
+ return;
}
// O2, O3 — the target.
@@ -914,7 +1090,7 @@ fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) {
ERR_OPERATION_TARGET_UNRESOLVED,
format!(
"operation.{sub} \"{op_label}\" @objectRef \"{object_ref}\" {}; an operation acts on an object.entity.",
- found(declared)
+ found_shape(tree, declared)
),
);
return;
@@ -1179,7 +1355,7 @@ fn check_permission_names(ctx: &Ctx<'_>, top_level: &[NodeId], sink: &mut Sink<'
}
}
for &api in top_level {
- if tree.node(api).type_name != T_API {
+ if !is_a(tree, api, T_API, SUB_OPERATIONAL) {
continue;
}
for &op in tree.children(api).iter() {
@@ -1237,6 +1413,14 @@ pub fn validate_rules(ctx: &Ctx<'_>, f: &mut Findings) {
if tree.node(api).type_name != T_API {
continue;
}
+ if tree.node(api).sub_type != SUB_OPERATIONAL {
+ for &op in tree.children(api).iter() {
+ if tree.node(op).type_name == T_OPERATION {
+ check_delivery_operation(ctx, op, &mut sink);
+ }
+ }
+ continue;
+ }
let ops: Vec = tree
.children(api)
.iter()
diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json
index 363ec1e16b..b8fbb2cd0a 100644
--- a/server/rust/metaobjects/tests/conformance-expected-failures.json
+++ b/server/rust/metaobjects/tests/conformance-expected-failures.json
@@ -1,6 +1,6 @@
{
"language": "rust",
"notes": "The Rust port passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.",
- "minPassing": 614,
+ "minPassing": 622,
"fixtures": []
}
diff --git a/server/typescript/packages/cli/test/unit/rules-inert.test.ts b/server/typescript/packages/cli/test/unit/rules-inert.test.ts
index d727fc9a7a..de2ec82e48 100644
--- a/server/typescript/packages/cli/test/unit/rules-inert.test.ts
+++ b/server/typescript/packages/cli/test/unit/rules-inert.test.ts
@@ -42,7 +42,7 @@ const SCRATCH = mkdtempSync(join(tmpdir(), "rules-inert-"));
const MODEL_FILE = join(SCRATCH, "model", "meta.purchasing.json");
const PROJECT = join(SCRATCH, "project");
-async function load(variant: "with" | "without"): Promise {
+async function load(variant: "with" | "without" | "with-delivery"): Promise {
mkdirSync(join(SCRATCH, "model"), { recursive: true });
copyFileSync(join(MODELS, variant, "meta.purchasing.json"), MODEL_FILE);
const file = MODEL_FILE;
@@ -129,10 +129,12 @@ const SERVICE_LAYER: Record = {
let withRules: MetaRoot;
let withoutRules: MetaRoot;
+let withDelivery: MetaRoot;
beforeAll(async () => {
withRules = await load("with");
withoutRules = await load("without");
+ withDelivery = await load("with-delivery");
});
afterAll(() => rmSync(SCRATCH, { recursive: true, force: true }));
@@ -278,3 +280,32 @@ describe("ADR-0066 the business-rules vocabulary is inert in every generator and
.toEqual(buildExpectedSchema(withoutRules, { dialect: "postgres", views: views(withoutRules) }));
});
});
+
+// 1.4.0 — `api.eventing` and `api.batch`, with `operation.event` / `.export` / `.import` and
+// `binding.messaging` / `binding.file`, are registered and nothing is generated from them yet.
+// The `with-delivery` model is `with` plus one API of each kind, whose operations reference the
+// same value and projection the operational API does. Every generator but the model explorer
+// (which lists every node) must write exactly what it writes for `with`: the service generators
+// included, which read only `api.operational` and select the `binding.rest` by subtype.
+describe("api.eventing and api.batch are inert in every generator and in migrate", () => {
+ test("the with-delivery model really carries an eventing and a batch API", () => {
+ const kinds = withDelivery.children().filter((c) => c.type === TYPE_API).map((c) => c.subType).sort();
+ expect(kinds).toEqual(["batch", "eventing", "operational"]);
+ });
+
+ const catalog = composeCatalog();
+ for (const [name, entry] of Object.entries(catalog)) {
+ if (name === DOCS_SITE) continue;
+ test(`generator "${name}" emits the same files, byte for byte`, async () => {
+ const expected = await emit(withRules, [entry.factory()]);
+ const actual = await emit(withDelivery, [entry.factory()]);
+ expect(actual).toEqual(expected);
+ });
+ }
+
+ test("migrate's expected schema is the same", () => {
+ const views = (m: MetaRoot) => buildProjectionViews(m, { dialect: "postgres" });
+ expect(buildExpectedSchema(withDelivery, { dialect: "postgres", views: views(withDelivery) }))
+ .toEqual(buildExpectedSchema(withRules, { dialect: "postgres", views: views(withRules) }));
+ });
+});
diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts
index 4d9e09b455..10b47d60f9 100644
--- a/server/typescript/packages/codegen-ts/src/service-walk.ts
+++ b/server/typescript/packages/codegen-ts/src/service-walk.ts
@@ -28,6 +28,7 @@ import {
OPERATION_ATTR_TRANSITIONS,
OPERATION_SUBTYPE_COMMAND,
TRANSITION_ATTR_CONDITION,
+ BINDING_SUBTYPE_REST,
TYPE_BINDING,
TYPE_FIELD,
claimedTransitions,
@@ -348,7 +349,9 @@ function operationOf(op: MetaData, target: ServiceEntity | undefined, settings:
const lifecycles = target === undefined ? [] : lifecyclesOf(target.obj);
const names = new Set(kind === "command" ? stringsOf(op, OPERATION_ATTR_TRANSITIONS) : []);
const transitions = lifecycles.flatMap((l) => l.transitions.filter((t) => names.has(t.name)).map((t) => transitionOf(t, l.field.name)));
- const binding = op.children().find((c) => c.type === TYPE_BINDING);
+ // The service is the HTTP surface, so the binding it reads is the rest one, chosen by subtype:
+ // another binding kind carries no method or path.
+ const binding = op.children().find((c) => c.type === TYPE_BINDING && c.subType === BINDING_SUBTYPE_REST);
const declaredMethod = binding?.attr(BINDING_ATTR_METHOD);
const declaredPath = binding?.attr(BINDING_ATTR_PATH);
const method = (typeof declaredMethod === "string" ? declaredMethod : kind === "query" ? "GET" : "POST") as ServiceOperation["method"];
diff --git a/server/typescript/packages/docs-site/app/assets/explorer-app.js b/server/typescript/packages/docs-site/app/assets/explorer-app.js
index a2681492a9..ec81740b86 100644
--- a/server/typescript/packages/docs-site/app/assets/explorer-app.js
+++ b/server/typescript/packages/docs-site/app/assets/explorer-app.js
@@ -265,5 +265,5 @@
`);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(`
`)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",`
`,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(`${tag}>`)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(`
-`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_SUBTYPE_RDB="rdb";var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE&&c.subType===SOURCE_SUBTYPE_RDB)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(`
`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
`}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`
${cols.map((o)=>`
${this.link(from,o.id)}
`).join("")}
`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`
`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`
`,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
None.
');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
None.
')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
Not scanned.
');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
No prompt text was read.
':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
None.
':`
${items.map((i)=>`
${i}
`).join("")}
`}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found
No such page
${escapeHtml2(r.path)} is not a page of this model.
`,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="
No model yet
The explorer is waiting for the running application's docs view.
";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="
explorer-model.js did not load. Run meta gen to write it beside this page.
";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})();
diff --git a/server/typescript/packages/metadata/src/core/api/api-constants.ts b/server/typescript/packages/metadata/src/core/api/api-constants.ts
index bc9eef468e..a90b56be6c 100644
--- a/server/typescript/packages/metadata/src/core/api/api-constants.ts
+++ b/server/typescript/packages/metadata/src/core/api/api-constants.ts
@@ -15,19 +15,39 @@ export { TYPE_API, TYPE_BINDING, TYPE_OPERATION };
/** A request/response surface whose children are operations. The axis is the
* interaction model, never the protocol (ADR-0030). */
export const API_SUBTYPE_OPERATIONAL = "operational";
-export const API_SUBTYPES = [API_SUBTYPE_OPERATIONAL] as const;
+/** Events the provider publishes; children are `operation.event`. */
+export const API_SUBTYPE_EVENTING = "eventing";
+/** Datasets delivered as files on a schedule; children are `operation.export` / `.import`. */
+export const API_SUBTYPE_BATCH = "batch";
+export const API_SUBTYPES = [API_SUBTYPE_OPERATIONAL, API_SUBTYPE_EVENTING, API_SUBTYPE_BATCH] as const;
export type ApiSubType = (typeof API_SUBTYPES)[number];
/** Changes state; takes an `object.value`. */
export const OPERATION_SUBTYPE_COMMAND = "command";
/** Reads; returns a projection, entity or value. */
export const OPERATION_SUBTYPE_QUERY = "query";
-export const OPERATION_SUBTYPES = [OPERATION_SUBTYPE_COMMAND, OPERATION_SUBTYPE_QUERY] as const;
+/** Something that happened; the payload is its `@outputRef`. */
+export const OPERATION_SUBTYPE_EVENT = "event";
+/** A file the provider publishes on a schedule; rows are its `@outputRef`. */
+export const OPERATION_SUBTYPE_EXPORT = "export";
+/** A file the provider accepts on a schedule; rows are its `@inputRef`. */
+export const OPERATION_SUBTYPE_IMPORT = "import";
+export const OPERATION_SUBTYPES = [
+ OPERATION_SUBTYPE_COMMAND,
+ OPERATION_SUBTYPE_QUERY,
+ OPERATION_SUBTYPE_EVENT,
+ OPERATION_SUBTYPE_EXPORT,
+ OPERATION_SUBTYPE_IMPORT,
+] as const;
export type OperationSubType = (typeof OPERATION_SUBTYPES)[number];
/** The HTTP binding of an operation (overrides the derived method and path). */
export const BINDING_SUBTYPE_REST = "rest";
-export const BINDING_SUBTYPES = [BINDING_SUBTYPE_REST] as const;
+/** How an event travels (optionally pinning the wire protocol). */
+export const BINDING_SUBTYPE_MESSAGING = "messaging";
+/** How an export's or import's file is delivered. */
+export const BINDING_SUBTYPE_FILE = "file";
+export const BINDING_SUBTYPES = [BINDING_SUBTYPE_REST, BINDING_SUBTYPE_MESSAGING, BINDING_SUBTYPE_FILE] as const;
export type BindingSubType = (typeof BINDING_SUBTYPES)[number];
// ---------------------------------------------------------------------------
@@ -60,6 +80,55 @@ export const BINDING_ATTR_PATH = "path";
export const HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const;
export type HttpMethod = (typeof HTTP_METHODS)[number];
+// ---------------------------------------------------------------------------
+// Attrs on operation.event / .export / .import
+// ---------------------------------------------------------------------------
+
+/** `operation.event @key` — the payload field whose events stay in order. */
+export const OPERATION_ATTR_KEY = "key";
+/** `operation.export|import @frequency`. */
+export const OPERATION_ATTR_FREQUENCY = "frequency";
+/** `operation.export @availableBy` — the UTC time each file is in place by. */
+export const OPERATION_ATTR_AVAILABLE_BY = "availableBy";
+export const FREQUENCY_HOURLY = "hourly";
+export const FREQUENCY_DAILY = "daily";
+export const FREQUENCY_WEEKLY = "weekly";
+export const FREQUENCY_MONTHLY = "monthly";
+export const FREQUENCIES = [FREQUENCY_HOURLY, FREQUENCY_DAILY, FREQUENCY_WEEKLY, FREQUENCY_MONTHLY] as const;
+export type Frequency = (typeof FREQUENCIES)[number];
+/** The form of `@availableBy` for each `@frequency`: hourly `:MM`, daily `HH:MM`, weekly
+ * `Ddd HH:MM`, monthly `D HH:MM` with the day 1 to 28 (every month has it). */
+export const AVAILABLE_BY_PATTERNS: Readonly> = {
+ [FREQUENCY_HOURLY]: /^:[0-5][0-9]$/,
+ [FREQUENCY_DAILY]: /^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/,
+ [FREQUENCY_WEEKLY]: /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/,
+ [FREQUENCY_MONTHLY]: /^(?:[1-9]|1[0-9]|2[0-8]) (?:[01][0-9]|2[0-3]):[0-5][0-9]$/,
+};
+/** An example of each form, for messages. */
+export const AVAILABLE_BY_EXAMPLES: Readonly> = {
+ [FREQUENCY_HOURLY]: ":15",
+ [FREQUENCY_DAILY]: "03:00",
+ [FREQUENCY_WEEKLY]: "Mon 06:00",
+ [FREQUENCY_MONTHLY]: "1 06:00",
+};
+
+// ---------------------------------------------------------------------------
+// Attrs on binding.messaging / binding.file
+// ---------------------------------------------------------------------------
+
+export const BINDING_ATTR_PROTOCOL = "protocol";
+export const BINDING_ATTR_TRANSPORT = "transport";
+export const BINDING_ATTR_FILE_NAME = "fileName";
+export const BINDING_ATTR_FORMAT = "format";
+export const BINDING_ATTR_COMPRESSION = "compression";
+export const BINDING_ATTR_COMPLETION = "completion";
+export const BINDING_ATTR_ENCRYPTION = "encryption";
+/** The placeholders a `binding.file @fileName` may hold: the UTC start of the run, as
+ * `YYYY-MM-DD` and `YYYYMMDDTHHMMSSZ`. */
+export const FILE_NAME_PLACEHOLDERS = ["date", "timestamp"] as const;
+/** The suffix of the marker object `completion: marker` puts beside a finished file. */
+export const COMPLETION_MARKER_SUFFIX = ".done";
+
/** Names a declared operation or a transition may not take: they are the derived CRUD
* verbs of the same service (ERR_TRANSITION_NAME_COLLISION). */
export const RESERVED_OPERATION_NAMES = ["create", "get", "list", "update", "delete"] as const;
diff --git a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts
index b1166a7f33..612a14514c 100644
--- a/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts
+++ b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts
@@ -25,26 +25,86 @@ export const API_DEFINITION: ProviderDefinition = {
"children": [
{
"type": "operation",
- "subType": "*",
+ "subType": "command",
+ "name": "*",
+ "min": 0,
+ "max": null,
+ "description": "The commands this surface exposes."
+ },
+ {
+ "type": "operation",
+ "subType": "query",
+ "name": "*",
+ "min": 0,
+ "max": null,
+ "description": "The queries this surface exposes."
+ }
+ ]
+ },
+ {
+ "type": "api",
+ "subType": "eventing",
+ "extendsBase": true,
+ "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.",
+ "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.",
+ "children": [
+ {
+ "type": "operation",
+ "subType": "event",
+ "name": "*",
+ "min": 0,
+ "max": null,
+ "description": "The events this surface publishes."
+ }
+ ]
+ },
+ {
+ "type": "api",
+ "subType": "batch",
+ "extendsBase": true,
+ "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.",
+ "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.",
+ "children": [
+ {
+ "type": "operation",
+ "subType": "export",
+ "name": "*",
+ "min": 0,
+ "max": null,
+ "description": "The datasets the provider publishes."
+ },
+ {
+ "type": "operation",
+ "subType": "import",
"name": "*",
"min": 0,
"max": null,
- "description": "The operations this surface exposes."
+ "description": "The datasets the provider accepts."
}
]
},
{
"type": "operation",
"subType": "base",
- "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.",
+ "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.",
+ "children": []
+ },
+ {
+ "type": "operation",
+ "subType": "command",
+ "extendsBase": true,
+ "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.",
"children": [
{
"type": "binding",
- "subType": "*",
+ "subType": "rest",
"name": "*",
"min": 0,
"max": null,
- "description": "Optional protocol bindings. Only needed to override the derived method and path."
+ "description": "Optional HTTP bindings. Only needed to override the derived method and path."
},
{
"type": "attr",
@@ -85,16 +145,7 @@ export const API_DEFINITION: ProviderDefinition = {
"min": 0,
"max": 1,
"description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT."
- }
- ]
- },
- {
- "type": "operation",
- "subType": "command",
- "extendsBase": true,
- "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
- "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.",
- "children": [
+ },
{
"type": "attr",
"subType": "string",
@@ -122,6 +173,54 @@ export const API_DEFINITION: ProviderDefinition = {
"description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
"whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.",
"children": [
+ {
+ "type": "binding",
+ "subType": "rest",
+ "name": "*",
+ "min": 0,
+ "max": null,
+ "description": "Optional HTTP bindings. Only needed to override the derived method and path."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "inputRef",
+ "min": 0,
+ "max": 1,
+ "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "outputRef",
+ "min": 0,
+ "max": 1,
+ "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "objectRef",
+ "min": 0,
+ "max": 1,
+ "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "permission",
+ "min": 0,
+ "max": 1,
+ "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one."
+ },
+ {
+ "type": "attr",
+ "subType": "boolean",
+ "name": "public",
+ "min": 0,
+ "max": 1,
+ "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT."
+ },
{
"type": "attr",
"subType": "boolean",
@@ -132,6 +231,125 @@ export const API_DEFINITION: ProviderDefinition = {
}
]
},
+ {
+ "type": "operation",
+ "subType": "event",
+ "extendsBase": true,
+ "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.",
+ "children": [
+ {
+ "type": "binding",
+ "subType": "messaging",
+ "name": "*",
+ "min": 0,
+ "max": null,
+ "description": "Optional messaging bindings: how the event travels."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "outputRef",
+ "min": 1,
+ "max": 1,
+ "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "key",
+ "min": 0,
+ "max": 1,
+ "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised."
+ }
+ ]
+ },
+ {
+ "type": "operation",
+ "subType": "export",
+ "extendsBase": true,
+ "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.",
+ "children": [
+ {
+ "type": "binding",
+ "subType": "file",
+ "name": "*",
+ "min": 0,
+ "max": null,
+ "description": "Optional file bindings: where the file is and how it is written."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "outputRef",
+ "min": 1,
+ "max": 1,
+ "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "frequency",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "hourly",
+ "daily",
+ "weekly",
+ "monthly"
+ ],
+ "description": "How often a new file appears: hourly, daily, weekly or monthly."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "availableBy",
+ "min": 0,
+ "max": 1,
+ "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised."
+ }
+ ]
+ },
+ {
+ "type": "operation",
+ "subType": "import",
+ "extendsBase": true,
+ "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.",
+ "children": [
+ {
+ "type": "binding",
+ "subType": "file",
+ "name": "*",
+ "min": 0,
+ "max": null,
+ "description": "Optional file bindings: where the file is delivered and how it is written."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "inputRef",
+ "min": 1,
+ "max": 1,
+ "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "frequency",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "hourly",
+ "daily",
+ "weekly",
+ "monthly"
+ ],
+ "description": "How often a new file is expected: hourly, daily, weekly or monthly."
+ }
+ ]
+ },
{
"type": "binding",
"subType": "base",
@@ -169,6 +387,119 @@ export const API_DEFINITION: ProviderDefinition = {
"description": "A path template. Its `{name}` placeholders must be exactly the target's primary key fields when the operation is keyed, and there must be none when it is not; two declared bindings of one API may not share the method and path (ERR_BINDING_PATH_MISMATCH)."
}
]
+ },
+ {
+ "type": "binding",
+ "subType": "messaging",
+ "extendsBase": true,
+ "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "protocol",
+ "min": 0,
+ "max": 1,
+ "allowedValues": [
+ "kafka",
+ "amqp",
+ "mqtt",
+ "sqs"
+ ],
+ "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks."
+ }
+ ]
+ },
+ {
+ "type": "binding",
+ "subType": "file",
+ "extendsBase": true,
+ "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Every export and import whose file conventions two parties must agree on.",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "transport",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "sftp",
+ "objectStore"
+ ],
+ "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "path",
+ "min": 0,
+ "max": 1,
+ "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "fileName",
+ "min": 1,
+ "max": 1,
+ "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "format",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "csv",
+ "jsonLines",
+ "parquet"
+ ],
+ "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "compression",
+ "min": 0,
+ "max": 1,
+ "allowedValues": [
+ "none",
+ "gzip"
+ ],
+ "default": "none",
+ "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "completion",
+ "min": 0,
+ "max": 1,
+ "allowedValues": [
+ "rename",
+ "marker",
+ "none"
+ ],
+ "default": "none",
+ "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "encryption",
+ "min": 0,
+ "max": 1,
+ "allowedValues": [
+ "none",
+ "pgp"
+ ],
+ "default": "none",
+ "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key."
+ }
+ ]
}
],
"extends": [
diff --git a/server/typescript/packages/metadata/src/core/systems/systems-constants.ts b/server/typescript/packages/metadata/src/core/systems/systems-constants.ts
index 97243bd83d..578512c2b9 100644
--- a/server/typescript/packages/metadata/src/core/systems/systems-constants.ts
+++ b/server/typescript/packages/metadata/src/core/systems/systems-constants.ts
@@ -97,12 +97,16 @@ export type GrantSubType = (typeof GRANT_SUBTYPES)[number];
export const SYSTEM_ATTR_OWNER = "owner";
/** `app @runsAs` — a `role.service`, by name. */
export const APP_ATTR_RUNS_AS = "runsAs";
+/** `app @provides` — the APIs the app provides (hosts), by name. */
+export const APP_ATTR_PROVIDES = "provides";
/** `app.service @public`. */
export const APP_ATTR_PUBLIC = "public";
/** `app.client @shell`. */
export const APP_ATTR_SHELL = "shell";
/** `app.job @schedule` — a five-field cron expression in UTC. */
export const APP_ATTR_SCHEDULE = "schedule";
+/** `app.job @extracts` — the entity or projection the job reads its rows from, by name. */
+export const APP_ATTR_EXTRACTS = "extracts";
/** `build.image @repository`. */
export const BUILD_ATTR_REPOSITORY = "repository";
/** `resource @residency` — `free` (default) or `confined`. */
@@ -121,6 +125,9 @@ export const RESOURCE_ATTR_PUBLIC_READ = "publicRead";
export const RESOURCE_ATTR_ORDERED = "ordered";
/** `resource.queue @deadLetter`. */
export const RESOURCE_ATTR_DEAD_LETTER = "deadLetter";
+/** `resource.stream|queue|objectStore @carries` — the APIs that travel on the resource, by name
+ * (an eventing API on a stream or queue, a batch API on an object store). */
+export const RESOURCE_ATTR_CARRIES = "carries";
/** `role @memberOf` — `role.group` nodes, by name. */
export const ROLE_ATTR_MEMBER_OF = "memberOf";
/** `role @credential` — the name of an adopted key, never a value. */
diff --git a/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts b/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts
index bab4c24f86..eecbd0ecc0 100644
--- a/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts
+++ b/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts
@@ -146,6 +146,18 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = {
"min": 0,
"max": 1,
"description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "provides",
+ "isArray": true,
+ "min": 0,
+ "max": 1,
+ "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.",
+ "ref": {
+ "targetType": "api"
+ }
}
]
},
@@ -180,6 +192,33 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = {
"min": 0,
"max": 1,
"description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "extracts",
+ "min": 0,
+ "max": 1,
+ "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object.",
+ "ref": {
+ "targetType": "object",
+ "targetSubTypes": [
+ "entity",
+ "projection"
+ ]
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "provides",
+ "isArray": true,
+ "min": 0,
+ "max": 1,
+ "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.",
+ "ref": {
+ "targetType": "api"
+ }
}
]
},
@@ -274,6 +313,21 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = {
"min": 0,
"max": 1,
"description": "Anyone may read the objects without a credential. Absent means every read needs a grant."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "carries",
+ "isArray": true,
+ "min": 0,
+ "max": 1,
+ "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`.",
+ "ref": {
+ "targetType": "api",
+ "targetSubTypes": [
+ "batch"
+ ]
+ }
}
]
},
@@ -313,6 +367,21 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = {
"min": 0,
"max": 1,
"description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "carries",
+ "isArray": true,
+ "min": 0,
+ "max": 1,
+ "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.",
+ "ref": {
+ "targetType": "api",
+ "targetSubTypes": [
+ "eventing"
+ ]
+ }
}
]
},
@@ -321,7 +390,24 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = {
"subType": "stream",
"extendsBase": true,
"description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.",
- "whenToUse": "Events several consumers read independently, or read again."
+ "whenToUse": "Events several consumers read independently, or read again.",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "carries",
+ "isArray": true,
+ "min": 0,
+ "max": 1,
+ "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.",
+ "ref": {
+ "targetType": "api",
+ "targetSubTypes": [
+ "eventing"
+ ]
+ }
+ }
+ ]
},
{
"type": "resource",
diff --git a/server/typescript/packages/metadata/src/core/transition/commands.ts b/server/typescript/packages/metadata/src/core/transition/commands.ts
index f1583cfa8a..5612dacf3b 100644
--- a/server/typescript/packages/metadata/src/core/transition/commands.ts
+++ b/server/typescript/packages/metadata/src/core/transition/commands.ts
@@ -13,6 +13,7 @@ import { TYPE_API, TYPE_OBJECT, TYPE_OPERATION } from "../../shared/base-types.j
import { OBJECT_SUBTYPE_ENTITY } from "../object/object-constants.js";
import { effectivePackageOf, topLevelNodeOf } from "../../naming-refs.js";
import {
+ API_SUBTYPE_OPERATIONAL,
OPERATION_ATTR_PERMISSION,
OPERATION_ATTR_PUBLIC,
OPERATION_ATTR_TRANSITIONS,
@@ -26,10 +27,13 @@ export function modelEntities(root: MetaData): MetaData[] {
return root.children().filter((c) => c.type === TYPE_OBJECT && c.subType === OBJECT_SUBTYPE_ENTITY);
}
-/** Every declared operation, across every `api.*` of the root, in model order. */
+/** Every declared command and query, across every `api.operational` of the root, in model order.
+ * An `api.eventing` or `api.batch` is not a request/response surface: its operations have no
+ * target, claim no transition, ask no policy and are served by no route, so nothing that reads
+ * this list sees them. */
export function modelOperations(root: MetaData): MetaData[] {
return root.children()
- .filter((c) => c.type === TYPE_API)
+ .filter((c) => c.type === TYPE_API && c.subType === API_SUBTYPE_OPERATIONAL)
.flatMap((api) => api.children().filter((c) => c.type === TYPE_OPERATION));
}
diff --git a/server/typescript/packages/metadata/src/loader/rules-validation.ts b/server/typescript/packages/metadata/src/loader/rules-validation.ts
index c14342ccd5..98cfb93343 100644
--- a/server/typescript/packages/metadata/src/loader/rules-validation.ts
+++ b/server/typescript/packages/metadata/src/loader/rules-validation.ts
@@ -15,8 +15,8 @@
// Rules:
// L1 ERR_TRANSITION_NOT_ON_ENTITY a transition under an enum field not declared on an object.entity
// L2 ERR_TRANSITION_NOT_ON_ENTITY a concrete entity with a lifecycle and a source, none of them writable
-// (on the entity). An entity with no source at all is inert: its
-// lifecycle loads and derives nothing (lifecycleIsLive).
+// (on the entity). An entity with no relational source (none, or
+// only source.document / source.search) is inert: its lifecycle loads and derives nothing (lifecycleIsLive).
// L3 ERR_LIFECYCLE_NO_INITIAL an enum field declaring transitions has no @default
// L4 ERR_TRANSITION_UNKNOWN_STATE a @from or @to value is not one of the enum's @values
// L5 ERR_TRANSITION_NAME_COLLISION a transition named create/get/list/update/delete, in any case
@@ -53,6 +53,15 @@
// (a keyed operation) or are not empty (an unkeyed one)
// B2 ERR_BINDING_PATH_MISMATCH two binding.rest of one API declaring a @path have the same
// effective method and the same path once placeholder names are ignored
+//
+// Operations of an api.eventing or api.batch (event, export, import) are not commands or queries:
+// only O1 applies to them, with three rules of their own:
+// D1 ERR_BAD_ATTR_VALUE an operation.export @availableBy does not have the form its
+// @frequency gives (AVAILABLE_BY_PATTERNS)
+// D2 ERR_BAD_ATTR_VALUE a binding.file @fileName holds a placeholder other than {date} or
+// {timestamp}, or an unclosed brace
+// D3 ERR_BAD_ATTR_VALUE an operation.event @key is not an effective field of the
+// object its @outputRef names
import type { MetaData } from "../shared/meta-data.js";
import type { MetaObject } from "../core/object/meta-object.js";
@@ -69,13 +78,24 @@ import {
import { FIELD_ATTR_DEFAULT, FIELD_ATTR_VALUES, FIELD_SUBTYPE_ENUM } from "../core/field/field-constants.js";
import { OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE } from "../core/object/object-constants.js";
import {
+ API_SUBTYPE_OPERATIONAL,
+ AVAILABLE_BY_EXAMPLES,
+ AVAILABLE_BY_PATTERNS,
+ BINDING_ATTR_FILE_NAME,
BINDING_ATTR_METHOD,
BINDING_ATTR_PATH,
+ BINDING_SUBTYPE_FILE,
BINDING_SUBTYPE_REST,
+ FILE_NAME_PLACEHOLDERS,
+ FREQUENCIES,
+ type Frequency,
+ OPERATION_ATTR_AVAILABLE_BY,
+ OPERATION_ATTR_FREQUENCY,
BUSINESS_ERROR_CODE_PATTERN,
PERMISSION_NAME_PATTERN,
OPERATION_ATTR_ERRORS,
OPERATION_ATTR_INPUT_REF,
+ OPERATION_ATTR_KEY,
OPERATION_ATTR_MANY,
OPERATION_ATTR_OBJECT_REF,
OPERATION_ATTR_OUTPUT_REF,
@@ -83,6 +103,7 @@ import {
OPERATION_ATTR_PUBLIC,
OPERATION_ATTR_TRANSITIONS,
OPERATION_SUBTYPE_COMMAND,
+ OPERATION_SUBTYPE_EVENT,
RESERVED_ERROR_CODES,
RESERVED_OPERATION_NAMES,
} from "../core/api/api-constants.js";
@@ -280,27 +301,7 @@ function checkOperation(op: MetaData, sink: Sink): void {
sink.add(op, "ERR_BAD_ATTR_VALUE", `operation.${op.subType} "${label(op)}" @errors: ${why}.`);
}
- // O1 — shapes.
- const inputRef = op.attr(OPERATION_ATTR_INPUT_REF);
- if (typeof inputRef === "string") {
- const input = resolveObjectOn(op, inputRef);
- if (input === undefined || input.subType !== OBJECT_SUBTYPE_VALUE) {
- sink.add(op, "ERR_OPERATION_SHAPE",
- `operation.${op.subType} "${label(op)}" @inputRef "${inputRef}" ${input === undefined ? "names no object" : `is an object.${input.subType}`}; an operation's input is an object.value.`);
- return;
- }
- }
- const outputRef = op.attr(OPERATION_ATTR_OUTPUT_REF);
- if (typeof outputRef === "string") {
- const output = resolveObjectOn(op, outputRef);
- const legal = output !== undefined &&
- [OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE].includes(output.subType);
- if (!legal) {
- sink.add(op, "ERR_OPERATION_SHAPE",
- `operation.${op.subType} "${label(op)}" @outputRef "${outputRef}" ${output === undefined ? "names no object" : `is an object.${output.subType}`}; an operation returns an object.entity, object.projection or object.value.`);
- return;
- }
- }
+ if (!checkShapes(op, sink)) return;
// O2, O3 — the target.
const derived = deriveOperationTarget(op)?.entity;
@@ -357,6 +358,75 @@ function checkOperation(op: MetaData, sink: Sink): void {
}
}
+/** The checks for one operation of an api.eventing or api.batch: its shapes (O1), the
+ * form of an export's @availableBy (D1), the placeholders of each binding.file @fileName (D2)
+ * and an event's @key (D3). */
+function checkDeliveryOperation(op: MetaData, sink: Sink): void {
+ if (!checkShapes(op, sink)) return;
+ const key = op.attr(OPERATION_ATTR_KEY);
+ const outputRef = op.attr(OPERATION_ATTR_OUTPUT_REF);
+ if (op.subType === OPERATION_SUBTYPE_EVENT && typeof key === "string" && typeof outputRef === "string") {
+ const output = resolveObjectOn(op, outputRef);
+ if (output !== undefined && !output.children().some((c) => c.type === TYPE_FIELD && c.name === key)) {
+ sink.add(op, "ERR_BAD_ATTR_VALUE",
+ `operation.event "${label(op)}" @key "${key}" is not a field of "${output.name}"; @key names the payload field whose events stay in order.`);
+ }
+ }
+ const frequency = op.attr(OPERATION_ATTR_FREQUENCY);
+ const availableBy = op.attr(OPERATION_ATTR_AVAILABLE_BY);
+ if (typeof availableBy === "string" && typeof frequency === "string" &&
+ (FREQUENCIES as readonly string[]).includes(frequency) &&
+ !AVAILABLE_BY_PATTERNS[frequency as Frequency].test(availableBy)) {
+ sink.add(op, "ERR_BAD_ATTR_VALUE",
+ `operation.${op.subType} "${label(op)}" @availableBy "${availableBy}" is not a ${frequency} time; a ${frequency} file's @availableBy is written like "${AVAILABLE_BY_EXAMPLES[frequency as Frequency]}" (UTC).`);
+ }
+ // ADR-0039: own — a binding is checked on the operation that declares it.
+ for (const b of op.ownChildren()) {
+ if (b.type !== TYPE_BINDING || b.subType !== BINDING_SUBTYPE_FILE) continue;
+ const fileName = b.attr(BINDING_ATTR_FILE_NAME);
+ if (typeof fileName !== "string") continue;
+ const bad = fileNamePlaceholderProblem(fileName);
+ if (bad !== undefined) {
+ sink.add(b, "ERR_BAD_ATTR_VALUE",
+ `binding.file on "${label(b)}" @fileName "${fileName}" ${bad}; the placeholders are {${FILE_NAME_PLACEHOLDERS.join("} and {")}}.`);
+ }
+ }
+}
+
+/** What is wrong with a @fileName's placeholders, or undefined when nothing is. */
+function fileNamePlaceholderProblem(fileName: string): string | undefined {
+ for (const m of fileName.matchAll(/\{([^{}]*)\}/g)) {
+ const name = m[1] ?? "";
+ if (!(FILE_NAME_PLACEHOLDERS as readonly string[]).includes(name)) return `holds the placeholder {${name}}`;
+ }
+ return /[{}]/.test(fileName.replace(/\{[^{}]*\}/g, "")) ? "has an unmatched brace" : undefined;
+}
+
+/** O1 — an operation's @inputRef and @outputRef shapes. False when one is wrong. */
+function checkShapes(op: MetaData, sink: Sink): boolean {
+ const inputRef = op.attr(OPERATION_ATTR_INPUT_REF);
+ if (typeof inputRef === "string") {
+ const input = resolveObjectOn(op, inputRef);
+ if (input === undefined || input.subType !== OBJECT_SUBTYPE_VALUE) {
+ sink.add(op, "ERR_OPERATION_SHAPE",
+ `operation.${op.subType} "${label(op)}" @inputRef "${inputRef}" ${input === undefined ? "names no object" : `is an object.${input.subType}`}; an operation's input is an object.value.`);
+ return false;
+ }
+ }
+ const outputRef = op.attr(OPERATION_ATTR_OUTPUT_REF);
+ if (typeof outputRef === "string") {
+ const output = resolveObjectOn(op, outputRef);
+ const legal = output !== undefined &&
+ [OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE].includes(output.subType);
+ if (!legal) {
+ sink.add(op, "ERR_OPERATION_SHAPE",
+ `operation.${op.subType} "${label(op)}" @outputRef "${outputRef}" ${output === undefined ? "names no object" : `is an object.${output.subType}`}; an operation returns an object.entity, object.projection or object.value.`);
+ return false;
+ }
+ }
+ return true;
+}
+
/** ADR-0066 — the rules pass. Runs after reference-bearing validation, before freeze. */
export function validateRules(root: MetaData): ParseError[] {
const sink = new Sink();
@@ -369,6 +439,10 @@ export function validateRules(root: MetaData): ParseError[] {
for (const api of root.children()) {
if (api.type !== TYPE_API) continue;
const ops = api.children().filter((c) => c.type === TYPE_OPERATION);
+ if (api.subType !== API_SUBTYPE_OPERATIONAL) {
+ for (const op of ops) checkDeliveryOperation(op, sink);
+ continue;
+ }
for (const op of ops) checkOperation(op, sink);
for (const op of ops) {
const pkg = effectivePackageOf(api);
@@ -430,7 +504,7 @@ function checkPermissionNames(root: MetaData, sink: Sink): void {
for (const t of entityTransitions(entity)) register(t, entity, `${entity.name}.${t.name}`);
}
for (const api of root.children()) {
- if (api.type !== TYPE_API) continue;
+ if (api.type !== TYPE_API || api.subType !== API_SUBTYPE_OPERATIONAL) continue;
for (const op of api.children()) if (op.type === TYPE_OPERATION) register(op, api, op.name);
}
}
diff --git a/server/typescript/packages/metadata/test/definition-schema.test.ts b/server/typescript/packages/metadata/test/definition-schema.test.ts
index 093ba1376d..3e4176c317 100644
--- a/server/typescript/packages/metadata/test/definition-schema.test.ts
+++ b/server/typescript/packages/metadata/test/definition-schema.test.ts
@@ -96,6 +96,12 @@ describe("definition schema — the existing definition files", () => {
`grant.${kind} @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: [kind], sameSystem: true, wrongSystemCode: "ERR_GRANT_CROSSES_SYSTEM" })}`,
),
`grant.api @api ${JSON.stringify({ targetType: "api" })}`,
+ `app.service @provides ${JSON.stringify({ targetType: "api" })}`,
+ `app.job @provides ${JSON.stringify({ targetType: "api" })}`,
+ `app.job @extracts ${JSON.stringify({ targetType: "object", targetSubTypes: ["entity", "projection"] })}`,
+ `resource.objectStore @carries ${JSON.stringify({ targetType: "api", targetSubTypes: ["batch"] })}`,
+ `resource.queue @carries ${JSON.stringify({ targetType: "api", targetSubTypes: ["eventing"] })}`,
+ `resource.stream @carries ${JSON.stringify({ targetType: "api", targetSubTypes: ["eventing"] })}`,
`source.rdb @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: ["rdb"] })}`,
`source.document @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: ["document"] })}`,
`source.search @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: ["search"] })}`,
diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts
index f3bb03fcd0..8d4f235d25 100644
--- a/server/typescript/packages/metadata/test/reference-facet.test.ts
+++ b/server/typescript/packages/metadata/test/reference-facet.test.ts
@@ -659,7 +659,10 @@ describe("reference facet — the registry manifest", () => {
expect(withRef.sort()).toEqual([
"app.base @runsAs",
"app.client @runsAs",
+ "app.job @extracts",
+ "app.job @provides",
"app.job @runsAs",
+ "app.service @provides",
"app.service @runsAs",
"field.map @objectRef",
"field.object @objectRef",
@@ -676,6 +679,9 @@ describe("reference facet — the registry manifest", () => {
"relationship.association @objectRef",
"relationship.base @objectRef",
"relationship.composition @objectRef",
+ "resource.objectStore @carries",
+ "resource.queue @carries",
+ "resource.stream @carries",
"role.base @memberOf",
"role.group @memberOf",
"role.service @memberOf",
diff --git a/site-reference/index.html b/site-reference/index.html
index 8ddf6d89df..6e9aba0960 100644
--- a/site-reference/index.html
+++ b/site-reference/index.html
@@ -66,6 +66,16 @@
A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that provides it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the resource.objectStore that carries it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that provides it publishes; a role holding grant.api on it consumes. It travels on the resource.stream or resource.queue that carries it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (v1, v2) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the resource.objectStore that carries the API; @transport says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an operation.export or operation.import. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an operation.event. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
The HTTP method and path of an operation, declared only to override the derived ones. A query is GET, a command POST; the path is /<collection>/{id}/<operation-kebab> for an operation with a target key and /<collection>/<operation-kebab> without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
Something that happened, published by the provider: the payload is its @outputRef. A child of an api.eventing. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
A file the provider publishes on a schedule for consumers to collect: each row has the shape of its @outputRef, and the file appears this often (@frequency), by this time (@availableBy). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (app.job @schedule). A child of an api.batch. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
A file the provider accepts on a schedule from consumers: each row has the shape of its @inputRef, and a new file is expected this often (@frequency). The consumer delivers; the provider collects and reads. A child of an api.batch. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
A named operation that reads. Returns an object.projection (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that provides it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the resource.objectStore that carries it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
Owning provider: metaobjects-rules
+
Rules: Children are operation.export and operation.import. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.
+
When to use: A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.
+
Attributes
+
No subtype-specific attributes.
+
Allowed children
+
+
operation.export — 0..*
+
operation.import — 0..*
+
+
api.eventing
+
A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that provides it publishes; a role holding grant.api on it consumes. It travels on the resource.stream or resource.queue that carries it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
Owning provider: metaobjects-rules
+
Rules: Children are operation.event. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.
+
When to use: Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.
+
Attributes
+
No subtype-specific attributes.
+
Allowed children
+
+
operation.event — 0..*
+
api.operational
A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (v1, v2) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
The entity or projection this job reads the rows of the files it writes from (DailyManifestLine), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object.
+
+
+
@provides
+
string[]
+
no
+
+
+
metaobjects-systems-core
+
The APIs this app provides, by name (ShipmentEvents, pkg::ManifestFeed): any api node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.
+
+
@runsAs
string
no
@@ -178,6 +196,15 @@
app.service
+
@provides
+
string[]
+
no
+
+
+
metaobjects-systems-core
+
The APIs this app provides, by name (ShipmentEvents, pkg::ManifestFeed): any api node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.
How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the resource.objectStore that carries the API; @transport says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an operation.export or operation.import. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
Owning provider: metaobjects-rules
+
When to use: Every export and import whose file conventions two parties must agree on.
+
Attributes
+
+
+
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@completion
+
string
+
no
+
none
+
rename, marker, none
+
metaobjects-rules
+
How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus .done (manifest-2026-12-03.csv.done) is put beside it. none (the default): the reader is told nothing.
+
+
+
@compression
+
string
+
no
+
none
+
none, gzip
+
metaobjects-rules
+
none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk.
+
+
+
@encryption
+
string
+
no
+
none
+
none, pgp
+
metaobjects-rules
+
none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key.
+
+
+
@fileName
+
string
+
yes
+
+
+
metaobjects-rules
+
The name of each file, with optional placeholders (manifest-{date}.csv). {date} is the UTC date on which the run that writes the file started, as YYYY-MM-DD (2026-12-03). {timestamp} is the UTC time at which that run started, to the second, as YYYYMMDDTHHMMSSZ (20261203T020000Z). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE.
+
+
+
@format
+
string
+
yes
+
+
csv, jsonLines, parquet
+
metaobjects-rules
+
How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (""), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in Z and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as 0); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet.
+
+
+
@path
+
string
+
no
+
+
+
metaobjects-rules
+
The folder, within the object store, that holds the files (manifests/). Absent: the top of the store.
+
+
+
@transport
+
string
+
yes
+
+
sftp, objectStore
+
metaobjects-rules
+
How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product.
+
+
+
Allowed children
+
No structural children.
+
binding.messaging
+
How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an operation.event. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
Owning provider: metaobjects-rules
+
When to use: Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.
+
Attributes
+
+
+
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@protocol
+
string
+
no
+
+
kafka, amqp, mqtt, sqs
+
metaobjects-rules
+
The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks.
+
+
+
Allowed children
+
No structural children.
binding.rest
The HTTP method and path of an operation, declared only to override the derived ones. A query is GET, a command POST; the path is /<collection>/{id}/<operation-kebab> for an operation with a target key and /<collection>/<operation-kebab> without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
Owning provider: metaobjects-rules
diff --git a/site-reference/types/operation.html b/site-reference/types/operation.html
index b13b6c311e..1454eae9e2 100644
--- a/site-reference/types/operation.html
+++ b/site-reference/types/operation.html
@@ -51,9 +51,17 @@
Allowed children lists the structural child rules with their cardinality
(min..max, * = unbounded).
operation.base
-
Registry anchor for the attributes every operation shares (ADR-0054): not authorable.
+
Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.
Owning provider: metaobjects-rules
Attributes
+
No subtype-specific attributes.
+
Allowed children
+
No structural children.
+
operation.command
+
A named operation that changes state. Takes an object.value (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
Owning provider: metaobjects-rules
+
When to use: A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.
+
Attributes
@@ -67,6 +75,15 @@
operation.base
+
@errors
+
string[]
+
no
+
+
+
metaobjects-rules
+
The business failures the hand-written body may return, each a lower snake case code (insufficient_funds). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE.
+
+
@inputRef
string
no
@@ -111,15 +128,24 @@
operation.base
metaobjects-rules
The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT.
+
+
@transitions
+
string[]
+
no
+
+
+
metaobjects-rules
+
The lifecycle moves this command may make: names of transition.action nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED).
+
Allowed children
-
binding.* — 0..*
+
binding.rest — 0..*
-
operation.command
-
A named operation that changes state. Takes an object.value (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
operation.event
+
Something that happened, published by the provider: the payload is its @outputRef. A child of an api.eventing. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
Owning provider: metaobjects-rules
-
When to use: A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.
+
When to use: Each distinct fact a consumer may react to: placed, delivered, cancelled.
Attributes
@@ -134,72 +160,116 @@
operation.command
-
@errors
-
string[]
+
@key
+
string
no
metaobjects-rules
-
The business failures the hand-written body may return, each a lower snake case code (insufficient_funds). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE.
+
The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised.
-
@inputRef
+
@outputRef
string
-
no
+
yes
metaobjects-rules
-
The object.value this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an object.value is ERR_OPERATION_SHAPE.
+
The payload the provider emits: an object.value, object.projection or object.entity. Anything else is ERR_OPERATION_SHAPE.
+
+
Allowed children
+
+
binding.messaging — 0..*
+
+
operation.export
+
A file the provider publishes on a schedule for consumers to collect: each row has the shape of its @outputRef, and the file appears this often (@frequency), by this time (@availableBy). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (app.job @schedule). A child of an api.batch. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
Owning provider: metaobjects-rules
+
When to use: A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.
+
Attributes
+
+
-
@objectRef
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@availableBy
string
no
metaobjects-rules
-
The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields extend every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an object.entity (ERR_OPERATION_TARGET_UNRESOLVED).
+
The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly :MM (minutes past each hour, :15); daily HH:MM (03:00); weekly a day and a time, Ddd HH:MM with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (Mon 06:00); monthly a day of the month from 1 to 28 and a time, D HH:MM (1 06:00), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised.
-
@outputRef
+
@frequency
string
-
no
-
+
yes
+
hourly, daily, weekly, monthly
metaobjects-rules
-
The object this operation returns: an object.projection, object.entity or object.value. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE.
+
How often a new file appears: hourly, daily, weekly or monthly.
-
@permission
+
@outputRef
string
-
no
+
yes
metaobjects-rules
-
The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as purchasing.approve; a package prefix may use :: (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name <package>.<operation>, with the package of the operation's API, and verify advises or requires an explicit one (setting rules.permissions.names). Several operations may share one.
+
The shape of one row of the file the provider publishes: an object.value, object.projection or object.entity. Anything else is ERR_OPERATION_SHAPE.
+
+
Allowed children
+
+
binding.file — 0..*
+
+
operation.import
+
A file the provider accepts on a schedule from consumers: each row has the shape of its @inputRef, and a new file is expected this often (@frequency). The consumer delivers; the provider collects and reads. A child of an api.batch. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
+
Owning provider: metaobjects-rules
+
When to use: A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.
+
Attributes
+
+
-
@public
-
boolean
-
no
-
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@frequency
+
string
+
yes
+
hourly, daily, weekly, monthly
metaobjects-rules
-
The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT.
+
How often a new file is expected: hourly, daily, weekly or monthly.
-
@transitions
-
string[]
-
no
+
@inputRef
+
string
+
yes
metaobjects-rules
-
The lifecycle moves this command may make: names of transition.action nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED).
+
The shape of one row of the file the provider accepts: an object.value. Anything else is ERR_OPERATION_SHAPE.
Allowed children
-
binding.* — 0..*
+
binding.file — 0..*
operation.query
A named operation that reads. Returns an object.projection (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).
The batch APIs whose files sit in this store, by name (ManifestFeed). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an api.batch, is ERR_REF_WRONG_KIND: an eventing API travels on a resource.stream or resource.queue.
+
+
@publicRead
boolean
no
@@ -201,6 +210,15 @@
resource.queue
+
@carries
+
string[]
+
no
+
+
+
metaobjects-systems-core
+
The eventing APIs whose events travel on this queue, by name (ShipmentEvents). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an api.eventing, is ERR_REF_WRONG_KIND: a batch API travels on a resource.objectStore.
+
+
@deadLetter
boolean
no
@@ -315,6 +333,15 @@
resource.stream
+
@carries
+
string[]
+
no
+
+
+
metaobjects-systems-core
+
The eventing APIs whose events travel on this stream, by name (ShipmentEvents). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an api.eventing, is ERR_REF_WRONG_KIND: a batch API travels on a resource.objectStore.
+
+
@residency
string
no
diff --git a/spec/metamodel/api.json b/spec/metamodel/api.json
index 6c803bfba0..79f2e2cb08 100644
--- a/spec/metamodel/api.json
+++ b/spec/metamodel/api.json
@@ -15,22 +15,39 @@
"whenToUse": "The application does something beyond derived CRUD: a named command (approve, cancel, import) or a named query (my open requests). Declare it here so its input, output, permission and business errors are part of the model. A plain lifecycle needs no api.operational at all: a transition nobody claims is held to derive its own command once a shell is generated, and no shell is generated yet.",
"rules": "Children are `operation.command` and `operation.query`. Lives at the document root. Declares no fields, sources or identities: shapes are referenced, never defined, by the surface. Operation names are compared without case, are unique across every API of one package, except one operation declared identically in two APIs, such as a versioned API beside its successor (one operation declared twice in one API merges), and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). Two declared bindings of one API may not share a method and path (ERR_BINDING_PATH_MISMATCH).",
"children": [
- { "type": "operation", "subType": "*", "name": "*", "min": 0, "max": null, "description": "The operations this surface exposes." }
+ { "type": "operation", "subType": "command", "name": "*", "min": 0, "max": null, "description": "The commands this surface exposes." },
+ { "type": "operation", "subType": "query", "name": "*", "min": 0, "max": null, "description": "The queries this surface exposes." }
]
},
{
- "type": "operation",
- "subType": "base",
- "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.",
+ "type": "api",
+ "subType": "eventing",
+ "extendsBase": true,
+ "description": "A named, packaged surface of events: the provider says something happened, and any number of consumers each read it at their own pace (ADR-0030; the names ADR-0007 Amendment 1 reserved). The app that `provides` it publishes; a role holding `grant.api` on it consumes. It travels on the `resource.stream` or `resource.queue` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Other apps, or another organization, must learn that something happened (a shipment was placed, a payment settled) without asking for it.",
+ "rules": "Children are `operation.event`. Lives at the document root. Declares no fields, sources or identities: payloads are referenced, never defined, by the surface. None of api.operational's operation rules apply: an event is not a command or a query, has no target entity, and derives no permission name.",
"children": [
- { "type": "binding", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Optional protocol bindings. Only needed to override the derived method and path." },
- { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." },
- { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." },
- { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." },
- { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." },
- { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." }
+ { "type": "operation", "subType": "event", "name": "*", "min": 0, "max": null, "description": "The events this surface publishes." }
+ ]
+ },
+ {
+ "type": "api",
+ "subType": "batch",
+ "extendsBase": true,
+ "description": "A named, packaged surface of datasets delivered as files on a schedule (ADR-0030). The app that `provides` it hosts the files: it publishes an export for consumers to collect, and accepts an import consumers deliver. It travels on the `resource.objectStore` that `carries` it. Nothing is generated from it yet: every port's API generators skip it. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A dataset changes hands as a file at an agreed time: a nightly manifest a partner collects, a batch of orders a retailer drops off.",
+ "rules": "Children are `operation.export` and `operation.import`. Lives at the document root. Declares no fields, sources or identities: row shapes are referenced, never defined, by the surface. None of api.operational's operation rules apply: an export or import is not a command or a query, has no target entity, and derives no permission name.",
+ "children": [
+ { "type": "operation", "subType": "export", "name": "*", "min": 0, "max": null, "description": "The datasets the provider publishes." },
+ { "type": "operation", "subType": "import", "name": "*", "min": 0, "max": null, "description": "The datasets the provider accepts." }
]
},
+ {
+ "type": "operation",
+ "subType": "base",
+ "description": "Registry anchor for operations (ADR-0054): not authorable. Each operation subtype declares its own attributes.",
+ "children": []
+ },
{
"type": "operation",
"subType": "command",
@@ -38,6 +55,12 @@
"description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
"whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.",
"children": [
+ { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." },
+ { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." },
+ { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." },
+ { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." },
{ "type": "attr", "subType": "string", "name": "transitions", "isArray": true, "min": 0, "max": 1, "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." },
{ "type": "attr", "subType": "string", "name": "errors", "isArray": true, "min": 0, "max": 1, "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." }
]
@@ -49,9 +72,52 @@
"description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
"whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.",
"children": [
+ { "type": "binding", "subType": "rest", "name": "*", "min": 0, "max": null, "description": "Optional HTTP bindings. Only needed to override the derived method and path." },
+ { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." },
+ { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." },
+ { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." },
{ "type": "attr", "subType": "boolean", "name": "many", "min": 0, "max": 1, "description": "The query returns a list and takes the filter, sort and paging contract. Not implied by the projection, so declared. Absent means one row. Legal on a query only." }
]
},
+ {
+ "type": "operation",
+ "subType": "event",
+ "extendsBase": true,
+ "description": "Something that happened, published by the provider: the payload is its `@outputRef`. A child of an `api.eventing`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Each distinct fact a consumer may react to: placed, delivered, cancelled.",
+ "children": [
+ { "type": "binding", "subType": "messaging", "name": "*", "min": 0, "max": null, "description": "Optional messaging bindings: how the event travels." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The payload the provider emits: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "key", "min": 0, "max": 1, "description": "The field of the payload whose events must stay in order: two events with the same value of it are read in the order they were published. Absent: no order is promised." }
+ ]
+ },
+ {
+ "type": "operation",
+ "subType": "export",
+ "extendsBase": true,
+ "description": "A file the provider publishes on a schedule for consumers to collect: each row has the shape of its `@outputRef`, and the file appears this often (`@frequency`), by this time (`@availableBy`). That pair is the promise the consumer plans around; the cron line that keeps it belongs to the job that provides the API (`app.job @schedule`). A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A partner collects a dataset from you at an agreed time: a nightly manifest, a weekly settlement.",
+ "children": [
+ { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is and how it is written." },
+ { "type": "attr", "subType": "string", "name": "outputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider publishes: an `object.value`, `object.projection` or `object.entity`. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file appears: hourly, daily, weekly or monthly." },
+ { "type": "attr", "subType": "string", "name": "availableBy", "min": 0, "max": 1, "description": "The time, in UTC, by which each new file is in place. Its form follows @frequency: hourly `:MM` (minutes past each hour, `:15`); daily `HH:MM` (`03:00`); weekly a day and a time, `Ddd HH:MM` with the day one of Mon, Tue, Wed, Thu, Fri, Sat or Sun (`Mon 06:00`); monthly a day of the month from 1 to 28 and a time, `D HH:MM` (`1 06:00`), because every month has those days. Hours run 00 to 23 and minutes 00 to 59, each two digits. Any other form, or one that does not match @frequency, is ERR_BAD_ATTR_VALUE. Absent: no time is promised." }
+ ]
+ },
+ {
+ "type": "operation",
+ "subType": "import",
+ "extendsBase": true,
+ "description": "A file the provider accepts on a schedule from consumers: each row has the shape of its `@inputRef`, and a new file is expected this often (`@frequency`). The consumer delivers; the provider collects and reads. A child of an `api.batch`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "A partner delivers a dataset to you: scanner logs every hour, a retailer's daily orders.",
+ "children": [
+ { "type": "binding", "subType": "file", "name": "*", "min": 0, "max": null, "description": "Optional file bindings: where the file is delivered and how it is written." },
+ { "type": "attr", "subType": "string", "name": "inputRef", "min": 1, "max": 1, "description": "The shape of one row of the file the provider accepts: an `object.value`. Anything else is ERR_OPERATION_SHAPE." },
+ { "type": "attr", "subType": "string", "name": "frequency", "min": 1, "max": 1, "allowedValues": ["hourly", "daily", "weekly", "monthly"], "description": "How often a new file is expected: hourly, daily, weekly or monthly." }
+ ]
+ },
{
"type": "binding",
"subType": "base",
@@ -68,6 +134,32 @@
{ "type": "attr", "subType": "string", "name": "method", "min": 0, "max": 1, "allowedValues": ["GET", "POST", "PUT", "PATCH", "DELETE"], "description": "The HTTP method. Absent: GET for a query, POST for a command." },
{ "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "A path template. Its `{name}` placeholders must be exactly the target's primary key fields when the operation is keyed, and there must be none when it is not; two declared bindings of one API may not share the method and path (ERR_BINDING_PATH_MISMATCH)." }
]
+ },
+ {
+ "type": "binding",
+ "subType": "messaging",
+ "extendsBase": true,
+ "description": "How an event travels: on the stream or queue that carries its API. Unpinned, any product may carry it. A protocol is a contract and a product is not, so the binding may pin the wire protocol and never a product. A child of an `operation.event`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Pin the protocol when another organization connects to the stream and must know what it speaks. Otherwise leave it out.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "protocol", "min": 0, "max": 1, "allowedValues": ["kafka", "amqp", "mqtt", "sqs"], "description": "The wire protocol the consumers speak. Absent: whatever protocol the product that carries the API speaks." }
+ ]
+ },
+ {
+ "type": "binding",
+ "subType": "file",
+ "extendsBase": true,
+ "description": "How a file of an export or import is delivered: where it sits, what it is called, how it is written and how a reader knows it is whole. The provider always hosts the files, in the `resource.objectStore` that carries the API; `@transport` says how the other party reaches them. No standard covers these conventions, so they are pinned here. A child of an `operation.export` or `operation.import`. Experimental since 1.4.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).",
+ "whenToUse": "Every export and import whose file conventions two parties must agree on.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "transport", "min": 1, "max": 1, "allowedValues": ["sftp", "objectStore"], "description": "How the other party reaches the files. sftp: over an SFTP server whose storage is the object store, with an account whose home is @path. objectStore: directly, through the interface of whatever product supplies the store (on Amazon, S3). Never a product." },
+ { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "The folder, within the object store, that holds the files (`manifests/`). Absent: the top of the store." },
+ { "type": "attr", "subType": "string", "name": "fileName", "min": 1, "max": 1, "description": "The name of each file, with optional placeholders (`manifest-{date}.csv`). `{date}` is the UTC date on which the run that writes the file started, as `YYYY-MM-DD` (`2026-12-03`). `{timestamp}` is the UTC time at which that run started, to the second, as `YYYYMMDDTHHMMSSZ` (`20261203T020000Z`). A run that writes a past day again uses that day's date. Any other placeholder, or an unclosed brace, is ERR_BAD_ATTR_VALUE." },
+ { "type": "attr", "subType": "string", "name": "format", "min": 1, "max": 1, "allowedValues": ["csv", "jsonLines", "parquet"], "description": "How the rows are written. csv: RFC 4180 with a comma between fields and CRLF after every line, in UTF-8 with no byte order mark. The first line is the field names. A field is quoted only when it holds a comma, a quote, CR or LF, and a quote inside a quoted field is doubled. An empty string is the one exception: it is always quoted (`\"\"`), so that it differs from null, which is an empty field. An object, a map and any array is its JSON text, quoted by the same rule. Every other value is written in the canonical form of the REST wire contract (docs/features/api-contract.md and fixtures/persistence-conformance/normalization.md), whatever the project's wire setting. Among that contract's forms: a timestamp ends in `Z` and one with @localTime has no zone suffix; a time or timestamp carries a fraction of a second only when it is nonzero, at millisecond resolution, truncated, with no trailing zeros; a decimal is the canonical string of ADR-0019 Amendment 1 (plain notation, no exponent, no trailing fraction zeros, zero as `0`); a currency amount is an integer in minor units. jsonLines: one JSON object per line, UTF-8, LF after each. parquet: Apache Parquet." },
+ { "type": "attr", "subType": "string", "name": "compression", "min": 0, "max": 1, "allowedValues": ["none", "gzip"], "default": "none", "description": "none (the default): the file is written as it is. gzip: the file is gzip-compressed, and @fileName is the name it has on disk." },
+ { "type": "attr", "subType": "string", "name": "completion", "min": 0, "max": 1, "allowedValues": ["rename", "marker", "none"], "default": "none", "description": "How a reader knows a file is whole. rename: the file appears under its final name only once it is complete. marker: once the file is complete, an empty object named the file's name plus `.done` (`manifest-2026-12-03.csv.done`) is put beside it. none (the default): the reader is told nothing." },
+ { "type": "attr", "subType": "string", "name": "encryption", "min": 0, "max": 1, "allowedValues": ["none", "pgp"], "default": "none", "description": "none (the default): the file is not encrypted beyond its transport. pgp: the file is encrypted with OpenPGP to the reader's public key." }
+ ]
}
],
"extends": [
diff --git a/spec/metamodel/systems.json b/spec/metamodel/systems.json
index cb6b7da4ed..189eaf4c5e 100644
--- a/spec/metamodel/systems.json
+++ b/spec/metamodel/systems.json
@@ -64,7 +64,8 @@
"description": "A long-running process that answers requests: a web server, an API, a socket server.",
"whenToUse": "Anything that listens on a port and stays up.",
"children": [
- { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." }
+ { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names." },
+ { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } }
]
},
{
@@ -84,7 +85,9 @@
"description": "Work that runs to completion and exits: a scheduled task, a migration, a one-off batch. It may run on a schedule (@schedule) or when something triggers it.",
"whenToUse": "A cron job, a nightly import, a queue drain that is not a long-running service.",
"children": [
- { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." }
+ { "type": "attr", "subType": "string", "name": "schedule", "min": 0, "max": 1, "description": "When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered." },
+ { "type": "attr", "subType": "string", "name": "extracts", "min": 0, "max": 1, "description": "The entity or projection this job reads the rows of the files it writes from (`DailyManifestLine`), by name. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an object that is neither an entity nor a projection, is ERR_REF_WRONG_KIND. Absent: the job reads no declared object.", "ref": { "targetType": "object", "targetSubTypes": ["entity", "projection"] } },
+ { "type": "attr", "subType": "string", "name": "provides", "isArray": true, "min": 0, "max": 1, "description": "The APIs this app provides, by name (`ShipmentEvents`, `pkg::ManifestFeed`): any `api` node. The provider hosts: a service answers an operational API, publishes an eventing API's events, and a job or service hosts a batch API's files. A client serves nothing, so it provides nothing. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } }
]
},
{
@@ -137,7 +140,8 @@
"description": "Files and blobs addressed by key.",
"whenToUse": "Uploaded images, exports, static assets kept outside the app.",
"children": [
- { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." }
+ { "type": "attr", "subType": "boolean", "name": "publicRead", "min": 0, "max": 1, "description": "Anyone may read the objects without a credential. Absent means every read needs a grant." },
+ { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The batch APIs whose files sit in this store, by name (`ManifestFeed`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.batch`, is ERR_REF_WRONG_KIND: an eventing API travels on a `resource.stream` or `resource.queue`.", "ref": { "targetType": "api", "targetSubTypes": ["batch"] } }
]
},
{
@@ -162,7 +166,8 @@
"whenToUse": "Work handed from one app to another to run later.",
"children": [
{ "type": "attr", "subType": "boolean", "name": "ordered", "min": 0, "max": 1, "description": "Messages with the same key are delivered in the order they were sent. Absent means no order is promised." },
- { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." }
+ { "type": "attr", "subType": "boolean", "name": "deadLetter", "min": 0, "max": 1, "description": "A message that keeps failing is set aside rather than dropped. How many attempts come first is a setting." },
+ { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this queue, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } }
]
},
{
@@ -170,7 +175,10 @@
"subType": "stream",
"extendsBase": true,
"description": "A retained, ordered log that many consumers read, each at its own position. A message can be read again.",
- "whenToUse": "Events several consumers read independently, or read again."
+ "whenToUse": "Events several consumers read independently, or read again.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "carries", "isArray": true, "min": 0, "max": 1, "description": "The eventing APIs whose events travel on this stream, by name (`ShipmentEvents`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or an API that is not an `api.eventing`, is ERR_REF_WRONG_KIND: a batch API travels on a `resource.objectStore`.", "ref": { "targetType": "api", "targetSubTypes": ["eventing"] } }
+ ]
},
{
"type": "resource",