diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index e72e5684ca..5252b3812c 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -18,13 +18,14 @@ Preserve the following contracts exactly across all language ports: **Metamodel subtype vocabularies (must be identical across languages):** the `registry-conformance` gate (`fixtures/registry-conformance/`) is the structural enforcer of this rule — each port emits its registry as a canonical manifest byte-matched to `expected-registry.json`. **All five shipped ports (TS / C# / Java / Kotlin / Python) plus Rust in preview (ADR-0065, byte-identical) are live + green** (SP-G Java/Kotlin reconciliation complete; the JVM runners compose from the defined metamodel provider set so codegen-base/om classpath SPI does not pollute the measured vocabulary). See `fixtures/registry-conformance/README.md`. - Filter operators: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `like`, `isNull` -- Object subtypes: `entity` (owns data: own identity, writable sources, lifecycle), `value` (pure shape: NO identity, NO source, ever; constructed — by caller/embedding — never populated; may `extends` entity fields for shape; a value-hosted field may carry `origin.passthrough` but never an assembly origin), `projection` (derived read-only representation: fields `extends`-bound / origin-derived / self-declared-under-external-assembly, all read-only at subtype level; identity optional and MUST extend an entity identity; sources restricted to read-only `@kind`s; the declared field set IS the exposure — inclusive list, fail-closed). A field carrying `origin.*` is derived ⇒ read-only wherever it lives (incl. on entities). An entity's primary source must be a writable `@kind` (read-only kinds only in read role). See [ADR-0028](spec/decisions/ADR-0028-object-taxonomy-projection-value-purity.md). (FR-024 Phase E — `object.projection`/`value` are registered in `expected-registry.json` and the projection/value validation passes [identity pass-through, value-purity, projection-licensing, `@via` inference/cardinality, extends/origin agreement, derived-field providability] are enforced cross-port in all 5 ports. The **B4b** entity-primary-source-readonly cutover [the "writable `@kind`" clause above — `ERR_ENTITY_PRIMARY_SOURCE_READONLY`] + the projection codegen fan-out (read-only DTOs for view-kind projections; FR-015 proc-callables for proc-kind projections in TypeScript, C# and Kotlin ONLY — Java and Python ship no callable generator at all, so the cross-port claim does NOT cover that clause; api-docs label `object.projection` units as `projection` and document their generated `Dto`) are now shipped cross-port; the remaining FR-024 work is the declared-API surface — tracked in #10.) **`report` (FR-044 Plan 1)** is a root object subtype registered in all five ports, with the `dimension.attribute` / `dimension.time` / `measure.aggregate` / `measure.ratio` / `segment.filter` children on `object.entity` and the relative-date filter value — loader-validated (`ERR_INVALID_DIMENSION` / `ERR_INVALID_MEASURE` / `ERR_INVALID_REPORT` / `ERR_REPORT_FOREIGN_MEASURE`, plus `ERR_BAD_ATTR_FILTER` for relative dates off a reporting host) and, since FR-044 Plan 2, **lowered only when it declares a read-only `source.rdb` of `@kind: view`**: `meta migrate` creates that view (TypeScript only, ADR-0015), every port reads it (persistence corpus, `report-shapes.json`), C# generates its typed row and Kotlin its Exposed table object, and, since FR-044 Plan 3, every port's generators **serve it as a keyless read-only projection** (GET list with filter/sort/paging on every derived field that has a filter band, `POST` 405, no `/{id}`; row type + filter allowlist + route/controller per port, gated by the api-contract `report/` sub-corpus in the generated lane). The client UI tier (hooks, grids, forms) and a report with no view source at all stay inert, gated by the 43 `reporting` conformance fixtures and the `codegen-noop` corpus. A served report is the predicate `servedReport` (TS) / `ReportRows.IsViewBacked` (C#) / `RestSurfaceGate.isServedReport` (Java, Kotlin) / `is_served_report` (Python): concrete, read source `@kind: view`. See [docs/features/reporting.md](docs/features/reporting.md). +- Object subtypes: `entity` (owns data: own identity, writable sources, lifecycle), `value` (pure shape: NO identity, NO source, ever; constructed — by caller/embedding — never populated; may `extends` entity fields for shape; a value-hosted field may carry `origin.passthrough` but never an assembly origin), `projection` (derived read-only representation: fields `extends`-bound / origin-derived / self-declared-under-external-assembly, all read-only at subtype level; identity optional and MUST extend an entity identity; sources restricted to read-only `@kind`s; the declared field set IS the exposure — inclusive list, fail-closed). A field carrying `origin.*` is derived ⇒ read-only wherever it lives (incl. on entities). An entity's primary source must be a writable `@kind` (read-only kinds only in read role). See [ADR-0028](spec/decisions/ADR-0028-object-taxonomy-projection-value-purity.md). (FR-024 Phase E — `object.projection`/`value` are registered in `expected-registry.json` and the projection/value validation passes [identity pass-through, value-purity, projection-licensing, `@via` inference/cardinality, extends/origin agreement, derived-field providability] are enforced cross-port in all 5 ports. The **B4b** entity-primary-source-readonly cutover [the "writable `@kind`" clause above — `ERR_ENTITY_PRIMARY_SOURCE_READONLY`] + the projection codegen fan-out (read-only DTOs for view-kind projections; FR-015 proc-callables for proc-kind projections in TypeScript, C# and Kotlin ONLY — Java and Python ship no callable generator at all, so the cross-port claim does NOT cover that clause; api-docs label `object.projection` units as `projection` and document their generated `Dto`) are now shipped cross-port; the declared-API surface, the last third of FR-024, is registered since 1.3.0 by ADR-0066 — see the API bullet below.) **`report` (FR-044 Plan 1)** is a root object subtype registered in all five ports, with the `dimension.attribute` / `dimension.time` / `measure.aggregate` / `measure.ratio` / `segment.filter` children on `object.entity` and the relative-date filter value — loader-validated (`ERR_INVALID_DIMENSION` / `ERR_INVALID_MEASURE` / `ERR_INVALID_REPORT` / `ERR_REPORT_FOREIGN_MEASURE`, plus `ERR_BAD_ATTR_FILTER` for relative dates off a reporting host) and, since FR-044 Plan 2, **lowered only when it declares a read-only `source.rdb` of `@kind: view`**: `meta migrate` creates that view (TypeScript only, ADR-0015), every port reads it (persistence corpus, `report-shapes.json`), C# generates its typed row and Kotlin its Exposed table object, and, since FR-044 Plan 3, every port's generators **serve it as a keyless read-only projection** (GET list with filter/sort/paging on every derived field that has a filter band, `POST` 405, no `/{id}`; row type + filter allowlist + route/controller per port, gated by the api-contract `report/` sub-corpus in the generated lane). The client UI tier (hooks, grids, forms) and a report with no view source at all stay inert, gated by the 43 `reporting` conformance fixtures and the `codegen-noop` corpus. A served report is the predicate `servedReport` (TS) / `ReportRows.IsViewBacked` (C#) / `RestSurfaceGate.isServedReport` (Java, Kotlin) / `is_served_report` (Python): concrete, read source `@kind: view`. See [docs/features/reporting.md](docs/features/reporting.md). - Source subtypes: `rdb` (paradigm; ADR-0007). The pre-v2 `dbTable`/`dbView` subtypes are RETIRED — `source.rdb` + `@kind: table|view|materializedView|storedProc|tableFunction` is the form, with read-only-ness derived from `@kind`. Multi-source via `@role` (exactly one `primary` per object). Source physical name = `@table` (NOT `@name`); field physical name = `@column` (renamed from `@dbColumn`). Referential actions on relationships: `@onDelete` / `@onUpdate`. - Origin subtypes: `passthrough`, `aggregate`, `collection`, `computed`, `first` (concrete; `base` is the abstract root). `passthrough` is legal on an `object.value`-hosted field (FR-015 parameter lineage); the four assembly origins (`aggregate`/`computed`/`collection`/`first`) live on `object.projection` only — a value-hosted assembly origin is `ERR_SUBTYPE_RULE_VIOLATION` (#210). - 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; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `rest` now, `messaging`/`grpc` reserved). Children: `operation.query` (outputRef → `object.projection`) / `operation.command` (inputRef → `object.value`, may also outputRef). 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). (FR-024 declared-API — planned; not yet in `expected-registry.json`; the remaining third of FR-024 after the projection/value taxonomy + validation parity.) +- 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/`); nothing is generated from it yet (`fixtures/codegen-noop/rules/`). +- 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) - Storage attrs: `@storage` on `field.object` (with `@objectRef`) — values `flattened` / `jsonb` / `subdocument`. Unifies "owned types" (flattened storage) and "structured JSONB" (jsonb storage). Defaults to single-jsonb-column when absent (back-compat). diff --git a/AGENTS.md b/AGENTS.md index 3fbd8d1e6b..5a5e0160a3 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` (KotlinPoet on 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/` (526 fixtures; 42 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/` (574 fixtures; 43 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 / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), 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** (TS owns schema migrations). **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.md b/CHANGELOG.md index 0132e8bd3e..04e509f0fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,62 @@ here.** ## [Unreleased] +**New metamodel vocabulary, experimental: `api.*`, `operation.*`, `binding.*` and `transition.*` +(ADR-0066).** It is additive: nothing that loaded before stops loading. This vocabulary ships in +1.3.0 with `metamodelVersion` 1.3 if it merges before the 1.3.0 publish; if it lands after, the +next release moves `metamodelVersion`. + ### Added +- **Business rules: operations, permission names and lifecycles (ADR-0066). Experimental:** the + shape may change in a MINOR, including removals and renames, until generated services run on + it in an adopter estate (`docs/compatibility-policy.md`). The names ADR-0030 + reserved are registered, with a lifecycle vocabulary, in all five ports: + - `api.operational` holds `operation.command` and `operation.query`, with `@inputRef`, + `@outputRef`, `@many` (query), `@objectRef`, `@transitions` and `@errors` (command), + `@permission` and `@public`. An optional `binding.rest` (`@method`, `@path`) overrides the + derived HTTP binding. + - `transition.action` is a child of a `field.enum` on an entity, with `@from`, `@to`, + `@condition` (the validators' grammar), `@permission` and `@public`. An enum with a + transition is a lifecycle: its states, initial state (`@default`), terminal states and each + unclaimed transition's command are derived. `transition.timed` is reserved. A lifecycle + belongs to the entity that declares the field and to the entities that extend it, never to + one whose field merely `extends` that field. A lifecycle on an entity with no source loads + and is inert, so a library's core layer can declare one; the writable-source check applies + once a source is added. + - Permission names include their owner. A declared `@permission` is a dotted identifier path + (`purchasing.approve`; a package prefix may use `::`). When it is absent, an operation asks + about `.` and a transition's derived command about + `..`, so two entities' `cancel` transitions never share a + grant. Operation names are unique across the APIs of a package, except one operation + declared identically in two APIs, such as a `v1` beside a `v2`. + - The loader refuses a malformed operation or lifecycle with eleven new codes, each pinned by a + `fixtures/conformance/error-rules-*` case: `ERR_TRANSITION_UNKNOWN_STATE`, + `ERR_TRANSITION_NOT_ON_ENTITY`, `ERR_LIFECYCLE_NO_INITIAL`, `ERR_LIFECYCLE_REDECLARED`, + `ERR_TRANSITION_NAME_COLLISION`, `ERR_OPERATION_SHAPE`, `ERR_OPERATION_TARGET_UNRESOLVED`, + `ERR_OPERATION_TARGET_MISMATCH`, `ERR_OPERATION_UNKNOWN_TRANSITION`, + `ERR_PERMISSION_PUBLIC_CONFLICT` and `ERR_BINDING_PATH_MISMATCH`. Names are compared without + case, an `@errors` code may not be one the route answers itself, two declared bindings + may not share a method and path, and a `@permission` must be a dotted identifier path. + - `verify` in every port gains a rules gate: unreachable states, an initial state that is + terminal, transitions that can never be made, a transition `@permission` no command reads, + and permission names the model derived. It is pinned by the new + `fixtures/rules-check-conformance/` corpus. + - New settings in `.metaobjects/config.json`: `rules.permissions.names`, + `rules.lifecycle.commands`, `rules.lifecycle.create` and `verify.lifecycle.unreachable`. + Absent, each behaves as before. `rules.lifecycle.create` is read and validated and has no + effect yet: the service shells that act on it are later work. + - A requirement's `@implementedBy` may name an operation (`Purchasing.decide`) or a + transition (`PurchaseRequest.status.submit`). + - The Rust preview port (ADR-0065) registers the same vocabulary and runs the same loader + rules with the same messages, so it still passes `registry-conformance` byte for byte and + the whole metamodel corpus (574 of 574, ledger empty). It reads and validates the new + settings. It has no `verify`, so the rules gate does not run there. + + Nothing is generated from the vocabulary yet: the enforcing service shells are later work + (ADR-0067), and `fixtures/codegen-noop/rules/` holds every generator to byte-identical output. + A model that declares none of it sees no change. See `docs/features/business-rules.md`. + ADR-0067 records the layering and service-seam design, and amends ADR-0045. - **Rust port foundation, in preview (ADR-0065).** `server/rust/` is a Cargo workspace with a pinned toolchain and one crate, `metaobjects`: the node model, the type registry and the built-in providers (strict, sealed after bootstrap, the same `ERR_*` codes), and a JSON loader diff --git a/README.md b/README.md index 24988c552c..59151ebf23 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,7 @@ first-week wedge plan — and `meta init` picks up from there. | Kotlin | **Maven Central `8.2.0`** — codegen tier on top of Java: 17 generators (entity, Exposed table, names, relations, repository, output-parser, output-prompt, render-helper, extractor, filter-allowlist, validator, Spring config, storedProc, Spring controller, requirement-tests, api-docs, report-export); 24 / 24 persistence-conformance | [`docs/ports/kotlin.md`](docs/ports/kotlin.md) | [`server/java/codegen-kotlin/`](server/java/codegen-kotlin/) · [`server/java/metadata-ktx/`](server/java/metadata-ktx/) | | C# | **NuGet `1.2.0`** — loader + conformance + EF Core codegen + render engine + `dotnet meta` CLI all shipped | [`docs/ports/csharp.md`](docs/ports/csharp.md) | [`server/csharp/`](server/csharp/) | | Python | **PyPI `1.2.0`** — loader + conformance + render + entity-model codegen + ObjectManager runtime shipped; schema migrations are TS-owned (ADR-0015) | [`docs/ports/python.md`](docs/ports/python.md) | [`server/python/`](server/python/) | -| Rust | **Preview, unpublished** — loader (JSON + YAML), project and source resolution, naming and all 40 validation passes; 526 / 526 metamodel conformance; `cargo meta gen` with the `entity` generator only (ADR-0065) | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | +| Rust | **Preview, unpublished** — loader (JSON + YAML), project and source resolution, naming and all 41 validation passes; 574 / 574 metamodel conformance; `cargo meta gen` with the `entity` generator only (ADR-0065) | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | ## Capability matrix diff --git a/agent-context/skills/metaobjects-audit/references/calibration.md b/agent-context/skills/metaobjects-audit/references/calibration.md index 6b9e72a398..8642c4e397 100644 --- a/agent-context/skills/metaobjects-audit/references/calibration.md +++ b/agent-context/skills/metaobjects-audit/references/calibration.md @@ -32,7 +32,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. +- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/agent-context/skills/metaobjects-audit/references/capability-checklist.md b/agent-context/skills/metaobjects-audit/references/capability-checklist.md index 5741cf9de1..0a892f296c 100644 --- a/agent-context/skills/metaobjects-audit/references/capability-checklist.md +++ b/agent-context/skills/metaobjects-audit/references/capability-checklist.md @@ -362,10 +362,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — planned, not yet shipped:** the declared-API surface (`api.base`, - `api.operational`, `operation.query`, `operation.command`, `binding.rest`) and MCP exposure - of declared prompts/tools are **not yet in the registry** — their absence is not an adopter - defect; do NOT audit for them. +- **CALIBRATION — registered, nothing generated yet:** the declared-API surface + (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles + (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at + load and by `verify`, but no generator emits from them yet. Their absence is not an adopter + defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* version drift (mixed package versions within one port, or a runtime package in diff --git a/agent-context/skills/metaobjects-audit/references/surface-review-axes.md b/agent-context/skills/metaobjects-audit/references/surface-review-axes.md index 58c7f3feb5..e3c3b4737c 100644 --- a/agent-context/skills/metaobjects-audit/references/surface-review-axes.md +++ b/agent-context/skills/metaobjects-audit/references/surface-review-axes.md @@ -228,9 +228,9 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in Exposed `T.update({ (T.id eq id) and (T.status eq ) })` on Kotlin; EF Core `ExecuteUpdateAsync` after a `Where(x => x.Status == )` on C#. Each checks the affected-row count. `` is the generated enum constant, never a literal (signature 13 in - `drift-signatures.md`). **If the allowed transitions need a declared form, that is a question - for the human, never a new attribute** (ADR-0023): the sketch proposes the ORM guard and - records the transition table as an open decision. Pillar `runtime`, surface `repository`. + `drift-signatures.md`). **The allowed transitions have a declared form**, `transition.action` + under a `field.enum` (ADR-0066, experimental): cite that table in the sketch, never a new + attribute (ADR-0023). The sketch proposes the ORM guard. Pillar `runtime`, surface `repository`. - [ ] **H. Authoring-correctness / ADR-conformance (deep).** Invented/unregistered `@`-attrs or post-bootstrap registration (ADR-0023 — custom attrs belong in a registered diff --git a/agent-context/skills/metaobjects-authoring/references/requirements.md b/agent-context/skills/metaobjects-authoring/references/requirements.md index abd10504a0..e2e63964d2 100644 --- a/agent-context/skills/metaobjects-authoring/references/requirements.md +++ b/agent-context/skills/metaobjects-authoring/references/requirements.md @@ -113,7 +113,7 @@ the loader requires those attrs to exist, never to say anything. **Hierarchy is nesting, and links live at the bottom.** L1 solution, L2 segment, L3 service — these never reference the model. **L4** binds a declared top-level node — an `object.*` **or a `template.*`** — and **L5** binds a member of one: a field, view, -validator, identity, or a template's child. `implementedBy` above L4 is an error. +validator, identity, a template's child, an operation, or a transition. `implementedBy` above L4 is an error. Regrouping *moves* a node; it does not edit a parent string. **Write an L5 ref as a dotted `pkg::Owner.member` path** — the level and the shape of the diff --git a/agent-context/skills/metaobjects-fit-assessment/references/capability-sheet.md b/agent-context/skills/metaobjects-fit-assessment/references/capability-sheet.md index 96836cc318..fbbee97586 100644 --- a/agent-context/skills/metaobjects-fit-assessment/references/capability-sheet.md +++ b/agent-context/skills/metaobjects-fit-assessment/references/capability-sheet.md @@ -29,8 +29,8 @@ building block. Every generator is a reference helper an adopter selects, ejects (TS); `mvn metaobjects:verify` (Java/Kotlin; unset `meta.verify.mode` runs both the codegen and the template gate); `dotnet meta verify --codegen` (C#; bare `verify` runs it when `csharp.outDir` (or `--out`) and `codegen/Generators.cs` are present); `metaobjects verify` (Python; `--codegen` is part of the default). Since 1.2 a bare `verify` runs - codegen drift, prompt templates and the requirement ledger in every port, and skips with a note - a gate it has no configuration for. Source: `docs/features/cli.md`. + codegen drift, prompt templates, the requirement ledger and the business-rules gate in every + port, and skips with a note a gate it has no configuration for. Source: `docs/features/cli.md`. - **Generated code compiles**: a codegen-compile gate compiles every port's emitted model tier with its real compiler in CI (`docs/CONFORMANCE.md`, "Split coverage"). - **Sharing a model** (`docs/features/metadata-dependencies.md`): in one repository, every port @@ -80,8 +80,8 @@ a released version counts these as generators the project writes, from the examp `docs/recipes/write-your-own-generator.md`. **Contract-only cannot** bind a shape to a queue, topic or transport as declared vocabulary -(`api.*`, `operation.*`, `binding.*` are not shipped); a generator can still emit per-transport -code from the shapes. +(the declared-API vocabulary is experimental, its only protocol binding is `binding.rest`, and a +messaging binding is reserved); a generator can still emit per-transport code from the shapes. - promise byte-identical JSON from type-only output: field-name casing on the wire follows each consumer's serializer settings (the byte-identical REST wire is a property of the *generated routes*, gated by `fixtures/api-contract-conformance/`). Check it in the wedge. @@ -136,6 +136,6 @@ code from the shapes. `.j2`, `.jinja2`) in Python and TypeScript only; Java, Kotlin and C# render Mustache and refuse a Jinja-only body with `ERR_TEMPLATE_ENGINE_UNSUPPORTED`. MCP exposure of declared prompts/tools is not shipped. -- **Not shipped, never promise**: the `api.*`/`operation.*`/`binding.*` declared-API surface; - the cut `byte`/`short`/`class` field stubs; `index.fulltext`/`vector`/`spatial`; native PG enums +- **Not shipped, never promise**: the `api.*`/`operation.*`/`binding.*` declared-API surface, + which is registered but experimental (ADR-0066) and generates nothing yet; the cut `byte`/`short`/`class` field stubs; `index.fulltext`/`vector`/`spatial`; native PG enums and int-backed enums. diff --git a/agent-context/skills/metaobjects-verify/SKILL.md b/agent-context/skills/metaobjects-verify/SKILL.md index 14b1f94cca..4ec6d5567a 100644 --- a/agent-context/skills/metaobjects-verify/SKILL.md +++ b/agent-context/skills/metaobjects-verify/SKILL.md @@ -93,8 +93,8 @@ always means "found nothing", never "never looked"; what the payload does not ca is named in its own `notRepresented[]`. **A bare `verify` runs the code gates, not the database gate.** In every port a bare -run covers codegen drift (stale generated code), prompt-template drift and the -requirement ledger, paired with the advisory anti-pattern pass above. `verify --db +run covers codegen drift (stale generated code), prompt-template drift, the +requirement ledger and the business-rules gate, paired with the advisory anti-pattern pass above. `verify --db `, `--deps` and `--replay` stay opt-in (`--db` is Node `meta` only). A bare run skips a gate it has no configuration for and says so in one line: Node `meta` with no `metaobjects.config.ts`, Python with no `metaobjects.config.yaml`, `dotnet meta` diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index bd9b129eac..b088cd05f3 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -1,6 +1,6 @@ # Conformance coverage -The MetaObjects standard ships **42 shared conformance corpora** under +The MetaObjects standard ships **43 shared conformance corpora** under [`fixtures/`](../fixtures/). Every port runs every corpus that is *applicable to it* and asserts the same expected behaviour against the same fixtures. **This page is the inverse index**: fixture → feature doc + per-port pass status, and it is the @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 526 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 574 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 18 / 19 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -53,24 +53,25 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (serializer arm: the 9 publish cases' document bytes; no publisher) | | [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) | 5 | ✓ (the emitter is TS-owned) | — | — | — | — | | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) | 1 | ✓ (docs emit is TS-owned) | — | — | — | — | -| [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 12 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | +| [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/requirement-check-conformance/`](../fixtures/requirement-check-conformance/) (the `verify` requirement gate, ADR-0057) | 43 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | -| [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 26 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | +| [`fixtures/requirement-check-conformance/`](../fixtures/requirement-check-conformance/) (the `verify` requirement gate, ADR-0057) | 49 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | +| [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 27 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | +| [`fixtures/rules-check-conformance/`](../fixtures/rules-check-conformance/) (the `verify` business-rules gate, ADR-0066) | 16 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | | [`fixtures/naming-conformance/`](../fixtures/naming-conformance/) | 8 cases + 23 collection segments (`@collectionName`, `naming.collections`) | ✓ | ✓ | inherits via Java (`RouteNaming.pluralize`, `RouteNaming.collectionSegment`) | ✓ | ✓ | | [`fixtures/wire-conformance/`](../fixtures/wire-conformance/) (the `wire` setting, ADR-0019 Amendment 2) | 6 cases + 8 refusals | ✓ | ✓ | inherits via Java (one config reader) | ✓ | ✓ | | [`fixtures/enum-length-conformance/`](../fixtures/enum-length-conformance/) (a string-stored enum's column length: `@maxLength`, else `enums.maxLength`) | 5 cases + 1 overflow + 5 refusals; run by a port that sizes the column | ✓ | ✓ | inherits via Java (one config reader, one resolver) | ✓ | — (sizes no column: emits no DDL or column type; the config reader accepts and shape-checks the `enums` block) | | [`fixtures/check-constraint-conformance/`](../fixtures/check-constraint-conformance/) (the CHECK constraints `meta migrate` derives: name and expression text per dialect) | 1 model, 5 expected files (postgres, sqlite, d1, and both skip-redundant variants) | ✓ (reference, `migrate-ts`) | — (no CHECK in a generated model) | — (same) | ✓ (the EF context declares them; live-Postgres `EnsureCreated` lane) | — (same) | | [`fixtures/foreign-key-index-conformance/`](../fixtures/foreign-key-index-conformance/) (the indexes `migrate.foreignKeyIndexes` adds: which foreign keys are uncovered, and each index's name per dialect, a name over 63 bytes cut on Postgres; and the name each declared `identity.secondary` / `index.lookup` is created under) | 1 model, 4 expected files (FK and declared, postgres and sqlite) | ✓ (reference, `migrate-ts`; the Drizzle tables declare the declared names) | — (no index in a generated model) | ✓ (the Exposed tables declare them) | ✓ (the EF context declares them) | — (same as Java) | | [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json` | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | -| [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (FR-044 — reporting vocabulary: what is lowered, what stays inert) | 1 model pair (`reporting/with` vs `reporting/without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | +| [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | | [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 41 cases (31 core + 10 TypeScript) | ✓ (the first writer; core and TypeScript dialect) | — (writer not built yet) | — (writer not built yet) | — (writer not built yet) | — (writer not built yet) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 19 cases (14 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — | **Rust (preview, ADR-0065) is not a column yet.** The sixth port runs six corpora -today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 526 +today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 574 green, with every validation pass the TypeScript loader runs, in the same order, so `server/rust/metaobjects/tests/conformance-expected-failures.json` is empty; `yaml-conformance`, 18 of 19 (the one on `yaml-conformance-expected-failures.json`, @@ -81,7 +82,7 @@ cases its `gen` can meet (the rest are named with their reason in its runner). T above may only shrink; the skip corpus has none, because each case it runs asserts its result outright. While the port is in preview, 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 the port -leaves preview. A regression still fails: the ledger's `minPassing` (526) is the number of +leaves preview. A regression still fails: the ledger's `minPassing` (574) is the number of fixtures known to pass, and the run fails when fewer do. The column joins this table when the port leaves preview. @@ -109,9 +110,11 @@ the corpora above do two different jobs. Only the first is a promise to adopters `persistence-conformance/` (runtime reads and writes, and the TS-owned migration scenarios), `agent-context-conformance/`, `metamodel-docs/`, `fmt-conformance/` (the canonical serializer, surfaced per-file — ADR-0034's "canonical format" is core), - `field-lint-conformance/` (the advisory field lint every port's `verify` prints) and + `field-lint-conformance/` (the advisory field lint every port's `verify` prints), `requirement-check-conformance/` (the requirement gate every port's `verify` runs; a - drift gate is core, and it is not ejectable in any port). `codegen-skip-conformance/` (ADR-0064: which changes make `gen` render, and what a local `verify --codegen` may answer from the stored key) is core for the same reason. + drift gate is core, and it is not ejectable in any port), + `rules-check-conformance/` (the business-rules gate every port's `verify` runs, ADR-0066) and + `codegen-skip-conformance/` (ADR-0064: which changes make `gen` render, and what a local `verify --codegen` may answer from the stored key), core for the same reason. A red cell here is a MetaObjects bug. - **Template quality checks — not a promise.** The generated lane of `api-contract-conformance/`, `generator-registry-conformance/` (stable generator names), @@ -408,7 +411,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (526) +### `fixtures/conformance/` — metamodel loader + canonical serializer (574) | Fixture prefix | Feature doc | |---|---| @@ -432,6 +435,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. | `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) | | `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)) | +| `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) | | `object-collection-name` | [features/migrations/physical-naming.md](features/migrations/physical-naming.md) (`@collectionName` and the `collections` pluralizer) | | `smoke-empty-metadata` | [features/entities.md](features/entities.md) | @@ -718,9 +722,9 @@ own those two functions), and `server/python/tests/codegen/test_route_path_naming.py` + `server/python/tests/unit/test_fr016_source_name_and_kind_aliases.py` (same split). -### `fixtures/requirement-check-conformance/` (43 cases) +### `fixtures/requirement-check-conformance/` (49 cases) -All 43 cases → [features/requirements.md](features/requirements.md) ("The gate in every +All 49 cases → [features/requirements.md](features/requirements.md) ("The gate in every port"). Each case is a directory: `input/` metadata, an optional `options.json` (`libraries`, `requireImplementers`) and an `expected.json` holding the gate's diagnostics (severity, code, requirement path, message text) and the ledger summary, or `null` for a @@ -735,9 +739,9 @@ a port that disagrees with one is wrong. The case list, and what each pins, is i (Kotlin inherits it, through the shared Maven goal) and `server/csharp/MetaObjects.Conformance.Tests/RequirementCheckConformanceTests.cs`. -### `fixtures/requirement-test-identity-conformance/` (26 cases) +### `fixtures/requirement-test-identity-conformance/` (27 cases) -All 26 cases → [features/requirements.md](features/requirements.md) ("Generated +All 27 cases → [features/requirements.md](features/requirements.md) ("Generated requirement tests and witnesses"). It pins the *identity* of every test the `requirement-tests` generator yields from a ledger (package, path, unit, id, witness key, status, skip state and digest), witness-key collisions, and the view a project's filter @@ -754,6 +758,24 @@ outside ASCII. The case list is in the Kotlin's identity function is the Java one; the names its generator emits are asserted by `server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementTestsGeneratorTest.kt`. +### `fixtures/rules-check-conformance/` (16 cases) + +All 16 cases → [features/business-rules.md](features/business-rules.md) ("What `verify` +reports"). Each case is a directory: `input/` metadata, an optional `options.json` (the +`rules` and `verify` blocks of `.metaobjects/config.json`, read through each port's own config +reader) and an `expected.json` holding the gate's diagnostics (severity, code, node address, +message text) and its summary counts, or `null` for a model with no operation and no +transition. The expectations are written from the TypeScript reference +(`scripts/write-requirement-corpus-expected.ts rules`). The case list is in the +[corpus README](../fixtures/rules-check-conformance/README.md). + +**Every port's `verify` is held to it:** +`server/typescript/packages/cli/test/rules-check-conformance.test.ts`, +`server/csharp/MetaObjects.Conformance.Tests/RulesCheckConformanceTests.cs`, +`server/java/metadata/src/test/java/com/metaobjects/conformance/RulesCheckConformanceTest.java` +and `server/python/tests/conformance/test_rules_check_conformance.py`. Kotlin inherits the Java +gate through the shared Maven goal. + ### `fixtures/cube-model/` (46 cases) All 46 cases and the canonical golden → [features/cube-export.md](features/cube-export.md). @@ -787,9 +809,9 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 526 + yaml 19 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 574 + yaml 19 + verify 45 + render 18 + persistence 67 + api-contract 139 + source-resolution 28 + scope 10 + -dependency 47) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance`, the +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 and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining corpora in the totals table gate tooling contracts (registry manifests, provider composition, agent context, docs emit) rather than user-facing metamodel behaviour, diff --git a/docs/README.md b/docs/README.md index f09826a23c..d297cf69ea 100644 --- a/docs/README.md +++ b/docs/README.md @@ -46,6 +46,7 @@ docs/ │ ├── metadata-dependencies.md # building on a metadata model published elsewhere (FR-023) │ ├── libraries.md # reusable declared design you opt into, a layer at a time (FR-043) │ ├── reporting.md # dimensions, measures, segments, reports: vocabulary and load rules (FR-044) +│ ├── business-rules.md # operations, permission names and lifecycles: vocabulary, load rules, verify checks (ADR-0066) │ ├── contract-emitters.md # the contract-schema and openapi generators: JSON Schema and OpenAPI for the REST contract (FR-022) │ ├── cube-export.md # the cube-model generator: reporting vocabulary as Cube data-model files (FR-044) │ ├── explorer-data.md # explorer.json and its inputs: export --effective, the verify ledger rows, manifest provenance @@ -77,6 +78,7 @@ this tree is documentation, not the source of truth. | Build on a metadata model another repository publishes (`dependencies`, `meta deps sync`, overlay/extend across the boundary) | [`features/metadata-dependencies.md`](features/metadata-dependencies.md) | | Adopt a design MetaObjects already ships — users/groups/roles, an LLM trace envelope — instead of authoring it (`libraries`, `meta eject `) | [`features/libraries.md`](features/libraries.md) | | Record what the system is supposed to do, and stop agents reviving retired features | [`features/requirements.md`](features/requirements.md) | +| Declare what the application does: named commands and queries, who may run them, and the allowed moves of a status field (`api.operational`, `operation.*`, `transition.action`; load-time checked, with a rules gate in `verify`) | [`features/business-rules.md`](features/business-rules.md) | | Declare what a dashboard groups by and counts (`dimension`, `measure`, `segment`, `object.report`; load-time checked; a view-backed report becomes a SQL view served by a generated read-only list route and a TypeScript list hook) | [`features/reporting.md`](features/reporting.md) | | Download a report as CSV, JSON or XML (`?format=`, the `report-export` generator, its cap and null forms) | [`features/reporting.md`](features/reporting.md#exporting-a-report) | | Move existing Zod, Drizzle or Pydantic models into the model, and prove the generated types match before you switch | [`features/adopting-existing-models.md`](features/adopting-existing-models.md) | diff --git a/docs/case-study-requirements-first.md b/docs/case-study-requirements-first.md index 0f18b02d8f..a8b0f475bd 100644 --- a/docs/case-study-requirements-first.md +++ b/docs/case-study-requirements-first.md @@ -60,7 +60,7 @@ That was a **modelling error, not a tool limitation**, and it is worth stating p is an easy one to repeat: > `@implementedBy` is legal at **L4/L5 only**, and **L5 names a member** — a field, a view, a -> validator, an identity, or a template's child. +> validator, an identity, a template's child, an operation or a transition. So a live-system fact is not an annotation hung off a requirement. It is modelled as an object, a field, or a validator, and the requirement **tags that member**. No oracle attribute is needed diff --git a/docs/compatibility-policy.md b/docs/compatibility-policy.md index 47fe1ba379..9d29c39b7b 100644 --- a/docs/compatibility-policy.md +++ b/docs/compatibility-policy.md @@ -72,8 +72,16 @@ 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-but-unregistered declared-API vocabulary `api.*`/`operation.*`/ - `binding.*`, and reserved index subtypes `index.fulltext`/`vector`/`spatial`). + (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`). +- **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 + rules, `verify` checks and `rules`/`verify.lifecycle` settings. The shape may change in a + MINOR, including removals and renames, as for a `preview` library below. It is promoted to + the promise above on evidence: generated services running on it in an adopter estate with the + drift gate enforced. Until then a model that declares none of it is unaffected by any change + to it. ## Shipped libraries (`libraries: [...]`) diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md new file mode 100644 index 0000000000..f101f36725 --- /dev/null +++ b/docs/features/business-rules.md @@ -0,0 +1,260 @@ +# Business rules: operations, permissions and lifecycles + +Declare what your application *does*, beside the entities it does it to: + +- **named commands and queries**, with the shapes they take and return; +- **who may run them**, as a permission name; +- **the allowed moves** between the values of a status field. + +The model never says *how* an operation works. That is code. The model says where a decision +is needed, which moves are legal, and what a command may return, so all three can be checked. + +**What 1.3.0 ships.** The vocabulary, checked when it loads and by `verify`, in all five ports. +The Rust preview port loads the vocabulary and runs the same loader rules; it has no `verify`, +so the checks under "What `verify` reports" do not run there ([Rust port](../ports/rust.md)). +A requirement can claim an operation or a transition. Nothing is generated from the vocabulary +yet: the service shells that enforce these rules at run time are later work (ADR-0067). Until +they land, a model with this vocabulary generates byte-identical code to the same model +without it. The design is [ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md). + +**Experimental.** This vocabulary, its loader rules, its `verify` checks and its settings may +change in a MINOR, including removals and renames, until generated services run on it in an +adopter estate ([compatibility policy](../compatibility-policy.md)). A model that declares none +of it is unaffected. + +## An example + +```yaml +metadata: + 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.long: { name: total } + - field.enum: + name: status + values: [draft, submitted, approved, rejected] + default: draft # the initial state + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - transition.action: + name: approve + from: [submitted] + to: approved + condition: { op: lte, left: { field: total }, right: { value: 50000 } } + - transition.action: { name: reject, from: [submitted], to: rejected } + + - object.value: + name: DecisionInput + children: + - field.long: { name: requestId, extends: PurchaseRequest.id } # borrows the key: the target is derived + + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: DecisionInput + transitions: [approve, reject] # claims both: they derive no command of their own + permission: purchasing.decide # so this is the permission that guards them + errors: [limit_exceeded] + - operation.query: + name: openRequests + outputRef: PurchaseRequest + many: true + public: true +``` + +## Operations + +An `api.operational` is a named, packaged surface at the top of a document. Its children are +operations: + +- **`operation.command`** changes state. It takes an `object.value` as input. +- **`operation.query`** reads. It returns an entity, a projection or a value. + +| Attribute | On | Meaning | +|---|---|---| +| `inputRef` | both | The input, an `object.value`. A query whose only parameter is its target's key needs none. | +| `outputRef` | both | What it returns: an `object.entity`, `object.projection` or `object.value`. | +| `many` | query | It returns a list, with the filter, sort and paging contract of a generated list. | +| `objectRef` | both | The target entity. Declare it only when it cannot be derived (below). | +| `transitions` | command | The transitions of its target that it may make. | +| `permission` | both | The permission name the policy is asked about: a dotted identifier path such as `purchasing.approve`. Several operations may share one. | +| `public` | both | `true`: no permission check. Cannot be combined with `permission`. | +| `errors` | command | The business errors its body may return, as lower snake case codes. | + +**The target entity is derived** when it can be: + +1. from the one entity whose whole primary key the input borrows, each key field extended by + exactly one field of the input (`requestId extends PurchaseRequest.id` above). An input that + borrows part of a composite key, one key field twice (`fromId` and `toId`), or the keys of + two entities derives nothing from the input; +2. else from the output: an entity is its own target, and a projection's target is its base + entity. + +Declare `objectRef` only for an operation with nothing to derive from, such as a command that +creates or imports. When you declare it and a target also derives, the two must agree. + +**`binding.rest`** is an optional child of an operation that overrides the derived HTTP +binding: + +- `method` is one of `GET`, `POST`, `PUT`, `PATCH`, `DELETE`. When absent, a query is `GET` and + a command is `POST`. +- `path` is a path template. Its `{placeholders}` must be the target's key fields when the + operation addresses one row by key, and must be empty when it does not. Two declared bindings + of one API may not have the same method and path. + +Most models never write a binding. + +## Lifecycles + +A `transition.action` is a child of a `field.enum` on an `object.entity`. An enum field with at +least one transition **is** a lifecycle. Nothing else needs declaring, because the rest is +derived: + +| Derived | From | +|---|---| +| The states | the enum's `values` | +| The initial state | the enum's `default` (required once the field has a transition) | +| The terminal states | the members no transition leaves | +| A transition's command | every transition that no declared command lists in `transitions` gets a command of its own name (setting `rules.lifecycle.commands`) | + +| Attribute | Meaning | +|---|---| +| `from` | The states the move starts from: members of the enum. | +| `to` | The state it ends in. It may be one of `from`, which records an action that changes nothing. | +| `condition` | A guard over the entity's own fields, in the same grammar as a cross-field validator's `condition`. | +| `permission`, `public` | As on operations. They apply to the transition's derived command only: when a declared command claims the transition, the command's own `permission` guards it, and `verify` warns that the transition's is never read. | + +A transition declared on an abstract base entity's field belongs to every entity that extends +it. It does not belong to an entity whose field merely `extends` the lifecycle field: a status +history table that borrows the enum's values has no lifecycle. An entity that extends the base +and redeclares the field must extend the base's field too, or the loader refuses it +(`ERR_LIFECYCLE_REDECLARED`). `transition.timed`, a move made by time rather than by a command, is reserved and not yet +registered. + +**A lifecycle on an entity with no source is inert.** It loads and is checked for shape, but +nothing is derived from it until the entity gets a source, declared or inherited; from then on +the source must be writable. A library's core layer, which declares no source, can carry its +lifecycles this way, and its `db` layer makes them live. + +**Permission names.** Every operation and every derived command asks the project's policy +about a permission name. A declared `permission` is a dotted identifier path: names of letters, +digits and `_` joined by `.`, such as `purchasing.approve`. When `permission` is absent, the name +is derived and includes its owner: + +- a declared operation: `.`, with its API's package. Operation names are + unique across the APIs of a package, so two operations never share one by accident. Two + APIs may expose the same operation by declaring it identically, and then share its name; +- a transition's derived command: `..`, so `Order.cancel` and + `Invoice.cancel` ask about different permissions. Above, `submit` derives + `acme::purchasing.PurchaseRequest.submit`. + +A package prefix may use `::`, so a derived name can be declared as it is. A derived name +changes when the operation, transition or entity is renamed, which silently moves access. The +setting `rules.permissions.names` makes `verify` warn about derived names, or fail on them. + +## What the loader refuses + +| 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. | +| 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. | +| L6 | `ERR_TRANSITION_NAME_COLLISION` | Two transitions of one entity share a name, across all its lifecycles, compared without case. | +| L7 | `ERR_BAD_ATTR_VALUE` | A `condition` names a field the entity does not have, or is not boolean. | +| L8 | `ERR_BAD_ATTR_VALUE` | A transition's `from` is empty. | +| L9 | `ERR_BAD_ATTR_VALUE` | The lifecycle field is an array (`isArray: true`). | +| L10 | `ERR_LIFECYCLE_REDECLARED` | An entity redeclares an inherited lifecycle field without extending it, dropping the base's transitions. | +| P1 | `ERR_PERMISSION_PUBLIC_CONFLICT` | `public: true` together with `permission`. | +| P2 | `ERR_BAD_ATTR_VALUE` | A `permission` is not a dotted identifier path. | +| O1 | `ERR_OPERATION_SHAPE` | `inputRef` is not an `object.value`, or `outputRef` is not an entity, projection or value. | +| O2 | `ERR_OPERATION_TARGET_UNRESOLVED` | `objectRef` is not an `object.entity`, or a command lists `transitions` and has no target. | +| O3 | `ERR_OPERATION_TARGET_MISMATCH` | A declared `objectRef` disagrees with the derived target. | +| O4 | `ERR_OPERATION_UNKNOWN_TRANSITION` | A `transitions` name is not a transition of the target. | +| O5 | `ERR_BAD_ATTR_VALUE` | An `errors` code is not lower snake case, is listed 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`. | +| O6 | `ERR_TRANSITION_NAME_COLLISION` | Two operations of one package share a name, compared without case, in one API or across the package's APIs. One operation declared in two files merges and is not refused. Neither is one operation declared identically in two APIs (a `v1` beside a `v2`): same name, subtype and every operation attribute; only the bindings may differ. | +| 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. | + +Names are compared without case because each one becomes a command, a permission constant and a +file, and those collide on a case-folding target. + +Some refusals come from the registry: + +- `many` on a command is `ERR_UNKNOWN_ATTR`. +- A `method` outside its set is `ERR_BAD_ATTR_VALUE`. +- An authored `operation.base` is `ERR_ABSTRACT_SUBTYPE_AUTHORED`. +- An `api.operational` anywhere but the top of a document is `ERR_CHILD_NOT_ALLOWED`. + +Each case is pinned in `fixtures/conformance/` (`error-rules-*`). + +## What `verify` reports + +`verify` in every port runs a rules gate. When the model declares an operation or a +transition, it prints one line: + +``` +meta verify — rules: 2 operation(s), 1 lifecycle(s) with 3 transition(s). +``` + +and reports: + +| Code | Severity | When | +|---|---|---| +| `WARN_LIFECYCLE_UNREACHABLE_STATE` | `verify.lifecycle.unreachable` | A state no chain of transitions reaches from the initial state. | +| `WARN_LIFECYCLE_INITIAL_TERMINAL` | warn | The initial state is terminal, so no row can ever move. | +| `WARN_TRANSITION_UNREACHABLE` | `verify.lifecycle.unreachable` | A transition whose every `from` state is unreachable. | +| `WARN_TRANSITION_PERMISSION_SHADOWED` | warn | A transition declares `permission` or `public: true` but derives no command of its own (every carrier's transition is claimed by a declared command, or `rules.lifecycle.commands` is `none`), so nothing reads it. | +| `WARN_PERMISSION_DERIVED_NAME` | `rules.permissions.names` | An operation, or a transition that derives a command, relies on a derived permission name. The message names it. A transition on an entity with no source derives no command and is not reported. | + +An error-severity finding fails the run. A model with no operation and no transition sees no +line and no finding. The cases are in `fixtures/rules-check-conformance/`. + +## Settings + +These go in `.metaobjects/config.json`, and every port reads them. When a key is absent, the +setting behaves as it does today. + +| Setting | Values | When absent | Effect | +|---|---|---|---| +| `rules.permissions.names` | `derive`, `advise`, `require` | `derive` | `derive` accepts derived permission names. `advise` warns about each one. `require` fails `verify` on each one. | +| `rules.lifecycle.commands` | `unclaimed`, `all`, `none` | `unclaimed` | Which transitions derive a command of their own, and so are permission points: those no declared command claims, every one, or none. A command claims a transition for its target entity and every entity extending it. | +| `rules.lifecycle.create` | `initial`, `any` | `initial` | **No effect yet.** Whether a create may start a row in a state other than the initial one. It is read and validated, and nothing acts on it until the service shells land. | +| `verify.lifecycle.unreachable` | `warn`, `error`, `off` | `warn` | The severity of the two reachability checks. `off` skips them. | + +```json +{ + "rules": { + "permissions": { "names": "advise" }, + "lifecycle": { "commands": "unclaimed", "create": "initial" } + }, + "verify": { "lifecycle": { "unreachable": "warn" } } +} +``` + +## Requirements can claim operations and transitions + +A level 5 requirement's `implementedBy` can name an operation as `.`, or a +transition as `..`. The reference is resolved, not trusted: renaming +the operation fails the build. The generated requirement test for it has the unit +`operation.command`, `operation.query` or `transition.action`. + +```yaml +- requirement.functional: + name: Decided + level: 5 + status: live + statement: A reviewer decides a submitted request. + counterexample: A request that waits forever. + implementedBy: [Purchasing.decide] +``` + +See [requirements](requirements.md). diff --git a/docs/features/cli.md b/docs/features/cli.md index cfa166fbe4..98fd3f9a98 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -65,8 +65,8 @@ Rules of the contract: each selected mode runs and the **exit code is non-zero if *any* mode reports drift**. - **Bare `verify` runs the same default gate set in every port: codegen drift, - prompt templates and the requirement ledger.** `--db`, `--deps` and `--replay` - stay opt-in. A gate the run has no configuration for is skipped with a one-line + prompt templates, the requirement ledger and the business-rules gate.** `--db`, `--deps` + and `--replay` stay opt-in. A gate the run has no configuration for is skipped with a one-line note, never failed: Node `meta` needs a `metaobjects.config.ts` for codegen (a config that exists but fails to load is not a missing config: it exits 2 with the load error); `metaobjects verify` needs a `metaobjects.config.yaml` or `--prompts ` for @@ -167,6 +167,12 @@ Rules of the contract: [`fixtures/requirement-check-conformance/`](../../fixtures/requirement-check-conformance/README.md). The seven requirement *authoring-lint* advisories are still printed by the Node `meta` only. See [requirements.md](requirements.md#the-gate-in-every-port). +- **The business-rules gate runs on every `verify`, in every port** + ([ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)). + It is not a subverb and nothing mutes it. A model with no operation and no transition gets no + line. A model with one gets a summary line, and an error-severity finding exits non-zero. The + codes, settings and the checks are in [business-rules.md](business-rules.md#what-verify-reports). + Rust has no `verify`, so the gate does not run there. ### The prompt directory: `--prompts` everywhere (F101) @@ -667,7 +673,8 @@ meta gen --format json → { gen[], summary, help[], antiPatterns: { status meta verify --format json → { verify[], exitCode, summary, help[], antiPatterns: { status, total, rows[] }, requirements: { status, total, rows[] }, - requirementCounts?, schemaDrift?, notRepresented[] } + requirementCounts?, rules?: { status, total, rows[] }, + rulesCounts?, schemaDrift?, notRepresented[] } ``` A pass that did **not** run says so (`status: "skipped"` with a `note` giving the diff --git a/docs/features/downstream-metadata-decisions.md b/docs/features/downstream-metadata-decisions.md index a9be37d3b5..c37b3a08f5 100644 --- a/docs/features/downstream-metadata-decisions.md +++ b/docs/features/downstream-metadata-decisions.md @@ -44,10 +44,10 @@ Before inventing, converge. Two failure modes to avoid: - **Re-deriving a shape core already ships (or plans).** If the roadmap already charts the concept, model it *in a shape that can fold into the eventual core vocabulary* rather than a divergent one. -- **Claiming a chartered name.** The declared-API surface and ecosystem tier reserve - the type names `api`, `operation`, `surface`, and `binding` for planned core - vocabulary. Do not use those names for a project-local type — a later core release - would force a breaking rename. Pick a project-local name that stays clear of them. +- **Claiming a chartered name.** The declared-API surface (registered as experimental in + 1.3.0, ADR-0066) and ecosystem tier reserve the type names `api`, `operation`, `surface`, + and `binding` for core vocabulary. Do not use those names for a project-local type — a + core release would force a breaking rename. Pick a project-local name that stays clear of them. ## Step 2 — run the ADR-0037 ordered test @@ -115,7 +115,7 @@ several channels — an HTTP webhook, a chat-room message, a heartbeat ping, a r email handed off to a local mail command, and a local stream write. Walking the ladder: - **Step 0/1:** no shipped subtype covers "outbound delivery channel," and the concept - sits near the (deferred) declared-API + ecosystem-tier roadmap — so model it + sits near the declared-API (experimental since 1.3.0) + ecosystem-tier roadmap — so model it downstream in a fold-in-friendly shape, avoiding the chartered names. - **Step 2:** "delivery channel" is a genuine thing with its own behavior and config (step 3) → a project-registered subtype; the individual channels are a closed diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index b59d8c57cb..52ccd50746 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -732,7 +732,7 @@ Postgres's text. If the metadata does not load, the baseline is written as befor ## Drift verify commands per port A bare `verify` runs the same default gate set in every port: **codegen drift**, -**prompt-template drift** and the **requirement ledger**. What a check does when the run has +**prompt-template drift**, the **requirement ledger** and the **business-rules gate**. What a check does when the run has no configuration for it differs by port. TypeScript, Java and Python skip it with a one-line note and do not fail: TypeScript skips the codegen gate when there is no `metaobjects.config.ts` (and its template gate passes with a note when the model has no `template.*` nodes), Java skips diff --git a/docs/features/migrations/0.x-to-1.0.md b/docs/features/migrations/0.x-to-1.0.md index 164ad00003..201d39e28b 100644 --- a/docs/features/migrations/0.x-to-1.0.md +++ b/docs/features/migrations/0.x-to-1.0.md @@ -429,6 +429,8 @@ first `metaobjects gen` after upgrading will rewrite the keys; commit the result ## Not in 1.0: the declared-API surface (FR-024) -`api.*` / `operation.*` / `binding.*` are **deferred** post-1.0 (reserved but -unregistered). Nothing to migrate; they can be added later without a breaking change. +`api.*` / `operation.*` / `binding.*` were **deferred** past 1.0 (reserved but +unregistered). They were registered as experimental in 1.3.0 +([business rules](../business-rules.md)). Nothing to migrate; they were added without a +breaking change. Derived CRUD remains the zero-config default. (Tracked in #10.) diff --git a/docs/features/requirements.md b/docs/features/requirements.md index d75e41ef9a..9b04b916fc 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -72,7 +72,8 @@ organisational and never reference the model. `template.*`**. A declared prompt is a model node realising a capability in the same sense an entity is — and it is the one most in need of a status, because a retired prompt leaves no table behind to notice. L5 names a member of one: a field, a view, a validator, an -identity, or a template's child. +identity, a template's child, an operation of an `api.operational`, or a transition of a +lifecycle ([business rules](business-rules.md)). ```jsonc { "requirement.functional": { diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 23a333b1e4..e72a40b341 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -1150,6 +1150,7 @@ generated code), and no `migrate` surface (schema is TypeScript-owned). | Drift verify | `dotnet meta verify` (template drift, FR-004; `--codegen` regenerates the list in `codegen/Generators.cs` and diffs it) | | API reference docs | Yes — the `ApiDocsGenerator` entry in `codegen/Generators.cs` (`OutDir`, `ApiSubDir`, `ProjectName`, `ModelBaseUrl`); `dotnet meta docs` was removed in 1.1.0 ([migration](../features/migrations/docs-are-generators.md#c)) | | Requirement gate + requirement tests | Yes (`dotnet meta verify`, on every run; `requirement-tests` emits xUnit and is ejectable) | +| Business-rules gate (ADR-0066, experimental) | Yes (`dotnet meta verify`, on every run; see [business rules](../features/business-rules.md)) | | Runtime metadata | Loader API + render engine; ObjectManager-style runtime tier on the roadmap | ## Conformance status diff --git a/docs/ports/java.md b/docs/ports/java.md index 275fbe043c..c67e36673c 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -1068,6 +1068,7 @@ an int-backed enum carries `dbValue()` and `fromDbValue(int)`, and the payload t | Migrations | TS-only (`@metaobjectsdev/cli migrate`) — the Java migration engine and the OMDB runtime auto-create path were both removed (ADR-0015); apply the TS-produced DDL to the database | | Drift verify | `Verify.check` / `Verify.checkOutputPrompt` (prompts). Live-DB schema-drift verification is part of the TS migration toolchain | | Requirement gate + requirement tests | Yes (`mvn metaobjects:verify`, on every run; `JUnitRequirementTestsGenerator` emits JUnit Jupiter and is ejectable) | +| Business-rules gate (ADR-0066, experimental) | Yes (`mvn metaobjects:verify`, on every run; see [business rules](../features/business-rules.md)) | | Runtime metadata | Full — OMDB ObjectManager | | REST controller codegen | Spring Web MVC — `metaobjects-codegen-spring` (FR-008 §2.1) | diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index 17b9253da9..6ff94a2ba3 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -984,6 +984,7 @@ reason. | Migrations | Via the TS toolchain (`@metaobjectsdev/cli migrate`) | | Drift verify | Template-drift: `Renderer.verify` (build-time); generated-table drift: `MetadataStartupValidator` (startup) | | Requirement gate + requirement tests | Yes (`mvn metaobjects:verify`, the Java goal; `KotlinRequirementTestsGenerator` emits JUnit Jupiter and is ejectable) | +| Business-rules gate (ADR-0066, experimental) | Yes (`mvn metaobjects:verify`, the Java goal; see [business rules](../features/business-rules.md)) | | Runtime metadata | Via Java OMDB (or hand-written Exposed transactions) | ## Test count diff --git a/docs/ports/python.md b/docs/ports/python.md index 80bbd0ced2..b08c562d12 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -1066,6 +1066,7 @@ import lines are stable. | Drift verify | Yes — template / payload drift (`metaobjects verify`); `verify --codegen` regenerates the config's list and diffs each target's `outDir` | | API reference docs | Yes — `api-docs` in a target's `generators`, options in the top-level `apiDocs` block (`apiSubDir`, `projectName`, `modelBaseUrl`); `metaobjects docs` was removed in 1.1.0 ([migration](../features/migrations/docs-are-generators.md#python)) | | Requirement gate + requirement tests | Yes (`metaobjects verify`, on every run; `requirement-tests` emits pytest and is ejectable) | +| Business-rules gate (ADR-0066, experimental) | Yes (`metaobjects verify`, on every run; see [business rules](../features/business-rules.md)) | | Runtime metadata | Yes (`metaobjects.runtime.ObjectManager` — DB-API 2 drivers: Postgres via pg8000/psycopg, `SqliteDriver` over the standard library's `sqlite3`, `MySqlDriver` over PyMySQL with the `mysql` extra) + loader API + render engine | ## Conformance status (as of 2026-05-27) diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 4496e80cda..5a6e803851 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -21,7 +21,7 @@ The loader is the `metaobjects` crate, and the workspace at `server/rust/` adds | Project resolution | Reads `.metaobjects/config.json` and resolves sources the way every port does: the four source kinds, directory discovery (symlinks followed, `_pending` skipped), and the `iam` and `ai` library sources, which are embedded in the crate so a library resolves with no file on disk. See [Metadata sources](../features/metadata-sources.md). | | Naming | The naming strategies, the pluralizers and the collection-name collision check ([ADR-0058](../../spec/decisions/ADR-0058-one-physical-naming-setting.md)). | | Registry | The type registry and the built-in providers. It is strict and sealed after bootstrap, with the same `ERR_*` codes as the other ports. | -| Validation | All 40 validation passes the TypeScript loader runs, in the same order. The ordered list is `PASSES` in `server/rust/metaobjects/src/validate/mod.rs`. | +| Validation | All 41 validation passes the TypeScript loader runs, in the same order, the business-rules pass among them (operations, permission names and lifecycles, [ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)). The ordered list is `PASSES` in `server/rust/metaobjects/src/validate/mod.rs`. | | Serializer | The canonical serializer. A tree it loads serializes to the same bytes the other ports write. | | Frozen tree | The loader freezes the tree when it finishes. A frozen tree memoizes its resolved reads (effective children, attributes and array-ness), so many readers can share one. | | Timings | Every load records how long each phase and each validation pass took (`LoadResult::timings`). | @@ -38,7 +38,7 @@ pass (`minPassing`) and may only shrink. `registry-conformance` (a byte-for-byte | Corpus | Rust today | |---|---| | `registry-conformance` | byte-identical manifest | -| `conformance` (the metamodel corpus) | **526 of 526**, and the ledger is empty | +| `conformance` (the metamodel corpus) | **574 of 574**, and the ledger is empty | | `yaml-conformance` | 18 of 19. The one on the ledger, `yaml-ref-root-escape`, waits for the root-level `::` reference rules of [ADR-0059](../../spec/decisions/ADR-0059-references-resolve-once-after-the-tree.md), which are reference resolution, not a validation pass. | | `source-resolution-conformance` | all 28 cases | | `naming-conformance` | all of it | @@ -66,7 +66,7 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to - **Other `cargo meta` commands.** Only `gen` exists: no `init`, `eject`, `verify` or `fmt`. The command is a Cargo subcommand (a `cargo-meta` binary), the way the other build-tool-hosted ports spell theirs (`dotnet meta`, `mvn metaobjects:...`). A bare `meta` stays the Node schema CLI. -- **Drift checks.** There is no `verify` for Rust yet, so nothing compares generated Rust to the model. +- **Drift checks.** There is no `verify` for Rust yet, so nothing compares generated Rust to the model. That includes the business-rules checks `verify` runs in the other ports (an unreachable state, a permission name left to derive): the loader refuses a broken operation or lifecycle, and the port reads and validates the `rules` and `verify.lifecycle` settings, but nothing reports on them. - **The service tier.** No `ObjectManager`, no persistence drivers and no web adapters. - **Templates and prompts.** No render engine, no payload value objects and no output parser. - **Publication.** The crate sets `publish = false`. There is no crates.io release, no version policy diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index c61e92fd4a..e2fa545f33 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -1019,6 +1019,7 @@ their own pages: [C#](csharp.md), [Java](java.md#known-gaps), | Templates + render (FR-004) | Yes (Mustache, and Jinja via nunjucks: a `.jinja` / `.j2` / `.jinja2` body, ADR-0061) | | Output parser codegen (FR-006) | Yes (`outputParser()` — Zod dual API) | | Requirement gate + requirement tests | Yes (`meta verify`; `requirementTests()`, ejectable) | +| Business-rules gate (ADR-0066, experimental) | Yes (`meta verify`; see [business rules](../features/business-rules.md)) | | Cube export (FR-044) | Yes (`cubeModel()`, ejectable; TypeScript only) | | Payload-VO codegen | Yes (via projection codegen) | | Migrations | `meta migrate` (Postgres / SQLite / D1) | diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 2e8db74b6a..d8b4588ba2 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,9 +7,9 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 526, - "corpora": 42, - "baseTypes": 17 + "fixtures": 574, + "corpora": 43, + "baseTypes": 21 }, "snippets": { "showcase-model": { diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md index 6b9e72a398..8642c4e397 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -32,7 +32,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. +- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 5741cf9de1..0a892f296c 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -362,10 +362,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — planned, not yet shipped:** the declared-API surface (`api.base`, - `api.operational`, `operation.query`, `operation.command`, `binding.rest`) and MCP exposure - of declared prompts/tools are **not yet in the registry** — their absence is not an adopter - defect; do NOT audit for them. +- **CALIBRATION — registered, nothing generated yet:** the declared-API surface + (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles + (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at + load and by `verify`, but no generator emits from them yet. Their absence is not an adopter + defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* version drift (mixed package versions within one port, or a runtime package in diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md index 58c7f3feb5..e3c3b4737c 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md @@ -228,9 +228,9 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in Exposed `T.update({ (T.id eq id) and (T.status eq ) })` on Kotlin; EF Core `ExecuteUpdateAsync` after a `Where(x => x.Status == )` on C#. Each checks the affected-row count. `` is the generated enum constant, never a literal (signature 13 in - `drift-signatures.md`). **If the allowed transitions need a declared form, that is a question - for the human, never a new attribute** (ADR-0023): the sketch proposes the ORM guard and - records the transition table as an open decision. Pillar `runtime`, surface `repository`. + `drift-signatures.md`). **The allowed transitions have a declared form**, `transition.action` + under a `field.enum` (ADR-0066, experimental): cite that table in the sketch, never a new + attribute (ADR-0023). The sketch proposes the ORM guard. Pillar `runtime`, surface `repository`. - [ ] **H. Authoring-correctness / ADR-conformance (deep).** Invented/unregistered `@`-attrs or post-bootstrap registration (ADR-0023 — custom attrs belong in a registered diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/requirements.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/requirements.md index abd10504a0..e2e63964d2 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/requirements.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/requirements.md @@ -113,7 +113,7 @@ the loader requires those attrs to exist, never to say anything. **Hierarchy is nesting, and links live at the bottom.** L1 solution, L2 segment, L3 service — these never reference the model. **L4** binds a declared top-level node — an `object.*` **or a `template.*`** — and **L5** binds a member of one: a field, view, -validator, identity, or a template's child. `implementedBy` above L4 is an error. +validator, identity, a template's child, an operation, or a transition. `implementedBy` above L4 is an error. Regrouping *moves* a node; it does not edit a parent string. **Write an L5 ref as a dotted `pkg::Owner.member` path** — the level and the shape of the diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-verify/SKILL.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-verify/SKILL.md index 14b1f94cca..4ec6d5567a 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-verify/SKILL.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-verify/SKILL.md @@ -93,8 +93,8 @@ always means "found nothing", never "never looked"; what the payload does not ca is named in its own `notRepresented[]`. **A bare `verify` runs the code gates, not the database gate.** In every port a bare -run covers codegen drift (stale generated code), prompt-template drift and the -requirement ledger, paired with the advisory anti-pattern pass above. `verify --db +run covers codegen drift (stale generated code), prompt-template drift, the +requirement ledger and the business-rules gate, paired with the advisory anti-pattern pass above. `verify --db `, `--deps` and `--replay` stay opt-in (`--db` is Node `meta` only). A bare run skips a gate it has no configuration for and says so in one line: Node `meta` with no `metaobjects.config.ts`, Python with no `metaobjects.config.yaml`, `dotnet meta` diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md index 6b9e72a398..8642c4e397 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -32,7 +32,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. +- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 5741cf9de1..0a892f296c 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -362,10 +362,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — planned, not yet shipped:** the declared-API surface (`api.base`, - `api.operational`, `operation.query`, `operation.command`, `binding.rest`) and MCP exposure - of declared prompts/tools are **not yet in the registry** — their absence is not an adopter - defect; do NOT audit for them. +- **CALIBRATION — registered, nothing generated yet:** the declared-API surface + (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles + (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at + load and by `verify`, but no generator emits from them yet. Their absence is not an adopter + defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* version drift (mixed package versions within one port, or a runtime package in diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md index 58c7f3feb5..e3c3b4737c 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md @@ -228,9 +228,9 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in Exposed `T.update({ (T.id eq id) and (T.status eq ) })` on Kotlin; EF Core `ExecuteUpdateAsync` after a `Where(x => x.Status == )` on C#. Each checks the affected-row count. `` is the generated enum constant, never a literal (signature 13 in - `drift-signatures.md`). **If the allowed transitions need a declared form, that is a question - for the human, never a new attribute** (ADR-0023): the sketch proposes the ORM guard and - records the transition table as an open decision. Pillar `runtime`, surface `repository`. + `drift-signatures.md`). **The allowed transitions have a declared form**, `transition.action` + under a `field.enum` (ADR-0066, experimental): cite that table in the sketch, never a new + attribute (ADR-0023). The sketch proposes the ORM guard. Pillar `runtime`, surface `repository`. - [ ] **H. Authoring-correctness / ADR-conformance (deep).** Invented/unregistered `@`-attrs or post-bootstrap registration (ADR-0023 — custom attrs belong in a registered diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/requirements.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/requirements.md index abd10504a0..e2e63964d2 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/requirements.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/requirements.md @@ -113,7 +113,7 @@ the loader requires those attrs to exist, never to say anything. **Hierarchy is nesting, and links live at the bottom.** L1 solution, L2 segment, L3 service — these never reference the model. **L4** binds a declared top-level node — an `object.*` **or a `template.*`** — and **L5** binds a member of one: a field, view, -validator, identity, or a template's child. `implementedBy` above L4 is an error. +validator, identity, a template's child, an operation, or a transition. `implementedBy` above L4 is an error. Regrouping *moves* a node; it does not edit a parent string. **Write an L5 ref as a dotted `pkg::Owner.member` path** — the level and the shape of the diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md index 14b1f94cca..4ec6d5567a 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md @@ -93,8 +93,8 @@ always means "found nothing", never "never looked"; what the payload does not ca is named in its own `notRepresented[]`. **A bare `verify` runs the code gates, not the database gate.** In every port a bare -run covers codegen drift (stale generated code), prompt-template drift and the -requirement ledger, paired with the advisory anti-pattern pass above. `verify --db +run covers codegen drift (stale generated code), prompt-template drift, the +requirement ledger and the business-rules gate, paired with the advisory anti-pattern pass above. `verify --db `, `--deps` and `--replay` stay opt-in (`--db` is Node `meta` only). A bare run skips a gate it has no configuration for and says so in one line: Node `meta` with no `metaobjects.config.ts`, Python with no `metaobjects.config.yaml`, `dotnet meta` diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md index 6b9e72a398..8642c4e397 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -32,7 +32,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. +- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 5741cf9de1..0a892f296c 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -362,10 +362,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — planned, not yet shipped:** the declared-API surface (`api.base`, - `api.operational`, `operation.query`, `operation.command`, `binding.rest`) and MCP exposure - of declared prompts/tools are **not yet in the registry** — their absence is not an adopter - defect; do NOT audit for them. +- **CALIBRATION — registered, nothing generated yet:** the declared-API surface + (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles + (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at + load and by `verify`, but no generator emits from them yet. Their absence is not an adopter + defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* version drift (mixed package versions within one port, or a runtime package in diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md index 58c7f3feb5..e3c3b4737c 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md @@ -228,9 +228,9 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in Exposed `T.update({ (T.id eq id) and (T.status eq ) })` on Kotlin; EF Core `ExecuteUpdateAsync` after a `Where(x => x.Status == )` on C#. Each checks the affected-row count. `` is the generated enum constant, never a literal (signature 13 in - `drift-signatures.md`). **If the allowed transitions need a declared form, that is a question - for the human, never a new attribute** (ADR-0023): the sketch proposes the ORM guard and - records the transition table as an open decision. Pillar `runtime`, surface `repository`. + `drift-signatures.md`). **The allowed transitions have a declared form**, `transition.action` + under a `field.enum` (ADR-0066, experimental): cite that table in the sketch, never a new + attribute (ADR-0023). The sketch proposes the ORM guard. Pillar `runtime`, surface `repository`. - [ ] **H. Authoring-correctness / ADR-conformance (deep).** Invented/unregistered `@`-attrs or post-bootstrap registration (ADR-0023 — custom attrs belong in a registered diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/requirements.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/requirements.md index abd10504a0..e2e63964d2 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/requirements.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/requirements.md @@ -113,7 +113,7 @@ the loader requires those attrs to exist, never to say anything. **Hierarchy is nesting, and links live at the bottom.** L1 solution, L2 segment, L3 service — these never reference the model. **L4** binds a declared top-level node — an `object.*` **or a `template.*`** — and **L5** binds a member of one: a field, view, -validator, identity, or a template's child. `implementedBy` above L4 is an error. +validator, identity, a template's child, an operation, or a transition. `implementedBy` above L4 is an error. Regrouping *moves* a node; it does not edit a parent string. **Write an L5 ref as a dotted `pkg::Owner.member` path** — the level and the shape of the diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-verify/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-verify/SKILL.md index 14b1f94cca..4ec6d5567a 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-verify/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-verify/SKILL.md @@ -93,8 +93,8 @@ always means "found nothing", never "never looked"; what the payload does not ca is named in its own `notRepresented[]`. **A bare `verify` runs the code gates, not the database gate.** In every port a bare -run covers codegen drift (stale generated code), prompt-template drift and the -requirement ledger, paired with the advisory anti-pattern pass above. `verify --db +run covers codegen drift (stale generated code), prompt-template drift, the +requirement ledger and the business-rules gate, paired with the advisory anti-pattern pass above. `verify --db `, `--deps` and `--replay` stay opt-in (`--db` is Node `meta` only). A bare run skips a gate it has no configuration for and says so in one line: Node `meta` with no `metaobjects.config.ts`, Python with no `metaobjects.config.yaml`, `dotnet meta` diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md index 6b9e72a398..8642c4e397 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -32,7 +32,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. +- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 5741cf9de1..0a892f296c 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -362,10 +362,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — planned, not yet shipped:** the declared-API surface (`api.base`, - `api.operational`, `operation.query`, `operation.command`, `binding.rest`) and MCP exposure - of declared prompts/tools are **not yet in the registry** — their absence is not an adopter - defect; do NOT audit for them. +- **CALIBRATION — registered, nothing generated yet:** the declared-API surface + (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles + (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at + load and by `verify`, but no generator emits from them yet. Their absence is not an adopter + defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* version drift (mixed package versions within one port, or a runtime package in diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md index 58c7f3feb5..e3c3b4737c 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md @@ -228,9 +228,9 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in Exposed `T.update({ (T.id eq id) and (T.status eq ) })` on Kotlin; EF Core `ExecuteUpdateAsync` after a `Where(x => x.Status == )` on C#. Each checks the affected-row count. `` is the generated enum constant, never a literal (signature 13 in - `drift-signatures.md`). **If the allowed transitions need a declared form, that is a question - for the human, never a new attribute** (ADR-0023): the sketch proposes the ORM guard and - records the transition table as an open decision. Pillar `runtime`, surface `repository`. + `drift-signatures.md`). **The allowed transitions have a declared form**, `transition.action` + under a `field.enum` (ADR-0066, experimental): cite that table in the sketch, never a new + attribute (ADR-0023). The sketch proposes the ORM guard. Pillar `runtime`, surface `repository`. - [ ] **H. Authoring-correctness / ADR-conformance (deep).** Invented/unregistered `@`-attrs or post-bootstrap registration (ADR-0023 — custom attrs belong in a registered diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/requirements.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/requirements.md index abd10504a0..e2e63964d2 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/requirements.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/requirements.md @@ -113,7 +113,7 @@ the loader requires those attrs to exist, never to say anything. **Hierarchy is nesting, and links live at the bottom.** L1 solution, L2 segment, L3 service — these never reference the model. **L4** binds a declared top-level node — an `object.*` **or a `template.*`** — and **L5** binds a member of one: a field, view, -validator, identity, or a template's child. `implementedBy` above L4 is an error. +validator, identity, a template's child, an operation, or a transition. `implementedBy` above L4 is an error. Regrouping *moves* a node; it does not edit a parent string. **Write an L5 ref as a dotted `pkg::Owner.member` path** — the level and the shape of the diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-verify/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-verify/SKILL.md index 14b1f94cca..4ec6d5567a 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-verify/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-verify/SKILL.md @@ -93,8 +93,8 @@ always means "found nothing", never "never looked"; what the payload does not ca is named in its own `notRepresented[]`. **A bare `verify` runs the code gates, not the database gate.** In every port a bare -run covers codegen drift (stale generated code), prompt-template drift and the -requirement ledger, paired with the advisory anti-pattern pass above. `verify --db +run covers codegen drift (stale generated code), prompt-template drift, the +requirement ledger and the business-rules gate, paired with the advisory anti-pattern pass above. `verify --db `, `--deps` and `--replay` stay opt-in (`--db` is Node `meta` only). A bare run skips a gate it has no configuration for and says so in one line: Node `meta` with no `metaobjects.config.ts`, Python with no `metaobjects.config.yaml`, `dotnet meta` diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md index 6b9e72a398..8642c4e397 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -32,7 +32,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. +- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 5741cf9de1..0a892f296c 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -362,10 +362,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — planned, not yet shipped:** the declared-API surface (`api.base`, - `api.operational`, `operation.query`, `operation.command`, `binding.rest`) and MCP exposure - of declared prompts/tools are **not yet in the registry** — their absence is not an adopter - defect; do NOT audit for them. +- **CALIBRATION — registered, nothing generated yet:** the declared-API surface + (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles + (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at + load and by `verify`, but no generator emits from them yet. Their absence is not an adopter + defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* version drift (mixed package versions within one port, or a runtime package in diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md index 58c7f3feb5..e3c3b4737c 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md @@ -228,9 +228,9 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in Exposed `T.update({ (T.id eq id) and (T.status eq ) })` on Kotlin; EF Core `ExecuteUpdateAsync` after a `Where(x => x.Status == )` on C#. Each checks the affected-row count. `` is the generated enum constant, never a literal (signature 13 in - `drift-signatures.md`). **If the allowed transitions need a declared form, that is a question - for the human, never a new attribute** (ADR-0023): the sketch proposes the ORM guard and - records the transition table as an open decision. Pillar `runtime`, surface `repository`. + `drift-signatures.md`). **The allowed transitions have a declared form**, `transition.action` + under a `field.enum` (ADR-0066, experimental): cite that table in the sketch, never a new + attribute (ADR-0023). The sketch proposes the ORM guard. Pillar `runtime`, surface `repository`. - [ ] **H. Authoring-correctness / ADR-conformance (deep).** Invented/unregistered `@`-attrs or post-bootstrap registration (ADR-0023 — custom attrs belong in a registered diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/requirements.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/requirements.md index abd10504a0..e2e63964d2 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/requirements.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/requirements.md @@ -113,7 +113,7 @@ the loader requires those attrs to exist, never to say anything. **Hierarchy is nesting, and links live at the bottom.** L1 solution, L2 segment, L3 service — these never reference the model. **L4** binds a declared top-level node — an `object.*` **or a `template.*`** — and **L5** binds a member of one: a field, view, -validator, identity, or a template's child. `implementedBy` above L4 is an error. +validator, identity, a template's child, an operation, or a transition. `implementedBy` above L4 is an error. Regrouping *moves* a node; it does not edit a parent string. **Write an L5 ref as a dotted `pkg::Owner.member` path** — the level and the shape of the diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md index 14b1f94cca..4ec6d5567a 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md @@ -93,8 +93,8 @@ always means "found nothing", never "never looked"; what the payload does not ca is named in its own `notRepresented[]`. **A bare `verify` runs the code gates, not the database gate.** In every port a bare -run covers codegen drift (stale generated code), prompt-template drift and the -requirement ledger, paired with the advisory anti-pattern pass above. `verify --db +run covers codegen drift (stale generated code), prompt-template drift, the +requirement ledger and the business-rules gate, paired with the advisory anti-pattern pass above. `verify --db `, `--deps` and `--replay` stay opt-in (`--db` is Node `meta` only). A bare run skips a gate it has no configuration for and says so in one line: Node `meta` with no `metaobjects.config.ts`, Python with no `metaobjects.config.yaml`, `dotnet meta` diff --git a/fixtures/codegen-noop/rules/README.md b/fixtures/codegen-noop/rules/README.md new file mode 100644 index 0000000000..2fb2f4e713 --- /dev/null +++ b/fixtures/codegen-noop/rules/README.md @@ -0,0 +1,36 @@ +# Business-rules vocabulary: inert in every generator (ADR-0066) + +Two models that differ ONLY by the business-rules vocabulary: + +- `without/meta.purchasing.json`: the entity `PurchaseRequest` with its `status` enum, the + value `DecisionInput` and the view-backed projection `RequestSummary`. +- `with/meta.purchasing.json`: the same model plus three `transition.action` children on + `PurchaseRequest.status` and the `api.operational` `Purchasing`, whose three operations + (one carrying a `binding.rest`) take those objects as input and output. It is derived from the + positive conformance fixture `fixtures/conformance/rules-purchase-request/`. + +1.3.0 registers the vocabulary, validates it at load and checks it in `verify`. The +generated services and enforcing shells that act on it are later work, so until they land +the two models produce the same output everywhere: + +- Every code generator in every port writes the same files, byte for byte. +- TypeScript `meta migrate` proposes the same schema. +- Every documentation generator writes the same pages, with one exception: the TypeScript + model explorer (`docs-site`) lists every node of the model in its data payload, so it + lists the `api`, `operation`, `binding` and `transition` nodes as well. Its other output + is byte-identical, and its payload gains only lines of those four types. + +A generator that started reading an operation or a transition by accident would emit +something half-built; these tests are what notice: + +| Port | Test | +|---|---| +| TypeScript | `server/typescript/packages/cli/test/unit/rules-inert.test.ts` (codegen + migrate) | +| C# | `server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs` | +| Java | `server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java` | +| Kotlin | `server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt` | +| Python | `server/python/tests/test_rules_inert.py` | +| Rust (preview) | `server/rust/metaobjects-codegen/tests/rules_inert.rs` (the `entity` generator, the one it has) | + +Regenerate `without/` from `with/` by deleting every `transition.*` child and the +`api.operational` node, nothing else. diff --git a/fixtures/codegen-noop/rules/with/meta.purchasing.json b/fixtures/codegen-noop/rules/with/meta.purchasing.json new file mode 100644 index 0000000000..e3e54c9681 --- /dev/null +++ b/fixtures/codegen-noop/rules/with/meta.purchasing.json @@ -0,0 +1,186 @@ +{ + "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" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/codegen-noop/rules/without/meta.purchasing.json b/fixtures/codegen-noop/rules/without/meta.purchasing.json new file mode 100644 index 0000000000..cb940223d8 --- /dev/null +++ b/fixtures/codegen-noop/rules/without/meta.purchasing.json @@ -0,0 +1,103 @@ +{ + "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" + } + } + ] + } + }, + { + "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" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index 9322a6e9db..757bc735b6 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -97,6 +97,17 @@ "ERR_INVALID_MEASURE": "FR-044: a measure.* is invalid: an @of item is not a field of the owning entity (M1); more than one @of item without @agg: count and @distinct: true (M2); @distinct: true with an @agg other than count (M3); sum/avg over a non-numeric field or min/max over a boolean, object or map field (M4); @segment names no segment of the owning entity (M5); or a measure.ratio @numerator/@denominator does not name a measure.aggregate of the same entity (M6).", "ERR_INVALID_REPORT": "FR-044: an object.report is invalid: @from does not resolve to an object.entity (R1); a @dimensions item names no dimension of @from, omits the grain of a time dimension, uses a grain the dimension does not declare, gives a grain to an attribute dimension, or repeats (R2); a @measures item resolves to no measure at all (R3); the report declares a field.* or identity.* child (R4) or a writable source (R5); two items derive the same report field name (R6); or @segment names no segment of @from (R7).", "ERR_REPORT_FOREIGN_MEASURE": "FR-044: an object.report lists a measure (bare or dotted) that belongs to an entity other than @from (R3). All measures of a report come from @from; combining two fact tables is a second report.", + "ERR_TRANSITION_UNKNOWN_STATE": "ADR-0066 (L4): a transition.action's @from or @to names a value that is not a member of its parent field.enum's @values.", + "ERR_TRANSITION_NOT_ON_ENTITY": "ADR-0066: a transition.action is declared on a field that is not a field of an object.entity (L1: a document-root field, or a field of a value, projection or report), or a concrete entity has a lifecycle and a source but no writable one (L2; reported on the entity). A transition is a guarded update of a stored row; an entity with no source at all may carry a lifecycle, which is inert.", + "ERR_LIFECYCLE_NO_INITIAL": "ADR-0066 (L3): a field.enum declares transitions but no @default. The @default is the lifecycle's initial state; it is never inferred.", + "ERR_LIFECYCLE_REDECLARED": "ADR-0066 (L10): an entity declares a field with the name of an inherited lifecycle field and does not extend it, so the base's transitions would silently stop applying. Extend the base field or name the field differently.", + "ERR_TRANSITION_NAME_COLLISION": "ADR-0066: a transition.action or an operation is named create, get, list, update or delete in any case (the derived CRUD verbs, L5 / O0), two transitions of one entity share a name across its lifecycles (L6; reported on the later one), or two operations of one package share a name, in one API or across its APIs (O6; one operation declared twice merges, and one operation declared identically in two APIs is the same operation, so neither is a collision). Names are compared without case, because a derived command, permission constant or file collides on a case-folding target. Transition names share one namespace per entity because each may derive a command.", + "ERR_OPERATION_TARGET_UNRESOLVED": "ADR-0066 (O2): an operation's @objectRef does not name an object.entity, or an operation.command lists @transitions and has no target entity: none is declared and none derives from its @inputRef (fields extending each primary key field of exactly one entity, each once) or its @outputRef (an entity, or a projection's base entity).", + "ERR_OPERATION_TARGET_MISMATCH": "ADR-0066 (O3): an operation declares @objectRef and its @inputRef / @outputRef derive a different target entity. @objectRef is declared only when the target cannot be derived; when both exist they must agree.", + "ERR_OPERATION_UNKNOWN_TRANSITION": "ADR-0066 (O4): an operation.command's @transitions names something that is not a transition.action of its target entity (declared or inherited).", + "ERR_OPERATION_SHAPE": "ADR-0066 (O1): an operation's @inputRef does not name an object.value, or its @outputRef does not name an object.entity, object.projection or object.value (an unresolved reference included).", + "ERR_PERMISSION_PUBLIC_CONFLICT": "ADR-0066 (P1): an operation or a transition.action declares both @public: true and @permission. A public operation calls no permission check, so the two contradict.", + "ERR_BINDING_PATH_MISMATCH": "ADR-0066 (B1): a binding.rest @path's {placeholders} are not exactly the target entity's primary key fields for an operation that addresses one row by key, or are not empty for one that does not; or (B2) two binding.rest of one API declare the same effective method and the same @path once placeholder names are ignored.", "ERR_COMPUTED_TYPE_MISMATCH": "#195: an origin.computed @expr tree's inferred root type does not equal the carrying field's declared field.. A computed column's type is DERIVED from its expression, never asserted (no @convert escape), so a mismatch is a hard load error (sibling of ERR_PASSTHROUGH_TYPE_MISMATCH).", "ERR_UNKNOWN_EXPR_NODE": "#195: an origin.computed @expr tree contains a node whose kind/op/fn is not in the closed expression grammar (field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now), or a node carries a key its kind does not take (a misspelled `else`, or a `field` node that also carries `case`). Fail-closed per ADR-0023; the detail names the offending token.", "ERR_SQL_BODY_WITH_UNMANAGED": "#208: a source.rdb declares both @sql (author-supplied body) and @unmanaged (DDL owned elsewhere). The two markers are the mutually exclusive non-default states of one DDL-ownership axis — contradictory on a single source.", diff --git a/fixtures/conformance/error-rules-api-not-at-root/expected-errors.json b/fixtures/conformance/error-rules-api-not-at-root/expected-errors.json new file mode 100644 index 0000000000..1cdb09a011 --- /dev/null +++ b/fixtures/conformance/error-rules-api-not-at-root/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_CHILD_NOT_ALLOWED", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-api-not-at-root/input/meta.purchasing.json b/fixtures/conformance/error-rules-api-not-at-root/input/meta.purchasing.json new file mode 100644 index 0000000000..f54041cac5 --- /dev/null +++ b/fixtures/conformance/error-rules-api-not-at-root/input/meta.purchasing.json @@ -0,0 +1,99 @@ +{ + "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" + } + } + ] + } + }, + { + "api.operational": { + "name": "Inner", + "children": [] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-api-not-at-root/providers.json b/fixtures/conformance/error-rules-api-not-at-root/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-api-not-at-root/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-binding-method-invalid/expected-errors.json b/fixtures/conformance/error-rules-binding-method-invalid/expected-errors.json new file mode 100644 index 0000000000..35147d8605 --- /dev/null +++ b/fixtures/conformance/error-rules-binding-method-invalid/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[0]['operation.command'].children[0]['binding.rest']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-binding-method-invalid/input/meta.purchasing.json b/fixtures/conformance/error-rules-binding-method-invalid/input/meta.purchasing.json new file mode 100644 index 0000000000..2fedca2be3 --- /dev/null +++ b/fixtures/conformance/error-rules-binding-method-invalid/input/meta.purchasing.json @@ -0,0 +1,186 @@ +{ + "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": "TRACE", + "@path": "/purchase-requests/{id}/decision" + } + } + ] + } + }, + { + "operation.query": { + "name": "openRequests", + "@outputRef": "RequestSummary", + "@many": true, + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-binding-method-invalid/providers.json b/fixtures/conformance/error-rules-binding-method-invalid/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-binding-method-invalid/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-binding-path-unkeyed/expected-errors.json b/fixtures/conformance/error-rules-binding-path-unkeyed/expected-errors.json new file mode 100644 index 0000000000..293f588216 --- /dev/null +++ b/fixtures/conformance/error-rules-binding-path-unkeyed/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BINDING_PATH_MISMATCH", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[1]['operation.query'].children[0]['binding.rest']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-binding-path-unkeyed/input/meta.purchasing.json b/fixtures/conformance/error-rules-binding-path-unkeyed/input/meta.purchasing.json new file mode 100644 index 0000000000..a3e56f918a --- /dev/null +++ b/fixtures/conformance/error-rules-binding-path-unkeyed/input/meta.purchasing.json @@ -0,0 +1,193 @@ +{ + "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, + "children": [ + { + "binding.rest": { + "@path": "/purchase-requests/{id}/open" + } + } + ] + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-binding-path-unkeyed/providers.json b/fixtures/conformance/error-rules-binding-path-unkeyed/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-binding-path-unkeyed/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-binding-path-wrong-key/expected-errors.json b/fixtures/conformance/error-rules-binding-path-wrong-key/expected-errors.json new file mode 100644 index 0000000000..f47167d00d --- /dev/null +++ b/fixtures/conformance/error-rules-binding-path-wrong-key/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BINDING_PATH_MISMATCH", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[0]['operation.command'].children[0]['binding.rest']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-binding-path-wrong-key/input/meta.purchasing.json b/fixtures/conformance/error-rules-binding-path-wrong-key/input/meta.purchasing.json new file mode 100644 index 0000000000..48a44501b2 --- /dev/null +++ b/fixtures/conformance/error-rules-binding-path-wrong-key/input/meta.purchasing.json @@ -0,0 +1,186 @@ +{ + "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/{requestId}/decision" + } + } + ] + } + }, + { + "operation.query": { + "name": "openRequests", + "@outputRef": "RequestSummary", + "@many": true, + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-binding-path-wrong-key/providers.json b/fixtures/conformance/error-rules-binding-path-wrong-key/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-binding-path-wrong-key/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-binding-route-duplicate/expected-errors.json b/fixtures/conformance/error-rules-binding-route-duplicate/expected-errors.json new file mode 100644 index 0000000000..59845d2580 --- /dev/null +++ b/fixtures/conformance/error-rules-binding-route-duplicate/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BINDING_PATH_MISMATCH", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[2]['api.operational'].children[1]['operation.command'].children[0]['binding.rest']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-binding-route-duplicate/input/meta.purchasing.json b/fixtures/conformance/error-rules-binding-route-duplicate/input/meta.purchasing.json new file mode 100644 index 0000000000..bfc05c84c1 --- /dev/null +++ b/fixtures/conformance/error-rules-binding-route-duplicate/input/meta.purchasing.json @@ -0,0 +1,135 @@ +{ + "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.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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.value": { + "name": "DecisionInput", + "children": [ + { + "field.long": { + "name": "requestId", + "extends": "PurchaseRequest.id" + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "decide", + "@inputRef": "DecisionInput", + "@transitions": [ + "approve", + "reject" + ], + "@permission": "purchasing.decide", + "children": [ + { + "binding.rest": { + "@method": "PUT", + "@path": "/purchase-requests/{id}/decision" + } + } + ] + } + }, + { + "operation.command": { + "name": "redecide", + "@inputRef": "DecisionInput", + "@transitions": [ + "approve" + ], + "@permission": "purchasing.decide", + "children": [ + { + "binding.rest": { + "@method": "PUT", + "@path": "/purchase-requests/{id}/decision" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-binding-route-duplicate/providers.json b/fixtures/conformance/error-rules-binding-route-duplicate/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-binding-route-duplicate/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-lifecycle-array/expected-errors.json b/fixtures/conformance/error-rules-lifecycle-array/expected-errors.json new file mode 100644 index 0000000000..155e056a39 --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-array/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[4]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-lifecycle-array/input/meta.purchasing.json b/fixtures/conformance/error-rules-lifecycle-array/input/meta.purchasing.json new file mode 100644 index 0000000000..e3718b3f26 --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-array/input/meta.purchasing.json @@ -0,0 +1,79 @@ +{ + "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.enum": { + "name": "status", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "@default": "draft", + "isArray": true, + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@from": [ + "submitted" + ], + "@to": "approved" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-lifecycle-array/providers.json b/fixtures/conformance/error-rules-lifecycle-array/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-array/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-lifecycle-no-initial/expected-errors.json b/fixtures/conformance/error-rules-lifecycle-no-initial/expected-errors.json new file mode 100644 index 0000000000..8bc259af69 --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-no-initial/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_LIFECYCLE_NO_INITIAL", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-lifecycle-no-initial/input/meta.purchasing.json b/fixtures/conformance/error-rules-lifecycle-no-initial/input/meta.purchasing.json new file mode 100644 index 0000000000..99393c00a7 --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-no-initial/input/meta.purchasing.json @@ -0,0 +1,92 @@ +{ + "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" + ], + "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" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-lifecycle-no-initial/providers.json b/fixtures/conformance/error-rules-lifecycle-no-initial/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-no-initial/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-lifecycle-readonly-source/expected-errors.json b/fixtures/conformance/error-rules-lifecycle-readonly-source/expected-errors.json new file mode 100644 index 0000000000..d50af48c9e --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-readonly-source/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NOT_ON_ENTITY", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity']" + } + }, + { + "code": "ERR_ENTITY_PRIMARY_SOURCE_READONLY", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[0]['source.rdb']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-lifecycle-readonly-source/input/meta.purchasing.json b/fixtures/conformance/error-rules-lifecycle-readonly-source/input/meta.purchasing.json new file mode 100644 index 0000000000..0a66706fbb --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-readonly-source/input/meta.purchasing.json @@ -0,0 +1,94 @@ +{ + "metadata.root": { + "package": "acme::purchasing", + "children": [ + { + "object.entity": { + "name": "PurchaseRequest", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_pr" + } + }, + { + "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" + } + } + ] + } + } + ] + } + } + ] + } +} \ No newline at end of file diff --git a/fixtures/conformance/error-rules-lifecycle-readonly-source/providers.json b/fixtures/conformance/error-rules-lifecycle-readonly-source/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-readonly-source/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-lifecycle-redeclared/expected-errors.json b/fixtures/conformance/error-rules-lifecycle-redeclared/expected-errors.json new file mode 100644 index 0000000000..2a0c668f9c --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-redeclared/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_LIFECYCLE_REDECLARED", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-lifecycle-redeclared/input/meta.purchasing.json b/fixtures/conformance/error-rules-lifecycle-redeclared/input/meta.purchasing.json new file mode 100644 index 0000000000..9989181277 --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-redeclared/input/meta.purchasing.json @@ -0,0 +1,99 @@ +{ + "metadata.root": { + "package": "acme::purchasing", + "children": [ + { + "object.entity": { + "name": "Request", + "abstract": true, + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.string": { + "name": "title" + } + }, + { + "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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "PurchaseRequest", + "extends": "Request", + "children": [ + { + "source.rdb": { + "@table": "purchase_requests" + } + }, + { + "field.enum": { + "name": "status", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "@default": "draft" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-lifecycle-redeclared/providers.json b/fixtures/conformance/error-rules-lifecycle-redeclared/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-lifecycle-redeclared/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-base-not-authorable/expected-errors.json b/fixtures/conformance/error-rules-operation-base-not-authorable/expected-errors.json new file mode 100644 index 0000000000..fbd57818a2 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-base-not-authorable/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_ABSTRACT_SUBTYPE_AUTHORED", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[3]['operation.base']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-base-not-authorable/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-base-not-authorable/input/meta.purchasing.json new file mode 100644 index 0000000000..a19c5d6e03 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-base-not-authorable/input/meta.purchasing.json @@ -0,0 +1,191 @@ +{ + "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" + } + }, + { + "operation.base": { + "name": "raw" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-base-not-authorable/providers.json b/fixtures/conformance/error-rules-operation-base-not-authorable/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-base-not-authorable/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-case-collision/expected-errors.json b/fixtures/conformance/error-rules-operation-case-collision/expected-errors.json new file mode 100644 index 0000000000..b16854b5cd --- /dev/null +++ b/fixtures/conformance/error-rules-operation-case-collision/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.operational'].children[1]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-case-collision/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-case-collision/input/meta.purchasing.json new file mode 100644 index 0000000000..605b2c026d --- /dev/null +++ b/fixtures/conformance/error-rules-operation-case-collision/input/meta.purchasing.json @@ -0,0 +1,101 @@ +{ + "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.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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@outputRef": "PurchaseRequest", + "@many": true, + "@public": true + } + }, + { + "operation.query": { + "name": "OpenRequests", + "@outputRef": "PurchaseRequest", + "@many": true, + "@public": true + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-case-collision/providers.json b/fixtures/conformance/error-rules-operation-case-collision/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-case-collision/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-error-code-case/expected-errors.json b/fixtures/conformance/error-rules-operation-error-code-case/expected-errors.json new file mode 100644 index 0000000000..4e9bc4f558 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-error-code-case/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[0]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-error-code-case/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-error-code-case/input/meta.purchasing.json new file mode 100644 index 0000000000..2cd0070ed9 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-error-code-case/input/meta.purchasing.json @@ -0,0 +1,185 @@ +{ + "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": [ + "OverBudget" + ], + "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" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-error-code-case/providers.json b/fixtures/conformance/error-rules-operation-error-code-case/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-error-code-case/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-error-code-duplicate/expected-errors.json b/fixtures/conformance/error-rules-operation-error-code-duplicate/expected-errors.json new file mode 100644 index 0000000000..4e9bc4f558 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-error-code-duplicate/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[0]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-error-code-duplicate/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-error-code-duplicate/input/meta.purchasing.json new file mode 100644 index 0000000000..8f5028b8d5 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-error-code-duplicate/input/meta.purchasing.json @@ -0,0 +1,186 @@ +{ + "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", + "over_budget" + ], + "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" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-error-code-duplicate/providers.json b/fixtures/conformance/error-rules-operation-error-code-duplicate/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-error-code-duplicate/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-error-code-reserved/expected-errors.json b/fixtures/conformance/error-rules-operation-error-code-reserved/expected-errors.json new file mode 100644 index 0000000000..43c542d808 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-error-code-reserved/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[2]['api.operational'].children[0]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-error-code-reserved/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-error-code-reserved/input/meta.purchasing.json new file mode 100644 index 0000000000..8ce74aa1a0 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-error-code-reserved/input/meta.purchasing.json @@ -0,0 +1,113 @@ +{ + "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.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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.value": { + "name": "DecisionInput", + "children": [ + { + "field.long": { + "name": "requestId", + "extends": "PurchaseRequest.id" + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "decide", + "@inputRef": "DecisionInput", + "@transitions": [ + "approve", + "reject" + ], + "@permission": "purchasing.decide", + "@errors": [ + "over_budget", + "invalid_transition" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-error-code-reserved/providers.json b/fixtures/conformance/error-rules-operation-error-code-reserved/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-error-code-reserved/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-input-key-twice/expected-errors.json b/fixtures/conformance/error-rules-operation-input-key-twice/expected-errors.json new file mode 100644 index 0000000000..fb39e82031 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-input-key-twice/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_OPERATION_TARGET_UNRESOLVED", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[2]['api.operational'].children[0]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-input-key-twice/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-input-key-twice/input/meta.purchasing.json new file mode 100644 index 0000000000..0529292919 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-input-key-twice/input/meta.purchasing.json @@ -0,0 +1,114 @@ +{ + "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.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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.value": { + "name": "MergeInput", + "children": [ + { + "field.long": { + "name": "fromId", + "extends": "PurchaseRequest.id" + } + }, + { + "field.long": { + "name": "toId", + "extends": "PurchaseRequest.id" + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "merge", + "@inputRef": "MergeInput", + "@transitions": [ + "reject" + ], + "@permission": "purchasing.merge" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-input-key-twice/providers.json b/fixtures/conformance/error-rules-operation-input-key-twice/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-input-key-twice/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-input-not-value/expected-errors.json b/fixtures/conformance/error-rules-operation-input-not-value/expected-errors.json new file mode 100644 index 0000000000..f0c87884cb --- /dev/null +++ b/fixtures/conformance/error-rules-operation-input-not-value/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_OPERATION_SHAPE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[0]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-input-not-value/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-input-not-value/input/meta.purchasing.json new file mode 100644 index 0000000000..a8e5a55b6b --- /dev/null +++ b/fixtures/conformance/error-rules-operation-input-not-value/input/meta.purchasing.json @@ -0,0 +1,186 @@ +{ + "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": "PurchaseRequest", + "@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" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-input-not-value/providers.json b/fixtures/conformance/error-rules-operation-input-not-value/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-input-not-value/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-input-partial-key/expected-errors.json b/fixtures/conformance/error-rules-operation-input-partial-key/expected-errors.json new file mode 100644 index 0000000000..fb39e82031 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-input-partial-key/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_OPERATION_TARGET_UNRESOLVED", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[2]['api.operational'].children[0]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-input-partial-key/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-input-partial-key/input/meta.purchasing.json new file mode 100644 index 0000000000..3f95fc0afc --- /dev/null +++ b/fixtures/conformance/error-rules-operation-input-partial-key/input/meta.purchasing.json @@ -0,0 +1,115 @@ +{ + "metadata.root": { + "package": "acme::purchasing", + "children": [ + { + "object.entity": { + "name": "PurchaseRequest", + "children": [ + { + "source.rdb": { + "@table": "purchase_requests" + } + }, + { + "field.long": { + "name": "orgId" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "orgId", + "id" + ] + } + }, + { + "field.string": { + "name": "title" + } + }, + { + "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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.value": { + "name": "DecisionInput", + "children": [ + { + "field.long": { + "name": "requestId", + "extends": "PurchaseRequest.id" + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "decide", + "@inputRef": "DecisionInput", + "@transitions": [ + "approve", + "reject" + ], + "@permission": "purchasing.decide" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-input-partial-key/providers.json b/fixtures/conformance/error-rules-operation-input-partial-key/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-input-partial-key/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-many-on-command/expected-errors.json b/fixtures/conformance/error-rules-operation-many-on-command/expected-errors.json new file mode 100644 index 0000000000..02441a81b2 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-many-on-command/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_ATTR", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[0]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-many-on-command/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-many-on-command/input/meta.purchasing.json new file mode 100644 index 0000000000..45e42668a6 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-many-on-command/input/meta.purchasing.json @@ -0,0 +1,187 @@ +{ + "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" + } + } + ], + "@many": true + } + }, + { + "operation.query": { + "name": "openRequests", + "@outputRef": "RequestSummary", + "@many": true, + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-many-on-command/providers.json b/fixtures/conformance/error-rules-operation-many-on-command/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-many-on-command/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-name-across-apis/expected-errors.json b/fixtures/conformance/error-rules-operation-name-across-apis/expected-errors.json new file mode 100644 index 0000000000..a8d871ec17 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-name-across-apis/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[2]['api.operational'].children[0]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-name-across-apis/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-name-across-apis/input/meta.purchasing.json new file mode 100644 index 0000000000..f26565f829 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-name-across-apis/input/meta.purchasing.json @@ -0,0 +1,108 @@ +{ + "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.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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@outputRef": "PurchaseRequest", + "@many": true, + "@public": true + } + } + ] + } + }, + { + "api.operational": { + "name": "Review", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@outputRef": "PurchaseRequest", + "@many": true, + "@permission": "review.openRequests" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-name-across-apis/providers.json b/fixtures/conformance/error-rules-operation-name-across-apis/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-name-across-apis/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-output-unresolved/expected-errors.json b/fixtures/conformance/error-rules-operation-output-unresolved/expected-errors.json new file mode 100644 index 0000000000..1e424053dd --- /dev/null +++ b/fixtures/conformance/error-rules-operation-output-unresolved/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_OPERATION_SHAPE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[1]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-output-unresolved/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-output-unresolved/input/meta.purchasing.json new file mode 100644 index 0000000000..49d6c95b44 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-output-unresolved/input/meta.purchasing.json @@ -0,0 +1,186 @@ +{ + "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": "Missing", + "@many": true, + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-output-unresolved/providers.json b/fixtures/conformance/error-rules-operation-output-unresolved/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-output-unresolved/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-permission-public/expected-errors.json b/fixtures/conformance/error-rules-operation-permission-public/expected-errors.json new file mode 100644 index 0000000000..1f4876a389 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-permission-public/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_PERMISSION_PUBLIC_CONFLICT", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[1]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-permission-public/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-permission-public/input/meta.purchasing.json new file mode 100644 index 0000000000..eba6eb5c48 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-permission-public/input/meta.purchasing.json @@ -0,0 +1,187 @@ +{ + "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, + "@permission": "purchasing.read" + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-permission-public/providers.json b/fixtures/conformance/error-rules-operation-permission-public/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-permission-public/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-reserved-name/expected-errors.json b/fixtures/conformance/error-rules-operation-reserved-name/expected-errors.json new file mode 100644 index 0000000000..aa25df184c --- /dev/null +++ b/fixtures/conformance/error-rules-operation-reserved-name/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[2]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-reserved-name/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-reserved-name/input/meta.purchasing.json new file mode 100644 index 0000000000..a7aff0e3d9 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-reserved-name/input/meta.purchasing.json @@ -0,0 +1,186 @@ +{ + "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": "get", + "@outputRef": "RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-reserved-name/providers.json b/fixtures/conformance/error-rules-operation-reserved-name/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-reserved-name/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-target-mismatch/expected-errors.json b/fixtures/conformance/error-rules-operation-target-mismatch/expected-errors.json new file mode 100644 index 0000000000..65ebd4e737 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-target-mismatch/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_OPERATION_TARGET_MISMATCH", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[4]['api.operational'].children[0]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-target-mismatch/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-target-mismatch/input/meta.purchasing.json new file mode 100644 index 0000000000..68746928a2 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-target-mismatch/input/meta.purchasing.json @@ -0,0 +1,212 @@ +{ + "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" + } + } + ] + } + }, + { + "object.entity": { + "name": "Vendor", + "children": [ + { + "source.rdb": { + "@table": "vendors" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "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" + } + } + ], + "@objectRef": "Vendor" + } + }, + { + "operation.query": { + "name": "openRequests", + "@outputRef": "RequestSummary", + "@many": true, + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-target-mismatch/providers.json b/fixtures/conformance/error-rules-operation-target-mismatch/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-target-mismatch/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-target-not-entity/expected-errors.json b/fixtures/conformance/error-rules-operation-target-not-entity/expected-errors.json new file mode 100644 index 0000000000..5b57f14cee --- /dev/null +++ b/fixtures/conformance/error-rules-operation-target-not-entity/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_OPERATION_TARGET_UNRESOLVED", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[3]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-target-not-entity/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-target-not-entity/input/meta.purchasing.json new file mode 100644 index 0000000000..50d5f80087 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-target-not-entity/input/meta.purchasing.json @@ -0,0 +1,192 @@ +{ + "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" + } + }, + { + "operation.command": { + "name": "remind", + "@objectRef": "DecisionInput" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-target-not-entity/providers.json b/fixtures/conformance/error-rules-operation-target-not-entity/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-target-not-entity/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-target-underivable/expected-errors.json b/fixtures/conformance/error-rules-operation-target-underivable/expected-errors.json new file mode 100644 index 0000000000..da7025bee5 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-target-underivable/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_OPERATION_TARGET_UNRESOLVED", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[4]['api.operational'].children[3]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-target-underivable/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-target-underivable/input/meta.purchasing.json new file mode 100644 index 0000000000..ec9b0fa330 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-target-underivable/input/meta.purchasing.json @@ -0,0 +1,207 @@ +{ + "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" + } + } + ] + } + }, + { + "object.value": { + "name": "Note", + "children": [ + { + "field.string": { + "name": "text" + } + } + ] + } + }, + { + "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" + } + }, + { + "operation.command": { + "name": "remind", + "@inputRef": "Note", + "@transitions": [ + "submit" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-target-underivable/providers.json b/fixtures/conformance/error-rules-operation-target-underivable/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-target-underivable/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-operation-unknown-transition/expected-errors.json b/fixtures/conformance/error-rules-operation-unknown-transition/expected-errors.json new file mode 100644 index 0000000000..6801d7452b --- /dev/null +++ b/fixtures/conformance/error-rules-operation-unknown-transition/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_OPERATION_UNKNOWN_TRANSITION", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[3]['api.operational'].children[0]['operation.command']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-operation-unknown-transition/input/meta.purchasing.json b/fixtures/conformance/error-rules-operation-unknown-transition/input/meta.purchasing.json new file mode 100644 index 0000000000..2bfa02a679 --- /dev/null +++ b/fixtures/conformance/error-rules-operation-unknown-transition/input/meta.purchasing.json @@ -0,0 +1,186 @@ +{ + "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", + "cancel" + ], + "@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" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-operation-unknown-transition/providers.json b/fixtures/conformance/error-rules-operation-unknown-transition/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-operation-unknown-transition/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-permission-shape/expected-errors.json b/fixtures/conformance/error-rules-permission-shape/expected-errors.json new file mode 100644 index 0000000000..bd1ab00a41 --- /dev/null +++ b/fixtures/conformance/error-rules-permission-shape/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[4]['field.enum'].children[2]['transition.action']" + } + }, + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.operational'].children[0]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-permission-shape/input/meta.purchasing.json b/fixtures/conformance/error-rules-permission-shape/input/meta.purchasing.json new file mode 100644 index 0000000000..8d6c4d4d2f --- /dev/null +++ b/fixtures/conformance/error-rules-permission-shape/input/meta.purchasing.json @@ -0,0 +1,94 @@ +{ + "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.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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected", + "@permission": "purchasing/review" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@outputRef": "PurchaseRequest", + "@many": true, + "@permission": "Has Spaces & ../ !" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-shape/providers.json b/fixtures/conformance/error-rules-permission-shape/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-permission-shape/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-reserved-name-case/expected-errors.json b/fixtures/conformance/error-rules-reserved-name-case/expected-errors.json new file mode 100644 index 0000000000..9d10d8d404 --- /dev/null +++ b/fixtures/conformance/error-rules-reserved-name-case/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[4]['field.enum'].children[0]['transition.action']" + } + }, + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.operational'].children[0]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-reserved-name-case/input/meta.purchasing.json b/fixtures/conformance/error-rules-reserved-name-case/input/meta.purchasing.json new file mode 100644 index 0000000000..70e563bfb1 --- /dev/null +++ b/fixtures/conformance/error-rules-reserved-name-case/input/meta.purchasing.json @@ -0,0 +1,75 @@ +{ + "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.enum": { + "name": "status", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "Create", + "@from": [ + "draft" + ], + "@to": "submitted" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.query": { + "name": "LIST", + "@outputRef": "PurchaseRequest", + "@many": true, + "@public": true + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-reserved-name-case/providers.json b/fixtures/conformance/error-rules-reserved-name-case/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-reserved-name-case/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-case-collision/expected-errors.json b/fixtures/conformance/error-rules-transition-case-collision/expected-errors.json new file mode 100644 index 0000000000..13ff5e28c6 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-case-collision/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[4]['field.enum'].children[1]['transition.action']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-case-collision/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-case-collision/input/meta.purchasing.json new file mode 100644 index 0000000000..026e32b333 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-case-collision/input/meta.purchasing.json @@ -0,0 +1,69 @@ +{ + "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.enum": { + "name": "status", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "close", + "@from": [ + "draft" + ], + "@to": "rejected" + } + }, + { + "transition.action": { + "name": "Close", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-case-collision/providers.json b/fixtures/conformance/error-rules-transition-case-collision/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-case-collision/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-condition-not-boolean/expected-errors.json b/fixtures/conformance/error-rules-transition-condition-not-boolean/expected-errors.json new file mode 100644 index 0000000000..76bb503628 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-condition-not-boolean/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['field.enum'].children[0]['transition.action']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-condition-not-boolean/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-condition-not-boolean/input/meta.purchasing.json new file mode 100644 index 0000000000..c47e2417e4 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-condition-not-boolean/input/meta.purchasing.json @@ -0,0 +1,68 @@ +{ + "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", + "@condition": { + "field": "amountCents" + } + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-condition-not-boolean/providers.json b/fixtures/conformance/error-rules-transition-condition-not-boolean/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-condition-not-boolean/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-condition-unknown-field/expected-errors.json b/fixtures/conformance/error-rules-transition-condition-unknown-field/expected-errors.json new file mode 100644 index 0000000000..76bb503628 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-condition-unknown-field/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['field.enum'].children[0]['transition.action']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-condition-unknown-field/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-condition-unknown-field/input/meta.purchasing.json new file mode 100644 index 0000000000..a2b97373cf --- /dev/null +++ b/fixtures/conformance/error-rules-transition-condition-unknown-field/input/meta.purchasing.json @@ -0,0 +1,74 @@ +{ + "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", + "@condition": { + "op": "gt", + "left": { + "field": "total" + }, + "right": { + "value": 0 + } + } + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-condition-unknown-field/providers.json b/fixtures/conformance/error-rules-transition-condition-unknown-field/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-condition-unknown-field/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-duplicate-name/expected-errors.json b/fixtures/conformance/error-rules-transition-duplicate-name/expected-errors.json new file mode 100644 index 0000000000..613957434a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-duplicate-name/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[6]['field.enum'].children[0]['transition.action']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-duplicate-name/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-duplicate-name/input/meta.purchasing.json new file mode 100644 index 0000000000..4b1fb6d85d --- /dev/null +++ b/fixtures/conformance/error-rules-transition-duplicate-name/input/meta.purchasing.json @@ -0,0 +1,114 @@ +{ + "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" + } + } + ] + } + }, + { + "field.enum": { + "name": "payment", + "@values": [ + "unpaid", + "paid" + ], + "@default": "unpaid", + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "unpaid" + ], + "@to": "paid" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-duplicate-name/providers.json b/fixtures/conformance/error-rules-transition-duplicate-name/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-duplicate-name/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-empty-from/expected-errors.json b/fixtures/conformance/error-rules-transition-empty-from/expected-errors.json new file mode 100644 index 0000000000..3dc429d3ff --- /dev/null +++ b/fixtures/conformance/error-rules-transition-empty-from/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[4]['field.enum'].children[0]['transition.action']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-empty-from/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-empty-from/input/meta.purchasing.json new file mode 100644 index 0000000000..09d65d97fe --- /dev/null +++ b/fixtures/conformance/error-rules-transition-empty-from/input/meta.purchasing.json @@ -0,0 +1,58 @@ +{ + "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.enum": { + "name": "status", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [], + "@to": "submitted" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-empty-from/providers.json b/fixtures/conformance/error-rules-transition-empty-from/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-empty-from/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-on-root-field/expected-errors.json b/fixtures/conformance/error-rules-transition-on-root-field/expected-errors.json new file mode 100644 index 0000000000..14a2b085b7 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-on-root-field/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NOT_ON_ENTITY", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['field.enum'].children[0]['transition.action']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-on-root-field/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-on-root-field/input/meta.purchasing.json new file mode 100644 index 0000000000..3d7ca97841 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-on-root-field/input/meta.purchasing.json @@ -0,0 +1,114 @@ +{ + "metadata.root": { + "package": "acme::purchasing", + "children": [ + { + "field.enum": { + "name": "status", + "@values": [ + "draft", + "submitted" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + } + ] + } + }, + { + "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" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-on-root-field/providers.json b/fixtures/conformance/error-rules-transition-on-root-field/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-on-root-field/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-on-value/expected-errors.json b/fixtures/conformance/error-rules-transition-on-value/expected-errors.json new file mode 100644 index 0000000000..8d095cce07 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-on-value/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NOT_ON_ENTITY", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.value'].children[0]['field.enum'].children[0]['transition.action']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-on-value/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-on-value/input/meta.purchasing.json new file mode 100644 index 0000000000..505057e390 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-on-value/input/meta.purchasing.json @@ -0,0 +1,123 @@ +{ + "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": "Draft", + "children": [ + { + "field.enum": { + "name": "status", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-on-value/providers.json b/fixtures/conformance/error-rules-transition-on-value/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-on-value/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-permission-public/expected-errors.json b/fixtures/conformance/error-rules-transition-permission-public/expected-errors.json new file mode 100644 index 0000000000..7c947bc787 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-permission-public/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_PERMISSION_PUBLIC_CONFLICT", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['field.enum'].children[0]['transition.action']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-permission-public/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-permission-public/input/meta.purchasing.json new file mode 100644 index 0000000000..6447281ae4 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-permission-public/input/meta.purchasing.json @@ -0,0 +1,67 @@ +{ + "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", + "@public": true, + "@permission": "purchasing.submit" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-permission-public/providers.json b/fixtures/conformance/error-rules-transition-permission-public/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-permission-public/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-reserved-name/expected-errors.json b/fixtures/conformance/error-rules-transition-reserved-name/expected-errors.json new file mode 100644 index 0000000000..ce4313121c --- /dev/null +++ b/fixtures/conformance/error-rules-transition-reserved-name/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['field.enum'].children[0]['transition.action']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-reserved-name/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-reserved-name/input/meta.purchasing.json new file mode 100644 index 0000000000..894aef5ff5 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-reserved-name/input/meta.purchasing.json @@ -0,0 +1,65 @@ +{ + "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": "update", + "@from": [ + "draft" + ], + "@to": "submitted" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-reserved-name/providers.json b/fixtures/conformance/error-rules-transition-reserved-name/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-reserved-name/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-timed-reserved/expected-errors.json b/fixtures/conformance/error-rules-transition-timed-reserved/expected-errors.json new file mode 100644 index 0000000000..a02e03ef58 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-timed-reserved/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_SUBTYPE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['field.enum'].children[0]['transition.timed']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-timed-reserved/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-timed-reserved/input/meta.purchasing.json new file mode 100644 index 0000000000..b8fff294e7 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-timed-reserved/input/meta.purchasing.json @@ -0,0 +1,61 @@ +{ + "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.timed": { + "name": "expire" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-timed-reserved/providers.json b/fixtures/conformance/error-rules-transition-timed-reserved/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-timed-reserved/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-rules-transition-unknown-state/expected-errors.json b/fixtures/conformance/error-rules-transition-unknown-state/expected-errors.json new file mode 100644 index 0000000000..925aaccebc --- /dev/null +++ b/fixtures/conformance/error-rules-transition-unknown-state/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_UNKNOWN_STATE", + "source": { + "format": "json", + "files": [ + "meta.purchasing.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['field.enum'].children[0]['transition.action']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-transition-unknown-state/input/meta.purchasing.json b/fixtures/conformance/error-rules-transition-unknown-state/input/meta.purchasing.json new file mode 100644 index 0000000000..a2965bdda7 --- /dev/null +++ b/fixtures/conformance/error-rules-transition-unknown-state/input/meta.purchasing.json @@ -0,0 +1,66 @@ +{ + "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", + "pending" + ], + "@to": "sent" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-transition-unknown-state/providers.json b/fixtures/conformance/error-rules-transition-unknown-state/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-rules-transition-unknown-state/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/rules-lifecycle-field-extends/expected.json b/fixtures/conformance/rules-lifecycle-field-extends/expected.json new file mode 100644 index 0000000000..f8c7026832 --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-field-extends/expected.json @@ -0,0 +1,109 @@ +{ + "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.enum": { + "name": "status", + "@default": "draft", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@from": [ + "submitted" + ], + "@to": "approved" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "PurchaseRequestStatusChange", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.enum": { + "name": "status", + "extends": "acme::purchasing::PurchaseRequest.status" + } + }, + { + "field.timestamp": { + "name": "changedAt" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-lifecycle-field-extends/input/meta.purchasing.json b/fixtures/conformance/rules-lifecycle-field-extends/input/meta.purchasing.json new file mode 100644 index 0000000000..df29c6d23e --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-field-extends/input/meta.purchasing.json @@ -0,0 +1,109 @@ +{ + "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.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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "PurchaseRequestStatusChange", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.enum": { + "name": "status", + "extends": "PurchaseRequest.status" + } + }, + { + "field.timestamp": { + "name": "changedAt" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-lifecycle-field-extends/providers.json b/fixtures/conformance/rules-lifecycle-field-extends/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-field-extends/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/rules-lifecycle-inherited/expected.json b/fixtures/conformance/rules-lifecycle-inherited/expected.json new file mode 100644 index 0000000000..2188537e20 --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-inherited/expected.json @@ -0,0 +1,194 @@ +{ + "metadata.root": { + "package": "acme::purchasing", + "children": [ + { + "object.entity": { + "name": "Request", + "abstract": true, + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.string": { + "name": "title" + } + }, + { + "field.long": { + "name": "amountCents" + } + }, + { + "field.enum": { + "name": "status", + "@default": "draft", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@condition": { + "op": "gt", + "left": { + "field": "amountCents" + }, + "right": { + "value": 0 + } + }, + "@from": [ + "submitted" + ], + "@to": "approved" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "PurchaseRequest", + "extends": "acme::purchasing::Request", + "children": [ + { + "source.rdb": { + "@table": "purchase_requests" + } + } + ] + } + }, + { + "object.value": { + "name": "DecisionInput", + "children": [ + { + "field.long": { + "name": "requestId", + "extends": "acme::purchasing::PurchaseRequest.id" + } + }, + { + "field.string": { + "name": "comment" + } + } + ] + } + }, + { + "object.projection": { + "name": "RequestSummary", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_request_summary" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::purchasing::PurchaseRequest.id" + } + }, + { + "field.string": { + "name": "title", + "extends": "acme::purchasing::PurchaseRequest.title" + } + }, + { + "identity.primary": { + "name": "pk", + "extends": "acme::purchasing::PurchaseRequest.pk" + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "decide", + "@errors": [ + "over_budget", + "already_decided" + ], + "@inputRef": "acme::purchasing::DecisionInput", + "@permission": "purchasing.decide", + "@transitions": [ + "approve", + "reject" + ], + "children": [ + { + "binding.rest": { + "@method": "PUT", + "@path": "/purchase-requests/{id}/decision" + } + } + ] + } + }, + { + "operation.query": { + "name": "openRequests", + "@many": true, + "@outputRef": "acme::purchasing::RequestSummary", + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "acme::purchasing::RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-lifecycle-inherited/input/meta.purchasing.json b/fixtures/conformance/rules-lifecycle-inherited/input/meta.purchasing.json new file mode 100644 index 0000000000..7bfc1e4a2f --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-inherited/input/meta.purchasing.json @@ -0,0 +1,194 @@ +{ + "metadata.root": { + "package": "acme::purchasing", + "children": [ + { + "object.entity": { + "name": "Request", + "abstract": true, + "children": [ + { + "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" + } + } + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "PurchaseRequest", + "extends": "Request", + "children": [ + { + "source.rdb": { + "@table": "purchase_requests" + } + } + ] + } + }, + { + "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" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-lifecycle-inherited/providers.json b/fixtures/conformance/rules-lifecycle-inherited/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-inherited/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/rules-lifecycle-no-api/expected.json b/fixtures/conformance/rules-lifecycle-no-api/expected.json new file mode 100644 index 0000000000..500e0f0df0 --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-no-api/expected.json @@ -0,0 +1,124 @@ +{ + "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", + "@default": "draft", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@condition": { + "op": "gt", + "left": { + "field": "amountCents" + }, + "right": { + "value": 0 + } + }, + "@from": [ + "submitted" + ], + "@to": "approved" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@permission": "purchasing.review", + "@to": "rejected" + } + }, + { + "transition.action": { + "name": "approveFirst", + "@from": [ + "submitted" + ], + "@to": "submitted" + } + } + ] + } + }, + { + "field.enum": { + "name": "payment", + "@default": "unpaid", + "@values": [ + "unpaid", + "paid" + ], + "children": [ + { + "transition.action": { + "name": "pay", + "@from": [ + "unpaid" + ], + "@public": true, + "@to": "paid" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-lifecycle-no-api/input/meta.purchasing.json b/fixtures/conformance/rules-lifecycle-no-api/input/meta.purchasing.json new file mode 100644 index 0000000000..735c93a55d --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-no-api/input/meta.purchasing.json @@ -0,0 +1,124 @@ +{ + "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" + } + }, + { + "transition.action": { + "name": "approveFirst", + "@from": [ + "submitted" + ], + "@to": "submitted" + } + } + ] + } + }, + { + "field.enum": { + "name": "payment", + "@values": [ + "unpaid", + "paid" + ], + "@default": "unpaid", + "children": [ + { + "transition.action": { + "name": "pay", + "@from": [ + "unpaid" + ], + "@to": "paid", + "@public": true + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-lifecycle-no-api/providers.json b/fixtures/conformance/rules-lifecycle-no-api/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-no-api/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/rules-lifecycle-no-source/expected.json b/fixtures/conformance/rules-lifecycle-no-source/expected.json new file mode 100644 index 0000000000..70dcea4647 --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-no-source/expected.json @@ -0,0 +1,88 @@ +{ + "metadata.root": { + "package": "acme::purchasing", + "children": [ + { + "object.entity": { + "name": "PurchaseRequest", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.string": { + "name": "title" + } + }, + { + "field.long": { + "name": "amountCents" + } + }, + { + "field.enum": { + "name": "status", + "@default": "draft", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@condition": { + "op": "gt", + "left": { + "field": "amountCents" + }, + "right": { + "value": 0 + } + }, + "@from": [ + "submitted" + ], + "@to": "approved" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@permission": "purchasing.review", + "@to": "rejected" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-lifecycle-no-source/input/meta.purchasing.json b/fixtures/conformance/rules-lifecycle-no-source/input/meta.purchasing.json new file mode 100644 index 0000000000..44bce44eef --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-no-source/input/meta.purchasing.json @@ -0,0 +1,88 @@ +{ + "metadata.root": { + "package": "acme::purchasing", + "children": [ + { + "object.entity": { + "name": "PurchaseRequest", + "children": [ + { + "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" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-lifecycle-no-source/providers.json b/fixtures/conformance/rules-lifecycle-no-source/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/rules-lifecycle-no-source/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/rules-operation-cross-package/expected.json b/fixtures/conformance/rules-operation-cross-package/expected.json new file mode 100644 index 0000000000..0d18bca19d --- /dev/null +++ b/fixtures/conformance/rules-operation-cross-package/expected.json @@ -0,0 +1,188 @@ +{ + "metadata.root": { + "children": [ + { + "api.operational": { + "name": "Purchasing", + "package": "acme::api", + "children": [ + { + "operation.command": { + "name": "decide", + "@errors": [ + "over_budget", + "already_decided" + ], + "@inputRef": "acme::purchasing::DecisionInput", + "@permission": "purchasing.decide", + "@transitions": [ + "approve", + "reject" + ], + "children": [ + { + "binding.rest": { + "@method": "PUT", + "@path": "/purchase-requests/{id}/decision" + } + } + ] + } + }, + { + "operation.query": { + "name": "openRequests", + "@many": true, + "@outputRef": "acme::purchasing::RequestSummary", + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "acme::purchasing::RequestSummary" + } + } + ] + } + }, + { + "object.entity": { + "name": "PurchaseRequest", + "package": "acme::purchasing", + "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", + "@default": "draft", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@condition": { + "op": "gt", + "left": { + "field": "amountCents" + }, + "right": { + "value": 0 + } + }, + "@from": [ + "submitted" + ], + "@to": "approved" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.value": { + "name": "DecisionInput", + "package": "acme::purchasing", + "children": [ + { + "field.long": { + "name": "requestId", + "extends": "acme::purchasing::PurchaseRequest.id" + } + }, + { + "field.string": { + "name": "comment" + } + } + ] + } + }, + { + "object.projection": { + "name": "RequestSummary", + "package": "acme::purchasing", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_request_summary" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::purchasing::PurchaseRequest.id" + } + }, + { + "field.string": { + "name": "title", + "extends": "acme::purchasing::PurchaseRequest.title" + } + }, + { + "identity.primary": { + "name": "pk", + "extends": "acme::purchasing::PurchaseRequest.pk" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-operation-cross-package/input/meta.api.json b/fixtures/conformance/rules-operation-cross-package/input/meta.api.json new file mode 100644 index 0000000000..3041c7254b --- /dev/null +++ b/fixtures/conformance/rules-operation-cross-package/input/meta.api.json @@ -0,0 +1,51 @@ +{ + "metadata.root": { + "package": "acme::api", + "children": [ + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "decide", + "@inputRef": "acme::purchasing::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": "acme::purchasing::RequestSummary", + "@many": true, + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "acme::purchasing::RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-operation-cross-package/input/meta.purchasing.json b/fixtures/conformance/rules-operation-cross-package/input/meta.purchasing.json new file mode 100644 index 0000000000..e2bedc6e72 --- /dev/null +++ b/fixtures/conformance/rules-operation-cross-package/input/meta.purchasing.json @@ -0,0 +1,141 @@ +{ + "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" + } + } + ] + } + } + ] + } + }, + { + "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" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-operation-cross-package/providers.json b/fixtures/conformance/rules-operation-cross-package/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/rules-operation-cross-package/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/rules-operation-declared-target/expected.json b/fixtures/conformance/rules-operation-declared-target/expected.json new file mode 100644 index 0000000000..f3998e7215 --- /dev/null +++ b/fixtures/conformance/rules-operation-declared-target/expected.json @@ -0,0 +1,222 @@ +{ + "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", + "@default": "draft", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@condition": { + "op": "gt", + "left": { + "field": "amountCents" + }, + "right": { + "value": 0 + } + }, + "@from": [ + "submitted" + ], + "@to": "approved" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.value": { + "name": "DecisionInput", + "children": [ + { + "field.long": { + "name": "requestId", + "extends": "acme::purchasing::PurchaseRequest.id" + } + }, + { + "field.string": { + "name": "comment" + } + } + ] + } + }, + { + "object.projection": { + "name": "RequestSummary", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_request_summary" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::purchasing::PurchaseRequest.id" + } + }, + { + "field.string": { + "name": "title", + "extends": "acme::purchasing::PurchaseRequest.title" + } + }, + { + "identity.primary": { + "name": "pk", + "extends": "acme::purchasing::PurchaseRequest.pk" + } + } + ] + } + }, + { + "object.value": { + "name": "VendorFilter", + "children": [ + { + "field.string": { + "name": "vendor" + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "decide", + "@errors": [ + "over_budget", + "already_decided" + ], + "@inputRef": "acme::purchasing::DecisionInput", + "@permission": "purchasing.decide", + "@transitions": [ + "approve", + "reject" + ], + "children": [ + { + "binding.rest": { + "@method": "PUT", + "@path": "/purchase-requests/{id}/decision" + } + } + ] + } + }, + { + "operation.query": { + "name": "openRequests", + "@many": true, + "@outputRef": "acme::purchasing::RequestSummary", + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "acme::purchasing::RequestSummary" + } + }, + { + "operation.command": { + "name": "remind", + "@objectRef": "acme::purchasing::PurchaseRequest", + "@transitions": [ + "submit" + ] + } + }, + { + "operation.command": { + "name": "resubmit", + "@outputRef": "acme::purchasing::RequestSummary", + "@public": true + } + }, + { + "operation.query": { + "name": "byVendor", + "@inputRef": "acme::purchasing::VendorFilter", + "@many": true, + "@objectRef": "acme::purchasing::PurchaseRequest", + "@outputRef": "acme::purchasing::RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-operation-declared-target/input/meta.purchasing.json b/fixtures/conformance/rules-operation-declared-target/input/meta.purchasing.json new file mode 100644 index 0000000000..8c34adb7be --- /dev/null +++ b/fixtures/conformance/rules-operation-declared-target/input/meta.purchasing.json @@ -0,0 +1,222 @@ +{ + "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" + } + } + ] + } + } + ] + } + }, + { + "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" + } + } + ] + } + }, + { + "object.value": { + "name": "VendorFilter", + "children": [ + { + "field.string": { + "name": "vendor" + } + } + ] + } + }, + { + "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" + } + }, + { + "operation.command": { + "name": "remind", + "@objectRef": "PurchaseRequest", + "@transitions": [ + "submit" + ] + } + }, + { + "operation.command": { + "name": "resubmit", + "@outputRef": "RequestSummary", + "@public": true + } + }, + { + "operation.query": { + "name": "byVendor", + "@inputRef": "VendorFilter", + "@objectRef": "PurchaseRequest", + "@outputRef": "RequestSummary", + "@many": true + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-operation-declared-target/providers.json b/fixtures/conformance/rules-operation-declared-target/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/rules-operation-declared-target/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/rules-operation-name-two-packages/expected.json b/fixtures/conformance/rules-operation-name-two-packages/expected.json new file mode 100644 index 0000000000..715913beec --- /dev/null +++ b/fixtures/conformance/rules-operation-name-two-packages/expected.json @@ -0,0 +1,110 @@ +{ + "metadata.root": { + "children": [ + { + "object.entity": { + "name": "PurchaseRequest", + "package": "acme::purchasing", + "children": [ + { + "source.rdb": { + "@table": "purchase_requests" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.string": { + "name": "title" + } + }, + { + "field.enum": { + "name": "status", + "@default": "draft", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@from": [ + "submitted" + ], + "@to": "approved" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "package": "acme::purchasing", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@many": true, + "@outputRef": "acme::purchasing::PurchaseRequest", + "@permission": "acme::purchasing.openRequests" + } + } + ] + } + }, + { + "api.operational": { + "name": "Review", + "package": "acme::review", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@many": true, + "@outputRef": "acme::purchasing::PurchaseRequest", + "@permission": "review.openRequests" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-operation-name-two-packages/input/meta.purchasing.json b/fixtures/conformance/rules-operation-name-two-packages/input/meta.purchasing.json new file mode 100644 index 0000000000..2598d6a1c0 --- /dev/null +++ b/fixtures/conformance/rules-operation-name-two-packages/input/meta.purchasing.json @@ -0,0 +1,93 @@ +{ + "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.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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@outputRef": "PurchaseRequest", + "@many": true, + "@permission": "acme::purchasing.openRequests" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-operation-name-two-packages/input/meta.review.json b/fixtures/conformance/rules-operation-name-two-packages/input/meta.review.json new file mode 100644 index 0000000000..e01210ee40 --- /dev/null +++ b/fixtures/conformance/rules-operation-name-two-packages/input/meta.review.json @@ -0,0 +1,22 @@ +{ + "metadata.root": { + "package": "acme::review", + "children": [ + { + "api.operational": { + "name": "Review", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@outputRef": "acme::purchasing::PurchaseRequest", + "@many": true, + "@permission": "review.openRequests" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-operation-name-two-packages/providers.json b/fixtures/conformance/rules-operation-name-two-packages/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/rules-operation-name-two-packages/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/rules-operation-versioned-apis/expected.json b/fixtures/conformance/rules-operation-versioned-apis/expected.json new file mode 100644 index 0000000000..76006e4546 --- /dev/null +++ b/fixtures/conformance/rules-operation-versioned-apis/expected.json @@ -0,0 +1,122 @@ +{ + "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.enum": { + "name": "status", + "@default": "draft", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@from": [ + "submitted" + ], + "@to": "approved" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "PurchasingV1", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@many": true, + "@outputRef": "acme::purchasing::PurchaseRequest", + "@permission": "purchasing.openRequests", + "children": [ + { + "binding.rest": { + "@path": "/v1/open-requests" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "PurchasingV2", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@many": true, + "@outputRef": "acme::purchasing::PurchaseRequest", + "@permission": "purchasing.openRequests", + "children": [ + { + "binding.rest": { + "@path": "/v2/open-requests" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-operation-versioned-apis/input/meta.purchasing.json b/fixtures/conformance/rules-operation-versioned-apis/input/meta.purchasing.json new file mode 100644 index 0000000000..0f2edf579b --- /dev/null +++ b/fixtures/conformance/rules-operation-versioned-apis/input/meta.purchasing.json @@ -0,0 +1,122 @@ +{ + "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.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" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "PurchasingV1", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@outputRef": "PurchaseRequest", + "@many": true, + "@permission": "purchasing.openRequests", + "children": [ + { + "binding.rest": { + "@path": "/v1/open-requests" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "PurchasingV2", + "children": [ + { + "operation.query": { + "name": "openRequests", + "@outputRef": "PurchaseRequest", + "@many": true, + "@permission": "purchasing.openRequests", + "children": [ + { + "binding.rest": { + "@path": "/v2/open-requests" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-operation-versioned-apis/providers.json b/fixtures/conformance/rules-operation-versioned-apis/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/rules-operation-versioned-apis/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/rules-purchase-request/expected.json b/fixtures/conformance/rules-purchase-request/expected.json new file mode 100644 index 0000000000..8859d0135e --- /dev/null +++ b/fixtures/conformance/rules-purchase-request/expected.json @@ -0,0 +1,185 @@ +{ + "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", + "@default": "draft", + "@values": [ + "draft", + "submitted", + "approved", + "rejected" + ], + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@condition": { + "op": "gt", + "left": { + "field": "amountCents" + }, + "right": { + "value": 0 + } + }, + "@from": [ + "submitted" + ], + "@to": "approved" + } + }, + { + "transition.action": { + "name": "reject", + "@from": [ + "submitted" + ], + "@to": "rejected" + } + } + ] + } + } + ] + } + }, + { + "object.value": { + "name": "DecisionInput", + "children": [ + { + "field.long": { + "name": "requestId", + "extends": "acme::purchasing::PurchaseRequest.id" + } + }, + { + "field.string": { + "name": "comment" + } + } + ] + } + }, + { + "object.projection": { + "name": "RequestSummary", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_request_summary" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::purchasing::PurchaseRequest.id" + } + }, + { + "field.string": { + "name": "title", + "extends": "acme::purchasing::PurchaseRequest.title" + } + }, + { + "identity.primary": { + "name": "pk", + "extends": "acme::purchasing::PurchaseRequest.pk" + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "decide", + "@errors": [ + "over_budget", + "already_decided" + ], + "@inputRef": "acme::purchasing::DecisionInput", + "@permission": "purchasing.decide", + "@transitions": [ + "approve", + "reject" + ], + "children": [ + { + "binding.rest": { + "@method": "PUT", + "@path": "/purchase-requests/{id}/decision" + } + } + ] + } + }, + { + "operation.query": { + "name": "openRequests", + "@many": true, + "@outputRef": "acme::purchasing::RequestSummary", + "@public": true + } + }, + { + "operation.query": { + "name": "requestSummary", + "@outputRef": "acme::purchasing::RequestSummary" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-purchase-request/input/meta.purchasing.json b/fixtures/conformance/rules-purchase-request/input/meta.purchasing.json new file mode 100644 index 0000000000..7822702ca8 --- /dev/null +++ b/fixtures/conformance/rules-purchase-request/input/meta.purchasing.json @@ -0,0 +1,185 @@ +{ + "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" + } + } + ] + } + } + ] + } + }, + { + "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" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/rules-purchase-request/providers.json b/fixtures/conformance/rules-purchase-request/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/rules-purchase-request/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/fmt-conformance/reorder-rules-vocabulary/expected.json b/fixtures/fmt-conformance/reorder-rules-vocabulary/expected.json new file mode 100644 index 0000000000..f8c6e3a2db --- /dev/null +++ b/fixtures/fmt-conformance/reorder-rules-vocabulary/expected.json @@ -0,0 +1,113 @@ +{ + "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.enum": { + "name": "status", + "@default": "draft", + "@values": [ + "draft", + "submitted", + "approved" + ], + "children": [ + { + "transition.action": { + "name": "submit", + "@from": [ + "draft" + ], + "@permission": "purchasing.submit", + "@to": "submitted" + } + }, + { + "transition.action": { + "name": "approve", + "@from": [ + "submitted" + ], + "@public": true, + "@to": "approved" + } + } + ] + } + } + ] + } + }, + { + "object.value": { + "name": "SubmitInput", + "children": [ + { + "field.long": { + "name": "requestId", + "extends": "PurchaseRequest.id" + } + } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "submit", + "@errors": [ + "not_ready" + ], + "@inputRef": "SubmitInput", + "@transitions": [ + "submit" + ], + "children": [ + { + "binding.rest": { + "@method": "POST", + "@path": "/purchase-requests/{id}/submit" + } + } + ] + } + }, + { + "operation.query": { + "name": "drafts", + "@many": true, + "@outputRef": "PurchaseRequest", + "@public": true + } + } + ] + } + } + ] + } +} diff --git a/fixtures/fmt-conformance/reorder-rules-vocabulary/input.json b/fixtures/fmt-conformance/reorder-rules-vocabulary/input.json new file mode 100644 index 0000000000..c99352906f --- /dev/null +++ b/fixtures/fmt-conformance/reorder-rules-vocabulary/input.json @@ -0,0 +1,16 @@ +{"metadata.root": {"children": [ + {"object.entity": {"children": [ + {"source.rdb": {"@table": "purchase_requests"}}, + {"field.long": {"name": "id"}}, + {"identity.primary": {"@fields": "id", "name": "pk"}}, + {"field.enum": {"children": [ + {"transition.action": {"@to": "submitted", "@permission": "purchasing.submit", "name": "submit", "@from": ["draft"]}}, + {"transition.action": {"@to": "approved", "@from": ["submitted"], "name": "approve", "@public": true}} + ], "@default": "draft", "name": "status", "@values": ["draft", "submitted", "approved"]}} + ], "name": "PurchaseRequest"}}, + {"object.value": {"name": "SubmitInput", "children": [{"field.long": {"extends": "PurchaseRequest.id", "name": "requestId"}}]}}, + {"api.operational": {"children": [ + {"operation.command": {"@transitions": ["submit"], "children": [{"binding.rest": {"@path": "/purchase-requests/{id}/submit", "@method": "POST"}}], "@inputRef": "SubmitInput", "name": "submit", "@errors": ["not_ready"]}}, + {"operation.query": {"@many": true, "name": "drafts", "@outputRef": "PurchaseRequest", "@public": true}} + ], "name": "Purchasing"}} +], "package": "acme::purchasing"}} diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 94ab806838..b4bf3b0c8c 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -15,6 +15,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.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) | | `attr.base` | Abstract base attribute — the polymorphic/unconstrained value-type marker. Stores its value type-preserved (never stringified), accepting any type; used for an untyped attr (e.g. a field's @default, whose value-type follows the owning field's subtype). Not authored directly: a `attr.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/attr.md#attrbase](types/attr.md#attrbase) | | `attr.boolean` | A boolean-valued metadata attribute. Coerces to and validates as true/false. | [types/attr.md#attrboolean](types/attr.md#attrboolean) | | `attr.class` | A class-/type-reference-valued metadata attribute. String-backed (a fully-qualified class or type name) used by binding facets. | [types/attr.md#attrclass](types/attr.md#attrclass) | @@ -26,6 +28,8 @@ children and the cardinality of that subtype. Documentation attributes | `attr.long` | A 64-bit-integer-valued metadata attribute. Coerces to and validates as a number. | [types/attr.md#attrlong](types/attr.md#attrlong) | | `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.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) | | `dimension.attribute` | A named group-by attribute of the entity that declares it (FR-044). Groups report rows by a column value as-is. @of names Entity.field: the owning entity, or the @via terminal. @via may follow only to-one hops, so grouping by a related row's column can never multiply the measured rows. | [types/dimension.md#dimensionattribute](types/dimension.md#dimensionattribute) | | `dimension.time` | A named time dimension (FR-044): groups report rows by a date or timestamp column truncated to a grain. @of names a field.date or field.timestamp. Weeks start on Monday (ISO-8601) in every lowering. A report names it as 'dimension:grain' and the derived report field is (e.g. purchasedAtDay). | [types/dimension.md#dimensiontime](types/dimension.md#dimensiontime) | | `field.base` | Abstract base field — the shared root subtype that concrete field subtypes specialize. Carries the attrs common to every field but binds no concrete data type of its own (falls back to string). Not authored directly: a `field.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/field.md#fieldbase](types/field.md#fieldbase) | @@ -62,6 +66,9 @@ 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.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.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) | | `origin.aggregate` | A value reduced from the related row-set reached along a relationship path (@via) from the base entity: count/sum/avg/min/max over a column (@of); any/all predicate quantifiers over a @filter; or collect (an array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted). | [types/origin.md#originaggregate](types/origin.md#originaggregate) | | `origin.base` | Abstract base origin — the shared root subtype for field-level provenance. A field carrying any origin.* is derived ⇒ read-only wherever it lives. The base carries no attrs of its own; concrete subtypes add their provenance attrs. Not authored directly: a `origin.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/origin.md#originbase](types/origin.md#originbase) | | `origin.computed` | A row-level value computed from the base entity's own fields via a structured expression tree (@expr). No related rows, no @via. Read-only; the expression's inferred type must equal the field's declared subType. | [types/origin.md#origincomputed](types/origin.md#origincomputed) | @@ -81,6 +88,8 @@ children and the cardinality of that subtype. Documentation attributes | `template.output` | An output / serialization template (FR-004): every rendered artifact other than an LLM prompt — a document (email, export, docs, config) or an email. Carries the generic reference + governance attrs and the @kind + email part-refs. OUTBOUND ONLY (ADR-0052) — it renders, and generates no parser. | [types/template.md#templateoutput](types/template.md#templateoutput) | | `template.prompt` | An LLM-targeted renderable prompt template (FR-004). Carries the generic reference + governance attrs plus the LLM overlay (@maxTokens / @requiredSlots / @model / @responseRef). Its renderable body is required via @textRef. A prompt declaring @responseRef also owns the INBOUND half (ADR-0052): the parser-on-receipt, the FR-010 response-format fragment (@promptStyle), and the reply syntax (@responseFormat). | [types/template.md#templateprompt](types/template.md#templateprompt) | | `template.toolcall` | A vendor-agnostic LLM tool-call envelope (ADR-0011). Unlike prompt/output it has NO renderable text body — the body IS the structured output schema resolved via @payloadRef. This is why toolcall is its own subtype rather than template.output + @toolName. Does NOT inherit the generic attrs. | [types/template.md#templatetoolcall](types/template.md#templatetoolcall) | +| `transition.action` | An allowed move between two values of a `field.enum`, made by an operation (ADR-0066). A `field.enum` with at least one is a lifecycle, named after the field. Its states are the enum's @values, its initial state the enum's @default, its terminal states the members no transition leaves; none of them has vocabulary of its own. Each transition is held to become a guarded update (`... WHERE id = ? AND IN (@from) [AND @condition]`), its own command when no declared operation claims it, its own permission point and its own wire error. No shell is generated yet: nothing is generated from this vocabulary, and the loader and `verify` only check it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). | [types/transition.md#transitionaction](types/transition.md#transitionaction) | +| `transition.base` | Registry anchor for the attributes every lifecycle move shares (ADR-0054): not authorable. | [types/transition.md#transitionbase](types/transition.md#transitionbase) | | `validator.array` | Bounds the element count of an array-valued field via @min/@max. | [types/validator.md#validatorarray](types/validator.md#validatorarray) | | `validator.atLeastOne` | Cardinality of presence: at least one of the named fields (@fields) must be present (NOT NULL). Entity-scoped; references fields by name (same @fields-by-name pattern as identity.*). | [types/validator.md#validatoratleastone](types/validator.md#validatoratleastone) | | `validator.base` | Abstract base validator — the shared root subtype concrete validators specialize. Carries the @min/@max bounds attrs but enforces no rule of its own. Not authored directly: a `validator.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/validator.md#validatorbase](types/validator.md#validatorbase) | diff --git a/fixtures/metamodel-docs/expected/types/api.md b/fixtures/metamodel-docs/expected/types/api.md new file mode 100644 index 0000000000..2b432a814a --- /dev/null +++ b/fixtures/metamodel-docs/expected/types/api.md @@ -0,0 +1,40 @@ + + +# Metamodel — `api` types + +Each section below is one `api.`. The **Attributes** table lists +the subtype's own + concern-contributed attributes (provider-tagged); universal +documentation attributes are omitted here (see [providers.md](../providers.md)). +**Allowed children** lists the structural child rules with their cardinality +(`min..max`, `*` = unbounded). + +### 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. + +**Attributes** + +_No subtype-specific attributes._ + +**Allowed children** + +_No structural children._ + +### 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). + +**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). + +**When to use:** 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. + +**Attributes** + +_No subtype-specific attributes._ + +**Allowed children** + +- `operation.*` — 0..* + diff --git a/fixtures/metamodel-docs/expected/types/binding.md b/fixtures/metamodel-docs/expected/types/binding.md new file mode 100644 index 0000000000..9ff5445830 --- /dev/null +++ b/fixtures/metamodel-docs/expected/types/binding.md @@ -0,0 +1,41 @@ + + +# Metamodel — `binding` types + +Each section below is one `binding.`. The **Attributes** table lists +the subtype's own + concern-contributed attributes (provider-tagged); universal +documentation attributes are omitted here (see [providers.md](../providers.md)). +**Allowed children** lists the structural child rules with their cardinality +(`min..max`, `*` = unbounded). + +### binding.base + +Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable. + +**Attributes** + +_No subtype-specific attributes._ + +**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). + +**When to use:** An operation must keep a method or path the derived one would not give it, such as an existing public URL. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@method` | string | no | | `GET`, `POST`, `PUT`, `PATCH`, `DELETE` | — | The HTTP method. Absent: GET for a query, POST for a command. | +| `@path` | string | no | | | — | 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). | + +**Allowed children** + +_No structural children._ + diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index c8074ef011..e61cf6a1dc 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -290,6 +290,7 @@ String-backed enumeration constrained to a closed set of member symbols (@values **Allowed children** - `origin.*` — 0..* +- `transition.*` — 0..* - `validator.*` — 0..* - `view.*` — 0..* diff --git a/fixtures/metamodel-docs/expected/types/metadata.md b/fixtures/metamodel-docs/expected/types/metadata.md index 9f0d40a502..c19913200a 100644 --- a/fixtures/metamodel-docs/expected/types/metadata.md +++ b/fixtures/metamodel-docs/expected/types/metadata.md @@ -20,6 +20,7 @@ _No subtype-specific attributes._ **Allowed children** +- `api.*` — 0..* - `field.*` — 0..* - `object.*` — 0..* - `requirement.*` — 0..* diff --git a/fixtures/metamodel-docs/expected/types/operation.md b/fixtures/metamodel-docs/expected/types/operation.md new file mode 100644 index 0000000000..b51be413d5 --- /dev/null +++ b/fixtures/metamodel-docs/expected/types/operation.md @@ -0,0 +1,73 @@ + + +# Metamodel — `operation` types + +Each section below is one `operation.`. The **Attributes** table lists +the subtype's own + concern-contributed attributes (provider-tagged); universal +documentation attributes are omitted here (see [providers.md](../providers.md)). +**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. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@inputRef` | string | no | | | — | 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 | | | — | 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 | | | — | 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 | | | — | 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 | | | — | 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. | + +**Allowed children** + +- `binding.*` — 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). + +**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** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@errors` | string[] | no | | | — | 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 | | | — | 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 | | | — | 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 | | | — | 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 | | | — | 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 | | | — | 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 | | | — | 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..* + +### 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). + +**When to use:** A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@inputRef` | string | no | | | — | 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. | +| `@many` | boolean | no | | | — | 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. | +| `@objectRef` | string | no | | | — | 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 | | | — | 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 | | | — | 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 | | | — | 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. | + +**Allowed children** + +- `binding.*` — 0..* + diff --git a/fixtures/metamodel-docs/expected/types/transition.md b/fixtures/metamodel-docs/expected/types/transition.md new file mode 100644 index 0000000000..20a5a4b6fb --- /dev/null +++ b/fixtures/metamodel-docs/expected/types/transition.md @@ -0,0 +1,49 @@ + + +# Metamodel — `transition` types + +Each section below is one `transition.`. The **Attributes** table lists +the subtype's own + concern-contributed attributes (provider-tagged); universal +documentation attributes are omitted here (see [providers.md](../providers.md)). +**Allowed children** lists the structural child rules with their cardinality +(`min..max`, `*` = unbounded). + +### transition.action + +An allowed move between two values of a `field.enum`, made by an operation (ADR-0066). A `field.enum` with at least one is a lifecycle, named after the field. Its states are the enum's @values, its initial state the enum's @default, its terminal states the members no transition leaves; none of them has vocabulary of its own. Each transition is held to become a guarded update (`... WHERE id = ? AND IN (@from) [AND @condition]`), its own command when no declared operation claims it, its own permission point and its own wire error. No shell is generated yet: nothing is generated from this vocabulary, and the loader and `verify` only check it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). + +**Rules:** Legal only under a `field.enum` of an `object.entity` (ERR_TRANSITION_NOT_ON_ENTITY). A concrete entity with a lifecycle and a source needs a writable one (ERR_TRANSITION_NOT_ON_ENTITY); on an entity with no source the lifecycle loads and is inert, deriving no command until a source is added. The field must declare @default (ERR_LIFECYCLE_NO_INITIAL). The field is not an array, and @from names at least one state (ERR_BAD_ATTR_VALUE). Names are unique across every lifecycle of the entity, compared without case, and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). A transition belongs to the entity that declares its field and to every entity extending it, never to an entity whose field merely `extends` that field; an inheritor that redeclares the field without extending it is ERR_LIFECYCLE_REDECLARED. + +**When to use:** A status field whose values may only change in certain ways: a request is submitted from draft, approved or rejected from submitted. Declare each allowed move here; once a shell is generated, the generic update path will no longer write the field. A move that leaves the state where it was (from submitted to submitted) records an action that changes nothing but still happened, such as a first approval of two. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@condition` | expression | no | | | — | A guard over the entity's own fields, in the attr.expression grammar: the same name, grammar and meaning as on the cross-field validators. The shell will evaluate it against the loaded row and also put it into the guarded update's WHERE (no shell is generated yet). It cannot read the actor; that is the policy's job. A field the entity does not have, or an expression that is not boolean, is ERR_BAD_ATTR_VALUE. | +| `@from` | string[] | yes | | | — | The states this move may start from: members of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise), at least one (ERR_BAD_ATTR_VALUE when empty). The allowed moves are the business rule itself, so they cannot be computed. | +| `@permission` | string | no | | | — | As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name `..`, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED). | +| `@public` | boolean | no | | | — | As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT. | +| `@to` | string | yes | | | — | The state this move ends in: one member of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise). May equal a member of @from, which records an action that leaves the state where it was. | + +**Allowed children** + +_No structural children._ + +### transition.base + +Registry anchor for the attributes every lifecycle move shares (ADR-0054): not authorable. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@permission` | string | no | | | — | As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name `..`, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED). | +| `@public` | boolean | no | | | — | As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT. | + +**Allowed children** + +_No structural children._ + diff --git a/fixtures/registry-conformance/coverage-report.json b/fixtures/registry-conformance/coverage-report.json index 565641e5c8..8ab7726a43 100644 --- a/fixtures/registry-conformance/coverage-report.json +++ b/fixtures/registry-conformance/coverage-report.json @@ -1,6 +1,6 @@ { - "registeredSubTypeCount": 79, - "exercisedSubTypeCount": 71, + "registeredSubTypeCount": 86, + "exercisedSubTypeCount": 78, "untestedSubTypes": [ "attr.boolean", "attr.class", @@ -101,7 +101,6 @@ "formExclude", "instruction", "mutability", - "sortable", "sortableDefaultOrder", "unique", "xmlText" @@ -146,7 +145,6 @@ "dbColumnType", "default", "example", - "filterable", "formExclude", "instruction", "mutability", @@ -171,7 +169,6 @@ { "key": "field.long", "untestedAttrs": [ - "column", "db.indexed", "dbColumnType", "example", @@ -263,7 +260,6 @@ "dbColumnType", "default", "example", - "filterable", "formExclude", "instruction", "mutability", diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 42273dbdf7..a4d319166d 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -1,6 +1,30 @@ { "metamodelVersion": "1.3", "types": [ + { + "type": "api", + "subType": "base", + "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.", + "attrs": [], + "children": [] + }, + { + "type": "api", + "subType": "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).", + "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).", + "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.", + "attrs": [], + "children": [ + { + "childType": "operation", + "childSubType": "*", + "childName": "*", + "min": 0, + "max": null + } + ] + }, { "type": "attr", "subType": "base", @@ -78,6 +102,43 @@ "attrs": [], "children": [] }, + { + "type": "binding", + "subType": "base", + "description": "Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable.", + "attrs": [], + "children": [] + }, + { + "type": "binding", + "subType": "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).", + "whenToUse": "An operation must keep a method or path the derived one would not give it, such as an existing public URL.", + "attrs": [ + { + "name": "method", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "GET", + "POST", + "PUT", + "PATCH", + "DELETE" + ], + "description": "The HTTP method. Absent: GET for a query, POST for a command." + }, + { + "name": "path", + "valueType": "string", + "isArray": false, + "required": false, + "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)." + } + ], + "children": [] + }, { "type": "dimension", "subType": "attribute", @@ -1343,6 +1404,13 @@ "min": 0, "max": null }, + { + "childType": "transition", + "childSubType": "*", + "childName": "*", + "min": 0, + "max": null + }, { "childType": "validator", "childSubType": "*", @@ -3352,6 +3420,11 @@ "description": "Root metadata document", "attrs": [], "children": [ + { + "childType": "api", + "childSubType": "*", + "childName": "*" + }, { "childType": "field", "childSubType": "*", @@ -3928,6 +4001,182 @@ } ] }, + { + "type": "operation", + "subType": "base", + "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "attrs": [ + { + "name": "inputRef", + "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." + }, + { + "name": "objectRef", + "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)." + }, + { + "name": "outputRef", + "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." + }, + { + "name": "permission", + "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." + }, + { + "name": "public", + "valueType": "boolean", + "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." + } + ], + "children": [ + { + "childType": "binding", + "childSubType": "*", + "childName": "*", + "min": 0, + "max": null + } + ] + }, + { + "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", + "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." + }, + { + "name": "objectRef", + "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)." + }, + { + "name": "outputRef", + "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." + }, + { + "name": "permission", + "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." + }, + { + "name": "public", + "valueType": "boolean", + "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": "*", + "childName": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "operation", + "subType": "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).", + "whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.", + "attrs": [ + { + "name": "inputRef", + "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." + }, + { + "name": "many", + "valueType": "boolean", + "isArray": false, + "required": false, + "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." + }, + { + "name": "objectRef", + "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)." + }, + { + "name": "outputRef", + "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." + }, + { + "name": "permission", + "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." + }, + { + "name": "public", + "valueType": "boolean", + "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." + } + ], + "children": [ + { + "childType": "binding", + "childSubType": "*", + "childName": "*", + "min": 0, + "max": null + } + ] + }, { "type": "origin", "subType": "aggregate", @@ -4984,6 +5233,73 @@ ], "children": [] }, + { + "type": "transition", + "subType": "action", + "description": "An allowed move between two values of a `field.enum`, made by an operation (ADR-0066). A `field.enum` with at least one is a lifecycle, named after the field. Its states are the enum's @values, its initial state the enum's @default, its terminal states the members no transition leaves; none of them has vocabulary of its own. Each transition is held to become a guarded update (`... WHERE id = ? AND IN (@from) [AND @condition]`), its own command when no declared operation claims it, its own permission point and its own wire error. No shell is generated yet: nothing is generated from this vocabulary, and the loader and `verify` only check it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "rules": "Legal only under a `field.enum` of an `object.entity` (ERR_TRANSITION_NOT_ON_ENTITY). A concrete entity with a lifecycle and a source needs a writable one (ERR_TRANSITION_NOT_ON_ENTITY); on an entity with no source the lifecycle loads and is inert, deriving no command until a source is added. The field must declare @default (ERR_LIFECYCLE_NO_INITIAL). The field is not an array, and @from names at least one state (ERR_BAD_ATTR_VALUE). Names are unique across every lifecycle of the entity, compared without case, and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). A transition belongs to the entity that declares its field and to every entity extending it, never to an entity whose field merely `extends` that field; an inheritor that redeclares the field without extending it is ERR_LIFECYCLE_REDECLARED.", + "whenToUse": "A status field whose values may only change in certain ways: a request is submitted from draft, approved or rejected from submitted. Declare each allowed move here; once a shell is generated, the generic update path will no longer write the field. A move that leaves the state where it was (from submitted to submitted) records an action that changes nothing but still happened, such as a first approval of two.", + "attrs": [ + { + "name": "condition", + "valueType": "expression", + "isArray": false, + "required": false, + "description": "A guard over the entity's own fields, in the attr.expression grammar: the same name, grammar and meaning as on the cross-field validators. The shell will evaluate it against the loaded row and also put it into the guarded update's WHERE (no shell is generated yet). It cannot read the actor; that is the policy's job. A field the entity does not have, or an expression that is not boolean, is ERR_BAD_ATTR_VALUE." + }, + { + "name": "from", + "valueType": "string", + "isArray": true, + "required": true, + "description": "The states this move may start from: members of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise), at least one (ERR_BAD_ATTR_VALUE when empty). The allowed moves are the business rule itself, so they cannot be computed." + }, + { + "name": "permission", + "valueType": "string", + "isArray": false, + "required": false, + "description": "As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name `..`, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED)." + }, + { + "name": "public", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." + }, + { + "name": "to", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The state this move ends in: one member of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise). May equal a member of @from, which records an action that leaves the state where it was." + } + ], + "children": [] + }, + { + "type": "transition", + "subType": "base", + "description": "Registry anchor for the attributes every lifecycle move shares (ADR-0054): not authorable.", + "attrs": [ + { + "name": "permission", + "valueType": "string", + "isArray": false, + "required": false, + "description": "As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name `..`, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED)." + }, + { + "name": "public", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." + } + ], + "children": [] + }, { "type": "validator", "subType": "array", diff --git a/fixtures/requirement-check-conformance/README.md b/fixtures/requirement-check-conformance/README.md index 5d77cc2dc7..07061e3703 100644 --- a/fixtures/requirement-check-conformance/README.md +++ b/fixtures/requirement-check-conformance/README.md @@ -107,6 +107,9 @@ it is wrong, unless the reference is shown to be wrong first. | `l4-names-member` | `ERR_REQUIREMENT_L4_NOT_OBJECT` on a functional L4, for a member that exists and for one that does not. | | `l5-names-object` | `ERR_REQUIREMENT_L5_NOT_MEMBER` on a functional L5, for an object that exists and for one that does not. | | `l5-member-resolves-clean` | A functional L5 naming a field, an identity, and a view under a field: no diagnostics. | +| `claim-operation-and-transition` | ADR-0066: a functional L5 naming an operation of a declared API (`Purchasing.decide`) and one naming a lifecycle transition (`PurchaseRequest.status.submit`) both resolve, with no diagnostics. Operations and transitions are member-grain claim targets. | +| `claim-operation-api-in-two-files` | ADR-0066: one `api.operational` declared in two files merges under the loader's general rule, so a claim on an operation from either file (`Purchasing.decide`, `Purchasing.pending`) resolves on the merged API, with no diagnostics. | +| `dangling-operation-and-transition` | The same two claims, renamed out from under the requirement: `ERR_REQUIREMENT_DANGLING_REF` for each, the hint naming the API and the enum field the missing member was looked for under. A renamed operation or transition fails the build. | | `bad-level-out-of-range` | `ERR_REQUIREMENT_BAD_LEVEL` for levels 0 and 6 on functional requirements. The message has no architectural suffix. | | `package-packageless-file-beside-packaged` | A package-less requirements document beside packaged ones: the requirement's package is "", so a bare reference to an entity that lives only in `acme::shop` is `ERR_REQUIREMENT_DANGLING_REF`. A regression pin; every port agrees. | | `package-overlay-child-from-packageless-file` | A child contributed through an `overlay: true` requirement that declares its own package, from a package-less file: the child resolves in the nearest declaring ancestor's package (`acme::shop`), so the reference is clean. | diff --git a/fixtures/requirement-check-conformance/claim-operation-and-transition/expected.json b/fixtures/requirement-check-conformance/claim-operation-and-transition/expected.json new file mode 100644 index 0000000000..0be9b9bb0b --- /dev/null +++ b/fixtures/requirement-check-conformance/claim-operation-and-transition/expected.json @@ -0,0 +1,15 @@ +{ + "diagnostics": [], + "summary": { + "total": 3, + "functional": 3, + "architectural": 0, + "byStatus": { + "live": 3 + }, + "undecided": 0, + "deferredUntracked": 0, + "entitiesClaimed": 1, + "entitiesTotal": 1 + } +} diff --git a/fixtures/requirement-check-conformance/claim-operation-and-transition/input/meta.purchasing.yaml b/fixtures/requirement-check-conformance/claim-operation-and-transition/input/meta.purchasing.yaml new file mode 100644 index 0000000000..23402c38f0 --- /dev/null +++ b/fixtures/requirement-check-conformance/claim-operation-and-transition/input/meta.purchasing.yaml @@ -0,0 +1,53 @@ +metadata: + 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.enum: + name: status + values: [draft, submitted, approved] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - transition.action: { name: approve, from: [submitted], to: approved } + - object.value: + name: ApproveInput + children: + - field.long: { name: requestId, extends: PurchaseRequest.id } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: ApproveInput + transitions: [approve] + permission: purchasing.decide + + - requirement.functional: + name: Approval + level: 4 + status: live + statement: A submitted request can be approved. + counterexample: A submitted request nobody can approve. + implementedBy: [PurchaseRequest] + children: + # An operation of a declared API. + - requirement.functional: + name: Decided + level: 5 + status: live + statement: A reviewer decides a submitted request. + counterexample: A request that waits forever. + implementedBy: [Purchasing.decide] + # A transition of a lifecycle. + - requirement.functional: + name: Submitted + level: 5 + status: live + statement: A draft request can be submitted. + counterexample: A draft that cannot be sent. + implementedBy: [PurchaseRequest.status.submit] diff --git a/fixtures/requirement-check-conformance/claim-operation-api-in-two-files/expected.json b/fixtures/requirement-check-conformance/claim-operation-api-in-two-files/expected.json new file mode 100644 index 0000000000..0be9b9bb0b --- /dev/null +++ b/fixtures/requirement-check-conformance/claim-operation-api-in-two-files/expected.json @@ -0,0 +1,15 @@ +{ + "diagnostics": [], + "summary": { + "total": 3, + "functional": 3, + "architectural": 0, + "byStatus": { + "live": 3 + }, + "undecided": 0, + "deferredUntracked": 0, + "entitiesClaimed": 1, + "entitiesTotal": 1 + } +} diff --git a/fixtures/requirement-check-conformance/claim-operation-api-in-two-files/input/meta.purchasing-review.yaml b/fixtures/requirement-check-conformance/claim-operation-api-in-two-files/input/meta.purchasing-review.yaml new file mode 100644 index 0000000000..fbc5cfb92f --- /dev/null +++ b/fixtures/requirement-check-conformance/claim-operation-api-in-two-files/input/meta.purchasing-review.yaml @@ -0,0 +1,11 @@ +metadata: + package: acme::purchasing + children: + - api.operational: + name: Purchasing + children: + - operation.query: + name: pending + outputRef: PurchaseRequest + many: true + permission: purchasing.review diff --git a/fixtures/requirement-check-conformance/claim-operation-api-in-two-files/input/meta.purchasing.yaml b/fixtures/requirement-check-conformance/claim-operation-api-in-two-files/input/meta.purchasing.yaml new file mode 100644 index 0000000000..f5b67c092b --- /dev/null +++ b/fixtures/requirement-check-conformance/claim-operation-api-in-two-files/input/meta.purchasing.yaml @@ -0,0 +1,54 @@ +# The api.operational "Purchasing" is declared here and again in meta.purchasing-review.yaml. +# Two declarations of one API merge under the loader's general rule (WARN_DUPLICATE_DECLARATION +# across files), so a claim on an operation from either file resolves on the merged API. +metadata: + 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.enum: + name: status + values: [draft, submitted, approved] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - transition.action: { name: approve, from: [submitted], to: approved } + - object.value: + name: ApproveInput + children: + - field.long: { name: requestId, extends: PurchaseRequest.id } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: ApproveInput + transitions: [approve] + permission: purchasing.decide + + - requirement.functional: + name: Approval + level: 4 + status: live + statement: A submitted request can be approved. + counterexample: A submitted request nobody can approve. + implementedBy: [PurchaseRequest] + children: + - requirement.functional: + name: Decided + level: 5 + status: live + statement: A reviewer decides a submitted request. + counterexample: A request that waits forever. + implementedBy: [Purchasing.decide] + - requirement.functional: + name: Reviewed + level: 5 + status: live + statement: A reviewer lists what waits for review. + counterexample: A queue nobody can see. + implementedBy: [Purchasing.pending] diff --git a/fixtures/requirement-check-conformance/dangling-operation-and-transition/expected.json b/fixtures/requirement-check-conformance/dangling-operation-and-transition/expected.json new file mode 100644 index 0000000000..913f195b08 --- /dev/null +++ b/fixtures/requirement-check-conformance/dangling-operation-and-transition/expected.json @@ -0,0 +1,28 @@ +{ + "diagnostics": [ + { + "severity": "error", + "code": "ERR_REQUIREMENT_DANGLING_REF", + "path": "Approval.Decided", + "message": "'Purchasing.decideNow' does not resolve in the loaded model (status 'live' — the model moved and the requirement is stale). 'acme::purchasing::Purchasing' has no member 'decideNow'." + }, + { + "severity": "error", + "code": "ERR_REQUIREMENT_DANGLING_REF", + "path": "Approval.Submitted", + "message": "'PurchaseRequest.status.send' does not resolve in the loaded model (status 'live' — the model moved and the requirement is stale). 'acme::purchasing::PurchaseRequest.status' has no member 'send'." + } + ], + "summary": { + "total": 3, + "functional": 3, + "architectural": 0, + "byStatus": { + "live": 3 + }, + "undecided": 0, + "deferredUntracked": 0, + "entitiesClaimed": 1, + "entitiesTotal": 1 + } +} diff --git a/fixtures/requirement-check-conformance/dangling-operation-and-transition/input/meta.purchasing.yaml b/fixtures/requirement-check-conformance/dangling-operation-and-transition/input/meta.purchasing.yaml new file mode 100644 index 0000000000..bb1944d73f --- /dev/null +++ b/fixtures/requirement-check-conformance/dangling-operation-and-transition/input/meta.purchasing.yaml @@ -0,0 +1,53 @@ +metadata: + 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.enum: + name: status + values: [draft, submitted, approved] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - transition.action: { name: approve, from: [submitted], to: approved } + - object.value: + name: ApproveInput + children: + - field.long: { name: requestId, extends: PurchaseRequest.id } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: ApproveInput + transitions: [approve] + permission: purchasing.decide + + - requirement.functional: + name: Approval + level: 4 + status: live + statement: A submitted request can be approved. + counterexample: A submitted request nobody can approve. + implementedBy: [PurchaseRequest] + children: + # An operation of a declared API. + - requirement.functional: + name: Decided + level: 5 + status: live + statement: A reviewer decides a submitted request. + counterexample: A request that waits forever. + implementedBy: [Purchasing.decideNow] + # A transition of a lifecycle. + - requirement.functional: + name: Submitted + level: 5 + status: live + statement: A draft request can be submitted. + counterexample: A draft that cannot be sent. + implementedBy: [PurchaseRequest.status.send] diff --git a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs index 571f6fbb0e..e11dd100f6 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 (119 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (124 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,6 +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 */ } + // 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 */ } + + // 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 */ } + + // Command — A command takes a declared value as input, names the transitions of its target it may make and the business errors it may return, and its target entity is derived from its input or output whenever it can be. + [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 */ } + + // 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 */ } + + // Transition — A transition names the states it leaves and the state it reaches, all members of its enum, on a field of an entity; an entity with a source needs a writable one, and the lifecycle of an entity with no source is inert. The field's default is the initial state, and verify reports a state nothing reaches. + [Fact(Skip = "unfilled slot — write an assertion that fails when: A status value that a typo in a transition made unreachable, found only when a row needs it.")] + public void declare_businessRules_transitionAction() { /* metaobjects.declare.businessRules.transitionAction */ } + // Element count — An element-count rule bounds how many entries a repeated value may hold. [Fact(Skip = "unfilled slot — write an assertion that fails when: An unbounded list accepted into a field whose reader only ever looks at the first few.")] public void declare_constraints_validatorArray() { /* metaobjects.declare.constraints.validatorArray */ } diff --git a/fixtures/requirement-harness/java/RequirementHarnessTest.java b/fixtures/requirement-harness/java/RequirementHarnessTest.java index c30bdd237f..fb187f2e09 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 (119 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (124 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,6 +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 */ } + // 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 */ } + + // 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.") + void declare_businessRules_bindingRest() { /* metaobjects.declare.businessRules.bindingRest */ } + + // Command — A command takes a declared value as input, names the transitions of its target it may make and the business errors it may return, and its target entity is derived from its input or output whenever it can be. + @Test + @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 */ } + + // 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.") + void declare_businessRules_operationQuery() { /* metaobjects.declare.businessRules.operationQuery */ } + + // Transition — A transition names the states it leaves and the state it reaches, all members of its enum, on a field of an entity; an entity with a source needs a writable one, and the lifecycle of an entity with no source is inert. The field's default is the initial state, and verify reports a state nothing reaches. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A status value that a typo in a transition made unreachable, found only when a row needs it.") + void declare_businessRules_transitionAction() { /* metaobjects.declare.businessRules.transitionAction */ } + // Element count — An element-count rule bounds how many entries a repeated value may hold. @Test @Disabled("unfilled slot — write an assertion that fails when: An unbounded list accepted into a field whose reader only ever looks at the first few.") diff --git a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt index 3df6053bf9..e34981c758 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 (119 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (124 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,6 +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 */ } + // 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 */ } + + // 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.") + fun declare_businessRules_bindingRest() { /* metaobjects.declare.businessRules.bindingRest */ } + + // Command — A command takes a declared value as input, names the transitions of its target it may make and the business errors it may return, and its target entity is derived from its input or output whenever it can be. + @Test + @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 */ } + + // 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.") + fun declare_businessRules_operationQuery() { /* metaobjects.declare.businessRules.operationQuery */ } + + // Transition — A transition names the states it leaves and the state it reaches, all members of its enum, on a field of an entity; an entity with a source needs a writable one, and the lifecycle of an entity with no source is inert. The field's default is the initial state, and verify reports a state nothing reaches. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A status value that a typo in a transition made unreachable, found only when a row needs it.") + fun declare_businessRules_transitionAction() { /* metaobjects.declare.businessRules.transitionAction */ } + // Element count — An element-count rule bounds how many entries a repeated value may hold. @Test @Disabled("unfilled slot — write an assertion that fails when: An unbounded list accepted into a field whose reader only ever looks at the first few.") diff --git a/fixtures/requirement-harness/python/test_requirement_harness.py b/fixtures/requirement-harness/python/test_requirement_harness.py index 27077e27e3..f8be0373e5 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 (119 of them). +# One slot per authored promise in metaobjects/meta.requirements.yaml (124 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,6 +57,31 @@ def test_declare_attributeValueTypes_attrProperties(): def test_declare_attributeValueTypes_attrString(): """metaobjects.declare.attributeValueTypes.attrString""" +# 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""" + +# 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(): + """metaobjects.declare.businessRules.bindingRest""" + +# Command — A command takes a declared value as input, names the transitions of its target it may make and the business errors it may return, and its target entity is derived from its input or output whenever it can be. +@pytest.mark.skip(reason="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.") +def test_declare_businessRules_operationCommand(): + """metaobjects.declare.businessRules.operationCommand""" + +# 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(): + """metaobjects.declare.businessRules.operationQuery""" + +# Transition — A transition names the states it leaves and the state it reaches, all members of its enum, on a field of an entity; an entity with a source needs a writable one, and the lifecycle of an entity with no source is inert. The field's default is the initial state, and verify reports a state nothing reaches. +@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A status value that a typo in a transition made unreachable, found only when a row needs it.") +def test_declare_businessRules_transitionAction(): + """metaobjects.declare.businessRules.transitionAction""" + # Element count — An element-count rule bounds how many entries a repeated value may hold. @pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: An unbounded list accepted into a field whose reader only ever looks at the first few.") def test_declare_constraints_validatorArray(): diff --git a/fixtures/requirement-harness/typescript/requirement-harness.test.ts b/fixtures/requirement-harness/typescript/requirement-harness.test.ts index 0c74868202..3ec4b2aa72 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 (119 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (124 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,6 +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. }); +// 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. +}); + +// 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. +}); + +// Command — A command takes a declared value as input, names the transitions of its target it may make and the business errors it may return, and its target entity is derived from its input or output whenever it can be. +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. +}); + +// 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. +}); + +// Transition — A transition names the states it leaves and the state it reaches, all members of its enum, on a field of an entity; an entity with a source needs a writable one, and the lifecycle of an entity with no source is inert. The field's default is the initial state, and verify reports a state nothing reaches. +test.skip("metaobjects.declare.businessRules.transitionAction", () => { + // unfilled slot — write an assertion that fails when: A status value that a typo in a transition made unreachable, found only when a row needs it. +}); + // Element count — An element-count rule bounds how many entries a repeated value may hold. test.skip("metaobjects.declare.constraints.validatorArray", () => { // unfilled slot — write an assertion that fails when: An unbounded list accepted into a field whose reader only ever looks at the first few. diff --git a/fixtures/requirement-test-identity-conformance/README.md b/fixtures/requirement-test-identity-conformance/README.md index d29f1570ab..5a11a7e0d1 100644 --- a/fixtures/requirement-test-identity-conformance/README.md +++ b/fixtures/requirement-test-identity-conformance/README.md @@ -205,6 +205,7 @@ function in each port: the address `acme::shop::Café.Réglé` with unit `*` giv | `filter-by-package` | `filter: package-acme-shop` over two files: a root requirement and a nested one take their file's package; one requirement in each file declares the other file's package, and its child, which declares none, takes that package too. The kept set follows the effective package, not the file, and a kept requirement's bare reference binds in its effective package. Pins `package`. | | `filter-by-path` | `filter: path-under-Shop`: `Shop` and both its descendants are kept. `Shopfront` and its child are not. Pins `path` as the whole dotted chain, without the package. | | `filter-by-claimed-concern` | `filter: claims-entity`: requirements claiming an entity are kept, a flat policy among them. One claiming only a template and one naming only a node that does not exist are dropped. Pins `implementedByTypes` as the concerns that resolved. | +| `claims-operation-and-transition` | One requirement claiming an entity, an operation of a declared API and two transitions of one lifecycle yields three tests: `object.entity`, `operation.command` and `transition.action`. An operation is addressed `.` and a transition `..`. | ## Who asserts it diff --git a/fixtures/requirement-test-identity-conformance/claims-operation-and-transition/expected.json b/fixtures/requirement-test-identity-conformance/claims-operation-and-transition/expected.json new file mode 100644 index 0000000000..a38a8f14cf --- /dev/null +++ b/fixtures/requirement-test-identity-conformance/claims-operation-and-transition/expected.json @@ -0,0 +1,35 @@ +{ + "tests": [ + { + "id": "acme::purchasing::Approval [object.entity]", + "package": "acme::purchasing", + "path": "Approval", + "unit": "object.entity", + "witnessKey": "req_acme_purchasing_Approval__object_entity", + "status": "live", + "skip": null, + "digest": "6fcb27ec98c08c12c7ab5c2368ca3ea27ebf2205b51c4196059227f947cae85e" + }, + { + "id": "acme::purchasing::Approval [operation.command]", + "package": "acme::purchasing", + "path": "Approval", + "unit": "operation.command", + "witnessKey": "req_acme_purchasing_Approval__operation_command", + "status": "live", + "skip": null, + "digest": "6fcb27ec98c08c12c7ab5c2368ca3ea27ebf2205b51c4196059227f947cae85e" + }, + { + "id": "acme::purchasing::Approval [transition.action]", + "package": "acme::purchasing", + "path": "Approval", + "unit": "transition.action", + "witnessKey": "req_acme_purchasing_Approval__transition_action", + "status": "live", + "skip": null, + "digest": "6fcb27ec98c08c12c7ab5c2368ca3ea27ebf2205b51c4196059227f947cae85e" + } + ], + "collisions": [] +} diff --git a/fixtures/requirement-test-identity-conformance/claims-operation-and-transition/input/meta.purchasing.yaml b/fixtures/requirement-test-identity-conformance/claims-operation-and-transition/input/meta.purchasing.yaml new file mode 100644 index 0000000000..eaeeb685ea --- /dev/null +++ b/fixtures/requirement-test-identity-conformance/claims-operation-and-transition/input/meta.purchasing.yaml @@ -0,0 +1,37 @@ +metadata: + 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.enum: + name: status + values: [draft, submitted, approved] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - transition.action: { name: approve, from: [submitted], to: approved } + - object.value: + name: ApproveInput + children: + - field.long: { name: requestId, extends: PurchaseRequest.id } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: ApproveInput + transitions: [approve] + permission: purchasing.decide + + # Four references, three concerns: two transitions of one lifecycle are one concern. + - requirement.functional: + name: Approval + level: 4 + status: live + statement: A submitted request can be approved. + counterexample: A submitted request nobody can approve. + implementedBy: [PurchaseRequest, Purchasing.decide, PurchaseRequest.status.submit, PurchaseRequest.status.approve] diff --git a/fixtures/rules-check-conformance/README.md b/fixtures/rules-check-conformance/README.md new file mode 100644 index 0000000000..efb7fd7e81 --- /dev/null +++ b/fixtures/rules-check-conformance/README.md @@ -0,0 +1,99 @@ +# `verify` business-rules conformance corpus + +Every port's `verify` runs the **rules gate** (ADR-0066): it reads the declared operations +(`api.operational` / `operation.*`) and lifecycles (`transition.action` under a `field.enum`) +of a loaded model and reports what loads clean but is almost certainly not what the author +meant. The loader already refuses a malformed operation or lifecycle; those errors are pinned +by `fixtures/conformance/` (`error-rules-*`), not here. This corpus is the shared source of +truth for the gate's codes, severities, node addresses, message text and summary counts. + +TypeScript is the reference: `server/typescript/packages/cli/src/lib/rules-check.ts`. A port +reads that file before it writes its own checks, and its test suite runs this corpus. + +It is a corpus of its own rather than a part of `fixtures/verify-conformance/`, which gates the +template (Mustache) drift check and has a different case shape. Its shape is the one +`fixtures/requirement-check-conformance/` uses, because the two gates do the same kind of +work: read a loaded model, report diagnostics. + +## The checks + +| Code | Severity | When | +|---|---|---| +| `WARN_LIFECYCLE_UNREACHABLE_STATE` | `verify.lifecycle.unreachable` (default `warn`; `off` skips it) | A member of a lifecycle's enum that no chain of transitions reaches from the initial state (`@default`). One diagnostic per lifecycle, listing the states in `@values` order. | +| `WARN_LIFECYCLE_INITIAL_TERMINAL` | `warn` | The initial state is terminal: no transition lists it in `@from` (a self-transition counts as leaving). | +| `WARN_TRANSITION_UNREACHABLE` | `verify.lifecycle.unreachable` | A transition whose every `@from` state is unreachable, so it can never be made. | +| `WARN_TRANSITION_PERMISSION_SHADOWED` | `warn` | A transition that declares `@permission` or `@public: true` but derives no command of its own for any concrete entity with a source that carries it, so nothing reads the attribute: every carrier's transition is claimed by a declared command (`rules.lifecycle.commands: unclaimed`), or `rules.lifecycle.commands` is `none`. Never reported under `all`. One diagnostic per transition node, at its declaring address, naming the claiming commands as `.`. | +| `WARN_PERMISSION_DERIVED_NAME` | `rules.permissions.names`: `derive` (default) skips it, `advise` warns, `require` errors | An operation, or a transition that derives a command of its own, with no `@permission` and not `@public: true`. Which transitions derive a command is `rules.lifecycle.commands`: `unclaimed` (default) means those no declared command claims for that entity, `all` means every transition, `none` means none. | + +A command claims a transition NODE, for its target entity and every entity that extends the +target: a command whose target is an abstract base claims the inherited transition of each +concrete child, and one whose target is a child claims it for that child only. + +The code keeps its `WARN_` prefix at every severity, as `WARN_REQUIREMENT_NOTHING_IMPLEMENTS` +does under `--require-implementers`. + +Order of evaluation, which is the order the reference reports in (not part of the contract): +each lifecycle once per DECLARING field, walking the root's entities in load order (abstract +included) — unreachable states, then initial-terminal, then each unreachable transition; then +each shadowed transition permission, per transition node; then the derived-command permission check per CONCRETE entity with a source, over its effective transitions in +field order; then each operation of each `api.operational` in load order. + +A lifecycle declared on an abstract base is checked once, at its declaring field. A derived +command exists per concrete entity that has a source (declared or inherited), so the +permission check names each such entity, with the path `::..`. +A lifecycle on an entity with no source is inert: its shape is checked (unreachable states, +initial-terminal), but it derives no command, so the permission and shadowed checks skip it. + +The derived permission name includes its owner. For a declared operation it is +`.`, with the package of the operation's API (the loader keeps operation +names unique per package). For a transition's derived command it is +`..`, with the concrete entity's package and name, so two entities' +`cancel` transitions ask about different permissions. With no package the `.` prefix is +dropped. + +## Fixture format + +Each case is a directory: + +- `input/` holds one or more metadata documents (`.yaml` or `.json`). +- `options.json` is optional. It holds the `rules` and `verify` blocks of + `.metaobjects/config.json` exactly as a project writes them, and nothing else. A port runs + them through its own config reader, so a key that reader does not know fails the case. +- `expected.json` holds `{ "diagnostics": [...], "summary": {...} | null }`. + +A runner loads `input/` strict, in ascending file-name order, asserts no load errors, reads the +settings from `options.json` (each absent key at its default), runs the gate and compares. + +`diagnostics` is an unordered multiset of `(severity, code, path, message)`. `path` is the +package-qualified dotted address of the node: `acme::purchasing::PurchaseRequest.status`. +`message` is compared exactly. + +`summary` is `null` when the model declares no operation and no transition (then `verify` +prints nothing and lists no `rules` gate). Otherwise it holds `operations` (declared +operations across every `api.operational`), `lifecycles` (enum fields with at least one +transition, counted once per declaring field) and `transitions` (across those lifecycles). + +`bun scripts/write-requirement-corpus-expected.ts rules` writes every `expected.json` from the +TypeScript reference. Review each written file by hand. A committed `expected.json` is never +edited to make a port pass. + +## Cases + +| Case | What it pins | +|---|---| +| `no-rules` | An entity with an enum and no transition, and no API: no diagnostics, and `summary` is `null`. | +| `clean-default-settings` | A full lifecycle (with a self-transition and a `@public` one), two commands and two queries, at the default settings: no diagnostics. | +| `lifecycle-create-any` | The same model with `rules.lifecycle.create: any`: the key is read and changes nothing `verify` reports. | +| `permission-names-advise` | `rules.permissions.names: advise`: warns on the unclaimed `submit` transition and on the two operations without `@permission`; not on a claimed transition, one with `@permission`, or anything `@public`. | +| `permission-names-require` | The same findings as errors under `require`. | +| `permission-names-commands-all` | `rules.lifecycle.commands: all`: the claimed transitions derive commands too, so they are reported as well. | +| `permission-names-commands-none` | `rules.lifecycle.commands: none`: no transition derives a command, so only operations are reported for permission names, and each transition declaring `@permission` or `@public: true` is reported as shadowed. | +| `unreachable-state` | Two unreachable states reported in one diagnostic, and the transition that starts only from them; a transition with one reachable `@from` state is not reported. | +| `unreachable-state-error` | The same findings as errors under `verify.lifecycle.unreachable: error`. | +| `unreachable-state-off` | Nothing under `verify.lifecycle.unreachable: off`. | +| `initial-terminal` | An initial state no transition leaves (with the unreachable checks off, to isolate it). | +| `inherited-lifecycle` | A lifecycle on an abstract base: its unreachable state is reported once at the base's field, and the derived-command permission check names each concrete entity. | +| `permission-shadowed-claimed` | `WARN_TRANSITION_PERMISSION_SHADOWED` at the default settings: a claimed transition with `@public: true` and one with `@permission` claimed by two commands (both named) are reported; an unclaimed transition with `@permission` is not. | +| `claimed-abstract-target` | Under `require`, a command whose target is an abstract base (its input borrows the base's key) claims the inherited transition of each concrete child, so neither child is reported. | +| `sourceless-lifecycle-inert` | Under `require`, two entities with a `publish` transition: the sourced one is reported with the owner-qualified name `acme::catalog.Product.publish`; the one with no source is inert, so its unreachable state is still reported but its transitions are not, and its claimed transition with `@permission` is not reported as shadowed. | +| `operations-only` | A model with operations and no lifecycle, under `require`: an operation without `@permission` is an error, and one with it is clean. | diff --git a/fixtures/rules-check-conformance/claimed-abstract-target/expected.json b/fixtures/rules-check-conformance/claimed-abstract-target/expected.json new file mode 100644 index 0000000000..01628a3f9f --- /dev/null +++ b/fixtures/rules-check-conformance/claimed-abstract-target/expected.json @@ -0,0 +1,8 @@ +{ + "diagnostics": [], + "summary": { + "operations": 1, + "lifecycles": 1, + "transitions": 1 + } +} diff --git a/fixtures/rules-check-conformance/claimed-abstract-target/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/claimed-abstract-target/input/meta.purchasing.yaml new file mode 100644 index 0000000000..092846d533 --- /dev/null +++ b/fixtures/rules-check-conformance/claimed-abstract-target/input/meta.purchasing.yaml @@ -0,0 +1,37 @@ +metadata: + package: acme::purchasing + children: + - object.entity: + name: Request + abstract: true + children: + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - field.enum: + name: status + values: [draft, submitted] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - object.entity: + name: PurchaseRequest + extends: Request + children: + - source.rdb: { table: purchase_requests } + - object.entity: + name: TravelRequest + extends: Request + children: + - source.rdb: { table: travel_requests } + - object.value: + name: SubmitInput + children: + - field.long: { name: requestId, extends: Request.id } + - api.operational: + name: Requests + children: + - operation.command: + name: submitRequest + inputRef: SubmitInput + transitions: [submit] + permission: requests.submit diff --git a/fixtures/rules-check-conformance/claimed-abstract-target/options.json b/fixtures/rules-check-conformance/claimed-abstract-target/options.json new file mode 100644 index 0000000000..0e8ef94e10 --- /dev/null +++ b/fixtures/rules-check-conformance/claimed-abstract-target/options.json @@ -0,0 +1 @@ +{ "rules": { "permissions": { "names": "require" } } } diff --git a/fixtures/rules-check-conformance/clean-default-settings/expected.json b/fixtures/rules-check-conformance/clean-default-settings/expected.json new file mode 100644 index 0000000000..9ec02cb2a3 --- /dev/null +++ b/fixtures/rules-check-conformance/clean-default-settings/expected.json @@ -0,0 +1,8 @@ +{ + "diagnostics": [], + "summary": { + "operations": 4, + "lifecycles": 1, + "transitions": 5 + } +} diff --git a/fixtures/rules-check-conformance/clean-default-settings/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/clean-default-settings/input/meta.purchasing.yaml new file mode 100644 index 0000000000..dc1fdce62d --- /dev/null +++ b/fixtures/rules-check-conformance/clean-default-settings/input/meta.purchasing.yaml @@ -0,0 +1,43 @@ +metadata: + 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.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 } + - transition.action: { name: reject, from: [submitted], to: rejected, permission: purchasing.review } + - transition.action: { name: approveFirst, from: [submitted], to: submitted } + - transition.action: { name: withdraw, from: [submitted], to: draft, public: true } + - 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 } + - identity.primary: { name: pk, extends: PurchaseRequest.pk } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: DecisionInput + transitions: [approve, approveFirst] + - operation.command: + name: escalate + inputRef: DecisionInput + permission: purchasing.escalate + - operation.query: { name: openRequests, outputRef: RequestSummary, many: true, public: true } + - operation.query: { name: requestSummary, outputRef: RequestSummary } diff --git a/fixtures/rules-check-conformance/inherited-lifecycle/expected.json b/fixtures/rules-check-conformance/inherited-lifecycle/expected.json new file mode 100644 index 0000000000..10b8a91230 --- /dev/null +++ b/fixtures/rules-check-conformance/inherited-lifecycle/expected.json @@ -0,0 +1,27 @@ +{ + "diagnostics": [ + { + "severity": "warn", + "code": "WARN_LIFECYCLE_UNREACHABLE_STATE", + "path": "acme::purchasing::Request.status", + "message": "state \"archived\" of \"status\" cannot be reached from the initial state \"draft\" by any transition. Add the transition that leads there, or set verify.lifecycle.unreachable if only seeded data uses it." + }, + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::PurchaseRequest.status.submit", + "message": "the command derived from transition \"submit\" of \"PurchaseRequest\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.PurchaseRequest.submit\", which changes if the transition is renamed. Declare @permission, or @public: true." + }, + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::TravelRequest.status.submit", + "message": "the command derived from transition \"submit\" of \"TravelRequest\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.TravelRequest.submit\", which changes if the transition is renamed. Declare @permission, or @public: true." + } + ], + "summary": { + "operations": 0, + "lifecycles": 1, + "transitions": 1 + } +} diff --git a/fixtures/rules-check-conformance/inherited-lifecycle/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/inherited-lifecycle/input/meta.purchasing.yaml new file mode 100644 index 0000000000..8a4366f4d7 --- /dev/null +++ b/fixtures/rules-check-conformance/inherited-lifecycle/input/meta.purchasing.yaml @@ -0,0 +1,25 @@ +metadata: + package: acme::purchasing + children: + - object.entity: + name: Request + abstract: true + children: + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - field.enum: + name: status + values: [draft, submitted, archived] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - object.entity: + name: PurchaseRequest + extends: Request + children: + - source.rdb: { table: purchase_requests } + - object.entity: + name: TravelRequest + extends: Request + children: + - source.rdb: { table: travel_requests } diff --git a/fixtures/rules-check-conformance/inherited-lifecycle/options.json b/fixtures/rules-check-conformance/inherited-lifecycle/options.json new file mode 100644 index 0000000000..33166eec10 --- /dev/null +++ b/fixtures/rules-check-conformance/inherited-lifecycle/options.json @@ -0,0 +1 @@ +{ "rules": { "permissions": { "names": "advise" } } } diff --git a/fixtures/rules-check-conformance/initial-terminal/expected.json b/fixtures/rules-check-conformance/initial-terminal/expected.json new file mode 100644 index 0000000000..368fdc8547 --- /dev/null +++ b/fixtures/rules-check-conformance/initial-terminal/expected.json @@ -0,0 +1,15 @@ +{ + "diagnostics": [ + { + "severity": "warn", + "code": "WARN_LIFECYCLE_INITIAL_TERMINAL", + "path": "acme::purchasing::Ticket.status", + "message": "the initial state \"closed\" of \"status\" is terminal: no transition leaves it, so no row of this lifecycle can ever move." + } + ], + "summary": { + "operations": 0, + "lifecycles": 1, + "transitions": 1 + } +} diff --git a/fixtures/rules-check-conformance/initial-terminal/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/initial-terminal/input/meta.purchasing.yaml new file mode 100644 index 0000000000..0bce3d4562 --- /dev/null +++ b/fixtures/rules-check-conformance/initial-terminal/input/meta.purchasing.yaml @@ -0,0 +1,15 @@ +metadata: + package: acme::purchasing + children: + - object.entity: + name: Ticket + children: + - source.rdb: { table: tickets } + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - field.enum: + name: status + values: [open, closed] + default: closed + children: + - transition.action: { name: close, from: [open], to: closed } diff --git a/fixtures/rules-check-conformance/initial-terminal/options.json b/fixtures/rules-check-conformance/initial-terminal/options.json new file mode 100644 index 0000000000..a03049bf31 --- /dev/null +++ b/fixtures/rules-check-conformance/initial-terminal/options.json @@ -0,0 +1 @@ +{ "verify": { "lifecycle": { "unreachable": "off" } } } diff --git a/fixtures/rules-check-conformance/lifecycle-create-any/expected.json b/fixtures/rules-check-conformance/lifecycle-create-any/expected.json new file mode 100644 index 0000000000..9ec02cb2a3 --- /dev/null +++ b/fixtures/rules-check-conformance/lifecycle-create-any/expected.json @@ -0,0 +1,8 @@ +{ + "diagnostics": [], + "summary": { + "operations": 4, + "lifecycles": 1, + "transitions": 5 + } +} diff --git a/fixtures/rules-check-conformance/lifecycle-create-any/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/lifecycle-create-any/input/meta.purchasing.yaml new file mode 100644 index 0000000000..dc1fdce62d --- /dev/null +++ b/fixtures/rules-check-conformance/lifecycle-create-any/input/meta.purchasing.yaml @@ -0,0 +1,43 @@ +metadata: + 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.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 } + - transition.action: { name: reject, from: [submitted], to: rejected, permission: purchasing.review } + - transition.action: { name: approveFirst, from: [submitted], to: submitted } + - transition.action: { name: withdraw, from: [submitted], to: draft, public: true } + - 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 } + - identity.primary: { name: pk, extends: PurchaseRequest.pk } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: DecisionInput + transitions: [approve, approveFirst] + - operation.command: + name: escalate + inputRef: DecisionInput + permission: purchasing.escalate + - operation.query: { name: openRequests, outputRef: RequestSummary, many: true, public: true } + - operation.query: { name: requestSummary, outputRef: RequestSummary } diff --git a/fixtures/rules-check-conformance/lifecycle-create-any/options.json b/fixtures/rules-check-conformance/lifecycle-create-any/options.json new file mode 100644 index 0000000000..b2c82d2474 --- /dev/null +++ b/fixtures/rules-check-conformance/lifecycle-create-any/options.json @@ -0,0 +1 @@ +{ "rules": { "lifecycle": { "create": "any" } } } diff --git a/fixtures/rules-check-conformance/no-rules/expected.json b/fixtures/rules-check-conformance/no-rules/expected.json new file mode 100644 index 0000000000..7aba952d13 --- /dev/null +++ b/fixtures/rules-check-conformance/no-rules/expected.json @@ -0,0 +1,4 @@ +{ + "diagnostics": [], + "summary": null +} diff --git a/fixtures/rules-check-conformance/no-rules/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/no-rules/input/meta.purchasing.yaml new file mode 100644 index 0000000000..40767e20ea --- /dev/null +++ b/fixtures/rules-check-conformance/no-rules/input/meta.purchasing.yaml @@ -0,0 +1,10 @@ +metadata: + 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.enum: { name: status, values: [draft, submitted], default: draft } diff --git a/fixtures/rules-check-conformance/operations-only/expected.json b/fixtures/rules-check-conformance/operations-only/expected.json new file mode 100644 index 0000000000..b3d9986e21 --- /dev/null +++ b/fixtures/rules-check-conformance/operations-only/expected.json @@ -0,0 +1,15 @@ +{ + "diagnostics": [ + { + "severity": "error", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::reports::Dashboard.totals", + "message": "operation.query \"totals\" has no @permission, so it asks the policy about the derived name \"acme::reports.totals\", which changes if the operation is renamed. Declare @permission, or @public: true." + } + ], + "summary": { + "operations": 2, + "lifecycles": 0, + "transitions": 0 + } +} diff --git a/fixtures/rules-check-conformance/operations-only/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/operations-only/input/meta.purchasing.yaml new file mode 100644 index 0000000000..53eca0da8e --- /dev/null +++ b/fixtures/rules-check-conformance/operations-only/input/meta.purchasing.yaml @@ -0,0 +1,19 @@ +metadata: + package: acme::reports + children: + - object.entity: + name: Order + children: + - source.rdb: { table: orders } + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - field.long: { name: totalCents } + - object.value: + name: Totals + children: + - field.long: { name: totalCents } + - api.operational: + name: Dashboard + children: + - operation.query: { name: totals, outputRef: Totals } + - operation.query: { name: recentOrders, outputRef: Order, many: true, permission: reports.read } diff --git a/fixtures/rules-check-conformance/operations-only/options.json b/fixtures/rules-check-conformance/operations-only/options.json new file mode 100644 index 0000000000..0e8ef94e10 --- /dev/null +++ b/fixtures/rules-check-conformance/operations-only/options.json @@ -0,0 +1 @@ +{ "rules": { "permissions": { "names": "require" } } } diff --git a/fixtures/rules-check-conformance/permission-names-advise/expected.json b/fixtures/rules-check-conformance/permission-names-advise/expected.json new file mode 100644 index 0000000000..740e0e0939 --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-advise/expected.json @@ -0,0 +1,27 @@ +{ + "diagnostics": [ + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::PurchaseRequest.status.submit", + "message": "the command derived from transition \"submit\" of \"PurchaseRequest\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.PurchaseRequest.submit\", which changes if the transition is renamed. Declare @permission, or @public: true." + }, + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::Purchasing.decide", + "message": "operation.command \"decide\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.decide\", which changes if the operation is renamed. Declare @permission, or @public: true." + }, + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::Purchasing.requestSummary", + "message": "operation.query \"requestSummary\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.requestSummary\", which changes if the operation is renamed. Declare @permission, or @public: true." + } + ], + "summary": { + "operations": 4, + "lifecycles": 1, + "transitions": 5 + } +} diff --git a/fixtures/rules-check-conformance/permission-names-advise/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/permission-names-advise/input/meta.purchasing.yaml new file mode 100644 index 0000000000..dc1fdce62d --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-advise/input/meta.purchasing.yaml @@ -0,0 +1,43 @@ +metadata: + 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.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 } + - transition.action: { name: reject, from: [submitted], to: rejected, permission: purchasing.review } + - transition.action: { name: approveFirst, from: [submitted], to: submitted } + - transition.action: { name: withdraw, from: [submitted], to: draft, public: true } + - 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 } + - identity.primary: { name: pk, extends: PurchaseRequest.pk } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: DecisionInput + transitions: [approve, approveFirst] + - operation.command: + name: escalate + inputRef: DecisionInput + permission: purchasing.escalate + - operation.query: { name: openRequests, outputRef: RequestSummary, many: true, public: true } + - operation.query: { name: requestSummary, outputRef: RequestSummary } diff --git a/fixtures/rules-check-conformance/permission-names-advise/options.json b/fixtures/rules-check-conformance/permission-names-advise/options.json new file mode 100644 index 0000000000..33166eec10 --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-advise/options.json @@ -0,0 +1 @@ +{ "rules": { "permissions": { "names": "advise" } } } diff --git a/fixtures/rules-check-conformance/permission-names-commands-all/expected.json b/fixtures/rules-check-conformance/permission-names-commands-all/expected.json new file mode 100644 index 0000000000..35923eadcd --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-commands-all/expected.json @@ -0,0 +1,39 @@ +{ + "diagnostics": [ + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::PurchaseRequest.status.submit", + "message": "the command derived from transition \"submit\" of \"PurchaseRequest\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.PurchaseRequest.submit\", which changes if the transition is renamed. Declare @permission, or @public: true." + }, + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::PurchaseRequest.status.approve", + "message": "the command derived from transition \"approve\" of \"PurchaseRequest\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.PurchaseRequest.approve\", which changes if the transition is renamed. Declare @permission, or @public: true." + }, + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::PurchaseRequest.status.approveFirst", + "message": "the command derived from transition \"approveFirst\" of \"PurchaseRequest\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.PurchaseRequest.approveFirst\", which changes if the transition is renamed. Declare @permission, or @public: true." + }, + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::Purchasing.decide", + "message": "operation.command \"decide\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.decide\", which changes if the operation is renamed. Declare @permission, or @public: true." + }, + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::Purchasing.requestSummary", + "message": "operation.query \"requestSummary\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.requestSummary\", which changes if the operation is renamed. Declare @permission, or @public: true." + } + ], + "summary": { + "operations": 4, + "lifecycles": 1, + "transitions": 5 + } +} diff --git a/fixtures/rules-check-conformance/permission-names-commands-all/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/permission-names-commands-all/input/meta.purchasing.yaml new file mode 100644 index 0000000000..dc1fdce62d --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-commands-all/input/meta.purchasing.yaml @@ -0,0 +1,43 @@ +metadata: + 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.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 } + - transition.action: { name: reject, from: [submitted], to: rejected, permission: purchasing.review } + - transition.action: { name: approveFirst, from: [submitted], to: submitted } + - transition.action: { name: withdraw, from: [submitted], to: draft, public: true } + - 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 } + - identity.primary: { name: pk, extends: PurchaseRequest.pk } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: DecisionInput + transitions: [approve, approveFirst] + - operation.command: + name: escalate + inputRef: DecisionInput + permission: purchasing.escalate + - operation.query: { name: openRequests, outputRef: RequestSummary, many: true, public: true } + - operation.query: { name: requestSummary, outputRef: RequestSummary } diff --git a/fixtures/rules-check-conformance/permission-names-commands-all/options.json b/fixtures/rules-check-conformance/permission-names-commands-all/options.json new file mode 100644 index 0000000000..f558c41ae7 --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-commands-all/options.json @@ -0,0 +1 @@ +{ "rules": { "permissions": { "names": "advise" }, "lifecycle": { "commands": "all" } } } diff --git a/fixtures/rules-check-conformance/permission-names-commands-none/expected.json b/fixtures/rules-check-conformance/permission-names-commands-none/expected.json new file mode 100644 index 0000000000..063c3579a6 --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-commands-none/expected.json @@ -0,0 +1,33 @@ +{ + "diagnostics": [ + { + "severity": "warn", + "code": "WARN_TRANSITION_PERMISSION_SHADOWED", + "path": "acme::purchasing::PurchaseRequest.status.reject", + "message": "transition \"reject\" declares @permission \"purchasing.review\", but rules.lifecycle.commands is \"none\": no command is derived from it, so the attribute is never read. Remove it from the transition, or declare it on the command that makes the transition." + }, + { + "severity": "warn", + "code": "WARN_TRANSITION_PERMISSION_SHADOWED", + "path": "acme::purchasing::PurchaseRequest.status.withdraw", + "message": "transition \"withdraw\" declares @public: true, but rules.lifecycle.commands is \"none\": no command is derived from it, so the attribute is never read. Remove it from the transition, or declare it on the command that makes the transition." + }, + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::Purchasing.decide", + "message": "operation.command \"decide\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.decide\", which changes if the operation is renamed. Declare @permission, or @public: true." + }, + { + "severity": "warn", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::Purchasing.requestSummary", + "message": "operation.query \"requestSummary\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.requestSummary\", which changes if the operation is renamed. Declare @permission, or @public: true." + } + ], + "summary": { + "operations": 4, + "lifecycles": 1, + "transitions": 5 + } +} diff --git a/fixtures/rules-check-conformance/permission-names-commands-none/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/permission-names-commands-none/input/meta.purchasing.yaml new file mode 100644 index 0000000000..dc1fdce62d --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-commands-none/input/meta.purchasing.yaml @@ -0,0 +1,43 @@ +metadata: + 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.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 } + - transition.action: { name: reject, from: [submitted], to: rejected, permission: purchasing.review } + - transition.action: { name: approveFirst, from: [submitted], to: submitted } + - transition.action: { name: withdraw, from: [submitted], to: draft, public: true } + - 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 } + - identity.primary: { name: pk, extends: PurchaseRequest.pk } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: DecisionInput + transitions: [approve, approveFirst] + - operation.command: + name: escalate + inputRef: DecisionInput + permission: purchasing.escalate + - operation.query: { name: openRequests, outputRef: RequestSummary, many: true, public: true } + - operation.query: { name: requestSummary, outputRef: RequestSummary } diff --git a/fixtures/rules-check-conformance/permission-names-commands-none/options.json b/fixtures/rules-check-conformance/permission-names-commands-none/options.json new file mode 100644 index 0000000000..d969462b5d --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-commands-none/options.json @@ -0,0 +1 @@ +{ "rules": { "permissions": { "names": "advise" }, "lifecycle": { "commands": "none" } } } diff --git a/fixtures/rules-check-conformance/permission-names-require/expected.json b/fixtures/rules-check-conformance/permission-names-require/expected.json new file mode 100644 index 0000000000..10e21d836f --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-require/expected.json @@ -0,0 +1,27 @@ +{ + "diagnostics": [ + { + "severity": "error", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::PurchaseRequest.status.submit", + "message": "the command derived from transition \"submit\" of \"PurchaseRequest\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.PurchaseRequest.submit\", which changes if the transition is renamed. Declare @permission, or @public: true." + }, + { + "severity": "error", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::Purchasing.decide", + "message": "operation.command \"decide\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.decide\", which changes if the operation is renamed. Declare @permission, or @public: true." + }, + { + "severity": "error", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::purchasing::Purchasing.requestSummary", + "message": "operation.query \"requestSummary\" has no @permission, so it asks the policy about the derived name \"acme::purchasing.requestSummary\", which changes if the operation is renamed. Declare @permission, or @public: true." + } + ], + "summary": { + "operations": 4, + "lifecycles": 1, + "transitions": 5 + } +} diff --git a/fixtures/rules-check-conformance/permission-names-require/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/permission-names-require/input/meta.purchasing.yaml new file mode 100644 index 0000000000..dc1fdce62d --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-require/input/meta.purchasing.yaml @@ -0,0 +1,43 @@ +metadata: + 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.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 } + - transition.action: { name: reject, from: [submitted], to: rejected, permission: purchasing.review } + - transition.action: { name: approveFirst, from: [submitted], to: submitted } + - transition.action: { name: withdraw, from: [submitted], to: draft, public: true } + - 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 } + - identity.primary: { name: pk, extends: PurchaseRequest.pk } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: DecisionInput + transitions: [approve, approveFirst] + - operation.command: + name: escalate + inputRef: DecisionInput + permission: purchasing.escalate + - operation.query: { name: openRequests, outputRef: RequestSummary, many: true, public: true } + - operation.query: { name: requestSummary, outputRef: RequestSummary } diff --git a/fixtures/rules-check-conformance/permission-names-require/options.json b/fixtures/rules-check-conformance/permission-names-require/options.json new file mode 100644 index 0000000000..0e8ef94e10 --- /dev/null +++ b/fixtures/rules-check-conformance/permission-names-require/options.json @@ -0,0 +1 @@ +{ "rules": { "permissions": { "names": "require" } } } diff --git a/fixtures/rules-check-conformance/permission-shadowed-claimed/expected.json b/fixtures/rules-check-conformance/permission-shadowed-claimed/expected.json new file mode 100644 index 0000000000..0314d180dc --- /dev/null +++ b/fixtures/rules-check-conformance/permission-shadowed-claimed/expected.json @@ -0,0 +1,21 @@ +{ + "diagnostics": [ + { + "severity": "warn", + "code": "WARN_TRANSITION_PERMISSION_SHADOWED", + "path": "acme::purchasing::PurchaseRequest.status.approve", + "message": "transition \"approve\" declares @public: true, but it derives no command of its own: it is made only by \"Purchasing.decide\", which asks the policy about its own permission, so the attribute is never read. Remove it from the transition, or declare it on the command that makes the transition." + }, + { + "severity": "warn", + "code": "WARN_TRANSITION_PERMISSION_SHADOWED", + "path": "acme::purchasing::PurchaseRequest.status.reject", + "message": "transition \"reject\" declares @permission \"purchasing.review\", but it derives no command of its own: it is made only by \"Purchasing.decide\", \"Purchasing.overrule\", which ask the policy about their own permission, so the attribute is never read. Remove it from the transition, or declare it on the command that makes the transition." + } + ], + "summary": { + "operations": 2, + "lifecycles": 1, + "transitions": 3 + } +} diff --git a/fixtures/rules-check-conformance/permission-shadowed-claimed/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/permission-shadowed-claimed/input/meta.purchasing.yaml new file mode 100644 index 0000000000..0701b537d6 --- /dev/null +++ b/fixtures/rules-check-conformance/permission-shadowed-claimed/input/meta.purchasing.yaml @@ -0,0 +1,35 @@ +metadata: + 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.enum: + name: status + values: [draft, submitted, approved, rejected] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted, permission: purchasing.submit } + - transition.action: { name: approve, from: [submitted], to: approved, public: true } + - 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 } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: DecisionInput + transitions: [approve, reject] + permission: purchasing.decide + - operation.command: + name: overrule + inputRef: DecisionInput + transitions: [reject] + permission: purchasing.overrule diff --git a/fixtures/rules-check-conformance/sourceless-lifecycle-inert/expected.json b/fixtures/rules-check-conformance/sourceless-lifecycle-inert/expected.json new file mode 100644 index 0000000000..7fd135b6ec --- /dev/null +++ b/fixtures/rules-check-conformance/sourceless-lifecycle-inert/expected.json @@ -0,0 +1,21 @@ +{ + "diagnostics": [ + { + "severity": "warn", + "code": "WARN_LIFECYCLE_UNREACHABLE_STATE", + "path": "acme::catalog::ProductTemplate.status", + "message": "state \"archived\" of \"status\" cannot be reached from the initial state \"draft\" by any transition. Add the transition that leads there, or set verify.lifecycle.unreachable if only seeded data uses it." + }, + { + "severity": "error", + "code": "WARN_PERMISSION_DERIVED_NAME", + "path": "acme::catalog::Product.status.publish", + "message": "the command derived from transition \"publish\" of \"Product\" has no @permission, so it asks the policy about the derived name \"acme::catalog.Product.publish\", which changes if the transition is renamed. Declare @permission, or @public: true." + } + ], + "summary": { + "operations": 1, + "lifecycles": 2, + "transitions": 3 + } +} diff --git a/fixtures/rules-check-conformance/sourceless-lifecycle-inert/input/meta.catalog.yaml b/fixtures/rules-check-conformance/sourceless-lifecycle-inert/input/meta.catalog.yaml new file mode 100644 index 0000000000..e7a0c7539f --- /dev/null +++ b/fixtures/rules-check-conformance/sourceless-lifecycle-inert/input/meta.catalog.yaml @@ -0,0 +1,42 @@ +metadata: + package: acme::catalog + children: + # Sourced: its unclaimed transition derives a command, reported under require. + - object.entity: + name: Product + children: + - source.rdb: { table: products } + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - field.enum: + name: status + values: [draft, live] + default: draft + children: + - transition.action: { name: publish, from: [draft], to: live } + # No source: the lifecycle is inert. Its shape is still checked (the unreachable state), + # but it derives no command, so neither the permission check nor the shadowed check names it. + - object.entity: + name: ProductTemplate + children: + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - field.enum: + name: status + values: [draft, live, retired, archived] + default: draft + children: + - transition.action: { name: publish, from: [draft], to: live } + - transition.action: { name: retire, from: [live], to: retired, permission: catalog.retire } + - object.value: + name: TemplateRef + children: + - field.long: { name: templateId, extends: ProductTemplate.id } + - api.operational: + name: Catalog + children: + - operation.command: + name: retireTemplate + inputRef: TemplateRef + transitions: [retire] + permission: catalog.templates.retire diff --git a/fixtures/rules-check-conformance/sourceless-lifecycle-inert/options.json b/fixtures/rules-check-conformance/sourceless-lifecycle-inert/options.json new file mode 100644 index 0000000000..0e8ef94e10 --- /dev/null +++ b/fixtures/rules-check-conformance/sourceless-lifecycle-inert/options.json @@ -0,0 +1 @@ +{ "rules": { "permissions": { "names": "require" } } } diff --git a/fixtures/rules-check-conformance/unreachable-state-error/expected.json b/fixtures/rules-check-conformance/unreachable-state-error/expected.json new file mode 100644 index 0000000000..fe289fccb5 --- /dev/null +++ b/fixtures/rules-check-conformance/unreachable-state-error/expected.json @@ -0,0 +1,21 @@ +{ + "diagnostics": [ + { + "severity": "error", + "code": "WARN_LIFECYCLE_UNREACHABLE_STATE", + "path": "acme::purchasing::PurchaseRequest.status", + "message": "states \"archived\", \"legacy\" of \"status\" cannot be reached from the initial state \"draft\" by any transition. Add the transition that leads there, or set verify.lifecycle.unreachable if only seeded data uses them." + }, + { + "severity": "error", + "code": "WARN_TRANSITION_UNREACHABLE", + "path": "acme::purchasing::PurchaseRequest.status.restore", + "message": "transition \"restore\" starts only from \"archived\", \"legacy\", which no transition reaches from the initial state \"draft\", so it can never be made." + } + ], + "summary": { + "operations": 0, + "lifecycles": 1, + "transitions": 4 + } +} diff --git a/fixtures/rules-check-conformance/unreachable-state-error/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/unreachable-state-error/input/meta.purchasing.yaml new file mode 100644 index 0000000000..0348741e0f --- /dev/null +++ b/fixtures/rules-check-conformance/unreachable-state-error/input/meta.purchasing.yaml @@ -0,0 +1,18 @@ +metadata: + 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.enum: + name: status + values: [draft, submitted, approved, archived, legacy] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - transition.action: { name: approve, from: [submitted], to: approved } + - transition.action: { name: restore, from: [archived, legacy], to: draft } + - transition.action: { name: reopen, from: [approved, archived], to: submitted } diff --git a/fixtures/rules-check-conformance/unreachable-state-error/options.json b/fixtures/rules-check-conformance/unreachable-state-error/options.json new file mode 100644 index 0000000000..9687ee338f --- /dev/null +++ b/fixtures/rules-check-conformance/unreachable-state-error/options.json @@ -0,0 +1 @@ +{ "verify": { "lifecycle": { "unreachable": "error" } } } diff --git a/fixtures/rules-check-conformance/unreachable-state-off/expected.json b/fixtures/rules-check-conformance/unreachable-state-off/expected.json new file mode 100644 index 0000000000..2dc389adfc --- /dev/null +++ b/fixtures/rules-check-conformance/unreachable-state-off/expected.json @@ -0,0 +1,8 @@ +{ + "diagnostics": [], + "summary": { + "operations": 0, + "lifecycles": 1, + "transitions": 4 + } +} diff --git a/fixtures/rules-check-conformance/unreachable-state-off/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/unreachable-state-off/input/meta.purchasing.yaml new file mode 100644 index 0000000000..0348741e0f --- /dev/null +++ b/fixtures/rules-check-conformance/unreachable-state-off/input/meta.purchasing.yaml @@ -0,0 +1,18 @@ +metadata: + 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.enum: + name: status + values: [draft, submitted, approved, archived, legacy] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - transition.action: { name: approve, from: [submitted], to: approved } + - transition.action: { name: restore, from: [archived, legacy], to: draft } + - transition.action: { name: reopen, from: [approved, archived], to: submitted } diff --git a/fixtures/rules-check-conformance/unreachable-state-off/options.json b/fixtures/rules-check-conformance/unreachable-state-off/options.json new file mode 100644 index 0000000000..a03049bf31 --- /dev/null +++ b/fixtures/rules-check-conformance/unreachable-state-off/options.json @@ -0,0 +1 @@ +{ "verify": { "lifecycle": { "unreachable": "off" } } } diff --git a/fixtures/rules-check-conformance/unreachable-state/expected.json b/fixtures/rules-check-conformance/unreachable-state/expected.json new file mode 100644 index 0000000000..7480942b31 --- /dev/null +++ b/fixtures/rules-check-conformance/unreachable-state/expected.json @@ -0,0 +1,21 @@ +{ + "diagnostics": [ + { + "severity": "warn", + "code": "WARN_LIFECYCLE_UNREACHABLE_STATE", + "path": "acme::purchasing::PurchaseRequest.status", + "message": "states \"archived\", \"legacy\" of \"status\" cannot be reached from the initial state \"draft\" by any transition. Add the transition that leads there, or set verify.lifecycle.unreachable if only seeded data uses them." + }, + { + "severity": "warn", + "code": "WARN_TRANSITION_UNREACHABLE", + "path": "acme::purchasing::PurchaseRequest.status.restore", + "message": "transition \"restore\" starts only from \"archived\", \"legacy\", which no transition reaches from the initial state \"draft\", so it can never be made." + } + ], + "summary": { + "operations": 0, + "lifecycles": 1, + "transitions": 4 + } +} diff --git a/fixtures/rules-check-conformance/unreachable-state/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/unreachable-state/input/meta.purchasing.yaml new file mode 100644 index 0000000000..0348741e0f --- /dev/null +++ b/fixtures/rules-check-conformance/unreachable-state/input/meta.purchasing.yaml @@ -0,0 +1,18 @@ +metadata: + 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.enum: + name: status + values: [draft, submitted, approved, archived, legacy] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - transition.action: { name: approve, from: [submitted], to: approved } + - transition.action: { name: restore, from: [archived, legacy], to: draft } + - transition.action: { name: reopen, from: [approved, archived], to: submitted } diff --git a/metaobjects/meta.requirements.yaml b/metaobjects/meta.requirements.yaml index ce93f87205..927e8a6e7a 100644 --- a/metaobjects/meta.requirements.yaml +++ b/metaobjects/meta.requirements.yaml @@ -1269,6 +1269,90 @@ metadata.root: measures, three of which are updated when the definition changes. + - requirement.functional: + name: businessRules + title: Business rules + level: 3 + status: live + statement: >- + What an application does to its entities is declared beside + them: named commands and queries, the permission each one asks + about, and the moves a status field allows, so each can be + checked instead of living only in hand-written code. + counterexample: >- + An approval rule that exists only inside one endpoint, so a + background job that writes the same row skips it. + description: >- + Covers the operation and lifecycle vocabulary and the checks the + loader and verify run on it (ADR-0066). The generated service + shells that enforce these rules at run time are later work + (ADR-0067); until they land the vocabulary generates nothing. + children: + - requirement.functional: + name: apiOperational + title: Operational API + level: 4 + status: live + statement: >- + An operational API is a named surface at the top of a + document whose children are the package's declared + operations. + counterexample: >- + A command declared inside an entity, where a versioned + second surface has nowhere to put it. + - requirement.functional: + name: operationCommand + title: Command + level: 4 + status: live + statement: >- + A command takes a declared value as input, names the + transitions of its target it may make and the business + errors it may return, and its target entity is derived + from its input or output whenever it can be. + counterexample: >- + A command whose declared target disagrees with the key + its input carries, so the permission check guards one + entity and the write touches another. + - requirement.functional: + name: operationQuery + title: Query + level: 4 + status: live + statement: >- + A query declares what it returns, an entity, a projection + or a value, and whether it returns a list. + counterexample: >- + A query that returns a list on one port and a single row + on another because nothing said which. + - requirement.functional: + name: bindingRest + title: REST binding + level: 4 + status: live + statement: >- + A REST binding overrides an operation's derived method or + path, and a path addressing one row names exactly its + target's key fields. + counterexample: >- + A path whose placeholder names a field the target does not + key on, so the route resolves the wrong row. + - requirement.functional: + name: transitionAction + title: Transition + level: 4 + status: live + statement: >- + A transition names the states it leaves and the state it + reaches, all members of its enum, on a field of an entity; + an entity with a source needs a writable one, and the + lifecycle of an entity with no source is inert. The field's + default is the initial state, and verify reports a state + nothing reaches. + counterexample: >- + A status value that a typo in a transition made + unreachable, found only when a row needs it. + - requirement.functional: name: constraints title: Constraints diff --git a/scripts/check-requirements-ledger.ts b/scripts/check-requirements-ledger.ts index 3e2c7d1e03..e7f6873403 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 = 151; +const DEFAULT_EXPECTED_WARNING_COUNT = 157; function expectedWarnings(argv: readonly string[]): number { const flag = argv.find((a) => a.startsWith("--expect-warnings=")); diff --git a/scripts/generate-embedded-metamodel.ts b/scripts/generate-embedded-metamodel.ts index 2a439c316d..804058ffbf 100644 --- a/scripts/generate-embedded-metamodel.ts +++ b/scripts/generate-embedded-metamodel.ts @@ -86,6 +86,9 @@ const CONCEPT_DIRS: Record = { requirement: "core/requirement", // FR-044: dimension / measure / segment (the object.report vocabulary) reporting: "core/reporting", + // ADR-0066: the declared API surface (api / operation / binding) and lifecycle moves + api: "core/api", + transition: "core/transition", // depth-1 template: "template", // FR-033 S1.5: the prompt concern provider lives in template/ (templateProvider diff --git a/scripts/site/reference.test.ts b/scripts/site/reference.test.ts index c9c0ef2dd8..4b7f06fa59 100644 --- a/scripts/site/reference.test.ts +++ b/scripts/site/reference.test.ts @@ -50,7 +50,7 @@ describe("renderReference", () => { test("renders every metamodel markdown page", () => { expect(existsSync(MD_DIR)).toBe(true); const p = pages(); - expect(Object.keys(p).length).toBe(19); + expect(Object.keys(p).length).toBe(23); expect(Object.keys(p)).toContain("index.html"); expect(Object.keys(p)).toContain("types/field.html"); }); @@ -153,7 +153,7 @@ describe("build-site-reference --check", () => { test("a freshly rendered tree checks clean", () => { const r = run("--check", "--out", rendered()); - expect(r.out).toContain("is fresh (19 page(s))"); + expect(r.out).toContain("is fresh (23 page(s))"); expect(r.code).toBe(0); }); diff --git a/scripts/write-requirement-corpus-expected.ts b/scripts/write-requirement-corpus-expected.ts index f4414640c1..0aa3893919 100644 --- a/scripts/write-requirement-corpus-expected.ts +++ b/scripts/write-requirement-corpus-expected.ts @@ -5,6 +5,7 @@ * * bun scripts/write-requirement-corpus-expected.ts check * bun scripts/write-requirement-corpus-expected.ts identity + * bun scripts/write-requirement-corpus-expected.ts rules * * ── What this is, and what it is not ─────────────────────────────────────────── * @@ -47,6 +48,9 @@ import { type Diagnostic, type RequirementSummary, } from "../server/typescript/packages/cli/src/lib/requirement-check.js"; +import { checkRules, type RulesSummary } from "../server/typescript/packages/cli/src/lib/rules-check.js"; +import { ConfigSchema } from "../server/typescript/packages/sdk/src/config.js"; +import { rulesSettingsOf } from "../server/typescript/packages/metadata/src/rules-settings.js"; import { requirementTestIdentities, witnessKeyCollisions, @@ -190,6 +194,26 @@ function identityExpected(root: MetaData, options: Readonly>): unknown { + const blocks = ConfigSchema.pick({ rules: true, verify: true }).parse(options); + const { diagnostics, summary } = checkRules(root, rulesSettingsOf(blocks)); + const summaryRecord = (s: RulesSummary): Record => ({ + operations: s.operations, + lifecycles: s.lifecycles, + transitions: s.transitions, + }); + return { + diagnostics: diagnostics.map(diagnosticRecord), + summary: summary === undefined ? null : summaryRecord(summary), + }; +} + const CORPORA: Readonly> = { check: { dir: "fixtures/requirement-check-conformance", @@ -201,6 +225,11 @@ const CORPORA: Readonly> = { optionKeys: ["grain", "filter"], expected: identityExpected, }, + rules: { + dir: "fixtures/rules-check-conformance", + optionKeys: ["rules", "verify"], + expected: rulesExpected, + }, }; // --------------------------------------------------------------------------- diff --git a/server/csharp/MetaObjects.Cli.Tests/VerifyRulesTests.cs b/server/csharp/MetaObjects.Cli.Tests/VerifyRulesTests.cs new file mode 100644 index 0000000000..ab63aaa5d5 --- /dev/null +++ b/server/csharp/MetaObjects.Cli.Tests/VerifyRulesTests.cs @@ -0,0 +1,99 @@ +using Xunit; + +namespace MetaObjects.Cli.Tests; + +/// +/// dotnet meta verify — the business-rules gate, end to end (ADR-0066). Drives the BUILT CLI, so +/// this proves the wiring: what is printed, where, and what reaches the exit code. The codes, severities +/// and message text are gated cross-port by RulesCheckConformanceTests. +/// +[Collection(OwnedRunnerCollection.Name)] +public sealed class VerifyRulesTests : IDisposable +{ + private readonly string _tmp = Directory.CreateTempSubdirectory("mo-verify-rules-").FullName; + + public void Dispose() + { + try { Directory.Delete(_tmp, recursive: true); } catch { /* best effort */ } + } + + private const string Plain = """ + metadata: + package: acme::shop + children: + - object.entity: + name: Order + children: + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + """; + + private const string WithOperations = """ + metadata: + package: acme::reports + children: + - object.entity: + name: Order + children: + - source.rdb: { table: orders } + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - field.long: { name: totalCents } + - object.value: + name: Totals + children: + - field.long: { name: totalCents } + - api.operational: + name: Dashboard + children: + - operation.query: { name: totals, outputRef: Totals } + - operation.query: { name: recentOrders, outputRef: Order, many: true, permission: reports.read } + """; + + private string[] Project(string yaml, string? configRules = null) + { + var model = Path.Combine(_tmp, "model"); + Directory.CreateDirectory(model); + File.WriteAllText(Path.Combine(model, "meta.shop.yaml"), yaml); + if (configRules is not null) + { + Directory.CreateDirectory(Path.Combine(_tmp, ".metaobjects")); + File.WriteAllText(Path.Combine(_tmp, ".metaobjects", "config.json"), + $$"""{ "schema_version": 1, {{configRules}} }"""); + } + var templates = Path.Combine(_tmp, "templates"); + Directory.CreateDirectory(templates); + return ["verify", model, "--templates", "--prompts", templates]; + } + + [Fact] + public void A_model_with_no_operation_and_no_transition_prints_nothing() + { + var (exitCode, stdout, stderr) = CliProcess.Run(_tmp, Project(Plain)); + + Assert.Equal(0, exitCode); + Assert.Equal("dotnet meta verify --templates: OK" + Environment.NewLine, stdout); + Assert.Equal("", stderr); + } + + [Fact] + public void Operations_print_the_summary_line() + { + var (exitCode, _, stderr) = CliProcess.Run(_tmp, Project(WithOperations)); + + Assert.Equal(0, exitCode); // the default policy derives a name and reports no error + var lines = stderr.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + Assert.Contains("dotnet meta verify — rules: 2 operation(s), 0 lifecycle(s) with 0 transition(s).", lines); + } + + [Fact] + public void An_error_severity_diagnostic_fails_the_run() + { + var (exitCode, _, stderr) = CliProcess.Run(_tmp, + Project(WithOperations, "\"rules\": { \"permissions\": { \"names\": \"require\" } }")); + + Assert.Equal(1, exitCode); + Assert.Contains("WARN_PERMISSION_DERIVED_NAME", stderr); + Assert.Contains("rules: 1 error(s).", stderr); + } +} diff --git a/server/csharp/MetaObjects.Cli/Program.cs b/server/csharp/MetaObjects.Cli/Program.cs index 33b19392ce..1a69176988 100644 --- a/server/csharp/MetaObjects.Cli/Program.cs +++ b/server/csharp/MetaObjects.Cli/Program.cs @@ -573,6 +573,8 @@ static int RunVerify(string[] rest) Naming = resolvedMeta.Naming, // ADR-0019 Amendment 2 — the wire setting, from the same file, for the --codegen regen. Wire = resolvedMeta.Wire ?? MetaObjects.Meta.WireFormat.Default, + // ADR-0066 — the business-rules settings, for the rules gate. + Rules = resolvedMeta.Rules ?? MetaObjects.Config.RulesSettings.Default, Api = resolvedMeta.Api ?? MetaObjects.Meta.ApiSettings.Default, TemplatesRoot = templatesRoot, OutDir = outDir, @@ -660,6 +662,11 @@ static int RunVerify(string[] rest) // load refuse the metadata, each says so. var requirementExit = VerifyCommand.RunRequirementGate(opts, requireImplementers, Console.Error, result.LoadFailureReported); + // The business-rules gate (ADR-0066): operations and lifecycles are metadata too, so it runs on + // EVERY verify and is opt-in by declaration. A model with no operation and no transition sees no + // line and no exit-code change. Its errors fold into the exit code like any other gate's. + var rulesExit = VerifyCommand.RunRulesGate(opts, Console.Error); + // The field AUTHORING lint — a reference identity over a field the object lacks, a // field name declared twice in one children list. Both load clean on every port. Runs // on every `verify`, whichever gates were selected; warnings ONLY, never the exit code. @@ -670,7 +677,7 @@ static int RunVerify(string[] rest) // fold its exit code into the aggregate the same way every other subverb does — max, // non-zero on any drift. var gatesExit = codegenHandedOff ? Math.Max(result.ExitCode, codegenHandoffExit) : result.ExitCode; - return Math.Max(Math.Max(gatesExit, requirementExit), depsExit); + return Math.Max(Math.Max(Math.Max(gatesExit, requirementExit), rulesExit), depsExit); } // `dotnet meta verify --deps` (FR-023): re-resolve each declared dependency's `path` and compare its diff --git a/server/csharp/MetaObjects.Cli/VerifyCommand.cs b/server/csharp/MetaObjects.Cli/VerifyCommand.cs index d089cb4e8e..3b6e911fbe 100644 --- a/server/csharp/MetaObjects.Cli/VerifyCommand.cs +++ b/server/csharp/MetaObjects.Cli/VerifyCommand.cs @@ -18,6 +18,7 @@ using System.Text.Json; using MetaObjects.Codegen; using MetaObjects.Core.Requirement; +using MetaObjects.Core.Transition; using MetaObjects.Loader; using MetaObjects.Render; using static MetaObjects.Core.Requirement.RequirementConstants; @@ -129,6 +130,8 @@ public sealed record Options /// and set on the loaded root beside it. Defaults to native. /// public MetaObjects.Meta.WireFormat Wire { get; init; } = MetaObjects.Meta.WireFormat.Default; + /// ADR-0066 — the business-rules settings, from the same file; defaults when none is read. + public MetaObjects.Config.RulesSettings Rules { get; init; } = MetaObjects.Config.RulesSettings.Default; /// The project's api block, set on the loaded root beside . public MetaObjects.Meta.ApiSettings Api { get; init; } = MetaObjects.Meta.ApiSettings.Default; /// Templates root for the --templates gate (--templates <root>). @@ -355,6 +358,43 @@ public static int RunRequirementGate(Options opts, bool requireImplementers, Tex return 1; } + // ------------------------------------------------------------------------ + // The business-rules gate (ADR-0066) — runs on EVERY verify, with no subverb. + // ------------------------------------------------------------------------ + + /// The command prefix the rules gate's summary and error-count lines carry. + private const string RulesPrefix = "dotnet meta verify — rules: "; + + /// + /// The business-rules gate: reads the declared operations and lifecycles of the loaded model and + /// reports what loads clean but is almost certainly not what the author meant. A model declaring no + /// operation and no transition is silent: no line is printed and the exit code is unchanged. + /// Returns 1 when any finding is an error, or when the metadata does not load (that failure is + /// reported by the requirement gate, which loads first, so it is not printed twice). + /// + public static int RunRulesGate(Options opts, TextWriter output) + { + var load = LoadMetadata(opts); + if (load.Errors.Count > 0) return 0; // reported once, by the requirement gate (which returns 1) + var result = RulesCheck.Check(load.Root, opts.Rules); + if (result.Summary is not { } summary) return 0; + + output.WriteLine(RulesPrefix + string.Create(CultureInfo.InvariantCulture, + $"{summary.Operations} operation(s), {summary.Lifecycles} lifecycle(s) with {summary.Transitions} transition(s).")); + var errors = result.Diagnostics.Where(d => d.Severity == RulesCheck.SeverityError).ToList(); + var warns = result.Diagnostics.Where(d => d.Severity != RulesCheck.SeverityError).ToList(); + foreach (var d in errors) output.WriteLine(FormatRulesDiagnostic(d)); + foreach (var d in warns) output.WriteLine(FormatRulesDiagnostic(d)); + if (errors.Count == 0) return 0; + + output.WriteLine(RulesPrefix + string.Create(CultureInfo.InvariantCulture, $"{errors.Count} error(s).")); + return 1; + } + + /// A diagnostic line, with no command prefix: <code> [<path>]: <message>. + private static string FormatRulesDiagnostic(RequirementDiagnostic d) => + $" {d.Code}{(d.Path is null ? "" : $" [{d.Path}]")}: {d.Message}"; + /// The summary line, minus its command prefix. Statuses in the closed enum's order, zero counts omitted. private static string SummaryText(RequirementSummary summary, int files) { diff --git a/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs b/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs new file mode 100644 index 0000000000..3a9b696868 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs @@ -0,0 +1,144 @@ +// ADR-0066 — the business-rules vocabulary is inert in every generator. +// +// `api.operational`, `operation.*`, `binding.*` and `transition.*` are registered, loaded, +// validated and checked by `verify`; no generator acts on them yet. So two models that differ +// ONLY by that vocabulary (fixtures/codegen-noop/rules/{with,without}, shared with the other +// ports' copies of this test) must produce the same output in every registered generator +// (code and documentation alike), byte for byte, alone and in one run. +// +// Runs through CodegenRunner.Run, the path `dotnet meta gen` takes, as ReportingInertTests does. + +using MetaObjects.Codegen; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; +using static MetaObjects.Shared.BaseTypes; + +namespace MetaObjects.Codegen.Tests; + +public class RulesInertTests +{ + private static string Model(string variant) => + Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "codegen-noop", "rules", variant, "meta.purchasing.json"); + + private static MetaRoot Load(string variant) + { + var result = new MetaDataLoader().Load([new FileSource(Model(variant))]); + Assert.True(result.Errors.Count == 0, + $"{Model(variant)} did not load:\n" + string.Join("\n", result.Errors.Select(e => $" {e.Code}: {e.Message}"))); + return result.Root; + } + + /// + /// Run a generator suite into a fresh directory and read back every file it wrote: + /// relative path to contents. A throw is recorded as the single entry "<threw>", so a + /// generator that cannot run from a bare model must at least fail identically. + /// + private static SortedDictionary Emit(MetaRoot root, IReadOnlyList generators) + { + var outDir = Path.Combine(Path.GetTempPath(), "rules-inert-" + Guid.NewGuid().ToString("N")); + var files = new SortedDictionary(StringComparer.Ordinal); + try + { + var config = new GenConfig + { + OutDir = outDir, + Namespace = "MetaObjects.RulesInert.Generated", + ColumnNamingStrategy = ColumnNamingStrategy.SnakeCase, + IncludeNames = true, + }; + CodegenRunner.Run(config, root, generators); + if (Directory.Exists(outDir)) + foreach (var path in Directory.EnumerateFiles(outDir, "*", SearchOption.AllDirectories)) + files[Path.GetRelativePath(outDir, path)] = File.ReadAllText(path); + } + catch (Exception e) + { + files.Clear(); + files[""] = e.Message; + } + finally + { + if (Directory.Exists(outDir)) Directory.Delete(outDir, recursive: true); + } + return files; + } + + private static IGenerator Build(GeneratorRegistryEntry entry) => + entry.Factory(new GeneratorBuildContext(CorpusPaths.FitnessTemplateRoot)); + + public static TheoryData GeneratorNames() + { + var data = new TheoryData(); + foreach (var name in GeneratorRegistry.Entries.Keys.Where(n => n != SharedModelTestSupport.Name)) data.Add(name); + return data; + } + + private static void AssertSame(SortedDictionary expected, SortedDictionary actual, string what) + { + Assert.Equal(expected.Keys.ToList(), actual.Keys.ToList()); + foreach (var (path, content) in expected) + Assert.True(content == actual[path], $"{what}: {path} differs once the rules vocabulary is declared"); + } + + [Fact] + public void The_with_model_really_carries_the_vocabulary() + { + // Else every comparison below is vacuously green. + static int Count(MetaData node, string type) => + node.Children().Sum(c => (c.Type == type ? 1 : 0) + Count(c, type)); + var with = Load("with").Root(); + var without = Load("without").Root(); + Assert.Equal(3, Count(with, TYPE_TRANSITION)); + Assert.Equal(1, Count(with, TYPE_API)); + Assert.Equal(3, Count(with, TYPE_OPERATION)); + Assert.Equal(1, Count(with, TYPE_BINDING)); + foreach (var type in new[] { TYPE_TRANSITION, TYPE_API, TYPE_OPERATION, TYPE_BINDING }) + Assert.Equal(0, Count(without, type)); + } + + [Theory] + [MemberData(nameof(GeneratorNames))] + public void Generator_emits_the_same_files_with_and_without_the_rules_vocabulary(string name) + { + var entry = GeneratorRegistry.Entries[name]; + AssertSame(Emit(Load("without"), [Build(entry)]), Emit(Load("with"), [Build(entry)]), name); + } + + [Fact] + public void Exactly_these_generators_cannot_run_from_a_bare_model() + { + // Each is compared above on its error message alone, which proves nothing about its + // output. Pinned by name so a generator that starts throwing cannot drop out silently. + var threw = GeneratorRegistry.Entries + .Where(e => Emit(Load("without"), [Build(e.Value)]).ContainsKey("")) + .Select(e => e.Key) + .OrderBy(n => n, StringComparer.Ordinal) + .ToList(); + Assert.Equal(new List { SharedModelTestSupport.Name }, threw); + } + + [Fact] + public void Every_runnable_generator_in_one_run_emits_the_same_files() + { + var runnable = GeneratorRegistry.Entries + .Where(e => !Emit(Load("without"), [Build(e.Value)]).ContainsKey("")) + .ToList(); + var expected = Emit(Load("without"), runnable.Select(e => Build(e.Value)).ToList()); + var actual = Emit(Load("with"), runnable.Select(e => Build(e.Value)).ToList()); + Assert.False(expected.ContainsKey(""), expected.GetValueOrDefault("")); + Assert.False(actual.ContainsKey(""), actual.GetValueOrDefault("")); + Assert.True(expected.Count > 10, $"only {expected.Count} files — the suite barely ran"); + AssertSame(expected, actual, "one run"); + } + + [Fact] + public void The_documentation_generators_are_among_those_compared() + { + // The api reference is a registered entry, so the comparisons above cover it; pin that so a + // renamed entry cannot take the docs out of the comparison. + Assert.Contains("api-docs", GeneratorRegistry.Entries.Keys); + var files = Emit(Load("with"), [Build(GeneratorRegistry.Entries["api-docs"])]); + Assert.Contains(files.Keys, k => k.StartsWith("api/", StringComparison.Ordinal)); + } +} diff --git a/server/csharp/MetaObjects.Conformance.Tests/BusinessErrorCodePatternTests.cs b/server/csharp/MetaObjects.Conformance.Tests/BusinessErrorCodePatternTests.cs new file mode 100644 index 0000000000..c3d3ca6338 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/BusinessErrorCodePatternTests.cs @@ -0,0 +1,21 @@ +using MetaObjects.Core.Api; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +/// The @errors code pattern anchors with \z: $ in .NET accepts a trailing newline. +public class BusinessErrorCodePatternTests +{ + [Theory] + [InlineData("over_budget")] + [InlineData("a1_b2")] + public void Accepts(string code) => Assert.Matches(ApiConstants.BUSINESS_ERROR_CODE_PATTERN, code); + + [Theory] + [InlineData("over_budget\n")] + [InlineData("over_budget\r\n")] + [InlineData("Over_budget")] + [InlineData("over__budget")] + [InlineData("")] + public void Refuses(string code) => Assert.DoesNotMatch(ApiConstants.BUSINESS_ERROR_CODE_PATTERN, code); +} diff --git a/server/csharp/MetaObjects.Conformance.Tests/NeutralConfigRulesTests.cs b/server/csharp/MetaObjects.Conformance.Tests/NeutralConfigRulesTests.cs new file mode 100644 index 0000000000..16ad99fb54 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/NeutralConfigRulesTests.cs @@ -0,0 +1,77 @@ +using System.IO; +using MetaObjects.Config; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +/// +/// ADR-0066 — the rules and verify blocks of config.json. An absent key takes +/// its default, which behaves as before the blocks existed; a mistake is refused rather than +/// silently defaulted, because a defaulted typo would change what verify reports. +/// +public sealed class NeutralConfigRulesTests +{ + private static RulesSettings Read(string extraJson) + { + var dir = Path.Combine(Path.GetTempPath(), "neutral-config-rules-" + System.Guid.NewGuid().ToString("N")); + var cfgDir = Path.Combine(dir, ".metaobjects"); + Directory.CreateDirectory(cfgDir); + var comma = extraJson.Length == 0 ? "" : ", "; + File.WriteAllText(Path.Combine(cfgDir, "config.json"), "{ \"schema_version\": 1" + comma + extraJson + " }"); + try + { + return NeutralConfig.Read(dir)!.Rules; + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public void AbsentKeys_TakeTheDefaults() + { + Assert.Equal(new RulesSettings("derive", "initial", "unclaimed", "warn"), Read("")); + } + + [Fact] + public void EveryKey_IsRead() + { + var settings = Read(""" + "rules": { "permissions": { "names": "require" }, "lifecycle": { "create": "any", "commands": "none" } }, + "verify": { "handEdits": "fail", "lifecycle": { "unreachable": "error" } } + """); + Assert.Equal(new RulesSettings("require", "any", "none", "error"), settings); + } + + [Theory] + [InlineData(""" + "rules": { "permission": { "names": "advise" } } + """)] + [InlineData(""" + "rules": { "lifecycle": { "initial": "any" } } + """)] + [InlineData(""" + "rules": { "permissions": { "names": "strict" } } + """)] + [InlineData(""" + "rules": { "lifecycle": { "commands": true } } + """)] + [InlineData(""" + "rules": "advise" + """)] + [InlineData(""" + "verify": { "lifecycle": { "unreachable": "fail" } } + """)] + [InlineData(""" + "verify": { "lifecycles": {} } + """)] + [InlineData(""" + "verify": { "handEdits": "warn" } + """)] + public void AMistake_IsRefusedNotDefaulted(string extraJson) + { + var ex = Assert.Throws(() => Read(extraJson)); + Assert.Equal(ErrorCode.ERR_BAD_ATTR_VALUE, ex.Code); + } +} diff --git a/server/csharp/MetaObjects.Conformance.Tests/RulesCheckConformanceTests.cs b/server/csharp/MetaObjects.Conformance.Tests/RulesCheckConformanceTests.cs new file mode 100644 index 0000000000..436b27b486 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/RulesCheckConformanceTests.cs @@ -0,0 +1,154 @@ +using System.Text.Json; +using System.Text.RegularExpressions; +using MetaObjects.Config; +using MetaObjects.Core.Transition; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +/// +/// Cross-port business-rules gate conformance corpus (ADR-0066): fixtures/rules-check-conformance/. +/// See that directory's README.md for the fixture format. Every case is LOADED strict first, so "this +/// model loads today" is proven by the fixture, and only then checked. options.json holds the +/// rules and verify blocks of .metaobjects/config.json, so it is run through this +/// port's own config reader. Mirrors the TypeScript reference (rules-check-conformance.test.ts); +/// a mismatch here is a bug in THIS port's gate, never in the fixture. +/// +public class RulesCheckConformanceTests +{ + private static readonly string CorpusDir = ResolveCorpusDir(); + + private static string ResolveCorpusDir() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null) + { + var candidate = Path.Combine(dir.FullName, "fixtures", "rules-check-conformance"); + if (Directory.Exists(candidate)) return candidate; + dir = dir.Parent; + } + throw new DirectoryNotFoundException( + "Could not locate fixtures/rules-check-conformance/ by walking up from " + AppContext.BaseDirectory); + } + + private static List Cases() => + Directory.GetDirectories(CorpusDir).Select(d => Path.GetFileName(d)!).OrderBy(n => n, StringComparer.Ordinal).ToList(); + + public static IEnumerable Fixtures() => Cases().Select(n => new object[] { n }); + + /// Read options.json through the port's own config reader, as a project's config.json. + private static RulesSettings ReadSettings(string caseDir) + { + var file = Path.Combine(caseDir, "options.json"); + if (!File.Exists(file)) return RulesSettings.Default; + return ReadConfigBlocks(File.ReadAllText(file)); + } + + private static RulesSettings ReadConfigBlocks(string blocksJson) + { + var dir = Directory.CreateTempSubdirectory("mo-rules-config-").FullName; + try + { + Directory.CreateDirectory(Path.Combine(dir, ".metaobjects")); + // The blocks sit beside a minimal config: a key the reader does not know fails the case. + using var blocks = JsonDocument.Parse(blocksJson); + var merged = new Dictionary { ["schema_version"] = 1 }; + foreach (var p in blocks.RootElement.EnumerateObject()) merged[p.Name] = p.Value.Clone(); + File.WriteAllText(Path.Combine(dir, ".metaobjects", "config.json"), JsonSerializer.Serialize(merged)); + return NeutralConfig.Read(dir)!.Rules; + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + private static string SummaryJson(RulesSummary? summary) => summary is null + ? "null" + : JsonSerializer.Serialize(new SortedDictionary(StringComparer.Ordinal) + { + ["operations"] = summary.Operations, + ["lifecycles"] = summary.Lifecycles, + ["transitions"] = summary.Transitions, + }); + + private static string CanonicalJson(JsonElement element) => element.ValueKind == JsonValueKind.Null + ? "null" + : JsonSerializer.Serialize(new SortedDictionary( + element.EnumerateObject().ToDictionary(p => p.Name, p => p.Value.GetInt32()), StringComparer.Ordinal)); + + private static List DocumentedCases() + { + var readme = File.ReadAllText(Path.Combine(CorpusDir, "README.md")); + var section = Regex.Split(readme, "^## ", RegexOptions.Multiline).FirstOrDefault(s => s.StartsWith("Cases\n", StringComparison.Ordinal)); + Assert.NotNull(section); + return Regex.Matches(section!, @"^\| `([^`]+)` \|", RegexOptions.Multiline).Select(m => m.Groups[1].Value).ToList(); + } + + [Fact] + public void Discovers_the_corpus() => Assert.NotEmpty(Cases()); + + [Fact] + public void Every_case_on_disk_is_documented_in_the_readme_and_nothing_else_is() => + Assert.Equal(Cases(), DocumentedCases().Order(StringComparer.Ordinal).ToList()); + + [Fact] + public void An_absent_block_is_every_default() + { + Assert.Equal(RulesSettings.Default, ReadConfigBlocks("{}")); + Assert.Equal(new RulesSettings("derive", "initial", "unclaimed", "warn"), RulesSettings.Default); + } + + [Theory] + [InlineData("""{ "rules": { "permissions": { "names": "loud" } } }""")] + [InlineData("""{ "rules": { "permissions": { "name": "advise" } } }""")] + [InlineData("""{ "rules": { "lifecycle": { "create": "never" } } }""")] + [InlineData("""{ "rules": { "lifecycle": { "commands": "some" } } }""")] + [InlineData("""{ "rules": { "audit": {} } }""")] + [InlineData("""{ "rules": [] }""")] + [InlineData("""{ "verify": { "lifecycle": { "unreachable": "ignore" } } }""")] + [InlineData("""{ "verify": { "lifecycle": { "reachable": "warn" } } }""")] + [InlineData("""{ "verify": { "other": {} } }""")] + [InlineData("""{ "verify": "warn" }""")] + public void An_unknown_key_or_value_is_refused(string blocks) => + Assert.Throws(() => ReadConfigBlocks(blocks)); + + [Fact] + public void Every_documented_value_is_read() + { + var settings = ReadConfigBlocks(""" + { "rules": { "permissions": { "names": "require" }, "lifecycle": { "create": "any", "commands": "all" } }, + "verify": { "lifecycle": { "unreachable": "off" } } } + """); + Assert.Equal(new RulesSettings("require", "any", "all", "off"), settings); + } + + [Theory] + [MemberData(nameof(Fixtures))] + public void Fixture(string name) + { + var caseDir = Path.Combine(CorpusDir, name); + using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(caseDir, "expected.json"))); + var settings = ReadSettings(caseDir); + + // Strict; the files load in ascending file-name order. + var load = MetaDataLoader.FromDirectory(Path.Combine(caseDir, "input"), strict: true); + Assert.Empty(load.Errors.Select(e => e.Code + ": " + e.Message)); + + var result = RulesCheck.Check(load.Root, settings); + var actual = result.Diagnostics + .Select(d => (d.Severity, d.Code, d.Path ?? "", d.Message)) + .Order().ToList(); + var wanted = doc.RootElement.GetProperty("diagnostics").EnumerateArray() + .Select(d => ( + d.GetProperty("severity").GetString()!, + d.GetProperty("code").GetString()!, + d.TryGetProperty("path", out var p) ? p.GetString()! : "", + d.GetProperty("message").GetString()!)) + .Order().ToList(); + Assert.Equal(wanted, actual); + + Assert.Equal(CanonicalJson(doc.RootElement.GetProperty("summary")), SummaryJson(result.Summary)); + } +} diff --git a/server/csharp/MetaObjects/Config/MetadataLocation.cs b/server/csharp/MetaObjects/Config/MetadataLocation.cs index 21a63df756..c044659352 100644 --- a/server/csharp/MetaObjects/Config/MetadataLocation.cs +++ b/server/csharp/MetaObjects/Config/MetadataLocation.cs @@ -58,6 +58,9 @@ public sealed record ResolvedMetadata( /// constructor and Deconstruct keep the signatures they had. public EnumDefaults? Enums { get; init; } + /// ADR-0066 — the project's business-rules settings (rules and verify in config.json); null when no config was read. + public RulesSettings? Rules { get; init; } + /// The project's api block, set on the loaded root by . public ApiSettings? Api { get; init; } @@ -154,7 +157,7 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd, bool val // No config found means no project to read a lock from: nothing is imported. var explicitImports = explicitCfg is null ? ImportScope.None : ImportScope.Resolve(explicitCfg.ConfigDir, explicitCfg); return new ResolvedMetadata( - metadataDir, null, explicitLibs, explicitNaming, explicitCfg?.Wire, explicitCfg?.OutDir, explicitImports, explicitCfg?.Namespace, LoadProviders(explicitCfg)) { Enums = explicitCfg?.Enums, Api = explicitCfg?.Api }; + metadataDir, null, explicitLibs, explicitNaming, explicitCfg?.Wire, explicitCfg?.OutDir, explicitImports, explicitCfg?.Namespace, LoadProviders(explicitCfg)) { Enums = explicitCfg?.Enums, Rules = explicitCfg?.Rules, Api = explicitCfg?.Api }; } var cfg = NeutralConfig.Read(cwd, validateNaming); @@ -169,7 +172,7 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd, bool val // No declared sources: resolve the DEFAULT directory through the same ladder // the shared conformance corpus gates (ERR_COLLECTION_NOT_FOUND when absent). var defaultFiles = SourceResolver.ResolveCollection(cwd); - return new ResolvedMetadata(Path.Combine(cwd, NeutralConfig.DefaultMetadataDir), defaultFiles, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, LoadProviders(cfg)) { Enums = cfg?.Enums, Api = cfg?.Api }; + return new ResolvedMetadata(Path.Combine(cwd, NeutralConfig.DefaultMetadataDir), defaultFiles, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, LoadProviders(cfg)) { Enums = cfg?.Enums, Rules = cfg?.Rules, Api = cfg?.Api }; } if (specs.Count > 1) @@ -199,6 +202,6 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd, bool val "\"sources\" at the file's containing directory."); } - return new ResolvedMetadata(resolved, files, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, LoadProviders(cfg)) { Enums = cfg?.Enums, Api = cfg?.Api }; + return new ResolvedMetadata(resolved, files, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, LoadProviders(cfg)) { Enums = cfg?.Enums, Rules = cfg?.Rules, Api = cfg?.Api }; } } diff --git a/server/csharp/MetaObjects/Config/NeutralConfig.cs b/server/csharp/MetaObjects/Config/NeutralConfig.cs index 0eb5a3d473..f981c01bde 100644 --- a/server/csharp/MetaObjects/Config/NeutralConfig.cs +++ b/server/csharp/MetaObjects/Config/NeutralConfig.cs @@ -117,6 +117,10 @@ public sealed class NeutralConfig /// absent key at its native default. Never null. public WireFormat Wire { get; } + /// ADR-0066 — the business-rules settings (`rules` and `verify` in config.json), each absent key at + /// its default. Never null. + public RulesSettings Rules { get; private init; } = RulesSettings.Default; + /// The project's `api` block (`api.pagination`, `api.unknownFields`). Never null: absent is the default. public ApiSettings Api { get; private init; } = ApiSettings.Default; @@ -385,6 +389,7 @@ private static bool ReadMigrateForeignKeyIndexes(JsonElement root) => Path.GetFullPath(configDir)) { Enums = ReadEnums(root, path), + Rules = ReadRules(root, path), Api = ReadApi(root, path), RequirementsInherit = ReadRequirementsInherit(root, path), OutputLayout = ReadOutputLayout(root, path), @@ -582,6 +587,96 @@ private static EnumDefaults ReadEnums(JsonElement root, string path) return maxLength is null ? EnumDefaults.Default : new EnumDefaults(maxLength); } + /// `verify.handEdits` and its values: read by the TypeScript `meta verify` only, validated by every port. + private const string VerifyKeyHandEdits = "handEdits"; + private static readonly string[] HandEditsPolicies = ["fail", "notice"]; + + /// The `rules` and `verify` blocks (ADR-0066): an unknown key, an unknown value or a non-object block is + /// refused, the same rule as `naming`. + private static RulesSettings ReadRules(JsonElement root, string path) + { + string permissionNames = RulesSettings.Default.PermissionNames; + string create = RulesSettings.Default.LifecycleCreate; + string commands = RulesSettings.Default.LifecycleCommands; + string unreachable = RulesSettings.Default.LifecycleUnreachable; + + static JsonElement.ObjectEnumerator Block(JsonElement owner, string name, string path) + { + if (owner.ValueKind != JsonValueKind.Object) + throw new MetaModelException($"{path}: \"{name}\" must be an object", ErrorCode.ERR_BAD_ATTR_VALUE); + return owner.EnumerateObject(); + } + + static string Choice(JsonElement value, string name, string[] allowed, string path) + { + var raw = value.ValueKind == JsonValueKind.String ? value.GetString() : null; + if (raw is null || !allowed.Contains(raw)) + throw new MetaModelException( + $"{path}: \"{name}\" must be one of {string.Join(", ", allowed.Select(a => $"\"{a}\""))}", + ErrorCode.ERR_BAD_ATTR_VALUE); + return raw; + } + + static MetaModelException Unknown(string path, string block, string key, string expected) => + new($"{path}: \"{block}\" has an unknown key \"{key}\" (expected {expected})", ErrorCode.ERR_BAD_ATTR_VALUE); + + if (root.TryGetProperty("rules", out var rules)) + { + foreach (var p in Block(rules, "rules", path)) + { + switch (p.Name) + { + case "permissions": + foreach (var q in Block(p.Value, "rules.permissions", path)) + { + if (q.Name != "names") throw Unknown(path, "rules.permissions", q.Name, "\"names\""); + permissionNames = Choice(q.Value, "rules.permissions.names", RulesSettings.PermissionNameValues, path); + } + break; + case "lifecycle": + foreach (var q in Block(p.Value, "rules.lifecycle", path)) + { + switch (q.Name) + { + case "create": + create = Choice(q.Value, "rules.lifecycle.create", RulesSettings.LifecycleCreateValues, path); + break; + case "commands": + commands = Choice(q.Value, "rules.lifecycle.commands", RulesSettings.LifecycleCommandsValues, path); + break; + default: + throw Unknown(path, "rules.lifecycle", q.Name, "\"create\" and/or \"commands\""); + } + } + break; + default: + throw Unknown(path, "rules", p.Name, "\"permissions\" and/or \"lifecycle\""); + } + } + } + + if (root.TryGetProperty("verify", out var verify)) + { + foreach (var p in Block(verify, "verify", path)) + { + // `verify.handEdits` is read by the TypeScript `meta verify` only (this port's verify + // already fails on any hand edit); it is validated here so `dotnet meta init`'s file loads. + if (p.Name == VerifyKeyHandEdits) + { + Choice(p.Value, "verify.handEdits", HandEditsPolicies, path); + continue; + } + if (p.Name != "lifecycle") throw Unknown(path, "verify", p.Name, "\"handEdits\" and/or \"lifecycle\""); + foreach (var q in Block(p.Value, "verify.lifecycle", path)) + { + if (q.Name != "unreachable") throw Unknown(path, "verify.lifecycle", q.Name, "\"unreachable\""); + unreachable = Choice(q.Value, "verify.lifecycle.unreachable", RulesSettings.LifecycleUnreachableValues, path); + } + } + } + return new RulesSettings(permissionNames, create, commands, unreachable); + } + /// The `wire` block (ADR-0019 Amendment 2): an unknown key, an unknown value, or a /// non-object block is refused, the same rule as `naming`. private static WireFormat ReadWire(JsonElement root, string path) diff --git a/server/csharp/MetaObjects/Config/RulesSettings.cs b/server/csharp/MetaObjects/Config/RulesSettings.cs new file mode 100644 index 0000000000..5ea983109b --- /dev/null +++ b/server/csharp/MetaObjects/Config/RulesSettings.cs @@ -0,0 +1,28 @@ +// ADR-0066 — the project settings the business-rules vocabulary reads, from the `rules` +// and `verify` blocks of `.metaobjects/config.json`. Every port reads the same keys with +// the same defaults. A key that is absent takes its default, which is always the +// behaviour a project had before the setting existed. Mirrors +// server/typescript/packages/metadata/src/rules-settings.ts. + +namespace MetaObjects.Config; + +/// The resolved settings, every absent key at its default. Each value is the +/// lower-case spelling the config uses. +/// rules.permissions.names: derive (default), advise, require. +/// rules.lifecycle.create: initial (default) or any. Read and validated; changes nothing yet. +/// rules.lifecycle.commands: unclaimed (default), all, none. +/// verify.lifecycle.unreachable: warn (default), error, off. +public sealed record RulesSettings( + string PermissionNames = "derive", + string LifecycleCreate = "initial", + string LifecycleCommands = "unclaimed", + string LifecycleUnreachable = "warn") +{ + public static readonly string[] PermissionNameValues = ["derive", "advise", "require"]; + public static readonly string[] LifecycleCreateValues = ["initial", "any"]; + public static readonly string[] LifecycleCommandsValues = ["unclaimed", "all", "none"]; + public static readonly string[] LifecycleUnreachableValues = ["warn", "error", "off"]; + + /// Every key at its default. + public static readonly RulesSettings Default = new(); +} diff --git a/server/csharp/MetaObjects/Config/SharedModel.cs b/server/csharp/MetaObjects/Config/SharedModel.cs index 2f6a6405df..56ec887c64 100644 --- a/server/csharp/MetaObjects/Config/SharedModel.cs +++ b/server/csharp/MetaObjects/Config/SharedModel.cs @@ -244,6 +244,7 @@ private static List CheckClosure( // node's own layer and is checked when the base itself is walked. foreach (var name in refBearingNames) { + if (!NamingRefs.IsRefBearingAttr(node, name)) continue; if (node.OwnAttr(name) is string s) candidates.Add(s); } var targets = new List(); diff --git a/server/csharp/MetaObjects/Core/Api/ApiConstants.cs b/server/csharp/MetaObjects/Core/Api/ApiConstants.cs new file mode 100644 index 0000000000..909ab5a287 --- /dev/null +++ b/server/csharp/MetaObjects/Core/Api/ApiConstants.cs @@ -0,0 +1,65 @@ +// Declared API surface constants (ADR-0030, ADR-0066) — subtypes and attribute keys for +// `api.*`, `operation.*` and `binding.*`. +// +// Colocated per ADR-0003. Mirrors +// server/typescript/packages/metadata/src/core/api/api-constants.ts. The type-name +// constants live in Shared/BaseTypes.cs beside every other base type. + +using System.Text.RegularExpressions; + +namespace MetaObjects.Core.Api; + +/// Constants of the declared API surface: subtypes, attr keys, reserved names. +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]; + + /// 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]; + + /// 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]; + + // Attrs on operation.* (and @permission / @public on transition.* too) + public const string OPERATION_ATTR_INPUT_REF = "inputRef"; + public const string OPERATION_ATTR_OUTPUT_REF = "outputRef"; + public const string OPERATION_ATTR_OBJECT_REF = "objectRef"; + public const string OPERATION_ATTR_TRANSITIONS = "transitions"; + public const string OPERATION_ATTR_PERMISSION = "permission"; + public const string OPERATION_ATTR_PUBLIC = "public"; + public const string OPERATION_ATTR_ERRORS = "errors"; + public const string OPERATION_ATTR_MANY = "many"; + + // Attrs on binding.rest + public const string BINDING_ATTR_METHOD = "method"; + public const string BINDING_ATTR_PATH = "path"; + public static readonly string[] HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"]; + + /// 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"]; + + /// A declared @permission: a dotted identifier path; a package prefix may use "::". Anchored + /// with \z so a trailing newline does not match. + public static readonly Regex PERMISSION_NAME_PATTERN = + new(@"^[A-Za-z_][A-Za-z0-9_]*(?:(?:\.|::)[A-Za-z_][A-Za-z0-9_]*)*\z", RegexOptions.CultureInvariant); + + /// A declared business error code: lower snake case. + public static readonly Regex BUSINESS_ERROR_CODE_PATTERN = + new(@"^[a-z][a-z0-9]*(_[a-z0-9]+)*\z", RegexOptions.CultureInvariant); + + /// Wire error codes an operation's route answers on its own, so a body may not declare them + /// in @errors (O5): the enforcing shell's codes (ADR-0066) and the API contract's generic ones. + public static readonly string[] RESERVED_ERROR_CODES = + [ + "not_found", "forbidden", "invalid_transition", "transition_condition_failed", "state_managed", + "validation", "invalid_json", "invalid_id", "method_not_allowed", "constraint_violation", "internal", + ]; +} diff --git a/server/csharp/MetaObjects/Core/Api/ApiSchema.cs b/server/csharp/MetaObjects/Core/Api/ApiSchema.cs new file mode 100644 index 0000000000..a761c2c47d --- /dev/null +++ b/server/csharp/MetaObjects/Core/Api/ApiSchema.cs @@ -0,0 +1,48 @@ +// Attribute schemas for the declared API surface (operation.*, binding.rest). +// +// Colocated per ADR-0003. Mirrors the canonical spec/metamodel/api.json: DESCRIPTIONS are +// not hand-copied — they come from the shared JSON via Registry.ApplySpecDescriptions. + +using MetaObjects.Core.Attr; + +namespace MetaObjects.Core.Api; + +/// Attribute schemas for operation.* and binding.*. +public static class ApiSchema +{ + private static AttrSchema Str(string name, bool isArray = false, IReadOnlyList? allowed = null) => + new(Name: name, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, + AllowedValues: allowed, IsArray: isArray); + + private static AttrSchema Bool(string name) => + new(Name: name, ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, Required: false); + + /// The attrs every operation shares (operation.base). + public static readonly IReadOnlyList OperationBaseAttrs = + [ + Str(ApiConstants.OPERATION_ATTR_INPUT_REF), + Str(ApiConstants.OPERATION_ATTR_OUTPUT_REF), + Str(ApiConstants.OPERATION_ATTR_OBJECT_REF), + Str(ApiConstants.OPERATION_ATTR_PERMISSION), + Bool(ApiConstants.OPERATION_ATTR_PUBLIC), + ]; + + public static readonly IReadOnlyList CommandAttrs = + [ + .. OperationBaseAttrs, + Str(ApiConstants.OPERATION_ATTR_TRANSITIONS, isArray: true), + Str(ApiConstants.OPERATION_ATTR_ERRORS, isArray: true), + ]; + + public static readonly IReadOnlyList QueryAttrs = + [ + .. OperationBaseAttrs, + Bool(ApiConstants.OPERATION_ATTR_MANY), + ]; + + public static readonly IReadOnlyList RestBindingAttrs = + [ + Str(ApiConstants.BINDING_ATTR_METHOD, allowed: [.. ApiConstants.HTTP_METHODS]), + Str(ApiConstants.BINDING_ATTR_PATH), + ]; +} diff --git a/server/csharp/MetaObjects/Core/Transition/Lifecycle.cs b/server/csharp/MetaObjects/Core/Transition/Lifecycle.cs new file mode 100644 index 0000000000..bef3eb2d6e --- /dev/null +++ b/server/csharp/MetaObjects/Core/Transition/Lifecycle.cs @@ -0,0 +1,258 @@ +// Lifecycle and operation-target derivation (ADR-0066), shared by the loader's rules pass +// and `verify`'s rules gate. Everything here is DERIVED: a lifecycle, its states, its +// initial and terminal states and an operation's target entity have no vocabulary of their +// own. Mirrors server/typescript/packages/metadata/src/core/transition/lifecycle.ts. +// +// Reads are RESOLVING (ADR-0039): a transition declared on a base entity's field is a +// transition of every entity that extends it. It is NOT a transition of an entity whose field +// merely `extends` that field: a field extends another to share its values, and a history +// table of an order's status is not an order (LifecycleTransitionsOf). + +using MetaObjects.Meta; + +namespace MetaObjects.Core.Transition; + +/// One lifecycle of an entity: an enum field with at least one transition. +/// The enum field. +/// The enum's @values, in declaration order. +/// The enum's @default; null only on a model the loader refused. +/// The field's transitions. +public sealed record Lifecycle( + MetaData Field, + IReadOnlyList States, + string? Initial, + IReadOnlyList Transitions); + +/// How an operation's target was derived. ViaInput means the input borrows the target's key. +public sealed record DerivedTarget(MetaData Entity, bool ViaInput); + +/// Lifecycle and operation-target derivations. +public static class Lifecycles +{ + /// A string-array attr read resolving; a bare string is ONE element. + public static IReadOnlyList StringList(MetaData node, string attr) => node.Attr(attr) switch + { + IReadOnlyList list => list, + IReadOnlyList objs => objs.OfType().ToList(), + string s => [s], + _ => [], + }; + + private static string? StringValue(MetaData node, string attr) => node.Attr(attr) as string; + + /// The transition.action children of a field, resolving. + public static IReadOnlyList TransitionsOf(MetaData field) => + field.Children().Where(c => c.Type == TYPE_TRANSITION && c.SubType == TRANSITION_SUBTYPE_ACTION).ToList(); + + /// Whether an entity's lifecycles are live: it declares or inherits a source. A lifecycle on an + /// entity with no source loads and is inert (it derives no command); the writable-source check applies + /// once a source is added (ADR-0066 section 2). Read through the resolving accessor. + public static bool LifecycleIsLive(MetaData entity) => entity.Children().Any(c => c.Type == TYPE_SOURCE); + + /// An entity and every entity it extends, nearest first. + public static IReadOnlyList EntityLineage(MetaData entity) + { + var output = new List(); + for (MetaData? e = entity; e is not null && !output.Contains(e); e = e.SuperData) output.Add(e); + return output; + } + + /// The transitions a field gives an entity: those declared on a field of the entity itself or + /// of an entity it extends. A transition reached only through the field's own extends of + /// another entity's field is not one (ADR-0066 section 2). + public static IReadOnlyList LifecycleTransitionsOf(MetaData entity, MetaData field) + { + var lineage = EntityLineage(entity); + return TransitionsOf(field).Where(t => t.Parent?.Parent is { } owner && lineage.Contains(owner)).ToList(); + } + + /// The lifecycles of an object, in effective field order. Only an object.entity has any. + public static IReadOnlyList LifecyclesOf(MetaData obj) + { + if (obj.Type != TYPE_OBJECT || obj.SubType != OBJECT_SUBTYPE_ENTITY) return []; + var output = new List(); + foreach (var field in obj.Children()) + { + if (field.Type != TYPE_FIELD || field.SubType != FIELD_SUBTYPE_ENUM) continue; + var transitions = LifecycleTransitionsOf(obj, field); + if (transitions.Count == 0) continue; + output.Add(new Lifecycle( + field, + StringList(field, FIELD_ATTR_VALUES), + field.Attr(FIELD_ATTR_DEFAULT) as string, + transitions)); + } + return output; + } + + /// Every transition of an entity, across all its lifecycles. + public static IReadOnlyList EntityTransitions(MetaData obj) => + LifecyclesOf(obj).SelectMany(l => l.Transitions).ToList(); + + /// A transition's @from (resolving). + public static IReadOnlyList TransitionFrom(MetaData t) => StringList(t, TRANSITION_ATTR_FROM); + + /// A transition's @to (resolving). + public static string? TransitionTo(MetaData t) => StringValue(t, TRANSITION_ATTR_TO); + + /// The states reachable from the initial state, following every transition. + public static HashSet ReachableStates(Lifecycle l) + { + var seen = new HashSet(StringComparer.Ordinal); + if (l.Initial is null) return seen; + var queue = new Queue(); + queue.Enqueue(l.Initial); + seen.Add(l.Initial); + while (queue.Count > 0) + { + var s = queue.Dequeue(); + foreach (var t in l.Transitions) + { + var to = TransitionTo(t); + if (to is not null && TransitionFrom(t).Contains(s) && seen.Add(to)) queue.Enqueue(to); + } + } + return seen; + } + + /// The members no transition leaves (a self-transition counts as leaving). + public static IReadOnlyList TerminalStates(Lifecycle l) + { + var leaving = l.Transitions.SelectMany(TransitionFrom).ToHashSet(StringComparer.Ordinal); + return l.States.Where(s => !leaving.Contains(s)).ToList(); + } + + /// The primary key field names of an entity: its effective identity.primary @fields. + public static IReadOnlyList PrimaryKeyFields(MetaData entity) + { + var primary = entity.Children().FirstOrDefault(c => c.Type == TYPE_IDENTITY && c.SubType == IDENTITY_SUBTYPE_PRIMARY); + return primary is null ? [] : StringList(primary, IDENTITY_ATTR_FIELDS); + } + + /// The package a node's references resolve in: its top-level node's effective package. + public static string ReferrerPackageOf(MetaData node) => + NamingRefs.EffectivePackageOf(NamingRefs.TopLevelNodeOf(node)); + + /// Resolve an object reference written on (owner part only). + public static MetaData? ResolveObjectOn(MetaData node, string reference) => + NamingRefs.ResolveObjectRef(node.Root(), NamingRefs.SplitChildTail(reference).Owner, ReferrerPackageOf(node)); + + /// + /// The object a field's extends NAMES, and the member it names there. id extends + /// PurchaseRequest.id names PurchaseRequest even when PurchaseRequest inherits id from + /// an abstract base, which is where the resolved super node physically lives. + /// + private static (MetaData Owner, string Member)? ExtendedMember(MetaData f) + { + var reference = f.SuperRef; + var sup = f.SuperData; + if (reference is null || sup is null) return null; + var (owner, tail) = NamingRefs.SplitChildTail(reference); + if (tail.Length > 0) + { + var named = NamingRefs.ResolveObjectRef(f.Root(), owner, ReferrerPackageOf(f)); + if (named is not null) return (named, sup.Name); + } + var parent = sup.Parent; + return parent is not null && parent.Type == TYPE_OBJECT ? (parent, sup.Name) : null; + } + + /// The entities whose whole primary key a value object borrows, once: every primary key field + /// of the object.entity is extended by exactly one field of the value. A value that borrows part + /// of a composite key, or one key field twice, names no single row of that entity, so it borrows + /// nothing from it. + private static List BorrowedKeyEntities(MetaData value) + { + var counts = new List<(MetaData Owner, Dictionary Members)>(); + foreach (var f in value.Children()) + { + if (f.Type != TYPE_FIELD) continue; + if (ExtendedMember(f) is not { } ext || ext.Owner.SubType != OBJECT_SUBTYPE_ENTITY) continue; + if (!PrimaryKeyFields(ext.Owner).Contains(ext.Member)) continue; + var idx = counts.FindIndex(c => ReferenceEquals(c.Owner, ext.Owner)); + if (idx < 0) { counts.Add((ext.Owner, new Dictionary(StringComparer.Ordinal))); idx = counts.Count - 1; } + var members = counts[idx].Members; + members[ext.Member] = members.GetValueOrDefault(ext.Member) + 1; + } + return counts + .Where(c => PrimaryKeyFields(c.Owner).All(k => c.Members.GetValueOrDefault(k) == 1)) + .Select(c => c.Owner).ToList(); + } + + /// The base entity of a projection: the entity its extended identity names, else the one + /// entity its extended fields name. Null when there is none or more than one. + public static MetaData? ProjectionBaseEntity(MetaData projection) + { + foreach (var id in projection.Children()) + { + if (id.Type != TYPE_IDENTITY) continue; + if (ExtendedMember(id) is { } ext && ext.Owner.SubType == OBJECT_SUBTYPE_ENTITY) return ext.Owner; + } + var owners = new List(); + foreach (var f in projection.Children()) + { + if (f.Type != TYPE_FIELD) continue; + if (ExtendedMember(f) is { } ext && ext.Owner.SubType == OBJECT_SUBTYPE_ENTITY && !owners.Contains(ext.Owner)) + owners.Add(ext.Owner); + } + return owners.Count == 1 ? owners[0] : null; + } + + /// + /// The target entity derived from an operation's shapes, or null: + /// 1. the one entity whose whole primary key the @inputRef value borrows (by extends), + /// each key field once; + /// 2. else the @outputRef: an entity is its own target, a projection its base entity. + /// Whole keys of two entities, part of a key, or one key field borrowed twice derive nothing + /// from the input. + /// + public static DerivedTarget? DeriveOperationTarget(MetaData op) + { + if (StringValue(op, OPERATION_ATTR_INPUT_REF) is { } inputRef) + { + var input = ResolveObjectOn(op, inputRef); + if (input is not null && input.SubType == OBJECT_SUBTYPE_VALUE) + { + var borrowed = BorrowedKeyEntities(input); + if (borrowed.Count == 1) return new DerivedTarget(borrowed[0], ViaInput: true); + } + } + if (StringValue(op, OPERATION_ATTR_OUTPUT_REF) is { } outputRef) + { + var output = ResolveObjectOn(op, outputRef); + if (output?.SubType == OBJECT_SUBTYPE_ENTITY) return new DerivedTarget(output, ViaInput: false); + if (output?.SubType == OBJECT_SUBTYPE_PROJECTION) + { + var baseEntity = ProjectionBaseEntity(output); + if (baseEntity is not null) return new DerivedTarget(baseEntity, ViaInput: false); + } + } + return null; + } + + /// The operation's target: the declared @objectRef when it names an entity, else the derived one. + public static MetaData? OperationTarget(MetaData op) + { + if (StringValue(op, OPERATION_ATTR_OBJECT_REF) is { } declared) + { + var node = ResolveObjectOn(op, declared); + return node?.SubType == OBJECT_SUBTYPE_ENTITY ? node : null; + } + return DeriveOperationTarget(op)?.Entity; + } + + /// + /// Whether the operation addresses one row of its target by key, so its derived path is + /// /<collection>/{key}/<operation>: its input borrows the target's key, or it is a + /// query with no input and no @many whose target comes from its output (a get by key). + /// + public static bool OperationIsKeyed(MetaData op) + { + var derived = DeriveOperationTarget(op); + if (derived is null) return false; + if (derived.ViaInput) return true; + return op.SubType == OPERATION_SUBTYPE_QUERY + && StringValue(op, OPERATION_ATTR_INPUT_REF) is null + && op.Attr(OPERATION_ATTR_MANY) is not true; + } +} diff --git a/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs b/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs new file mode 100644 index 0000000000..d05970c8f7 --- /dev/null +++ b/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs @@ -0,0 +1,276 @@ +// `verify` — the business-rules gate (ADR-0066). +// +// The loader refuses a model whose operations or lifecycles are malformed. This gate reports +// what loads clean but is almost certainly not what the author meant: a state nothing can +// reach, a lifecycle that cannot move, a transition nothing can make, and (by setting) a +// permission name the model derived instead of declaring. +// +// TypeScript is the reference (server/typescript/packages/cli/src/lib/rules-check.ts); this +// port implements the same checks with the same codes, severities, paths and message text, +// and fixtures/rules-check-conformance/ is the contract. A model that declares no operation +// and no transition gets no diagnostics, no summary and no gate row: opt-in by declaration. +// +// Checks, in the order they are reported: +// WARN_LIFECYCLE_UNREACHABLE_STATE states no transition reaches from the initial state +// (severity: `verify.lifecycle.unreachable`) +// WARN_LIFECYCLE_INITIAL_TERMINAL the initial state is one no transition leaves +// WARN_TRANSITION_UNREACHABLE a transition whose every @from state is unreachable +// (severity: `verify.lifecycle.unreachable`) +// WARN_TRANSITION_PERMISSION_SHADOWED a transition declaring @permission or @public: true that +// derives no command of its own, so the attribute is never +// read (always a warning) +// WARN_PERMISSION_DERIVED_NAME a transition that derives its own command, or an +// operation, with no @permission and not @public +// (severity: `rules.permissions.names`) +// +// Lifecycles are checked once per declaring field, so a lifecycle on an abstract base is +// reported once, not once per inheritor. A derived command exists per concrete entity, so +// the permission check runs per concrete entity and names it. +// +// A command claims a transition NODE for its target entity and every entity that extends the +// target: a command acting on an abstract base claims the inherited transition of each child. + +using System.Globalization; +using MetaObjects.Config; +using MetaObjects.Core.Requirement; +using MetaObjects.Meta; + +namespace MetaObjects.Core.Transition; + +/// What the model declares, for the line `verify` prints on every run. +/// Declared operations, across every api.operational. +/// Lifecycles: enum fields that declare at least one transition. +/// Declared transitions, across every lifecycle. +public sealed record RulesSummary(int Operations, int Lifecycles, int Transitions); + +/// The rules gate's result. is null when the model declares no operation and no transition. +public sealed record RulesCheckResult(IReadOnlyList Diagnostics, RulesSummary? Summary); + +/// The business-rules gate. +public static class RulesCheck +{ + public const string SeverityError = "error"; + public const string SeverityWarn = "warn"; + + public const string WARN_LIFECYCLE_UNREACHABLE_STATE = "WARN_LIFECYCLE_UNREACHABLE_STATE"; + public const string WARN_LIFECYCLE_INITIAL_TERMINAL = "WARN_LIFECYCLE_INITIAL_TERMINAL"; + public const string WARN_TRANSITION_UNREACHABLE = "WARN_TRANSITION_UNREACHABLE"; + public const string WARN_TRANSITION_PERMISSION_SHADOWED = "WARN_TRANSITION_PERMISSION_SHADOWED"; + public const string WARN_PERMISSION_DERIVED_NAME = "WARN_PERMISSION_DERIVED_NAME"; + + private static string QuoteList(IEnumerable xs) => string.Join(", ", xs.Select(x => $"\"{x}\"")); + + /// A node's package-qualified address: acme::shop::Order.status.submit. + public static string Address(MetaData node) + { + var parts = new List(); + for (MetaData? n = node; n is not null && n.Parent is not null; n = n.Parent) + { + if (n.Name != "") parts.Insert(0, n.Name); + } + var pkg = NamingRefs.EffectivePackageOf(NamingRefs.TopLevelNodeOf(node)); + var dotted = string.Join(".", parts); + return pkg.Length == 0 ? dotted : $"{pkg}{PACKAGE_SEPARATOR}{dotted}"; + } + + /// The permission name a node gets when it declares none, <package>.<path>: the path is + /// <operation> for an operation and <Entity>.<transition> for a transition's derived command. + private static string DerivedPermissionName(MetaData owner, string path) + { + var pkg = NamingRefs.EffectivePackageOf(NamingRefs.TopLevelNodeOf(owner)); + return pkg.Length == 0 ? path : $"{pkg}.{path}"; + } + + private static bool NeedsPermissionName(MetaData node) => + node.Attr(OPERATION_ATTR_PERMISSION) is null && node.Attr(OPERATION_ATTR_PUBLIC) is not true; + + private static List Entities(MetaData root) => + root.Children().Where(c => c.Type == TYPE_OBJECT && c.SubType == OBJECT_SUBTYPE_ENTITY).ToList(); + + private static List Operations(MetaData root) => + root.Children().Where(c => c.Type == TYPE_API) + .SelectMany(api => api.Children().Where(c => c.Type == TYPE_OPERATION)).ToList(); + + /// Every lifecycle of the model, once per declaring field, in model order. + private static List DeclaredLifecycles(MetaData root) + { + var seen = new HashSet(ReferenceEqualityComparer.Instance); + var output = new List(); + foreach (var entity in Entities(root)) + { + foreach (var l in Lifecycles.LifecyclesOf(entity)) + { + if (!seen.Add(l.Field)) continue; + output.Add(l); + } + } + return output; + } + + private static void CheckLifecycle(Lifecycle l, RulesSettings settings, List output) + { + var where = Address(l.Field); + var initial = l.Initial; + if (initial is null) return; // the loader refused this model (ERR_LIFECYCLE_NO_INITIAL) + var reachable = Lifecycles.ReachableStates(l); + string? unreachableSeverity = settings.LifecycleUnreachable == "off" ? null : settings.LifecycleUnreachable; + + if (unreachableSeverity is not null) + { + var unreachable = l.States.Where(s => !reachable.Contains(s)).ToList(); + if (unreachable.Count > 0) + { + output.Add(new RequirementDiagnostic(unreachableSeverity, WARN_LIFECYCLE_UNREACHABLE_STATE, where, + $"{(unreachable.Count == 1 ? "state" : "states")} {QuoteList(unreachable)} of \"{l.Field.Name}\" " + + $"cannot be reached from the initial state \"{initial}\" by any transition. " + + "Add the transition that leads there, or set verify.lifecycle.unreachable if only seeded data uses " + + $"{(unreachable.Count == 1 ? "it" : "them")}.")); + } + } + + if (Lifecycles.TerminalStates(l).Contains(initial)) + { + output.Add(new RequirementDiagnostic(SeverityWarn, WARN_LIFECYCLE_INITIAL_TERMINAL, where, + $"the initial state \"{initial}\" of \"{l.Field.Name}\" is terminal: no transition leaves it, " + + "so no row of this lifecycle can ever move.")); + } + + if (unreachableSeverity is not null) + { + foreach (var t in l.Transitions) + { + var from = Lifecycles.TransitionFrom(t); + if (from.Count == 0 || from.Any(reachable.Contains)) continue; + output.Add(new RequirementDiagnostic(unreachableSeverity, WARN_TRANSITION_UNREACHABLE, Address(t), + $"transition \"{t.Name}\" starts only from {QuoteList(from)}, which no transition reaches from " + + $"the initial state \"{initial}\", so it can never be made.")); + } + } + } + + /// One command's claim on a transition node, made for its target entity. + private sealed record Claim(MetaData Target, MetaData Op); + + /// Each transition node the declared commands claim, with the claims on it in model order. + private static Dictionary> ClaimedTransitions(MetaData root) + { + var claimed = new Dictionary>(ReferenceEqualityComparer.Instance); + foreach (var op in Operations(root)) + { + if (op.SubType != OPERATION_SUBTYPE_COMMAND) continue; + var target = Lifecycles.OperationTarget(op); + if (target is null) continue; + var names = Lifecycles.StringList(op, OPERATION_ATTR_TRANSITIONS).ToHashSet(StringComparer.Ordinal); + foreach (var t in Lifecycles.EntityTransitions(target)) + { + if (!names.Contains(t.Name)) continue; + if (!claimed.TryGetValue(t, out var claims)) claimed[t] = claims = []; + claims.Add(new Claim(target, op)); + } + } + return claimed; + } + + /// The claims that cover transition on : those made for the entity or an entity it extends. + private static List ClaimsOn(Dictionary> claimed, MetaData entity, MetaData t) + { + var lineage = Lifecycles.EntityLineage(entity); + return claimed.TryGetValue(t, out var claims) ? claims.Where(c => lineage.Contains(c.Target)).ToList() : []; + } + + /// Whether , carried by , derives a command of its own under the setting. + private static bool DerivesCommand(Dictionary> claimed, RulesSettings settings, MetaData entity, MetaData t) => + settings.LifecycleCommands switch + { + "none" => false, + "all" => true, + _ => ClaimsOn(claimed, entity, t).Count == 0, + }; + + /// The entities a transition can derive a command on: concrete, with a source. + private static List CommandEntities(MetaData root) => + Entities(root).Where(e => !e.IsAbstract && Lifecycles.LifecycleIsLive(e)).ToList(); + + /// A transition's @permission or @public is read only by the command derived from it. One that + /// derives no command for any entity carrying it declares an attribute nothing reads. One carried only by + /// entities with no source is inert, not shadowed. + private static void CheckShadowedPermissions(MetaData root, RulesSettings settings, List output) + { + if (settings.LifecycleCommands == "all") return; + var claimed = ClaimedTransitions(root); + var carriers = new List<(MetaData T, List Entities)>(); + foreach (var entity in CommandEntities(root)) + { + foreach (var t in Lifecycles.EntityTransitions(entity)) + { + var idx = carriers.FindIndex(c => ReferenceEquals(c.T, t)); + if (idx < 0) carriers.Add((t, [entity])); else carriers[idx].Entities.Add(entity); + } + } + foreach (var (t, entitiesWithT) in carriers) + { + var permission = t.Attr(OPERATION_ATTR_PERMISSION); + var isPublic = t.Attr(OPERATION_ATTR_PUBLIC) is true; + if (permission is null && !isPublic) continue; + if (entitiesWithT.Any(e => DerivesCommand(claimed, settings, e, t))) continue; + var declared = permission is not null ? $"@permission \"{permission}\"" : "@public: true"; + var claimers = entitiesWithT.SelectMany(e => ClaimsOn(claimed, e, t)) + .Select(c => $"{c.Op.Parent?.Name ?? ""}.{c.Op.Name}").Distinct(StringComparer.Ordinal).ToList(); + var why = settings.LifecycleCommands == "none" + ? "rules.lifecycle.commands is \"none\": no command is derived from it" + : $"it derives no command of its own: it is made only by {QuoteList(claimers)}, which " + + $"{(claimers.Count == 1 ? "asks" : "ask")} the policy about {(claimers.Count == 1 ? "its" : "their")} own permission"; + output.Add(new RequirementDiagnostic(SeverityWarn, WARN_TRANSITION_PERMISSION_SHADOWED, Address(t), + $"transition \"{t.Name}\" declares {declared}, but {why}, so the attribute is never read. " + + "Remove it from the transition, or declare it on the command that makes the transition.")); + } + } + + private static void CheckPermissionNames(MetaData root, RulesSettings settings, List output) + { + if (settings.PermissionNames == "derive") return; + var severity = settings.PermissionNames == "require" ? SeverityError : SeverityWarn; + static string Advice(string kind) => $"which changes if the {kind} is renamed. Declare @permission, or @public: true."; + + if (settings.LifecycleCommands != "none") + { + var claimed = ClaimedTransitions(root); + foreach (var entity in CommandEntities(root)) + { + foreach (var t in Lifecycles.EntityTransitions(entity)) + { + if (!DerivesCommand(claimed, settings, entity, t)) continue; + if (!NeedsPermissionName(t)) continue; + output.Add(new RequirementDiagnostic(severity, WARN_PERMISSION_DERIVED_NAME, + $"{Address(entity)}.{t.Parent?.Name ?? ""}.{t.Name}", + $"the command derived from transition \"{t.Name}\" of \"{entity.Name}\" has no @permission, so it asks " + + $"the policy about the derived name \"{DerivedPermissionName(entity, $"{entity.Name}.{t.Name}")}\", {Advice("transition")}")); + } + } + } + + foreach (var op in Operations(root)) + { + if (!NeedsPermissionName(op)) continue; + output.Add(new RequirementDiagnostic(severity, WARN_PERMISSION_DERIVED_NAME, Address(op), + $"operation.{op.SubType} \"{op.Name}\" has no @permission, so it asks the policy about the derived " + + $"name \"{DerivedPermissionName(op, op.Name)}\", {Advice("operation")}")); + } + } + + /// The rules gate over a loaded model. + public static RulesCheckResult Check(MetaData root, RulesSettings settings) + { + var lifecycles = DeclaredLifecycles(root); + var ops = Operations(root); + if (lifecycles.Count == 0 && ops.Count == 0) return new RulesCheckResult([], null); + + var diagnostics = new List(); + foreach (var l in lifecycles) CheckLifecycle(l, settings, diagnostics); + CheckShadowedPermissions(root, settings, diagnostics); + CheckPermissionNames(root, settings, diagnostics); + return new RulesCheckResult( + diagnostics, + new RulesSummary(ops.Count, lifecycles.Count, lifecycles.Sum(l => l.Transitions.Count))); + } +} diff --git a/server/csharp/MetaObjects/Core/Transition/TransitionConstants.cs b/server/csharp/MetaObjects/Core/Transition/TransitionConstants.cs new file mode 100644 index 0000000000..d7ff4d4a8c --- /dev/null +++ b/server/csharp/MetaObjects/Core/Transition/TransitionConstants.cs @@ -0,0 +1,25 @@ +// Lifecycle constants (ADR-0066) — the `transition` type, its subtype and attrs. +// +// A lifecycle has no vocabulary of its own: it is a `field.enum` with at least one +// `transition.action` child. Its states are the enum's @values, its initial state the +// enum's @default, its terminal states the members no transition leaves. +// Mirrors server/typescript/packages/metadata/src/core/transition/transition-constants.ts. + +namespace MetaObjects.Core.Transition; + +/// Constants of the lifecycle concern. +public static class TransitionConstants +{ + /// A move made by an operation. + public const string TRANSITION_SUBTYPE_ACTION = "action"; + public static readonly string[] TRANSITION_SUBTYPES = [TRANSITION_SUBTYPE_ACTION]; + + /// The states a move may start from (members of the parent enum's @values). + public const string TRANSITION_ATTR_FROM = "from"; + /// The state a move ends in. + public const string TRANSITION_ATTR_TO = "to"; + /// A guard over the entity's own fields (the attr.expression grammar). + public const string TRANSITION_ATTR_CONDITION = "condition"; + public const string TRANSITION_ATTR_PERMISSION = "permission"; + public const string TRANSITION_ATTR_PUBLIC = "public"; +} diff --git a/server/csharp/MetaObjects/Core/Transition/TransitionSchema.cs b/server/csharp/MetaObjects/Core/Transition/TransitionSchema.cs new file mode 100644 index 0000000000..2b6543cddb --- /dev/null +++ b/server/csharp/MetaObjects/Core/Transition/TransitionSchema.cs @@ -0,0 +1,25 @@ +// Attribute schemas for transition.* (ADR-0066). Mirrors spec/metamodel/transition.json; +// descriptions come from the shared JSON via Registry.ApplySpecDescriptions. + +using MetaObjects.Core.Attr; + +namespace MetaObjects.Core.Transition; + +/// Attribute schemas for transition.*. +public static class TransitionSchema +{ + /// The attrs every transition shares (transition.base). + public static readonly IReadOnlyList TransitionBaseAttrs = + [ + new(Name: TransitionConstants.TRANSITION_ATTR_PERMISSION, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false), + new(Name: TransitionConstants.TRANSITION_ATTR_PUBLIC, ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, Required: false), + ]; + + public static readonly IReadOnlyList ActionAttrs = + [ + .. TransitionBaseAttrs, + new(Name: TransitionConstants.TRANSITION_ATTR_FROM, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true, IsArray: true), + new(Name: TransitionConstants.TRANSITION_ATTR_TO, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true), + new(Name: TransitionConstants.TRANSITION_ATTR_CONDITION, ValueType: AttrConstants.ATTR_SUBTYPE_EXPRESSION, Required: false), + ]; +} diff --git a/server/csharp/MetaObjects/CoreTypes.cs b/server/csharp/MetaObjects/CoreTypes.cs index d357b4b908..5e09ffe41d 100644 --- a/server/csharp/MetaObjects/CoreTypes.cs +++ b/server/csharp/MetaObjects/CoreTypes.cs @@ -15,7 +15,9 @@ using MetaObjects.Core.Identity; using MetaObjects.Core.Index; using MetaObjects.Core.Relationship; +using MetaObjects.Core.Api; using MetaObjects.Core.Reporting; +using MetaObjects.Core.Transition; using MetaObjects.Core.Requirement; using MetaObjects.Persistence.Origin; using MetaObjects.Persistence.Source; @@ -270,6 +272,8 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) Wildcard(TYPE_TEMPLATE), // Capability requirements are declared beside the entities they describe. Wildcard(TYPE_REQUIREMENT), + // ADR-0030 / ADR-0066 — a declared API surface is a top-level, packaged node. + Wildcard(TYPE_API), ], (tid, n) => new MetaRoot(tid, n), [])); @@ -684,6 +688,23 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) ReportingSchema.SegmentAttrsMap[subType].ToList())); } + // ADR-0030 / ADR-0066 — the declared API surface (api / operation / binding) and + // lifecycle moves (transition, a child of field.enum). One class per type; the + // subtype carries no behaviour of its own. Descriptions, the structural child graph + // and cardinalities come from the embedded api.json / transition.json via + // ApplySpecDescriptions; the cross-node rules live in Loader/ValidationPasses.Rules.cs. + void RegisterRulesType(string type, string subType, List attrs, Func factory) => + registry.Register(Def(type, subType, $"{type} ({subType})", [Wildcard(TYPE_ATTR)], factory, attrs)); + RegisterRulesType(TYPE_API, SUBTYPE_BASE, [], (tid, n) => new MetaApi(tid, n)); + RegisterRulesType(TYPE_API, API_SUBTYPE_OPERATIONAL, [], (tid, n) => new MetaApi(tid, n)); + RegisterRulesType(TYPE_OPERATION, SUBTYPE_BASE, [.. ApiSchema.OperationBaseAttrs], (tid, n) => new MetaOperation(tid, n)); + RegisterRulesType(TYPE_OPERATION, OPERATION_SUBTYPE_COMMAND, [.. ApiSchema.CommandAttrs], (tid, n) => new MetaOperation(tid, n)); + RegisterRulesType(TYPE_OPERATION, OPERATION_SUBTYPE_QUERY, [.. ApiSchema.QueryAttrs], (tid, n) => new MetaOperation(tid, n)); + RegisterRulesType(TYPE_BINDING, SUBTYPE_BASE, [], (tid, n) => new MetaBinding(tid, n)); + RegisterRulesType(TYPE_BINDING, BINDING_SUBTYPE_REST, [.. ApiSchema.RestBindingAttrs], (tid, n) => new MetaBinding(tid, n)); + RegisterRulesType(TYPE_TRANSITION, SUBTYPE_BASE, [.. TransitionSchema.TransitionBaseAttrs], (tid, n) => new MetaTransition(tid, n)); + RegisterRulesType(TYPE_TRANSITION, TRANSITION_SUBTYPE_ACTION, [.. TransitionSchema.ActionAttrs], (tid, n) => new MetaTransition(tid, n)); + // template — fourth-pillar metatype (FR-004). prompt + output + toolcall; // attr-only children. A single MetaTemplate class backs every subtype (mirrors // source/requirement); per-subtype attr schemas drive validation (prompt + diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index 728d590f3d..ca72657be3 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -270,6 +270,33 @@ public enum ErrorCode // An object.report lists a measure that belongs to an entity other than @from; // v1 refuses multi-fact reports (R3). ERR_REPORT_FOREIGN_MEASURE, + // ADR-0066 — business rules (ValidationPasses.ValidateRules). A transition.action + // @from/@to value that is not a member of its enum (L4). + ERR_TRANSITION_UNKNOWN_STATE, + // A transition.action on a field of anything but an object.entity, or a concrete + // entity with a lifecycle and no writable source (L1, L2). + ERR_TRANSITION_NOT_ON_ENTITY, + // An enum field with transitions and no @default, its initial state (L3). + ERR_LIFECYCLE_NO_INITIAL, + // An entity redeclares an inherited lifecycle field without extending it, so the base's + // transitions would be lost (L10). + ERR_LIFECYCLE_REDECLARED, + // Two transitions of one entity share a name, or a transition or operation is named + // create / get / list / update / delete (L5, L6, O0). + ERR_TRANSITION_NAME_COLLISION, + // An operation's @objectRef is not an entity, or a command lists @transitions with no + // target (O2). + ERR_OPERATION_TARGET_UNRESOLVED, + // A declared @objectRef disagrees with the derived target (O3). + ERR_OPERATION_TARGET_MISMATCH, + // A @transitions name that is not a transition of the operation's target (O4). + ERR_OPERATION_UNKNOWN_TRANSITION, + // @inputRef is not an object.value, or @outputRef is not an entity, projection or value (O1). + ERR_OPERATION_SHAPE, + // @public: true together with @permission (P1). + ERR_PERMISSION_PUBLIC_CONFLICT, + // A binding.rest @path whose placeholders are not the target's key fields (B1). + ERR_BINDING_PATH_MISMATCH, // FR-039 — @status: retired declares @implementedBy. Refused rather than exempted: // a retired capability has no implementation BY DEFINITION, so forbidding the // attribute makes the dangling-reference class unreachable instead of tolerated. diff --git a/server/csharp/MetaObjects/GlobalUsings.cs b/server/csharp/MetaObjects/GlobalUsings.cs index fc271fe67e..3a169cd9a9 100644 --- a/server/csharp/MetaObjects/GlobalUsings.cs +++ b/server/csharp/MetaObjects/GlobalUsings.cs @@ -22,6 +22,8 @@ global using static MetaObjects.Core.Relationship.RelationshipConstants; global using static MetaObjects.Core.Requirement.RequirementConstants; global using static MetaObjects.Core.Reporting.ReportingConstants; +global using static MetaObjects.Core.Api.ApiConstants; +global using static MetaObjects.Core.Transition.TransitionConstants; global using static MetaObjects.Persistence.Source.SourceConstants; global using static MetaObjects.Persistence.Origin.OriginConstants; global using static MetaObjects.Persistence.Db.DbConstants; diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index 0192498084..7ffdc10198 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -538,6 +538,9 @@ public LoadResult Load(IReadOnlyList sources) // segments, reports, relative-date filter values). errors.AddRange(ValidationPasses.ValidateReporting(root, _registry)); + // Pass 7d (ADR-0066): business rules — operations (slice A) and lifecycles (slice B). + errors.AddRange(ValidationPasses.ValidateRules(root)); + // Pass 8: @storage cross-attribute validation on field.object errors.AddRange(ValidationPasses.ValidateFieldObjectStorage(root)); diff --git a/server/csharp/MetaObjects/Loader/ResolveReferences.cs b/server/csharp/MetaObjects/Loader/ResolveReferences.cs index c44a7e0519..5c35778e88 100644 --- a/server/csharp/MetaObjects/Loader/ResolveReferences.cs +++ b/server/csharp/MetaObjects/Loader/ResolveReferences.cs @@ -34,7 +34,7 @@ private static void Visit(MetaData root, MetaData node) // is resolved once, on the node that declares it. foreach (string name in node.OwnAttrs().Keys.ToList()) { - if (NamingRefs.RefBearingAttrNames.Contains(name)) ResolveAttr(root, node, name, declPkg); + if (NamingRefs.IsRefBearingAttr(node, name)) ResolveAttr(root, node, name, declPkg); } } // ADR-0039: own — structural walk over the physical declaration tree. diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs new file mode 100644 index 0000000000..7f8c7f309e --- /dev/null +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs @@ -0,0 +1,426 @@ +// ADR-0066 — cross-node rules for operations (slice A) and lifecycles (slice B). +// +// Ported rule-for-rule, WITH THE SAME MESSAGE TEXT, from the TS reference +// server/typescript/packages/metadata/src/loader/rules-validation.ts; the fixtures under +// fixtures/conformance/ (`error-rules-*`, with the positive `rules-*` cases) are the contract. +// +// One broken rule yields one error: +// - Each error's source is the offending node: the transition, the enum field (L3), the +// entity (L2b), the operation or the binding. +// - An operation whose @inputRef / @outputRef fails O1 is not checked further; one whose +// target fails O2 or O3 is not checked for O4 or B1. +// - An error is reported once per (node, code), so a broken transition on an abstract base +// is reported once, not once per inheritor. +// +// 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 (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 +// L6 ERR_TRANSITION_NAME_COLLISION two transitions of one entity (across its lifecycles) share a +// name, compared without case +// L7 ERR_BAD_ATTR_VALUE @condition names a field the entity does not have, or is not boolean +// L8 ERR_BAD_ATTR_VALUE @from is empty +// L9 ERR_BAD_ATTR_VALUE a lifecycle field is an array (@isArray: true) +// L10 ERR_LIFECYCLE_REDECLARED an entity redeclares an inherited lifecycle field without +// extending it, so the base's transitions would be lost +// P1 ERR_PERMISSION_PUBLIC_CONFLICT @public: true with @permission (operation or transition) +// P2 ERR_BAD_ATTR_VALUE @permission is not a dotted identifier path (PERMISSION_NAME_PATTERN) +// O0 ERR_TRANSITION_NAME_COLLISION an operation named create/get/list/update/delete, in any case +// O6 ERR_TRANSITION_NAME_COLLISION two operations of one package share a name, compared without case, in +// one API or across its APIs; one operation declared twice merges, and +// the same operation declared identically in two APIs is exposed twice (SameOperation) +// O1 ERR_OPERATION_SHAPE @inputRef is not an object.value; @outputRef is not an entity, projection or value +// O2 ERR_OPERATION_TARGET_UNRESOLVED @objectRef is not an object.entity, or a command lists +// @transitions and no target is declared or derivable +// O3 ERR_OPERATION_TARGET_MISMATCH a declared @objectRef disagrees with the derived target +// O4 ERR_OPERATION_UNKNOWN_TRANSITION a @transitions name is not a transition of the target +// O5 ERR_BAD_ATTR_VALUE an @errors code is not lower snake case, is listed twice, or is +// one the route answers itself (RESERVED_ERROR_CODES) +// B1 ERR_BINDING_PATH_MISMATCH a binding.rest @path's placeholders are not the target's key fields +// (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 + +using System.Text.RegularExpressions; +using MetaObjects.Core.Transition; +using MetaObjects.Meta; + +namespace MetaObjects.Loader; + +public static partial class ValidationPasses +{ + private static readonly string ReservedOperationNameList = string.Join(", ", RESERVED_OPERATION_NAMES); + + private static readonly Regex BindingPlaceholder = new(@"\{([^}]*)\}", RegexOptions.CultureInvariant); + + /// "Entity.field.transition" for a transition, "Api.operation" for an operation. + private static string RulesLabel(MetaData node) + { + var parts = new List(); + // A binding is unnamed: its label is its operation's. + for (MetaData? n = node; n is not null && n.Parent is not null; n = n.Parent) + { + if (n.Name != "") parts.Insert(0, n.Name); + } + return string.Join(".", parts); + } + + private static readonly HashSet ReservedErrorCodes = new(RESERVED_ERROR_CODES, StringComparer.Ordinal); + + /// A derived name is compared without case: a command, a permission constant or a file named + /// from it collides with another that differs only in case on a case-folding target. + private static bool IsReservedName(string name) => + RESERVED_OPERATION_NAMES.Contains(name.ToLowerInvariant()); + + private static string RulesQuoteList(IEnumerable xs) => string.Join(", ", xs.Select(x => $"\"{x}\"")); + + private sealed class RulesErrorSink + { + public readonly List Errors = []; + private readonly Dictionary> _seen = new(ReferenceEqualityComparer.Instance); + + public void Add(MetaData node, ErrorCode code, string message) + { + if (!_seen.TryGetValue(node, out var codes)) _seen[node] = codes = []; + if (!codes.Add(code)) return; + Errors.Add(new MetaError(message, code, Envelope: node.Source)); + } + } + + /// P1 and P2 for an operation or a transition. + private static void CheckPermission(MetaData node, RulesErrorSink sink) + { + var permission = node.Attr(OPERATION_ATTR_PERMISSION); + if (node.Attr(OPERATION_ATTR_PUBLIC) is true && permission is not null) + { + sink.Add(node, ErrorCode.ERR_PERMISSION_PUBLIC_CONFLICT, + $"{node.Type}.{node.SubType} \"{RulesLabel(node)}\" declares both @public: true and @permission; a public {node.Type} calls no permission check, so remove one."); + } + if (permission is string name && !PERMISSION_NAME_PATTERN.IsMatch(name)) + { + sink.Add(node, ErrorCode.ERR_BAD_ATTR_VALUE, + $"{node.Type}.{node.SubType} \"{RulesLabel(node)}\" @permission \"{name}\" is not a dotted identifier path; use names of letters, digits and _ joined by \".\" (a package prefix may use \"::\"), such as \"purchasing.approve\"."); + } + } + + /// L1, L3, L4, L5, L7 and P1 for the transitions declared on one field. + private static void CheckDeclaredTransitions(MetaData field, RulesErrorSink sink) + { + // ADR-0039: own — each transition is checked where it is declared. + var declared = field.OwnChildren().Where(c => c.Type == TYPE_TRANSITION && c.SubType == TRANSITION_SUBTYPE_ACTION).ToList(); + if (declared.Count == 0) return; + var owner = field.Parent; + if (owner is null || owner.Type != TYPE_OBJECT || owner.SubType != OBJECT_SUBTYPE_ENTITY) + { + var where = owner is null || owner.Type != TYPE_OBJECT ? "the document root" : $"object.{owner.SubType} \"{owner.Name}\""; + foreach (var t in declared) + { + sink.Add(t, ErrorCode.ERR_TRANSITION_NOT_ON_ENTITY, + $"transition.action \"{RulesLabel(t)}\" is declared on a field of {where}; a lifecycle belongs to an object.entity with a writable source."); + } + return; + } + if (field.SubType == FIELD_SUBTYPE_ENUM && field.Attr(FIELD_ATTR_DEFAULT) is not string) + { + sink.Add(field, ErrorCode.ERR_LIFECYCLE_NO_INITIAL, + $"field.enum \"{RulesLabel(field)}\" declares transitions but no @default; its @default is the lifecycle's initial state."); + } + if (field.ResolvedIsArray()) + { + sink.Add(field, ErrorCode.ERR_BAD_ATTR_VALUE, + $"field.{field.SubType} \"{RulesLabel(field)}\" declares transitions but is an array (@isArray: true); a lifecycle's state is one value."); + } + var stateList = Lifecycles.StringList(field, FIELD_ATTR_VALUES).Distinct(StringComparer.Ordinal).ToList(); + var states = stateList.ToHashSet(StringComparer.Ordinal); + foreach (var t in declared) + { + CheckPermission(t, sink); + if (Lifecycles.TransitionFrom(t).Count == 0) + { + sink.Add(t, ErrorCode.ERR_BAD_ATTR_VALUE, + $"transition.action \"{RulesLabel(t)}\" @from is empty; name at least one state the transition leaves."); + } + var to = Lifecycles.TransitionTo(t); + var unknown = Lifecycles.TransitionFrom(t).Concat(to is null ? [] : [to]) + .Distinct(StringComparer.Ordinal).Where(s => !states.Contains(s)).ToList(); + if (unknown.Count > 0) + { + sink.Add(t, ErrorCode.ERR_TRANSITION_UNKNOWN_STATE, + $"transition.action \"{RulesLabel(t)}\" names {RulesQuoteList(unknown)}, which {(unknown.Count == 1 ? "is not a member" : "are not members")} of \"{field.Name}\" @values ({RulesQuoteList(stateList)})."); + } + if (IsReservedName(t.Name)) + { + sink.Add(t, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + $"transition.action \"{RulesLabel(t)}\" is named \"{t.Name}\", which is a derived CRUD verb ({ReservedOperationNameList}); rename it."); + } + var condition = t.Attr(TRANSITION_ATTR_CONDITION); + if (condition is not null && owner is MetaObject ownerObject) + { + var message = ConditionMessage(condition, ownerObject, $"transition.action \"{RulesLabel(t)}\" @condition"); + if (message is not null) sink.Add(t, ErrorCode.ERR_BAD_ATTR_VALUE, message); + } + } + } + + /// Every field declared in the tree: at the root and on every object. + private static List RulesDeclaredFields(MetaData root) + { + var output = new List(); + // ADR-0039: own — a structural walk over the declarations themselves. + foreach (var top in root.OwnChildren()) + { + if (top.Type == TYPE_FIELD) output.Add(top); + else if (top.Type == TYPE_OBJECT) output.AddRange(top.OwnChildren().Where(c => c.Type == TYPE_FIELD)); + } + return output; + } + + /// L10: an entity's field named like an ancestor's lifecycle field that does not carry that + /// lifecycle's transitions. Redeclaring the field replaces it, so the base's state machine would + /// silently stop applying to this entity. + private static void CheckRedeclaredLifecycles(MetaData entity, RulesErrorSink sink) + { + foreach (var ancestor in Lifecycles.EntityLineage(entity).Skip(1)) + { + // ADR-0039: own — the lifecycle fields the ancestor itself declares. + foreach (var baseField in ancestor.OwnChildren()) + { + if (baseField.Type != TYPE_FIELD) continue; + var baseTransitions = Lifecycles.LifecycleTransitionsOf(ancestor, baseField); + if (baseTransitions.Count == 0) continue; + var field = entity.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == baseField.Name); + if (field is null || ReferenceEquals(field, baseField)) continue; + var kept = Lifecycles.LifecycleTransitionsOf(entity, field).ToHashSet(ReferenceEqualityComparer.Instance); + if (baseTransitions.All(kept.Contains)) continue; + sink.Add(field, ErrorCode.ERR_LIFECYCLE_REDECLARED, + $"field.{field.SubType} \"{RulesLabel(field)}\" redeclares \"{RulesLabel(baseField)}\", which has a lifecycle, and drops its transitions; extend it (\"extends\": \"{ancestor.Name}.{baseField.Name}\") or give the field another name."); + } + } + } + + /// L2, L6 and L10 for one entity, over its effective (inherited) lifecycles. + private static void CheckEntityLifecycles(MetaData entity, RulesErrorSink sink) + { + CheckRedeclaredLifecycles(entity, sink); + var transitions = Lifecycles.EntityTransitions(entity); + if (transitions.Count == 0) return; + var byName = new Dictionary(StringComparer.Ordinal); + foreach (var t in transitions) + { + var key = t.Name.ToLowerInvariant(); + if (!byName.TryGetValue(key, out var first)) + { + byName[key] = t; + } + else if (!ReferenceEquals(first, t)) + { + sink.Add(t, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + $"transition.action \"{RulesLabel(t)}\" has the same name as \"{RulesLabel(first)}\" (names are compared without case); the transitions of \"{entity.Name}\" share one namespace (each may derive a command), so rename one."); + } + } + if (!entity.IsAbstract && Lifecycles.LifecycleIsLive(entity) && + !entity.Children().Any(c => c is MetaSource ms && ms.IsWritable())) + { + sink.Add(entity, ErrorCode.ERR_TRANSITION_NOT_ON_ENTITY, + $"object.entity \"{entity.Name}\" has a lifecycle (transitions on {RulesQuoteList(transitions.Select(t => t.Parent?.Name ?? "").Distinct(StringComparer.Ordinal))}) 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.)"); + } + } + + /// O0-O5, P1 and B1 for one operation. + private static void CheckOperation(MetaData op, RulesErrorSink sink) + { + if (IsReservedName(op.Name)) + { + sink.Add(op, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + $"operation.{op.SubType} \"{RulesLabel(op)}\" is named \"{op.Name}\", which is a derived CRUD verb ({ReservedOperationNameList}); rename it."); + } + CheckPermission(op, sink); + + var errorCodes = Lifecycles.StringList(op, OPERATION_ATTR_ERRORS); + var bad = errorCodes.Where(c => !BUSINESS_ERROR_CODE_PATTERN.IsMatch(c)).ToList(); + var dup = errorCodes.Where((c, i) => errorCodes.ToList().IndexOf(c) != i).ToList(); + var reserved = errorCodes.Where(ReservedErrorCodes.Contains).Distinct(StringComparer.Ordinal).ToList(); + if (bad.Count > 0 || dup.Count > 0 || reserved.Count > 0) + { + var dupSet = dup.Distinct(StringComparer.Ordinal).ToList(); + var why = bad.Count > 0 + ? $"{RulesQuoteList(bad)} {(bad.Count == 1 ? "is not a" : "are not")} lower snake case code{(bad.Count == 1 ? "" : "s")}" + : dup.Count > 0 + ? $"{RulesQuoteList(dupSet)} {(dupSet.Count == 1 ? "is" : "are")} listed twice" + : $"{RulesQuoteList(reserved)} {(reserved.Count == 1 ? "is a code" : "are codes")} the route answers itself ({string.Join(", ", RESERVED_ERROR_CODES)})"; + sink.Add(op, ErrorCode.ERR_BAD_ATTR_VALUE, $"operation.{op.SubType} \"{RulesLabel(op)}\" @errors: {why}."); + } + + // O1 — shapes. + if (op.Attr(OPERATION_ATTR_INPUT_REF) is string inputRef) + { + var input = Lifecycles.ResolveObjectOn(op, inputRef); + if (input is null || input.SubType != OBJECT_SUBTYPE_VALUE) + { + sink.Add(op, ErrorCode.ERR_OPERATION_SHAPE, + $"operation.{op.SubType} \"{RulesLabel(op)}\" @inputRef \"{inputRef}\" {(input is null ? "names no object" : $"is an object.{input.SubType}")}; an operation's input is an object.value."); + return; + } + } + if (op.Attr(OPERATION_ATTR_OUTPUT_REF) is string outputRef) + { + var output = Lifecycles.ResolveObjectOn(op, outputRef); + var legal = output is not null && + (output.SubType == OBJECT_SUBTYPE_ENTITY || output.SubType == OBJECT_SUBTYPE_PROJECTION || output.SubType == OBJECT_SUBTYPE_VALUE); + if (!legal) + { + sink.Add(op, ErrorCode.ERR_OPERATION_SHAPE, + $"operation.{op.SubType} \"{RulesLabel(op)}\" @outputRef \"{outputRef}\" {(output is null ? "names no object" : $"is an object.{output.SubType}")}; an operation returns an object.entity, object.projection or object.value."); + return; + } + } + + // O2, O3 — the target. + var derived = Lifecycles.DeriveOperationTarget(op)?.Entity; + var target = derived; + if (op.Attr(OPERATION_ATTR_OBJECT_REF) is string objectRef) + { + var declared = Lifecycles.ResolveObjectOn(op, objectRef); + if (declared is null || declared.SubType != OBJECT_SUBTYPE_ENTITY) + { + sink.Add(op, ErrorCode.ERR_OPERATION_TARGET_UNRESOLVED, + $"operation.{op.SubType} \"{RulesLabel(op)}\" @objectRef \"{objectRef}\" {(declared is null ? "names no object" : $"is an object.{declared.SubType}")}; an operation acts on an object.entity."); + return; + } + if (derived is not null && !ReferenceEquals(derived, declared)) + { + sink.Add(op, ErrorCode.ERR_OPERATION_TARGET_MISMATCH, + $"operation.{op.SubType} \"{RulesLabel(op)}\" @objectRef names \"{declared.Name}\", but its input and output derive \"{derived.Name}\"; remove @objectRef or make them agree."); + return; + } + target = declared; + } + var transitions = op.SubType == OPERATION_SUBTYPE_COMMAND ? Lifecycles.StringList(op, OPERATION_ATTR_TRANSITIONS) : []; + if (transitions.Count > 0 && target is null) + { + sink.Add(op, ErrorCode.ERR_OPERATION_TARGET_UNRESOLVED, + $"operation.command \"{RulesLabel(op)}\" lists @transitions but has no target entity: the @inputRef does not borrow one entity's whole primary key (each key field extended exactly once), no @outputRef has a base entity, and there is no @objectRef."); + return; + } + + // O4 — the transitions it may make. + if (target is not null && transitions.Count > 0) + { + var known = Lifecycles.EntityTransitions(target).Select(t => t.Name).ToHashSet(StringComparer.Ordinal); + var unknown = transitions.Distinct(StringComparer.Ordinal).Where(n => !known.Contains(n)).ToList(); + if (unknown.Count > 0) + { + sink.Add(op, ErrorCode.ERR_OPERATION_UNKNOWN_TRANSITION, + $"operation.command \"{RulesLabel(op)}\" @transitions names {RulesQuoteList(unknown)}, which {(unknown.Count == 1 ? "is not a transition" : "are not transitions")} of \"{target.Name}\"."); + } + } + + // B1 — binding paths. + // ADR-0039: own — a binding is checked on the operation that declares it. + foreach (var b in op.OwnChildren()) + { + if (b.Type != TYPE_BINDING || b.SubType != BINDING_SUBTYPE_REST) continue; + if (b.Attr(BINDING_ATTR_PATH) is not string path) continue; + var placeholders = BindingPlaceholder.Matches(path).Select(m => m.Groups[1].Value).ToList(); + IReadOnlyList expected = target is not null && Lifecycles.OperationIsKeyed(op) ? Lifecycles.PrimaryKeyFields(target) : []; + var sortedPlaceholders = placeholders.Order(StringComparer.Ordinal).ToList(); + var sortedExpected = expected.Order(StringComparer.Ordinal).ToList(); + var same = sortedPlaceholders.Count == sortedExpected.Count && sortedPlaceholders.SequenceEqual(sortedExpected); + if (!same) + { + sink.Add(b, ErrorCode.ERR_BINDING_PATH_MISMATCH, + $"binding.rest on \"{RulesLabel(b)}\" @path \"{path}\" has placeholders [{RulesQuoteList(placeholders)}]; " + + (expected.Count == 0 + ? $"\"{RulesLabel(op)}\" addresses no row by key, so its path takes none." + : $"\"{RulesLabel(op)}\" addresses one \"{target!.Name}\" by key, so its path takes exactly [{RulesQuoteList(expected)}].")); + } + } + } + + /// ADR-0066 — the rules pass. Runs after reference-bearing validation, before freeze. + public static IReadOnlyList ValidateRules(MetaData root) + { + var sink = new RulesErrorSink(); + foreach (var field in RulesDeclaredFields(root)) CheckDeclaredTransitions(field, sink); + foreach (var obj in root.Children()) + { + if (obj.Type == TYPE_OBJECT && obj.SubType == OBJECT_SUBTYPE_ENTITY) CheckEntityLifecycles(obj, sink); + } + // O6 — keyed by package, then by the name without case. + var byName = new Dictionary(StringComparer.Ordinal); + foreach (var api in root.Children()) + { + if (api.Type != TYPE_API) continue; + var ops = api.Children().Where(c => c.Type == TYPE_OPERATION).ToList(); + foreach (var op in ops) CheckOperation(op, sink); + foreach (var op in ops) + { + var pkg = NamingRefs.EffectivePackageOf(api); + var key = $"{pkg}\0{op.Name.ToLowerInvariant()}"; + if (!byName.TryGetValue(key, out var first)) byName[key] = op; + else if (!ReferenceEquals(first, op) && !SameOperation(first, op)) + { + sink.Add(op, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + $"operation.{op.SubType} \"{RulesLabel(op)}\" has the same name as \"{RulesLabel(first)}\" (names are compared without case) and is not the same operation; the operations of package \"{pkg}\" share one namespace (each derives the permission name .), so rename one, or declare both identically to expose one operation in two APIs."); + } + } + CheckApiRoutes(ops, sink); + } + return sink.Errors; + } + + /// A reference attr's identity: the node it resolves to, else the raw value. + private static object? RefIdentity(MetaData op, string attr) => + op.Attr(attr) is string r ? (object?)Lifecycles.ResolveObjectOn(op, r) ?? r : op.Attr(attr); + + private static string SetKey(MetaData op, string attr) => + string.Join("\0", Lifecycles.StringList(op, attr).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)); + + /// Whether two operations of one package in different APIs are one operation exposed twice + /// (a versioned API beside its successor, ADR-0067 section 2): same name and subtype, same contract. + /// Bindings are per API and are not compared. + private static bool SameOperation(MetaData a, MetaData b) + { + if (a.Name != b.Name || a.SubType != b.SubType) return false; + foreach (var attr in new[] { OPERATION_ATTR_INPUT_REF, OPERATION_ATTR_OUTPUT_REF, OPERATION_ATTR_OBJECT_REF }) + { + if (!Equals(RefIdentity(a, attr), RefIdentity(b, attr))) return false; + } + foreach (var attr in new[] { OPERATION_ATTR_TRANSITIONS, OPERATION_ATTR_ERRORS }) + { + if (SetKey(a, attr) != SetKey(b, attr)) return false; + } + return Equals(a.Attr(OPERATION_ATTR_PERMISSION), b.Attr(OPERATION_ATTR_PERMISSION)) + && (a.Attr(OPERATION_ATTR_PUBLIC) is true) == (b.Attr(OPERATION_ATTR_PUBLIC) is true) + && (a.Attr(OPERATION_ATTR_MANY) is true) == (b.Attr(OPERATION_ATTR_MANY) is true); + } + + /// B2 across the operations of one API. + private static void CheckApiRoutes(IReadOnlyList ops, RulesErrorSink sink) + { + var byRoute = new Dictionary(StringComparer.Ordinal); + foreach (var op in ops) + { + // ADR-0039: own — a binding is checked on the operation that declares it. + foreach (var b in op.OwnChildren()) + { + if (b.Type != TYPE_BINDING || b.SubType != BINDING_SUBTYPE_REST) continue; + if (b.Attr(BINDING_ATTR_PATH) is not string path) continue; + // The effective method: the declared one, else the derived (ADR-0066 section 1). + var method = b.Attr(BINDING_ATTR_METHOD) is string declaredMethod + ? declaredMethod + : op.SubType == OPERATION_SUBTYPE_COMMAND ? "POST" : "GET"; + var route = $"{method} {BindingPlaceholder.Replace(path, "{}")}"; + if (!byRoute.TryGetValue(route, out var other)) byRoute[route] = b; + else + { + sink.Add(b, ErrorCode.ERR_BINDING_PATH_MISMATCH, + $"binding.rest on \"{RulesLabel(b)}\" declares {method} \"{path}\", the same route as the binding on \"{RulesLabel(other)}\"; two operations cannot share a method and path."); + } + } + } + } +} diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 53d6562753..ee4ca7dc7f 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -2862,7 +2862,6 @@ public static IReadOnlyList ValidateCrossFieldValidators(MetaData roo var errors = new List(); foreach (var obj in root.Children().OfType()) { - var fieldNames = obj.Fields().Select(f => f.Name).ToHashSet(StringComparer.Ordinal); foreach (var v in obj.OwnChildren().Where(c => c.Type == TYPE_VALIDATOR && CrossFieldValidatorSubtypes.Contains(c.SubType))) { // validator.atLeastOne takes no @max: "exactly one of these fields" is @@ -2915,28 +2914,37 @@ public static IReadOnlyList ValidateCrossFieldValidators(MetaData roo } var condition = v.Attr(VALIDATOR_ATTR_CONDITION); if (condition is null) continue; - var label = $"validator.{v.SubType} \"{obj.Name}.{v.Name}\" @condition"; - var unknown = MetaObjects.Core.Attr.ExpressionGrammar.FieldRefs(condition) - .Distinct(StringComparer.Ordinal).Where(f => !fieldNames.Contains(f)) - .OrderBy(f => f, StringComparer.Ordinal).ToList(); - if (unknown.Count > 0) + var message = ConditionMessage(condition, obj, $"validator.{v.SubType} \"{obj.Name}.{v.Name}\" @condition"); + if (message is not null) { - errors.Add(new MetaError( - $"{label} names {string.Join(", ", unknown.Select(f => $"\"{f}\""))}, " + - $"which {(unknown.Count == 1 ? "is not a field" : "are not fields")} of \"{obj.Name}\".", - ErrorCode.ERR_BAD_ATTR_VALUE, - Envelope: v.Source)); - continue; - } - if (ConditionProblem(condition, obj) is { } problem) - { - errors.Add(new MetaError($"{label} {problem}", ErrorCode.ERR_BAD_ATTR_VALUE, Envelope: v.Source)); + errors.Add(new MetaError(message, ErrorCode.ERR_BAD_ATTR_VALUE, Envelope: v.Source)); } } } return errors; } + /// + /// Why a @condition (the attr.expression grammar) over 's own fields is + /// refused, or null when it is legal. opens the message. One rule for a + /// cross-field validator's condition and a transition's guard (ADR-0066): every named field is a + /// field of , and the expression passes . + /// Mirrors TS conditionMessage. + /// + public static string? ConditionMessage(object condition, MetaObject obj, string label) + { + var fieldNames = obj.Fields().Select(f => f.Name).ToHashSet(StringComparer.Ordinal); + var unknown = MetaObjects.Core.Attr.ExpressionGrammar.FieldRefs(condition) + .Distinct(StringComparer.Ordinal).Where(f => !fieldNames.Contains(f)) + .OrderBy(f => f, StringComparer.Ordinal).ToList(); + if (unknown.Count > 0) + { + return $"{label} names {string.Join(", ", unknown.Select(f => $"\"{f}\""))}, " + + $"which {(unknown.Count == 1 ? "is not a field" : "are not fields")} of \"{obj.Name}\"."; + } + return ConditionProblem(condition, obj) is { } problem ? $"{label} {problem}" : null; + } + /// The accepted ISO-8601 duration form, the same pattern as TS DURATION_PATTERN. private static readonly Regex DurationLiteral = new(@"^[-+]?P(?!\z)([0-9]+W)?([0-9]+D)?(T(?=[0-9])([0-9]+H)?([0-9]+M)?([0-9]+(\.[0-9]+)?S)?)?\z", RegexOptions.CultureInvariant); diff --git a/server/csharp/MetaObjects/Meta/MetaApi.cs b/server/csharp/MetaObjects/Meta/MetaApi.cs new file mode 100644 index 0000000000..f1552242e7 --- /dev/null +++ b/server/csharp/MetaObjects/Meta/MetaApi.cs @@ -0,0 +1,21 @@ +// Concrete node classes for the declared API surface (ADR-0030, ADR-0066): api.*, +// operation.* and binding.*. One class per type; the subtype carries no behaviour. +// +// Mirrors server/typescript/packages/metadata/src/core/api/meta-api.ts. + +namespace MetaObjects.Meta; + +/// Concrete node class for api.* nodes. +public class MetaApi(TypeId typeId, string name) : MetaData(typeId, name) +{ +} + +/// Concrete node class for operation.* nodes. +public class MetaOperation(TypeId typeId, string name) : MetaData(typeId, name) +{ +} + +/// Concrete node class for binding.* nodes. +public class MetaBinding(TypeId typeId, string name) : MetaData(typeId, name) +{ +} diff --git a/server/csharp/MetaObjects/Meta/MetaTransition.cs b/server/csharp/MetaObjects/Meta/MetaTransition.cs new file mode 100644 index 0000000000..8969f91fd7 --- /dev/null +++ b/server/csharp/MetaObjects/Meta/MetaTransition.cs @@ -0,0 +1,9 @@ +// Concrete node class for transition.* nodes (ADR-0066). Mirrors +// server/typescript/packages/metadata/src/core/transition/meta-transition.ts. + +namespace MetaObjects.Meta; + +/// Concrete node class for transition.* nodes. +public class MetaTransition(TypeId typeId, string name) : MetaData(typeId, name) +{ +} diff --git a/server/csharp/MetaObjects/NamingRefs.cs b/server/csharp/MetaObjects/NamingRefs.cs index 12d6da14fc..e47ace4e2d 100644 --- a/server/csharp/MetaObjects/NamingRefs.cs +++ b/server/csharp/MetaObjects/NamingRefs.cs @@ -35,7 +35,7 @@ public static class NamingRefs /// /// The inline attribute names whose VALUE is a metadata object reference (ADR-0059 R4). - /// The structural extends key is handled separately. @sourceRefField (a FK + /// The structural extends key is handled separately. An operation's @inputRef/@outputRef/@objectRef are in it (ADR-0066). @sourceRefField (a FK /// field name) and @implementedBy (which may name a member) are NOT in the set. /// public static readonly IReadOnlySet RefBearingAttrNames = new HashSet(StringComparer.Ordinal) @@ -46,8 +46,18 @@ public static class NamingRefs ORIGIN_AGGREGATE_ATTR_OF, ORIGIN_AGGREGATE_ATTR_VIA, SOURCE_ATTR_PARAMETER_REF, TEMPLATE_ATTR_PAYLOAD_REF, TEMPLATE_ATTR_RESPONSE_REF, OBJECT_REPORT_ATTR_FROM, OBJECT_REPORT_ATTR_SPINE, + OPERATION_ATTR_INPUT_REF, OPERATION_ATTR_OUTPUT_REF, }; + /// + /// True when on holds an object reference: in + /// , and not on a transition.*, whose @from names + /// members of its enum (ADR-0066). The set is keyed by NAME, so a node type that reuses one of + /// these names for something else is excluded here. + /// + public static bool IsRefBearingAttr(MetaData node, string attrName) => + RefBearingAttrNames.Contains(attrName) && node.Type != TYPE_TRANSITION; + /// /// Split a ref into its owner part and any FR-024 dotted child tail. The . that marks /// a child can only appear in the FINAL ::-segment, so the owner ends at the first diff --git a/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs b/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs index a0ad5b50c9..975ab06c7c 100644 --- a/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs +++ b/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs @@ -1,6 +1,6 @@ // FR-033 — the C# reader for the shared spec/metamodel/*.json provider files. // -// The 19 JSON files (one per concern provider) are the cross-port single source of +// The 21 JSON files (one per concern provider) are the cross-port single source of // truth for every type / attr / common-attr DESCRIPTION (+ optional rules/example/ // whenToUse). They are byte-identical across the ports by design, so each port READS // them rather than hand-copying the prose — the exact duplication FR-033 kills. @@ -115,13 +115,13 @@ public sealed record SpecExtendsDirective( /// public sealed class SpecMetamodelReader { - /// The 19 shared provider-definition file names (keep in lockstep with spec/metamodel/). + /// The 21 shared provider-definition file names (keep in lockstep with spec/metamodel/). public static readonly IReadOnlyList SpecFiles = new[] { - "attr.json", "db.json", "documentation.json", "field.json", "identity.json", + "api.json", "attr.json", "db.json", "documentation.json", "field.json", "identity.json", "index.json", "layout.json", "object.json", "origin.json", "prompt.json", "relationship.json", "reporting.json", "requirement.json", "source.json", "template.json", - "ui.json", "ui-web.json", "validator.json", "view.json", + "transition.json", "ui.json", "ui-web.json", "validator.json", "view.json", }; /// The embedded-resource logical-name prefix (RootNamespace + folder). @@ -173,7 +173,7 @@ private SpecMetamodelReader() { } // ------------------------------------------------------------------ /// - /// Load + parse the 19 embedded spec/metamodel/*.json files off this + /// Load + parse the 21 embedded spec/metamodel/*.json files off this /// assembly's manifest resources (AOT-safe). /// /// If a spec file is missing or unparseable. diff --git a/server/csharp/MetaObjects/Shared/BaseTypes.cs b/server/csharp/MetaObjects/Shared/BaseTypes.cs index d457d8d355..92bdb62418 100644 --- a/server/csharp/MetaObjects/Shared/BaseTypes.cs +++ b/server/csharp/MetaObjects/Shared/BaseTypes.cs @@ -46,6 +46,15 @@ public static class BaseTypes public const string TYPE_DIMENSION = "dimension"; public const string TYPE_MEASURE = "measure"; public const string TYPE_SEGMENT = "segment"; + /// + /// ADR-0030 / ADR-0066 — the declared API surface: api.operational holds + /// operation.command / operation.query, each optionally carrying a binding.rest. + /// + public const string TYPE_API = "api"; + public const string TYPE_OPERATION = "operation"; + public const string TYPE_BINDING = "binding"; + /// ADR-0066 — an allowed move between two members of a field.enum (transition.action). + public const string TYPE_TRANSITION = "transition"; public static readonly string[] BASE_TYPES = [ @@ -66,6 +75,10 @@ public static class BaseTypes TYPE_DIMENSION, TYPE_MEASURE, TYPE_SEGMENT, + TYPE_API, + TYPE_OPERATION, + TYPE_BINDING, + TYPE_TRANSITION, ]; // ----------------------------------------------------------------------- diff --git a/server/csharp/MetaObjects/SpecMetamodel/api.json b/server/csharp/MetaObjects/SpecMetamodel/api.json new file mode 100644 index 0000000000..0f30e16e08 --- /dev/null +++ b/server/csharp/MetaObjects/SpecMetamodel/api.json @@ -0,0 +1,73 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "api", + "subType": "base", + "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.", + "children": [] + }, + { + "type": "api", + "subType": "operational", + "extendsBase": true, + "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).", + "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": "base", + "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "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": "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", "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." } + ] + }, + { + "type": "operation", + "subType": "query", + "extendsBase": true, + "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": "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": "binding", + "subType": "base", + "description": "Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable.", + "children": [] + }, + { + "type": "binding", + "subType": "rest", + "extendsBase": true, + "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).", + "whenToUse": "An operation must keep a method or path the derived one would not give it, such as an existing public URL.", + "children": [ + { "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)." } + ] + } + ] +} diff --git a/server/csharp/MetaObjects/SpecMetamodel/field.json b/server/csharp/MetaObjects/SpecMetamodel/field.json index 46a2f064ce..8d4c5a2185 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/field.json +++ b/server/csharp/MetaObjects/SpecMetamodel/field.json @@ -149,6 +149,7 @@ "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ + { "type": "transition", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Lifecycle moves between this enum's members (ADR-0066). An enum with at least one transition.action is a lifecycle: its states are @values, its initial state @default, its terminal states the members no transition leaves." }, { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer. Justified in ADR-0023 Amendment 1." }, diff --git a/server/csharp/MetaObjects/SpecMetamodel/transition.json b/server/csharp/MetaObjects/SpecMetamodel/transition.json new file mode 100644 index 0000000000..cbac9d3ef7 --- /dev/null +++ b/server/csharp/MetaObjects/SpecMetamodel/transition.json @@ -0,0 +1,27 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "transition", + "subType": "base", + "description": "Registry anchor for the attributes every lifecycle move shares (ADR-0054): not authorable.", + "children": [ + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name `..`, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED)." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." } + ] + }, + { + "type": "transition", + "subType": "action", + "extendsBase": true, + "description": "An allowed move between two values of a `field.enum`, made by an operation (ADR-0066). A `field.enum` with at least one is a lifecycle, named after the field. Its states are the enum's @values, its initial state the enum's @default, its terminal states the members no transition leaves; none of them has vocabulary of its own. Each transition is held to become a guarded update (`... WHERE id = ? AND IN (@from) [AND @condition]`), its own command when no declared operation claims it, its own permission point and its own wire error. No shell is generated yet: nothing is generated from this vocabulary, and the loader and `verify` only check it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A status field whose values may only change in certain ways: a request is submitted from draft, approved or rejected from submitted. Declare each allowed move here; once a shell is generated, the generic update path will no longer write the field. A move that leaves the state where it was (from submitted to submitted) records an action that changes nothing but still happened, such as a first approval of two.", + "rules": "Legal only under a `field.enum` of an `object.entity` (ERR_TRANSITION_NOT_ON_ENTITY). A concrete entity with a lifecycle and a source needs a writable one (ERR_TRANSITION_NOT_ON_ENTITY); on an entity with no source the lifecycle loads and is inert, deriving no command until a source is added. The field must declare @default (ERR_LIFECYCLE_NO_INITIAL). The field is not an array, and @from names at least one state (ERR_BAD_ATTR_VALUE). Names are unique across every lifecycle of the entity, compared without case, and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). A transition belongs to the entity that declares its field and to every entity extending it, never to an entity whose field merely `extends` that field; an inheritor that redeclares the field without extending it is ERR_LIFECYCLE_REDECLARED.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "isArray": true, "min": 1, "max": 1, "description": "The states this move may start from: members of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise), at least one (ERR_BAD_ATTR_VALUE when empty). The allowed moves are the business rule itself, so they cannot be computed." }, + { "type": "attr", "subType": "string", "name": "to", "min": 1, "max": 1, "description": "The state this move ends in: one member of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise). May equal a member of @from, which records an action that leaves the state where it was." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "A guard over the entity's own fields, in the attr.expression grammar: the same name, grammar and meaning as on the cross-field validators. The shell will evaluate it against the loaded row and also put it into the guarded update's WHERE (no shell is generated yet). It cannot read the actor; that is the policy's job. A field the entity does not have, or an expression that is not boolean, is ERR_BAD_ATTR_VALUE." } + ] + } + ] +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt new file mode 100644 index 0000000000..ac8261bd70 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt @@ -0,0 +1,158 @@ +package com.metaobjects.generator.kotlin + +import com.metaobjects.generator.kotlin.apidocs.DocsPaths +import com.metaobjects.generator.kotlin.apidocs.KotlinApiDocsRenderer +import com.metaobjects.generator.kotlin.apidocs.KotlinApiModelBuilder +import com.metaobjects.generator.util.GeneratedFileWriter +import com.metaobjects.MetaData +import com.metaobjects.metadata.ktx.loadDirectory +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths +import java.util.TreeMap +import kotlin.io.path.isRegularFile +import kotlin.io.path.readText +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * ADR-0066 - the business-rules vocabulary is INERT in the Kotlin generators. + * + * `api.operational`, `operation.*`, `binding.rest` and `transition.action` are registered, + * validated at load and checked in `verify`; nothing generates from them yet. A model that + * uses them emits exactly what the same model without them emits, byte for byte, through every + * generator in [GENERATOR_REGISTRY] and every page of the api reference. + * + * The model pair is `fixtures/codegen-noop/rules/{with,without}`, shared with the other ports. + */ +class RulesInertTest { + + private fun modelDir(variant: String): Path { + var cur: Path? = Paths.get("").toAbsolutePath() + while (cur != null) { + val candidate = cur.resolve("fixtures/codegen-noop/rules/$variant") + if (Files.isDirectory(candidate)) return candidate + cur = cur.parent + } + throw IllegalStateException("Could not locate fixtures/codegen-noop/rules from ${Paths.get("").toAbsolutePath()}") + } + + // One loader name for both variants, so nothing that stamps it into output can differ. + private fun load(variant: String) = loadDirectory("rules-inert", modelDir(variant)) + + /** + * Run a generator suite into a fresh directory and read back every file it wrote: + * relative path to contents. A throw is recorded as the single entry ``, so a + * generator that cannot run from a bare model must at least fail identically. + */ + private fun emit(variant: String, suite: List): Map { + val loader = load(variant) + val outDir = Files.createTempDirectory("rules-inert-") + val templateRoot = Files.createTempDirectory("rules-inert-templates-") + try { + try { + GeneratedFileWriter.beginRun().use { run -> + for (info in suite) { + val gen = info.factory() + run.attributeTo(info.name) + gen.setArgs(mapOf( + "outputDir" to outDir.toString(), + // KotlinValidatorGenerator emits a package-level stub and needs one. + "packageName" to "acme.shop", + "templateRoot" to templateRoot.toString(), + )) + gen.execute(loader) + } + } + } catch (e: Exception) { + return mapOf(THREW to e.message.toString()) + } + val files = TreeMap() + Files.walk(outDir).use { s -> + s.filter { it.isRegularFile() }.forEach { files[outDir.relativize(it).toString()] = it.readText() } + } + return files + } finally { + outDir.toFile().deleteRecursively() + templateRoot.toFile().deleteRecursively() + } + } + + private fun sameOrLeak(label: String, expected: Map, actual: Map): String? { + if (expected.keys.toList() != actual.keys.toList()) { + return "$label: emitted file set ${expected.keys} became ${actual.keys}" + } + val differing = expected.keys.filter { expected[it] != actual[it] } + return if (differing.isEmpty()) null else "$label: $differing differ once rules nodes are declared" + } + + // shared-model writes no code: it publishes the model's own metadata files, named by its args. + private val codeGenerators get() = GENERATOR_REGISTRY.values.filter { it.name != "api-docs" && it.name != "shared-model" } + + @Test + fun `the with-model really carries the vocabulary`() { + // Else every comparison below is vacuously green. + val root = load("with").root + assertEquals(1, root.getChildren(MetaData::class.java, true).count { it.type == "api" }) + val transitions = root.getChildren(MetaData::class.java, true).filter { it.type == "object" } + .flatMap { o -> o.getChildren(MetaData::class.java, true) } + .flatMap { f -> f.getChildren(MetaData::class.java, true) } + .count { it.type == "transition" } + assertEquals(3, transitions) + assertFalse(load("without").root.getChildren(MetaData::class.java, true).any { it.type == "api" }) + } + + @Test + fun `every generator emits the same files`() { + val leaks = codeGenerators.mapNotNull { info -> + sameOrLeak(info.name, emit("without", listOf(info)), emit("with", listOf(info))) + } + assertTrue(leaks.isEmpty(), leaks.joinToString("\n")) + } + + @Test + fun `every runnable generator in one run emits the same files`() { + val runnable = codeGenerators.filter { THREW !in emit("without", listOf(it)) } + val expected = emit("without", runnable) + assertFalse(THREW in expected, "the combined suite threw: ${expected[THREW]}") + assertTrue(expected.size > 10, "only ${expected.size} files - the suite barely ran") + val leak = sameOrLeak("combined", expected, emit("with", runnable)) + assertTrue(leak == null, leak) + } + + /** + * The api docs surface: every unit page, the index and the agent page, rendered for + * one variant of the with/without model pair. + */ + private fun apiDocs(variant: String): Map { + val out = Files.createTempDirectory("rules-inert-docs-") + try { + val docs = GENERATOR_REGISTRY.getValue("api-docs").factory() + docs.setArgs(mapOf("outputDir" to out.toString(), "projectName" to "purchasing", "layout" to "package")) + docs.execute(load(variant)) + val pages = TreeMap() + Files.walk(out).use { s -> + s.filter { it.isRegularFile() }.forEach { + pages[out.resolve("api/kotlin").relativize(it).toString()] = it.readText() + } + } + return pages + } finally { + out.toFile().deleteRecursively() + } + } + + @Test + fun `the api reference is identical`() { + val expected = apiDocs("without") + assertTrue(expected.size > 3, "only ${expected.size} pages - the docs barely ran") + val leak = sameOrLeak("api docs", expected, apiDocs("with")) + assertTrue(leak == null, leak) + } + + private companion object { + const val THREW = "" + } +} diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java new file mode 100644 index 0000000000..4747770ef7 --- /dev/null +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java @@ -0,0 +1,183 @@ +package com.metaobjects.generator.spring; + +import com.metaobjects.generator.direct.MultiFileDirectGeneratorBase; +import com.metaobjects.generator.Generator; +import com.metaobjects.generator.GeneratorRegistry; +import com.metaobjects.generator.GeneratorRegistry.GeneratorInfo; +import com.metaobjects.generator.apidocs.ApiUnit; +import com.metaobjects.generator.apidocs.DocsPaths; +import com.metaobjects.generator.apidocs.JavaApiDocsRenderer; +import com.metaobjects.generator.apidocs.JavaApiModel; +import com.metaobjects.generator.apidocs.JavaApiModelBuilder; +import com.metaobjects.generator.util.GeneratedFileWriter; +import com.metaobjects.MetaData; +import com.metaobjects.MetaRoot; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.registry.SharedRegistryTestBase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * ADR-0066 - the business-rules vocabulary is INERT in the Java generators. + * + *

{@code api.operational}, {@code operation.*}, {@code binding.rest} and + * {@code transition.action} are registered, validated at load and checked in {@code verify}, and + * nothing generates from them yet: a model that uses them emits exactly what the same model + * without them emits, byte for byte, through every generator in {@link GeneratorRegistry} and + * every page of the api reference. + * + *

The model pair is {@code fixtures/codegen-noop/rules/{with,without}}, shared with the + * other ports' copies of this test. + */ +public class RulesInertTest extends SharedRegistryTestBase { + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + private static final String THREW = ""; + + private static Path model(String variant) { + return SpringTestFixtures.findCorpusRoot().getParent() + .resolve("codegen-noop/rules/" + variant + "/meta.purchasing.json"); + } + + private MetaDataLoader load(String variant) throws Exception { + String json = Files.readString(model(variant), StandardCharsets.UTF_8); + // One loader name for both variants: the model tier stamps it into generated code. + return SpringTestFixtures.loadFixture(tempFolder.newFolder().toPath(), "purchasing", json); + } + + private static Generator instantiate(GeneratorInfo info) throws Exception { + return (Generator) Class.forName(info.classname()).getDeclaredConstructor().newInstance(); + } + + /** Run a generator suite into a fresh directory; a throw is the single entry {@code }. */ + private Map emit(String variant, List suite) throws Exception { + MetaDataLoader loader = load(variant); + Path outDir = tempFolder.newFolder().toPath(); + Map files = new TreeMap<>(); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + for (GeneratorInfo info : suite) { + Generator gen = instantiate(info); + run.attributeTo(gen.getClass().getSimpleName()); + Map args = new LinkedHashMap<>(); + args.put("outputDir", outDir.toString()); + args.put("templateRoot", tempFolder.newFolder().toString()); + if ("entity".equals(info.stableName())) { + args.put("type", "class"); + args.put("flavor", "pojoAware"); + } + if (!(gen instanceof MultiFileDirectGeneratorBase)) { + args.put("outputFilename", gen.getClass().getSimpleName() + ".out"); + } + gen.setArgs(args).execute(loader); + } + } catch (Exception | LinkageError e) { + files.clear(); + files.put(THREW, String.valueOf(e.getMessage())); + return files; + } + try (Stream s = Files.walk(outDir)) { + for (Path p : s.filter(Files::isRegularFile).collect(Collectors.toList())) { + files.put(outDir.relativize(p).toString(), Files.readString(p, StandardCharsets.UTF_8)); + } + } + return files; + } + + private static void assertSame(String label, Map expected, Map actual) { + assertEquals(label + ": emitted file set", new ArrayList<>(expected.keySet()), new ArrayList<>(actual.keySet())); + for (Map.Entry e : expected.entrySet()) { + assertEquals(label + ": " + e.getKey() + " differs once rules nodes are declared", + e.getValue(), actual.get(e.getKey())); + } + } + + @Test + public void theWithModelReallyCarriesTheVocabulary() throws Exception { + // Else every comparison below is vacuously green. + MetaRoot with = load("with").getRoot(); + int apis = 0; + int transitions = 0; + for (MetaData child : with.getChildren(MetaData.class, true)) { + if ("api".equals(child.getType())) apis++; + if ("object".equals(child.getType())) { + for (MetaData f : child.getChildren(MetaData.class, true)) { + for (MetaData t : f.getChildren(MetaData.class, true)) { + if ("transition".equals(t.getType())) transitions++; + } + } + } + } + assertEquals("api nodes", 1, apis); + assertEquals("transitions", 3, transitions); + for (MetaData child : load("without").getRoot().getChildren(MetaData.class, true)) { + assertFalse("without-model declares an api", "api".equals(child.getType())); + } + } + + @Test + public void everyGeneratorEmitsTheSameFiles() throws Exception { + List leaks = new ArrayList<>(); + for (GeneratorInfo info : GeneratorRegistry.list().values()) { + try { + assertSame(info.stableName(), emit("without", List.of(info)), emit("with", List.of(info))); + } catch (AssertionError e) { + leaks.add(e.getMessage()); + } + } + assertTrue(String.join("\n", leaks), leaks.isEmpty()); + } + + @Test + public void theModelAndWebTiersInOneRunEmitTheSameFiles() throws Exception { + Map all = GeneratorRegistry.list(); + for (List tier : List.of( + List.of("entity", "names"), + List.of("value-object", "dto", "repository", "filter-allowlist", "routes", "names"))) { + List suite = tier.stream().map(all::get).collect(Collectors.toList()); + Map expected = emit("without", suite); + assertFalse(tier + " threw: " + expected.get(THREW), expected.containsKey(THREW)); + assertTrue(tier + ": only " + expected.size() + " files - the suite barely ran", expected.size() >= 3); + assertSame(tier.toString(), expected, emit("with", suite)); + } + } + + /** The api docs surface: every unit page, the index and the agent page. */ + private Map apiDocs(String variant) throws Exception { + JavaApiModel model = new JavaApiModelBuilder().build(load(variant), "purchasing"); + JavaApiDocsRenderer renderer = new JavaApiDocsRenderer(); + Map pages = new TreeMap<>(); + for (ApiUnit unit : model.units()) { + pages.put(DocsPaths.docPageOutputPath(DocsPaths.Layout.PACKAGE, unit.pkg(), unit.node()), + renderer.renderUnitPage(unit, null)); + } + pages.put("README.md", renderer.renderIndex(model, DocsPaths.Layout.PACKAGE)); + pages.put("AGENT-API.md", renderer.renderAgentApi(model)); + return pages; + } + + @Test + public void theApiReferenceIsIdentical() throws Exception { + Map expected = apiDocs("without"); + assertTrue("only " + expected.size() + " pages - the docs barely ran", expected.size() >= 3); + assertSame("api docs", expected, apiDocs("with")); + } +} diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java index 5f8fa0096b..c4fb0dd1d4 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java @@ -11,6 +11,8 @@ import com.metaobjects.generator.util.OrphanSweep; import com.metaobjects.generator.verify.TemplateVerify; import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.api.RulesCheck; +import com.metaobjects.config.RulesSettings; import com.metaobjects.requirement.RequirementCheck; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; @@ -399,6 +401,44 @@ private int runRequirementGate(MetaDataLoader loader) { // A default-set run reaches here once per gate; the ledger is one report, not two. if (advisoriesDone) return 0; advisoriesDone = true; + return runRequirementLedger(loader) + runRulesGate(loader); + } + + /** + * The business-rules gate (ADR-0066), beside the requirement gate. A model that declares no + * operation and no transition sees no change at all: nothing is logged. + * + * @return the number of error-severity diagnostics + */ + private int runRulesGate(MetaDataLoader loader) { + RulesSettings settings = RulesSettings.DEFAULT; + try { + settings = resolveProjectConfig(getSourceDir()).map(NeutralConfig::getRulesSettings) + .orElse(RulesSettings.DEFAULT); + } catch (MetaDataException e) { + getLog().error(PREFIX + "rules: " + e.getMessage()); + return 1; + } + RulesCheck.Result result = RulesCheck.check(loader.getRoot(), settings); + if (result.summary() == null) return 0; + RulesCheck.Summary sm = result.summary(); + getLog().info(PREFIX + "rules: " + sm.operations() + " operation(s), " + sm.lifecycles() + + " lifecycle(s) with " + sm.transitions() + " transition(s)."); + int errors = 0; + for (RequirementCheck.Diagnostic d : result.diagnostics()) { + if (d.severity() != RequirementCheck.Severity.ERROR) continue; + errors++; + getLog().error(RequirementCheck.formatDiagnostic(d)); + } + for (RequirementCheck.Diagnostic d : result.diagnostics()) { + if (d.severity() == RequirementCheck.Severity.ERROR) continue; + getLog().warn(RequirementCheck.formatDiagnostic(d)); + } + if (errors > 0) getLog().error(PREFIX + "rules: " + errors + " error(s)."); + return errors; + } + + private int runRequirementLedger(MetaDataLoader loader) { RequirementCheck.Scan scan = RequirementCheck.scan(loader.getRoot(), new RequirementCheck.Options(null, requireImplementers || "1".equals(getEnv(ENV_REQUIRE_IMPLEMENTERS)))); @@ -430,7 +470,7 @@ private int runRequirementGate(MetaDataLoader loader) { private static void failOnRequirementErrors(int errors) throws MojoFailureException { if (errors > 0) { - throw new MojoFailureException("metaobjects:verify \u2014 requirements: " + errors + throw new MojoFailureException("metaobjects:verify \u2014 requirements/rules: " + errors + " error(s); see the lines above."); } } diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MetaDataVerifyRulesTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MetaDataVerifyRulesTest.java new file mode 100644 index 0000000000..04f8cbbac7 --- /dev/null +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MetaDataVerifyRulesTest.java @@ -0,0 +1,113 @@ +package com.metaobjects.mojo; + +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.logging.SystemStreamLog; +import org.junit.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * {@code metaobjects:verify} - the business-rules gate (ADR-0066), end to end: the summary line, + * the diagnostics and the failure. The codes, paths and message text are gated cross-port by + * {@code RulesCheckConformanceTest} in the metadata module. + */ +public class MetaDataVerifyRulesTest { + + private static final String PREFIX = "metaobjects:verify — "; + + private static final class CapturingLog extends SystemStreamLog { + final List infos = new ArrayList<>(); + final List warnings = new ArrayList<>(); + final List errors = new ArrayList<>(); + + @Override public void info(CharSequence c) { infos.add(c.toString()); } + @Override public void warn(CharSequence c) { warnings.add(c.toString()); } + @Override public void error(CharSequence c) { errors.add(c.toString()); } + } + + private static final String PLAIN = """ + { "object.entity": { "name": "Order", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } ] } }"""; + + /** A lifecycle whose "lost" state nothing reaches, and no operation. */ + private static final String LIFECYCLE = """ + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "name": "src", "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.enum": { "name": "status", "@values": ["draft", "open", "lost"], "@default": "draft", + "children": [ + { "transition.action": { "name": "submit", "@from": ["draft"], "@to": "open" } } ] } } ] } }"""; + + private static Path model(String settings, String... children) throws Exception { + Path dir = Files.createTempDirectory("verify-rules"); + dir.toFile().deleteOnExit(); + Files.writeString(dir.resolve("meta.app.json"), "{ \"metadata.root\": { \"package\": \"acme::shop\", \"children\": [\n" + + String.join(",\n", children) + "\n] } }", StandardCharsets.UTF_8); + if (settings != null) { + Files.createDirectories(dir.resolve(".metaobjects")); + Files.writeString(dir.resolve(".metaobjects/config.json"), settings, StandardCharsets.UTF_8); + } + return dir; + } + + private record Run(CapturingLog log, MojoFailureException failure) {} + + private static Run run(Path dir) throws Exception { + MetaDataVerifyMojo mojo = new MetaDataVerifyMojo(); + mojo.setLoader(LoaderParam.builder("verify-rules-test") + .withClassname("com.metaobjects.loader.MetaDataLoader") + .withSourceDir(dir.toString()) + .withSource("meta.app.json") + .build()); + mojo.setGenerators(Collections.emptyList()); + mojo.setGlobals(Collections.emptyMap()); + mojo.setMode("templates"); + mojo.setTemplateRoot(Files.createTempDirectory("verify-rules-templates").toString()); + CapturingLog log = new CapturingLog(); + mojo.setLog(log); + try { + mojo.execute(); + return new Run(log, null); + } catch (MojoFailureException e) { + return new Run(log, e); + } + } + + @Test + public void aModelWithNoOperationAndNoTransitionLogsNothing() throws Exception { + Run run = run(model(null, PLAIN)); + assertNull(run.failure()); + assertTrue(run.log().infos.stream().noneMatch(l -> l.contains("rules:"))); + } + + @Test + public void anUnreachableStateWarnsAndPrintsTheSummaryByDefault() throws Exception { + Run run = run(model(null, LIFECYCLE)); + assertNull(run.failure()); + assertTrue(run.log().infos.toString(), run.log().infos.contains( + PREFIX + "rules: 0 operation(s), 1 lifecycle(s) with 1 transition(s).")); + assertTrue(run.log().warnings.toString(), run.log().warnings.stream().anyMatch( + w -> w.startsWith(" WARN_LIFECYCLE_UNREACHABLE_STATE [acme::shop::Order.status]: "))); + } + + @Test + public void unreachableAsErrorFailsTheBuild() throws Exception { + Run run = run(model("{ \"schema_version\": 1, \"verify\": { \"lifecycle\": { \"unreachable\": \"error\" } } }", LIFECYCLE)); + assertNotNull("the build must fail", run.failure()); + assertTrue(run.log().errors.toString(), run.log().errors.stream().anyMatch( + e -> e.startsWith(" WARN_LIFECYCLE_UNREACHABLE_STATE [acme::shop::Order.status]: "))); + assertTrue(run.log().errors.toString(), run.log().errors.contains(PREFIX + "rules: 1 error(s).")); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java index c3edaf70fd..6ac72efaf7 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java +++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java @@ -48,6 +48,12 @@ public enum ErrorCode { */ ERR_CHILD_NOT_OBJECT, + /** + * A structural child is placed under a parent whose registered child rules do not admit it + * (the structural analogue of {@code ERR_UNKNOWN_ATTR}). Reported on the PARENT. + */ + ERR_CHILD_NOT_ALLOWED, + /** A node uses a type not registered in the registry. */ ERR_UNKNOWN_TYPE, @@ -615,6 +621,39 @@ public enum ErrorCode { */ ERR_REPORT_FOREIGN_MEASURE, + /** ADR-0066: a transition.action @from or @to names a value that is not a member of its enum (L4). */ + ERR_TRANSITION_UNKNOWN_STATE, + + /** ADR-0066: a transition.action on a field of anything but an object.entity, or a concrete entity with a lifecycle and a source but no writable one; an entity with no source is inert (L1, L2). */ + ERR_TRANSITION_NOT_ON_ENTITY, + + /** ADR-0066: a field.enum declares transitions but no @default, its initial state (L3). */ + ERR_LIFECYCLE_NO_INITIAL, + + /** ADR-0066: an entity redeclares an inherited lifecycle field without extending it, dropping the base's transitions (L10). */ + ERR_LIFECYCLE_REDECLARED, + + /** ADR-0066: a transition or operation is named create, get, list, update or delete, or two transitions of one entity share a name (L5, L6, O0). */ + ERR_TRANSITION_NAME_COLLISION, + + /** ADR-0066: an operation @objectRef is not an object.entity, or a command lists @transitions with no target (O2). */ + ERR_OPERATION_TARGET_UNRESOLVED, + + /** ADR-0066: a declared @objectRef disagrees with the derived target (O3). */ + ERR_OPERATION_TARGET_MISMATCH, + + /** ADR-0066: a @transitions name is not a transition of the operation's target (O4). */ + ERR_OPERATION_UNKNOWN_TRANSITION, + + /** ADR-0066: @inputRef is not an object.value, or @outputRef is not an entity, projection or value (O1). */ + ERR_OPERATION_SHAPE, + + /** ADR-0066: @public: true together with @permission (P1). */ + ERR_PERMISSION_PUBLIC_CONFLICT, + + /** ADR-0066: a binding.rest @path whose placeholders are not the target's key fields (B1). */ + ERR_BINDING_PATH_MISMATCH, + /** An internal loader error with no stable error code. */ ERR_UNKNOWN, } diff --git a/server/java/metadata/src/main/java/com/metaobjects/InvalidMetaDataException.java b/server/java/metadata/src/main/java/com/metaobjects/InvalidMetaDataException.java index b197856a25..40fadd1c57 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/InvalidMetaDataException.java +++ b/server/java/metadata/src/main/java/com/metaobjects/InvalidMetaDataException.java @@ -33,6 +33,11 @@ public InvalidMetaDataException( MetaData md, String msg, Throwable cause) { super(prefix(md)+msg, cause); } + /** A placement-style failure that carries its structured code and the node it is reported on. */ + public InvalidMetaDataException( MetaData md, String msg, ErrorCode code, com.metaobjects.source.ErrorSource envelope) { + super(prefix(md)+msg, code, envelope); + } + protected static String prefix( MetaData md ) { if ( md == null ) return "[null] "; String pkg = md.getPackage(); diff --git a/server/java/metadata/src/main/java/com/metaobjects/MetaData.java b/server/java/metadata/src/main/java/com/metaobjects/MetaData.java index b939535ef1..3debdc38e1 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/MetaData.java +++ b/server/java/metadata/src/main/java/com/metaobjects/MetaData.java @@ -1335,7 +1335,8 @@ public void addChild(MetaData data, boolean checkExists) throws InvalidMetaData throw new InvalidMetaDataException(data, String.format( "%s.%s does not accept child '%s' of type %s.%s. %s", this.getType(), this.getSubType(), data.getName(), - data.getType(), data.getSubType(), supportedChildren)); + data.getType(), data.getSubType(), supportedChildren), + ErrorCode.ERR_CHILD_NOT_ALLOWED, this.getSource()); } // Constraint enforcement during construction, against the resolved registry. diff --git a/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java b/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java index 3b9325adf0..03006079d7 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java +++ b/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java @@ -126,6 +126,7 @@ public static void registerTypes(MetaDataRegistry registry) { .optionalChild(MetaValidator.TYPE_VALIDATOR, "*", "*") .optionalChild(com.metaobjects.template.TemplateConstants.TYPE_TEMPLATE, "*", "*") .optionalChild(com.metaobjects.requirement.MetaRequirement.TYPE_REQUIREMENT, "*", "*") + .optionalChild(com.metaobjects.api.ApiConstants.TYPE_API, "*", "*") .optionalChild(com.metaobjects.attr.MetaAttribute.TYPE_ATTR, "*", "*") ); log.debug("Registered MetaRoot type (metadata.root) with unified registry"); diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/ApiConstants.java b/server/java/metadata/src/main/java/com/metaobjects/api/ApiConstants.java new file mode 100644 index 0000000000..371564aa65 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/ApiConstants.java @@ -0,0 +1,68 @@ +/* + * 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.api; + +import java.util.List; +import java.util.regex.Pattern; + +/** Names of the declared API surface vocabulary: {@code api.*}, {@code operation.*}, {@code binding.*} (ADR-0030, ADR-0066). */ +public final class ApiConstants { + + private ApiConstants() { + } + + public static final String TYPE_API = "api"; + public static final String TYPE_OPERATION = "operation"; + public static final String TYPE_BINDING = "binding"; + + public static final String API_SUBTYPE_OPERATIONAL = "operational"; + public static final String OPERATION_SUBTYPE_COMMAND = "command"; + public static final String OPERATION_SUBTYPE_QUERY = "query"; + public static final String BINDING_SUBTYPE_REST = "rest"; + + public static final String ATTR_INPUT_REF = "inputRef"; + public static final String ATTR_OUTPUT_REF = "outputRef"; + public static final String ATTR_OBJECT_REF = "objectRef"; + public static final String ATTR_PERMISSION = "permission"; + public static final String ATTR_PUBLIC = "public"; + public static final String ATTR_TRANSITIONS = "transitions"; + public static final String ATTR_ERRORS = "errors"; + public static final String ATTR_MANY = "many"; + public static final String ATTR_METHOD = "method"; + public static final String ATTR_PATH = "path"; + + /** The HTTP methods a {@code binding.rest @method} may name. */ + public static final List BINDING_METHODS = List.of("GET", "POST", "PUT", "PATCH", "DELETE"); + + /** The derived CRUD verbs a transition or operation may not be named. */ + public static final List RESERVED_OPERATION_NAMES = List.of("create", "get", "list", "update", "delete"); + + /** Wire error codes the route answers itself, so an operation's {@code @errors} may not declare them (O5); the order appears in a message. */ + public static final List RESERVED_ERROR_CODES = List.of( + "not_found", "forbidden", "invalid_transition", "transition_condition_failed", "state_managed", + "validation", "invalid_json", "invalid_id", "method_not_allowed", "constraint_violation", "internal"); + + /** + * A declared {@code @permission}: a dotted identifier path ({@code purchasing.approve}). A + * package prefix may use {@code ::}, so a derived name can be declared as it is. Match with + * {@code matches()}, which anchors the whole string. + */ + public static final Pattern PERMISSION_NAME_PATTERN = Pattern.compile( + "[A-Za-z_][A-Za-z0-9_]*(?:(?:\\.|::)[A-Za-z_][A-Za-z0-9_]*)*"); + + /** A business error code: lower snake case. */ + public static final Pattern BUSINESS_ERROR_CODE_PATTERN = Pattern.compile("^[a-z][a-z0-9]*(_[a-z0-9]+)*$"); +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/CommandOperation.java b/server/java/metadata/src/main/java/com/metaobjects/api/CommandOperation.java new file mode 100644 index 0000000000..d60a1cc130 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/CommandOperation.java @@ -0,0 +1,65 @@ +/* + * 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.api; + +import com.metaobjects.MetaData; +import com.metaobjects.attr.BooleanAttribute; +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.registry.MetaDataRegistry; + +/** {@code operation.command} and {@code operation.query} (ADR-0030, ADR-0066), registered with {@code operation.base}. */ +@SuppressWarnings("serial") +public class CommandOperation extends MetaOperation { + + public CommandOperation(String name) { + super(ApiConstants.OPERATION_SUBTYPE_COMMAND, name); + } + + /** Register {@code operation.base}, {@code operation.command} and {@code operation.query}. */ + public static void registerTypes(MetaDataRegistry registry) { + registry.registerType(MetaOperation.class, def -> { + def.type(ApiConstants.TYPE_OPERATION).subType(MetaData.SUBTYPE_BASE) + .description("Registry anchor for the attributes every operation shares") + .inheritsFrom(MetaData.TYPE_METADATA, MetaData.SUBTYPE_BASE) + .optionalChild(ApiConstants.TYPE_BINDING, "*", "*") + // Like template.base: the any-attr wildcard lets an undeclared attr reach the + // strict-load ERR_UNKNOWN_ATTR diagnostic instead of failing placement. + .optionalChild(com.metaobjects.attr.MetaAttribute.TYPE_ATTR, "*", "*"); + for (String ref : new String[] {ApiConstants.ATTR_INPUT_REF, ApiConstants.ATTR_OUTPUT_REF, + ApiConstants.ATTR_OBJECT_REF, ApiConstants.ATTR_PERMISSION}) { + def.optionalAttributeWithConstraints(ref).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + } + def.optionalAttributeWithConstraints(ApiConstants.ATTR_PUBLIC) + .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + }); + registry.registerType(CommandOperation.class, def -> { + def.type(ApiConstants.TYPE_OPERATION).subType(ApiConstants.OPERATION_SUBTYPE_COMMAND) + .description("A named operation that changes state.") + .inheritsFrom(ApiConstants.TYPE_OPERATION, MetaData.SUBTYPE_BASE); + def.optionalAttributeWithConstraints(ApiConstants.ATTR_TRANSITIONS) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.optionalAttributeWithConstraints(ApiConstants.ATTR_ERRORS) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + }); + registry.registerType(QueryOperation.class, def -> { + def.type(ApiConstants.TYPE_OPERATION).subType(ApiConstants.OPERATION_SUBTYPE_QUERY) + .description("A named operation that reads.") + .inheritsFrom(ApiConstants.TYPE_OPERATION, MetaData.SUBTYPE_BASE); + def.optionalAttributeWithConstraints(ApiConstants.ATTR_MANY) + .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + }); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/Lifecycles.java b/server/java/metadata/src/main/java/com/metaobjects/api/Lifecycles.java new file mode 100644 index 0000000000..4fa024f9ab --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/Lifecycles.java @@ -0,0 +1,341 @@ +/* + * 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.api; + +import com.metaobjects.MetaData; +import com.metaobjects.field.EnumField; +import com.metaobjects.field.MetaField; +import com.metaobjects.identity.MetaIdentity; +import com.metaobjects.loader.References; +import com.metaobjects.object.MetaObject; +import com.metaobjects.transition.TransitionConstants; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Lifecycle and operation-target derivation (ADR-0066), shared by the loader's rules pass + * and the {@code verify} rules gate. Everything here is DERIVED: a lifecycle, its states, + * its initial and terminal states and an operation's target entity have no vocabulary of + * their own. Mirrors the TypeScript {@code core/transition/lifecycle.ts}. + * + *

Reads are RESOLVING (ADR-0039): a transition declared on a base entity's field is a + * transition of every entity that extends it.

+ */ +public final class Lifecycles { + + private Lifecycles() { + } + + /** One lifecycle of an entity: an enum field with at least one transition. */ + public record Lifecycle(MetaData field, List states, String initial, List transitions) { + } + + /** How an operation's target was derived: {@code viaInput} means the input borrows the target's key. */ + public record DerivedTarget(MetaData entity, boolean viaInput) { + } + + /** A string-array attr read resolving; a bare string is ONE element. */ + public static List stringList(MetaData node, String attr) { + List out = new ArrayList<>(); + if (!node.hasMetaAttr(attr)) return out; + Object v = node.getMetaAttr(attr).getValue(); + if (v instanceof List list) { + for (Object item : list) if (item instanceof String s) out.add(s); + } else if (v instanceof String s) { + out.add(s); + } + return out; + } + + /** A string attr read resolving, or {@code null}. */ + public static String stringValue(MetaData node, String attr) { + if (!node.hasMetaAttr(attr)) return null; + return node.getMetaAttr(attr).getValue() instanceof String s ? s : null; + } + + /** True when the node's own {@code isAbstract} flag is set (abstractness is never inherited). */ + public static boolean isAbstract(MetaData node) { + // ADR-0039: own — abstractness describes the declaration itself. + return node.hasMetaAttr(MetaData.ATTR_IS_ABSTRACT, false) + && Boolean.TRUE.equals(node.getMetaAttr(MetaData.ATTR_IS_ABSTRACT, false).getValue()); + } + + /** + * Whether an entity's lifecycles are live: it declares or inherits a source (read resolving). + * A lifecycle on an entity with no source loads and is inert (ADR-0066 section 2). + */ + public static boolean lifecycleIsLive(MetaData entity) { + for (MetaData c : entity.getChildren(MetaData.class, true)) { + if (com.metaobjects.source.MetaSource.TYPE_SOURCE.equals(c.getType())) return true; + } + return false; + } + + /** True for an {@code object.entity}. */ + public static boolean isEntity(MetaData node) { + return node != null && MetaObject.TYPE_OBJECT.equals(node.getType()) + && MetaObject.SUBTYPE_ENTITY.equals(node.getSubType()); + } + + /** The {@code transition.action} children of a field, resolving. */ + public static List transitionsOf(MetaData field) { + List out = new ArrayList<>(); + for (MetaData c : field.getChildren(MetaData.class, true)) { + if (TransitionConstants.TYPE_TRANSITION.equals(c.getType()) + && TransitionConstants.SUBTYPE_ACTION.equals(c.getSubType())) out.add(c); + } + return out; + } + + /** An entity and every entity it extends, nearest first. */ + public static List entityLineage(MetaData entity) { + List out = new ArrayList<>(); + for (MetaData e = entity; e != null && !containsIdentity(out, e); e = e.hasSuperData() ? e.getSuperData() : null) out.add(e); + return out; + } + + /** Identity membership: nodes are compared by reference, never by equals. */ + public static boolean containsIdentity(List list, MetaData node) { + for (MetaData x : list) if (x == node) return true; + return false; + } + + /** + * The transitions a field gives an entity: those declared on a field of the entity itself or of + * an entity it extends. A transition reached only through the field's own {@code extends} of + * another entity's field is not one (ADR-0066 section 2). + */ + public static List lifecycleTransitionsOf(MetaData entity, MetaData field) { + List lineage = entityLineage(entity); + List out = new ArrayList<>(); + for (MetaData t : transitionsOf(field)) { + MetaData owner = t.getParent() == null ? null : t.getParent().getParent(); + if (owner != null && containsIdentity(lineage, owner)) out.add(t); + } + return out; + } + + /** The lifecycles of an object, in effective field order. Only an {@code object.entity} has any. */ + public static List lifecyclesOf(MetaData obj) { + List out = new ArrayList<>(); + if (!isEntity(obj)) return out; + for (MetaData field : obj.getChildren(MetaData.class, true)) { + if (!MetaField.TYPE_FIELD.equals(field.getType()) || !EnumField.SUBTYPE_ENUM.equals(field.getSubType())) continue; + List transitions = lifecycleTransitionsOf(obj, field); + if (transitions.isEmpty()) continue; + out.add(new Lifecycle(field, stringList(field, EnumField.ATTR_VALUES), + stringValue(field, MetaField.ATTR_DEFAULT), transitions)); + } + return out; + } + + /** Every transition of an entity, across all its lifecycles. */ + public static List entityTransitions(MetaData obj) { + List out = new ArrayList<>(); + for (Lifecycle l : lifecyclesOf(obj)) out.addAll(l.transitions()); + return out; + } + + /** A transition's {@code @from} (resolving). */ + public static List transitionFrom(MetaData t) { + return stringList(t, TransitionConstants.ATTR_FROM); + } + + /** A transition's {@code @to} (resolving), or {@code null}. */ + public static String transitionTo(MetaData t) { + return stringValue(t, TransitionConstants.ATTR_TO); + } + + /** The states reachable from the initial state, following every transition. */ + public static Set reachableStates(Lifecycle l) { + Set seen = new HashSet<>(); + if (l.initial() == null) return seen; + List queue = new ArrayList<>(); + queue.add(l.initial()); + seen.add(l.initial()); + for (int i = 0; i < queue.size(); i++) { + String s = queue.get(i); + for (MetaData t : l.transitions()) { + String to = transitionTo(t); + if (to != null && transitionFrom(t).contains(s) && seen.add(to)) queue.add(to); + } + } + return seen; + } + + /** The members no transition leaves (a self-transition counts as leaving). */ + public static List terminalStates(Lifecycle l) { + Set leaving = new HashSet<>(); + for (MetaData t : l.transitions()) leaving.addAll(transitionFrom(t)); + List out = new ArrayList<>(); + for (String s : l.states()) if (!leaving.contains(s)) out.add(s); + return out; + } + + /** The primary key field names of an entity: its effective {@code identity.primary @fields}. */ + public static List primaryKeyFields(MetaData entity) { + for (MetaData c : entity.getChildren(MetaData.class, true)) { + if (MetaIdentity.TYPE_IDENTITY.equals(c.getType()) && MetaIdentity.SUBTYPE_PRIMARY.equals(c.getSubType())) { + return stringList(c, "fields"); + } + } + return new ArrayList<>(); + } + + /** The package a node's references resolve in: its top-level node's effective package. */ + public static String referrerPackageOf(MetaData node) { + return References.effectivePackageOf(node); + } + + /** Resolve an object reference written on {@code node} (owner part only); {@code null} when it names nothing. */ + public static MetaData resolveObjectOn(MetaData node, String ref) { + MetaData root = References.topLevelRoot(node); + if (root == null) return null; + return References.resolveObjectRef(root, References.splitChildTail(ref).owner(), referrerPackageOf(node)).node(); + } + + private record Extended(MetaData owner, String member) { + } + + /** + * The object a field's {@code extends} NAMES, and the member it names there. {@code id extends + * PurchaseRequest.id} names PurchaseRequest even when PurchaseRequest inherits {@code id} + * from an abstract base, which is where the resolved super node physically lives. + */ + private static Extended extendedMember(MetaData f) { + String ref = f.getAuthoredSuperRef(); + MetaData sup = f.hasSuperData() ? f.getSuperData() : null; + if (ref == null || sup == null) return null; + int lastSep = ref.lastIndexOf(MetaData.PKG_SEPARATOR); + int segStart = lastSep == -1 ? 0 : lastSep + MetaData.PKG_SEPARATOR.length(); + int dot = ref.indexOf('.', segStart); + if (dot > segStart) { + MetaData root = References.topLevelRoot(f); + if (root != null) { + MetaData named = References.resolveObjectRef(root, ref.substring(0, dot), referrerPackageOf(f)).node(); + if (named != null) return new Extended(named, sup.getShortName()); + } + } + MetaData parent = sup.getParent(); + return parent != null && MetaObject.TYPE_OBJECT.equals(parent.getType()) + ? new Extended(parent, sup.getShortName()) : null; + } + + /** + * The entities whose whole primary key a value object borrows, once: every primary key field of + * the entity is extended by exactly one field of the value. Part of a composite key, or one key + * field borrowed twice, borrows nothing from it. + */ + private static List borrowedKeyEntities(MetaData value) { + List owners = new ArrayList<>(); + List> counts = new ArrayList<>(); + for (MetaData f : value.getChildren(MetaData.class, true)) { + if (!MetaField.TYPE_FIELD.equals(f.getType())) continue; + Extended ext = extendedMember(f); + if (ext == null || !isEntity(ext.owner())) continue; + if (!primaryKeyFields(ext.owner()).contains(ext.member())) continue; + int i = -1; + for (int k = 0; k < owners.size(); k++) if (owners.get(k) == ext.owner()) i = k; + if (i < 0) { + owners.add(ext.owner()); + counts.add(new java.util.HashMap<>()); + i = owners.size() - 1; + } + counts.get(i).merge(ext.member(), 1, Integer::sum); + } + List out = new ArrayList<>(); + for (int i = 0; i < owners.size(); i++) { + boolean whole = true; + for (String k : primaryKeyFields(owners.get(i))) if (!Integer.valueOf(1).equals(counts.get(i).get(k))) whole = false; + if (whole) out.add(owners.get(i)); + } + return out; + } + + /** + * The base entity of a projection: the entity its extended identity names, else the one + * entity its extended fields name. {@code null} when there is none or more than one. + */ + public static MetaData projectionBaseEntity(MetaData projection) { + for (MetaData id : projection.getChildren(MetaData.class, true)) { + if (!MetaIdentity.TYPE_IDENTITY.equals(id.getType())) continue; + Extended ext = extendedMember(id); + if (ext != null && isEntity(ext.owner())) return ext.owner(); + } + List owners = new ArrayList<>(); + for (MetaData f : projection.getChildren(MetaData.class, true)) { + if (!MetaField.TYPE_FIELD.equals(f.getType())) continue; + Extended ext = extendedMember(f); + if (ext != null && isEntity(ext.owner()) && !containsIdentity(owners, ext.owner())) owners.add(ext.owner()); + } + return owners.size() == 1 ? owners.get(0) : null; + } + + /** + * The target entity derived from an operation's shapes, or {@code null}: the one entity whose + * whole primary key the {@code @inputRef} value borrows (each key field once); else the {@code @outputRef} + * (an entity is its own target, a projection its base entity). + */ + public static DerivedTarget deriveOperationTarget(MetaData op) { + String inputRef = stringValue(op, ApiConstants.ATTR_INPUT_REF); + if (inputRef != null) { + MetaData input = resolveObjectOn(op, inputRef); + if (input != null && MetaObject.SUBTYPE_VALUE.equals(input.getSubType())) { + List borrowed = borrowedKeyEntities(input); + if (borrowed.size() == 1) return new DerivedTarget(borrowed.get(0), true); + } + } + String outputRef = stringValue(op, ApiConstants.ATTR_OUTPUT_REF); + if (outputRef != null) { + MetaData output = resolveObjectOn(op, outputRef); + if (output != null && MetaObject.SUBTYPE_ENTITY.equals(output.getSubType())) return new DerivedTarget(output, false); + if (output != null && MetaObject.SUBTYPE_PROJECTION.equals(output.getSubType())) { + MetaData base = projectionBaseEntity(output); + if (base != null) return new DerivedTarget(base, false); + } + } + return null; + } + + /** The operation's target: the declared {@code @objectRef} when it names an entity, else the derived one. */ + public static MetaData operationTarget(MetaData op) { + String declared = stringValue(op, ApiConstants.ATTR_OBJECT_REF); + if (declared != null) { + MetaData node = resolveObjectOn(op, declared); + return isEntity(node) ? node : null; + } + DerivedTarget d = deriveOperationTarget(op); + return d == null ? null : d.entity(); + } + + /** + * Whether the operation addresses one row of its target by key: its input borrows the + * target's key, or it is a query with no input and no {@code @many} whose target comes from + * its output (a get by key). + */ + public static boolean operationIsKeyed(MetaData op) { + DerivedTarget derived = deriveOperationTarget(op); + if (derived == null) return false; + if (derived.viaInput()) return true; + return ApiConstants.OPERATION_SUBTYPE_QUERY.equals(op.getSubType()) + && stringValue(op, ApiConstants.ATTR_INPUT_REF) == null + && !Boolean.TRUE.equals(op.hasMetaAttr(ApiConstants.ATTR_MANY) ? op.getMetaAttr(ApiConstants.ATTR_MANY).getValue() : null); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/MetaApi.java b/server/java/metadata/src/main/java/com/metaobjects/api/MetaApi.java new file mode 100644 index 0000000000..5530b9a9c2 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/MetaApi.java @@ -0,0 +1,27 @@ +/* + * 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.api; + +import com.metaobjects.MetaData; + +/** Base node class for {@code type = "api"} (ADR-0030): the declared API surface. Accessors are RESOLVING (ADR-0039). */ +@SuppressWarnings("serial") +public abstract class MetaApi extends MetaData { + + protected MetaApi(String subType, String name) { + super(ApiConstants.TYPE_API, subType, name); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/MetaBinding.java b/server/java/metadata/src/main/java/com/metaobjects/api/MetaBinding.java new file mode 100644 index 0000000000..17d1a25cc6 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/MetaBinding.java @@ -0,0 +1,27 @@ +/* + * 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.api; + +import com.metaobjects.MetaData; + +/** Base node class for {@code type = "binding"} (ADR-0030): a protocol binding of one operation. Accessors are RESOLVING (ADR-0039). */ +@SuppressWarnings("serial") +public abstract class MetaBinding extends MetaData { + + protected MetaBinding(String subType, String name) { + super(ApiConstants.TYPE_BINDING, subType, name); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/MetaOperation.java b/server/java/metadata/src/main/java/com/metaobjects/api/MetaOperation.java new file mode 100644 index 0000000000..842b9bf447 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/MetaOperation.java @@ -0,0 +1,27 @@ +/* + * 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.api; + +import com.metaobjects.MetaData; + +/** Base node class for {@code type = "operation"} (ADR-0030, ADR-0066). Accessors are RESOLVING (ADR-0039). */ +@SuppressWarnings("serial") +public abstract class MetaOperation extends MetaData { + + protected MetaOperation(String subType, String name) { + super(ApiConstants.TYPE_OPERATION, subType, name); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/OperationalApi.java b/server/java/metadata/src/main/java/com/metaobjects/api/OperationalApi.java new file mode 100644 index 0000000000..104ba49140 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/OperationalApi.java @@ -0,0 +1,44 @@ +/* + * 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.api; + +import com.metaobjects.MetaData; +import com.metaobjects.registry.MetaDataRegistry; + +/** {@code api.operational} (ADR-0030): a named, packaged request/response surface. */ +@SuppressWarnings("serial") +public class OperationalApi extends MetaApi { + + public OperationalApi(String name) { + super(ApiConstants.API_SUBTYPE_OPERATIONAL, name); + } + + /** Register {@code api.base} and {@code api.operational}; text and children come from {@code spec/metamodel/api.json}. */ + public static void registerTypes(MetaDataRegistry registry) { + registry.registerType(MetaApi.class, def -> def + .type(ApiConstants.TYPE_API).subType(MetaData.SUBTYPE_BASE) + .description("Registry anchor for the declared API surface") + .inheritsFrom(MetaData.TYPE_METADATA, MetaData.SUBTYPE_BASE) + // Like template.base: the any-attr wildcard lets an undeclared attr reach the + // strict-load ERR_UNKNOWN_ATTR diagnostic instead of failing placement. + .optionalChild(com.metaobjects.attr.MetaAttribute.TYPE_ATTR, "*", "*")); + registry.registerType(OperationalApi.class, def -> def + .type(ApiConstants.TYPE_API).subType(ApiConstants.API_SUBTYPE_OPERATIONAL) + .description("A named, packaged request/response surface whose children are operations.") + .inheritsFrom(ApiConstants.TYPE_API, MetaData.SUBTYPE_BASE) + .optionalChild(ApiConstants.TYPE_OPERATION, "*", "*")); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/QueryOperation.java b/server/java/metadata/src/main/java/com/metaobjects/api/QueryOperation.java new file mode 100644 index 0000000000..0ff8c94348 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/QueryOperation.java @@ -0,0 +1,25 @@ +/* + * 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.api; + +/** {@code operation.query} (ADR-0030): a named operation that reads. Registered by {@link CommandOperation#registerTypes}. */ +@SuppressWarnings("serial") +public class QueryOperation extends MetaOperation { + + public QueryOperation(String name) { + super(ApiConstants.OPERATION_SUBTYPE_QUERY, name); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/RestBinding.java b/server/java/metadata/src/main/java/com/metaobjects/api/RestBinding.java new file mode 100644 index 0000000000..6bccde15d8 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/RestBinding.java @@ -0,0 +1,50 @@ +/* + * 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.api; + +import com.metaobjects.MetaData; +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.registry.MetaDataRegistry; + +/** {@code binding.rest} (ADR-0030): the HTTP method and path of an operation, declared only to override the derived ones. */ +@SuppressWarnings("serial") +public class RestBinding extends MetaBinding { + + public RestBinding(String name) { + super(ApiConstants.BINDING_SUBTYPE_REST, name); + } + + /** Register {@code binding.base} and {@code binding.rest}. */ + public static void registerTypes(MetaDataRegistry registry) { + registry.registerType(MetaBinding.class, def -> def + .type(ApiConstants.TYPE_BINDING).subType(MetaData.SUBTYPE_BASE) + .description("Registry anchor for protocol bindings") + .inheritsFrom(MetaData.TYPE_METADATA, MetaData.SUBTYPE_BASE) + // Like template.base: the any-attr wildcard lets an undeclared attr reach the + // strict-load ERR_UNKNOWN_ATTR diagnostic instead of failing placement. + .optionalChild(com.metaobjects.attr.MetaAttribute.TYPE_ATTR, "*", "*")); + registry.registerType(RestBinding.class, def -> { + def.type(ApiConstants.TYPE_BINDING).subType(ApiConstants.BINDING_SUBTYPE_REST) + .description("The HTTP method and path of an operation.") + .inheritsFrom(ApiConstants.TYPE_BINDING, MetaData.SUBTYPE_BASE); + def.optionalAttributeWithConstraints(ApiConstants.ATTR_METHOD) + .ofType(StringAttribute.SUBTYPE_STRING) + .withEnum(ApiConstants.BINDING_METHODS.toArray(new String[0])); + def.optionalAttributeWithConstraints(ApiConstants.ATTR_PATH) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java b/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java new file mode 100644 index 0000000000..bbb29d22a7 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java @@ -0,0 +1,295 @@ +/* + * 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.api; + +import com.metaobjects.MetaData; +import com.metaobjects.MetaRoot; +import com.metaobjects.api.Lifecycles.Lifecycle; +import com.metaobjects.config.RulesSettings; +import com.metaobjects.loader.References; +import com.metaobjects.requirement.RequirementCheck.Diagnostic; +import com.metaobjects.requirement.RequirementCheck.Severity; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * The business-rules gate ({@code verify}, ADR-0066). The loader refuses a model whose + * operations or lifecycles are malformed; this gate reports what loads clean but is almost + * certainly not what the author meant: a state nothing can reach, a lifecycle that cannot move, + * a transition nothing can make, and (by setting) a permission name the model derived instead + * of declaring. + * + *

Java port of the TypeScript reference, {@code rules-check.ts}: the codes, severities, + * paths and message text are copied from it, and {@code fixtures/rules-check-conformance/} + * holds this port to it. A model that declares no operation and no transition gets no + * diagnostics, no summary and no gate row.

+ */ +public final class RulesCheck { + + private RulesCheck() {} + + public static final String WARN_LIFECYCLE_UNREACHABLE_STATE = "WARN_LIFECYCLE_UNREACHABLE_STATE"; + public static final String WARN_LIFECYCLE_INITIAL_TERMINAL = "WARN_LIFECYCLE_INITIAL_TERMINAL"; + public static final String WARN_TRANSITION_UNREACHABLE = "WARN_TRANSITION_UNREACHABLE"; + public static final String WARN_PERMISSION_DERIVED_NAME = "WARN_PERMISSION_DERIVED_NAME"; + public static final String WARN_TRANSITION_PERMISSION_SHADOWED = "WARN_TRANSITION_PERMISSION_SHADOWED"; + + /** What the model declares, for the line {@code verify} prints. */ + public record Summary(int operations, int lifecycles, int transitions) {} + + /** @param summary {@code null} when the model declares no operation and no transition */ + public record Result(List diagnostics, Summary summary) {} + + private static String quoteList(Iterable xs) { + List q = new ArrayList<>(); + for (String x : xs) q.add("\"" + x + "\""); + return String.join(", ", q); + } + + /** A node's package-qualified address: {@code acme::shop::Order.status.submit}. */ + public static String rulesAddress(MetaData node) { + List parts = new ArrayList<>(); + for (MetaData n = node; n != null && n.getParent() != null; n = n.getParent()) { + String name = n.getShortName(); + if (name != null && !name.isEmpty() && !n.isAutoNamed()) parts.add(0, name); + } + String pkg = References.effectivePackageOf(node); + return pkg.isEmpty() ? String.join(".", parts) : pkg + MetaData.PKG_SEPARATOR + String.join(".", parts); + } + + /** The permission name a node gets when it declares none, {@code .}: the path is {@code } for an operation and {@code .} for a transition's derived command. */ + private static String derivedPermissionName(MetaData owner, String path) { + String pkg = References.effectivePackageOf(owner); + return pkg.isEmpty() ? path : pkg + "." + path; + } + + private static boolean needsPermissionName(MetaData node) { + boolean isPublic = node.hasMetaAttr(ApiConstants.ATTR_PUBLIC) + && Boolean.TRUE.equals(node.getMetaAttr(ApiConstants.ATTR_PUBLIC).getValue()); + return !node.hasMetaAttr(ApiConstants.ATTR_PERMISSION) && !isPublic; + } + + private static List entities(MetaRoot root) { + List out = new ArrayList<>(); + for (MetaData c : root.getChildren(MetaData.class, true)) if (Lifecycles.isEntity(c)) out.add(c); + return out; + } + + private static List operations(MetaRoot root) { + List out = new ArrayList<>(); + for (MetaData api : root.getChildren(MetaData.class, true)) { + if (!ApiConstants.TYPE_API.equals(api.getType())) continue; + for (MetaData op : api.getChildren(MetaData.class, true)) { + if (ApiConstants.TYPE_OPERATION.equals(op.getType())) out.add(op); + } + } + return out; + } + + /** Every lifecycle of the model, once per declaring field, in model order. */ + private static List declaredLifecycles(MetaRoot root) { + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + List out = new ArrayList<>(); + for (MetaData entity : entities(root)) { + for (Lifecycle l : Lifecycles.lifecyclesOf(entity)) { + if (seen.add(l.field())) out.add(l); + } + } + return out; + } + + private static void checkLifecycle(Lifecycle l, RulesSettings settings, List out) { + String where = rulesAddress(l.field()); + String initial = l.initial(); + if (initial == null) return; // the loader refused this model (ERR_LIFECYCLE_NO_INITIAL) + Set reachable = Lifecycles.reachableStates(l); + Severity severity = switch (settings.lifecycleUnreachable()) { + case OFF -> null; + case ERROR -> Severity.ERROR; + case WARN -> Severity.WARN; + }; + String field = l.field().getShortName(); + + if (severity != null) { + List unreachable = new ArrayList<>(); + for (String s : l.states()) if (!reachable.contains(s)) unreachable.add(s); + if (!unreachable.isEmpty()) { + boolean one = unreachable.size() == 1; + out.add(new Diagnostic(severity, WARN_LIFECYCLE_UNREACHABLE_STATE, where, + (one ? "state " : "states ") + quoteList(unreachable) + " of \"" + field + + "\" cannot be reached from the initial state \"" + initial + "\" by any transition. " + + "Add the transition that leads there, or set verify.lifecycle.unreachable if only seeded data uses " + + (one ? "it" : "them") + ".")); + } + } + + if (Lifecycles.terminalStates(l).contains(initial)) { + out.add(new Diagnostic(Severity.WARN, WARN_LIFECYCLE_INITIAL_TERMINAL, where, + "the initial state \"" + initial + "\" of \"" + field + "\" is terminal: no transition leaves it, " + + "so no row of this lifecycle can ever move.")); + } + + if (severity != null) { + for (MetaData t : l.transitions()) { + List from = Lifecycles.transitionFrom(t); + if (from.isEmpty() || from.stream().anyMatch(reachable::contains)) continue; + out.add(new Diagnostic(severity, WARN_TRANSITION_UNREACHABLE, rulesAddress(t), + "transition \"" + t.getShortName() + "\" starts only from " + quoteList(from) + + ", which no transition reaches from the initial state \"" + initial + + "\", so it can never be made.")); + } + } + } + + /** One command's claim on a transition node, made for its target entity. */ + private record Claim(MetaData target, MetaData op) {} + + /** Each transition node the declared commands claim, with the claims on it in model order. */ + private static Map> claimedTransitions(MetaRoot root) { + Map> claimed = new IdentityHashMap<>(); + for (MetaData op : operations(root)) { + if (!ApiConstants.OPERATION_SUBTYPE_COMMAND.equals(op.getSubType())) continue; + MetaData target = Lifecycles.operationTarget(op); + if (target == null) continue; + Set names = new HashSet<>(Lifecycles.stringList(op, ApiConstants.ATTR_TRANSITIONS)); + for (MetaData t : Lifecycles.entityTransitions(target)) { + if (!names.contains(t.getShortName())) continue; + claimed.computeIfAbsent(t, k -> new ArrayList<>()).add(new Claim(target, op)); + } + } + return claimed; + } + + /** The claims that cover transition {@code t} on {@code entity}: those made for the entity or an entity it extends. */ + private static List claimsOn(Map> claimed, MetaData entity, MetaData t) { + List lineage = Lifecycles.entityLineage(entity); + List out = new ArrayList<>(); + for (Claim c : claimed.getOrDefault(t, List.of())) { + if (Lifecycles.containsIdentity(lineage, c.target())) out.add(c); + } + return out; + } + + /** Whether {@code t}, carried by {@code entity}, derives a command of its own under the setting. */ + private static boolean derivesCommand(Map> claimed, RulesSettings settings, MetaData entity, MetaData t) { + if (settings.lifecycleCommands() == RulesSettings.LifecycleCommands.NONE) return false; + if (settings.lifecycleCommands() == RulesSettings.LifecycleCommands.ALL) return true; + return claimsOn(claimed, entity, t).isEmpty(); + } + + /** The entities a transition can derive a command on: concrete, with a source. */ + private static List commandEntities(MetaRoot root) { + List out = new ArrayList<>(); + for (MetaData e : entities(root)) if (!Lifecycles.isAbstract(e) && Lifecycles.lifecycleIsLive(e)) out.add(e); + return out; + } + + /** + * A transition's @permission or @public is read only by the command derived from it. One that + * derives no command for any concrete entity carrying it declares an attribute nothing reads. + */ + private static void checkShadowedPermissions(MetaRoot root, RulesSettings settings, List out) { + if (settings.lifecycleCommands() == RulesSettings.LifecycleCommands.ALL) return; + Map> claimed = claimedTransitions(root); + Map> carriers = new IdentityHashMap<>(); + List order = new ArrayList<>(); + for (MetaData entity : commandEntities(root)) { + for (MetaData t : Lifecycles.entityTransitions(entity)) { + List list = carriers.get(t); + if (list == null) { list = new ArrayList<>(); carriers.put(t, list); order.add(t); } + list.add(entity); + } + } + for (MetaData t : order) { + List withT = carriers.get(t); + boolean hasPermission = t.hasMetaAttr(ApiConstants.ATTR_PERMISSION); + boolean isPublic = t.hasMetaAttr(ApiConstants.ATTR_PUBLIC) + && Boolean.TRUE.equals(t.getMetaAttr(ApiConstants.ATTR_PUBLIC).getValue()); + if (!hasPermission && !isPublic) continue; + boolean derives = false; + for (MetaData e : withT) if (derivesCommand(claimed, settings, e, t)) derives = true; + if (derives) continue; + String declared = hasPermission + ? "@permission \"" + t.getMetaAttr(ApiConstants.ATTR_PERMISSION).getValue() + "\"" : "@public: true"; + Set claimers = new java.util.LinkedHashSet<>(); + for (MetaData e : withT) { + for (Claim c : claimsOn(claimed, e, t)) { + claimers.add((c.op().getParent() == null ? "" : c.op().getParent().getShortName()) + "." + c.op().getShortName()); + } + } + String why = settings.lifecycleCommands() == RulesSettings.LifecycleCommands.NONE + ? "rules.lifecycle.commands is \"none\": no command is derived from it" + : "it derives no command of its own: it is made only by " + quoteList(claimers) + ", which " + + (claimers.size() == 1 ? "asks" : "ask") + " the policy about " + + (claimers.size() == 1 ? "its" : "their") + " own permission"; + out.add(new Diagnostic(Severity.WARN, WARN_TRANSITION_PERMISSION_SHADOWED, rulesAddress(t), + "transition \"" + t.getShortName() + "\" declares " + declared + ", but " + why + + ", so the attribute is never read. Remove it from the transition, or declare it on the command that makes the transition.")); + } + } + + private static void checkPermissionNames(MetaRoot root, RulesSettings settings, List out) { + if (settings.permissionNames() == RulesSettings.PermissionNames.DERIVE) return; + Severity severity = settings.permissionNames() == RulesSettings.PermissionNames.REQUIRE ? Severity.ERROR : Severity.WARN; + + if (settings.lifecycleCommands() != RulesSettings.LifecycleCommands.NONE) { + Map> claimed = claimedTransitions(root); + for (MetaData entity : commandEntities(root)) { + for (MetaData t : Lifecycles.entityTransitions(entity)) { + if (!derivesCommand(claimed, settings, entity, t)) continue; + if (!needsPermissionName(t)) continue; + out.add(new Diagnostic(severity, WARN_PERMISSION_DERIVED_NAME, + rulesAddress(entity) + "." + (t.getParent() == null ? "" : t.getParent().getShortName()) + "." + t.getShortName(), + "the command derived from transition \"" + t.getShortName() + "\" of \"" + entity.getShortName() + + "\" has no @permission, so it asks the policy about the derived name \"" + + derivedPermissionName(entity, entity.getShortName() + "." + t.getShortName()) + "\", " + advice("transition"))); + } + } + } + + for (MetaData op : operations(root)) { + if (!needsPermissionName(op)) continue; + out.add(new Diagnostic(severity, WARN_PERMISSION_DERIVED_NAME, rulesAddress(op), + "operation." + op.getSubType() + " \"" + op.getShortName() + "\" has no @permission, so it asks the policy about the derived name \"" + + derivedPermissionName(op, op.getShortName()) + "\", " + advice("operation"))); + } + } + + private static String advice(String kind) { + return "which changes if the " + kind + " is renamed. Declare @permission, or @public: true."; + } + + /** The rules gate over a loaded model. */ + public static Result check(MetaRoot root, RulesSettings settings) { + List lifecycles = declaredLifecycles(root); + List ops = operations(root); + if (lifecycles.isEmpty() && ops.isEmpty()) return new Result(new ArrayList<>(), null); + + List diagnostics = new ArrayList<>(); + for (Lifecycle l : lifecycles) checkLifecycle(l, settings, diagnostics); + checkShadowedPermissions(root, settings, diagnostics); + checkPermissionNames(root, settings, diagnostics); + int transitions = 0; + for (Lifecycle l : lifecycles) transitions += l.transitions().size(); + return new Result(diagnostics, new Summary(ops.size(), lifecycles.size(), transitions)); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/RulesTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/api/RulesTypesMetaDataProvider.java new file mode 100644 index 0000000000..1e87661e69 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/api/RulesTypesMetaDataProvider.java @@ -0,0 +1,52 @@ +/* + * 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.api; + +import com.metaobjects.registry.MetaDataRegistry; +import com.metaobjects.registry.MetaDataTypeProvider; +import com.metaobjects.transition.ActionTransition; + +/** + * Business-rules Types MetaData provider (ADR-0030, ADR-0066): the declared API surface + * ({@code api.*}, {@code operation.*}, {@code binding.*}) and lifecycle moves + * ({@code transition.*}, a child of {@code field.enum}). The cross-node rules live in + * {@code loader/RulesValidation}. + */ +public class RulesTypesMetaDataProvider implements MetaDataTypeProvider { + + @Override + public void registerTypes(MetaDataRegistry registry) { + OperationalApi.registerTypes(registry); + CommandOperation.registerTypes(registry); + RestBinding.registerTypes(registry); + ActionTransition.registerTypes(registry); + } + + @Override + public String getProviderId() { + return "rules-types"; + } + + @Override + public String[] getDependencies() { + return new String[]{"core-types"}; + } + + @Override + public String getDescription() { + return "Business-rules Types (api, operation, binding, transition) — ADR-0066"; + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java b/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java index b88617dd51..c481706873 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java +++ b/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java @@ -73,6 +73,7 @@ public final class NeutralConfig { private ApiSettings apiSettings = ApiSettings.DEFAULT; private MigrateSettings migrateSettings = MigrateSettings.DEFAULT; private List requirementsInherit = List.of(); + private RulesSettings rulesSettings = RulesSettings.DEFAULT; private NeutralConfig(List> sources, List> dependencies, List scopeInclude, List migrateScope, @@ -153,6 +154,14 @@ public EnumDefaults getEnumDefaults() { return enumDefaults; } + /** + * ADR-0066 — the business-rules settings ({@code rules} and {@code verify.lifecycle} in this + * file), each absent key at its default. + */ + public RulesSettings getRulesSettings() { + return rulesSettings; + } + /** * The project's {@code api} block ({@code api.pagination}, {@code api.unknownFields}), absent * keys at their defaults (no page size, {@code reject}). Never {@code null}. @@ -378,6 +387,7 @@ public static NeutralConfig parse(String content, String origin) { cfg.apiSettings = parseApi(root.get("api"), origin); cfg.migrateSettings = parseMigrateSettings(root.get("migrate")); cfg.requirementsInherit = parseRequirementsInherit(root.get("requirements"), origin); + cfg.rulesSettings = parseRulesSettings(root.get("rules"), root.get("verify"), origin); return cfg; } @@ -566,6 +576,83 @@ private static List parseScopeInclude(JsonElement scope, String origin) return stringArray(include, "scope.include", origin); } + /** ADR-0066 — one nested settings object, or {@code null} when absent; refused unless an object with only {@code allowed} keys. */ + private static JsonObject settingsBlock(JsonObject parent, String key, String path, java.util.List allowed, + String origin) { + JsonElement el = parent.get(key); + if (el == null) return null; + if (!el.isJsonObject()) throw bad(origin + ": \"" + path + "\" must be an object"); + for (String k : el.getAsJsonObject().keySet()) { + if (!allowed.contains(k)) { + throw bad(origin + ": \"" + path + "\" has unknown key \"" + k + "\"; expected " + + String.join(", ", allowed.stream().map(a -> "\"" + a + "\"").toList())); + } + } + return el.getAsJsonObject(); + } + + /** One closed-set string setting at {@code path}, or {@code null} when absent; a wrong value is refused. */ + private static E settingValue(JsonObject block, String key, String path, java.util.function.Function of, + String expected, String origin) { + if (block == null) return null; + JsonElement el = block.get(key); + if (el == null) return null; + E value = el.isJsonPrimitive() && el.getAsJsonPrimitive().isString() ? of.apply(el.getAsString()) : null; + if (value == null) throw bad(origin + ": \"" + path + "\" must be one of " + expected); + return value; + } + + /** The {@code verify.handEdits} key and its values (read by the TypeScript {@code meta verify}). */ + private static final String VERIFY_KEY_HAND_EDITS = "handEdits"; + private static final List HAND_EDITS_POLICIES = List.of("fail", "notice"); + + /** ADR-0066 — the {@code rules} and {@code verify} blocks; see {@link #getRulesSettings()}. */ + private static RulesSettings parseRulesSettings(JsonElement rules, JsonElement verify, String origin) { + RulesSettings d = RulesSettings.DEFAULT; + RulesSettings.PermissionNames names = null; + RulesSettings.LifecycleCreate create = null; + RulesSettings.LifecycleCommands commands = null; + RulesSettings.LifecycleUnreachable unreachable = null; + if (rules != null) { + if (!rules.isJsonObject()) throw bad(origin + ": \"rules\" must be an object"); + JsonObject rulesObj = rules.getAsJsonObject(); + for (String k : rulesObj.keySet()) { + if (!k.equals("permissions") && !k.equals("lifecycle")) { + throw bad(origin + ": \"rules\" has unknown key \"" + k + "\"; expected \"permissions\" and/or \"lifecycle\""); + } + } + JsonObject perms = settingsBlock(rulesObj, "permissions", "rules.permissions", List.of("names"), origin); + names = settingValue(perms, "names", "rules.permissions.names", RulesSettings.PermissionNames::of, + "\"derive\", \"advise\", \"require\"", origin); + JsonObject life = settingsBlock(rulesObj, "lifecycle", "rules.lifecycle", List.of("create", "commands"), origin); + create = settingValue(life, "create", "rules.lifecycle.create", RulesSettings.LifecycleCreate::of, + "\"initial\", \"any\"", origin); + commands = settingValue(life, "commands", "rules.lifecycle.commands", RulesSettings.LifecycleCommands::of, + "\"unclaimed\", \"all\", \"none\"", origin); + } + if (verify != null) { + if (!verify.isJsonObject()) throw bad(origin + ": \"verify\" must be an object"); + JsonObject verifyObj = verify.getAsJsonObject(); + for (String k : verifyObj.keySet()) { + if (!k.equals("lifecycle") && !k.equals(VERIFY_KEY_HAND_EDITS)) { + throw bad(origin + ": \"verify\" has unknown key \"" + k + "\"; expected \"handEdits\" and/or \"lifecycle\""); + } + } + // `verify.handEdits` is read by the TypeScript `meta verify` only (this port's verify + // already fails on any hand edit); it is validated here so `meta init`'s file loads. + JsonElement handEdits = verifyObj.get(VERIFY_KEY_HAND_EDITS); + if (handEdits != null && !(handEdits.isJsonPrimitive() && handEdits.getAsJsonPrimitive().isString() + && HAND_EDITS_POLICIES.contains(handEdits.getAsString()))) { + throw bad(origin + ": \"verify.handEdits\" must be one of \"fail\", \"notice\""); + } + JsonObject life = settingsBlock(verifyObj, "lifecycle", "verify.lifecycle", List.of("unreachable"), origin); + unreachable = settingValue(life, "unreachable", "verify.lifecycle.unreachable", + RulesSettings.LifecycleUnreachable::of, "\"warn\", \"error\", \"off\"", origin); + } + return new RulesSettings(names != null ? names : d.permissionNames(), create != null ? create : d.lifecycleCreate(), + commands != null ? commands : d.lifecycleCommands(), unreachable != null ? unreachable : d.lifecycleUnreachable()); + } + /** * FR-023 — {@code requirements.inherit}. Refused like {@code naming}: an unknown key inside * {@code requirements} would otherwise be a misspelt {@code inherit} that silently leaves the diff --git a/server/java/metadata/src/main/java/com/metaobjects/config/RulesSettings.java b/server/java/metadata/src/main/java/com/metaobjects/config/RulesSettings.java new file mode 100644 index 0000000000..3b40feba8b --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/config/RulesSettings.java @@ -0,0 +1,79 @@ +/* + * 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.config; + +import java.util.Locale; + +/** + * ADR-0066 — the project settings the business-rules vocabulary reads, from the {@code rules} + * and {@code verify} blocks of {@code .metaobjects/config.json}. Every port reads the same keys + * with the same defaults. A key that is absent takes its default, which is always the behaviour a + * project had before the setting existed: no project declared an operation or a transition + * before 1.3.0, so every default here is the safe one. + * + * @param permissionNames {@code rules.permissions.names} + * @param lifecycleCreate {@code rules.lifecycle.create}: read and validated, changes nothing yet + * @param lifecycleCommands {@code rules.lifecycle.commands} + * @param lifecycleUnreachable {@code verify.lifecycle.unreachable} + */ +public record RulesSettings(PermissionNames permissionNames, LifecycleCreate lifecycleCreate, + LifecycleCommands lifecycleCommands, LifecycleUnreachable lifecycleUnreachable) { + + public static final RulesSettings DEFAULT = new RulesSettings( + PermissionNames.DERIVE, LifecycleCreate.INITIAL, LifecycleCommands.UNCLAIMED, LifecycleUnreachable.WARN); + + /** {@code derive} (default) says nothing, {@code advise} warns, {@code require} fails the build. */ + public enum PermissionNames { + DERIVE, ADVISE, REQUIRE; + + public String wireName() { return name().toLowerCase(Locale.ROOT); } + + public static PermissionNames of(String s) { return parse(values(), s); } + } + + /** Whether a create may start a row in any state ({@code any}) or only the initial one ({@code initial}, default). */ + public enum LifecycleCreate { + INITIAL, ANY; + + public String wireName() { return name().toLowerCase(Locale.ROOT); } + + public static LifecycleCreate of(String s) { return parse(values(), s); } + } + + /** Which transitions derive a command of their own: {@code unclaimed} (default), {@code all} or {@code none}. */ + public enum LifecycleCommands { + UNCLAIMED, ALL, NONE; + + public String wireName() { return name().toLowerCase(Locale.ROOT); } + + public static LifecycleCommands of(String s) { return parse(values(), s); } + } + + /** Severity of an unreachable state or transition: {@code warn} (default), {@code error} or {@code off}. */ + public enum LifecycleUnreachable { + WARN, ERROR, OFF; + + public String wireName() { return name().toLowerCase(Locale.ROOT); } + + public static LifecycleUnreachable of(String s) { return parse(values(), s); } + } + + /** The constant whose wire name is {@code s}, or {@code null}. */ + private static > E parse(E[] values, String s) { + for (E e : values) if (e.name().toLowerCase(Locale.ROOT).equals(s)) return e; + return null; + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/config/SharedModel.java b/server/java/metadata/src/main/java/com/metaobjects/config/SharedModel.java index 4be477c50d..435b2424c3 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/config/SharedModel.java +++ b/server/java/metadata/src/main/java/com/metaobjects/config/SharedModel.java @@ -322,7 +322,7 @@ private static List checkClosure(MetaData root, List selected, S // ADR-0039 sanctioned own-only case: an INHERITED ref-bearing attr belongs to the // base node's own layer and is checked when the base itself is walked. for (MetaAttribute attr : node.getMetaAttrs(false)) { - if (!References.REF_BEARING_ATTR_NAMES.contains(attr.getName())) continue; + if (!References.isRefBearingAttr(node, attr.getName())) continue; Object value = attr.getValue(); if (value instanceof String s) candidates.add(s); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/References.java b/server/java/metadata/src/main/java/com/metaobjects/loader/References.java index 8c03796b33..cbfb0bec0c 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/References.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/References.java @@ -37,7 +37,16 @@ private References() {} /** ADR-0059 R4 — the inline attribute names whose value is an object reference. */ public static final Set REF_BEARING_ATTR_NAMES = Set.of( "objectRef", "through", "references", "from", "via", "of", - "parameterRef", "payloadRef", "responseRef", "spine"); + "parameterRef", "payloadRef", "responseRef", "spine", "inputRef", "outputRef"); + + /** + * True when {@code attrName} on {@code node} holds an object reference: in + * {@link #REF_BEARING_ATTR_NAMES}, and not on a {@code transition.*}, whose {@code @from} + * lists members of its enum (ADR-0066). + */ + public static boolean isRefBearingAttr(MetaData node, String attrName) { + return REF_BEARING_ATTR_NAMES.contains(attrName) && !"transition".equals(node.getType()); + } /** A parent-relative reference with more {@code ..::} than its referrer's package has segments. */ public static final class OverDropException extends RuntimeException { @@ -264,7 +273,7 @@ private static void visit(MetaRoot root, MetaData node) { // ADR-0039: own — this pass rewrites the declared-here layer; an inherited attribute // is resolved once, on the node that declares it. for (MetaAttribute attr : new ArrayList<>(node.getMetaAttrs(false))) { - if (REF_BEARING_ATTR_NAMES.contains(attr.getName())) resolveAttr(root, node, attr, declPkg); + if (isRefBearingAttr(node, attr.getName())) resolveAttr(root, node, attr, declPkg); } } // ADR-0039: own — structural walk over the physical declaration tree. 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 new file mode 100644 index 0000000000..a1fb9e223a --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java @@ -0,0 +1,500 @@ +/* + * 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.MetaData; +import com.metaobjects.MetaDataException; +import com.metaobjects.MetaRoot; +import com.metaobjects.api.ApiConstants; +import com.metaobjects.api.Lifecycles; +import com.metaobjects.field.EnumField; +import com.metaobjects.field.MetaField; +import com.metaobjects.object.MetaObject; +import com.metaobjects.source.MetaSource; +import com.metaobjects.transition.TransitionConstants; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * ADR-0066 — cross-node rules for operations (slice A) and lifecycles (slice B). Every port + * implements the same rules WITH THE SAME MESSAGE TEXT; the TypeScript + * {@code rules-validation.ts} is the reference and {@code fixtures/conformance/error-rules-*} + * (with the positive {@code rules-*} cases) are the contract. + * + *

One broken rule yields one error: each error's source is the offending node (the + * transition, the enum field (L3), the entity (L2b), the operation or the binding); an + * operation that fails O1 is not checked further, one whose target fails O2 or O3 is not + * checked for O4 or B1; and an error is reported once per (node, code), so a broken transition + * on an abstract base is reported once, not once per inheritor.

+ * + *

Rules: L1 and L2 {@code ERR_TRANSITION_NOT_ON_ENTITY}; L3 {@code ERR_LIFECYCLE_NO_INITIAL}; + * L4 {@code ERR_TRANSITION_UNKNOWN_STATE}; L5, L6 and O0 {@code ERR_TRANSITION_NAME_COLLISION}; + * L7 and O5 {@code ERR_BAD_ATTR_VALUE}; P1 {@code ERR_PERMISSION_PUBLIC_CONFLICT}; P2 {@code ERR_BAD_ATTR_VALUE} (@permission shape); O1 + * {@code ERR_OPERATION_SHAPE}; O2 {@code ERR_OPERATION_TARGET_UNRESOLVED}; O3 + * {@code ERR_OPERATION_TARGET_MISMATCH}; O4 {@code ERR_OPERATION_UNKNOWN_TRANSITION}; B1 + * {@code ERR_BINDING_PATH_MISMATCH}.

+ */ +final class RulesValidation { + + private RulesValidation() { + } + + private static final Set RESERVED = new LinkedHashSet<>(ApiConstants.RESERVED_OPERATION_NAMES); + private static final String RESERVED_LIST = String.join(", ", ApiConstants.RESERVED_OPERATION_NAMES); + private static final Set RESERVED_CODES = new LinkedHashSet<>(ApiConstants.RESERVED_ERROR_CODES); + private static final Pattern PLACEHOLDER = Pattern.compile("\\{([^}]*)\\}"); + + /** A derived name is compared without case: a command, a permission constant or a file named from it collides on a case-folding target. */ + private static boolean isReservedName(String name) { + return RESERVED.contains(name.toLowerCase(java.util.Locale.ROOT)); + } + + /** {@code "Entity.field.transition"} for a transition, {@code "Api.operation"} for an operation. */ + private static String label(MetaData node) { + List parts = new ArrayList<>(); + // A binding is unnamed (its parser-generated name is not shown): its label is its operation's. + for (MetaData n = node; n != null && n.getParent() != null; n = n.getParent()) { + String name = n.getShortName(); + if (name == null || name.isEmpty() || n.isAutoNamed()) continue; + parts.add(0, name); + } + return String.join(".", parts); + } + + private static String quoteList(Collection xs) { + List q = new ArrayList<>(); + for (String x : xs) q.add("\"" + x + "\""); + return String.join(", ", q); + } + + private static final class Sink { + final List errors = new ArrayList<>(); + private final Map> seen = new IdentityHashMap<>(); + + void add(MetaData node, ErrorCode code, String message) { + if (!seen.computeIfAbsent(node, k -> EnumSet.noneOf(ErrorCode.class)).add(code)) return; + errors.add(new MetaDataException(message, code, node.getSource())); + } + } + + /** P1 and P2 for an operation or a transition. */ + private static void checkPermission(MetaData node, Sink sink) { + boolean isPublic = node.hasMetaAttr(ApiConstants.ATTR_PUBLIC) + && Boolean.TRUE.equals(node.getMetaAttr(ApiConstants.ATTR_PUBLIC).getValue()); + if (isPublic && node.hasMetaAttr(ApiConstants.ATTR_PERMISSION)) { + sink.add(node, ErrorCode.ERR_PERMISSION_PUBLIC_CONFLICT, + node.getType() + "." + node.getSubType() + " \"" + label(node) + + "\" declares both @public: true and @permission; a public " + node.getType() + + " calls no permission check, so remove one."); + } + String permission = Lifecycles.stringValue(node, ApiConstants.ATTR_PERMISSION); + if (permission != null && !ApiConstants.PERMISSION_NAME_PATTERN.matcher(permission).matches()) { + sink.add(node, ErrorCode.ERR_BAD_ATTR_VALUE, + node.getType() + "." + node.getSubType() + " \"" + label(node) + "\" @permission \"" + permission + + "\" is not a dotted identifier path; use names of letters, digits and _ joined by \".\" " + + "(a package prefix may use \"::\"), such as \"purchasing.approve\"."); + } + } + + /** L1, L3, L4, L5, L7 and P1 for the transitions declared on one field. */ + private static void checkDeclaredTransitions(MetaData field, Sink sink) { + List declared = new ArrayList<>(); + // ADR-0039: own — each transition is checked where it is declared. + for (MetaData c : field.getChildren(MetaData.class, false)) { + if (TransitionConstants.TYPE_TRANSITION.equals(c.getType()) + && TransitionConstants.SUBTYPE_ACTION.equals(c.getSubType())) declared.add(c); + } + if (declared.isEmpty()) return; + MetaData owner = field.getParent(); + if (!Lifecycles.isEntity(owner)) { + String where = owner == null || !MetaObject.TYPE_OBJECT.equals(owner.getType()) + ? "the document root" : "object." + owner.getSubType() + " \"" + owner.getShortName() + "\""; + for (MetaData t : declared) { + sink.add(t, ErrorCode.ERR_TRANSITION_NOT_ON_ENTITY, + "transition.action \"" + label(t) + "\" is declared on a field of " + where + + "; a lifecycle belongs to an object.entity with a writable source."); + } + return; + } + if (EnumField.SUBTYPE_ENUM.equals(field.getSubType()) + && Lifecycles.stringValue(field, MetaField.ATTR_DEFAULT) == null) { + sink.add(field, ErrorCode.ERR_LIFECYCLE_NO_INITIAL, + "field.enum \"" + label(field) + "\" declares transitions but no @default; its @default is the lifecycle's initial state."); + } + // ADR-0039: RESOLVING array-ness (isArrayType), never the own-only native flag. + if (field instanceof MetaField mf && mf.isArrayType()) { + sink.add(field, ErrorCode.ERR_BAD_ATTR_VALUE, + "field." + field.getSubType() + " \"" + label(field) + + "\" declares transitions but is an array (@isArray: true); a lifecycle's state is one value."); + } + Set states = new LinkedHashSet<>(Lifecycles.stringList(field, EnumField.ATTR_VALUES)); + for (MetaData t : declared) { + checkPermission(t, sink); + if (Lifecycles.transitionFrom(t).isEmpty()) { + sink.add(t, ErrorCode.ERR_BAD_ATTR_VALUE, + "transition.action \"" + label(t) + "\" @from is empty; name at least one state the transition leaves."); + } + String to = Lifecycles.transitionTo(t); + Set mentioned = new LinkedHashSet<>(Lifecycles.transitionFrom(t)); + if (to != null) mentioned.add(to); + List unknown = new ArrayList<>(); + for (String s : mentioned) if (!states.contains(s)) unknown.add(s); + if (!unknown.isEmpty()) { + sink.add(t, ErrorCode.ERR_TRANSITION_UNKNOWN_STATE, + "transition.action \"" + label(t) + "\" names " + quoteList(unknown) + ", which " + + (unknown.size() == 1 ? "is not a member" : "are not members") + " of \"" + field.getShortName() + + "\" @values (" + quoteList(states) + ")."); + } + if (isReservedName(t.getShortName())) { + sink.add(t, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + "transition.action \"" + label(t) + "\" is named \"" + t.getShortName() + + "\", which is a derived CRUD verb (" + RESERVED_LIST + "); rename it."); + } + if (t.hasMetaAttr(TransitionConstants.ATTR_CONDITION)) { + // L7 reuses the cross-field validator's @condition grammar check. + String message = ValidationPhase.conditionMessage( + t.getMetaAttr(TransitionConstants.ATTR_CONDITION).getValue(), (MetaObject) owner, + "transition.action \"" + label(t) + "\" @condition"); + if (message != null) sink.add(t, ErrorCode.ERR_BAD_ATTR_VALUE, message); + } + } + } + + /** Every field declared in the tree: at the root and on every object. */ + private static List declaredFields(MetaData root) { + List out = new ArrayList<>(); + // ADR-0039: own — a structural walk over the declarations themselves. + for (MetaData top : root.getChildren(MetaData.class, false)) { + if (MetaField.TYPE_FIELD.equals(top.getType())) { + out.add(top); + } else if (MetaObject.TYPE_OBJECT.equals(top.getType())) { + for (MetaData c : top.getChildren(MetaData.class, false)) { + if (MetaField.TYPE_FIELD.equals(c.getType())) out.add(c); + } + } + } + return out; + } + + /** + * L10: an entity's field named like an ancestor's lifecycle field that does not carry that + * lifecycle's transitions. Redeclaring the field replaces it, so the base's state machine + * would silently stop applying to this entity. + */ + private static void checkRedeclaredLifecycles(MetaData entity, Sink sink) { + List lineage = Lifecycles.entityLineage(entity); + for (MetaData ancestor : lineage.subList(1, lineage.size())) { + // ADR-0039: own — the lifecycle fields the ancestor itself declares. + for (MetaData baseField : ancestor.getChildren(MetaData.class, false)) { + if (!MetaField.TYPE_FIELD.equals(baseField.getType())) continue; + List baseTransitions = Lifecycles.lifecycleTransitionsOf(ancestor, baseField); + if (baseTransitions.isEmpty()) continue; + MetaData field = null; + for (MetaData c : entity.getChildren(MetaData.class, true)) { + if (MetaField.TYPE_FIELD.equals(c.getType()) && c.getShortName().equals(baseField.getShortName())) { field = c; break; } + } + if (field == null || field == baseField) continue; + List kept = Lifecycles.lifecycleTransitionsOf(entity, field); + boolean all = true; + for (MetaData t : baseTransitions) if (!Lifecycles.containsIdentity(kept, t)) all = false; + if (all) continue; + sink.add(field, ErrorCode.ERR_LIFECYCLE_REDECLARED, + "field." + field.getSubType() + " \"" + label(field) + "\" redeclares \"" + label(baseField) + + "\", which has a lifecycle, and drops its transitions; extend it (\"extends\": \"" + + ancestor.getShortName() + "." + baseField.getShortName() + "\") or give the field another name."); + } + } + } + + /** L2, L6 and L10 for one entity, over its effective (inherited) lifecycles. */ + private static void checkEntityLifecycles(MetaData entity, Sink sink) { + checkRedeclaredLifecycles(entity, sink); + List transitions = Lifecycles.entityTransitions(entity); + if (transitions.isEmpty()) return; + Map byName = new java.util.LinkedHashMap<>(); + for (MetaData t : transitions) { + MetaData first = byName.putIfAbsent(t.getShortName().toLowerCase(java.util.Locale.ROOT), t); + if (first != null && first != t) { + sink.add(t, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + "transition.action \"" + label(t) + "\" has the same name as \"" + label(first) + + "\" (names are compared without case); the transitions of \"" + entity.getShortName() + + "\" share one namespace (each may derive a command), so rename one."); + } + } + boolean writable = false; + for (MetaData c : entity.getChildren(MetaData.class, true)) { + if (c instanceof MetaSource src && src.isWritable()) { writable = true; break; } + } + if (!Lifecycles.isAbstract(entity) && Lifecycles.lifecycleIsLive(entity) && !writable) { + Set fields = new LinkedHashSet<>(); + for (MetaData t : transitions) fields.add(t.getParent() == null ? "" : t.getParent().getShortName()); + 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.)"); + } + } + + private static String objectKind(MetaData node) { + return node == null ? "names no object" : "is an object." + node.getSubType(); + } + + /** O0-O5, P1 and B1 for one operation. */ + private static void checkOperation(MetaData op, Sink sink) { + String head = "operation." + op.getSubType() + " \"" + label(op) + "\""; + if (isReservedName(op.getShortName())) { + sink.add(op, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + head + " is named \"" + op.getShortName() + "\", which is a derived CRUD verb (" + RESERVED_LIST + "); rename it."); + } + checkPermission(op, sink); + + List errorCodes = Lifecycles.stringList(op, ApiConstants.ATTR_ERRORS); + List bad = new ArrayList<>(); + List dup = new ArrayList<>(); + for (int i = 0; i < errorCodes.size(); i++) { + String c = errorCodes.get(i); + if (!ApiConstants.BUSINESS_ERROR_CODE_PATTERN.matcher(c).matches()) bad.add(c); + if (errorCodes.indexOf(c) != i) dup.add(c); + } + Set reserved = new LinkedHashSet<>(); + for (String c : errorCodes) if (RESERVED_CODES.contains(c)) reserved.add(c); + if (!bad.isEmpty() || !dup.isEmpty() || !reserved.isEmpty()) { + String why; + if (!bad.isEmpty()) { + why = quoteList(bad) + " " + (bad.size() == 1 ? "is not a" : "are not") + " lower snake case code" + + (bad.size() == 1 ? "" : "s"); + } else if (!dup.isEmpty()) { + Set uniq = new LinkedHashSet<>(dup); + why = quoteList(uniq) + " " + (uniq.size() == 1 ? "is" : "are") + " listed twice"; + } else { + why = quoteList(reserved) + " " + (reserved.size() == 1 ? "is a code" : "are codes") + + " the route answers itself (" + String.join(", ", ApiConstants.RESERVED_ERROR_CODES) + ")"; + } + 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; + } + } + + // O2, O3 — the target. + Lifecycles.DerivedTarget derivedTarget = Lifecycles.deriveOperationTarget(op); + MetaData derived = derivedTarget == null ? null : derivedTarget.entity(); + MetaData target = derived; + String objectRef = Lifecycles.stringValue(op, ApiConstants.ATTR_OBJECT_REF); + if (objectRef != null) { + MetaData declared = Lifecycles.resolveObjectOn(op, objectRef); + if (declared == null || !MetaObject.SUBTYPE_ENTITY.equals(declared.getSubType())) { + sink.add(op, ErrorCode.ERR_OPERATION_TARGET_UNRESOLVED, + head + " @objectRef \"" + objectRef + "\" " + objectKind(declared) + "; an operation acts on an object.entity."); + return; + } + if (derived != null && derived != declared) { + sink.add(op, ErrorCode.ERR_OPERATION_TARGET_MISMATCH, + head + " @objectRef names \"" + declared.getShortName() + "\", but its input and output derive \"" + + derived.getShortName() + "\"; remove @objectRef or make them agree."); + return; + } + target = declared; + } + List transitions = ApiConstants.OPERATION_SUBTYPE_COMMAND.equals(op.getSubType()) + ? Lifecycles.stringList(op, ApiConstants.ATTR_TRANSITIONS) : Collections.emptyList(); + if (!transitions.isEmpty() && target == null) { + sink.add(op, ErrorCode.ERR_OPERATION_TARGET_UNRESOLVED, + "operation.command \"" + label(op) + "\" lists @transitions but has no target entity: the @inputRef does not borrow one entity's whole primary key (each key field extended exactly once), no @outputRef has a base entity, and there is no @objectRef."); + return; + } + + // O4 — the transitions it may make. + if (target != null && !transitions.isEmpty()) { + Set known = new LinkedHashSet<>(); + for (MetaData t : Lifecycles.entityTransitions(target)) known.add(t.getShortName()); + List unknown = new ArrayList<>(); + for (String n : new LinkedHashSet<>(transitions)) if (!known.contains(n)) unknown.add(n); + if (!unknown.isEmpty()) { + sink.add(op, ErrorCode.ERR_OPERATION_UNKNOWN_TRANSITION, + "operation.command \"" + label(op) + "\" @transitions names " + quoteList(unknown) + ", which " + + (unknown.size() == 1 ? "is not a transition" : "are not transitions") + " of \"" + target.getShortName() + "\"."); + } + } + + // B1 — binding paths. + // 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_REST.equals(b.getSubType())) continue; + String path = Lifecycles.stringValue(b, ApiConstants.ATTR_PATH); + if (path == null) continue; + List placeholders = new ArrayList<>(); + Matcher m = PLACEHOLDER.matcher(path); + while (m.find()) placeholders.add(m.group(1)); + List expected = target != null && Lifecycles.operationIsKeyed(op) + ? Lifecycles.primaryKeyFields(target) : new ArrayList<>(); + List a = new ArrayList<>(placeholders); + List e = new ArrayList<>(expected); + Collections.sort(a); + Collections.sort(e); + if (!a.equals(e)) { + sink.add(b, ErrorCode.ERR_BINDING_PATH_MISMATCH, + "binding.rest on \"" + label(b) + "\" @path \"" + path + "\" has placeholders [" + quoteList(placeholders) + "]; " + + (expected.isEmpty() + ? "\"" + label(op) + "\" addresses no row by key, so its path takes none." + : "\"" + label(op) + "\" addresses one \"" + target.getShortName() + + "\" by key, so its path takes exactly [" + quoteList(expected) + "].")); + } + } + } + + /** ADR-0066 — the rules pass. Runs after reference-bearing validation. */ + static List validate(MetaRoot root) { + Sink sink = new Sink(); + for (MetaData field : declaredFields(root)) checkDeclaredTransitions(field, sink); + for (MetaData obj : root.getChildren(MetaData.class, true)) { + if (Lifecycles.isEntity(obj)) checkEntityLifecycles(obj, sink); + } + // O6 — keyed by package, then by the name without case. + Map byName = new java.util.HashMap<>(); + for (MetaData api : root.getChildren(MetaData.class, true)) { + if (!ApiConstants.TYPE_API.equals(api.getType())) continue; + List ops = new ArrayList<>(); + for (MetaData op : api.getChildren(MetaData.class, true)) { + if (ApiConstants.TYPE_OPERATION.equals(op.getType())) ops.add(op); + } + for (MetaData op : ops) checkOperation(op, sink); + for (MetaData op : ops) { + String pkg = References.effectivePackageOf(api); + String key = pkg + "\u0000" + op.getShortName().toLowerCase(java.util.Locale.ROOT); + MetaData first = byName.putIfAbsent(key, op); + if (first != null && first != op && !sameOperation(first, op)) { + sink.add(op, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + "operation." + op.getSubType() + " \"" + label(op) + "\" has the same name as \"" + label(first) + + "\" (names are compared without case) and is not the same operation; the operations of package \"" + pkg + + "\" share one namespace (each derives the permission name .), so rename one, or declare both identically to expose one operation in two APIs."); + } + } + checkApiRoutes(ops, sink); + } + return sink.errors; + } + + /** A reference attr's identity: the node it resolves to, else the raw value. */ + private static Object refIdentity(MetaData op, String attr) { + String ref = Lifecycles.stringValue(op, attr); + if (ref == null) return null; + MetaData node = Lifecycles.resolveObjectOn(op, ref); + return node != null ? node : ref; + } + + /** A list attr as a set, for comparison. */ + private static Set setKey(MetaData op, String attr) { + return new java.util.TreeSet<>(Lifecycles.stringList(op, attr)); + } + + private static boolean flag(MetaData op, String attr) { + return op.hasMetaAttr(attr) && Boolean.TRUE.equals(op.getMetaAttr(attr).getValue()); + } + + /** + * Whether two operations of one package in different APIs are one operation exposed twice (a + * versioned API beside its successor, ADR-0067 section 2): same name and subtype and the same + * contract. Bindings are per API and are not compared. + */ + private static boolean sameOperation(MetaData a, MetaData b) { + if (!a.getShortName().equals(b.getShortName()) || !a.getSubType().equals(b.getSubType())) return false; + for (String attr : List.of(ApiConstants.ATTR_INPUT_REF, ApiConstants.ATTR_OUTPUT_REF, ApiConstants.ATTR_OBJECT_REF)) { + Object x = refIdentity(a, attr); + Object y = refIdentity(b, attr); + // A resolved node compares by identity, a raw string by value. + boolean same = x instanceof String xs ? xs.equals(y) : x == y; + if (!same) return false; + } + for (String attr : List.of(ApiConstants.ATTR_TRANSITIONS, ApiConstants.ATTR_ERRORS)) { + if (!setKey(a, attr).equals(setKey(b, attr))) return false; + } + return java.util.Objects.equals(Lifecycles.stringValue(a, ApiConstants.ATTR_PERMISSION), + Lifecycles.stringValue(b, ApiConstants.ATTR_PERMISSION)) + && flag(a, ApiConstants.ATTR_PUBLIC) == flag(b, ApiConstants.ATTR_PUBLIC) + && flag(a, ApiConstants.ATTR_MANY) == flag(b, ApiConstants.ATTR_MANY); + } + + /** B2 across the operations of one API. */ + private static void checkApiRoutes(List ops, Sink sink) { + Map byRoute = new java.util.HashMap<>(); + for (MetaData op : ops) { + // 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_REST.equals(b.getSubType())) continue; + String path = Lifecycles.stringValue(b, ApiConstants.ATTR_PATH); + if (path == null) continue; + // The effective method: the declared one, else the derived (ADR-0066 section 1). + String declared = Lifecycles.stringValue(b, ApiConstants.ATTR_METHOD); + String method = declared != null ? declared + : ApiConstants.OPERATION_SUBTYPE_COMMAND.equals(op.getSubType()) ? "POST" : "GET"; + String route = method + " " + PLACEHOLDER.matcher(path).replaceAll("{}"); + MetaData other = byRoute.putIfAbsent(route, b); + if (other != null) { + sink.add(b, ErrorCode.ERR_BINDING_PATH_MISMATCH, + "binding.rest on \"" + label(b) + "\" declares " + method + " \"" + path + + "\", the same route as the binding on \"" + label(other) + + "\"; two operations cannot share a method and path."); + } + } + } + } +} 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 d501356d0f..8f0df29b6f 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 @@ -199,6 +199,10 @@ public static void run(MetaRoot root, MetaDataLoader loader) { pass(collected, () -> validateDiscriminator(root)); // FR-015 — source.rdb @parameterRef typed-input rules. pass(collected, () -> validateSourceParameterRef(root)); + // ADR-0066 — business rules: operations and lifecycles (L1-L7, P1, P2, O0-O6, B1). Run + // before the primary-source pass, as the TypeScript loader orders them: a lifecycle on an + // entity whose only source is read-only yields L2 first, then the source error. + pass(collected, () -> collected.addAll(RulesValidation.validate(root))); pass(collected, () -> validateOnePrimarySource(root)); // #208 — DDL-ownership escape valves (@sql/@unmanaged on source.rdb). // Sibling of the source-role pass above; must run after it. @@ -2514,29 +2518,40 @@ static void validateCrossFieldValidators(MetaRoot root, List } if (!v.hasMetaAttr(com.metaobjects.validator.MetaValidator.ATTR_CONDITION)) continue; Object condition = v.getMetaAttr(com.metaobjects.validator.MetaValidator.ATTR_CONDITION).getValue(); - java.util.TreeSet unknown = new java.util.TreeSet<>(); - collectExprFieldRefs(condition, unknown); - unknown.removeAll(fields.keySet()); - if (!unknown.isEmpty()) { - StringBuilder names = new StringBuilder(); - for (String u : unknown) names.append(names.length() == 0 ? "" : ", ").append('"').append(u).append('"'); - out.add(new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": validator." + label + " @condition names " + names - + ", which " + (unknown.size() == 1 ? "is not a field" : "are not fields") - + " of \"" + obj.getShortName() + "\".", - ErrorCode.ERR_BAD_ATTR_VALUE, v.getSource())); - continue; - } - String problem = conditionProblem(condition, fields); - if (problem != null) { + String conditionError = conditionMessage(condition, obj, + "validator." + label + " @condition"); + if (conditionError != null) { out.add(new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": validator." + label + " @condition " + problem, + ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": " + conditionError, ErrorCode.ERR_BAD_ATTR_VALUE, v.getSource())); } } } } + /** + * Why a {@code @condition} (the attr.expression grammar) over {@code obj}'s own fields is + * refused, or {@code null} when it is legal. {@code label} opens the message. One rule for a + * cross-field validator's condition and a transition's guard (ADR-0066): every named field + * is a field of {@code obj}, and the expression passes {@link #conditionProblem}. Mirrors TS + * {@code conditionMessage}. + */ + static String conditionMessage(Object condition, MetaObject obj, String label) { + java.util.Map> fields = new java.util.LinkedHashMap<>(); + for (MetaField f : obj.getMetaFields()) fields.put(f.getShortName(), f); + java.util.TreeSet unknown = new java.util.TreeSet<>(); + collectExprFieldRefs(condition, unknown); + unknown.removeAll(fields.keySet()); + if (!unknown.isEmpty()) { + StringBuilder names = new StringBuilder(); + for (String u : unknown) names.append(names.length() == 0 ? "" : ", ").append('"').append(u).append('"'); + return label + " names " + names + ", which " + (unknown.size() == 1 ? "is not a field" : "are not fields") + + " of \"" + obj.getShortName() + "\"."; + } + String problem = conditionProblem(condition, fields); + return problem == null ? null : label + " " + problem; + } + /** What a literal compared with a field.duration must be. */ private static final String DURATION_LITERAL_FORM = "an ISO-8601 duration (such as PT1H30M; no years or months)"; diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java index 84d7640288..a08c550560 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java @@ -285,7 +285,7 @@ protected MetaData createOrOverlayMetaData( boolean isRoot, } // Auto-naming only allowed for the types in isAutoNamingType (validator, view, - // source, identity) and not abstract at root. + // source, identity, origin, binding) and not abstract at root. if (isAutoNamingType(typeName) && !(isRoot && Boolean.TRUE.equals(isAbstract))) { // Generate sequential name based on subtype if available, otherwise use type @@ -929,7 +929,9 @@ public static boolean isAutoNamingType(String typeName) { || MetaView.TYPE_VIEW.equals(typeName) || MetaSource.TYPE_SOURCE.equals(typeName) || MetaIdentity.TYPE_IDENTITY.equals(typeName) - || MetaOrigin.TYPE_ORIGIN.equals(typeName); + || MetaOrigin.TYPE_ORIGIN.equals(typeName) + // ADR-0030: a binding names no one; it is addressed through its operation. + || com.metaobjects.api.ApiConstants.TYPE_BINDING.equals(typeName); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java b/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java index d1bcb81814..52ee65ddd4 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java +++ b/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java @@ -265,6 +265,7 @@ public static List metamodelProviders() { new com.metaobjects.index.IndexTypesMetaDataProvider(), new com.metaobjects.requirement.RequirementTypesMetaDataProvider(), new com.metaobjects.reporting.ReportingTypesMetaDataProvider(), + new com.metaobjects.api.RulesTypesMetaDataProvider(), new com.metaobjects.database.CoreDBMetaDataProvider(), new com.metaobjects.source.SourceTypesMetaDataProvider(), new com.metaobjects.origin.OriginTypesMetaDataProvider(), diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/spec/SpecMetamodelReader.java b/server/java/metadata/src/main/java/com/metaobjects/registry/spec/SpecMetamodelReader.java index c123a4c99b..2afef7757c 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/registry/spec/SpecMetamodelReader.java +++ b/server/java/metadata/src/main/java/com/metaobjects/registry/spec/SpecMetamodelReader.java @@ -66,12 +66,12 @@ public final class SpecMetamodelReader { /** Classpath directory the metadata jar embeds the spec files under. */ public static final String EMBED_DIR = "spec/metamodel"; - /** The 19 shared provider-definition file names (keep in lockstep with {@code spec/metamodel/}). */ + /** The 21 shared provider-definition file names (keep in lockstep with {@code spec/metamodel/}). */ public static final List SPEC_FILES = List.of( - "attr.json", "db.json", "documentation.json", "field.json", "identity.json", + "api.json", "attr.json", "db.json", "documentation.json", "field.json", "identity.json", "index.json", "layout.json", "object.json", "origin.json", "prompt.json", "relationship.json", "reporting.json", "requirement.json", "source.json", - "template.json", "ui.json", "ui-web.json", "validator.json", "view.json"); + "template.json", "transition.json", "ui.json", "ui-web.json", "validator.json", "view.json"); /** Wildcard token used in the JSON for "any type / any subType". */ private static final String WILDCARD = "*"; diff --git a/server/java/metadata/src/main/java/com/metaobjects/transition/ActionTransition.java b/server/java/metadata/src/main/java/com/metaobjects/transition/ActionTransition.java new file mode 100644 index 0000000000..a33938849a --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/transition/ActionTransition.java @@ -0,0 +1,58 @@ +/* + * 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.transition; + +import com.metaobjects.MetaData; +import com.metaobjects.attr.BooleanAttribute; +import com.metaobjects.attr.ExpressionAttribute; +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.registry.MetaDataRegistry; + +/** {@code transition.action} (ADR-0066): an allowed move between two values of a {@code field.enum}. */ +@SuppressWarnings("serial") +public class ActionTransition extends MetaTransition { + + public ActionTransition(String name) { + super(TransitionConstants.SUBTYPE_ACTION, name); + } + + /** Register {@code transition.base} and {@code transition.action}; text comes from {@code spec/metamodel/transition.json}. */ + public static void registerTypes(MetaDataRegistry registry) { + registry.registerType(MetaTransition.class, def -> { + def.type(TransitionConstants.TYPE_TRANSITION).subType(MetaData.SUBTYPE_BASE) + .description("Registry anchor for the attributes every lifecycle move shares") + .inheritsFrom(MetaData.TYPE_METADATA, MetaData.SUBTYPE_BASE) + // Like template.base: the any-attr wildcard lets an undeclared attr reach the + // strict-load ERR_UNKNOWN_ATTR diagnostic instead of failing placement. + .optionalChild(com.metaobjects.attr.MetaAttribute.TYPE_ATTR, "*", "*"); + def.optionalAttributeWithConstraints(TransitionConstants.ATTR_PERMISSION) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(TransitionConstants.ATTR_PUBLIC) + .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + }); + registry.registerType(ActionTransition.class, def -> { + def.type(TransitionConstants.TYPE_TRANSITION).subType(TransitionConstants.SUBTYPE_ACTION) + .description("An allowed move between two values of a field.enum.") + .inheritsFrom(TransitionConstants.TYPE_TRANSITION, MetaData.SUBTYPE_BASE); + def.requiredAttributeWithConstraints(TransitionConstants.ATTR_FROM) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.requiredAttributeWithConstraints(TransitionConstants.ATTR_TO) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(TransitionConstants.ATTR_CONDITION) + .ofType(ExpressionAttribute.SUBTYPE_EXPRESSION).asSingle(); + }); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/transition/MetaTransition.java b/server/java/metadata/src/main/java/com/metaobjects/transition/MetaTransition.java new file mode 100644 index 0000000000..7a9b4e6947 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/transition/MetaTransition.java @@ -0,0 +1,27 @@ +/* + * 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.transition; + +import com.metaobjects.MetaData; + +/** Base node class for {@code type = "transition"} (ADR-0066): one allowed move of a lifecycle. Accessors are RESOLVING (ADR-0039). */ +@SuppressWarnings("serial") +public abstract class MetaTransition extends MetaData { + + protected MetaTransition(String subType, String name) { + super(TransitionConstants.TYPE_TRANSITION, subType, name); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/transition/TransitionConstants.java b/server/java/metadata/src/main/java/com/metaobjects/transition/TransitionConstants.java new file mode 100644 index 0000000000..ac94b4a521 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/transition/TransitionConstants.java @@ -0,0 +1,31 @@ +/* + * 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.transition; + +/** Names of the lifecycle vocabulary: {@code transition.*} (ADR-0066). */ +public final class TransitionConstants { + + private TransitionConstants() { + } + + public static final String TYPE_TRANSITION = "transition"; + public static final String SUBTYPE_ACTION = "action"; + public static final String ATTR_FROM = "from"; + public static final String ATTR_TO = "to"; + public static final String ATTR_CONDITION = "condition"; + public static final String ATTR_PERMISSION = "permission"; + public static final String ATTR_PUBLIC = "public"; +} diff --git a/server/java/metadata/src/main/resources/META-INF/services/com.metaobjects.registry.MetaDataTypeProvider b/server/java/metadata/src/main/resources/META-INF/services/com.metaobjects.registry.MetaDataTypeProvider index 949d3c2b88..a3be93e703 100644 --- a/server/java/metadata/src/main/resources/META-INF/services/com.metaobjects.registry.MetaDataTypeProvider +++ b/server/java/metadata/src/main/resources/META-INF/services/com.metaobjects.registry.MetaDataTypeProvider @@ -8,6 +8,7 @@ com.metaobjects.identity.IdentityTypesMetaDataProvider com.metaobjects.index.IndexTypesMetaDataProvider com.metaobjects.requirement.RequirementTypesMetaDataProvider com.metaobjects.reporting.ReportingTypesMetaDataProvider +com.metaobjects.api.RulesTypesMetaDataProvider com.metaobjects.database.CoreDBMetaDataProvider com.metaobjects.source.SourceTypesMetaDataProvider com.metaobjects.origin.OriginTypesMetaDataProvider diff --git a/server/java/metadata/src/test/java/com/metaobjects/config/NeutralConfigTest.java b/server/java/metadata/src/test/java/com/metaobjects/config/NeutralConfigTest.java index 3aa7ccc519..666af21467 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/config/NeutralConfigTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/config/NeutralConfigTest.java @@ -195,4 +195,49 @@ public void refusesAPackagedTransportWithoutAVersion() { public void refusesAVersionBesideAnotherTransport() { assertBadAttr("[{\"name\":\"a\",\"npm\":\"@x/y\",\"version\":\"1.0.0\"}]"); } + + // ADR-0066 — the `rules` and `verify` blocks. An absent key takes its default; a mistake is + // refused rather than silently defaulted, because a defaulted typo would change what verify reports. + + @Test + public void rulesSettingsAbsentKeysTakeTheDefaults() throws IOException { + Path dir = writeConfig("{ \"schema_version\": 1 }"); + assertEquals(RulesSettings.DEFAULT, NeutralConfig.read(dir).orElseThrow().getRulesSettings()); + assertEquals("derive", RulesSettings.DEFAULT.permissionNames().wireName()); + assertEquals("warn", RulesSettings.DEFAULT.lifecycleUnreachable().wireName()); + } + + @Test + public void rulesSettingsEveryKeyIsRead() throws IOException { + Path dir = writeConfig("{ \"schema_version\": 1, " + + "\"rules\": { \"permissions\": { \"names\": \"require\" }, " + + "\"lifecycle\": { \"create\": \"any\", \"commands\": \"none\" } }, " + + "\"verify\": { \"handEdits\": \"fail\", \"lifecycle\": { \"unreachable\": \"error\" } } }"); + RulesSettings s = NeutralConfig.read(dir).orElseThrow().getRulesSettings(); + assertEquals("require", s.permissionNames().wireName()); + assertEquals("any", s.lifecycleCreate().wireName()); + assertEquals("none", s.lifecycleCommands().wireName()); + assertEquals("error", s.lifecycleUnreachable().wireName()); + } + + @Test + public void rulesSettingsMistakesAreRefusedNotDefaulted() throws IOException { + String[] mistakes = { + "\"rules\": { \"permission\": { \"names\": \"advise\" } }", + "\"rules\": { \"lifecycle\": { \"initial\": \"any\" } }", + "\"rules\": { \"permissions\": { \"names\": \"strict\" } }", + "\"rules\": { \"lifecycle\": { \"commands\": true } }", + "\"rules\": \"advise\"", + "\"rules\": null", + "\"verify\": null", + "\"verify\": { \"lifecycle\": { \"unreachable\": \"fail\" } }", + "\"verify\": { \"lifecycles\": {} }", + "\"verify\": { \"handEdits\": \"warn\" }", + }; + for (String mistake : mistakes) { + Path dir = writeConfig("{ \"schema_version\": 1, " + mistake + " }"); + MetaDataException ex = assertThrows(mistake, MetaDataException.class, () -> NeutralConfig.read(dir)); + assertEquals(mistake, ErrorCode.ERR_BAD_ATTR_VALUE, ex.getCode().orElseThrow()); + } + } } diff --git a/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTest.java b/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTest.java index 0105234b4c..6ca0316fe8 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTest.java @@ -148,7 +148,9 @@ public class ConformanceTest { "origin-types", "requirement-types", // FR-044 reporting vocabulary (dimension / measure / segment). - "reporting-types" + "reporting-types", + // ADR-0066 business-rules vocabulary (api / operation / binding / transition). + "rules-types" ), // The corpus's "metaobjects-db" provider maps to Java's // CoreDBMetaDataProvider (id "database-extensions"), which registers the diff --git a/server/java/metadata/src/test/java/com/metaobjects/conformance/RulesCheckConformanceTest.java b/server/java/metadata/src/test/java/com/metaobjects/conformance/RulesCheckConformanceTest.java new file mode 100644 index 0000000000..7dfa6b0dda --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/conformance/RulesCheckConformanceTest.java @@ -0,0 +1,150 @@ +package com.metaobjects.conformance; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.MetaRoot; +import com.metaobjects.loader.DirectorySource; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.loader.MetaDataSource; +import com.metaobjects.api.RulesCheck; +import com.metaobjects.config.RulesSettings; +import com.metaobjects.config.NeutralConfig; +import com.metaobjects.requirement.RequirementCheck; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Cross-port rules-gate conformance corpus ({@code fixtures/rules-check-conformance/}, ADR-0066). + * Loads {@code input/} strict, reads {@code options.json} through the config reader, runs the + * gate and compares diagnostics (an unordered multiset) and the summary with {@code expected.json}. + */ +@RunWith(Parameterized.class) +public class RulesCheckConformanceTest { + + private static final Path CORPUS = CorpusRoot.locate().resolveSibling("rules-check-conformance"); + private static final Pattern DOCUMENTED_CASE = Pattern.compile("^\\| `([^`]+)` \\|", Pattern.MULTILINE); + + @Parameterized.Parameters(name = "{0}") + public static Collection fixtures() throws IOException { + List params = new ArrayList<>(); + for (String name : caseNames()) params.add(new Object[]{name}); + return params; + } + + private static List caseNames() throws IOException { + try (Stream dirs = Files.list(CORPUS)) { + return dirs.filter(Files::isDirectory).map(d -> d.getFileName().toString()).sorted().toList(); + } + } + + private final String name; + + public RulesCheckConformanceTest(String name) { + this.name = name; + } + + @Test + public void everyCaseOnDiskIsDocumentedInTheReadmeAndNothingElseIs() throws IOException { + String readme = Files.readString(CORPUS.resolve("README.md"), StandardCharsets.UTF_8); + String section = readme.substring(readme.indexOf("\n## Cases\n")); + int next = section.indexOf("\n## ", 1); + if (next > 0) section = section.substring(0, next); + List documented = new ArrayList<>(); + Matcher m = DOCUMENTED_CASE.matcher(section); + while (m.find()) documented.add(m.group(1)); + documented.sort(Comparator.naturalOrder()); + assertEquals(caseNames(), documented); + } + + @Test + public void fixture() throws IOException { + Path dir = CORPUS.resolve(name); + Path expectedFile = dir.resolve("expected.json"); + assertTrue(name + ": no expected.json", Files.isRegularFile(expectedFile)); + JsonObject expected = JsonParser.parseString(Files.readString(expectedFile, StandardCharsets.UTF_8)).getAsJsonObject(); + + RulesSettings settings = RulesSettings.DEFAULT; + Path optionsFile = dir.resolve("options.json"); + if (Files.isRegularFile(optionsFile)) { + // options.json holds the rules/verify blocks only; the reader also wants the schema marker. + JsonObject options = JsonParser.parseString(Files.readString(optionsFile, StandardCharsets.UTF_8)).getAsJsonObject(); + options.addProperty("schema_version", 1); + settings = NeutralConfig.parse(options.toString(), optionsFile.toString()).getRulesSettings(); + } + + MetaDataLoader loader = new MetaDataLoader(LoaderOptions.create(false, false, true), + MetaDataLoader.SUBTYPE_MANUAL, "rules_check_" + name.replace('-', '_')); + loader.init(); + loader.load(new DirectorySource(dir.resolve("input"), new DirectorySource.Options()).expandToList()); + assertTrue(name + ": expected a clean strict load, got: " + loader.getErrors(), loader.getErrors().isEmpty()); + + RulesCheck.Result result = RulesCheck.check(loader.getRoot(), settings); + + assertEquals(name, multiset(expected.getAsJsonArray("diagnostics")), actualRows(result.diagnostics())); + assertEquals(name, expectedSummary(expected.get("summary")), actualSummary(result.summary())); + } + + private static List multiset(JsonArray diagnostics) { + List rows = new ArrayList<>(); + for (JsonElement e : diagnostics) { + JsonObject d = e.getAsJsonObject(); + rows.add(row(d.get("severity").getAsString(), d.get("code").getAsString(), + d.has("path") ? d.get("path").getAsString() : "", d.get("message").getAsString())); + } + rows.sort(Comparator.naturalOrder()); + return rows; + } + + private static List actualRows(List diagnostics) { + List rows = new ArrayList<>(); + for (RequirementCheck.Diagnostic d : diagnostics) { + rows.add(row(d.severity().name().toLowerCase(java.util.Locale.ROOT), d.code(), + d.path() == null ? "" : d.path(), d.message())); + } + rows.sort(Comparator.naturalOrder()); + return rows; + } + + private static String row(String severity, String code, String path, String message) { + return severity + " | " + code + " | " + path + " | " + message; + } + + private static List expectedSummary(JsonElement summary) { + if (summary == null || summary.isJsonNull()) return null; + JsonObject s = summary.getAsJsonObject(); + List out = new ArrayList<>(); + for (String key : s.keySet()) out.add(key + "=" + s.get(key).getAsInt()); + out.sort(Comparator.naturalOrder()); + return out; + } + + private static List actualSummary(RulesCheck.Summary s) { + if (s == null) return null; + List out = new ArrayList<>(Arrays.asList( + "operations=" + s.operations(), "lifecycles=" + s.lifecycles(), "transitions=" + s.transitions())); + out.sort(Comparator.naturalOrder()); + return out; + } +} 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 new file mode 100644 index 0000000000..23058c7bf5 --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/loader/RulesValidationMethodOrderTest.java @@ -0,0 +1,67 @@ +/* + * 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.MetaRoot; +import com.metaobjects.registry.SharedRegistryTestBase; +import org.junit.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertTrue; + +/** F3h: a bad binding {@code @method} is reported even when the operation fails O1-O3 first. */ +public class RulesValidationMethodOrderTest extends SharedRegistryTestBase { + + private static Path fixture() { + Path dir = Paths.get("").toAbsolutePath(); + while (dir != null) { + Path c = dir.resolve("fixtures/conformance/error-rules-binding-method-invalid/input/meta.purchasing.json"); + if (Files.isRegularFile(c)) return c; + dir = dir.getParent(); + } + throw new AssertionError("fixture not found"); + } + + @Test + public void badMethodIsReportedAlongsideAnO1Failure() throws Exception { + String json = Files.readString(fixture(), StandardCharsets.UTF_8); + // Point the command's input at a projection: O1 (ERR_OPERATION_SHAPE) short-circuits the operation. + String broken = json.replace("\"@inputRef\": \"DecisionInput\"", "\"@inputRef\": \"RequestSummary\""); + assertTrue("fixture shape changed", !broken.equals(json)); + MetaDataLoader loader = new MetaDataLoader( + LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "rules-method-order"); + loader.setSourceURIs(java.util.Collections.emptyList()); + loader.init(); + 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 + } + MetaRoot root = loader.getRoot(); + List codes = RulesValidation.validate(root).stream() + .map(e -> e.getCode().orElseThrow()).collect(Collectors.toList()); + assertTrue(codes.toString(), codes.contains(ErrorCode.ERR_OPERATION_SHAPE)); + assertTrue(codes.toString(), codes.contains(ErrorCode.ERR_BAD_ATTR_VALUE)); + } +} diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 7eacbe9ac7..468568f07c 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -176,6 +176,8 @@ verify as render_verify, ) from metaobjects.shared.base_types import TYPE_OBJECT, TYPE_TEMPLATE +from metaobjects.rules_check import check_rules +from metaobjects.rules_settings import RulesSettings, rules_settings_of from metaobjects.wire import WireFormat, wire_block, wire_candidates @@ -535,6 +537,7 @@ def load(strict_load: bool) -> LoadResult: # invocation) read the same values `gen`/`verify --codegen` would. result.root.naming = neutral.naming if neutral is not None else NamingRules() result.root.wire = neutral.wire if neutral is not None else WireFormat() + result.root.rules_settings = neutral.rules if neutral is not None else RulesSettings() result.root.api = neutral.api if neutral is not None else ApiSettings() return result.root, [] @@ -599,6 +602,7 @@ def _load_collection_result( # it to the loaded root so codegen, the runtime and `verify` agree. result.root.naming = collection.naming result.root.wire = collection.wire + result.root.rules_settings = collection.rules result.root.api = collection.api return result @@ -3215,6 +3219,38 @@ def _verify_requirements(args: argparse.Namespace, model: "_VerifyModel | None") return 0 +def _verify_rules(args: argparse.Namespace, model: "_VerifyModel | None") -> int: + """The business-rules gate (ADR-0066, see :mod:`metaobjects.rules_check`) — runs on EVERY + ``verify``, with no subverb to select it: operations and lifecycles are metadata, so a + model declaring none is silent, not in drift (no line, no finding, exit unchanged). + + Otherwise prints the summary line, then every finding (uncapped), and returns 1 when any + finding is an error. Returns 0 and prints nothing when the metadata did not load + (``model`` is ``None``): that is reported, and fails the command, in :func:`_cmd_verify`. + """ + if model is None: + return 0 + result = check_rules(model.root, rules_settings_of(model.root)) + if result.summary is None: + return 0 + s = result.summary + print( + f"metaobjects verify — rules: {s.operations} operation(s), {s.lifecycles} lifecycle(s) " + f"with {s.transitions} transition(s).", + file=sys.stderr, + ) + errors = [d for d in result.diagnostics if d.severity == SEVERITY_ERROR] + warnings = [d for d in result.diagnostics if d.severity != SEVERITY_ERROR] + for d in errors: + print(_format_requirement_diagnostic(d), file=sys.stderr) + for d in warnings: + print(_format_requirement_diagnostic(d), file=sys.stderr) + if errors: + print(f"metaobjects verify — rules: {len(errors)} error(s).", file=sys.stderr) + return 1 + return 0 + + def _deps_project_root(args: argparse.Namespace) -> Path: """The project whose ``.metaobjects/config.json`` declares the dependencies: the one holding the metadata the run names (````, else the config's ``metadata``), else the @@ -3331,6 +3367,8 @@ def _cmd_verify(args: argparse.Namespace) -> int: if model is None: exit_code = max(exit_code, _report_unloaded_model(load_failure, gates_stderr.lines())) exit_code = max(exit_code, _verify_requirements(args, model)) + # ADR-0066: the business-rules gate, also on every verify and also opt-in by declaration. + exit_code = max(exit_code, _verify_rules(args, model)) _run_field_lint_advisory(args, model) if exit_code != 2: # 2 is a refused invocation: its own message is the whole answer _run_pagination_advisory(args, model) diff --git a/server/python/src/metaobjects/config/dependencies.py b/server/python/src/metaobjects/config/dependencies.py index e81841c048..17830370c1 100644 --- a/server/python/src/metaobjects/config/dependencies.py +++ b/server/python/src/metaobjects/config/dependencies.py @@ -18,6 +18,7 @@ from metaobjects.meta.meta_data import MetaData from metaobjects.naming import NamingRules, package_of_resolution_key from metaobjects.api_settings import ApiSettings +from metaobjects.rules_settings import RulesSettings from metaobjects.wire import WireFormat from metaobjects.registry_manifest import METAMODEL_VERSION from metaobjects.shared.base_types import TYPE_OBJECT, TYPE_REQUIREMENT @@ -678,6 +679,10 @@ class Collection: #: attached to the loaded root beside `naming`. wire: WireFormat = WireFormat() + #: ADR-0066 — this project's `rules` / `verify` settings, read at the same rung; + #: attached to the loaded root beside `wire`. + rules: RulesSettings = RulesSettings() + #: This project's `api` setting (page size, unknown-field rule), attached beside `wire`. api: ApiSettings = ApiSettings() diff --git a/server/python/src/metaobjects/config/neutral_config.py b/server/python/src/metaobjects/config/neutral_config.py index 43dba03913..9204ffb844 100644 --- a/server/python/src/metaobjects/config/neutral_config.py +++ b/server/python/src/metaobjects/config/neutral_config.py @@ -23,6 +23,13 @@ registered_table_naming_rules, unknown_naming_strategy_message, ) +from metaobjects.rules_settings import ( + RULES_LIFECYCLE_COMMANDS, + RULES_LIFECYCLE_CREATE, + RULES_PERMISSION_NAMES, + VERIFY_LIFECYCLE_UNREACHABLE, + RulesSettings, +) from metaobjects.wire import WIRE_DECIMALS, WIRE_DURATIONS, WIRE_NULL_MEMBERS, WireFormat #: The DEFAULT value of `sources` when the key is absent or empty — never a @@ -102,6 +109,10 @@ class NeutralConfig: #: for the same reason `naming` is. wire: WireFormat = WireFormat() + #: ADR-0066 — the `rules` and `verify` blocks (business-rules settings), each absent key at + #: its default. Attached to the loaded root (`MetaRoot.rules_settings`) beside `wire`. + rules: RulesSettings = RulesSettings() + #: FR-023 — `requirements.inherit`: scope patterns naming the dependencies whose #: requirements this project takes on as its own ledger (`Collection.in_ledger`). requirements_inherit: list[str] = field(default_factory=list) @@ -203,6 +214,7 @@ def read_neutral_config(config_dir: Path) -> NeutralConfig | None: libraries = _read_libraries(raw, path) naming = _read_naming(raw, path) wire = _read_wire(raw, path) + rules = _read_rules(raw, path) _check_enums(raw, path) api = _read_api(raw, path) requirements_inherit = _read_requirements_inherit(raw, path) @@ -216,6 +228,7 @@ def read_neutral_config(config_dir: Path) -> NeutralConfig | None: libraries=libraries, naming=naming, wire=wire, + rules=rules, requirements_inherit=requirements_inherit, api=api, ) @@ -369,6 +382,79 @@ def _read_naming(raw: dict[str, object], path: Path) -> NamingRules: return NamingRules(columns=columns, tables=tables, collections=collections) +#: ADR-0066 — the closed shape of the `rules` and `verify` blocks: block -> sub-block -> key -> values. +_RULES_BLOCKS: dict[str, dict[str, dict[str, tuple[str, ...]]]] = { + "rules": { + "permissions": {"names": RULES_PERMISSION_NAMES}, + "lifecycle": {"create": RULES_LIFECYCLE_CREATE, "commands": RULES_LIFECYCLE_COMMANDS}, + }, + "verify": {"lifecycle": {"unreachable": VERIFY_LIFECYCLE_UNREACHABLE}}, +} + + +#: `verify.handEdits` and its values: read by the TypeScript `meta verify` only, validated by every port. +_VERIFY_KEY_HAND_EDITS = "handEdits" +_HAND_EDITS_POLICIES: tuple[str, ...] = ("fail", "notice") + + +def _read_rules(raw: dict[str, object], path: Path) -> RulesSettings: + """ADR-0066 — the `rules` and `verify` blocks. Absent or `{}` ⇒ every key at its default. + Refuses a non-object block, an unknown key at any level, or a value outside the closed set a + key accepts, exactly as `naming` and `wire` do: a mistake must not silently fall back to the + default and change what `verify` reports.""" + found: dict[tuple[str, str, str], str] = {} + for block, subs in _RULES_BLOCKS.items(): + if block not in raw: + continue + value = raw[block] + if not isinstance(value, dict): + raise ParseError(f'{path}: "{block}" must be an object', code=ErrorCode.ERR_BAD_ATTR_VALUE) + for sub_name, sub_value in value.items(): + if block == "verify" and sub_name == _VERIFY_KEY_HAND_EDITS: + # Read by the TypeScript `meta verify` only (this port's verify already fails on + # any hand edit); validated here so the file `metaobjects init` writes loads. + if sub_value not in _HAND_EDITS_POLICIES: + choices = ", ".join(f'"{a}"' for a in _HAND_EDITS_POLICIES) + raise ParseError( + f'{path}: "verify.handEdits" must be one of {choices}, got {json.dumps(sub_value)}', + code=ErrorCode.ERR_BAD_ATTR_VALUE, + ) + continue + if sub_name not in subs: + expected = ", ".join(f'"{k}"' for k in ((_VERIFY_KEY_HAND_EDITS, *subs) if block == "verify" else subs)) + raise ParseError( + f'{path}: "{block}" has an unknown key "{sub_name}" (expected {expected})', + code=ErrorCode.ERR_BAD_ATTR_VALUE, + ) + if not isinstance(sub_value, dict): + raise ParseError( + f'{path}: "{block}.{sub_name}" must be an object', code=ErrorCode.ERR_BAD_ATTR_VALUE + ) + keys = subs[sub_name] + for key, key_value in sub_value.items(): + if key not in keys: + expected = ", ".join(f'"{k}"' for k in keys) + raise ParseError( + f'{path}: "{block}.{sub_name}" has an unknown key "{key}" (expected {expected})', + code=ErrorCode.ERR_BAD_ATTR_VALUE, + ) + allowed = keys[key] + if not isinstance(key_value, str) or key_value not in allowed: + choices = ", ".join(f'"{a}"' for a in allowed) + raise ParseError( + f'{path}: "{block}.{sub_name}.{key}" must be one of {choices}, got {json.dumps(key_value)}', + code=ErrorCode.ERR_BAD_ATTR_VALUE, + ) + found[(block, sub_name, key)] = key_value + defaults = RulesSettings() + return RulesSettings( + permission_names=found.get(("rules", "permissions", "names"), defaults.permission_names), + lifecycle_create=found.get(("rules", "lifecycle", "create"), defaults.lifecycle_create), + lifecycle_commands=found.get(("rules", "lifecycle", "commands"), defaults.lifecycle_commands), + lifecycle_unreachable=found.get(("verify", "lifecycle", "unreachable"), defaults.lifecycle_unreachable), + ) + + _PAGE_SIZE_MAX = 2147483647 diff --git a/server/python/src/metaobjects/config/source_resolver.py b/server/python/src/metaobjects/config/source_resolver.py index 15eeba3935..56088dcf4a 100644 --- a/server/python/src/metaobjects/config/source_resolver.py +++ b/server/python/src/metaobjects/config/source_resolver.py @@ -8,6 +8,7 @@ from metaobjects.loader.sources import DirectorySource from metaobjects.naming import NamingRules, package_of_resolution_key from metaobjects.api_settings import ApiSettings +from metaobjects.rules_settings import RulesSettings from metaobjects.wire import WireFormat from metaobjects.scope import compile_scope, matches_scope @@ -158,6 +159,7 @@ def _collection_from_own_files( libraries: list[str] = cfg.libraries if cfg is not None else [] naming: NamingRules = cfg.naming if cfg is not None else NamingRules() wire: WireFormat = cfg.wire if cfg is not None else WireFormat() + rules: RulesSettings = cfg.rules if cfg is not None else RulesSettings() api: ApiSettings = cfg.api if cfg is not None else ApiSettings() lock = read_lock(root) @@ -190,6 +192,7 @@ def _collection_from_own_files( libraries=tuple(libraries), naming=naming, wire=wire, + rules=rules, api=api, requirements_inherit=tuple(cfg.requirements_inherit if cfg is not None else []), ) diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index 4564e9a559..8942619aaa 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -77,6 +77,33 @@ OBJECT_SUBTYPES, ) from .meta.core.relationship.meta_relationship import MetaRelationship +from .meta.core.api.api_constants import ( + API_SUBTYPE_OPERATIONAL, + BINDING_ATTR_METHOD, + BINDING_ATTR_PATH, + BINDING_SUBTYPE_REST, + HTTP_METHODS, + OPERATION_ATTR_ERRORS, + OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_MANY, + OPERATION_ATTR_OBJECT_REF, + OPERATION_ATTR_OUTPUT_REF, + OPERATION_ATTR_PERMISSION, + OPERATION_ATTR_PUBLIC, + OPERATION_ATTR_TRANSITIONS, + OPERATION_SUBTYPE_COMMAND, + OPERATION_SUBTYPE_QUERY, +) +from .meta.core.api.meta_api import MetaApi, MetaBinding, MetaOperation +from .meta.core.transition.meta_transition import MetaTransition +from .meta.core.transition.transition_constants import ( + TRANSITION_ATTR_CONDITION, + TRANSITION_ATTR_FROM, + TRANSITION_ATTR_PERMISSION, + TRANSITION_ATTR_PUBLIC, + TRANSITION_ATTR_TO, + TRANSITION_SUBTYPE_ACTION, +) from .meta.core.reporting.meta_dimension import MetaDimension from .meta.core.reporting.meta_measure import MetaMeasure from .meta.core.reporting.meta_segment import MetaSegment @@ -192,6 +219,10 @@ TYPE_RELATIONSHIP, TYPE_REQUIREMENT, TYPE_SEGMENT, + TYPE_API, + TYPE_BINDING, + TYPE_OPERATION, + TYPE_TRANSITION, TYPE_SOURCE, TYPE_TEMPLATE, TYPE_VALIDATOR, @@ -258,6 +289,8 @@ def _register_subtypes( factory=MetaRoot, description="Root metadata document", child_rules=[ + # ADR-0030 / ADR-0066 — a declared API surface is a top-level, packaged node. + ChildRule(TYPE_API, "*"), ChildRule(TYPE_FIELD, "*"), ChildRule(TYPE_OBJECT, "*"), # Capability requirements are declared beside the entities they describe. @@ -500,6 +533,104 @@ def _register_subtypes( ) ) +# ADR-0030 / ADR-0066 — the declared API surface (api / operation / binding) and the +# lifecycle moves of a field.enum (transition). Attr scoping is per-subtype exactly as +# spec/metamodel/api.json and transition.json declare it; the cross-node rules live in +# loader/validate_rules.py. Mirrors TS core-types.ts. +_OPERATION_COMMON_ATTRS = [ + AttrSchema(name=OPERATION_ATTR_INPUT_REF, value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name=OPERATION_ATTR_OUTPUT_REF, value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name=OPERATION_ATTR_OBJECT_REF, value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name=OPERATION_ATTR_PERMISSION, value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name=OPERATION_ATTR_PUBLIC, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), +] +# The registry anchors: not authorable, they carry what every subtype of the type shares. +core_provider.add(TypeDefinition(type=TYPE_API, sub_type=SUBTYPE_BASE, factory=MetaApi)) +core_provider.add( + TypeDefinition( + type=TYPE_OPERATION, + sub_type=SUBTYPE_BASE, + factory=MetaOperation, + attrs=list(_OPERATION_COMMON_ATTRS), + child_rules=[ChildRule(TYPE_BINDING, "*")], + ) +) +core_provider.add(TypeDefinition(type=TYPE_BINDING, sub_type=SUBTYPE_BASE, factory=MetaBinding)) +core_provider.add( + TypeDefinition( + type=TYPE_TRANSITION, + sub_type=SUBTYPE_BASE, + factory=MetaTransition, + attrs=[ + AttrSchema(name=TRANSITION_ATTR_PERMISSION, value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name=TRANSITION_ATTR_PUBLIC, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), + ], + ) +) +core_provider.add( + TypeDefinition( + type=TYPE_API, + sub_type=API_SUBTYPE_OPERATIONAL, + factory=MetaApi, + child_rules=[ChildRule(TYPE_OPERATION, "*")], + ) +) +core_provider.add( + TypeDefinition( + type=TYPE_OPERATION, + sub_type=OPERATION_SUBTYPE_COMMAND, + factory=MetaOperation, + attrs=[ + *_OPERATION_COMMON_ATTRS, + 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, "*")], + ) +) +core_provider.add( + TypeDefinition( + type=TYPE_OPERATION, + sub_type=OPERATION_SUBTYPE_QUERY, + factory=MetaOperation, + attrs=[ + *_OPERATION_COMMON_ATTRS, + AttrSchema(name=OPERATION_ATTR_MANY, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), + ], + child_rules=[ChildRule(TYPE_BINDING, "*")], + ) +) +core_provider.add( + TypeDefinition( + type=TYPE_BINDING, + sub_type=BINDING_SUBTYPE_REST, + factory=MetaBinding, + attrs=[ + AttrSchema( + name=BINDING_ATTR_METHOD, + value_type=ATTR_SUBTYPE_STRING, + required=False, + allowed_values=HTTP_METHODS, + ), + AttrSchema(name=BINDING_ATTR_PATH, value_type=ATTR_SUBTYPE_STRING, required=False), + ], + ) +) +core_provider.add( + TypeDefinition( + type=TYPE_TRANSITION, + sub_type=TRANSITION_SUBTYPE_ACTION, + factory=MetaTransition, + attrs=[ + AttrSchema(name=TRANSITION_ATTR_FROM, value_type=ATTR_SUBTYPE_STRING, required=True, is_array=True), + AttrSchema(name=TRANSITION_ATTR_TO, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name=TRANSITION_ATTR_CONDITION, value_type=ATTR_SUBTYPE_EXPRESSION, required=False), + AttrSchema(name=TRANSITION_ATTR_PERMISSION, value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name=TRANSITION_ATTR_PUBLIC, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), + ], + ) +) + # field.* (one factory, data_type by subtype) # Note: FIELD_SUBTYPE_ENUM is excluded from FIELD_SUBTYPES; it is registered # separately below with its required @values AttrSchema (sharing these child rules). @@ -702,7 +833,8 @@ def _register_subtypes( # TypeRegistry.extend, matching the TS promptProvider split. @values + @provided # stay in core (they are core field.enum properties, declared in field.json). ], - child_rules=_FIELD_CHILD_RULES, + # ADR-0066: a field.enum may carry lifecycle moves. + child_rules=[*_FIELD_CHILD_RULES, ChildRule(TYPE_TRANSITION, "*")], ) ) diff --git a/server/python/src/metaobjects/errors.py b/server/python/src/metaobjects/errors.py index 54e35f5960..e8c47055c2 100644 --- a/server/python/src/metaobjects/errors.py +++ b/server/python/src/metaobjects/errors.py @@ -132,6 +132,19 @@ class ErrorCode(str, Enum): ERR_INVALID_MEASURE = "ERR_INVALID_MEASURE" ERR_INVALID_REPORT = "ERR_INVALID_REPORT" ERR_REPORT_FOREIGN_MEASURE = "ERR_REPORT_FOREIGN_MEASURE" + # ADR-0066 business rules (loader/validate_rules.py; rule ids L1-L7, P1, O0-O5, B1): + # lifecycle transitions on a field.enum and the declared operations of an api.operational. + ERR_TRANSITION_UNKNOWN_STATE = "ERR_TRANSITION_UNKNOWN_STATE" + ERR_TRANSITION_NOT_ON_ENTITY = "ERR_TRANSITION_NOT_ON_ENTITY" + ERR_LIFECYCLE_NO_INITIAL = "ERR_LIFECYCLE_NO_INITIAL" + ERR_LIFECYCLE_REDECLARED = "ERR_LIFECYCLE_REDECLARED" + ERR_TRANSITION_NAME_COLLISION = "ERR_TRANSITION_NAME_COLLISION" + ERR_OPERATION_TARGET_UNRESOLVED = "ERR_OPERATION_TARGET_UNRESOLVED" + ERR_OPERATION_TARGET_MISMATCH = "ERR_OPERATION_TARGET_MISMATCH" + ERR_OPERATION_UNKNOWN_TRANSITION = "ERR_OPERATION_UNKNOWN_TRANSITION" + ERR_OPERATION_SHAPE = "ERR_OPERATION_SHAPE" + ERR_PERMISSION_PUBLIC_CONFLICT = "ERR_PERMISSION_PUBLIC_CONFLICT" + ERR_BINDING_PATH_MISMATCH = "ERR_BINDING_PATH_MISMATCH" # Reserved structural body key authored as an @-attr (source-v2 / ADR-0007). ERR_RESERVED_ATTR = "ERR_RESERVED_ATTR" # Source-v2 multi-source one-primary rule (ADR-0007). diff --git a/server/python/src/metaobjects/loader/resolve_references.py b/server/python/src/metaobjects/loader/resolve_references.py index 64483dde58..bf1e219847 100644 --- a/server/python/src/metaobjects/loader/resolve_references.py +++ b/server/python/src/metaobjects/loader/resolve_references.py @@ -24,7 +24,7 @@ from ..meta.core.reporting.reporting_constants import REPORTING_ATTR_OF, REPORTING_ATTR_VIA from ..meta.meta_data import MetaData from ..naming_refs import ( - REF_BEARING_ATTR_NAMES, + is_ref_bearing_attr, RefOverDropError, effective_package_of, find_named_top_level, @@ -143,7 +143,7 @@ def visit(node: MetaData) -> None: # ADR-0039 sanctioned own: this pass rewrites the declared-here layer; an # inherited attribute is resolved once, on the node that declares it. for attr in node.own_meta_attrs(): - if attr.name in REF_BEARING_ATTR_NAMES and isinstance(attr, MetaAttr): + if is_ref_bearing_attr(node, attr.name) and isinstance(attr, MetaAttr): _resolve_attr(root, node, attr, decl_pkg) # ADR-0039 sanctioned own: structural walk over the physical declaration tree. for child in node.own_children(): diff --git a/server/python/src/metaobjects/loader/validate_rules.py b/server/python/src/metaobjects/loader/validate_rules.py new file mode 100644 index 0000000000..bca8e40abb --- /dev/null +++ b/server/python/src/metaobjects/loader/validate_rules.py @@ -0,0 +1,559 @@ +"""ADR-0066 — cross-node rules for operations (slice A) and lifecycles (slice B). + +A rule-for-rule port of the TypeScript reference +``server/typescript/packages/metadata/src/loader/rules-validation.ts``. Every port implements +the same rules WITH THE SAME MESSAGE TEXT; the fixtures under ``fixtures/conformance/`` +(``error-rules-*``, with the positive ``rules-*`` cases) are the contract. + +One broken rule yields one error: + +- Each error's source is the offending node: the transition, the enum field (L3), the entity + (L2b), the operation or the binding. +- An operation whose @inputRef / @outputRef fails O1 is not checked further; one whose target + fails O2 or O3 is not checked for O4 or B1. +- An error is reported once per (node, code), so a broken transition on an abstract base is + reported once, not once per inheritor. + +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). + 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 + L6 ERR_TRANSITION_NAME_COLLISION two transitions of one entity share a name, compared without case + L7 ERR_BAD_ATTR_VALUE @condition names a field the entity does not have, or is not boolean + L8 ERR_BAD_ATTR_VALUE @from is empty + L9 ERR_BAD_ATTR_VALUE a lifecycle field is an array + L10 ERR_LIFECYCLE_REDECLARED an entity redeclares an inherited lifecycle field without extending it + B2 ERR_BINDING_PATH_MISMATCH two bindings of one API share an effective method and path + P1 ERR_PERMISSION_PUBLIC_CONFLICT @public: true with @permission (operation or transition) + P2 ERR_BAD_ATTR_VALUE @permission is not a dotted identifier path (PERMISSION_NAME_PATTERN) + O0 ERR_TRANSITION_NAME_COLLISION an operation named create/get/list/update/delete + O6 ERR_TRANSITION_NAME_COLLISION two operations of one package share a name, compared without case, + in one API or across its APIs (each derives the permission name + .), unless they are the same operation: + declared twice in one API (they merge), or declared identically + in two APIs (_same_operation) + O1 ERR_OPERATION_SHAPE @inputRef is not an object.value; @outputRef is not an entity, projection or value + O2 ERR_OPERATION_TARGET_UNRESOLVED @objectRef is not an object.entity, or a command lists @transitions and + no target is declared or derivable + O3 ERR_OPERATION_TARGET_MISMATCH a declared @objectRef disagrees with the derived target + O4 ERR_OPERATION_UNKNOWN_TRANSITION a @transitions name is not a transition of the target + O5 ERR_BAD_ATTR_VALUE an @errors code is not lower snake case, is listed twice, or is one the route answers itself + B1 ERR_BINDING_PATH_MISMATCH a binding.rest @path's placeholders are not the target's key fields + (a keyed operation) or are not empty (an unkeyed one) + +ADR-0039 NAMING INVERSION: Python ``attr()`` is OWN-ONLY. Every place the TS reference calls +the resolving ``attr()`` / ``children()``, this module calls ``get_meta_attr()`` / +``children()``. The ``own_children()`` uses carry their sanctioned case in a comment. +""" +from __future__ import annotations + +import re + +from ..errors import ErrorCode, MetaError +from ..meta.core.api.api_constants import ( + BINDING_ATTR_METHOD, + BINDING_ATTR_PATH, + BINDING_SUBTYPE_REST, + BUSINESS_ERROR_CODE_PATTERN, + OPERATION_ATTR_ERRORS, + OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_MANY, + OPERATION_ATTR_OBJECT_REF, + OPERATION_ATTR_OUTPUT_REF, + OPERATION_ATTR_PERMISSION, + OPERATION_ATTR_PUBLIC, + OPERATION_ATTR_TRANSITIONS, + PERMISSION_NAME_PATTERN, + OPERATION_SUBTYPE_COMMAND, + RESERVED_ERROR_CODES, + RESERVED_OPERATION_NAMES, +) +from ..meta.core.field.field_constants import ( + FIELD_ATTR_DEFAULT, + FIELD_ATTR_VALUES, + FIELD_SUBTYPE_ENUM, +) +from ..meta.core.object.object_constants import ( + OBJECT_SUBTYPE_ENTITY, + OBJECT_SUBTYPE_PROJECTION, + OBJECT_SUBTYPE_VALUE, +) +from ..meta.core.transition.lifecycle import ( + derive_operation_target, + entity_lineage, + entity_transitions, + lifecycle_is_live, + lifecycle_transitions_of, + operation_is_keyed, + primary_key_fields, + resolve_object_on, + string_list, + transition_from, + transition_to, +) +from ..meta.core.transition.transition_constants import ( + TRANSITION_ATTR_CONDITION, + TRANSITION_SUBTYPE_ACTION, +) +from ..meta.meta_data import MetaData +from ..naming_refs import effective_package_of +from ..meta.persistence.source.meta_source import MetaSource +from ..shared.base_types import ( + TYPE_API, + TYPE_BINDING, + TYPE_FIELD, + TYPE_OBJECT, + TYPE_OPERATION, + TYPE_SOURCE, + TYPE_TRANSITION, +) + +_RESERVED = frozenset(RESERVED_OPERATION_NAMES) +_RESERVED_LIST = ", ".join(RESERVED_OPERATION_NAMES) +_RESERVED_CODES = frozenset(RESERVED_ERROR_CODES) + + +def _is_reserved_name(name: str) -> bool: + """A derived name is compared without case: a command, a permission constant or a file named + from it collides with another that differs only in case on a case-folding target.""" + return name.lower() in _RESERVED +_PLACEHOLDER_RE = re.compile(r"\{([^}]*)\}") + + +def _label(node: MetaData) -> str: + """``"Entity.field.transition"`` for a transition, ``"Api.operation"`` for an operation.""" + parts: list[str] = [] + n: MetaData | None = node + # A binding is unnamed: its label is its operation's. + while n is not None and n.parent is not None: + if n.name != "": + parts.insert(0, n.name) + n = n.parent + return ".".join(parts) + + +def _quote_list(xs: list[str]) -> str: + return ", ".join(f'"{x}"' for x in xs) + + +def _unique(xs: list[str]) -> list[str]: + return list(dict.fromkeys(xs)) + + +class _Sink: + def __init__(self, errors: list[MetaError]) -> None: + self.errors = errors + self._seen: set[tuple[int, ErrorCode]] = set() + + def add(self, node: MetaData, code: ErrorCode, message: str) -> None: + key = (id(node), code) + if key in self._seen: + return + self._seen.add(key) + self.errors.append(MetaError(code=code, message=message, envelope=node.source)) + + +def _check_permission(node: MetaData, sink: _Sink) -> None: + """P1 and P2 for an operation or a transition.""" + permission = node.get_meta_attr(OPERATION_ATTR_PERMISSION) + if node.get_meta_attr(OPERATION_ATTR_PUBLIC) is True and permission is not None: + sink.add( + node, + ErrorCode.ERR_PERMISSION_PUBLIC_CONFLICT, + f'{node.type}.{node.sub_type} "{_label(node)}" declares both @public: true and @permission; ' + f"a public {node.type} calls no permission check, so remove one.", + ) + if isinstance(permission, str) and not PERMISSION_NAME_PATTERN.fullmatch(permission): + sink.add( + node, + ErrorCode.ERR_BAD_ATTR_VALUE, + f'{node.type}.{node.sub_type} "{_label(node)}" @permission "{permission}" is not a dotted ' + 'identifier path; use names of letters, digits and _ joined by "." (a package prefix may use ' + '"::"), such as "purchasing.approve".', + ) + + +def _check_declared_transitions(field: MetaData, sink: _Sink) -> None: + """L1, L3, L4, L5, L7 and P1 for the transitions declared on one field.""" + from .validation_passes import condition_message + + # ADR-0039 sanctioned own: each transition is checked where it is declared. + declared = [ + c for c in field.own_children() + if c.type == TYPE_TRANSITION and c.sub_type == TRANSITION_SUBTYPE_ACTION + ] + if not declared: + return + owner = field.parent + if owner is None or owner.type != TYPE_OBJECT or owner.sub_type != OBJECT_SUBTYPE_ENTITY: + where = ( + "the document root" + if owner is None or owner.type != TYPE_OBJECT + else f'object.{owner.sub_type} "{owner.name}"' + ) + for t in declared: + sink.add( + t, + ErrorCode.ERR_TRANSITION_NOT_ON_ENTITY, + f'transition.action "{_label(t)}" is declared on a field of {where}; ' + "a lifecycle belongs to an object.entity with a writable source.", + ) + return + if field.sub_type == FIELD_SUBTYPE_ENUM and not isinstance(field.get_meta_attr(FIELD_ATTR_DEFAULT), str): + sink.add( + field, + ErrorCode.ERR_LIFECYCLE_NO_INITIAL, + f'field.enum "{_label(field)}" declares transitions but no @default; ' + "its @default is the lifecycle's initial state.", + ) + if field.resolved_is_array(): + sink.add( + field, + ErrorCode.ERR_BAD_ATTR_VALUE, + f'field.{field.sub_type} "{_label(field)}" declares transitions but is an array ' + "(@isArray: true); a lifecycle's state is one value.", + ) + states = _unique(string_list(field, FIELD_ATTR_VALUES)) + for t in declared: + _check_permission(t, sink) + if not transition_from(t): + sink.add( + t, + ErrorCode.ERR_BAD_ATTR_VALUE, + f'transition.action "{_label(t)}" @from is empty; name at least one state the transition leaves.', + ) + to = transition_to(t) + unknown = [s for s in _unique([*transition_from(t), *([] if to is None else [to])]) if s not in states] + if unknown: + sink.add( + t, + ErrorCode.ERR_TRANSITION_UNKNOWN_STATE, + f'transition.action "{_label(t)}" names {_quote_list(unknown)}, which ' + f'{"is not a member" if len(unknown) == 1 else "are not members"} of "{field.name}" ' + f"@values ({_quote_list(states)}).", + ) + if _is_reserved_name(t.name): + sink.add( + t, + ErrorCode.ERR_TRANSITION_NAME_COLLISION, + f'transition.action "{_label(t)}" is named "{t.name}", which is a derived CRUD verb ' + f"({_RESERVED_LIST}); rename it.", + ) + condition = t.get_meta_attr(TRANSITION_ATTR_CONDITION) + if condition is not None: + message = condition_message(condition, owner, f'transition.action "{_label(t)}" @condition') + if message is not None: + sink.add(t, ErrorCode.ERR_BAD_ATTR_VALUE, message) + + +def _declared_fields(root: MetaData) -> list[MetaData]: + """Every field declared in the tree: at the root and on every object.""" + out: list[MetaData] = [] + # ADR-0039 sanctioned own: a structural walk over the declarations themselves. + for top in root.own_children(): + if top.type == TYPE_FIELD: + out.append(top) + elif top.type == TYPE_OBJECT: + out.extend(c for c in top.own_children() if c.type == TYPE_FIELD) + return out + + +def _check_redeclared_lifecycles(entity: MetaData, sink: _Sink) -> None: + """L10: an entity's field named like an ancestor's lifecycle field that does not carry that + lifecycle's transitions. Redeclaring the field replaces it, so the base's state machine would + silently stop applying to this entity.""" + for ancestor in entity_lineage(entity)[1:]: + # ADR-0039 sanctioned own: the lifecycle fields the ancestor itself declares. + for base_field in ancestor.own_children(): + if base_field.type != TYPE_FIELD: + continue + base_transitions = lifecycle_transitions_of(ancestor, base_field) + if not base_transitions: + continue + field = next( + (c for c in entity.children() if c.type == TYPE_FIELD and c.name == base_field.name), None + ) + if field is None or field is base_field: + continue + kept = lifecycle_transitions_of(entity, field) + if all(t in kept for t in base_transitions): + continue + sink.add( + field, + ErrorCode.ERR_LIFECYCLE_REDECLARED, + f'field.{field.sub_type} "{_label(field)}" redeclares "{_label(base_field)}", which has a ' + f'lifecycle, and drops its transitions; extend it ("extends": "{ancestor.name}.{base_field.name}") ' + "or give the field another name.", + ) + + +def _check_entity_lifecycles(entity: MetaData, sink: _Sink) -> None: + """L2, L6 and L10 for one entity, over its effective (inherited) lifecycles.""" + _check_redeclared_lifecycles(entity, sink) + transitions = entity_transitions(entity) + if not transitions: + return + by_name: dict[str, MetaData] = {} + for t in transitions: + key = t.name.lower() + first = by_name.get(key) + if first is None: + by_name[key] = t + elif first is not t: + sink.add( + t, + ErrorCode.ERR_TRANSITION_NAME_COLLISION, + f'transition.action "{_label(t)}" has the same name as "{_label(first)}" ' + f'(names are compared without case); the transitions of ' + f'"{entity.name}" share one namespace (each may derive a command), so rename one.', + ) + if ( + not entity.is_abstract + and lifecycle_is_live(entity) + and not any( + c.type == TYPE_SOURCE and isinstance(c, MetaSource) and c.is_writable() for c in entity.children() + ) + ): + owners = _unique([t.parent.name if t.parent is not None else "" for t in transitions]) + sink.add( + entity, + 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.)", + ) + + +def _check_operation(op: MetaData, sink: _Sink) -> None: + """O0-O5, P1 and B1 for one operation.""" + if _is_reserved_name(op.name): + sink.add( + op, + ErrorCode.ERR_TRANSITION_NAME_COLLISION, + f'operation.{op.sub_type} "{_label(op)}" is named "{op.name}", which is a derived CRUD verb ' + f"({_RESERVED_LIST}); rename it.", + ) + _check_permission(op, sink) + + error_codes = string_list(op, OPERATION_ATTR_ERRORS) + bad = [c for c in error_codes if not BUSINESS_ERROR_CODE_PATTERN.fullmatch(c)] + dup = [c for i, c in enumerate(error_codes) if error_codes.index(c) != i] + reserved = _unique([c for c in error_codes if c in _RESERVED_CODES]) + if bad or dup or reserved: + if bad: + why = ( + f'{_quote_list(bad)} {"is not a" if len(bad) == 1 else "are not"} lower snake case ' + f'code{"" if len(bad) == 1 else "s"}' + ) + elif dup: + uniq = _unique(dup) + why = f'{_quote_list(uniq)} {"is" if len(uniq) == 1 else "are"} listed twice' + else: + why = ( + f'{_quote_list(reserved)} {"is a code" if len(reserved) == 1 else "are codes"} ' + f'the route answers itself ({", ".join(RESERVED_ERROR_CODES)})' + ) + 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 + + # O2, O3 — the target. + derived_target = derive_operation_target(op) + derived = derived_target.entity if derived_target is not None else None + target = derived + object_ref = op.get_meta_attr(OPERATION_ATTR_OBJECT_REF) + if isinstance(object_ref, str): + declared = resolve_object_on(op, object_ref) + if declared is None or declared.sub_type != OBJECT_SUBTYPE_ENTITY: + what = "names no object" if declared is None else f"is an object.{declared.sub_type}" + sink.add( + op, + ErrorCode.ERR_OPERATION_TARGET_UNRESOLVED, + f'operation.{op.sub_type} "{_label(op)}" @objectRef "{object_ref}" {what}; ' + "an operation acts on an object.entity.", + ) + return + if derived is not None and derived is not declared: + sink.add( + op, + ErrorCode.ERR_OPERATION_TARGET_MISMATCH, + f'operation.{op.sub_type} "{_label(op)}" @objectRef names "{declared.name}", but its input and ' + f'output derive "{derived.name}"; remove @objectRef or make them agree.', + ) + return + target = declared + transitions = string_list(op, OPERATION_ATTR_TRANSITIONS) if op.sub_type == OPERATION_SUBTYPE_COMMAND else [] + if transitions and target is None: + sink.add( + op, + ErrorCode.ERR_OPERATION_TARGET_UNRESOLVED, + f'operation.command "{_label(op)}" lists @transitions but has no target entity: the @inputRef does not ' + "borrow one entity's whole primary key (each key field extended exactly once), no @outputRef has a " + "base entity, and there is no @objectRef.", + ) + return + + # O4 — the transitions it may make. + if target is not None and transitions: + known = {t.name for t in entity_transitions(target)} + unknown = [n for n in _unique(transitions) if n not in known] + if unknown: + sink.add( + op, + ErrorCode.ERR_OPERATION_UNKNOWN_TRANSITION, + f'operation.command "{_label(op)}" @transitions names {_quote_list(unknown)}, which ' + f'{"is not a transition" if len(unknown) == 1 else "are not transitions"} of "{target.name}".', + ) + + # B1 — binding paths. + # 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_REST: + continue + path = b.get_meta_attr(BINDING_ATTR_PATH) + if not isinstance(path, str): + continue + placeholders = _PLACEHOLDER_RE.findall(path) + expected = primary_key_fields(target) if target is not None and operation_is_keyed(op) else [] + if sorted(placeholders) != sorted(expected): + if not expected: + tail = f'"{_label(op)}" addresses no row by key, so its path takes none.' + else: + tail = ( + f'"{_label(op)}" addresses one "{target.name}" by key, so its path takes exactly ' # type: ignore[union-attr] + f"[{_quote_list(expected)}]." + ) + sink.add( + b, + ErrorCode.ERR_BINDING_PATH_MISMATCH, + f'binding.rest on "{_label(b)}" @path "{path}" has placeholders [{_quote_list(placeholders)}]; ' + + tail, + ) + + +def validate_rules(root: MetaData, errors: list[MetaError]) -> None: + """ADR-0066 — the rules pass. Runs after reference-bearing validation, before freeze.""" + sink = _Sink(errors) + for field in _declared_fields(root): + _check_declared_transitions(field, sink) + for obj in root.children(): + if obj.type == TYPE_OBJECT and obj.sub_type == OBJECT_SUBTYPE_ENTITY: + _check_entity_lifecycles(obj, sink) + # O6 — keyed by package, then by the name without case. + by_name: dict[tuple[str, str], MetaData] = {} + for api in root.children(): + if api.type != TYPE_API: + continue + ops = [c for c in api.children() if c.type == TYPE_OPERATION] + for op in ops: + _check_operation(op, sink) + for op in ops: + pkg = effective_package_of(api) + key = (pkg, op.name.lower()) + first = by_name.get(key) + if first is None: + by_name[key] = op + elif first is not op and not _same_operation(first, op): + sink.add( + op, + ErrorCode.ERR_TRANSITION_NAME_COLLISION, + f'operation.{op.sub_type} "{_label(op)}" has the same name as "{_label(first)}" (names ' + f'are compared without case) and is not the same operation; the operations of package "{pkg}" ' + "share one namespace (each derives the permission name .), so " + "rename one, or declare both identically to expose one operation in two APIs.", + ) + _check_api_routes(ops, sink) + + +def _ref_identity(op: MetaData, attr: str) -> object: + """A reference attr's identity: the node it resolves to, else the raw value.""" + ref = op.get_meta_attr(attr) + if isinstance(ref, str): + resolved = resolve_object_on(op, ref) + return resolved if resolved is not None else ref + return ref + + +def _set_key(op: MetaData, attr: str) -> frozenset[str]: + return frozenset(string_list(op, attr)) + + +def _same_operation(a: MetaData, b: MetaData) -> bool: + """Whether two operations of one package in different APIs are one operation exposed twice (a + versioned API beside its successor, ADR-0067 section 2): the same name and subtype and the same + contract. Bindings are per API and are not compared.""" + if a.name != b.name or a.sub_type != b.sub_type: + return False + for attr in (OPERATION_ATTR_INPUT_REF, OPERATION_ATTR_OUTPUT_REF, OPERATION_ATTR_OBJECT_REF): + ia, ib = _ref_identity(a, attr), _ref_identity(b, attr) + if not (ia is ib or (not isinstance(ia, MetaData) and not isinstance(ib, MetaData) and ia == ib)): + return False + for attr in (OPERATION_ATTR_TRANSITIONS, OPERATION_ATTR_ERRORS): + if _set_key(a, attr) != _set_key(b, attr): + return False + return ( + a.get_meta_attr(OPERATION_ATTR_PERMISSION) == b.get_meta_attr(OPERATION_ATTR_PERMISSION) + and (a.get_meta_attr(OPERATION_ATTR_PUBLIC) is True) == (b.get_meta_attr(OPERATION_ATTR_PUBLIC) is True) + and (a.get_meta_attr(OPERATION_ATTR_MANY) is True) == (b.get_meta_attr(OPERATION_ATTR_MANY) is True) + ) + + +def _check_api_routes(ops: list[MetaData], sink: _Sink) -> None: + """B2 across the operations of one API.""" + by_route: dict[str, MetaData] = {} + for op in ops: + # 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_REST: + continue + path = b.get_meta_attr(BINDING_ATTR_PATH) + if not isinstance(path, str): + continue + # The effective method: the declared one, else the derived (ADR-0066 section 1). + declared_method = b.get_meta_attr(BINDING_ATTR_METHOD) + if isinstance(declared_method, str): + method = declared_method + else: + method = "POST" if op.sub_type == OPERATION_SUBTYPE_COMMAND else "GET" + route = f"{method} {_PLACEHOLDER_RE.sub('{}', path)}" + other = by_route.get(route) + if other is None: + by_route[route] = b + else: + sink.add( + b, + ErrorCode.ERR_BINDING_PATH_MISMATCH, + f'binding.rest on "{_label(b)}" declares {method} "{path}", the same route as the binding ' + f'on "{_label(other)}"; two operations cannot share a method and path.', + ) diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 2d8a3f1502..257c46c6e3 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -25,6 +25,7 @@ from .validate_source_parameter_ref import validate_source_parameter_ref from .validate_source_escapes import validate_source_escapes from .validate_reporting import validate_reporting +from .validate_rules import validate_rules from ..codegen.runtime.duration_wire import DURATION_RE from ..meta.core.reporting.reporting_constants import ( FILTER_RELATIVE_NOW, @@ -236,6 +237,8 @@ def run_validations( # FR-044 — the reporting vocabulary (dimension / measure / segment / # object.report) and relative-date filter values (rules D1-F2). validate_reporting(root, errors) + # ADR-0066 — business rules: operations and lifecycles. + validate_rules(root, errors) _validate_origin_paths(root, errors) # FR-024 B6 — an entity's origin-bearing field needs a read-capable source. _validate_derived_field_providability(root, errors) @@ -4569,6 +4572,23 @@ def check(lit: object, ref: object) -> str | None: return None +def condition_message(condition: object, obj: MetaData, label: str) -> str | None: + """Why a ``@condition`` (the attr.expression grammar) over *obj*'s own fields is refused, or + None when it is legal. *label* opens the message. One rule for a cross-field validator's + condition and a transition's guard (ADR-0066): every named field is a field of *obj*, and the + expression passes :func:`_condition_problem`. Mirrors TS ``conditionMessage``.""" + field_names = {f.name for f in obj.fields()} + refs: set[str] = set() + _expr_field_refs(condition, refs) + unknown = sorted(refs - field_names) + if unknown: + names = ", ".join(f'"{u}"' for u in unknown) + verb = "is not a field" if len(unknown) == 1 else "are not fields" + return f'{label} names {names}, which {verb} of "{obj.name}".' + problem = _condition_problem(condition, obj) + return None if problem is None else f"{label} {problem}" + + def _validate_cross_field_validators(root: MetaData, errors: list[MetaError], strict: bool = False) -> None: """Cross-field validator rules. *strict*: a strict load already refuses an atLeastOne ``@max`` as an unregistered attr, so that check runs only on the default load (one error per node).""" @@ -4577,7 +4597,6 @@ def _validate_cross_field_validators(root: MetaData, errors: list[MetaError], st for obj in root.children(): if obj.type != TYPE_OBJECT: continue - field_names = {f.name for f in obj.fields()} for v in obj.own_children(): if v.type != TYPE_VALIDATOR or v.sub_type not in vc.CROSS_FIELD_VALIDATOR_SUBTYPES: continue @@ -4633,26 +4652,11 @@ def _validate_cross_field_validators(root: MetaData, errors: list[MetaError], st condition = v.get_meta_attr(vc.VALIDATOR_ATTR_CONDITION) if condition is None: continue - label = f'validator.{v.sub_type} "{obj.name}.{v.name}" @condition' - refs: set[str] = set() - _expr_field_refs(condition, refs) - unknown = sorted(refs - field_names) - if unknown: - names = ", ".join(f'"{u}"' for u in unknown) - verb = "is not a field" if len(unknown) == 1 else "are not fields" - errors.append(MetaError( - code=ErrorCode.ERR_BAD_ATTR_VALUE, - message=f'{label} names {names}, which {verb} of "{obj.name}".', - envelope=v.source, - )) - continue - problem = _condition_problem(condition, obj) - if problem is not None: - errors.append(MetaError( - code=ErrorCode.ERR_BAD_ATTR_VALUE, - message=f"{label} {problem}", - envelope=v.source, - )) + message = condition_message( + condition, obj, f'validator.{v.sub_type} "{obj.name}.{v.name}" @condition' + ) + if message is not None: + errors.append(MetaError(code=ErrorCode.ERR_BAD_ATTR_VALUE, message=message, envelope=v.source)) # field.enum @maxLength — the column length of a string-stored enum: diff --git a/server/python/src/metaobjects/meta/core/api/__init__.py b/server/python/src/metaobjects/meta/core/api/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/server/python/src/metaobjects/meta/core/api/api_constants.py b/server/python/src/metaobjects/meta/core/api/api_constants.py new file mode 100644 index 0000000000..8e24c45146 --- /dev/null +++ b/server/python/src/metaobjects/meta/core/api/api_constants.py @@ -0,0 +1,62 @@ +"""Declared API surface constants (ADR-0030, ADR-0066): type names, subtypes and attribute +keys for ``api.*``, ``operation.*`` and ``binding.*``. Mirrors TS ``core/api/api-constants.ts``. +""" +import re + +# 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,) + +OPERATION_SUBTYPE_COMMAND = "command" +OPERATION_SUBTYPE_QUERY = "query" +OPERATION_SUBTYPES = (OPERATION_SUBTYPE_COMMAND, OPERATION_SUBTYPE_QUERY) + +# The HTTP binding of an operation (overrides the derived method and path). +BINDING_SUBTYPE_REST = "rest" +BINDING_SUBTYPES = (BINDING_SUBTYPE_REST,) + +# Attrs on operation.* (@permission / @public are on transition.* too). +OPERATION_ATTR_INPUT_REF = "inputRef" +OPERATION_ATTR_OUTPUT_REF = "outputRef" +OPERATION_ATTR_OBJECT_REF = "objectRef" +OPERATION_ATTR_TRANSITIONS = "transitions" +OPERATION_ATTR_PERMISSION = "permission" +OPERATION_ATTR_PUBLIC = "public" +OPERATION_ATTR_ERRORS = "errors" +OPERATION_ATTR_MANY = "many" + +# Attrs on binding.rest. +BINDING_ATTR_METHOD = "method" +BINDING_ATTR_PATH = "path" +HTTP_METHODS = ("GET", "POST", "PUT", "PATCH", "DELETE") + +# 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") + +# A declared @permission: a dotted identifier path (``purchasing.approve``). A package prefix may +# use ``::``, so a derived name can be declared as it is. Matched with ``fullmatch`` so a +# trailing newline does not match. +PERMISSION_NAME_PATTERN = re.compile( + r"[A-Za-z_][A-Za-z0-9_]*(?:(?:\.|::)[A-Za-z_][A-Za-z0-9_]*)*" +) + +# A declared business error code: lower snake case. +BUSINESS_ERROR_CODE_PATTERN = re.compile(r"^[a-z][a-z0-9]*(_[a-z0-9]+)*$") + +# Wire error codes an operation's route answers on its own, so a body may not declare them in +# @errors (O5). Order matters: it appears in a message. +RESERVED_ERROR_CODES = ( + "not_found", + "forbidden", + "invalid_transition", + "transition_condition_failed", + "state_managed", + "validation", + "invalid_json", + "invalid_id", + "method_not_allowed", + "constraint_violation", + "internal", +) diff --git a/server/python/src/metaobjects/meta/core/api/meta_api.py b/server/python/src/metaobjects/meta/core/api/meta_api.py new file mode 100644 index 0000000000..c3b0f65a9a --- /dev/null +++ b/server/python/src/metaobjects/meta/core/api/meta_api.py @@ -0,0 +1,82 @@ +"""Node classes for the declared API surface (ADR-0030, ADR-0066): ``api.*``, +``operation.*`` and ``binding.*``. Accessors are RESOLVING (ADR-0039) — Python naming +inversion: ``attr()`` is own-only, so reads go through ``get_meta_attr()``. +Mirrors TS ``core/api/meta-api.ts``. +""" +from __future__ import annotations + +from ...meta_data import MetaData +from ....shared.base_types import TYPE_BINDING, TYPE_OPERATION +from .api_constants import ( + BINDING_ATTR_METHOD, + BINDING_ATTR_PATH, + OPERATION_ATTR_ERRORS, + OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_MANY, + OPERATION_ATTR_OBJECT_REF, + OPERATION_ATTR_OUTPUT_REF, + OPERATION_ATTR_PERMISSION, + OPERATION_ATTR_PUBLIC, + OPERATION_ATTR_TRANSITIONS, +) + + +def _string_attr(node: MetaData, name: str) -> str | None: + v = node.get_meta_attr(name) # ADR-0039: resolving + return v if isinstance(v, str) else None + + +def _string_list_attr(node: MetaData, name: str) -> list[str]: + """A bare string authored for an array attr is ONE element.""" + v = node.get_meta_attr(name) # ADR-0039: resolving + if isinstance(v, list): + return [x for x in v if isinstance(x, str)] + return [v] if isinstance(v, str) else [] + + +class MetaApi(MetaData): + """``api.operational`` — a named surface whose children are operations.""" + + def operations(self) -> list["MetaOperation"]: + return [c for c in self.children() if c.type == TYPE_OPERATION and isinstance(c, MetaOperation)] + + +class MetaOperation(MetaData): + """``operation.command`` / ``operation.query``.""" + + def input_ref(self) -> str | None: + return _string_attr(self, OPERATION_ATTR_INPUT_REF) + + def output_ref(self) -> str | None: + return _string_attr(self, OPERATION_ATTR_OUTPUT_REF) + + def object_ref(self) -> str | None: + return _string_attr(self, OPERATION_ATTR_OBJECT_REF) + + def transitions(self) -> list[str]: + return _string_list_attr(self, OPERATION_ATTR_TRANSITIONS) + + def errors(self) -> list[str]: + return _string_list_attr(self, OPERATION_ATTR_ERRORS) + + def permission(self) -> str | None: + return _string_attr(self, OPERATION_ATTR_PERMISSION) + + def is_public(self) -> bool: + return self.get_meta_attr(OPERATION_ATTR_PUBLIC) is True + + def is_many(self) -> bool: + return self.get_meta_attr(OPERATION_ATTR_MANY) is True + + def bindings(self) -> list["MetaBinding"]: + return [c for c in self.children() if c.type == TYPE_BINDING and isinstance(c, MetaBinding)] + + +class MetaBinding(MetaData): + """``binding.rest``.""" + + def method(self) -> str | None: + return _string_attr(self, BINDING_ATTR_METHOD) + + def path(self) -> str | None: + return _string_attr(self, BINDING_ATTR_PATH) diff --git a/server/python/src/metaobjects/meta/core/transition/__init__.py b/server/python/src/metaobjects/meta/core/transition/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/server/python/src/metaobjects/meta/core/transition/lifecycle.py b/server/python/src/metaobjects/meta/core/transition/lifecycle.py new file mode 100644 index 0000000000..421209a54e --- /dev/null +++ b/server/python/src/metaobjects/meta/core/transition/lifecycle.py @@ -0,0 +1,314 @@ +"""Lifecycle and operation-target derivation (ADR-0066), shared by the loader's rules pass +and ``verify``'s rules gate. Everything here is DERIVED: a lifecycle, its states, its initial +and terminal states and an operation's target entity have no vocabulary of their own. Every +port implements these rules the same way. Mirrors TS ``core/transition/lifecycle.ts``. + +Reads are RESOLVING (ADR-0039): a transition declared on a base entity's field is a +transition of every entity that extends it. Python ``attr()`` is OWN-ONLY, so every attr +read here goes through ``get_meta_attr()``. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional + +from ....naming_refs import ( + CHILD_REF_SEP, + effective_package_of, + resolve_object_ref, + top_level_node_of, +) +from ....shared.base_types import TYPE_FIELD, TYPE_IDENTITY, TYPE_OBJECT, TYPE_SOURCE, TYPE_TRANSITION +from ....shared.separators import PACKAGE_SEP +from ...meta_data import MetaData +from ..api.api_constants import ( + OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_MANY, + OPERATION_ATTR_OBJECT_REF, + OPERATION_ATTR_OUTPUT_REF, + OPERATION_SUBTYPE_QUERY, +) +from ..field.field_constants import FIELD_ATTR_DEFAULT, FIELD_ATTR_VALUES, FIELD_SUBTYPE_ENUM +from ..identity.identity_constants import IDENTITY_ATTR_FIELDS, IDENTITY_SUBTYPE_PRIMARY +from ..object.object_constants import ( + OBJECT_SUBTYPE_ENTITY, + OBJECT_SUBTYPE_PROJECTION, + OBJECT_SUBTYPE_VALUE, +) +from .transition_constants import TRANSITION_ATTR_FROM, TRANSITION_ATTR_TO, TRANSITION_SUBTYPE_ACTION + + +def string_list(node: MetaData, attr: str) -> list[str]: + """A string-array attr read resolving; a bare string is ONE element.""" + v = node.get_meta_attr(attr) # ADR-0039: resolving + if isinstance(v, list): + return [x for x in v if isinstance(x, str)] + return [v] if isinstance(v, str) else [] + + +def _string_value(node: MetaData, attr: str) -> Optional[str]: + v = node.get_meta_attr(attr) # ADR-0039: resolving + return v if isinstance(v, str) else None + + +def transitions_of(field: MetaData) -> list[MetaData]: + """The ``transition.action`` children of a field, resolving.""" + return [ + c for c in field.children() + if c.type == TYPE_TRANSITION and c.sub_type == TRANSITION_SUBTYPE_ACTION + ] + + +def entity_lineage(entity: MetaData) -> list[MetaData]: + """An entity and every entity it extends, nearest first.""" + out: list[MetaData] = [] + e: Optional[MetaData] = entity + while e is not None and e not in out: + out.append(e) + e = e.super_data + return out + + +def lifecycle_transitions_of(entity: MetaData, field: MetaData) -> list[MetaData]: + """The transitions a field gives an entity: those declared on a field of the entity itself + or of an entity it extends. A transition reached only through the field's own ``extends`` + of another entity's field is not one (ADR-0066 section 2).""" + lineage = entity_lineage(entity) + out: list[MetaData] = [] + for t in transitions_of(field): + owner = t.parent.parent if t.parent is not None else None + if owner is not None and owner in lineage: + out.append(t) + return out + + +@dataclass(frozen=True) +class Lifecycle: + """One lifecycle of an entity: an enum field with at least one transition.""" + + field: MetaData + #: The enum's @values, in declaration order. + states: tuple[str, ...] + #: The enum's @default; None only on a model the loader refused. + initial: Optional[str] + transitions: tuple[MetaData, ...] + + +def lifecycles_of(obj: MetaData) -> list[Lifecycle]: + """The lifecycles of an object, in effective field order. Only an ``object.entity`` has any.""" + if obj.type != TYPE_OBJECT or obj.sub_type != OBJECT_SUBTYPE_ENTITY: + return [] + out: list[Lifecycle] = [] + for field in obj.children(): + if field.type != TYPE_FIELD or field.sub_type != FIELD_SUBTYPE_ENUM: + continue + transitions = lifecycle_transitions_of(obj, field) + if not transitions: + continue + initial = field.get_meta_attr(FIELD_ATTR_DEFAULT) # ADR-0039: resolving + out.append(Lifecycle( + field=field, + states=tuple(string_list(field, FIELD_ATTR_VALUES)), + initial=initial if isinstance(initial, str) else None, + transitions=tuple(transitions), + )) + return out + + +def lifecycle_is_live(entity: MetaData) -> bool: + """Whether an entity's lifecycles are live: it declares or inherits a source (RESOLVING + ``children()``, ADR-0039). A lifecycle on an entity with no source loads and is inert: it + derives no command (ADR-0066 section 2).""" + return any(c.type == TYPE_SOURCE for c in entity.children()) + + +def entity_transitions(obj: MetaData) -> list[MetaData]: + """Every transition of an entity, across all its lifecycles.""" + return [t for l in lifecycles_of(obj) for t in l.transitions] + + +def transition_from(t: MetaData) -> list[str]: + """A transition's @from (resolving).""" + return string_list(t, TRANSITION_ATTR_FROM) + + +def transition_to(t: MetaData) -> Optional[str]: + """A transition's @to (resolving).""" + return _string_value(t, TRANSITION_ATTR_TO) + + +def reachable_states(l: Lifecycle) -> set[str]: + """The states reachable from the initial state, following every transition.""" + seen: set[str] = set() + if l.initial is None: + return seen + queue = [l.initial] + seen.add(l.initial) + while queue: + s = queue.pop(0) + for t in l.transitions: + to = transition_to(t) + if to is not None and s in transition_from(t) and to not in seen: + seen.add(to) + queue.append(to) + return seen + + +def terminal_states(l: Lifecycle) -> list[str]: + """The members no transition leaves (a self-transition counts as leaving).""" + leaving = {s for t in l.transitions for s in transition_from(t)} + return [s for s in l.states if s not in leaving] + + +def primary_key_fields(entity: MetaData) -> list[str]: + """The primary key field names of an entity: its effective ``identity.primary`` @fields.""" + primary = next( + (c for c in entity.children() if c.type == TYPE_IDENTITY and c.sub_type == IDENTITY_SUBTYPE_PRIMARY), + None, + ) + return [] if primary is None else string_list(primary, IDENTITY_ATTR_FIELDS) + + +def referrer_package_of(node: MetaData) -> str: + """The package a node's references resolve in: its top-level node's effective package.""" + return effective_package_of(top_level_node_of(node)) + + +def _owner_of(ref: str) -> str: + """The owner part of a reference: everything before the child dot of its last ``::`` segment.""" + last_sep = ref.rfind(PACKAGE_SEP) + seg_start = 0 if last_sep < 0 else last_sep + len(PACKAGE_SEP) + dot = ref.find(CHILD_REF_SEP, seg_start) + return ref if dot < 0 else ref[:dot] + + +def resolve_object_on(node: MetaData, ref: str) -> Optional[MetaData]: + """Resolve an object reference written on *node* (owner part only).""" + return resolve_object_ref(node.root(), _owner_of(ref), referrer_package_of(node)) + + +def _extended_member(f: MetaData) -> Optional[tuple[MetaData, str]]: + """The object a field's ``extends`` NAMES, and the member it names there. ``id extends + PurchaseRequest.id`` names PurchaseRequest even when PurchaseRequest inherits ``id`` from an + abstract base, which is where the resolved super node physically lives.""" + ref = f.super_ref + sup = f.super_data + if ref is None or sup is None: + return None + last_sep = ref.rfind(PACKAGE_SEP) + seg_start = 0 if last_sep < 0 else last_sep + len(PACKAGE_SEP) + dot = ref.find(CHILD_REF_SEP, seg_start) + if dot > seg_start: + named = resolve_object_ref(f.root(), ref[:dot], referrer_package_of(f)) + if named is not None: + return named, sup.name + parent = sup.parent + if parent is not None and parent.type == TYPE_OBJECT: + return parent, sup.name + return None + + +def _borrowed_key_entities(value: MetaData) -> list[MetaData]: + """The entities whose whole primary key a value object borrows, once: every primary key + field of the ``object.entity`` is extended by exactly one field of the value. Part of a + composite key, or one key field borrowed twice, names no single row, so borrows nothing.""" + counts: dict[MetaData, dict[str, int]] = {} + for f in value.children(): + if f.type != TYPE_FIELD: + continue + ext = _extended_member(f) + if ext is None or ext[0].sub_type != OBJECT_SUBTYPE_ENTITY: + continue + owner, member = ext + if member not in primary_key_fields(owner): + continue + members = counts.setdefault(owner, {}) + members[member] = members.get(member, 0) + 1 + return [ + owner for owner, members in counts.items() + if all(members.get(k) == 1 for k in primary_key_fields(owner)) + ] + + +def projection_base_entity(projection: MetaData) -> Optional[MetaData]: + """The base entity of a projection: the entity its extended identity names, else the one + entity its extended fields name. None when there is none or more than one.""" + for ident in projection.children(): + if ident.type != TYPE_IDENTITY: + continue + ext = _extended_member(ident) + if ext is not None and ext[0].sub_type == OBJECT_SUBTYPE_ENTITY: + return ext[0] + owners: list[MetaData] = [] + for f in projection.children(): + if f.type != TYPE_FIELD: + continue + ext = _extended_member(f) + if ext is not None and ext[0].sub_type == OBJECT_SUBTYPE_ENTITY and ext[0] not in owners: + owners.append(ext[0]) + return owners[0] if len(owners) == 1 else None + + +@dataclass(frozen=True) +class DerivedTarget: + """How an operation's target was derived. ``via == "input"`` means the input borrows the + target's key.""" + + entity: MetaData + via: str + + +def derive_operation_target(op: MetaData) -> Optional[DerivedTarget]: + """The target entity derived from an operation's shapes, or None: + + 1. the one entity whose whole primary key the ``@inputRef`` value borrows (by ``extends``), + each key field once; + 2. else the ``@outputRef``: an entity is its own target, a projection its base entity. + + Whole keys of two entities, part of a key, or one key field borrowed twice derive nothing + from the input. + """ + input_ref = _string_value(op, OPERATION_ATTR_INPUT_REF) + if input_ref is not None: + inp = resolve_object_on(op, input_ref) + if inp is not None and inp.sub_type == OBJECT_SUBTYPE_VALUE: + borrowed = _borrowed_key_entities(inp) + if len(borrowed) == 1: + return DerivedTarget(borrowed[0], "input") + output_ref = _string_value(op, OPERATION_ATTR_OUTPUT_REF) + if output_ref is not None: + out = resolve_object_on(op, output_ref) + if out is not None and out.sub_type == OBJECT_SUBTYPE_ENTITY: + return DerivedTarget(out, "output") + if out is not None and out.sub_type == OBJECT_SUBTYPE_PROJECTION: + base = projection_base_entity(out) + if base is not None: + return DerivedTarget(base, "output") + return None + + +def operation_target(op: MetaData) -> Optional[MetaData]: + """The operation's target: the declared ``@objectRef`` when it names an entity, else the + derived one.""" + declared = _string_value(op, OPERATION_ATTR_OBJECT_REF) + if declared is not None: + node = resolve_object_on(op, declared) + return node if node is not None and node.sub_type == OBJECT_SUBTYPE_ENTITY else None + derived = derive_operation_target(op) + return derived.entity if derived is not None else None + + +def operation_is_keyed(op: MetaData) -> bool: + """Whether the operation addresses one row of its target by key, so its derived path is + ``//{key}/``: its input borrows the target's key, or it is a query + with no input and no @many whose target comes from its output (a get by key).""" + derived = derive_operation_target(op) + if derived is None: + return False + if derived.via == "input": + return True + return ( + op.sub_type == OPERATION_SUBTYPE_QUERY + and _string_value(op, OPERATION_ATTR_INPUT_REF) is None + and op.get_meta_attr(OPERATION_ATTR_MANY) is not True + ) diff --git a/server/python/src/metaobjects/meta/core/transition/meta_transition.py b/server/python/src/metaobjects/meta/core/transition/meta_transition.py new file mode 100644 index 0000000000..0e2978d0f1 --- /dev/null +++ b/server/python/src/metaobjects/meta/core/transition/meta_transition.py @@ -0,0 +1,38 @@ +"""MetaTransition — node class for ``transition.*`` (ADR-0066). Accessors are RESOLVING +(ADR-0039): a transition declared on a base entity's field applies, unchanged, to every +entity that extends it. Python ``attr()`` is own-only, so reads go through +``get_meta_attr()``. Mirrors TS ``core/transition/meta-transition.ts``. +""" +from __future__ import annotations + +from ...meta_data import MetaData +from .transition_constants import ( + TRANSITION_ATTR_CONDITION, + TRANSITION_ATTR_FROM, + TRANSITION_ATTR_PERMISSION, + TRANSITION_ATTR_PUBLIC, + TRANSITION_ATTR_TO, +) + + +class MetaTransition(MetaData): + def from_states(self) -> list[str]: + """The states this move may start from. A bare string is one element.""" + v = self.get_meta_attr(TRANSITION_ATTR_FROM) # ADR-0039: resolving + if isinstance(v, list): + return [x for x in v if isinstance(x, str)] + return [v] if isinstance(v, str) else [] + + def to(self) -> str | None: + v = self.get_meta_attr(TRANSITION_ATTR_TO) + return v if isinstance(v, str) else None + + def condition(self) -> object: + return self.get_meta_attr(TRANSITION_ATTR_CONDITION) + + def permission(self) -> str | None: + v = self.get_meta_attr(TRANSITION_ATTR_PERMISSION) + return v if isinstance(v, str) else None + + def is_public(self) -> bool: + return self.get_meta_attr(TRANSITION_ATTR_PUBLIC) is True diff --git a/server/python/src/metaobjects/meta/core/transition/transition_constants.py b/server/python/src/metaobjects/meta/core/transition/transition_constants.py new file mode 100644 index 0000000000..62cc2adbbd --- /dev/null +++ b/server/python/src/metaobjects/meta/core/transition/transition_constants.py @@ -0,0 +1,15 @@ +"""Lifecycle constants (ADR-0066): the ``transition`` type, its subtypes and attrs. + +A lifecycle has no vocabulary of its own: it is a ``field.enum`` with at least one +``transition.action`` child. Mirrors TS ``core/transition/transition-constants.ts``. +""" +TRANSITION_SUBTYPE_ACTION = "action" +# RESERVED, not registered (ADR-0066): a move made by time. +TRANSITION_SUBTYPE_TIMED_RESERVED = "timed" +TRANSITION_SUBTYPES = (TRANSITION_SUBTYPE_ACTION,) + +TRANSITION_ATTR_FROM = "from" +TRANSITION_ATTR_TO = "to" +TRANSITION_ATTR_CONDITION = "condition" +TRANSITION_ATTR_PERMISSION = "permission" +TRANSITION_ATTR_PUBLIC = "public" diff --git a/server/python/src/metaobjects/meta/meta_root.py b/server/python/src/metaobjects/meta/meta_root.py index d3fd314db9..8af20a3dfa 100644 --- a/server/python/src/metaobjects/meta/meta_root.py +++ b/server/python/src/metaobjects/meta/meta_root.py @@ -3,6 +3,7 @@ from ..naming import NamingRules from ..api_settings import ApiSettings +from ..rules_settings import DEFAULT_RULES_SETTINGS, RulesSettings from ..wire import WireFormat from .meta_data import MetaData @@ -22,5 +23,8 @@ def __init__(self, type_: str, sub_type: str, name: str) -> None: # REST surface), attached by the same project-aware loads as `naming`; read with # `wire_of()`. `native` for both keys until a load attaches the project's own. self.wire: WireFormat = WireFormat() + # ADR-0066 — the project `rules` / `verify` settings, attached by the same project-aware + # loads as `wire`; read with `rules_settings_of()`. Defaults until a load attaches them. + self.rules_settings: RulesSettings = DEFAULT_RULES_SETTINGS # The project `api` setting (page size, unknown-field rule), attached the same way; read with `api_of()`. self.api: ApiSettings = ApiSettings() diff --git a/server/python/src/metaobjects/naming_refs.py b/server/python/src/metaobjects/naming_refs.py index 3b9742c0cd..3ddc678a4c 100644 --- a/server/python/src/metaobjects/naming_refs.py +++ b/server/python/src/metaobjects/naming_refs.py @@ -44,7 +44,8 @@ TEMPLATE_ATTR_PAYLOAD_REF, TEMPLATE_ATTR_RESPONSE_REF, ) -from .shared.base_types import TYPE_OBJECT +from .meta.core.api.api_constants import OPERATION_ATTR_INPUT_REF, OPERATION_ATTR_OUTPUT_REF +from .shared.base_types import TYPE_OBJECT, TYPE_TRANSITION from .shared.separators import PACKAGE_SEP from .top_level_index import TopLevelView, find_top_level_by_key @@ -66,7 +67,10 @@ #: relationship/field tail; ``@parameterRef``/``@payloadRef``/``@responseRef`` name #: value-objects. The same set is used in every port. ``@sourceRefField`` (a FK FIELD #: name) and ``@implementedBy`` (which may name a template as well as an object) are -#: NOT in the set. Mirrors TS REF_BEARING_ATTR_NAMES. +#: NOT in the set. An operation's ``@inputRef``/``@outputRef``/``@objectRef`` are (ADR-0066). +#: The set is keyed by NAME, so a node type that reuses one of these names for something +#: else is excluded by :func:`is_ref_bearing_attr`: a ``transition.action @from`` lists enum +#: members. Mirrors TS REF_BEARING_ATTR_NAMES. REF_BEARING_ATTR_NAMES: frozenset[str] = frozenset({ RELATIONSHIP_ATTR_OBJECT_REF, # == FIELD_ATTR_OBJECT_REF ("objectRef") FIELD_ATTR_OBJECT_REF, @@ -79,9 +83,18 @@ TEMPLATE_ATTR_PAYLOAD_REF, TEMPLATE_ATTR_RESPONSE_REF, OBJECT_REPORT_ATTR_SPINE, + OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_OUTPUT_REF, }) +def is_ref_bearing_attr(node: "MetaData", attr_name: str) -> bool: + """True when *attr_name* on *node* holds an object reference: in + REF_BEARING_ATTR_NAMES, and not on a transition.*, whose @from names + members of its enum (ADR-0066).""" + return attr_name in REF_BEARING_ATTR_NAMES and node.type != TYPE_TRANSITION + + def split_child_tail(raw: str) -> tuple[str, str]: """Split a ref into its owner part and any FR-024 dotted child tail. diff --git a/server/python/src/metaobjects/rules_check.py b/server/python/src/metaobjects/rules_check.py new file mode 100644 index 0000000000..8fc85a4a81 --- /dev/null +++ b/server/python/src/metaobjects/rules_check.py @@ -0,0 +1,346 @@ +"""``metaobjects verify`` — the business-rules gate (ADR-0066). + +The loader refuses a model whose operations or lifecycles are malformed. This gate reports +what loads clean but is almost certainly not what the author meant: a state nothing can +reach, a lifecycle that cannot move, a transition nothing can make, and (by setting) a +permission name the model derived instead of declaring. + +Mirrors the TS reference ``packages/cli/src/lib/rules-check.ts``: the codes, severities, +paths and message text. ``fixtures/rules-check-conformance/`` is the contract. A model that +declares no operation and no transition gets no diagnostics, no summary and no gate row: +opt-in by declaration, so an existing project sees no change. + +Checks, in the order they are reported: + +* ``WARN_LIFECYCLE_UNREACHABLE_STATE``: states no transition reaches from the initial state + (severity: ``verify.lifecycle.unreachable``) +* ``WARN_LIFECYCLE_INITIAL_TERMINAL``: the initial state is one no transition leaves +* ``WARN_TRANSITION_UNREACHABLE``: a transition whose every @from state is unreachable + (severity: ``verify.lifecycle.unreachable``) +* ``WARN_TRANSITION_PERMISSION_SHADOWED``: a transition declaring @permission or @public: true + that derives no command of its own, so the attribute is never read (always a warning) +* ``WARN_PERMISSION_DERIVED_NAME``: a transition that derives its own command, or an + operation, with no @permission and not @public (severity: ``rules.permissions.names``) + +Lifecycles are checked once per declaring field, so a lifecycle on an abstract base is +reported once, not once per inheritor. A derived command exists per concrete entity, so the +permission check runs per concrete entity and names it. + +ADR-0039 NAMING INVERSION: Python ``attr()`` is OWN-ONLY, so every read here is +``get_meta_attr()`` (resolving). +""" +from __future__ import annotations + +from dataclasses import dataclass + +from metaobjects.meta.core.api.api_constants import ( + OPERATION_ATTR_PERMISSION, + OPERATION_ATTR_PUBLIC, + OPERATION_ATTR_TRANSITIONS, + OPERATION_SUBTYPE_COMMAND, +) +from metaobjects.meta.core.object.object_constants import OBJECT_SUBTYPE_ENTITY +from metaobjects.meta.core.transition.lifecycle import ( + Lifecycle, + entity_lineage, + entity_transitions, + lifecycle_is_live, + lifecycles_of, + operation_target, + reachable_states, + terminal_states, + transition_from, +) +from metaobjects.meta.meta_data import MetaData +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.shared.base_types import TYPE_API, TYPE_OBJECT, TYPE_OPERATION +from metaobjects.shared.separators import PACKAGE_SEP + +WARN_LIFECYCLE_UNREACHABLE_STATE = "WARN_LIFECYCLE_UNREACHABLE_STATE" +WARN_LIFECYCLE_INITIAL_TERMINAL = "WARN_LIFECYCLE_INITIAL_TERMINAL" +WARN_TRANSITION_UNREACHABLE = "WARN_TRANSITION_UNREACHABLE" +WARN_PERMISSION_DERIVED_NAME = "WARN_PERMISSION_DERIVED_NAME" +WARN_TRANSITION_PERMISSION_SHADOWED = "WARN_TRANSITION_PERMISSION_SHADOWED" + + +@dataclass(frozen=True) +class RulesSummary: + """What the model declares, for the line ``verify`` prints on every run.""" + + #: Declared operations, across every ``api.operational``. + operations: int + #: Lifecycles: enum fields that declare at least one transition. + lifecycles: int + #: Declared transitions, across every lifecycle. + transitions: int + + +@dataclass(frozen=True) +class RulesCheckResult: + diagnostics: list[Diagnostic] + #: ``None`` when the model declares no operation and no transition. + summary: RulesSummary | None + + +def _quote_list(xs: list[str]) -> str: + return ", ".join(f'"{x}"' for x in xs) + + +def rules_address(node: MetaData) -> str: + """A node's package-qualified address: ``acme::shop::Order.status.submit``.""" + parts: list[str] = [] + n: MetaData | None = node + while n is not None and n.parent is not None: + if n.name != "": + parts.insert(0, n.name) + n = n.parent + pkg = effective_package_of(top_level_node_of(node)) + return ".".join(parts) if pkg == "" else f"{pkg}{PACKAGE_SEP}{'.'.join(parts)}" + + +def _derived_permission_name(owner: MetaData, path: str) -> str: + """The permission name a node gets when it declares none, ``.``: the path is + ```` for a declared operation and ``.`` for a transition's + derived command, so two entities' transitions of one name ask about different permissions.""" + pkg = effective_package_of(top_level_node_of(owner)) + return path if pkg == "" else f"{pkg}.{path}" + + +def _needs_permission_name(node: MetaData) -> bool: + return ( + node.get_meta_attr(OPERATION_ATTR_PERMISSION) is None + and node.get_meta_attr(OPERATION_ATTR_PUBLIC) is not True + ) + + +def _entities(root: MetaData) -> list[MetaData]: + return [c for c in root.children() if c.type == TYPE_OBJECT and c.sub_type == OBJECT_SUBTYPE_ENTITY] + + +def _operations(root: MetaData) -> list[MetaData]: + return [ + op + for api in root.children() + if api.type == TYPE_API + for op in api.children() + if op.type == TYPE_OPERATION + ] + + +def _declared_lifecycles(root: MetaData) -> list[Lifecycle]: + """Every lifecycle of the model, once per declaring field, in model order.""" + seen: set[MetaData] = set() + out: list[Lifecycle] = [] + for entity in _entities(root): + for l in lifecycles_of(entity): + if l.field in seen: + continue + seen.add(l.field) + out.append(l) + return out + + +def _check_lifecycle(l: Lifecycle, settings: RulesSettings, out: list[Diagnostic]) -> None: + where = rules_address(l.field) + initial = l.initial + if initial is None: + return # the loader refused this model (ERR_LIFECYCLE_NO_INITIAL) + reachable = reachable_states(l) + unreachable_severity = None if settings.lifecycle_unreachable == "off" else settings.lifecycle_unreachable + + if unreachable_severity is not None: + unreachable = [s for s in l.states if s not in reachable] + if unreachable: + one = len(unreachable) == 1 + out.append(Diagnostic( + severity=unreachable_severity, + code=WARN_LIFECYCLE_UNREACHABLE_STATE, + path=where, + message=( + f'{"state" if one else "states"} {_quote_list(unreachable)} of "{l.field.name}" ' + f'cannot be reached from the initial state "{initial}" by any transition. ' + "Add the transition that leads there, or set verify.lifecycle.unreachable if only seeded data uses " + f'{"it" if one else "them"}.' + ), + )) + + if initial in terminal_states(l): + out.append(Diagnostic( + severity=SEVERITY_WARN, + code=WARN_LIFECYCLE_INITIAL_TERMINAL, + path=where, + message=( + f'the initial state "{initial}" of "{l.field.name}" is terminal: no transition leaves it, ' + "so no row of this lifecycle can ever move." + ), + )) + + if unreachable_severity is not None: + for t in l.transitions: + frm = transition_from(t) + if not frm or any(s in reachable for s in frm): + continue + out.append(Diagnostic( + severity=unreachable_severity, + code=WARN_TRANSITION_UNREACHABLE, + path=rules_address(t), + message=( + f'transition "{t.name}" starts only from {_quote_list(frm)}, which no transition reaches from ' + f'the initial state "{initial}", so it can never be made.' + ), + )) + + +@dataclass(frozen=True) +class _Claim: + """One command's claim on a transition node, made for its target entity.""" + + target: MetaData + op: MetaData + + +def _claimed_transitions(root: MetaData) -> dict[MetaData, list[_Claim]]: + """Each transition node the declared commands claim, with the claims on it in model order.""" + claimed: dict[MetaData, list[_Claim]] = {} + for op in _operations(root): + if op.sub_type != OPERATION_SUBTYPE_COMMAND: + continue + target = operation_target(op) + if target is None: + continue + raw = op.get_meta_attr(OPERATION_ATTR_TRANSITIONS) # ADR-0039: resolving + names = {x for x in raw if isinstance(x, str)} if isinstance(raw, list) else set() + for t in entity_transitions(target): + if t.name in names: + claimed.setdefault(t, []).append(_Claim(target, op)) + return claimed + + +def _claims_on(claimed: dict[MetaData, list[_Claim]], entity: MetaData, t: MetaData) -> list[_Claim]: + """The claims that cover transition ``t`` on ``entity``: those made for the entity or an entity it extends.""" + lineage = entity_lineage(entity) + return [c for c in claimed.get(t, []) if c.target in lineage] + + +def _derives_command( + claimed: dict[MetaData, list[_Claim]], settings: RulesSettings, entity: MetaData, t: MetaData +) -> bool: + """Whether ``t``, carried by ``entity``, derives a command of its own under the setting.""" + if settings.lifecycle_commands == "none": + return False + if settings.lifecycle_commands == "all": + return True + return not _claims_on(claimed, entity, t) + + +def _command_entities(root: MetaData) -> list[MetaData]: + """The entities a transition can derive a command on: concrete, with a source.""" + return [e for e in _entities(root) if not e.is_abstract and lifecycle_is_live(e)] + + +def _check_shadowed_permissions(root: MetaData, settings: RulesSettings, out: list[Diagnostic]) -> None: + """A transition's @permission or @public is read only by the command derived from it. One that + derives no command for any concrete entity carrying it declares an attribute nothing reads.""" + if settings.lifecycle_commands == "all": + return + claimed = _claimed_transitions(root) + carriers: dict[MetaData, list[MetaData]] = {} + for entity in _command_entities(root): + for t in entity_transitions(entity): + carriers.setdefault(t, []).append(entity) + for t, entities_with_t in carriers.items(): + permission = t.get_meta_attr(OPERATION_ATTR_PERMISSION) + is_public = t.get_meta_attr(OPERATION_ATTR_PUBLIC) is True + if permission is None and not is_public: + continue + if any(_derives_command(claimed, settings, e, t) for e in entities_with_t): + continue + declared = f'@permission "{permission}"' if permission is not None else "@public: true" + claimers = list(dict.fromkeys( + f"{c.op.parent.name if c.op.parent is not None else ''}.{c.op.name}" + for e in entities_with_t + for c in _claims_on(claimed, e, t) + )) + if settings.lifecycle_commands == "none": + why = 'rules.lifecycle.commands is "none": no command is derived from it' + else: + one = len(claimers) == 1 + why = ( + f"it derives no command of its own: it is made only by {_quote_list(claimers)}, which " + f'{"asks" if one else "ask"} the policy about {"its" if one else "their"} own permission' + ) + out.append(Diagnostic( + severity=SEVERITY_WARN, + code=WARN_TRANSITION_PERMISSION_SHADOWED, + path=rules_address(t), + message=( + f'transition "{t.name}" declares {declared}, but {why}, so the attribute is never read. ' + "Remove it from the transition, or declare it on the command that makes the transition." + ), + )) + + +def _check_permission_names(root: MetaData, settings: RulesSettings, out: list[Diagnostic]) -> None: + if settings.permission_names == "derive": + return + severity = SEVERITY_ERROR if settings.permission_names == "require" else SEVERITY_WARN + + def advice(kind: str) -> str: + return f"which changes if the {kind} is renamed. Declare @permission, or @public: true." + + if settings.lifecycle_commands != "none": + claimed = _claimed_transitions(root) + for entity in _command_entities(root): + for t in entity_transitions(entity): + if not _derives_command(claimed, settings, entity, t): + continue + if not _needs_permission_name(t): + continue + field_name = t.parent.name if t.parent is not None else "" + out.append(Diagnostic( + severity=severity, + code=WARN_PERMISSION_DERIVED_NAME, + path=f"{rules_address(entity)}.{field_name}.{t.name}", + message=( + f'the command derived from transition "{t.name}" of "{entity.name}" has no @permission, ' + f'so it asks the policy about the derived name "{_derived_permission_name(entity, f"{entity.name}.{t.name}")}", ' + f'{advice("transition")}' + ), + )) + + for op in _operations(root): + if not _needs_permission_name(op): + continue + out.append(Diagnostic( + severity=severity, + code=WARN_PERMISSION_DERIVED_NAME, + path=rules_address(op), + message=( + f'operation.{op.sub_type} "{op.name}" has no @permission, so it asks the policy about the ' + f'derived name "{_derived_permission_name(op, op.name)}", {advice("operation")}' + ), + )) + + +def check_rules(root: MetaData, settings: RulesSettings) -> RulesCheckResult: + """The rules gate over a loaded model.""" + lifecycles = _declared_lifecycles(root) + ops = _operations(root) + if not lifecycles and not ops: + return RulesCheckResult(diagnostics=[], summary=None) + + diagnostics: list[Diagnostic] = [] + for l in lifecycles: + _check_lifecycle(l, settings, diagnostics) + _check_shadowed_permissions(root, settings, diagnostics) + _check_permission_names(root, settings, diagnostics) + return RulesCheckResult( + diagnostics=diagnostics, + summary=RulesSummary( + operations=len(ops), + lifecycles=len(lifecycles), + transitions=sum(len(l.transitions) for l in lifecycles), + ), + ) diff --git a/server/python/src/metaobjects/rules_settings.py b/server/python/src/metaobjects/rules_settings.py new file mode 100644 index 0000000000..3eb0184bb7 --- /dev/null +++ b/server/python/src/metaobjects/rules_settings.py @@ -0,0 +1,54 @@ +"""ADR-0066 — the project settings the business-rules vocabulary reads, from the ``rules`` and +``verify`` blocks of ``.metaobjects/config.json``. Every port reads the same keys with the same +defaults. A key that is absent takes its default, which is always the behaviour a project had +before the setting existed: no project declared an operation or a transition before 1.3.0, so +every default here is the safe one. Mirrors TS ``metadata/src/rules-settings.ts``; the reader +lives in ``metaobjects.config.neutral_config`` beside ``naming`` and ``wire``. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .meta.meta_data import MetaData + +#: ``rules.permissions.names``: how strongly ``verify`` asks for an explicit ``@permission``. +#: ``derive`` (default) says nothing, ``advise`` warns, ``require`` fails the build. +RULES_PERMISSION_NAMES = ("derive", "advise", "require") + +#: ``rules.lifecycle.create``: whether a create may start a row in any state (``any``) or only +#: in the initial one (``initial``, default). Read by the enforcing shells. +RULES_LIFECYCLE_CREATE = ("initial", "any") + +#: ``rules.lifecycle.commands``: which transitions derive a command of their own. +#: ``unclaimed`` (default): those no declared command lists in ``@transitions``. +RULES_LIFECYCLE_COMMANDS = ("unclaimed", "all", "none") + +#: ``verify.lifecycle.unreachable``: the severity of an unreachable state, and of a transition +#: that starts only from unreachable states. +VERIFY_LIFECYCLE_UNREACHABLE = ("warn", "error", "off") + + +@dataclass(frozen=True) +class RulesSettings: + """The resolved settings, every absent key at its default. Trusted input: validation + happens where the raw JSON is parsed (``metaobjects.config.neutral_config``).""" + + permission_names: str = "derive" + lifecycle_create: str = "initial" + lifecycle_commands: str = "unclaimed" + lifecycle_unreachable: str = "warn" + + +DEFAULT_RULES_SETTINGS = RulesSettings() + + +def rules_settings_of(node: "MetaData") -> RulesSettings: + """The :class:`RulesSettings` in force for *node*: the loaded root's, or the defaults for a + root nobody attached project config to.""" + cur = node + while cur.parent is not None: + cur = cur.parent + settings = getattr(cur, "rules_settings", None) + return settings if isinstance(settings, RulesSettings) else DEFAULT_RULES_SETTINGS diff --git a/server/python/src/metaobjects/shared/base_types.py b/server/python/src/metaobjects/shared/base_types.py index 9e70a339f8..9097b8793a 100644 --- a/server/python/src/metaobjects/shared/base_types.py +++ b/server/python/src/metaobjects/shared/base_types.py @@ -20,6 +20,12 @@ TYPE_DIMENSION = "dimension" TYPE_MEASURE = "measure" TYPE_SEGMENT = "segment" +# ADR-0030 / ADR-0066 — the declared API surface (api > operation > binding) and the +# lifecycle moves of a field.enum (transition). Mirrors TS shared/base-types.ts. +TYPE_API = "api" +TYPE_OPERATION = "operation" +TYPE_BINDING = "binding" +TYPE_TRANSITION = "transition" SUBTYPE_BASE = "base" SUBTYPE_ROOT = "root" diff --git a/server/python/src/metaobjects/spec_metamodel/__init__.py b/server/python/src/metaobjects/spec_metamodel/__init__.py index 079ca88673..cc2cff63bb 100644 --- a/server/python/src/metaobjects/spec_metamodel/__init__.py +++ b/server/python/src/metaobjects/spec_metamodel/__init__.py @@ -1,12 +1,12 @@ """FR-033 — the Python reader for the shared ``spec/metamodel/*.json`` files. -The 15 JSON files (one per concern provider) are the cross-port single source of +The JSON files (one per concern provider) are the cross-port single source of truth for every type / attr / common-attr **description** (+ optional ``rules``/``example``/``whenToUse``). They are byte-identical across the ports by design, so each port READS them rather than hand-copying the prose — the exact duplication FR-033 kills. -This module embeds committed copies of the 15 files **inside the package** (beside +This module embeds committed copies of those files **inside the package** (beside this ``__init__.py``, in ``metaobjects/spec_metamodel/``) and reads them via ``importlib.resources`` — AOT-safe (ships with the wheel, no arbitrary filesystem scan). A byte-identity gate test (``tests/conformance/test_spec_metamodel_embed.py``) @@ -38,9 +38,10 @@ from dataclasses import dataclass, field from importlib import resources -#: The 15 shared provider-definition file names (keep in lockstep with the +#: The shared provider-definition file names (keep in lockstep with the #: repo-root ``spec/metamodel/`` directory — the byte-identity gate enforces it). SPEC_FILES: tuple[str, ...] = ( + "api.json", "attr.json", "db.json", "documentation.json", @@ -56,6 +57,7 @@ "requirement.json", "source.json", "template.json", + "transition.json", "ui.json", "ui-web.json", "validator.json", @@ -177,7 +179,7 @@ class SpecMetamodelReader: @classmethod def load(cls) -> "SpecMetamodelReader": - """Load + parse the 15 embedded ``spec/metamodel/*.json`` files via + """Load + parse the embedded ``spec/metamodel/*.json`` files via ``importlib.resources`` (off the package, AOT-safe).""" reader = cls() pkg = resources.files(__package__) diff --git a/server/python/src/metaobjects/spec_metamodel/api.json b/server/python/src/metaobjects/spec_metamodel/api.json new file mode 100644 index 0000000000..0f30e16e08 --- /dev/null +++ b/server/python/src/metaobjects/spec_metamodel/api.json @@ -0,0 +1,73 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "api", + "subType": "base", + "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.", + "children": [] + }, + { + "type": "api", + "subType": "operational", + "extendsBase": true, + "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).", + "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": "base", + "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "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": "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", "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." } + ] + }, + { + "type": "operation", + "subType": "query", + "extendsBase": true, + "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": "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": "binding", + "subType": "base", + "description": "Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable.", + "children": [] + }, + { + "type": "binding", + "subType": "rest", + "extendsBase": true, + "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).", + "whenToUse": "An operation must keep a method or path the derived one would not give it, such as an existing public URL.", + "children": [ + { "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)." } + ] + } + ] +} diff --git a/server/python/src/metaobjects/spec_metamodel/field.json b/server/python/src/metaobjects/spec_metamodel/field.json index 46a2f064ce..8d4c5a2185 100644 --- a/server/python/src/metaobjects/spec_metamodel/field.json +++ b/server/python/src/metaobjects/spec_metamodel/field.json @@ -149,6 +149,7 @@ "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ + { "type": "transition", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Lifecycle moves between this enum's members (ADR-0066). An enum with at least one transition.action is a lifecycle: its states are @values, its initial state @default, its terminal states the members no transition leaves." }, { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer. Justified in ADR-0023 Amendment 1." }, diff --git a/server/python/src/metaobjects/spec_metamodel/transition.json b/server/python/src/metaobjects/spec_metamodel/transition.json new file mode 100644 index 0000000000..cbac9d3ef7 --- /dev/null +++ b/server/python/src/metaobjects/spec_metamodel/transition.json @@ -0,0 +1,27 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "transition", + "subType": "base", + "description": "Registry anchor for the attributes every lifecycle move shares (ADR-0054): not authorable.", + "children": [ + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name `..`, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED)." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." } + ] + }, + { + "type": "transition", + "subType": "action", + "extendsBase": true, + "description": "An allowed move between two values of a `field.enum`, made by an operation (ADR-0066). A `field.enum` with at least one is a lifecycle, named after the field. Its states are the enum's @values, its initial state the enum's @default, its terminal states the members no transition leaves; none of them has vocabulary of its own. Each transition is held to become a guarded update (`... WHERE id = ? AND IN (@from) [AND @condition]`), its own command when no declared operation claims it, its own permission point and its own wire error. No shell is generated yet: nothing is generated from this vocabulary, and the loader and `verify` only check it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A status field whose values may only change in certain ways: a request is submitted from draft, approved or rejected from submitted. Declare each allowed move here; once a shell is generated, the generic update path will no longer write the field. A move that leaves the state where it was (from submitted to submitted) records an action that changes nothing but still happened, such as a first approval of two.", + "rules": "Legal only under a `field.enum` of an `object.entity` (ERR_TRANSITION_NOT_ON_ENTITY). A concrete entity with a lifecycle and a source needs a writable one (ERR_TRANSITION_NOT_ON_ENTITY); on an entity with no source the lifecycle loads and is inert, deriving no command until a source is added. The field must declare @default (ERR_LIFECYCLE_NO_INITIAL). The field is not an array, and @from names at least one state (ERR_BAD_ATTR_VALUE). Names are unique across every lifecycle of the entity, compared without case, and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). A transition belongs to the entity that declares its field and to every entity extending it, never to an entity whose field merely `extends` that field; an inheritor that redeclares the field without extending it is ERR_LIFECYCLE_REDECLARED.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "isArray": true, "min": 1, "max": 1, "description": "The states this move may start from: members of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise), at least one (ERR_BAD_ATTR_VALUE when empty). The allowed moves are the business rule itself, so they cannot be computed." }, + { "type": "attr", "subType": "string", "name": "to", "min": 1, "max": 1, "description": "The state this move ends in: one member of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise). May equal a member of @from, which records an action that leaves the state where it was." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "A guard over the entity's own fields, in the attr.expression grammar: the same name, grammar and meaning as on the cross-field validators. The shell will evaluate it against the loaded row and also put it into the guarded update's WHERE (no shell is generated yet). It cannot read the actor; that is the policy's job. A field the entity does not have, or an expression that is not boolean, is ERR_BAD_ATTR_VALUE." } + ] + } + ] +} diff --git a/server/python/src/metaobjects/wire.py b/server/python/src/metaobjects/wire.py index e96b608e6f..547e1a0d8c 100644 --- a/server/python/src/metaobjects/wire.py +++ b/server/python/src/metaobjects/wire.py @@ -13,6 +13,8 @@ from pathlib import Path from typing import TYPE_CHECKING +from metaobjects.rules_settings import RulesSettings + if TYPE_CHECKING: from metaobjects.meta.meta_data import MetaData @@ -72,5 +74,7 @@ def attach_wire(root: "MetaData", project_dir: Path) -> "MetaData": cfg = read_neutral_config(project_dir) root.wire = cfg.wire if cfg is not None else WireFormat() # type: ignore[attr-defined] + # ADR-0066 — the business-rules settings travel with the wire setting: same file, same load sites. + root.rules_settings = cfg.rules if cfg is not None else RulesSettings() # type: ignore[attr-defined] root.api = cfg.api if cfg is not None else ApiSettings() # type: ignore[attr-defined] return root diff --git a/server/python/tests/codegen/test_cli_verify_rules.py b/server/python/tests/codegen/test_cli_verify_rules.py new file mode 100644 index 0000000000..1b9eb5aa81 --- /dev/null +++ b/server/python/tests/codegen/test_cli_verify_rules.py @@ -0,0 +1,85 @@ +"""``metaobjects verify`` — the business-rules gate (ADR-0066), end to end. + +Codes, paths and message text are gated cross-port by +``tests/conformance/test_rules_check_conformance.py``; these tests pin the wiring: what is +printed, what reaches the exit code, and that a model with no operation and no transition +sees no change at all. +""" + +from __future__ import annotations + +import json +import shutil +from pathlib import Path + +import pytest + +from metaobjects import cli +from metaobjects.cli import main +from tests.codegen.config_helpers import as_config +from tests.codegen.gen_suite import GEN_SUITE + +NOOP = Path(__file__).parents[4] / "fixtures" / "codegen-noop" / "rules" + + +def _project(tmp_path: Path, variant: str, config: dict | None = None) -> str: + meta = tmp_path / "meta" + meta.mkdir() + shutil.copy(NOOP / variant / "meta.purchasing.json", meta / "meta.purchasing.json") + if config is not None: + (tmp_path / ".metaobjects").mkdir() + (tmp_path / ".metaobjects" / "config.json").write_text(json.dumps({"schema_version": 1, **config})) + return str(meta) + + +def _gen(tmp_path: Path, meta_dir: str) -> None: + out = tmp_path / "out" + assert main(as_config(["gen", "--generators", GEN_SUITE, meta_dir, "--out", str(out)])) == 0 + + +def _verify(tmp_path: Path, meta_dir: str) -> int: + out = tmp_path / "out" + return main(as_config(["verify", "--codegen", "--generators", GEN_SUITE, meta_dir, "--out", str(out)])) + + +def test_a_model_with_no_rules_prints_nothing_and_exits_as_before( + tmp_path: Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + meta_dir = _project(tmp_path, "without") + # Generate once and drop what `gen` printed: only the two `verify` runs are compared. + _gen(tmp_path, meta_dir) + capsys.readouterr() + after_code = _verify(tmp_path, meta_dir) + after = capsys.readouterr() + + monkeypatch.setattr(cli, "_verify_rules", lambda args, loaded=None: 0) + before_code = _verify(tmp_path, meta_dir) + before = capsys.readouterr() + + assert (after_code, after.err, after.out) == (before_code, before.err, before.out) + assert after_code == 0 + assert "rules:" not in after.err + + +def test_a_model_with_rules_prints_the_summary( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + meta_dir = _project(tmp_path, "with") + _gen(tmp_path, meta_dir) + capsys.readouterr() + code = _verify(tmp_path, meta_dir) + err = capsys.readouterr().err + assert "metaobjects verify — rules: 3 operation(s), 1 lifecycle(s) with 3 transition(s)." in err + assert code == 0 + + +def test_an_error_severity_finding_exits_1( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + meta_dir = _project(tmp_path, "with", {"rules": {"permissions": {"names": "require"}}}) + _gen(tmp_path, meta_dir) + capsys.readouterr() + code = _verify(tmp_path, meta_dir) + err = capsys.readouterr().err + assert "rules:" in err + assert code == 1 diff --git a/server/python/tests/config/test_neutral_config.py b/server/python/tests/config/test_neutral_config.py index e1cbd4f24d..c550a5aae3 100644 --- a/server/python/tests/config/test_neutral_config.py +++ b/server/python/tests/config/test_neutral_config.py @@ -218,3 +218,43 @@ def test_a_malformed_enums_block_is_refused(tmp_path: Path, enums: object) -> No with pytest.raises(ParseError) as e: read_neutral_config(tmp_path) assert e.value.code == ErrorCode.ERR_BAD_ATTR_VALUE + + +# ADR-0066 — the `rules` and `verify` blocks. Absent keys take their defaults; a mistake is refused. + + +def test_rules_settings_absent_are_defaults(tmp_path: Path) -> None: + _write_config(tmp_path, {"schema_version": 1}) + cfg = read_neutral_config(tmp_path) + assert cfg is not None + assert (cfg.rules.permission_names, cfg.rules.lifecycle_create, cfg.rules.lifecycle_commands, + cfg.rules.lifecycle_unreachable) == ("derive", "initial", "unclaimed", "warn") + + +def test_rules_settings_are_read(tmp_path: Path) -> None: + _write_config(tmp_path, { + "schema_version": 1, + "rules": {"permissions": {"names": "require"}, "lifecycle": {"create": "any", "commands": "none"}}, + "verify": {"handEdits": "fail", "lifecycle": {"unreachable": "error"}}, + }) + cfg = read_neutral_config(tmp_path) + assert cfg is not None + assert (cfg.rules.permission_names, cfg.rules.lifecycle_create, cfg.rules.lifecycle_commands, + cfg.rules.lifecycle_unreachable) == ("require", "any", "none", "error") + + +@pytest.mark.parametrize("extra", [ + {"rules": {"permission": {"names": "advise"}}}, + {"rules": {"lifecycle": {"initial": "any"}}}, + {"rules": {"permissions": {"names": "strict"}}}, + {"rules": {"lifecycle": {"commands": True}}}, + {"rules": "advise"}, + {"verify": {"lifecycle": {"unreachable": "fail"}}}, + {"verify": {"lifecycles": {}}}, + {"verify": {"handEdits": "warn"}}, +]) +def test_rules_settings_mistakes_are_refused(tmp_path: Path, extra: dict) -> None: + _write_config(tmp_path, {"schema_version": 1, **extra}) + with pytest.raises(ParseError) as exc: + read_neutral_config(tmp_path) + assert exc.value.code == ErrorCode.ERR_BAD_ATTR_VALUE diff --git a/server/python/tests/conformance/test_rules_check_conformance.py b/server/python/tests/conformance/test_rules_check_conformance.py new file mode 100644 index 0000000000..dc99aeef68 --- /dev/null +++ b/server/python/tests/conformance/test_rules_check_conformance.py @@ -0,0 +1,127 @@ +"""Cross-port business-rules conformance corpus — fixtures/rules-check-conformance/ (ADR-0066). + +The rules gate is part of ``verify`` in every port; this corpus holds the other ports to the +TypeScript reference: the same inputs, the same diagnostics down to the message text, the same +summary. Every case is LOADED strict first, so "this model loads today" is proven by the +fixture, and only then checked. A mismatch here is a bug in THIS port's gate, never in the +fixture, and a committed ``expected.json`` is never edited to make this port pass. +""" +from __future__ import annotations + +import json +import re +import warnings +from pathlib import Path +from typing import Any + +import pytest + +from metaobjects import MetaDataLoader +from metaobjects.config.neutral_config import read_neutral_config +from metaobjects.requirement_check import Diagnostic +from metaobjects.rules_check import RulesSummary, check_rules +from metaobjects.rules_settings import RulesSettings + + +def _corpus_root() -> Path: + here = Path(__file__).resolve() + for parent in [here, *here.parents]: + candidate = parent / "fixtures" / "rules-check-conformance" + if candidate.is_dir(): + return candidate + raise RuntimeError("could not locate fixtures/rules-check-conformance from " + str(here)) + + +CORPUS = _corpus_root() +FIXTURES = sorted(p.name for p in CORPUS.iterdir() if p.is_dir()) + + +def _read_settings(case_dir: Path, scratch: Path) -> RulesSettings: + """``options.json`` holds the ``rules`` and ``verify`` config blocks as a project writes + them. They go through this port's own config reader (a scratch ``.metaobjects/config.json``), + so a key that reader does not know, or a value outside its set, fails the case.""" + file = case_dir / "options.json" + options: dict[str, Any] = json.loads(file.read_text(encoding="utf-8")) if file.exists() else {} + unknown = sorted(set(options) - {"rules", "verify"}) + assert not unknown, f"{file}: unknown block(s) {unknown}" + config_dir = scratch / ".metaobjects" + config_dir.mkdir() + (config_dir / "config.json").write_text(json.dumps({"schema_version": 1, **options}), encoding="utf-8") + cfg = read_neutral_config(scratch) + assert cfg is not None + return cfg.rules + + +def _summary_dict(summary: RulesSummary | None) -> dict[str, int] | None: + if summary is None: + return None + return {"operations": summary.operations, "lifecycles": summary.lifecycles, "transitions": summary.transitions} + + +def _row(d: Diagnostic) -> tuple[str, str, str, str]: + return (d.severity, d.code, d.path or "", d.message) + + +def _documented_cases() -> list[str]: + readme = (CORPUS / "README.md").read_text(encoding="utf-8") + section = next((s for s in re.split(r"^## ", readme, flags=re.M) if s.startswith("Cases\n")), None) + assert section is not None, "README.md has no '## Cases' section" + return re.findall(r"^\| `([^`]+)` \|", section, flags=re.M) + + +def test_found_fixtures() -> None: + assert FIXTURES, "fixtures/rules-check-conformance/ discovered no fixture directories" + + +def test_every_case_on_disk_is_documented_in_the_readme_and_nothing_else_is() -> None: + assert sorted(_documented_cases()) == FIXTURES + + +@pytest.mark.parametrize("name", FIXTURES) +def test_fixture(name: str, tmp_path: Path) -> None: + case_dir = CORPUS / name + expected = json.loads((case_dir / "expected.json").read_text(encoding="utf-8")) + settings = _read_settings(case_dir, tmp_path) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) # no project config next to the fixture input + result = MetaDataLoader.from_directory(str(case_dir / "input"), strict=True) + assert [str(e) for e in result.errors] == [] + + check = check_rules(result.root, settings) + actual = sorted(_row(d) for d in check.diagnostics) + wanted = sorted( + (d["severity"], d["code"], d.get("path", ""), d["message"]) for d in expected["diagnostics"] + ) + assert actual == wanted + assert _summary_dict(check.summary) == expected["summary"] + + +def test_an_unknown_rules_key_is_refused(tmp_path: Path) -> None: + config_dir = tmp_path / ".metaobjects" + config_dir.mkdir() + (config_dir / "config.json").write_text( + json.dumps({"schema_version": 1, "rules": {"permissions": {"name": "advise"}}}), encoding="utf-8" + ) + with pytest.raises(Exception, match="unknown key"): + read_neutral_config(tmp_path) + + +def test_an_unknown_rules_value_is_refused(tmp_path: Path) -> None: + config_dir = tmp_path / ".metaobjects" + config_dir.mkdir() + (config_dir / "config.json").write_text( + json.dumps({"schema_version": 1, "verify": {"lifecycle": {"unreachable": "maybe"}}}), encoding="utf-8" + ) + with pytest.raises(Exception, match="must be one of"): + read_neutral_config(tmp_path) + + +def test_absent_rules_blocks_read_as_the_defaults(tmp_path: Path) -> None: + config_dir = tmp_path / ".metaobjects" + config_dir.mkdir() + (config_dir / "config.json").write_text(json.dumps({"schema_version": 1}), encoding="utf-8") + cfg = read_neutral_config(tmp_path) + assert cfg is not None and cfg.rules == RulesSettings() + assert (cfg.rules.permission_names, cfg.rules.lifecycle_create, cfg.rules.lifecycle_commands, + cfg.rules.lifecycle_unreachable) == ("derive", "initial", "unclaimed", "warn") diff --git a/server/python/tests/test_rules_inert.py b/server/python/tests/test_rules_inert.py new file mode 100644 index 0000000000..bf01538658 --- /dev/null +++ b/server/python/tests/test_rules_inert.py @@ -0,0 +1,139 @@ +"""ADR-0066 — the business-rules vocabulary is INERT in every Python generator. + +1.3.0 registers ``api.operational``, ``operation.*``, ``binding.rest`` and ``transition.action``, +validates them at load and checks them in ``verify``. The generated services and enforcing +shells that act on them are later work, so until they land a model that USES the vocabulary +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 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. + +Runs through ``run_gen`` — the path ``metaobjects gen`` takes. +""" +from __future__ import annotations + +from pathlib import Path + +import pytest + +from metaobjects import load_uris +from metaobjects.codegen.config import GenConfig +from metaobjects.codegen.generator import Generator +from metaobjects.codegen.generator_registry import ( + GeneratorBuildContext, + GeneratorEntry, + list_generators, +) +from metaobjects.codegen.runner import run_gen +from metaobjects.codegen.runtime.api_docs_builder import PythonApiModelBuilder +from metaobjects.codegen.runtime.api_docs_paths import Layout, doc_page_output_path +from metaobjects.codegen.runtime.api_docs_renderer import render_agent_api, render_index, render_unit_page +from metaobjects.meta.core.transition.lifecycle import entity_transitions +from metaobjects.shared.base_types import TYPE_API, TYPE_OBJECT + +MODELS = Path(__file__).parents[3] / "fixtures" / "codegen-noop" / "rules" +THREW = "" + + +def _load(variant: str): + result = load_uris([(MODELS / variant / "meta.purchasing.json").as_uri()]) + assert not result.errors, "\n".join(e.message for e in result.errors) + return result.root + + +def _build(entry: GeneratorEntry, template_root: Path) -> Generator: + return entry.factory(GeneratorBuildContext(template_root=str(template_root))) + + +def _emit(variant: str, entries: list[GeneratorEntry], tmp: Path) -> dict[str, str]: + """Run a generator suite into a fresh directory and read back every file it wrote. + + A throw is recorded as the single entry ````, so a generator that cannot run from + a bare model must at least fail identically. + """ + out = tmp / f"out-{variant}" + templates = tmp / "templates" + templates.mkdir(parents=True, exist_ok=True) + try: + run_gen( + GenConfig(out_dir=str(out)), + _load(variant), + generators=[_build(e, templates) for e in entries], + ) + except Exception as exc: # noqa: BLE001 — a throw is compared, not swallowed + return {THREW: str(exc)} + if not out.exists(): + return {} + return { + str(p.relative_to(out)): p.read_text(encoding="utf-8") + for p in sorted(out.rglob("*")) + if p.is_file() + } + + +def test_the_with_model_really_carries_the_vocabulary() -> None: + # Else every comparison below is vacuously green. + with_root = _load("with") + # ADR-0039: resolving — the root is never extended, so children() == own_children(). + apis = [c for c in with_root.children() if c.type == TYPE_API] + assert [a.name for a in apis] == ["Purchasing"] + assert len(apis[0].children()) == 3 + request = next(c for c in with_root.children() if c.type == TYPE_OBJECT and c.name == "PurchaseRequest") + assert len(entity_transitions(request)) == 3 + without_root = _load("without") + assert not any(c.type == TYPE_API for c in without_root.children()) + request = next(c for c in without_root.children() if c.type == TYPE_OBJECT and c.name == "PurchaseRequest") + assert entity_transitions(request) == [] + + +@pytest.mark.parametrize("entry", list_generators(), ids=lambda e: e.name) +def test_generator_emits_the_same_files_with_and_without_rules_nodes( + entry: GeneratorEntry, tmp_path: Path +) -> None: + # `list_generators()` includes the documentation generator (`api-docs`): its pages are + # held to the same byte-for-byte rule here. + expected = _emit("without", [entry], tmp_path / "a") + actual = _emit("with", [entry], tmp_path / "b") + assert actual == expected + + +def test_every_runnable_generator_in_one_run_emits_the_same_files(tmp_path: Path) -> None: + runnable = [ + e for i, e in enumerate(list_generators()) + if THREW not in _emit("without", [e], tmp_path / f"probe-{i}") + ] + expected = _emit("without", runnable, tmp_path / "a") + actual = _emit("with", runnable, tmp_path / "b") + assert THREW not in expected, expected.get(THREW) + assert len(expected) > 10, f"only {len(expected)} files — the suite barely ran" + assert actual == expected + + +def _api_docs(variant: str) -> dict[str, str]: + """The api docs surface: every unit page, the index and the agent page.""" + model = PythonApiModelBuilder().build(_load(variant), "purchasing") + pages = { + doc_page_output_path(Layout.PACKAGE, unit.package, unit.node): render_unit_page(unit, None) + for unit in model.units + } + pages["README.md"] = render_index(model, Layout.PACKAGE) + pages["AGENT-API.md"] = render_agent_api(model) + return dict(sorted(pages.items())) + + +def test_api_docs_are_byte_identical_with_and_without_rules_nodes() -> None: + expected = _api_docs("without") + assert len(expected) > 3, f"only {len(expected)} pages — the docs barely ran" + assert _api_docs("with") == expected + + +def test_exactly_these_generators_cannot_run_from_a_bare_model(tmp_path: Path) -> None: + # Pinned so a generator that starts throwing cannot drop out of the comparison silently; + # the list may only shrink. + threw = sorted( + e.name for i, e in enumerate(list_generators()) + if THREW in _emit("without", [e], tmp_path / f"probe-{i}") + ) + assert threw == [] diff --git a/server/rust/metaobjects-codegen/tests/rules_inert.rs b/server/rust/metaobjects-codegen/tests/rules_inert.rs new file mode 100644 index 0000000000..0ff6315364 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/rules_inert.rs @@ -0,0 +1,61 @@ +//! ADR-0066: the business-rules vocabulary is inert in the Rust generators. +//! +//! `api.operational`, `operation.*`, `binding.rest` and `transition.action` are registered +//! and validated at load; nothing generates from them yet. A model that uses them emits +//! exactly what the same model without them emits, byte for byte. +//! +//! The model pair is `fixtures/codegen-noop/rules/{with,without}`, shared with the other +//! ports (the table in that directory's README lists each port's test). + +mod common; + +use std::collections::BTreeMap; +use std::path::Path; + +use common::Scratch; +use metaobjects_codegen::generator::GenContext; +use metaobjects_codegen::project::load_project; +use metaobjects_codegen::{EntityGenerator, Generator}; + +const MODEL_FILE: &str = "meta.purchasing.json"; + +/// Every file the entity generator writes for one variant: path to contents. +fn emit(variant: &str) -> BTreeMap { + let fixture = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../../fixtures/codegen-noop/rules") + .join(variant) + .join(MODEL_FILE); + let model = + std::fs::read_to_string(&fixture).unwrap_or_else(|e| panic!("{}: {e}", fixture.display())); + // One project name for both variants, so nothing that stamps it into output can differ. + let project = Scratch::project( + "rules-inert", + &[(&format!("metaobjects/{MODEL_FILE}"), &model)], + ); + let loaded = load_project(project.path(), None, false).expect("the model loads clean"); + let ctx = GenContext { + tree: &loaded.result.tree, + root: loaded.result.root, + entities: &[], + }; + EntityGenerator + .generate(&ctx) + .expect("the entity generator runs") + .into_iter() + .map(|f| (f.path, f.content)) + .collect() +} + +#[test] +fn a_model_with_operations_and_transitions_generates_what_it_does_without_them() { + let with = emit("with"); + let without = emit("without"); + assert!(!without.is_empty(), "the model generates something"); + assert_eq!( + with.keys().collect::>(), + without.keys().collect::>() + ); + for (path, text) in &without { + assert_eq!(&with[path], text, "{path}"); + } +} diff --git a/server/rust/metaobjects/src/config.rs b/server/rust/metaobjects/src/config.rs index ac3e9cadcb..82d01149dd 100644 --- a/server/rust/metaobjects/src/config.rs +++ b/server/rust/metaobjects/src/config.rs @@ -41,6 +41,7 @@ pub const CONFIG_TOP_LEVEL_KEYS: &[&str] = &[ "wire", "api", "enums", + "rules", "csharp", ]; @@ -103,6 +104,45 @@ string_enum!( /// `verify.handEdits`. HandEditsPolicy { Fail => "fail", Notice => "notice" } ); +string_enum!( + /// `rules.permissions.names`: how strongly `verify` asks for an explicit `@permission`. + RulesPermissionNames { Derive => "derive", Advise => "advise", Require => "require" } +); +string_enum!( + /// `rules.lifecycle.create`: whether a create may start a row in any state. + RulesLifecycleCreate { Initial => "initial", Any => "any" } +); +string_enum!( + /// `rules.lifecycle.commands`: which transitions derive a command of their own. + RulesLifecycleCommands { Unclaimed => "unclaimed", All => "all", NoneDerived => "none" } +); +string_enum!( + /// `verify.lifecycle.unreachable`: the severity of an unreachable lifecycle state. + VerifyLifecycleUnreachable { Warn => "warn", Error => "error", Off => "off" } +); + +/// The business-rules settings (ADR-0066), from the `rules` and `verify` blocks, each +/// absent key at its default. Every port reads the same keys with the same defaults. +/// This port validates and keeps them; nothing here reads them yet, because the checks +/// they tune live in `verify`, which the Rust port does not have. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RulesSettings { + pub permission_names: RulesPermissionNames, + pub lifecycle_create: RulesLifecycleCreate, + pub lifecycle_commands: RulesLifecycleCommands, + pub lifecycle_unreachable: VerifyLifecycleUnreachable, +} + +impl Default for RulesSettings { + fn default() -> Self { + Self { + permission_names: RulesPermissionNames::Derive, + lifecycle_create: RulesLifecycleCreate::Initial, + lifecycle_commands: RulesLifecycleCommands::Unclaimed, + lifecycle_unreachable: VerifyLifecycleUnreachable::Warn, + } + } +} /// The output form of a generated REST surface, each absent key at its default. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -278,6 +318,8 @@ pub struct Config { pub wire: Option, pub api: Option, pub enums: Option, + /// `rules.*` and `verify.lifecycle.*`, each absent key at its default. + pub rules: RulesSettings, pub csharp: Option, } @@ -300,6 +342,7 @@ impl Default for Config { wire: None, api: None, enums: None, + rules: RulesSettings::default(), csharp: None, } } @@ -907,6 +950,64 @@ fn parse_enums(v: &Value, issues: &mut Issues) -> Option { Some(out) } +/// The value of `key` in `o` when it is one of `options`; an issue at `.` otherwise. +fn enum_key( + o: &Map, + at: &str, + key: &str, + options: &[&str], + issues: &mut Issues, +) -> Option { + enum_of(o.get(key)?, &format!("{at}.{key}"), options, None, issues) +} + +/// The `rules` block (ADR-0066): closed at every level, as `naming` and `wire` are, so a +/// misspelling cannot fall back to a default and change what `verify` reports. +fn parse_rules(v: &Value, rules: &mut RulesSettings, issues: &mut Issues) { + let Some(o) = strict_object(v, "rules", &["permissions", "lifecycle"], issues) else { + return; + }; + if let Some(p) = o.get("permissions") + && let Some(po) = strict_object(p, "rules.permissions", &["names"], issues) + && let Some(n) = enum_key( + po, + "rules.permissions", + "names", + RulesPermissionNames::ALL, + issues, + ) + .and_then(|s| RulesPermissionNames::parse(&s)) + { + rules.permission_names = n; + } + if let Some(l) = o.get("lifecycle") + && let Some(lo) = strict_object(l, "rules.lifecycle", &["create", "commands"], issues) + { + if let Some(c) = enum_key( + lo, + "rules.lifecycle", + "create", + RulesLifecycleCreate::ALL, + issues, + ) + .and_then(|s| RulesLifecycleCreate::parse(&s)) + { + rules.lifecycle_create = c; + } + if let Some(c) = enum_key( + lo, + "rules.lifecycle", + "commands", + RulesLifecycleCommands::ALL, + issues, + ) + .and_then(|s| RulesLifecycleCommands::parse(&s)) + { + rules.lifecycle_commands = c; + } + } +} + fn parse_csharp(v: &Value, issues: &mut Issues) -> Option { let o = strict_object(v, "csharp", &["outDir", "namespace", "providers"], issues)?; let mut out = CsharpConfig { @@ -1075,14 +1176,31 @@ pub fn parse_config( match v.as_object() { None => issues.add("verify", "\"verify\" must be an object"), Some(vo) => { - if let Some(k) = vo.keys().find(|k| k.as_str() != "handEdits") { + if let Some(k) = vo + .keys() + .find(|k| !["handEdits", "lifecycle"].contains(&k.as_str())) + { issues.add( "verify", format!( - "\"verify\" has an unknown key \"{k}\" (expected \"handEdits\")" + "\"verify\" has an unknown key \"{k}\" (expected \"handEdits\" or \"lifecycle\")" ), ); } + if let Some(l) = vo.get("lifecycle") + && let Some(lo) = + strict_object(l, "verify.lifecycle", &["unreachable"], &mut issues) + && let Some(u) = enum_key( + lo, + "verify.lifecycle", + "unreachable", + VerifyLifecycleUnreachable::ALL, + &mut issues, + ) + .and_then(|s| VerifyLifecycleUnreachable::parse(&s)) + { + cfg.rules.lifecycle_unreachable = u; + } if let Some(h) = vo.get("handEdits") { let list: Vec = HandEditsPolicy::ALL .iter() @@ -1121,6 +1239,9 @@ pub fn parse_config( if let Some(v) = o.get("enums") { cfg.enums = parse_enums(v, &mut issues); } + if let Some(v) = o.get("rules") { + parse_rules(v, &mut cfg.rules, &mut issues); + } if let Some(v) = o.get("csharp") { cfg.csharp = parse_csharp(v, &mut issues); } diff --git a/server/rust/metaobjects/src/loader.rs b/server/rust/metaobjects/src/loader.rs index dac642895f..72b5b49f45 100644 --- a/server/rust/metaobjects/src/loader.rs +++ b/server/rust/metaobjects/src/loader.rs @@ -45,7 +45,10 @@ const PENDING_DIR: &str = "_pending"; const TYPE_IDENTITY: &str = "identity"; const IDENTITY_UNIQUE_KEY_SUBTYPES: &[&str] = &["primary", "secondary"]; -/// Attributes whose value names another top-level object (ADR-0059 R4). +/// Attributes whose value names another top-level object (ADR-0059 R4). An operation's +/// `@inputRef`, `@outputRef` and `@objectRef` are among them (ADR-0066). The set is keyed +/// by name, so [`is_ref_bearing_attr`] excludes a node type that reuses one of these +/// names for something else. pub const REF_BEARING_ATTR_NAMES: &[&str] = &[ "objectRef", "through", @@ -57,8 +60,19 @@ pub const REF_BEARING_ATTR_NAMES: &[&str] = &[ "payloadRef", "responseRef", "spine", + "inputRef", + "outputRef", ]; +const TYPE_TRANSITION: &str = "transition"; + +/// `true` when `attr` on a node of type `type_name` holds an object reference: it is in +/// [`REF_BEARING_ATTR_NAMES`], and the node is not a `transition.*`, whose `@from` lists +/// members of its enum (ADR-0066). +pub fn is_ref_bearing_attr(type_name: &str, attr: &str) -> bool { + REF_BEARING_ATTR_NAMES.contains(&attr) && type_name != TYPE_TRANSITION +} + /// One load: the tree, its root, and every error and warning. #[derive(Debug)] pub struct LoadResult { @@ -947,10 +961,11 @@ fn resolve_references(tree: &mut Tree, root: NodeId, top: &TopLevel) { if id != root { resolve_extends(tree, top, id); let decl_pkg = tree.effective_package(tree.top_level_of(id)); + let type_name = tree.node(id).type_name.as_str(); let names: Vec = tree // ADR-0039: own — reference resolution rewrites the value this node declares, not an inherited one. .own_attrs(id) - .filter(|(k, _)| REF_BEARING_ATTR_NAMES.contains(&k.as_str())) + .filter(|(k, _)| is_ref_bearing_attr(type_name, k)) .map(|(k, _)| k.clone()) .collect(); for name in names { diff --git a/server/rust/metaobjects/src/providers.rs b/server/rust/metaobjects/src/providers.rs index ad8ae16016..355cb420b0 100644 --- a/server/rust/metaobjects/src/providers.rs +++ b/server/rust/metaobjects/src/providers.rs @@ -87,6 +87,8 @@ const CORE_FAMILIES: &[(&str, &str)] = &[ spec!("index"), spec!("requirement"), spec!("reporting"), + spec!("api"), + spec!("transition"), ]; const DB_SPEC: (&str, &str) = spec!("db"); @@ -480,10 +482,17 @@ fn apply_definition( fn register_core(registry: &mut TypeRegistry) -> Result<(), MetaError> { let mut root = TypeDefinition::new("metadata", "root", "Root metadata document"); - root.child_rules = ["object", "field", "validator", "template", "requirement"] - .iter() - .map(|t| ChildRule::wildcard(t)) - .collect(); + root.child_rules = [ + "object", + "field", + "validator", + "template", + "requirement", + "api", + ] + .iter() + .map(|t| ChildRule::wildcard(t)) + .collect(); registry.register(root)?; for family in &definitions().core { for def in define_from_data(family)? { diff --git a/server/rust/metaobjects/src/validate/field_expr.rs b/server/rust/metaobjects/src/validate/field_expr.rs index 50aba05a95..09d23dd7bc 100644 --- a/server/rust/metaobjects/src/validate/field_expr.rs +++ b/server/rust/metaobjects/src/validate/field_expr.rs @@ -916,6 +916,56 @@ fn condition_problem<'a>( literal_comparison_problem(condition, &field_of) } +/// An object's effective fields by name. +pub(crate) fn fields_by_name<'a>(ctx: &Ctx<'a>, obj: NodeId) -> HashMap<&'a str, NodeId> { + let tree = ctx.tree; + field_children(ctx, obj) + .into_iter() + .map(|x| (tree.node(x).name.as_str(), x)) + .collect() +} + +/// Why a `@condition` over an object's fields is refused, or `None` when it is legal. +/// `label` opens the message. One rule for a cross-field validator's condition and a +/// transition's guard (ADR-0066): every field it names is a field of the object, and the +/// expression passes [`condition_problem`]. +pub(crate) fn condition_message( + ctx: &Ctx<'_>, + condition: &Value, + object_name: &str, + fields: &HashMap<&str, NodeId>, + label: &str, +) -> Option { + let mut refs: Vec<&String> = Vec::new(); + let mut nodes = Vec::new(); + expression_nodes(condition, &mut nodes); + for n in nodes { + if let Some(Value::String(s)) = n.get("field") + && !refs.contains(&s) + { + refs.push(s); + } + } + let mut unknown: Vec<&String> = refs + .into_iter() + .filter(|r| !fields.contains_key(r.as_str())) + .collect(); + unknown.sort(); + if !unknown.is_empty() { + let names: Vec = unknown.iter().map(|u| format!("\"{u}\"")).collect(); + return Some(format!( + "{label} names {}, which {} of \"{object_name}\".", + names.join(", "), + if unknown.len() == 1 { + "is not a field" + } else { + "are not fields" + } + )); + } + condition_problem(ctx, condition, fields).map(|problem| format!("{label} {problem}")) +} + pub fn validate_cross_field_validators(ctx: &Ctx<'_>, f: &mut Findings) { let tree = ctx.tree; for &obj in tree @@ -923,11 +973,7 @@ pub fn validate_cross_field_validators(ctx: &Ctx<'_>, f: &mut Findings) { .iter() .filter(|&&c| tree.node(c).type_name == TYPE_OBJECT) { - let field_nodes = field_children(ctx, obj); - let fields: HashMap<&str, NodeId> = field_nodes - .iter() - .map(|&x| (tree.node(x).name.as_str(), x)) - .collect(); + let fields = fields_by_name(ctx, obj); let oname = &tree.node(obj).name; // ADR-0039: own — each validator is checked where it is declared. for &v in tree.own_children(obj) { @@ -1004,40 +1050,8 @@ pub fn validate_cross_field_validators(ctx: &Ctx<'_>, f: &mut Findings) { "validator.{} \"{oname}.{}\" @condition", vn.sub_type, vn.name ); - let mut refs: Vec = Vec::new(); - let mut nodes = Vec::new(); - expression_nodes(condition, &mut nodes); - for n in nodes { - if let Some(Value::String(s)) = n.get("field") - && !refs.contains(s) - { - refs.push(s.clone()); - } - } - let mut unknown: Vec<&String> = refs - .iter() - .filter(|r| !fields.contains_key(r.as_str())) - .collect(); - unknown.sort(); - if !unknown.is_empty() { - let names: Vec = unknown.iter().map(|u| format!("\"{u}\"")).collect(); - push( - f, - ERR_BAD_ATTR_VALUE, - format!( - "{label} names {}, which {} of \"{oname}\".", - names.join(", "), - if unknown.len() == 1 { - "is not a field" - } else { - "are not fields" - } - ), - ); - continue; - } - if let Some(problem) = condition_problem(ctx, condition, &fields) { - push(f, ERR_BAD_ATTR_VALUE, format!("{label} {problem}")); + if let Some(message) = condition_message(ctx, condition, oname, &fields, &label) { + push(f, ERR_BAD_ATTR_VALUE, message); } } } diff --git a/server/rust/metaobjects/src/validate/mod.rs b/server/rust/metaobjects/src/validate/mod.rs index 98592ce9d6..beb340bd04 100644 --- a/server/rust/metaobjects/src/validate/mod.rs +++ b/server/rust/metaobjects/src/validate/mod.rs @@ -15,6 +15,7 @@ pub mod prompt; pub mod refs; pub mod relationships; pub mod reporting; +pub mod rules; pub mod structure; pub mod util; @@ -63,18 +64,19 @@ pub type PassFn = fn(&Ctx<'_>, &mut Findings); /// validateDataGridFilterValues validateProjectionFilter /// validateOriginSegmentsAndCorrelation validateProjectionUnionAndGrain /// validateDerivedCycles validateReporting -/// validateRelationships validateOneSideReferenceResolution -/// validateM2MJunctionPairing validateIndexLookupFields -/// validateColumnNameCollisions validateRetiredRequirementLinks -/// runRegisteredValidation validateTemplatePayloadRefs -/// validateAttrSchema (errors + warnings) validateFieldObjectStorage -/// validateFieldMap validateEnumMaxLength -/// validateIdentitySequence validateCrossFieldValidators -/// validateDbCheck validateSourceRoles -/// validateSourceEscapes validateSourcePhysicalNames -/// validateFieldMutability validateEnumNormalizeAmbiguity (warning) -/// validateEnumNormalizeCollision validateSourceParameterRef -/// validateDiscriminator validateFieldDefaults +/// validateRules validateRelationships +/// validateOneSideReferenceResolution validateM2MJunctionPairing +/// validateIndexLookupFields validateColumnNameCollisions +/// validateRetiredRequirementLinks runRegisteredValidation +/// validateTemplatePayloadRefs validateAttrSchema (errors + warnings) +/// validateFieldObjectStorage validateFieldMap +/// validateEnumMaxLength validateIdentitySequence +/// validateCrossFieldValidators validateDbCheck +/// validateSourceRoles validateSourceEscapes +/// validateSourcePhysicalNames validateFieldMutability +/// validateEnumNormalizeAmbiguity (warning) validateEnumNormalizeCollision +/// validateSourceParameterRef validateDiscriminator +/// validateFieldDefaults /// ``` pub const PASSES: &[(&str, PassFn)] = &[ ("subtype rules", structure::subtype_rules), @@ -120,6 +122,7 @@ pub const PASSES: &[(&str, PassFn)] = &[ ), ("derived cycles", origin::validate_derived_cycles), ("reporting", reporting::validate_reporting), + ("rules", rules::validate_rules), ("relationships", relationships::validate_relationships), ( "one-side reference resolution", diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs new file mode 100644 index 0000000000..20ad116121 --- /dev/null +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -0,0 +1,1276 @@ +//! ADR-0066: the cross-node rules for operations and lifecycles. +//! +//! A port of the TypeScript reference (`loader/rules-validation.ts`, with the derivation +//! helpers of `core/transition/lifecycle.ts`). Every port implements the same rules with +//! the same message text; the `error-rules-*` and `rules-*` fixtures under +//! `fixtures/conformance/` are the contract, and the rule ids are the ones +//! `docs/features/business-rules.md` lists. +//! +//! One broken rule yields one error: +//! - each error's source is the offending node: the transition, the enum field (L3), +//! the entity (L2), the operation or the binding; +//! - an operation whose `@inputRef` or `@outputRef` fails O1 is not checked further, and +//! one whose target fails O2 or O3 is not checked for O4 or B1; +//! - an error is reported once per (node, code), so a broken transition on an abstract +//! base is reported once, not once per inheritor. +//! +//! ```text +//! 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 writable +//! 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 +//! L6 ERR_TRANSITION_NAME_COLLISION two transitions of one entity share a name, without case +//! L7 ERR_BAD_ATTR_VALUE @condition names a field the entity lacks, or is not boolean +//! L8 ERR_BAD_ATTR_VALUE @from is empty +//! L9 ERR_BAD_ATTR_VALUE a lifecycle field is an array +//! L10 ERR_LIFECYCLE_REDECLARED an inherited lifecycle field redeclared without extending it +//! P1 ERR_PERMISSION_PUBLIC_CONFLICT @public: true with @permission (operation or transition) +//! P2 ERR_BAD_ATTR_VALUE @permission is not a dotted identifier path +//! O0 ERR_TRANSITION_NAME_COLLISION an operation named create/get/list/update/delete, in any case +//! O6 ERR_TRANSITION_NAME_COLLISION two operations of one package share a name, unless they are +//! the same operation declared identically in two APIs +//! O1 ERR_OPERATION_SHAPE @inputRef is not an object.value; @outputRef is not an +//! entity, projection or value +//! O2 ERR_OPERATION_TARGET_UNRESOLVED @objectRef is not an object.entity, or a command lists +//! @transitions and no target is declared or derivable +//! O3 ERR_OPERATION_TARGET_MISMATCH a declared @objectRef disagrees with the derived target +//! O4 ERR_OPERATION_UNKNOWN_TRANSITION a @transitions name is not a transition of the target +//! O5 ERR_BAD_ATTR_VALUE an @errors code is not lower snake case, is listed twice, +//! or is one the route answers itself +//! 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 +//! ``` +//! +//! Everything a lifecycle has beyond its transitions is derived, with no vocabulary of +//! its own: its states, its initial state and an operation's target entity. Reads are +//! resolving (ADR-0039): a transition declared on a base entity's field is a transition +//! of every entity that extends it. It is not a transition of an entity whose field merely +//! `extends` that field: a field extends another to share its values. + +use std::collections::{HashMap, HashSet}; + +use serde_json::Value; + +use crate::errors::{ERR_BAD_ATTR_VALUE, MetaError}; +use crate::loader::split_child_tail; +use crate::node::{NodeId, PACKAGE_SEP, Tree}; +use crate::parser::{TYPE_FIELD, TYPE_OBJECT}; +use crate::validate::field_expr::{condition_message, fields_by_name}; +use crate::validate::{Ctx, Findings}; + +pub const ERR_TRANSITION_UNKNOWN_STATE: &str = "ERR_TRANSITION_UNKNOWN_STATE"; +pub const ERR_TRANSITION_NOT_ON_ENTITY: &str = "ERR_TRANSITION_NOT_ON_ENTITY"; +pub const ERR_LIFECYCLE_NO_INITIAL: &str = "ERR_LIFECYCLE_NO_INITIAL"; +pub const ERR_LIFECYCLE_REDECLARED: &str = "ERR_LIFECYCLE_REDECLARED"; +pub const ERR_TRANSITION_NAME_COLLISION: &str = "ERR_TRANSITION_NAME_COLLISION"; +pub const ERR_OPERATION_SHAPE: &str = "ERR_OPERATION_SHAPE"; +pub const ERR_OPERATION_TARGET_UNRESOLVED: &str = "ERR_OPERATION_TARGET_UNRESOLVED"; +pub const ERR_OPERATION_TARGET_MISMATCH: &str = "ERR_OPERATION_TARGET_MISMATCH"; +pub const ERR_OPERATION_UNKNOWN_TRANSITION: &str = "ERR_OPERATION_UNKNOWN_TRANSITION"; +pub const ERR_PERMISSION_PUBLIC_CONFLICT: &str = "ERR_PERMISSION_PUBLIC_CONFLICT"; +pub const ERR_BINDING_PATH_MISMATCH: &str = "ERR_BINDING_PATH_MISMATCH"; + +const T_API: &str = "api"; +const T_OPERATION: &str = "operation"; +const T_BINDING: &str = "binding"; +const T_TRANSITION: &str = "transition"; +const T_SOURCE: &str = "source"; +const T_IDENTITY: &str = "identity"; + +const SUB_ENTITY: &str = "entity"; +const SUB_PROJECTION: &str = "projection"; +const SUB_VALUE: &str = "value"; +const SUB_ENUM: &str = "enum"; +const SUB_ACTION: &str = "action"; +const SUB_COMMAND: &str = "command"; +const SUB_QUERY: &str = "query"; +const SUB_REST: &str = "rest"; +const SUB_PRIMARY: &str = "primary"; + +const A_DEFAULT: &str = "default"; +const A_VALUES: &str = "values"; +const A_FROM: &str = "from"; +const A_TO: &str = "to"; +const A_CONDITION: &str = "condition"; +const A_PERMISSION: &str = "permission"; +const A_PUBLIC: &str = "public"; +const A_ERRORS: &str = "errors"; +const A_INPUT_REF: &str = "inputRef"; +const A_OUTPUT_REF: &str = "outputRef"; +const A_OBJECT_REF: &str = "objectRef"; +const A_TRANSITIONS: &str = "transitions"; +const A_MANY: &str = "many"; +const A_METHOD: &str = "method"; +const A_PATH: &str = "path"; +const A_FIELDS: &str = "fields"; +const A_KIND: &str = "kind"; + +const KIND_TABLE: &str = "table"; +const READ_ONLY_KINDS: [&str; 4] = ["view", "materializedView", "storedProc", "tableFunction"]; +const METHOD_POST: &str = "POST"; +const METHOD_GET: &str = "GET"; + +/// Names a declared operation or a transition may not take: the derived CRUD verbs of +/// the same service. +const RESERVED_OPERATION_NAMES: [&str; 5] = ["create", "get", "list", "update", "delete"]; + +/// Wire error codes an operation's route answers on its own, so a body may not declare +/// them in `@errors`. +const RESERVED_ERROR_CODES: [&str; 11] = [ + "not_found", + "forbidden", + "invalid_transition", + "transition_condition_failed", + "state_managed", + "validation", + "invalid_json", + "invalid_id", + "method_not_allowed", + "constraint_violation", + "internal", +]; + +// ---- small helpers ------------------------------------------------------------------ + +/// A derived name is compared without case: a command, a permission constant or a file +/// named from it collides with another that differs only in case on a case-folding target. +fn is_reserved_name(name: &str) -> bool { + RESERVED_OPERATION_NAMES.contains(&name.to_lowercase().as_str()) +} + +fn reserved_list() -> String { + RESERVED_OPERATION_NAMES.join(", ") +} + +fn is_identifier(s: &str) -> bool { + let mut chars = s.chars(); + chars + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +/// A declared `@permission`: identifiers joined by `.`, where a package prefix may use +/// `::` (the reference's `PERMISSION_NAME_PATTERN`). +fn is_permission_name(s: &str) -> bool { + s.split(PACKAGE_SEP) + .all(|part| part.split('.').all(is_identifier)) +} + +/// A declared business error code: lower snake case (the reference's +/// `BUSINESS_ERROR_CODE_PATTERN`). +fn is_business_error_code(s: &str) -> bool { + let word = |w: &str| { + !w.is_empty() + && w.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + }; + let mut words = s.split('_'); + words + .next() + .is_some_and(|first| first.starts_with(|c: char| c.is_ascii_lowercase()) && word(first)) + && words.all(word) +} + +/// What each `{...}` of a path holds, in order. +fn placeholders(path: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut rest = path; + while let Some(open) = rest.find('{') { + let Some(len) = rest[open + 1..].find('}') else { + break; + }; + out.push(&rest[open + 1..open + 1 + len]); + rest = &rest[open + len + 2..]; + } + out +} + +/// A path with every placeholder's name removed, so two routes that differ only in what +/// they call a placeholder compare equal. +fn route_shape(path: &str) -> String { + let mut out = String::new(); + let mut rest = path; + while let Some(open) = rest.find('{') { + let Some(len) = rest[open + 1..].find('}') else { + break; + }; + out.push_str(&rest[..open]); + out.push_str("{}"); + rest = &rest[open + len + 2..]; + } + out.push_str(rest); + out +} + +fn quote_list>(xs: &[S]) -> String { + xs.iter() + .map(|x| format!("\"{}\"", x.as_ref())) + .collect::>() + .join(", ") +} + +fn sorted<'a>(xs: &[&'a str]) -> Vec<&'a str> { + let mut v = xs.to_vec(); + v.sort_unstable(); + v +} + +/// The distinct values, first occurrence first. +fn unique<'a>(xs: impl IntoIterator) -> Vec<&'a str> { + let mut out: Vec<&str> = Vec::new(); + for x in xs { + if !out.contains(&x) { + out.push(x); + } + } + out +} + +/// `"Entity.field.transition"` for a transition, `"Api.operation"` for an operation. A +/// binding is unnamed, so its label is its operation's. +fn label(tree: &Tree, node: NodeId) -> String { + let mut parts: Vec<&str> = Vec::new(); + let mut cur = node; + while let Some(parent) = tree.node(cur).parent { + let name = tree.node(cur).name.as_str(); + if !name.is_empty() { + parts.push(name); + } + cur = parent; + } + parts.reverse(); + parts.join(".") +} + +/// A string-array attr read resolving; a bare string is one element. +fn string_list<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Vec<&'a str> { + match tree.attr(node, attr) { + Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(), + Some(Value::String(s)) => vec![s.as_str()], + _ => Vec::new(), + } +} + +fn str_attr<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Option<&'a str> { + tree.attr(node, attr).and_then(Value::as_str) +} + +fn is_true(tree: &Tree, node: NodeId, attr: &str) -> bool { + tree.attr(node, attr) == Some(&Value::Bool(true)) +} + +fn is_a(tree: &Tree, node: NodeId, type_name: &str, sub_type: &str) -> bool { + let n = tree.node(node); + n.type_name == type_name && n.sub_type == sub_type +} + +fn is_entity(tree: &Tree, node: NodeId) -> bool { + is_a(tree, node, TYPE_OBJECT, SUB_ENTITY) +} + +struct Sink<'a> { + tree: &'a Tree, + errors: Vec, + seen: HashSet<(NodeId, &'static str)>, +} + +impl Sink<'_> { + fn add(&mut self, node: NodeId, code: &'static str, message: String) { + if self.seen.insert((node, code)) { + self.errors.push(MetaError::at( + code, + message, + self.tree.node(node).source.clone(), + )); + } + } +} + +// ---- lifecycle and target derivation ------------------------------------------------ + +/// The `transition.action` children of a field, resolving. +fn transitions_of(tree: &Tree, field: NodeId) -> Vec { + tree.children(field) + .iter() + .copied() + .filter(|&c| is_a(tree, c, T_TRANSITION, SUB_ACTION)) + .collect() +} + +/// An entity and every entity it extends, nearest first. +fn entity_lineage(tree: &Tree, entity: NodeId) -> Vec { + let mut out = Vec::new(); + let mut cur = Some(entity); + while let Some(e) = cur.filter(|e| !out.contains(e)) { + out.push(e); + cur = tree.node(e).super_node; + } + out +} + +/// The transitions a field gives the entity whose lineage this is: those declared on a +/// field of the entity itself or of an entity it extends. A transition reached only +/// through the field's own `extends` of another entity's field is not one. +fn lifecycle_transitions_of(tree: &Tree, lineage: &[NodeId], field: NodeId) -> Vec { + transitions_of(tree, field) + .into_iter() + .filter(|&t| { + tree.node(t) + .parent + .and_then(|f| tree.node(f).parent) + .is_some_and(|owner| lineage.contains(&owner)) + }) + .collect() +} + +/// Every transition of an object, across all its lifecycles (its enum fields with at +/// least one transition), in effective field order. Only an `object.entity` has any. +fn entity_transitions(tree: &Tree, obj: NodeId) -> Vec { + if !is_entity(tree, obj) { + return Vec::new(); + } + let lineage = entity_lineage(tree, obj); + tree.children(obj) + .iter() + .copied() + .filter(|&f| is_a(tree, f, TYPE_FIELD, SUB_ENUM)) + .flat_map(|f| lifecycle_transitions_of(tree, &lineage, f)) + .collect() +} + +/// The primary key field names of an entity: its effective `identity.primary` `@fields`. +fn primary_key_fields(tree: &Tree, entity: NodeId) -> Vec<&str> { + tree.children(entity) + .iter() + .copied() + .find(|&c| is_a(tree, c, T_IDENTITY, SUB_PRIMARY)) + .map(|primary| string_list(tree, primary, A_FIELDS)) + .unwrap_or_default() +} + +/// The package a node's references resolve in: its top-level node's effective package. +fn referrer_package_of(tree: &Tree, node: NodeId) -> String { + tree.effective_package(tree.top_level_of(node)) +} + +/// Resolve an object reference written on `node` (owner part only). +fn resolve_object_on(ctx: &Ctx<'_>, node: NodeId, reference: &str) -> Option { + ctx.objects.resolve( + split_child_tail(reference).0, + &referrer_package_of(ctx.tree, node), + ) +} + +/// The object a member's `extends` names, and the member it names there. `id extends +/// PurchaseRequest.id` names `PurchaseRequest` even when that entity inherits `id` from +/// an abstract base, which is where the resolved super node physically lives. +fn extended_member<'a>(ctx: &Ctx<'a>, member: NodeId) -> Option<(NodeId, &'a str)> { + let tree = ctx.tree; + let node = tree.node(member); + let reference = node.super_ref.as_deref()?; + let sup = node.super_node?; + let name = tree.node(sup).name.as_str(); + let (owner, tail) = split_child_tail(reference); + if !tail.is_empty() + && !owner.is_empty() + && !owner.ends_with(PACKAGE_SEP) + && let Some(named) = ctx + .objects + .resolve(owner, &referrer_package_of(tree, member)) + { + return Some((named, name)); + } + let parent = tree.node(sup).parent?; + (tree.node(parent).type_name == TYPE_OBJECT).then_some((parent, name)) +} + +/// The entities whose whole primary key a value object borrows, once: every primary key +/// field of the entity is extended by exactly one field of the value. A value that +/// borrows part of a composite key, or one key field twice (`fromId` and `toId`), names +/// no single row of that entity, so it borrows nothing from it. +fn borrowed_key_entities(ctx: &Ctx<'_>, value: NodeId) -> Vec { + let tree = ctx.tree; + let mut counts: Vec<(NodeId, HashMap<&str, usize>)> = Vec::new(); + for &f in tree.children(value).iter() { + if tree.node(f).type_name != TYPE_FIELD { + continue; + } + let Some((owner, member)) = extended_member(ctx, f) else { + continue; + }; + if tree.node(owner).sub_type != SUB_ENTITY + || !primary_key_fields(tree, owner).contains(&member) + { + continue; + } + let slot = match counts.iter().position(|(o, _)| *o == owner) { + Some(i) => i, + None => { + counts.push((owner, HashMap::new())); + counts.len() - 1 + } + }; + *counts[slot].1.entry(member).or_insert(0) += 1; + } + counts + .into_iter() + .filter(|(owner, members)| { + primary_key_fields(tree, *owner) + .iter() + .all(|k| members.get(k) == Some(&1)) + }) + .map(|(owner, _)| owner) + .collect() +} + +/// The base entity of a projection: the entity its extended identity names, else the one +/// entity its extended fields name. `None` when there is none or more than one. +fn projection_base_entity(ctx: &Ctx<'_>, projection: NodeId) -> Option { + let tree = ctx.tree; + let kids = tree.children(projection); + let entity_named_by = |member: NodeId| { + extended_member(ctx, member) + .map(|(owner, _)| owner) + .filter(|&owner| tree.node(owner).sub_type == SUB_ENTITY) + }; + if let Some(owner) = kids + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == T_IDENTITY) + .find_map(entity_named_by) + { + return Some(owner); + } + let mut owners: Vec = Vec::new(); + for owner in kids + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_FIELD) + .filter_map(entity_named_by) + { + if !owners.contains(&owner) { + owners.push(owner); + } + } + (owners.len() == 1).then(|| owners[0]) +} + +/// How an operation's target was derived. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Via { + /// The input borrows the target's key. + Input, + Output, +} + +/// The target entity derived from an operation's shapes: +/// 1. the one entity whose whole primary key the `@inputRef` value borrows (by +/// `extends`), each key field once; +/// 2. else the `@outputRef`: an entity is its own target, a projection its base entity. +/// +/// Whole keys of two entities, part of a key, or one key field borrowed twice derive +/// nothing from the input. +fn derive_operation_target(ctx: &Ctx<'_>, op: NodeId) -> Option<(NodeId, Via)> { + let tree = ctx.tree; + if let Some(input) = str_attr(tree, op, A_INPUT_REF) + .and_then(|r| resolve_object_on(ctx, op, r)) + .filter(|&i| tree.node(i).sub_type == SUB_VALUE) + { + let borrowed = borrowed_key_entities(ctx, input); + if borrowed.len() == 1 { + return Some((borrowed[0], Via::Input)); + } + } + let output = str_attr(tree, op, A_OUTPUT_REF).and_then(|r| resolve_object_on(ctx, op, r))?; + match tree.node(output).sub_type.as_str() { + SUB_ENTITY => Some((output, Via::Output)), + SUB_PROJECTION => projection_base_entity(ctx, output).map(|base| (base, Via::Output)), + _ => None, + } +} + +/// Whether the operation addresses one row of its target by key: its input borrows the +/// target's key, or it is a query with no input and no `@many` whose target comes from +/// its output (a get by key). +fn operation_is_keyed(ctx: &Ctx<'_>, op: NodeId, derived: Option<(NodeId, Via)>) -> bool { + let tree = ctx.tree; + match derived { + None => false, + Some((_, Via::Input)) => true, + Some((_, Via::Output)) => { + tree.node(op).sub_type == SUB_QUERY + && str_attr(tree, op, A_INPUT_REF).is_none() + && !is_true(tree, op, A_MANY) + } + } +} + +// ---- the rules ---------------------------------------------------------------------- + +/// P1 and P2 for an operation or a transition. +fn check_permission(tree: &Tree, node: NodeId, sink: &mut Sink<'_>) { + let n = tree.node(node); + let permission = tree.attr(node, A_PERMISSION); + if is_true(tree, node, A_PUBLIC) && permission.is_some() { + sink.add( + node, + ERR_PERMISSION_PUBLIC_CONFLICT, + format!( + "{}.{} \"{}\" declares both @public: true and @permission; a public {} calls no permission check, so remove one.", + n.type_name, + n.sub_type, + label(tree, node), + n.type_name + ), + ); + } + if let Some(Value::String(p)) = permission + && !is_permission_name(p) + { + sink.add( + node, + ERR_BAD_ATTR_VALUE, + format!( + "{}.{} \"{}\" @permission \"{p}\" is not a dotted identifier path; use names of letters, digits and _ joined by \".\" (a package prefix may use \"::\"), such as \"purchasing.approve\".", + n.type_name, + n.sub_type, + label(tree, node) + ), + ); + } +} + +/// L1, L3, L4, L5, L7, L8, L9, P1 and P2 for the transitions declared on one field. +fn check_declared_transitions(ctx: &Ctx<'_>, field: NodeId, sink: &mut Sink<'_>) { + let tree = ctx.tree; + // ADR-0039: own — each transition is checked where it is declared. + let declared: Vec = tree + .own_children(field) + .iter() + .copied() + .filter(|&c| is_a(tree, c, T_TRANSITION, SUB_ACTION)) + .collect(); + if declared.is_empty() { + return; + } + let fnode = tree.node(field); + let Some(owner) = fnode.parent.filter(|&o| is_entity(tree, o)) else { + let place = match fnode.parent.map(|o| tree.node(o)) { + Some(o) if o.type_name == TYPE_OBJECT => { + format!("object.{} \"{}\"", o.sub_type, o.name) + } + _ => "the document root".to_string(), + }; + for t in declared { + sink.add( + t, + ERR_TRANSITION_NOT_ON_ENTITY, + format!( + "transition.action \"{}\" is declared on a field of {place}; a lifecycle belongs to an object.entity with a writable source.", + label(tree, t) + ), + ); + } + return; + }; + if fnode.sub_type == SUB_ENUM && str_attr(tree, field, A_DEFAULT).is_none() { + sink.add( + field, + ERR_LIFECYCLE_NO_INITIAL, + format!( + "field.enum \"{}\" declares transitions but no @default; its @default is the lifecycle's initial state.", + label(tree, field) + ), + ); + } + if tree.resolved_is_array(field) { + sink.add( + field, + ERR_BAD_ATTR_VALUE, + format!( + "field.{} \"{}\" declares transitions but is an array (@isArray: true); a lifecycle's state is one value.", + fnode.sub_type, + label(tree, field) + ), + ); + } + let states = unique(string_list(tree, field, A_VALUES)); + let mut owner_fields = None; + for t in declared { + check_permission(tree, t, sink); + let from = string_list(tree, t, A_FROM); + if from.is_empty() { + sink.add( + t, + ERR_BAD_ATTR_VALUE, + format!( + "transition.action \"{}\" @from is empty; name at least one state the transition leaves.", + label(tree, t) + ), + ); + } + let unknown: Vec<&str> = unique(from.into_iter().chain(str_attr(tree, t, A_TO))) + .into_iter() + .filter(|s| !states.contains(s)) + .collect(); + if !unknown.is_empty() { + sink.add( + t, + ERR_TRANSITION_UNKNOWN_STATE, + format!( + "transition.action \"{}\" names {}, which {} of \"{}\" @values ({}).", + label(tree, t), + quote_list(&unknown), + if unknown.len() == 1 { + "is not a member" + } else { + "are not members" + }, + fnode.name, + quote_list(&states) + ), + ); + } + let name = &tree.node(t).name; + if is_reserved_name(name) { + sink.add( + t, + ERR_TRANSITION_NAME_COLLISION, + format!( + "transition.action \"{}\" is named \"{name}\", which is a derived CRUD verb ({}); rename it.", + label(tree, t), + reserved_list() + ), + ); + } + if let Some(condition) = tree.attr(t, A_CONDITION) { + let fields = owner_fields.get_or_insert_with(|| fields_by_name(ctx, owner)); + let opening = format!("transition.action \"{}\" @condition", label(tree, t)); + if let Some(message) = + condition_message(ctx, condition, &tree.node(owner).name, fields, &opening) + { + sink.add(t, ERR_BAD_ATTR_VALUE, message); + } + } + } +} + +/// L10: an entity's field named like an ancestor's lifecycle field that does not carry +/// that lifecycle's transitions. Redeclaring the field replaces it, so the base's state +/// machine would silently stop applying to this entity. +fn check_redeclared_lifecycles( + tree: &Tree, + entity: NodeId, + lineage: &[NodeId], + sink: &mut Sink<'_>, +) { + for (depth, &ancestor) in lineage.iter().enumerate().skip(1) { + // ADR-0039: own — the lifecycle fields the ancestor itself declares. + for &base_field in tree.own_children(ancestor) { + if tree.node(base_field).type_name != TYPE_FIELD { + continue; + } + let base_transitions = lifecycle_transitions_of(tree, &lineage[depth..], base_field); + if base_transitions.is_empty() { + continue; + } + let base_name = &tree.node(base_field).name; + let Some(field) = tree.children(entity).iter().copied().find(|&c| { + let n = tree.node(c); + n.type_name == TYPE_FIELD && n.name == *base_name + }) else { + continue; + }; + if field == base_field { + continue; + } + let kept = lifecycle_transitions_of(tree, lineage, field); + if base_transitions.iter().all(|t| kept.contains(t)) { + continue; + } + sink.add( + field, + ERR_LIFECYCLE_REDECLARED, + format!( + "field.{} \"{}\" redeclares \"{}\", which has a lifecycle, and drops its transitions; extend it (\"extends\": \"{}.{base_name}\") or give the field another name.", + tree.node(field).sub_type, + label(tree, field), + label(tree, base_field), + tree.node(ancestor).name + ), + ); + } + } +} + +/// A source that is not one of the read-only kinds; `table` is the default. +fn is_writable_source(tree: &Tree, node: NodeId) -> bool { + tree.node(node).type_name == T_SOURCE && { + let kind = str_attr(tree, node, A_KIND) + .filter(|k| !k.is_empty()) + .unwrap_or(KIND_TABLE); + !READ_ONLY_KINDS.contains(&kind) + } +} + +/// L2, L6 and L10 for one entity, over its effective (inherited) lifecycles. +fn check_entity_lifecycles(tree: &Tree, entity: NodeId, sink: &mut Sink<'_>) { + check_redeclared_lifecycles(tree, entity, &entity_lineage(tree, entity), sink); + let transitions = entity_transitions(tree, entity); + if transitions.is_empty() { + return; + } + let enode = tree.node(entity); + let mut by_name: HashMap = HashMap::new(); + for &t in &transitions { + match by_name.get(&tree.node(t).name.to_lowercase()) { + None => { + by_name.insert(tree.node(t).name.to_lowercase(), t); + } + Some(&first) if first != t => sink.add( + t, + ERR_TRANSITION_NAME_COLLISION, + format!( + "transition.action \"{}\" has the same name as \"{}\" (names are compared without case); the transitions of \"{}\" share one namespace (each may derive a command), so rename one.", + label(tree, t), + label(tree, first), + enode.name + ), + ), + Some(_) => {} + } + } + let kids = tree.children(entity); + // A lifecycle is live once the entity declares or inherits a source. With no source + // at all it loads and is inert, like everything else on a sourceless entity. + let live = kids.iter().any(|&c| tree.node(c).type_name == T_SOURCE); + if !enode.is_abstract && live && !kids.iter().any(|&c| is_writable_source(tree, c)) { + let fields = unique(transitions.iter().map(|&t| { + tree.node(t) + .parent + .map_or("", |f| tree.node(f).name.as_str()) + })); + sink.add( + 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.)", + enode.name, + quote_list(&fields) + ), + ); + } +} + +/// The `binding.rest` children an operation declares that carry a `@path`. +fn declared_paths(tree: &Tree, op: NodeId) -> Vec<(NodeId, &str)> { + // ADR-0039: own — a binding is checked on the operation that declares it. + tree.own_children(op) + .iter() + .copied() + .filter(|&b| is_a(tree, b, T_BINDING, SUB_REST)) + .filter_map(|b| str_attr(tree, b, A_PATH).map(|path| (b, path))) + .collect() +} + +/// O0 to O5, P1, P2 and B1 for one operation. +fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { + let tree = ctx.tree; + let onode = tree.node(op); + let sub = onode.sub_type.as_str(); + let op_label = label(tree, op); + if is_reserved_name(&onode.name) { + sink.add( + op, + ERR_TRANSITION_NAME_COLLISION, + format!( + "operation.{sub} \"{op_label}\" is named \"{}\", which is a derived CRUD verb ({}); rename it.", + onode.name, + reserved_list() + ), + ); + } + check_permission(tree, op, sink); + + // O5 — the business errors. + let codes = string_list(tree, op, A_ERRORS); + let bad: Vec<&str> = codes + .iter() + .copied() + .filter(|c| !is_business_error_code(c)) + .collect(); + let dup = unique( + codes + .iter() + .enumerate() + .filter(|&(i, c)| codes.iter().position(|x| x == c) != Some(i)) + .map(|(_, c)| *c), + ); + let reserved = unique( + codes + .iter() + .copied() + .filter(|c| RESERVED_ERROR_CODES.contains(c)), + ); + let why = if !bad.is_empty() { + let one = bad.len() == 1; + Some(format!( + "{} {} lower snake case code{}", + quote_list(&bad), + if one { "is not a" } else { "are not" }, + if one { "" } else { "s" } + )) + } else if !dup.is_empty() { + Some(format!( + "{} {} listed twice", + quote_list(&dup), + if dup.len() == 1 { "is" } else { "are" } + )) + } else if !reserved.is_empty() { + Some(format!( + "{} {} the route answers itself ({})", + quote_list(&reserved), + if reserved.len() == 1 { + "is a code" + } else { + "are codes" + }, + RESERVED_ERROR_CODES.join(", ") + )) + } else { + None + }; + if let Some(why) = why { + sink.add( + op, + ERR_BAD_ATTR_VALUE, + format!("operation.{sub} \"{op_label}\" @errors: {why}."), + ); + } + + // 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, 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, 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; + } + } + + // O2, O3 — the target. + let derived = derive_operation_target(ctx, op); + let mut target = derived.map(|(entity, _)| entity); + if let Some(object_ref) = str_attr(tree, op, A_OBJECT_REF) { + let declared = resolve_object_on(ctx, op, object_ref); + let Some(declared) = declared.filter(|&d| tree.node(d).sub_type == SUB_ENTITY) else { + sink.add( + op, + ERR_OPERATION_TARGET_UNRESOLVED, + format!( + "operation.{sub} \"{op_label}\" @objectRef \"{object_ref}\" {}; an operation acts on an object.entity.", + found(declared) + ), + ); + return; + }; + if let Some(derived) = target.filter(|&d| d != declared) { + sink.add( + op, + ERR_OPERATION_TARGET_MISMATCH, + format!( + "operation.{sub} \"{op_label}\" @objectRef names \"{}\", but its input and output derive \"{}\"; remove @objectRef or make them agree.", + tree.node(declared).name, + tree.node(derived).name + ), + ); + return; + } + target = Some(declared); + } + let transitions = if sub == SUB_COMMAND { + string_list(tree, op, A_TRANSITIONS) + } else { + Vec::new() + }; + if !transitions.is_empty() && target.is_none() { + sink.add( + op, + ERR_OPERATION_TARGET_UNRESOLVED, + format!( + "operation.command \"{op_label}\" lists @transitions but has no target entity: the @inputRef does not borrow one entity's whole primary key (each key field extended exactly once), no @outputRef has a base entity, and there is no @objectRef." + ), + ); + return; + } + + // O4 — the transitions it may make. + if let Some(target) = target.filter(|_| !transitions.is_empty()) { + let known: Vec<&str> = entity_transitions(tree, target) + .into_iter() + .map(|t| tree.node(t).name.as_str()) + .collect(); + let unknown: Vec<&str> = unique(transitions) + .into_iter() + .filter(|n| !known.contains(n)) + .collect(); + if !unknown.is_empty() { + sink.add( + op, + ERR_OPERATION_UNKNOWN_TRANSITION, + format!( + "operation.command \"{op_label}\" @transitions names {}, which {} of \"{}\".", + quote_list(&unknown), + if unknown.len() == 1 { + "is not a transition" + } else { + "are not transitions" + }, + tree.node(target).name + ), + ); + } + } + + // B1 — binding paths. + for (binding, path) in declared_paths(tree, op) { + let found = placeholders(path); + let expected = match target { + Some(t) if operation_is_keyed(ctx, op, derived) => primary_key_fields(tree, t), + _ => Vec::new(), + }; + if sorted(&found) == sorted(&expected) { + continue; + } + let takes = match target { + Some(t) if !expected.is_empty() => format!( + "\"{op_label}\" addresses one \"{}\" by key, so its path takes exactly [{}].", + tree.node(t).name, + quote_list(&expected) + ), + _ => format!("\"{op_label}\" addresses no row by key, so its path takes none."), + }; + sink.add( + binding, + ERR_BINDING_PATH_MISMATCH, + format!( + "binding.rest on \"{}\" @path \"{path}\" has placeholders [{}]; {takes}", + label(tree, binding), + quote_list(&found) + ), + ); + } +} + +/// Whether two attr values as written are the same value. A list or a map is never the +/// same as another (the reference compares them by identity), so two operations that +/// both carry a malformed value are not declared identically. +fn same_written(a: &Value, b: &Value) -> bool { + !a.is_array() && !a.is_object() && a == b +} + +/// A reference attr's identity: the node it resolves to, else the value as written. +enum RefIdentity<'a> { + Node(NodeId), + Raw(&'a Value), + Absent, +} + +impl PartialEq for RefIdentity<'_> { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::Node(a), Self::Node(b)) => a == b, + (Self::Raw(a), Self::Raw(b)) => same_written(a, b), + (Self::Absent, Self::Absent) => true, + _ => false, + } + } +} + +fn ref_identity<'a>(ctx: &Ctx<'a>, op: NodeId, attr: &str) -> RefIdentity<'a> { + match ctx.tree.attr(op, attr) { + None => RefIdentity::Absent, + Some(v) => v + .as_str() + .and_then(|r| resolve_object_on(ctx, op, r)) + .map_or(RefIdentity::Raw(v), RefIdentity::Node), + } +} + +/// A list attr as a set, for comparison. +fn set_of<'a>(tree: &'a Tree, op: NodeId, attr: &str) -> Vec<&'a str> { + sorted(&unique(string_list(tree, op, attr))) +} + +/// Whether two operations of one package in different APIs are one operation exposed +/// twice, as a versioned API beside its successor does (ADR-0067: one router per API, one +/// service): the same name and subtype, and the same contract. The contract is every +/// operation attribute: the referenced shapes (compared by the node they resolve to), the +/// transitions and errors (as sets), the permission, public and many. Bindings are per +/// API and are not compared. +fn same_operation(ctx: &Ctx<'_>, a: NodeId, b: NodeId) -> bool { + let tree = ctx.tree; + let (na, nb) = (tree.node(a), tree.node(b)); + na.name == nb.name + && na.sub_type == nb.sub_type + && [A_INPUT_REF, A_OUTPUT_REF, A_OBJECT_REF] + .iter() + .all(|attr| ref_identity(ctx, a, attr) == ref_identity(ctx, b, attr)) + && [A_TRANSITIONS, A_ERRORS] + .iter() + .all(|attr| set_of(tree, a, attr) == set_of(tree, b, attr)) + && match (tree.attr(a, A_PERMISSION), tree.attr(b, A_PERMISSION)) { + (None, None) => true, + (Some(x), Some(y)) => same_written(x, y), + _ => false, + } + && is_true(tree, a, A_PUBLIC) == is_true(tree, b, A_PUBLIC) + && is_true(tree, a, A_MANY) == is_true(tree, b, A_MANY) +} + +/// B2 across the operations of one API. +fn check_api_routes(tree: &Tree, ops: &[NodeId], sink: &mut Sink<'_>) { + let mut by_route: HashMap = HashMap::new(); + for &op in ops { + for (binding, path) in declared_paths(tree, op) { + // The effective method: the declared one, else the derived (ADR-0066). + let method = str_attr(tree, binding, A_METHOD).unwrap_or( + if tree.node(op).sub_type == SUB_COMMAND { + METHOD_POST + } else { + METHOD_GET + }, + ); + let route = format!("{method} {}", route_shape(path)); + match by_route.get(&route) { + None => { + by_route.insert(route, binding); + } + Some(&other) => sink.add( + binding, + ERR_BINDING_PATH_MISMATCH, + format!( + "binding.rest on \"{}\" declares {method} \"{path}\", the same route as the binding on \"{}\"; two operations cannot share a method and path.", + label(tree, binding), + label(tree, other) + ), + ), + } + } + } +} + +/// The rules pass. Runs after the reference-bearing validation, where the reference runs it. +pub fn validate_rules(ctx: &Ctx<'_>, f: &mut Findings) { + let tree = ctx.tree; + let mut sink = Sink { + tree, + errors: Vec::new(), + seen: HashSet::new(), + }; + let mut any_transition = false; + // ADR-0039: own — a structural walk over the declarations themselves: every field + // declared at the root and on every object. A root extends nothing, so its own + // children are its children. + let top_level = tree.own_children(ctx.root); + for &top in top_level { + let fields: &[NodeId] = match tree.node(top).type_name.as_str() { + TYPE_FIELD => &[top], + TYPE_OBJECT => tree.own_children(top), + _ => &[], + }; + for &field in fields { + if tree.node(field).type_name != TYPE_FIELD { + continue; + } + // ADR-0039: own — the same declared-here walk as check_declared_transitions. + any_transition |= tree + .own_children(field) + .iter() + .any(|&c| tree.node(c).type_name == T_TRANSITION); + check_declared_transitions(ctx, field, &mut sink); + } + } + // An entity has a lifecycle only when some field of some object declares a + // transition, so a model with none (most of them) skips the per-entity walk. + if any_transition { + for &obj in top_level { + if is_entity(tree, obj) { + check_entity_lifecycles(tree, obj, &mut sink); + } + } + } + // O6 — keyed by package, then by the name without case. + let mut by_name: HashMap<(String, String), NodeId> = HashMap::new(); + for &api in top_level { + if tree.node(api).type_name != T_API { + continue; + } + let ops: Vec = tree + .children(api) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == T_OPERATION) + .collect(); + for &op in &ops { + check_operation(ctx, op, &mut sink); + } + let package = tree.effective_package(api); + for &op in &ops { + let key = (package.clone(), tree.node(op).name.to_lowercase()); + match by_name.get(&key) { + None => { + by_name.insert(key, op); + } + Some(&first) if first != op && !same_operation(ctx, first, op) => sink.add( + op, + ERR_TRANSITION_NAME_COLLISION, + format!( + "operation.{} \"{}\" has the same name as \"{}\" (names are compared without case) and is not the same operation; the operations of package \"{package}\" share one namespace (each derives the permission name .), so rename one, or declare both identically to expose one operation in two APIs.", + tree.node(op).sub_type, + label(tree, op), + label(tree, first) + ), + ), + Some(_) => {} + } + } + check_api_routes(tree, &ops, &mut sink); + } + f.errors.extend(sink.errors); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_in_the_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for c in [ + ERR_TRANSITION_UNKNOWN_STATE, + ERR_TRANSITION_NOT_ON_ENTITY, + ERR_LIFECYCLE_NO_INITIAL, + ERR_LIFECYCLE_REDECLARED, + ERR_TRANSITION_NAME_COLLISION, + ERR_OPERATION_SHAPE, + ERR_OPERATION_TARGET_UNRESOLVED, + ERR_OPERATION_TARGET_MISMATCH, + ERR_OPERATION_UNKNOWN_TRANSITION, + ERR_PERMISSION_PUBLIC_CONFLICT, + ERR_BINDING_PATH_MISMATCH, + ERR_BAD_ATTR_VALUE, + ] { + assert!(codes.contains_key(c), "{c}"); + } + } + + #[test] + fn a_written_list_or_map_is_never_the_same_value_as_another() { + let s = |v: &str| Value::String(v.to_string()); + assert!(same_written( + &s("purchasing.approve"), + &s("purchasing.approve") + )); + assert!(!same_written( + &s("purchasing.approve"), + &s("purchasing.decide") + )); + assert!(same_written(&Value::Bool(true), &Value::Bool(true))); + let list = serde_json::json!(["a"]); + assert!(!same_written(&list, &list.clone())); + let map = serde_json::json!({ "a": 1 }); + assert!(!same_written(&map, &map.clone())); + } + + #[test] + fn permission_names_are_dotted_identifier_paths() { + for ok in [ + "approve", + "purchasing.approve", + "_a.b_1", + "acme::purchasing.PurchaseRequest.submit", + ] { + assert!(is_permission_name(ok), "{ok}"); + } + for bad in [ + "", + "purchasing.", + ".approve", + "a..b", + "a b", + "a/b", + "1a", + "a:b", + "a:::b", + "a::", + "a-b", + "a\n", + ] { + assert!(!is_permission_name(bad), "{bad:?}"); + } + } + + #[test] + fn business_error_codes_are_lower_snake_case() { + for ok in ["over_budget", "a", "a1_2b", "insufficient_funds"] { + assert!(is_business_error_code(ok), "{ok}"); + } + for bad in [ + "", + "OverBudget", + "over-budget", + "_a", + "a_", + "a__b", + "1a", + "over budget", + ] { + assert!(!is_business_error_code(bad), "{bad:?}"); + } + } + + #[test] + fn placeholders_and_route_shapes() { + assert_eq!(placeholders("/requests/{id}/decision"), vec!["id"]); + assert_eq!(placeholders("/a/{x}/b/{y}"), vec!["x", "y"]); + assert_eq!(placeholders("/plain"), Vec::<&str>::new()); + assert_eq!(placeholders("/a/{}"), vec![""]); + assert_eq!(placeholders("/a/{open"), Vec::<&str>::new()); + assert_eq!(route_shape("/a/{x}/b/{y}"), "/a/{}/b/{}"); + assert_eq!(route_shape("/a/{open"), "/a/{open"); + assert_eq!(route_shape("/plain"), "/plain"); + } +} diff --git a/server/rust/metaobjects/tests/config_reader.rs b/server/rust/metaobjects/tests/config_reader.rs index cc07cf7250..2d64c54753 100644 --- a/server/rust/metaobjects/tests/config_reader.rs +++ b/server/rust/metaobjects/tests/config_reader.rs @@ -280,6 +280,14 @@ fn a_nested_typo_or_wrong_type_is_an_error() { json!({"schema_version": 1, "scope": {"include": [""]}}), json!({"schema_version": 1, "verify": {"handEdits": "maybe"}}), json!({"schema_version": 1, "verify": {"other": 1}}), + json!({"schema_version": 1, "verify": {"lifecycle": {"unreachable": "loud"}}}), + json!({"schema_version": 1, "verify": {"lifecycle": {"unreachablee": "off"}}}), + json!({"schema_version": 1, "rules": []}), + json!({"schema_version": 1, "rules": {"permission": {}}}), + json!({"schema_version": 1, "rules": {"permissions": {"names": "always"}}}), + json!({"schema_version": 1, "rules": {"permissions": {"name": "derive"}}}), + json!({"schema_version": 1, "rules": {"lifecycle": {"create": "none"}}}), + json!({"schema_version": 1, "rules": {"lifecycle": {"commands": 1}}}), json!({"schema_version": 1, "requirements": {"inheret": []}}), json!({"schema_version": 1, "csharp": {"outDir": ""}}), json!({"schema_version": 1, "libraries": "iam"}), @@ -319,6 +327,67 @@ fn extract_and_confidence_thresholds_ignore_unknown_keys_as_the_typescript_reade assert_eq!(c.extract_metaignore.as_deref(), Some(".m")); } +#[test] +fn the_business_rules_settings_default_and_are_kept() { + use metaobjects::config::{ + RulesLifecycleCommands, RulesLifecycleCreate, RulesPermissionNames, RulesSettings, + VerifyLifecycleUnreachable, + }; + let parse = |doc: Value| { + parse_config(&doc, "c.json", &NamingRegistry::builtin()) + .unwrap() + .config + }; + // Absent, and empty at every level, take every default. + for doc in [ + json!({"schema_version": 1}), + json!({"schema_version": 1, "rules": {}, "verify": {}}), + json!({"schema_version": 1, "rules": {"permissions": {}, "lifecycle": {}}, "verify": {"lifecycle": {}}}), + ] { + assert_eq!(parse(doc).rules, RulesSettings::default()); + } + let c = parse(json!({ + "schema_version": 1, + "rules": {"permissions": {"names": "require"}, "lifecycle": {"create": "any", "commands": "none"}}, + "verify": {"handEdits": "fail", "lifecycle": {"unreachable": "error"}} + })); + assert_eq!( + c.rules, + RulesSettings { + permission_names: RulesPermissionNames::Require, + lifecycle_create: RulesLifecycleCreate::Any, + lifecycle_commands: RulesLifecycleCommands::NoneDerived, + lifecycle_unreachable: VerifyLifecycleUnreachable::Error, + } + ); + assert_eq!(c.hand_edits, Some(HandEditsPolicy::Fail)); + // `rules` is a known key: it does not draw the unknown-key warning. + let l = parse_config( + &json!({"schema_version": 1, "rules": {}}), + "c.json", + &NamingRegistry::builtin(), + ) + .unwrap(); + assert!(l.warnings.is_empty(), "{:?}", l.warnings); +} + +#[test] +fn a_verify_typo_names_both_keys_it_accepts() { + let err = parse_config( + &json!({"schema_version": 1, "verify": {"lifecycles": {}}}), + "c.json", + &NamingRegistry::builtin(), + ) + .unwrap_err(); + assert!( + err.message.contains( + "\"verify\" has an unknown key \"lifecycles\" (expected \"handEdits\" or \"lifecycle\")" + ), + "{}", + err.message + ); +} + #[test] fn migrate_verify_requirements_scope_and_csharp_are_kept() { let c = parse_config( diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json index 721f2af7f5..a38e1cb607 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 is in preview. It 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": 526, + "minPassing": 574, "fixtures": [] } diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index df1b6ade2f..e4c7a35c46 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -52,6 +52,7 @@ import { checkRequirements, summariseRequirements, scanRequirements, type Diagnostic, } from "../lib/requirement-check.js"; import { lintRequirements } from "../lib/requirement-lint.js"; +import { checkRules, type RulesSummary } from "../lib/rules-check.js"; import { lintOverlays } from "../lib/overlay-lint.js"; import { lintNodeNames } from "../lib/name-lint.js"; import { lintDeprecatedReferences } from "../lib/deprecation-lint.js"; @@ -478,6 +479,11 @@ export async function verifyCommand( // reported against its path. Undefined exactly when `requirementCounts` is — same // opt-in-by-declaration rule. let requirementLedger: RequirementLedgerRow[] | undefined; + // ADR-0066 — the business-rules gate's findings and what the model declares. Both stay + // undefined for a model with no operation and no transition, and then the payload, the + // gate list and the printed output are exactly what they were before the gate existed. + let rulesSection: AdvisorySection | undefined; + let rulesSummary: RulesSummary | undefined; // Whether the schema gate is selected. `runSchemaVerify` makes this decision // internally (it is selected by --db or --dialect d1, not by a subverb flag); @@ -502,6 +508,9 @@ export async function verifyCommand( // are checked on every `meta verify`. Opt-in by DECLARATION — a model with no // requirement nodes is silent, not in drift. const requirementExit = runRequirementVerify(); + // Business rules (ADR-0066): operations and lifecycles are metadata too, so this gate + // also runs on every `meta verify`, and is also opt-in by declaration. + const rulesExit = runRulesVerify(); // #313 — BOTH replay flags select this gate. `--replay-snapshot` implies // `--replay`'s work, so a broken chain must fail under it even when `--replay` // was not passed; naming only `flags.replay` here is how `--replay-snapshot` @@ -540,6 +549,7 @@ export async function verifyCommand( codegenExit, depsExit, requirementExit, + rulesExit, replayExit, ); @@ -553,6 +563,9 @@ export async function verifyCommand( { gate: "codegen", ran: runCodegen, ok: codegenExit === 0 }, { gate: "deps", ran: runDeps, ok: depsExit === 0 }, { gate: "requirements", ran: true, ok: requirementExit === 0 }, + // Listed only when the model declares an operation or a transition: a row for a gate + // with nothing to check would change every existing project's payload. + ...(rulesSummary !== undefined ? [{ gate: "rules", ran: true, ok: rulesExit === 0 }] : []), { gate: "replay", ran: flags.replay || flags.replaySnapshot, ok: replayExit === 0 }, ]; @@ -578,6 +591,8 @@ export async function verifyCommand( names: nameSection, deprecations: deprecationSection, fields: fieldSection, + ...(rulesSection !== undefined ? { rules: rulesSection } : {}), + ...(rulesSummary !== undefined ? { rulesCounts: rulesSummary } : {}), ...(schemaDrift !== undefined ? { schemaDrift } : {}), errors: schemaRunError !== undefined ? [{ gate: "schema", error: schemaRunError }] : [], }), @@ -924,6 +939,30 @@ export async function verifyCommand( return 0; } + // -- business rules (ADR-0066) ---------------------------------------------- + function runRulesVerify(): number { + const result = checkRules(root, collection.rulesSettings); + if (result.summary === undefined) return 0; + rulesSummary = result.summary; + const s = result.summary; + // Printed on every run that has something to check, like the requirement line: a gate + // that says nothing when it passes cannot be told from one that checked nothing. + say( + `meta verify — rules: ${s.operations} operation(s), ${s.lifecycles} lifecycle(s) ` + + `with ${s.transitions} transition(s).`, + ); + const errors = result.diagnostics.filter((d) => d.severity === "error"); + const warns = result.diagnostics.filter((d) => d.severity === "warn"); + for (const d of errors) log.error(formatDiagnostic(d)); + warnCapped(warns.map(formatDiagnostic), flags.limit, { structured }); + rulesSection = ranSection(result.diagnostics.map((d) => toDiagnosticRow(d, "gate"))); + if (errors.length > 0) { + log.error(`meta verify — rules: ${errors.length} error(s).`); + return 1; + } + return 0; + } + // -- overlay authoring lint (FR-023 §11.1 item 4, Task 17) ------------------ // Its own section, its own cap — same discipline as the requirement lint // above: a noisy section must not push another section's findings off the @@ -2272,6 +2311,9 @@ function buildVerifyPayload(input: { names: AdvisorySection; deprecations: AdvisorySection; fields: AdvisorySection; + /** The business-rules gate (ADR-0066), only when the model declares operations or transitions. */ + rules?: AdvisorySection; + rulesCounts?: RulesSummary; /** What the schema gate found, when it compared anything. */ schemaDrift?: SchemaDriftSection; /** Gates that could not run at all (an unreachable database) — failures, not drift. */ @@ -2311,6 +2353,10 @@ function buildVerifyPayload(input: { if (input.fields.status === "ran" && input.fields.total > 0) { parts.push(`${input.fields.total} field authoring finding(s)`); } + const rulesTotal = input.rules?.total ?? 0; + if (rulesTotal > 0) { + parts.push(`${rulesTotal} rules finding(s)`); + } const help: string[] = errors.map((e) => `the ${e.gate} gate could not run, which is not drift: ${e.error} — fix the connection and re-run`); @@ -2347,8 +2393,14 @@ function buildVerifyPayload(input: { `${input.fields.total} field authoring finding(s) — see fields.rows[]; each names a reference identity listing a field its object lacks, or a field name declared twice in one children list`, ); } + if (rulesTotal > 0) { + help.push( + `${rulesTotal} business-rules finding(s) — see rules.rows[]; each names a lifecycle state or transition nothing can reach, a lifecycle that cannot move, or a permission name the model derived instead of declaring`, + ); + } if ( failed.length === 0 && + rulesTotal === 0 && input.antiPatterns.total === 0 && input.requirements.total === 0 && input.overlays.total === 0 && @@ -2371,6 +2423,8 @@ function buildVerifyPayload(input: { names: input.names, deprecations: input.deprecations, fields: input.fields, + ...(input.rules !== undefined ? { rules: input.rules } : {}), + ...(input.rulesCounts !== undefined ? { rulesCounts: input.rulesCounts } : {}), ...(input.requirementCounts !== undefined ? { requirementCounts: input.requirementCounts } : {}), ...(input.requirementLedger !== undefined ? { requirementLedger: input.requirementLedger } : {}), ...(input.schemaDrift !== undefined ? { schemaDrift: input.schemaDrift } : {}), diff --git a/server/typescript/packages/cli/src/lib/rules-check.ts b/server/typescript/packages/cli/src/lib/rules-check.ts new file mode 100644 index 0000000000..e039aea352 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/rules-check.ts @@ -0,0 +1,318 @@ +// `meta verify` — the business-rules gate (ADR-0066). +// +// The loader refuses a model whose operations or lifecycles are malformed. This gate reports +// what loads clean but is almost certainly not what the author meant: a state nothing can +// reach, a lifecycle that cannot move, a transition nothing can make, and (by setting) a +// permission name the model derived instead of declaring. +// +// TypeScript is the reference. Every port's `verify` implements these checks with the same +// codes, severities, paths and message text, and `fixtures/rules-check-conformance/` is the +// contract. A model that declares no operation and no transition gets no diagnostics, no +// summary and no gate row: opt-in by declaration, so an existing project sees no change. +// +// Checks, in the order they are reported: +// WARN_LIFECYCLE_UNREACHABLE_STATE states no transition reaches from the initial state +// (severity: `verify.lifecycle.unreachable`) +// WARN_LIFECYCLE_INITIAL_TERMINAL the initial state is one no transition leaves +// WARN_TRANSITION_UNREACHABLE a transition whose every @from state is unreachable +// (severity: `verify.lifecycle.unreachable`) +// WARN_TRANSITION_PERMISSION_SHADOWED a transition declaring @permission or @public: true that +// derives no command of its own, so the attribute is never +// read (always a warning) +// WARN_PERMISSION_DERIVED_NAME a transition that derives its own command, or an +// operation, with no @permission and not @public +// (severity: `rules.permissions.names`) +// +// Lifecycles are checked once per declaring field, so a lifecycle on an abstract base is +// reported once, not once per inheritor. A derived command exists per concrete entity that has +// a source, so the permission checks run per such entity and name it; a lifecycle on an entity +// with no source is inert and derives no command (lifecycleIsLive). +// +// A derived permission name includes its owner: `..` for a +// transition's derived command, `.` for a declared operation (the loader +// keeps operation names unique per package). +// +// A command claims a transition NODE for its target entity and every entity that extends the +// target: a command acting on an abstract base claims the inherited transition of each child. + +import { + TYPE_API, + TYPE_OBJECT, + TYPE_OPERATION, + OBJECT_SUBTYPE_ENTITY, + OPERATION_ATTR_PERMISSION, + OPERATION_ATTR_PUBLIC, + OPERATION_ATTR_TRANSITIONS, + OPERATION_SUBTYPE_COMMAND, + PACKAGE_SEPARATOR, + effectivePackageOf, + entityLineage, + entityTransitions, + lifecycleIsLive, + lifecyclesOf, + operationTarget, + reachableStates, + terminalStates, + topLevelNodeOf, + transitionFrom, + type Lifecycle, + type MetaData, + type RulesSettings, +} from "@metaobjectsdev/metadata"; +import type { Diagnostic, Severity } from "./requirement-check.js"; + +export const WARN_LIFECYCLE_UNREACHABLE_STATE = "WARN_LIFECYCLE_UNREACHABLE_STATE"; +export const WARN_LIFECYCLE_INITIAL_TERMINAL = "WARN_LIFECYCLE_INITIAL_TERMINAL"; +export const WARN_TRANSITION_UNREACHABLE = "WARN_TRANSITION_UNREACHABLE"; +export const WARN_PERMISSION_DERIVED_NAME = "WARN_PERMISSION_DERIVED_NAME"; +export const WARN_TRANSITION_PERMISSION_SHADOWED = "WARN_TRANSITION_PERMISSION_SHADOWED"; + +/** What the model declares, for the line `meta verify` prints on every run. */ +export interface RulesSummary { + /** Declared operations, across every `api.operational`. */ + readonly operations: number; + /** Lifecycles: enum fields that declare at least one transition. */ + readonly lifecycles: number; + /** Declared transitions, across every lifecycle. */ + readonly transitions: number; +} + +export interface RulesCheckResult { + readonly diagnostics: Diagnostic[]; + /** Undefined when the model declares no operation and no transition. */ + readonly summary: RulesSummary | undefined; +} + +function quoteList(xs: readonly string[]): string { + return xs.map((x) => `"${x}"`).join(", "); +} + +/** A node's package-qualified address: `acme::shop::Order.status.submit`. */ +export function rulesAddress(node: MetaData): string { + const parts: string[] = []; + for (let n: MetaData | undefined = node; n !== undefined && n.parent !== undefined; n = n.parent) { + if (n.name !== "") parts.unshift(n.name); + } + const pkg = effectivePackageOf(topLevelNodeOf(node)); + return pkg === "" ? parts.join(".") : `${pkg}${PACKAGE_SEPARATOR}${parts.join(".")}`; +} + +/** The permission name a node gets when it declares none, `.`: the path is + * `` for a declared operation and `.` for a transition's derived + * command, so two entities' transitions of one name ask about different permissions. */ +function derivedPermissionName(owner: MetaData, path: string): string { + const pkg = effectivePackageOf(topLevelNodeOf(owner)); + return pkg === "" ? path : `${pkg}.${path}`; +} + +function needsPermissionName(node: MetaData): boolean { + return node.attr(OPERATION_ATTR_PERMISSION) === undefined && node.attr(OPERATION_ATTR_PUBLIC) !== true; +} + +function entities(root: MetaData): MetaData[] { + return root.children().filter((c) => c.type === TYPE_OBJECT && c.subType === OBJECT_SUBTYPE_ENTITY); +} + +function operations(root: MetaData): MetaData[] { + return root.children() + .filter((c) => c.type === TYPE_API) + .flatMap((api) => api.children().filter((c) => c.type === TYPE_OPERATION)); +} + +/** Every lifecycle of the model, once per declaring field, in model order. */ +function declaredLifecycles(root: MetaData): Lifecycle[] { + const seen = new Set(); + const out: Lifecycle[] = []; + for (const entity of entities(root)) { + for (const l of lifecyclesOf(entity)) { + if (seen.has(l.field)) continue; + seen.add(l.field); + out.push(l); + } + } + return out; +} + +function checkLifecycle(l: Lifecycle, settings: RulesSettings, out: Diagnostic[]): void { + const where = rulesAddress(l.field); + const initial = l.initial; + if (initial === undefined) return; // the loader refused this model (ERR_LIFECYCLE_NO_INITIAL) + const reachable = reachableStates(l); + const unreachableSeverity: Severity | undefined = + settings.lifecycleUnreachable === "off" ? undefined : settings.lifecycleUnreachable; + + if (unreachableSeverity !== undefined) { + const unreachable = l.states.filter((s) => !reachable.has(s)); + if (unreachable.length > 0) { + out.push({ + severity: unreachableSeverity, + code: WARN_LIFECYCLE_UNREACHABLE_STATE, + path: where, + message: + `${unreachable.length === 1 ? "state" : "states"} ${quoteList(unreachable)} of "${l.field.name}" ` + + `cannot be reached from the initial state "${initial}" by any transition. ` + + `Add the transition that leads there, or set verify.lifecycle.unreachable if only seeded data uses ` + + `${unreachable.length === 1 ? "it" : "them"}.`, + }); + } + } + + if (terminalStates(l).includes(initial)) { + out.push({ + severity: "warn", + code: WARN_LIFECYCLE_INITIAL_TERMINAL, + path: where, + message: + `the initial state "${initial}" of "${l.field.name}" is terminal: no transition leaves it, ` + + `so no row of this lifecycle can ever move.`, + }); + } + + if (unreachableSeverity !== undefined) { + for (const t of l.transitions) { + const from = transitionFrom(t); + if (from.length === 0 || from.some((s) => reachable.has(s))) continue; + out.push({ + severity: unreachableSeverity, + code: WARN_TRANSITION_UNREACHABLE, + path: rulesAddress(t), + message: + `transition "${t.name}" starts only from ${quoteList(from)}, which no transition reaches from ` + + `the initial state "${initial}", so it can never be made.`, + }); + } + } +} + +/** One command's claim on a transition node, made for its target entity. */ +interface Claim { + readonly target: MetaData; + readonly op: MetaData; +} + +/** Each transition node the declared commands claim, with the claims on it in model order. */ +function claimedTransitions(root: MetaData): Map { + const claimed = new Map(); + for (const op of operations(root)) { + if (op.subType !== OPERATION_SUBTYPE_COMMAND) continue; + const target = operationTarget(op); + if (target === undefined) continue; + const raw = op.attr(OPERATION_ATTR_TRANSITIONS); + const names = new Set(Array.isArray(raw) ? raw.filter((x): x is string => typeof x === "string") : []); + for (const t of entityTransitions(target)) { + if (!names.has(t.name)) continue; + const claims = claimed.get(t) ?? []; + claims.push({ target, op }); + claimed.set(t, claims); + } + } + return claimed; +} + +/** The claims that cover transition `t` on `entity`: those made for the entity or an entity it extends. */ +function claimsOn(claimed: Map, entity: MetaData, t: MetaData): Claim[] { + const lineage = entityLineage(entity); + return (claimed.get(t) ?? []).filter((c) => lineage.includes(c.target)); +} + +/** Whether `t`, carried by `entity`, derives a command of its own under the setting. */ +function derivesCommand(claimed: Map, settings: RulesSettings, entity: MetaData, t: MetaData): boolean { + if (settings.lifecycleCommands === "none") return false; + if (settings.lifecycleCommands === "all") return true; + return claimsOn(claimed, entity, t).length === 0; +} + +/** The entities a transition can derive a command on: concrete, with a source. */ +function commandEntities(root: MetaData): MetaData[] { + return entities(root).filter((e) => !e.isAbstract && lifecycleIsLive(e)); +} + +/** A transition's @permission or @public is read only by the command derived from it. One that + * derives no command for any entity carrying it declares an attribute nothing reads. A transition + * carried only by entities with no source is inert, not shadowed: it is not reported. */ +function checkShadowedPermissions(root: MetaData, settings: RulesSettings, out: Diagnostic[]): void { + if (settings.lifecycleCommands === "all") return; + const claimed = claimedTransitions(root); + const carriers = new Map(); + for (const entity of commandEntities(root)) { + for (const t of entityTransitions(entity)) carriers.set(t, [...(carriers.get(t) ?? []), entity]); + } + for (const [t, entitiesWithT] of carriers) { + const permission = t.attr(OPERATION_ATTR_PERMISSION); + const isPublic = t.attr(OPERATION_ATTR_PUBLIC) === true; + if (permission === undefined && !isPublic) continue; + if (entitiesWithT.some((e) => derivesCommand(claimed, settings, e, t))) continue; + const declared = permission !== undefined ? `@permission "${String(permission)}"` : "@public: true"; + const claimers = [...new Set(entitiesWithT.flatMap((e) => claimsOn(claimed, e, t)) + .map((c) => `${c.op.parent?.name ?? ""}.${c.op.name}`))]; + const why = settings.lifecycleCommands === "none" + ? `rules.lifecycle.commands is "none": no command is derived from it` + : `it derives no command of its own: it is made only by ${quoteList(claimers)}, which ` + + `${claimers.length === 1 ? "asks" : "ask"} the policy about ${claimers.length === 1 ? "its" : "their"} own permission`; + out.push({ + severity: "warn", + code: WARN_TRANSITION_PERMISSION_SHADOWED, + path: rulesAddress(t), + message: + `transition "${t.name}" declares ${declared}, but ${why}, so the attribute is never read. ` + + `Remove it from the transition, or declare it on the command that makes the transition.`, + }); + } +} + +function checkPermissionNames(root: MetaData, settings: RulesSettings, out: Diagnostic[]): void { + if (settings.permissionNames === "derive") return; + const severity: Severity = settings.permissionNames === "require" ? "error" : "warn"; + const advice = (kind: string): string => + `which changes if the ${kind} is renamed. Declare @permission, or @public: true.`; + + if (settings.lifecycleCommands !== "none") { + const claimed = claimedTransitions(root); + for (const entity of commandEntities(root)) { + for (const t of entityTransitions(entity)) { + if (!derivesCommand(claimed, settings, entity, t)) continue; + if (!needsPermissionName(t)) continue; + out.push({ + severity, + code: WARN_PERMISSION_DERIVED_NAME, + path: `${rulesAddress(entity)}.${t.parent?.name ?? ""}.${t.name}`, + message: + `the command derived from transition "${t.name}" of "${entity.name}" has no @permission, so it asks ` + + `the policy about the derived name "${derivedPermissionName(entity, `${entity.name}.${t.name}`)}", ${advice("transition")}`, + }); + } + } + } + + for (const op of operations(root)) { + if (!needsPermissionName(op)) continue; + out.push({ + severity, + code: WARN_PERMISSION_DERIVED_NAME, + path: rulesAddress(op), + message: + `operation.${op.subType} "${op.name}" has no @permission, so it asks the policy about the derived ` + + `name "${derivedPermissionName(op, op.name)}", ${advice("operation")}`, + }); + } +} + +/** The rules gate over a loaded model. */ +export function checkRules(root: MetaData, settings: RulesSettings): RulesCheckResult { + const lifecycles = declaredLifecycles(root); + const ops = operations(root); + if (lifecycles.length === 0 && ops.length === 0) return { diagnostics: [], summary: undefined }; + + const diagnostics: Diagnostic[] = []; + for (const l of lifecycles) checkLifecycle(l, settings, diagnostics); + checkShadowedPermissions(root, settings, diagnostics); + checkPermissionNames(root, settings, diagnostics); + return { + diagnostics, + summary: { + operations: ops.length, + lifecycles: lifecycles.length, + transitions: lifecycles.reduce((n, l) => n + l.transitions.length, 0), + }, + }; +} diff --git a/server/typescript/packages/cli/test/rules-check-conformance.test.ts b/server/typescript/packages/cli/test/rules-check-conformance.test.ts new file mode 100644 index 0000000000..55adbf53a1 --- /dev/null +++ b/server/typescript/packages/cli/test/rules-check-conformance.test.ts @@ -0,0 +1,64 @@ +// Cross-port business-rules conformance corpus — fixtures/rules-check-conformance/ (ADR-0066). +// +// The rules gate is part of `meta verify` in every port; this corpus holds the other four to +// this one: the same inputs, the same diagnostics down to the message text, the same summary. +// Every case is LOADED strict first, then checked. `expected.json` is written from this +// implementation by `scripts/write-requirement-corpus-expected.ts rules` and reviewed by hand. +import { describe, test, expect } from "bun:test"; +import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { MetaDataLoader, rulesSettingsOf } from "@metaobjectsdev/metadata"; +import { ConfigSchema } from "@metaobjectsdev/sdk"; +import { checkRules, type RulesSummary } from "../src/lib/rules-check.js"; + +const CORPUS_DIR = join(import.meta.dir, "../../../../../fixtures/rules-check-conformance"); + +interface Finding { severity: string; code: string; path?: string; message: string } +interface Expected { diagnostics: Finding[]; summary: RulesSummary | null } + +type Row = readonly [severity: string, code: string, path: string, message: string]; +const row = (d: Finding): Row => [d.severity, d.code, d.path ?? "", d.message]; +const order = (a: Row, b: Row): number => { + for (let i = 0; i < a.length; i++) { + if (a[i]! < b[i]!) return -1; + if (a[i]! > b[i]!) return 1; + } + return 0; +}; +const multiset = (ds: readonly Finding[]): Row[] => ds.map(row).sort(order); + +/** `options.json` is the `rules` and `verify` config blocks, through the real config schema: + * a key it does not know, or a value outside its set, fails the case instead of being ignored. */ +function readSettings(caseDir: string) { + const file = join(caseDir, "options.json"); + const raw: unknown = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {}; + return rulesSettingsOf(ConfigSchema.pick({ rules: true, verify: true }).strict().parse(raw)); +} + +function documentedCases(): string[] { + const readme = readFileSync(join(CORPUS_DIR, "README.md"), "utf8"); + const section = readme.split(/^## /m).find((s) => s.startsWith("Cases\n")); + if (section === undefined) throw new Error("README.md has no '## Cases' section"); + return [...section.matchAll(/^\| `([^`]+)` \|/gm)].map((m) => m[1]!); +} + +const cases = readdirSync(CORPUS_DIR).filter((n) => statSync(join(CORPUS_DIR, n)).isDirectory()).sort(); + +describe("rules-check conformance corpus", () => { + test("every case on disk is documented in the README, and nothing else is", () => { + expect(cases.length).toBeGreaterThan(0); + expect(documentedCases().sort()).toEqual(cases); + }); + + for (const name of cases) { + test(name, async () => { + const caseDir = join(CORPUS_DIR, name); + const expected = JSON.parse(readFileSync(join(caseDir, "expected.json"), "utf8")) as Expected; + const result = await MetaDataLoader.fromDirectory(join(caseDir, "input"), { strict: true }); + expect(result.errors.map(String)).toEqual([]); + const { diagnostics, summary } = checkRules(result.root, readSettings(caseDir)); + expect(multiset(diagnostics)).toEqual(multiset(expected.diagnostics)); + expect(summary ?? null).toStrictEqual(expected.summary); + }); + } +}); diff --git a/server/typescript/packages/cli/test/unit/rules-inert.test.ts b/server/typescript/packages/cli/test/unit/rules-inert.test.ts new file mode 100644 index 0000000000..c72edbe1c2 --- /dev/null +++ b/server/typescript/packages/cli/test/unit/rules-inert.test.ts @@ -0,0 +1,156 @@ +// ADR-0066 — the business-rules vocabulary generates nothing yet. +// +// 1.3.0 registers `api.operational`, `operation.*`, `binding.rest` and `transition.action`, +// with their loader rules and `verify` checks. The generated services and enforcing shells +// that act on them are later work, so until they land every generator, every documentation +// page and `meta migrate` must produce byte-identical output for a model with the vocabulary +// and the same model without it. A generator that started reading an operation or a +// transition by accident would emit something half-built; this test is what notices. +// +// The model pair lives in fixtures/codegen-noop/rules/ and is shared with the other four +// ports' copies of this test. +// +// One generator is held to a different line: `docs-site`, the model explorer, lists every +// node of the model in its data payload, so it lists the new nodes too. Its other output is +// byte-identical, and the payload differs by exactly the `api`, `operation`, `binding` and +// `transition` nodes. + +import { describe, test, expect, beforeAll, afterAll } from "bun:test"; +import { copyFileSync, mkdirSync, mkdtempSync, rmSync, readFileSync, readdirSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative, resolve, sep } from "node:path"; +import { pathToFileURL } from "node:url"; +import { loadUris, TYPE_API, type MetaRoot } from "@metaobjectsdev/metadata"; +import { runGen, buildProjectionViews, type Generator, type MetaobjectsGenConfig } from "@metaobjectsdev/codegen-ts"; +import { buildExpectedSchema } from "@metaobjectsdev/migrate-ts"; +import { composeCatalog } from "../../src/lib/catalog.js"; + +// test/unit → cli → packages → typescript → server → repo root +const REPO_ROOT = resolve(import.meta.dir, "..", "..", "..", "..", "..", ".."); +const MODELS = join(REPO_ROOT, "fixtures", "codegen-noop", "rules"); +const GEN_STATE = ".gen-state"; + +// Both variants load from ONE path, and every run writes under ONE project root: the +// documentation pages print the source file and the project's directory name, and those must +// not be what differs. +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 { + mkdirSync(join(SCRATCH, "model"), { recursive: true }); + copyFileSync(join(MODELS, variant, "meta.purchasing.json"), MODEL_FILE); + const file = MODEL_FILE; + const result = await loadUris([pathToFileURL(file).href]); + if (result.errors.length > 0) { + throw new Error(`${file} did not load:\n${result.errors.map((e) => e.message).join("\n")}`); + } + return result.root; +} + +function walkFiles(root: string, dir = root): string[] { + const out: string[] = []; + for (const entry of readdirSync(dir)) { + const abs = join(dir, entry); + if (statSync(abs).isDirectory()) out.push(...walkFiles(root, abs)); + else out.push(relative(root, abs)); + } + return out.sort(); +} + +async function emit(metadata: MetaRoot, generators: Generator[]): Promise> { + const root = PROJECT; + rmSync(root, { recursive: true, force: true }); + mkdirSync(root, { recursive: true }); + const config: MetaobjectsGenConfig = { + outDir: "src/generated", + extStyle: "js", + dialect: "postgres", + dbImport: "../db", + targets: { docs: { outDir: "src/generated" } }, + generators, + }; + try { + await runGen({ config, metadata, projectRoot: root, genStateDir: join(root, GEN_STATE) }); + const files: Record = {}; + for (const rel of walkFiles(root)) { + if (rel.split(sep)[0] === GEN_STATE) continue; + files[rel] = readFileSync(join(root, rel), "utf8"); + } + return files; + } catch (e) { + return { "": e instanceof Error ? e.message : String(e) }; + } finally { + rmSync(root, { recursive: true, force: true }); + } +} + +const DOCS_SITE = "docs-site"; + +let withRules: MetaRoot; +let withoutRules: MetaRoot; + +beforeAll(async () => { + withRules = await load("with"); + withoutRules = await load("without"); +}); + +afterAll(() => rmSync(SCRATCH, { recursive: true, force: true })); + +describe("ADR-0066 the business-rules vocabulary is inert in every generator and in migrate", () => { + test("the with-model really carries the vocabulary (else every check below is vacuous)", () => { + expect(withRules.children().some((c) => c.type === TYPE_API)).toBe(true); + expect(withoutRules.children().some((c) => c.type === TYPE_API)).toBe(false); + }); + + 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(withoutRules, [entry.factory()]); + const actual = await emit(withRules, [entry.factory()]); + expect(actual).toEqual(expected); + }); + } + + test("docs-site differs by exactly the new nodes in its data payload", async () => { + const expected = await emit(withoutRules, [catalog[DOCS_SITE]!.factory()]); + const actual = await emit(withRules, [catalog[DOCS_SITE]!.factory()]); + expect(expected[""]).toBeUndefined(); + expect(Object.keys(actual).sort()).toEqual(Object.keys(expected).sort()); + const moved = Object.keys(expected).filter((p) => actual[p] !== expected[p]); + for (const path of moved) { + // Every line the page had is still there, in order; every added line belongs to a new node. + const before = expected[path]!.split("\n"); + const after = actual[path]!.split("\n"); + let kept = 0; + for (const line of after) if (line === before[kept]) kept++; + expect({ path, kept }).toEqual({ path, kept: before.length }); + } + const added = moved.flatMap((p) => actual[p]!.split("\n").filter((l) => !expected[p]!.split("\n").includes(l))); + expect(added.length).toBeGreaterThan(0); + const ids = added.filter((l) => l.includes(`"type": `)).map((l) => l.trim()); + expect([...new Set(ids)].sort()).toEqual( + [`"type": "api",`, `"type": "binding",`, `"type": "operation",`, `"type": "transition",`], + ); + }); + + test("every generator in one run emits the same files, byte for byte (docs-site aside)", async () => { + // shared-model needs a `files` selection `meta gen` supplies; prisma-schema refuses the + // model's view-backed projection, with and without the vocabulary alike. + const runnable = Object.entries(catalog) + .filter(([n]) => n !== "shared-model" && n !== "prisma-schema" && n !== DOCS_SITE) + .map(([, e]) => e.factory); + const expected = await emit(withoutRules, runnable.map((f) => f())); + const actual = await emit(withRules, runnable.map((f) => f())); + expect(expected[""]).toBeUndefined(); + expect(Object.keys(expected).length).toBeGreaterThan(10); + expect(actual).toEqual(expected); + }); + + test("migrate's expected schema is the same", () => { + const views = (m: MetaRoot) => buildProjectionViews(m, { dialect: "postgres" }); + expect(buildExpectedSchema(withRules, { dialect: "postgres", views: views(withRules) })) + .toEqual(buildExpectedSchema(withoutRules, { dialect: "postgres", views: views(withoutRules) })); + }); +}); diff --git a/server/typescript/packages/codegen-ts/src/shared-model/build-shared-model.ts b/server/typescript/packages/codegen-ts/src/shared-model/build-shared-model.ts index 3970674173..ae2e8f1497 100644 --- a/server/typescript/packages/codegen-ts/src/shared-model/build-shared-model.ts +++ b/server/typescript/packages/codegen-ts/src/shared-model/build-shared-model.ts @@ -44,6 +44,7 @@ import { compileScope, matchesScope, REF_BEARING_ATTR_NAMES, + isRefBearingAttr, resolveObjectRef, serializeSharedDocument, packageOfResolutionKey, @@ -186,6 +187,7 @@ function checkClosure( // one's, and is checked when the base itself is walked — reading it via the // resolving `attr()` here would attribute the base's reference to this node. for (const attrName of REF_BEARING_ATTR_NAMES) { + if (!isRefBearingAttr(node, attrName)) continue; const value = node.ownAttr(attrName); if (typeof value === "string") candidates.push(value); } diff --git a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts index 36184a6ace..babddf6ef7 100644 --- a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts +++ b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts @@ -266,9 +266,13 @@ describe("rc.21 part B view vocabulary — live Postgres", () => { // A local timestamp result on a zoned field: the cast would read it in the session's zone. const [zoned] = await findings({ "field.timestamp": fn({ name: "since" }, { "@function": "member_since", "@args": ["id"], "@params": ["long"], "@returns": "timestamp" }) }); expect(zoned).toMatch(/needs app\.member_since\(bigint\) → timestamp with time zone; the database has app\.member_since\(bigint\) → timestamp without time zone\.$/); - // A parameter of another type, and a function that does not exist. - const [param] = await findings({ "field.decimal": fn({ name: "limit" }, { "@function": "credit_limit", "@args": ["pin"], "@params": ["int"], "@returns": "decimal" }) }); - expect(param).toMatch(/needs app\.credit_limit\(integer\) → numeric; the database has app\.credit_limit\(bigint\) → numeric\.$/); + // An argument Postgres widens implicitly (integer onto a bigint parameter) is a call the + // database serves, so it is not a finding. + expect(await findings({ "field.decimal": fn({ name: "limit" }, { "@function": "credit_limit", "@args": ["pin"], "@params": ["int"], "@returns": "decimal" }) })).toEqual([]); + // A parameter of an unrelated type (no implicit widening reaches it), and a function that does not exist. + await sql.raw(`CREATE FUNCTION app.pin_label(text) RETURNS text LANGUAGE sql STABLE AS $$ SELECT 'pin-' || $1 $$`).execute(k); + const [param] = await findings({ "field.string": fn({ name: "pinLabel" }, { "@function": "pin_label", "@args": ["pin"], "@params": ["int"], "@returns": "string" }) }); + expect(param).toMatch(/needs app\.pin_label\(integer\) → text \| character varying \| character; the database has app\.pin_label\(text\) → text\.$/); // Fix round 3 (M1): a trailing defaulted parameter may be left out; fewer than the required ones is a finding. await sql.raw(`CREATE FUNCTION app.tier_label(bigint, as_of date DEFAULT current_date) RETURNS text LANGUAGE sql STABLE AS $$ SELECT 'tier-' || $1 || '@' || $2 $$`).execute(k); diff --git a/server/typescript/packages/metadata/src/constants.ts b/server/typescript/packages/metadata/src/constants.ts index ea53622836..8b019202c0 100644 --- a/server/typescript/packages/metadata/src/constants.ts +++ b/server/typescript/packages/metadata/src/constants.ts @@ -37,6 +37,7 @@ export * from "./shared/base-types.js"; export * from "./shared/structural.js"; +export * from "./core/api/api-constants.js"; export * from "./core/attr/attr-constants.js"; export * from "./core/documentation/doc-constants.js"; export * from "./core/field/field-constants.js"; @@ -45,6 +46,7 @@ export * from "./core/index/index-constants.js"; export * from "./core/object/object-constants.js"; export * from "./core/query/query-constants.js"; export * from "./core/relationship/relationship-constants.js"; +export * from "./core/transition/transition-constants.js"; export * from "./core/reporting/reporting-constants.js"; export * from "./core/validator/validator-constants.js"; export * from "./persistence/db/db-constants.js"; diff --git a/server/typescript/packages/metadata/src/core-types.ts b/server/typescript/packages/metadata/src/core-types.ts index 3f9290dbf3..39fe730d30 100644 --- a/server/typescript/packages/metadata/src/core-types.ts +++ b/server/typescript/packages/metadata/src/core-types.ts @@ -58,6 +58,10 @@ import { MetaIndex } from "./core/index/meta-index.js"; import { INDEX_DEFINITION } from "./core/index/index-definition.embedded.js"; import { INDEX_SUBTYPES } from "./core/index/index-constants.js"; import { MetaRequirement } from "./core/requirement/meta-requirement.js"; +import { MetaApi, MetaBinding, MetaOperation } from "./core/api/meta-api.js"; +import { API_DEFINITION } from "./core/api/api-definition.embedded.js"; +import { MetaTransition } from "./core/transition/meta-transition.js"; +import { TRANSITION_DEFINITION } from "./core/transition/transition-definition.embedded.js"; import { REQUIREMENT_DEFINITION } from "./core/requirement/requirement-definition.embedded.js"; import { REQUIREMENT_SUBTYPES } from "./core/requirement/requirement-constants.js"; import { MetaDimension } from "./core/reporting/meta-dimension.js"; @@ -87,6 +91,9 @@ import { TYPE_DIMENSION, TYPE_MEASURE, TYPE_SEGMENT, + TYPE_API, + TYPE_OPERATION, + TYPE_BINDING, SUBTYPE_ROOT, } from "./shared/base-types.js"; import { CHILD_RULE_WILDCARD } from "./shared/structural.js"; @@ -203,6 +210,8 @@ function registerCoreTypeDefs(registry: TypeRegistry): void { wildcard(TYPE_TEMPLATE), // Capability requirements are declared beside the entities they describe. wildcard(TYPE_REQUIREMENT), + // ADR-0030 / ADR-0066 — a declared API surface is a top-level, packaged node. + wildcard(TYPE_API), ], MetaRoot), ); @@ -551,6 +560,25 @@ function registerCoreTypeDefs(registry: TypeRegistry): void { registry.register(reportingDef); } + // ADR-0030 / ADR-0066 — the declared API surface (api / operation / binding) and + // lifecycle moves (transition, a child of field.enum). One class per type; the + // subtype carries no behaviour of its own. The cross-node rules live in + // loader/rules-validation.ts. + const RULES_FACTORIES: FactoryMap = {}; + for (const def of [...(API_DEFINITION.types ?? []), ...(TRANSITION_DEFINITION.types ?? [])]) { + const key = `${def.type}.${def.subType}`; + if (def.type === TYPE_API) RULES_FACTORIES[key] = (typeId: TypeId, name: string) => new MetaApi(typeId, name); + else if (def.type === TYPE_OPERATION) RULES_FACTORIES[key] = (typeId: TypeId, name: string) => new MetaOperation(typeId, name); + else if (def.type === TYPE_BINDING) RULES_FACTORIES[key] = (typeId: TypeId, name: string) => new MetaBinding(typeId, name); + else RULES_FACTORIES[key] = (typeId: TypeId, name: string) => new MetaTransition(typeId, name); + } + for (const rulesDef of [ + ...defineProviderFromData(API_DEFINITION, RULES_FACTORIES), + ...defineProviderFromData(TRANSITION_DEFINITION, RULES_FACTORIES), + ]) { + registry.register(rulesDef); + } + // Declare the core cross-references ON their TypeDefinitions, so the loader's // registry-derived validation resolves them generically (a dangling target fails the // load). Set on the concrete subtypes the parser produces. (Production moves these into diff --git a/server/typescript/packages/metadata/src/core/api/api-constants.ts b/server/typescript/packages/metadata/src/core/api/api-constants.ts new file mode 100644 index 0000000000..bc9eef468e --- /dev/null +++ b/server/typescript/packages/metadata/src/core/api/api-constants.ts @@ -0,0 +1,92 @@ +// Declared API surface constants (ADR-0030, ADR-0066) — type names, subtypes and +// attribute keys for `api.*`, `operation.*` and `binding.*`. +// +// The type-name constants live in shared/base-types.ts beside every other base type +// and are re-exported here so a consumer has one import site. + +import { TYPE_API, TYPE_BINDING, TYPE_OPERATION } from "../../shared/base-types.js"; + +export { TYPE_API, TYPE_BINDING, TYPE_OPERATION }; + +// --------------------------------------------------------------------------- +// Subtypes +// --------------------------------------------------------------------------- + +/** 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; +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; +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; +export type BindingSubType = (typeof BINDING_SUBTYPES)[number]; + +// --------------------------------------------------------------------------- +// Attrs on operation.* (and @permission / @public on transition.* too) +// --------------------------------------------------------------------------- + +/** FQN of the `object.value` an operation takes. */ +export const OPERATION_ATTR_INPUT_REF = "inputRef"; +/** FQN of the projection, entity or value an operation returns. */ +export const OPERATION_ATTR_OUTPUT_REF = "outputRef"; +/** The target entity, declared only when it cannot be derived. */ +export const OPERATION_ATTR_OBJECT_REF = "objectRef"; +/** The lifecycle moves a command may make (names of the target's transitions). */ +export const OPERATION_ATTR_TRANSITIONS = "transitions"; +/** The permission name the shell asks the policy about. */ +export const OPERATION_ATTR_PERMISSION = "permission"; +/** The shell calls no permission check. */ +export const OPERATION_ATTR_PUBLIC = "public"; +/** The business error codes a command body may return. */ +export const OPERATION_ATTR_ERRORS = "errors"; +/** A query returns a list. */ +export const OPERATION_ATTR_MANY = "many"; + +// --------------------------------------------------------------------------- +// Attrs on binding.rest +// --------------------------------------------------------------------------- + +export const BINDING_ATTR_METHOD = "method"; +export const BINDING_ATTR_PATH = "path"; +export const HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const; +export type HttpMethod = (typeof HTTP_METHODS)[number]; + +/** 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; + +/** A declared @permission: a dotted identifier path (`purchasing.approve`). A package prefix may + * use `::`, so a derived name (`acme::purchasing.PurchaseRequest.submit`) can be declared as + * it is. The name becomes a constant and a key into grant data, so it carries no spaces, + * punctuation or path segments. */ +export const PERMISSION_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*(?:(?:\.|::)[A-Za-z_][A-Za-z0-9_]*)*$/; + +/** A declared business error code: lower snake case. */ +export const BUSINESS_ERROR_CODE_PATTERN = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/; + +/** Wire error codes an operation's route answers on its own, so a body may not declare them + * in @errors (O5): the enforcing shell's codes (ADR-0066 §6) and the API contract's generic + * ones (docs/features/api-contract.md). A body returning one would be indistinguishable on the + * wire from the shell or the transport answering. */ +export const RESERVED_ERROR_CODES = [ + "not_found", + "forbidden", + "invalid_transition", + "transition_condition_failed", + "state_managed", + "validation", + "invalid_json", + "invalid_id", + "method_not_allowed", + "constraint_violation", + "internal", +] 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 new file mode 100644 index 0000000000..fff7337a4a --- /dev/null +++ b/server/typescript/packages/metadata/src/core/api/api-definition.embedded.ts @@ -0,0 +1,174 @@ +// AUTO-GENERATED by scripts/generate-embedded-metamodel.ts — DO NOT EDIT. +// Canonical source: repo-root spec/metamodel/api.json +// Regenerate: bun run scripts/generate-embedded-metamodel.ts +// +// Embeds the canonical FR-033 ProviderDefinition so the provider can register +// itself wherever the on-disk spec/ tree is unavailable (bundled builds). +import type { ProviderDefinition } from "../../provider-data.js"; + +export const API_DEFINITION: ProviderDefinition = { + "provider": "metaobjects-core-types", + "types": [ + { + "type": "api", + "subType": "base", + "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.", + "children": [] + }, + { + "type": "api", + "subType": "operational", + "extendsBase": true, + "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).", + "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": "base", + "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "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": "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", + "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." + } + ] + }, + { + "type": "operation", + "subType": "query", + "extendsBase": true, + "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": "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": "binding", + "subType": "base", + "description": "Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable.", + "children": [] + }, + { + "type": "binding", + "subType": "rest", + "extendsBase": true, + "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).", + "whenToUse": "An operation must keep a method or path the derived one would not give it, such as an existing public URL.", + "children": [ + { + "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)." + } + ] + } + ] +}; diff --git a/server/typescript/packages/metadata/src/core/api/meta-api.ts b/server/typescript/packages/metadata/src/core/api/meta-api.ts new file mode 100644 index 0000000000..6bc156ab9f --- /dev/null +++ b/server/typescript/packages/metadata/src/core/api/meta-api.ts @@ -0,0 +1,78 @@ +// Node classes for the declared API surface (ADR-0030, ADR-0066): `api.*`, +// `operation.*` and `binding.*`. Accessors are RESOLVING (ADR-0039), so an +// operation that `extends` another reads the inherited attributes. + +import { MetaData } from "../../shared/meta-data.js"; +import { TYPE_BINDING, TYPE_OPERATION } from "../../shared/base-types.js"; +import { + BINDING_ATTR_METHOD, + BINDING_ATTR_PATH, + OPERATION_ATTR_ERRORS, + OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_MANY, + OPERATION_ATTR_OBJECT_REF, + OPERATION_ATTR_OUTPUT_REF, + OPERATION_ATTR_PERMISSION, + OPERATION_ATTR_PUBLIC, + OPERATION_ATTR_TRANSITIONS, +} from "./api-constants.js"; + +function stringAttr(node: MetaData, name: string): string | undefined { + const v = node.attr(name); + return typeof v === "string" ? v : undefined; +} + +/** A bare string authored for an array attr is ONE element (the attr-schema rule). */ +function stringArrayAttr(node: MetaData, name: string): readonly string[] { + const v = node.attr(name); + if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string"); + return typeof v === "string" ? [v] : []; +} + +/** `api.operational` — a named surface whose children are operations. */ +export class MetaApi extends MetaData { + operations(): MetaOperation[] { + return this.childrenOfType(TYPE_OPERATION).filter((c): c is MetaOperation => c instanceof MetaOperation); + } +} + +/** `operation.command` / `operation.query`. */ +export class MetaOperation extends MetaData { + inputRef(): string | undefined { + return stringAttr(this, OPERATION_ATTR_INPUT_REF); + } + outputRef(): string | undefined { + return stringAttr(this, OPERATION_ATTR_OUTPUT_REF); + } + objectRef(): string | undefined { + return stringAttr(this, OPERATION_ATTR_OBJECT_REF); + } + transitions(): readonly string[] { + return stringArrayAttr(this, OPERATION_ATTR_TRANSITIONS); + } + errors(): readonly string[] { + return stringArrayAttr(this, OPERATION_ATTR_ERRORS); + } + permission(): string | undefined { + return stringAttr(this, OPERATION_ATTR_PERMISSION); + } + isPublic(): boolean { + return this.attr(OPERATION_ATTR_PUBLIC) === true; + } + isMany(): boolean { + return this.attr(OPERATION_ATTR_MANY) === true; + } + bindings(): MetaBinding[] { + return this.childrenOfType(TYPE_BINDING).filter((c): c is MetaBinding => c instanceof MetaBinding); + } +} + +/** `binding.rest`. */ +export class MetaBinding extends MetaData { + method(): string | undefined { + return stringAttr(this, BINDING_ATTR_METHOD); + } + path(): string | undefined { + return stringAttr(this, BINDING_ATTR_PATH); + } +} diff --git a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts index cc1f081144..0956a07787 100644 --- a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts @@ -268,6 +268,14 @@ export const FIELD_DEFINITION: ProviderDefinition = { "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ + { + "type": "transition", + "subType": "*", + "name": "*", + "min": 0, + "max": null, + "description": "Lifecycle moves between this enum's members (ADR-0066). An enum with at least one transition.action is a lifecycle: its states are @values, its initial state @default, its terminal states the members no transition leaves." + }, { "type": "attr", "subType": "string", diff --git a/server/typescript/packages/metadata/src/core/transition/lifecycle.ts b/server/typescript/packages/metadata/src/core/transition/lifecycle.ts new file mode 100644 index 0000000000..fec3a72398 --- /dev/null +++ b/server/typescript/packages/metadata/src/core/transition/lifecycle.ts @@ -0,0 +1,280 @@ +// Lifecycle and operation-target derivation (ADR-0066), shared by the loader's rules +// pass and `meta verify`'s rules gate. Everything here is DERIVED: a lifecycle, its +// states, its initial and terminal states and an operation's target entity have no +// vocabulary of their own. Every port implements these rules the same way. +// +// Reads are RESOLVING (ADR-0039): a transition declared on a base entity's field is a +// transition of every entity that extends it. It is NOT a transition of an entity whose field +// merely `extends` that field: a field extends another to share its values, and a history +// table of an order's status is not an order (lifecycleTransitionsOf). + +import type { MetaData } from "../../shared/meta-data.js"; +import { TYPE_FIELD, TYPE_IDENTITY, TYPE_OBJECT, TYPE_SOURCE, TYPE_TRANSITION } from "../../shared/base-types.js"; +import { CHILD_REF_SEPARATOR, PACKAGE_SEPARATOR } from "../../shared/structural.js"; +import { FIELD_ATTR_DEFAULT, FIELD_ATTR_VALUES, FIELD_SUBTYPE_ENUM } from "../field/field-constants.js"; +import { IDENTITY_ATTR_FIELDS, IDENTITY_SUBTYPE_PRIMARY } from "../identity/identity-constants.js"; +import { + OBJECT_SUBTYPE_ENTITY, + OBJECT_SUBTYPE_PROJECTION, + OBJECT_SUBTYPE_VALUE, +} from "../object/object-constants.js"; +import { effectivePackageOf, resolveObjectRef, topLevelNodeOf } from "../../naming-refs.js"; +import { OPERATION_ATTR_INPUT_REF, OPERATION_ATTR_MANY, OPERATION_ATTR_OBJECT_REF, OPERATION_ATTR_OUTPUT_REF, OPERATION_SUBTYPE_QUERY } from "../api/api-constants.js"; +import { TRANSITION_ATTR_FROM, TRANSITION_ATTR_TO, TRANSITION_SUBTYPE_ACTION } from "./transition-constants.js"; + +/** A string-array attr read resolving; a bare string is ONE element. */ +export function stringList(node: MetaData, attr: string): string[] { + const v = node.attr(attr); + if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string"); + return typeof v === "string" ? [v] : []; +} + +function stringValue(node: MetaData, attr: string): string | undefined { + const v = node.attr(attr); + return typeof v === "string" ? v : undefined; +} + +/** The `transition.action` children of a field, resolving. */ +export function transitionsOf(field: MetaData): MetaData[] { + return field.children().filter((c) => c.type === TYPE_TRANSITION && c.subType === TRANSITION_SUBTYPE_ACTION); +} + +/** An entity and every entity it extends, nearest first. */ +export function entityLineage(entity: MetaData): MetaData[] { + const out: MetaData[] = []; + for (let e: MetaData | undefined = entity; e !== undefined && !out.includes(e); e = e.superResolved) out.push(e); + return out; +} + +/** + * Whether an entity's lifecycles are live: it declares or inherits a source. A lifecycle on an + * entity with no source loads and is inert, like everything else on a sourceless entity (#248): + * it derives no command, and the writable-source check applies once a source is added + * (ADR-0066 §2). A library's core layer declares its lifecycles this way. + */ +export function lifecycleIsLive(entity: MetaData): boolean { + return entity.children().some((c) => c.type === TYPE_SOURCE); +} + +/** + * The transitions a field gives an entity: those declared on a field of the entity itself or of + * an entity it extends. A transition reached only through the field's own `extends` of another + * entity's field is not one (ADR-0066 §2). + */ +export function lifecycleTransitionsOf(entity: MetaData, field: MetaData): MetaData[] { + const lineage = entityLineage(entity); + return transitionsOf(field).filter((t) => { + const owner = t.parent?.parent; + return owner !== undefined && lineage.includes(owner); + }); +} + +/** One lifecycle of an entity: an enum field with at least one transition. */ +export interface Lifecycle { + readonly field: MetaData; + /** The enum's @values, in declaration order. */ + readonly states: readonly string[]; + /** The enum's @default; undefined only on a model the loader refused. */ + readonly initial: string | undefined; + readonly transitions: readonly MetaData[]; +} + +/** The lifecycles of an object, in effective field order. Only an `object.entity` has any. */ +export function lifecyclesOf(obj: MetaData): Lifecycle[] { + if (obj.type !== TYPE_OBJECT || obj.subType !== OBJECT_SUBTYPE_ENTITY) return []; + const out: Lifecycle[] = []; + for (const field of obj.children()) { + if (field.type !== TYPE_FIELD || field.subType !== FIELD_SUBTYPE_ENUM) continue; + const transitions = lifecycleTransitionsOf(obj, field); + if (transitions.length === 0) continue; + const initial = field.attr(FIELD_ATTR_DEFAULT); + out.push({ + field, + states: stringList(field, FIELD_ATTR_VALUES), + initial: typeof initial === "string" ? initial : undefined, + transitions, + }); + } + return out; +} + +/** Every transition of an entity, across all its lifecycles. */ +export function entityTransitions(obj: MetaData): MetaData[] { + return lifecyclesOf(obj).flatMap((l) => l.transitions); +} + +/** A transition's @from (resolving). */ +export function transitionFrom(t: MetaData): string[] { + return stringList(t, TRANSITION_ATTR_FROM); +} + +/** A transition's @to (resolving). */ +export function transitionTo(t: MetaData): string | undefined { + return stringValue(t, TRANSITION_ATTR_TO); +} + +/** The states reachable from the initial state, following every transition. */ +export function reachableStates(l: Lifecycle): Set { + const seen = new Set(); + if (l.initial === undefined) return seen; + const queue = [l.initial]; + seen.add(l.initial); + while (queue.length > 0) { + const s = queue.shift()!; + for (const t of l.transitions) { + const to = transitionTo(t); + if (to !== undefined && transitionFrom(t).includes(s) && !seen.has(to)) { + seen.add(to); + queue.push(to); + } + } + } + return seen; +} + +/** The members no transition leaves (a self-transition counts as leaving). */ +export function terminalStates(l: Lifecycle): string[] { + const leaving = new Set(l.transitions.flatMap((t) => transitionFrom(t))); + return l.states.filter((s) => !leaving.has(s)); +} + +/** The primary key field names of an entity: its effective `identity.primary` @fields. */ +export function primaryKeyFields(entity: MetaData): string[] { + const primary = entity.children().find((c) => c.type === TYPE_IDENTITY && c.subType === IDENTITY_SUBTYPE_PRIMARY); + return primary === undefined ? [] : stringList(primary, IDENTITY_ATTR_FIELDS); +} + +/** The package a node's references resolve in: its top-level node's effective package. */ +export function referrerPackageOf(node: MetaData): string { + return effectivePackageOf(topLevelNodeOf(node)); +} + +/** Resolve an object reference written on `node` (owner part only). */ +export function resolveObjectOn(node: MetaData, ref: string): MetaData | undefined { + return resolveObjectRef(node.root(), ownerOf(ref), referrerPackageOf(node)).node; +} + +/** The owner part of a reference: everything before the child dot of its last `::` segment. */ +function ownerOf(ref: string): string { + const lastSep = ref.lastIndexOf(PACKAGE_SEPARATOR); + const segStart = lastSep === -1 ? 0 : lastSep + PACKAGE_SEPARATOR.length; + const dot = ref.indexOf(CHILD_REF_SEPARATOR, segStart); + return dot === -1 ? ref : ref.slice(0, dot); +} + +/** + * The object a field's `extends` NAMES, and the member it names there. `id extends + * PurchaseRequest.id` names PurchaseRequest even when PurchaseRequest inherits `id` from + * an abstract base, which is where the resolved super node physically lives. + */ +function extendedMember(f: MetaData): { owner: MetaData; member: string } | undefined { + const ref = f.superRef; + const sup = f.superResolved; + if (ref === undefined || sup === undefined) return undefined; + const lastSep = ref.lastIndexOf(PACKAGE_SEPARATOR); + const segStart = lastSep === -1 ? 0 : lastSep + PACKAGE_SEPARATOR.length; + const dot = ref.indexOf(CHILD_REF_SEPARATOR, segStart); + if (dot > segStart) { + const named = resolveObjectRef(f.root(), ref.slice(0, dot), referrerPackageOf(f)).node; + if (named !== undefined) return { owner: named, member: sup.name }; + } + const parent = sup.parent; + return parent !== undefined && parent.type === TYPE_OBJECT ? { owner: parent, member: sup.name } : undefined; +} + +/** The entities whose whole primary key a value object borrows, once: every primary key field + * of the `object.entity` is extended by exactly one field of the value. A value that borrows + * part of a composite key, or one key field twice (`fromId` and `toId`), names no single row of + * that entity, so it borrows nothing from it. */ +function borrowedKeyEntities(value: MetaData): MetaData[] { + const counts = new Map>(); + for (const f of value.children()) { + if (f.type !== TYPE_FIELD) continue; + const ext = extendedMember(f); + if (ext === undefined || ext.owner.subType !== OBJECT_SUBTYPE_ENTITY) continue; + if (!primaryKeyFields(ext.owner).includes(ext.member)) continue; + const members = counts.get(ext.owner) ?? new Map(); + members.set(ext.member, (members.get(ext.member) ?? 0) + 1); + counts.set(ext.owner, members); + } + return [...counts] + .filter(([owner, members]) => primaryKeyFields(owner).every((k) => members.get(k) === 1)) + .map(([owner]) => owner); +} + +/** The base entity of a projection: the entity its extended identity names, else the one + * entity its extended fields name. Undefined when there is none or more than one. */ +export function projectionBaseEntity(projection: MetaData): MetaData | undefined { + for (const id of projection.children()) { + if (id.type !== TYPE_IDENTITY) continue; + const ext = extendedMember(id); + if (ext !== undefined && ext.owner.subType === OBJECT_SUBTYPE_ENTITY) return ext.owner; + } + const owners: MetaData[] = []; + for (const f of projection.children()) { + if (f.type !== TYPE_FIELD) continue; + const ext = extendedMember(f); + if (ext !== undefined && ext.owner.subType === OBJECT_SUBTYPE_ENTITY && !owners.includes(ext.owner)) owners.push(ext.owner); + } + return owners.length === 1 ? owners[0] : undefined; +} + +/** How an operation's target was derived. `key` means the input borrows the target's key. */ +export interface DerivedTarget { + readonly entity: MetaData; + readonly via: "input" | "output"; +} + +/** + * The target entity derived from an operation's shapes, or undefined: + * 1. the one entity whose whole primary key the `@inputRef` value borrows (by `extends`), + * each key field once; + * 2. else the `@outputRef`: an entity is its own target, a projection its base entity. + * Whole keys of two entities, part of a key, or one key field borrowed twice derive nothing + * from the input. + */ +export function deriveOperationTarget(op: MetaData): DerivedTarget | undefined { + const inputRef = stringValue(op, OPERATION_ATTR_INPUT_REF); + if (inputRef !== undefined) { + const input = resolveObjectOn(op, inputRef); + if (input !== undefined && input.subType === OBJECT_SUBTYPE_VALUE) { + const borrowed = borrowedKeyEntities(input); + if (borrowed.length === 1) return { entity: borrowed[0]!, via: "input" }; + } + } + const outputRef = stringValue(op, OPERATION_ATTR_OUTPUT_REF); + if (outputRef !== undefined) { + const output = resolveObjectOn(op, outputRef); + if (output?.subType === OBJECT_SUBTYPE_ENTITY) return { entity: output, via: "output" }; + if (output?.subType === OBJECT_SUBTYPE_PROJECTION) { + const base = projectionBaseEntity(output); + if (base !== undefined) return { entity: base, via: "output" }; + } + } + return undefined; +} + +/** The operation's target: the declared `@objectRef` when it names an entity, else the + * derived one. */ +export function operationTarget(op: MetaData): MetaData | undefined { + const declared = stringValue(op, OPERATION_ATTR_OBJECT_REF); + if (declared !== undefined) { + const node = resolveObjectOn(op, declared); + return node?.subType === OBJECT_SUBTYPE_ENTITY ? node : undefined; + } + return deriveOperationTarget(op)?.entity; +} + +/** + * Whether the operation addresses one row of its target by key, so its derived path is + * `//{key}/`: its input borrows the target's key, or it is a + * query with no input and no @many whose target comes from its output (a get by key). + */ +export function operationIsKeyed(op: MetaData): boolean { + const derived = deriveOperationTarget(op); + if (derived === undefined) return false; + if (derived.via === "input") return true; + return op.subType === OPERATION_SUBTYPE_QUERY && + stringValue(op, OPERATION_ATTR_INPUT_REF) === undefined && + op.attr(OPERATION_ATTR_MANY) !== true; +} diff --git a/server/typescript/packages/metadata/src/core/transition/meta-transition.ts b/server/typescript/packages/metadata/src/core/transition/meta-transition.ts new file mode 100644 index 0000000000..9f68d2e1c2 --- /dev/null +++ b/server/typescript/packages/metadata/src/core/transition/meta-transition.ts @@ -0,0 +1,35 @@ +// MetaTransition — node class for `transition.*` (ADR-0066). Accessors are +// RESOLVING (ADR-0039): a transition declared on a base entity's field applies, +// unchanged, to every entity that extends it. + +import { MetaData } from "../../shared/meta-data.js"; +import { + TRANSITION_ATTR_CONDITION, + TRANSITION_ATTR_FROM, + TRANSITION_ATTR_PERMISSION, + TRANSITION_ATTR_PUBLIC, + TRANSITION_ATTR_TO, +} from "./transition-constants.js"; + +export class MetaTransition extends MetaData { + /** The states this move may start from. A bare string is one element. */ + from(): readonly string[] { + const v = this.attr(TRANSITION_ATTR_FROM); + if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string"); + return typeof v === "string" ? [v] : []; + } + to(): string | undefined { + const v = this.attr(TRANSITION_ATTR_TO); + return typeof v === "string" ? v : undefined; + } + condition(): unknown { + return this.attr(TRANSITION_ATTR_CONDITION); + } + permission(): string | undefined { + const v = this.attr(TRANSITION_ATTR_PERMISSION); + return typeof v === "string" ? v : undefined; + } + isPublic(): boolean { + return this.attr(TRANSITION_ATTR_PUBLIC) === true; + } +} diff --git a/server/typescript/packages/metadata/src/core/transition/transition-constants.ts b/server/typescript/packages/metadata/src/core/transition/transition-constants.ts new file mode 100644 index 0000000000..a0989cfd1b --- /dev/null +++ b/server/typescript/packages/metadata/src/core/transition/transition-constants.ts @@ -0,0 +1,27 @@ +// Lifecycle constants (ADR-0066) — the `transition` type, its subtypes and attrs. +// +// A lifecycle has no vocabulary of its own: it is a `field.enum` with at least one +// `transition.action` child. Its states are the enum's @values, its initial state the +// enum's @default, its terminal states the members no transition leaves. + +import { TYPE_TRANSITION } from "../../shared/base-types.js"; + +export { TYPE_TRANSITION }; + +/** A move made by an operation. */ +export const TRANSITION_SUBTYPE_ACTION = "action"; +/** A move made by time. RESERVED, not registered (ADR-0066): a different generated + * shape (a sweep or a derived read, no operation, no permission point). */ +export const TRANSITION_SUBTYPE_TIMED_RESERVED = "timed"; +export const TRANSITION_SUBTYPES = [TRANSITION_SUBTYPE_ACTION] as const; +export type TransitionSubType = (typeof TRANSITION_SUBTYPES)[number]; + +/** The states a move may start from (members of the parent enum's @values). */ +export const TRANSITION_ATTR_FROM = "from"; +/** The state a move ends in. */ +export const TRANSITION_ATTR_TO = "to"; +/** A guard over the entity's own fields (the attr.expression grammar). */ +export const TRANSITION_ATTR_CONDITION = "condition"; +/** As on an operation. */ +export const TRANSITION_ATTR_PERMISSION = "permission"; +export const TRANSITION_ATTR_PUBLIC = "public"; diff --git a/server/typescript/packages/metadata/src/core/transition/transition-definition.embedded.ts b/server/typescript/packages/metadata/src/core/transition/transition-definition.embedded.ts new file mode 100644 index 0000000000..fd5c808453 --- /dev/null +++ b/server/typescript/packages/metadata/src/core/transition/transition-definition.embedded.ts @@ -0,0 +1,71 @@ +// AUTO-GENERATED by scripts/generate-embedded-metamodel.ts — DO NOT EDIT. +// Canonical source: repo-root spec/metamodel/transition.json +// Regenerate: bun run scripts/generate-embedded-metamodel.ts +// +// Embeds the canonical FR-033 ProviderDefinition so the provider can register +// itself wherever the on-disk spec/ tree is unavailable (bundled builds). +import type { ProviderDefinition } from "../../provider-data.js"; + +export const TRANSITION_DEFINITION: ProviderDefinition = { + "provider": "metaobjects-core-types", + "types": [ + { + "type": "transition", + "subType": "base", + "description": "Registry anchor for the attributes every lifecycle move shares (ADR-0054): not authorable.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "permission", + "min": 0, + "max": 1, + "description": "As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name `..`, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED)." + }, + { + "type": "attr", + "subType": "boolean", + "name": "public", + "min": 0, + "max": 1, + "description": "As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." + } + ] + }, + { + "type": "transition", + "subType": "action", + "extendsBase": true, + "description": "An allowed move between two values of a `field.enum`, made by an operation (ADR-0066). A `field.enum` with at least one is a lifecycle, named after the field. Its states are the enum's @values, its initial state the enum's @default, its terminal states the members no transition leaves; none of them has vocabulary of its own. Each transition is held to become a guarded update (`... WHERE id = ? AND IN (@from) [AND @condition]`), its own command when no declared operation claims it, its own permission point and its own wire error. No shell is generated yet: nothing is generated from this vocabulary, and the loader and `verify` only check it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A status field whose values may only change in certain ways: a request is submitted from draft, approved or rejected from submitted. Declare each allowed move here; once a shell is generated, the generic update path will no longer write the field. A move that leaves the state where it was (from submitted to submitted) records an action that changes nothing but still happened, such as a first approval of two.", + "rules": "Legal only under a `field.enum` of an `object.entity` (ERR_TRANSITION_NOT_ON_ENTITY). A concrete entity with a lifecycle and a source needs a writable one (ERR_TRANSITION_NOT_ON_ENTITY); on an entity with no source the lifecycle loads and is inert, deriving no command until a source is added. The field must declare @default (ERR_LIFECYCLE_NO_INITIAL). The field is not an array, and @from names at least one state (ERR_BAD_ATTR_VALUE). Names are unique across every lifecycle of the entity, compared without case, and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). A transition belongs to the entity that declares its field and to every entity extending it, never to an entity whose field merely `extends` that field; an inheritor that redeclares the field without extending it is ERR_LIFECYCLE_REDECLARED.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "from", + "isArray": true, + "min": 1, + "max": 1, + "description": "The states this move may start from: members of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise), at least one (ERR_BAD_ATTR_VALUE when empty). The allowed moves are the business rule itself, so they cannot be computed." + }, + { + "type": "attr", + "subType": "string", + "name": "to", + "min": 1, + "max": 1, + "description": "The state this move ends in: one member of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise). May equal a member of @from, which records an action that leaves the state where it was." + }, + { + "type": "attr", + "subType": "expression", + "name": "condition", + "min": 0, + "max": 1, + "description": "A guard over the entity's own fields, in the attr.expression grammar: the same name, grammar and meaning as on the cross-field validators. The shell will evaluate it against the loaded row and also put it into the guarded update's WHERE (no shell is generated yet). It cannot read the actor; that is the policy's job. A field the entity does not have, or an expression that is not boolean, is ERR_BAD_ATTR_VALUE." + } + ] + } + ] +}; diff --git a/server/typescript/packages/metadata/src/errors.ts b/server/typescript/packages/metadata/src/errors.ts index 0be9f19be7..5af954eb22 100644 --- a/server/typescript/packages/metadata/src/errors.ts +++ b/server/typescript/packages/metadata/src/errors.ts @@ -251,6 +251,35 @@ export const ERROR_CODES = [ // An object.report lists a measure that belongs to an entity other than @from; // v1 refuses multi-fact reports (R3). "ERR_REPORT_FOREIGN_MEASURE", + // ADR-0066 — business rules. A transition.action @from/@to value that is not a + // member of its enum (L4). + "ERR_TRANSITION_UNKNOWN_STATE", + // A transition.action on a field of anything but an object.entity, or a concrete + // entity with a lifecycle and a source but no writable one (L1, L2). A sourceless + // entity's lifecycle is inert, not an error. + "ERR_TRANSITION_NOT_ON_ENTITY", + // An enum field with transitions and no @default, its initial state (L3). + "ERR_LIFECYCLE_NO_INITIAL", + // An entity redeclares an inherited lifecycle field without extending it, dropping the + // base's transitions (L10). + "ERR_LIFECYCLE_REDECLARED", + // Two transitions of one entity share a name, two operations of one package share a + // name (unless one operation is declared identically in two APIs), or a transition or + // operation is named create / get / list / update / delete (L5, L6, O0, O6). + "ERR_TRANSITION_NAME_COLLISION", + // An operation's @objectRef is not an entity, or a command lists @transitions with no + // target (O2). + "ERR_OPERATION_TARGET_UNRESOLVED", + // A declared @objectRef disagrees with the derived target (O3). + "ERR_OPERATION_TARGET_MISMATCH", + // A @transitions name that is not a transition of the operation's target (O4). + "ERR_OPERATION_UNKNOWN_TRANSITION", + // @inputRef is not an object.value, or @outputRef is not an entity, projection or value (O1). + "ERR_OPERATION_SHAPE", + // @public: true together with @permission (P1). + "ERR_PERMISSION_PUBLIC_CONFLICT", + // A binding.rest @path whose placeholders are not the target's key fields (B1). + "ERR_BINDING_PATH_MISMATCH", // FR-039 — a requirement.* with @status: retired declares @implementedBy. Refused // rather than exempted: a retired capability has no implementation BY DEFINITION, // so forbidding the attribute makes the dangling-reference class unreachable diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 1fa511f1cf..9df5535b5f 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -48,6 +48,31 @@ export * from "./core/reporting/reporting-constants.js"; export { MetaDimension } from "./core/reporting/meta-dimension.js"; export { MetaMeasure } from "./core/reporting/meta-measure.js"; export { MetaSegment } from "./core/reporting/meta-segment.js"; +export * from "./core/api/api-constants.js"; +export { MetaApi, MetaOperation, MetaBinding } from "./core/api/meta-api.js"; +export * from "./core/transition/transition-constants.js"; +export { MetaTransition } from "./core/transition/meta-transition.js"; +// ADR-0066 — derived lifecycle and operation-target facts, shared by the loader, verify and +// (later) the generators, so no consumer re-derives them. +export { + lifecyclesOf, + entityLineage, + entityTransitions, + lifecycleTransitionsOf, + lifecycleIsLive, + transitionsOf, + transitionFrom, + transitionTo, + reachableStates, + terminalStates, + primaryKeyFields, + projectionBaseEntity, + deriveOperationTarget, + operationTarget, + operationIsKeyed, + type Lifecycle, + type DerivedTarget, +} from "./core/transition/lifecycle.js"; export { isDerivedExpr, derivedExprFields, type DerivedExprNode } from "./core/reporting/derived-expr.js"; export { reportFrom, @@ -327,6 +352,9 @@ export { didYouMeanHint, didYouMeanSuperHint, REF_BEARING_ATTR_NAMES, + isRefBearingAttr, + effectivePackageOf, + topLevelNodeOf, } from "./naming-refs.js"; export { resolveReferences } from "./loader/resolve-references.js"; @@ -430,6 +458,16 @@ export { } from "./wire.js"; export type { WireFormat, WireDecimals, WireNullMembers, WireDurations } from "./wire.js"; +// ADR-0066: the `rules` and `verify` blocks of .metaobjects/config.json. +export { + RULES_PERMISSION_NAMES, RULES_LIFECYCLE_CREATE, RULES_LIFECYCLE_COMMANDS, VERIFY_LIFECYCLE_UNREACHABLE, + DEFAULT_RULES_SETTINGS, rulesSettingsOf, +} from "./rules-settings.js"; +export type { + RulesSettings, RulesConfigBlocks, RulesPermissionNames, RulesLifecycleCreate, RulesLifecycleCommands, + VerifyLifecycleUnreachable, +} from "./rules-settings.js"; + // Retired vocabulary: the map the loader reads to explain a retirement, and the raw-document // rewriter `meta upgrade` drives from the SAME entries — so the error message and the fix // cannot drift apart. diff --git a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts index 654bacda73..f14f6b003d 100644 --- a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts +++ b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts @@ -28,6 +28,7 @@ import { parseJson } from "../parser-json.js"; import { validateDataGridSortFields, validateFilterableHasIndex, validateFilterableHasSupportedOps, validateSortableHasSupportedSubtype, validateOriginPaths, validateDerivedFieldProvidability, validateDataGridFilterValues, validateFieldObjectStorage, validateFieldMap, validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateDbCheck, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateProjectionUnionAndGrain, validateDerivedCycles, validateExtenderSubtypeScope, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; import { validateReporting } from "./reporting-validation.js"; +import { validateRules } from "./rules-validation.js"; import { runRegisteredValidation } from "./validation-registry.js"; import { validateSourceRoles } from "../persistence/source/validate-source-roles.js"; import { validateSourceEscapes } from "../persistence/source/validate-source-escapes.js"; @@ -674,6 +675,9 @@ export class MetaDataLoader { // segments, reports, relative-date filter values). errors.push(...validateReporting(root)); + // ADR-0066 — business rules: operations (slice A) and lifecycles (slice B). + errors.push(...validateRules(root)); + // FR-017 — M:N relationship validation (deferred-resolution): @through names a // junction declaring two identity.reference children; @sourceRefField matches one; // @symmetric is self-join-only + mutually exclusive with @sourceRefField; M:N attrs diff --git a/server/typescript/packages/metadata/src/loader/resolve-references.ts b/server/typescript/packages/metadata/src/loader/resolve-references.ts index ba18eea2b3..4b7ec7e21a 100644 --- a/server/typescript/packages/metadata/src/loader/resolve-references.ts +++ b/server/typescript/packages/metadata/src/loader/resolve-references.ts @@ -23,7 +23,7 @@ import { } from "../core/object/object-constants.js"; import { TYPE_OBJECT } from "../shared/base-types.js"; import { - REF_BEARING_ATTR_NAMES, + isRefBearingAttr, effectivePackageOf, resolveObjectRef, spellRef, @@ -134,7 +134,7 @@ export function resolveReferences(root: MetaData): void { // ADR-0039: own — this pass rewrites the declared-here layer; an inherited // attribute is resolved once, on the node that declares it. for (const attr of node.ownMetaAttrs()) { - if (REF_BEARING_ATTR_NAMES.has(attr.name)) resolveAttr(root, node, attr, declPkg); + if (isRefBearingAttr(node, attr.name)) resolveAttr(root, node, attr, declPkg); } } // ADR-0039: own — structural walk over the physical declaration tree. diff --git a/server/typescript/packages/metadata/src/loader/rules-validation.ts b/server/typescript/packages/metadata/src/loader/rules-validation.ts new file mode 100644 index 0000000000..e238446ebe --- /dev/null +++ b/server/typescript/packages/metadata/src/loader/rules-validation.ts @@ -0,0 +1,435 @@ +// ADR-0066 — cross-node rules for operations (slice A) and lifecycles (slice B). +// +// Every port implements the same rules WITH THE SAME MESSAGE TEXT; the fixtures under +// fixtures/conformance/ (`error-rules-*`, with the positive `rules-*` cases) are the +// contract. The rule ids below are the ones docs/features/business-rules.md lists. +// +// One broken rule yields one error: +// - Each error's source is the offending node: the transition, the enum field (L3), +// the entity (L2b), the operation or the binding. +// - An operation whose @inputRef / @outputRef fails O1 is not checked further; one +// whose target fails O2 or O3 is not checked for O4 or B1. +// - An error is reported once per (node, code), so a broken transition on an abstract +// base is reported once, not once per inheritor. +// +// 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). +// 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 +// L6 ERR_TRANSITION_NAME_COLLISION two transitions of one entity (across its lifecycles) share a +// name, compared without case +// L7 ERR_BAD_ATTR_VALUE @condition names a field the entity does not have, or is not boolean +// L8 ERR_BAD_ATTR_VALUE @from is empty +// L9 ERR_BAD_ATTR_VALUE a lifecycle field is an array (@isArray: true) +// L10 ERR_LIFECYCLE_REDECLARED an entity redeclares an inherited lifecycle field without +// extending it, so the base's transitions would be lost +// P1 ERR_PERMISSION_PUBLIC_CONFLICT @public: true with @permission (operation or transition) +// P2 ERR_BAD_ATTR_VALUE @permission is not a dotted identifier path (PERMISSION_NAME_PATTERN) +// O0 ERR_TRANSITION_NAME_COLLISION an operation named create/get/list/update/delete, in any case +// O6 ERR_TRANSITION_NAME_COLLISION two operations of one package share a name, compared without case, +// in one API or across its APIs (each derives the permission +// name .), unless they are the same +// operation: declared twice in one API (they merge), or +// declared identically in two APIs (sameOperation) +// O1 ERR_OPERATION_SHAPE @inputRef is not an object.value; @outputRef is not an entity, projection or value +// O2 ERR_OPERATION_TARGET_UNRESOLVED @objectRef is not an object.entity, or a command lists +// @transitions and no target is declared or derivable +// O3 ERR_OPERATION_TARGET_MISMATCH a declared @objectRef disagrees with the derived target +// O4 ERR_OPERATION_UNKNOWN_TRANSITION a @transitions name is not a transition of the target +// O5 ERR_BAD_ATTR_VALUE an @errors code is not lower snake case, is listed twice, or is +// one the route answers itself (RESERVED_ERROR_CODES) +// B1 ERR_BINDING_PATH_MISMATCH a binding.rest @path's placeholders are not the target's key fields +// (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 + +import type { MetaData } from "../shared/meta-data.js"; +import type { MetaObject } from "../core/object/meta-object.js"; +import { ParseError, type ErrorCode } from "../errors.js"; +import { + TYPE_API, + TYPE_BINDING, + TYPE_FIELD, + TYPE_OBJECT, + TYPE_OPERATION, + TYPE_SOURCE, + TYPE_TRANSITION, +} from "../shared/base-types.js"; +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 { + BINDING_ATTR_METHOD, + BINDING_ATTR_PATH, + BINDING_SUBTYPE_REST, + BUSINESS_ERROR_CODE_PATTERN, + PERMISSION_NAME_PATTERN, + OPERATION_ATTR_ERRORS, + OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_MANY, + OPERATION_ATTR_OBJECT_REF, + OPERATION_ATTR_OUTPUT_REF, + OPERATION_ATTR_PERMISSION, + OPERATION_ATTR_PUBLIC, + OPERATION_ATTR_TRANSITIONS, + OPERATION_SUBTYPE_COMMAND, + RESERVED_ERROR_CODES, + RESERVED_OPERATION_NAMES, +} from "../core/api/api-constants.js"; +import { TRANSITION_ATTR_CONDITION, TRANSITION_SUBTYPE_ACTION } from "../core/transition/transition-constants.js"; +import { + deriveOperationTarget, + entityLineage, + entityTransitions, + lifecycleIsLive, + lifecycleTransitionsOf, + operationIsKeyed, + primaryKeyFields, + resolveObjectOn, + stringList, + transitionFrom, + transitionTo, +} from "../core/transition/lifecycle.js"; +import { isWritableSource } from "../shared/node-guards.js"; +import { effectivePackageOf } from "../naming-refs.js"; +import { conditionMessage } from "./validation-passes.js"; + +const RESERVED = new Set(RESERVED_OPERATION_NAMES); +const RESERVED_LIST = RESERVED_OPERATION_NAMES.join(", "); +const RESERVED_CODES = new Set(RESERVED_ERROR_CODES); + +/** A derived name is compared without case: a command, a permission constant or a file named + * from it collides with another that differs only in case on a case-folding target. */ +function isReservedName(name: string): boolean { + return RESERVED.has(name.toLowerCase()); +} + +/** `"Entity.field.transition"` for a transition, `"Api.operation"` for an operation. */ +function label(node: MetaData): string { + const parts: string[] = []; + // A binding is unnamed: its label is its operation's. + for (let n: MetaData | undefined = node; n !== undefined && n.parent !== undefined; n = n.parent) { + if (n.name !== "") parts.unshift(n.name); + } + return parts.join("."); +} + +function quoteList(xs: readonly string[]): string { + return xs.map((x) => `"${x}"`).join(", "); +} + +class Sink { + readonly errors: ParseError[] = []; + private readonly seen = new Set(); + private readonly ids = new Map(); + add(node: MetaData, code: ErrorCode, message: string): void { + let id = this.ids.get(node); + if (id === undefined) { + id = this.ids.size; + this.ids.set(node, id); + } + const key = `${id}\u0000${code}`; + if (this.seen.has(key)) return; + this.seen.add(key); + this.errors.push(new ParseError(message, { code, source: node.source })); + } +} + +/** P1 and P2 for an operation or a transition. */ +function checkPermission(node: MetaData, sink: Sink): void { + const permission = node.attr(OPERATION_ATTR_PERMISSION); + if (node.attr(OPERATION_ATTR_PUBLIC) === true && permission !== undefined) { + sink.add(node, "ERR_PERMISSION_PUBLIC_CONFLICT", + `${node.type}.${node.subType} "${label(node)}" declares both @public: true and @permission; a public ${node.type} calls no permission check, so remove one.`); + } + if (typeof permission === "string" && !PERMISSION_NAME_PATTERN.test(permission)) { + sink.add(node, "ERR_BAD_ATTR_VALUE", + `${node.type}.${node.subType} "${label(node)}" @permission "${permission}" is not a dotted identifier path; use names of letters, digits and _ joined by "." (a package prefix may use "::"), such as "purchasing.approve".`); + } +} + +/** L1, L3, L4, L5, L7 and P1 for the transitions declared on one field. */ +function checkDeclaredTransitions(field: MetaData, sink: Sink): void { + // ADR-0039: own — each transition is checked where it is declared. + const declared = field.ownChildren().filter((c) => c.type === TYPE_TRANSITION && c.subType === TRANSITION_SUBTYPE_ACTION); + if (declared.length === 0) return; + const owner = field.parent; + if (owner === undefined || owner.type !== TYPE_OBJECT || owner.subType !== OBJECT_SUBTYPE_ENTITY) { + const where = owner === undefined || owner.type !== TYPE_OBJECT ? "the document root" : `object.${owner.subType} "${owner.name}"`; + for (const t of declared) { + sink.add(t, "ERR_TRANSITION_NOT_ON_ENTITY", + `transition.action "${label(t)}" is declared on a field of ${where}; a lifecycle belongs to an object.entity with a writable source.`); + } + return; + } + if (field.subType === FIELD_SUBTYPE_ENUM && typeof field.attr(FIELD_ATTR_DEFAULT) !== "string") { + sink.add(field, "ERR_LIFECYCLE_NO_INITIAL", + `field.enum "${label(field)}" declares transitions but no @default; its @default is the lifecycle's initial state.`); + } + if (field.resolvedIsArray()) { + sink.add(field, "ERR_BAD_ATTR_VALUE", + `field.${field.subType} "${label(field)}" declares transitions but is an array (@isArray: true); a lifecycle's state is one value.`); + } + const states = new Set(stringList(field, FIELD_ATTR_VALUES)); + for (const t of declared) { + checkPermission(t, sink); + if (transitionFrom(t).length === 0) { + sink.add(t, "ERR_BAD_ATTR_VALUE", + `transition.action "${label(t)}" @from is empty; name at least one state the transition leaves.`); + } + const to = transitionTo(t); + const unknown = [...new Set([...transitionFrom(t), ...(to === undefined ? [] : [to])])].filter((s) => !states.has(s)); + if (unknown.length > 0) { + sink.add(t, "ERR_TRANSITION_UNKNOWN_STATE", + `transition.action "${label(t)}" names ${quoteList(unknown)}, which ${unknown.length === 1 ? "is not a member" : "are not members"} of "${field.name}" @values (${quoteList([...states])}).`); + } + if (isReservedName(t.name)) { + sink.add(t, "ERR_TRANSITION_NAME_COLLISION", + `transition.action "${label(t)}" is named "${t.name}", which is a derived CRUD verb (${RESERVED_LIST}); rename it.`); + } + const condition = t.attr(TRANSITION_ATTR_CONDITION); + if (condition !== undefined) { + const message = conditionMessage(condition, owner as MetaObject, `transition.action "${label(t)}" @condition`); + if (message !== undefined) sink.add(t, "ERR_BAD_ATTR_VALUE", message); + } + } +} + +/** Every field declared in the tree: at the root and on every object. */ +function declaredFields(root: MetaData): MetaData[] { + const out: MetaData[] = []; + // ADR-0039: own — a structural walk over the declarations themselves. + for (const top of root.ownChildren()) { + if (top.type === TYPE_FIELD) out.push(top); + else if (top.type === TYPE_OBJECT) out.push(...top.ownChildren().filter((c) => c.type === TYPE_FIELD)); + } + return out; +} + +/** L10: an entity's field named like an ancestor's lifecycle field that does not carry that + * lifecycle's transitions. Redeclaring the field replaces it, so the base's state machine would + * silently stop applying to this entity. */ +function checkRedeclaredLifecycles(entity: MetaData, sink: Sink): void { + for (const ancestor of entityLineage(entity).slice(1)) { + // ADR-0039: own — the lifecycle fields the ancestor itself declares. + for (const baseField of ancestor.ownChildren()) { + if (baseField.type !== TYPE_FIELD) continue; + const baseTransitions = lifecycleTransitionsOf(ancestor, baseField); + if (baseTransitions.length === 0) continue; + const field = entity.children().find((c) => c.type === TYPE_FIELD && c.name === baseField.name); + if (field === undefined || field === baseField) continue; + const kept = new Set(lifecycleTransitionsOf(entity, field)); + if (baseTransitions.every((t) => kept.has(t))) continue; + sink.add(field, "ERR_LIFECYCLE_REDECLARED", + `field.${field.subType} "${label(field)}" redeclares "${label(baseField)}", which has a lifecycle, and drops its transitions; extend it ("extends": "${ancestor.name}.${baseField.name}") or give the field another name.`); + } + } +} + +/** L2, L6 and L10 for one entity, over its effective (inherited) lifecycles. */ +function checkEntityLifecycles(entity: MetaData, sink: Sink): void { + checkRedeclaredLifecycles(entity, sink); + const transitions = entityTransitions(entity); + if (transitions.length === 0) return; + const byName = new Map(); + for (const t of transitions) { + const key = t.name.toLowerCase(); + const first = byName.get(key); + if (first === undefined) { + byName.set(key, t); + } else if (first !== t) { + sink.add(t, "ERR_TRANSITION_NAME_COLLISION", + `transition.action "${label(t)}" has the same name as "${label(first)}" (names are compared without case); the transitions of "${entity.name}" share one namespace (each may derive a command), so rename one.`); + } + } + if (!entity.isAbstract && lifecycleIsLive(entity) && + !entity.children().some((c) => c.type === TYPE_SOURCE && isWritableSource(c))) { + sink.add(entity, "ERR_TRANSITION_NOT_ON_ENTITY", + `object.entity "${entity.name}" has a lifecycle (transitions on ${quoteList([...new Set(transitions.map((t) => t.parent?.name ?? ""))])}) 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.)`); + } +} + +/** O0-O5, P1 and B1 for one operation. */ +function checkOperation(op: MetaData, sink: Sink): void { + if (isReservedName(op.name)) { + sink.add(op, "ERR_TRANSITION_NAME_COLLISION", + `operation.${op.subType} "${label(op)}" is named "${op.name}", which is a derived CRUD verb (${RESERVED_LIST}); rename it.`); + } + checkPermission(op, sink); + + const errorCodes = stringList(op, OPERATION_ATTR_ERRORS); + const bad = errorCodes.filter((c) => !BUSINESS_ERROR_CODE_PATTERN.test(c)); + const dup = errorCodes.filter((c, i) => errorCodes.indexOf(c) !== i); + const reserved = [...new Set(errorCodes.filter((c) => RESERVED_CODES.has(c)))]; + if (bad.length > 0 || dup.length > 0 || reserved.length > 0) { + const why = bad.length > 0 + ? `${quoteList(bad)} ${bad.length === 1 ? "is not a" : "are not"} lower snake case code${bad.length === 1 ? "" : "s"}` + : dup.length > 0 + ? `${quoteList([...new Set(dup)])} ${new Set(dup).size === 1 ? "is" : "are"} listed twice` + : `${quoteList(reserved)} ${reserved.length === 1 ? "is a code" : "are codes"} the route answers itself (${RESERVED_ERROR_CODES.join(", ")})`; + 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; + } + } + + // O2, O3 — the target. + const derived = deriveOperationTarget(op)?.entity; + let target = derived; + const objectRef = op.attr(OPERATION_ATTR_OBJECT_REF); + if (typeof objectRef === "string") { + const declared = resolveObjectOn(op, objectRef); + if (declared === undefined || declared.subType !== OBJECT_SUBTYPE_ENTITY) { + sink.add(op, "ERR_OPERATION_TARGET_UNRESOLVED", + `operation.${op.subType} "${label(op)}" @objectRef "${objectRef}" ${declared === undefined ? "names no object" : `is an object.${declared.subType}`}; an operation acts on an object.entity.`); + return; + } + if (derived !== undefined && derived !== declared) { + sink.add(op, "ERR_OPERATION_TARGET_MISMATCH", + `operation.${op.subType} "${label(op)}" @objectRef names "${declared.name}", but its input and output derive "${derived.name}"; remove @objectRef or make them agree.`); + return; + } + target = declared; + } + const transitions = op.subType === OPERATION_SUBTYPE_COMMAND ? stringList(op, OPERATION_ATTR_TRANSITIONS) : []; + if (transitions.length > 0 && target === undefined) { + sink.add(op, "ERR_OPERATION_TARGET_UNRESOLVED", + `operation.command "${label(op)}" lists @transitions but has no target entity: the @inputRef does not borrow one entity's whole primary key (each key field extended exactly once), no @outputRef has a base entity, and there is no @objectRef.`); + return; + } + + // O4 — the transitions it may make. + if (target !== undefined && transitions.length > 0) { + const known = new Set(entityTransitions(target).map((t) => t.name)); + const unknown = [...new Set(transitions)].filter((n) => !known.has(n)); + if (unknown.length > 0) { + sink.add(op, "ERR_OPERATION_UNKNOWN_TRANSITION", + `operation.command "${label(op)}" @transitions names ${quoteList(unknown)}, which ${unknown.length === 1 ? "is not a transition" : "are not transitions"} of "${target.name}".`); + } + } + + // B1 — binding paths. + // 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_REST) continue; + const path = b.attr(BINDING_ATTR_PATH); + if (typeof path !== "string") continue; + const placeholders = [...path.matchAll(/\{([^}]*)\}/g)].map((m) => m[1] ?? ""); + const expected = target !== undefined && operationIsKeyed(op) ? primaryKeyFields(target) : []; + const same = placeholders.length === expected.length && + [...placeholders].sort().every((p, i) => p === [...expected].sort()[i]); + if (!same) { + sink.add(b, "ERR_BINDING_PATH_MISMATCH", + `binding.rest on "${label(b)}" @path "${path}" has placeholders [${quoteList(placeholders)}]; ` + + (expected.length === 0 + ? `"${label(op)}" addresses no row by key, so its path takes none.` + : `"${label(op)}" addresses one "${target!.name}" by key, so its path takes exactly [${quoteList(expected)}].`)); + } + } +} + +/** ADR-0066 — the rules pass. Runs after reference-bearing validation, before freeze. */ +export function validateRules(root: MetaData): ParseError[] { + const sink = new Sink(); + for (const field of declaredFields(root)) checkDeclaredTransitions(field, sink); + for (const obj of root.children()) { + if (obj.type === TYPE_OBJECT && obj.subType === OBJECT_SUBTYPE_ENTITY) checkEntityLifecycles(obj, sink); + } + // O6 — keyed by package, then by the name without case. + const byName = new Map(); + for (const api of root.children()) { + if (api.type !== TYPE_API) continue; + const ops = api.children().filter((c) => c.type === TYPE_OPERATION); + for (const op of ops) checkOperation(op, sink); + for (const op of ops) { + const pkg = effectivePackageOf(api); + const key = `${pkg}\u0000${op.name.toLowerCase()}`; + const first = byName.get(key); + if (first === undefined) byName.set(key, op); + else if (first !== op && !sameOperation(first, op)) { + sink.add(op, "ERR_TRANSITION_NAME_COLLISION", + `operation.${op.subType} "${label(op)}" has the same name as "${label(first)}" (names are compared without case) and is not the same operation; the operations of package "${pkg}" share one namespace (each derives the permission name .), so rename one, or declare both identically to expose one operation in two APIs.`); + } + } + checkApiRoutes(ops, sink); + } + return sink.errors; +} + +/** A reference attr's identity: the node it resolves to, else the raw value. */ +function refIdentity(op: MetaData, attr: string): unknown { + const ref = op.attr(attr); + return typeof ref === "string" ? resolveObjectOn(op, ref) ?? ref : ref; +} + +/** A list attr as a set, for comparison. */ +function setKey(op: MetaData, attr: string): string { + return [...new Set(stringList(op, attr))].sort().join("\u0000"); +} + +/** + * Whether two operations of one package in different APIs are one operation exposed twice, as a + * versioned API beside its successor does (ADR-0067 §2: one router per API, one service): the same + * name and subtype, and the same contract. The contract is every operation attribute: the + * referenced shapes (compared by the node they resolve to), the transitions and errors (as sets), + * the permission, public and many. Bindings are per API and are not compared. + */ +function sameOperation(a: MetaData, b: MetaData): boolean { + if (a.name !== b.name || a.subType !== b.subType) return false; + for (const attr of [OPERATION_ATTR_INPUT_REF, OPERATION_ATTR_OUTPUT_REF, OPERATION_ATTR_OBJECT_REF]) { + if (refIdentity(a, attr) !== refIdentity(b, attr)) return false; + } + for (const attr of [OPERATION_ATTR_TRANSITIONS, OPERATION_ATTR_ERRORS]) { + if (setKey(a, attr) !== setKey(b, attr)) return false; + } + return a.attr(OPERATION_ATTR_PERMISSION) === b.attr(OPERATION_ATTR_PERMISSION) && + (a.attr(OPERATION_ATTR_PUBLIC) === true) === (b.attr(OPERATION_ATTR_PUBLIC) === true) && + (a.attr(OPERATION_ATTR_MANY) === true) === (b.attr(OPERATION_ATTR_MANY) === true); +} + +/** B2 across the operations of one API. */ +function checkApiRoutes(ops: readonly MetaData[], sink: Sink): void { + const byRoute = new Map(); + for (const op of ops) { + // 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_REST) continue; + const path = b.attr(BINDING_ATTR_PATH); + if (typeof path !== "string") continue; + // The effective method: the declared one, else the derived (ADR-0066 §1). + const declaredMethod = b.attr(BINDING_ATTR_METHOD); + const method = typeof declaredMethod === "string" + ? declaredMethod + : op.subType === OPERATION_SUBTYPE_COMMAND ? "POST" : "GET"; + const route = `${method} ${path.replace(/\{[^}]*\}/g, "{}")}`; + const other = byRoute.get(route); + if (other === undefined) byRoute.set(route, b); + else { + sink.add(b, "ERR_BINDING_PATH_MISMATCH", + `binding.rest on "${label(b)}" declares ${method} "${path}", the same route as the binding on "${label(other)}"; two operations cannot share a method and path.`); + } + } + } +} diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index da1c2f06ac..4aeca05731 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -2430,6 +2430,23 @@ export function literalComparisonProblem( return undefined; } +/** + * Why a `@condition` (the attr.expression grammar) over `obj`'s own fields is refused, or + * undefined when it is legal. `label` opens the message. One rule for a cross-field + * validator's condition and a transition's guard (ADR-0066): every named field is a field of + * `obj`, and the expression passes `conditionProblem`. + */ +export function conditionMessage(condition: unknown, obj: MetaObject, label: string): string | undefined { + const fieldNames = new Set(obj.fields().map((f) => f.name)); + const unknown = [...new Set(expressionFieldRefs(condition))].filter((f) => !fieldNames.has(f)).sort(); + if (unknown.length > 0) { + return `${label} names ${unknown.map((f) => `"${f}"`).join(", ")}, ` + + `which ${unknown.length === 1 ? "is not a field" : "are not fields"} of "${obj.name}".`; + } + const problem = conditionProblem(condition, obj); + return problem === undefined ? undefined : `${label} ${problem}`; +} + export function validateCrossFieldValidators(root: MetaData, strict = false): ParseError[] { const errors: ParseError[] = []; for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT)) { diff --git a/server/typescript/packages/metadata/src/naming-refs.ts b/server/typescript/packages/metadata/src/naming-refs.ts index 87d4a083e0..a079fe2f5d 100644 --- a/server/typescript/packages/metadata/src/naming-refs.ts +++ b/server/typescript/packages/metadata/src/naming-refs.ts @@ -37,6 +37,8 @@ import { import { SOURCE_ATTR_PARAMETER_REF } from "./persistence/source/source-constants.js"; import { OBJECT_REPORT_ATTR_FROM, OBJECT_REPORT_ATTR_SPINE } from "./core/object/object-constants.js"; import { TEMPLATE_ATTR_PAYLOAD_REF, TEMPLATE_ATTR_RESPONSE_REF } from "./template/template-constants.js"; +import { OPERATION_ATTR_INPUT_REF, OPERATION_ATTR_OUTPUT_REF } from "./core/api/api-constants.js"; +import { TYPE_TRANSITION } from "./shared/base-types.js"; const PARENT_PREFIX = PACKAGE_PARENT + PACKAGE_SEPARATOR; // "..::" @@ -48,7 +50,9 @@ const PARENT_PREFIX = PACKAGE_PARENT + PACKAGE_SEPARATOR; // "..::" * relationship/field tail; `@parameterRef`/`@payloadRef`/`@responseRef` name * value-objects. The same set is used in every port. `@sourceRefField` (a FK FIELD * name) and `@implementedBy` (which may name a template as well as an object) are - * NOT in the set. + * NOT in the set. An operation's `@inputRef`/`@outputRef`/`@objectRef` are (ADR-0066). + * The set is keyed by NAME, so a node type that reuses one of these names for something + * else is excluded by `isRefBearingAttr`: a `transition.action @from` lists enum members. */ export const REF_BEARING_ATTR_NAMES: ReadonlySet = new Set([ RELATIONSHIP_ATTR_OBJECT_REF, // = FIELD_ATTR_OBJECT_REF (same spelling "objectRef") @@ -64,8 +68,16 @@ export const REF_BEARING_ATTR_NAMES: ReadonlySet = new Set([ TEMPLATE_ATTR_RESPONSE_REF, OBJECT_REPORT_ATTR_FROM, // = ORIGIN_PASSTHROUGH_ATTR_FROM ("from") OBJECT_REPORT_ATTR_SPINE, + OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_OUTPUT_REF, ]); +/** True when `attrName` on `node` holds an object reference: in REF_BEARING_ATTR_NAMES, + * and not on a `transition.*`, whose `@from` names members of its enum (ADR-0066). */ +export function isRefBearingAttr(node: MetaData, attrName: string): boolean { + return REF_BEARING_ATTR_NAMES.has(attrName) && node.type !== TYPE_TRANSITION; +} + /** True when `raw` is a relative reference form (`::Rest` or `..::Rest`). */ export function isRelativeRef(raw: string): boolean { return raw.startsWith(PACKAGE_SEPARATOR) || raw.startsWith(PARENT_PREFIX); diff --git a/server/typescript/packages/metadata/src/rules-settings.ts b/server/typescript/packages/metadata/src/rules-settings.ts new file mode 100644 index 0000000000..c6091e06f2 --- /dev/null +++ b/server/typescript/packages/metadata/src/rules-settings.ts @@ -0,0 +1,65 @@ +// ADR-0066 — the project settings the business-rules vocabulary reads, from the `rules` +// and `verify` blocks of `.metaobjects/config.json`. Every port reads the same keys with +// the same defaults. A key that is absent takes its default, which is always the +// behaviour a project had before the setting existed: no project declared an operation or +// a transition before 1.3.0, so every default here is the safe one. + +/** `rules.permissions.names`: how strongly `verify` asks for an explicit `@permission`. + * `derive` (default) says nothing, `advise` warns, `require` fails the build. */ +export const RULES_PERMISSION_NAMES = ["derive", "advise", "require"] as const; +export type RulesPermissionNames = (typeof RULES_PERMISSION_NAMES)[number]; + +/** `rules.lifecycle.create`: whether a create may start a row in any state (`any`) or only + * in the initial one (`initial`, default). No effect yet: validated and stored, and read by + * nothing until the enforcing shells land. */ +export const RULES_LIFECYCLE_CREATE = ["initial", "any"] as const; +export type RulesLifecycleCreate = (typeof RULES_LIFECYCLE_CREATE)[number]; + +/** `rules.lifecycle.commands`: which transitions derive a command of their own. + * `unclaimed` (default): those no declared command lists in `@transitions`. */ +export const RULES_LIFECYCLE_COMMANDS = ["unclaimed", "all", "none"] as const; +export type RulesLifecycleCommands = (typeof RULES_LIFECYCLE_COMMANDS)[number]; + +/** `verify.lifecycle.unreachable`: the severity of an unreachable state, and of a + * transition that starts only from unreachable states. `warn` (default), `error`, `off`. */ +export const VERIFY_LIFECYCLE_UNREACHABLE = ["warn", "error", "off"] as const; +export type VerifyLifecycleUnreachable = (typeof VERIFY_LIFECYCLE_UNREACHABLE)[number]; + +/** The resolved settings, every absent key at its default. */ +export interface RulesSettings { + readonly permissionNames: RulesPermissionNames; + readonly lifecycleCreate: RulesLifecycleCreate; + readonly lifecycleCommands: RulesLifecycleCommands; + readonly lifecycleUnreachable: VerifyLifecycleUnreachable; +} + +export const DEFAULT_RULES_SETTINGS: RulesSettings = { + permissionNames: "derive", + lifecycleCreate: "initial", + lifecycleCommands: "unclaimed", + lifecycleUnreachable: "warn", +}; + +/** The `rules` and `verify` config blocks as written; every key optional. */ +export interface RulesConfigBlocks { + readonly rules?: { + readonly permissions?: { readonly names?: RulesPermissionNames | undefined } | undefined; + readonly lifecycle?: { + readonly create?: RulesLifecycleCreate | undefined; + readonly commands?: RulesLifecycleCommands | undefined; + } | undefined; + } | undefined; + readonly verify?: { + readonly lifecycle?: { readonly unreachable?: VerifyLifecycleUnreachable | undefined } | undefined; + } | undefined; +} + +/** The settings a config declares, each absent key at its default. */ +export function rulesSettingsOf(cfg: RulesConfigBlocks): RulesSettings { + return { + permissionNames: cfg.rules?.permissions?.names ?? DEFAULT_RULES_SETTINGS.permissionNames, + lifecycleCreate: cfg.rules?.lifecycle?.create ?? DEFAULT_RULES_SETTINGS.lifecycleCreate, + lifecycleCommands: cfg.rules?.lifecycle?.commands ?? DEFAULT_RULES_SETTINGS.lifecycleCommands, + lifecycleUnreachable: cfg.verify?.lifecycle?.unreachable ?? DEFAULT_RULES_SETTINGS.lifecycleUnreachable, + }; +} diff --git a/server/typescript/packages/metadata/src/shared/base-types.ts b/server/typescript/packages/metadata/src/shared/base-types.ts index 89c53952f7..999789a608 100644 --- a/server/typescript/packages/metadata/src/shared/base-types.ts +++ b/server/typescript/packages/metadata/src/shared/base-types.ts @@ -28,6 +28,13 @@ export const TYPE_REQUIREMENT = "requirement"; export const TYPE_DIMENSION = "dimension"; export const TYPE_MEASURE = "measure"; export const TYPE_SEGMENT = "segment"; +/** ADR-0030 / ADR-0066 — the declared API surface: `api.operational` holds + * `operation.command` / `operation.query`, each optionally carrying a `binding.rest`. */ +export const TYPE_API = "api"; +export const TYPE_OPERATION = "operation"; +export const TYPE_BINDING = "binding"; +/** ADR-0066 — an allowed move between two members of a `field.enum` (`transition.action`). */ +export const TYPE_TRANSITION = "transition"; export const BASE_TYPES = [ TYPE_METADATA, @@ -47,6 +54,10 @@ export const BASE_TYPES = [ TYPE_DIMENSION, TYPE_MEASURE, TYPE_SEGMENT, + TYPE_API, + TYPE_OPERATION, + TYPE_BINDING, + TYPE_TRANSITION, ] as const; export type BaseType = (typeof BASE_TYPES)[number]; diff --git a/server/typescript/packages/metadata/test/index.test.ts b/server/typescript/packages/metadata/test/index.test.ts index a88f224458..5a4f71f0a3 100644 --- a/server/typescript/packages/metadata/test/index.test.ts +++ b/server/typescript/packages/metadata/test/index.test.ts @@ -313,7 +313,7 @@ describe("Public API surface — @metaobjectsdev/metadata index", () => { }); test("BASE_TYPES array is exported and correct length", () => { - expect(BASE_TYPES).toHaveLength(17); + expect(BASE_TYPES).toHaveLength(21); expect(BASE_TYPES).toContain(TYPE_OBJECT); expect(BASE_TYPES).toContain(TYPE_FIELD); expect(BASE_TYPES).toContain(TYPE_LAYOUT); diff --git a/server/typescript/packages/metadata/test/registry.test.ts b/server/typescript/packages/metadata/test/registry.test.ts index 321f4e7a68..07db65b519 100644 --- a/server/typescript/packages/metadata/test/registry.test.ts +++ b/server/typescript/packages/metadata/test/registry.test.ts @@ -17,6 +17,7 @@ import { TYPE_ORIGIN, TYPE_TEMPLATE, TYPE_REQUIREMENT, + TYPE_API, SUBTYPE_BASE, SUBTYPE_ROOT, FIELD_SUBTYPE_STRING, @@ -449,7 +450,7 @@ describe("registerCoreTypes", () => { expect(def!.childRules).toHaveLength(0); }); - it("metadata.root allows object, field, validator, template and requirement children (NOT a bare attr — strict model)", () => { + it("metadata.root allows object, field, validator, template, requirement and api children (NOT a bare attr — strict model)", () => { // FR-033 S1-simple: the attr wildcard is dropped from the document root; the // genuinely-open structural wildcards stay. `requirement` joined them when // the capability ledger became metadata (ruling amendment 3) — capability @@ -457,7 +458,7 @@ describe("registerCoreTypes", () => { const def = registry.find(TYPE_METADATA, SUBTYPE_ROOT); expect(def).toBeDefined(); const childTypes = def!.childRules.map((r) => r.childType).sort(); - expect(childTypes).toEqual([TYPE_FIELD, TYPE_OBJECT, TYPE_VALIDATOR, TYPE_TEMPLATE, TYPE_REQUIREMENT].sort()); + expect(childTypes).toEqual([TYPE_FIELD, TYPE_OBJECT, TYPE_VALIDATOR, TYPE_TEMPLATE, TYPE_REQUIREMENT, TYPE_API].sort()); }); // 6. attr.* has empty child rules diff --git a/server/typescript/packages/sdk/src/collection.ts b/server/typescript/packages/sdk/src/collection.ts index dc62673a84..a9095d890c 100644 --- a/server/typescript/packages/sdk/src/collection.ts +++ b/server/typescript/packages/sdk/src/collection.ts @@ -22,12 +22,14 @@ import { type PhysicalNaming, type WireFormat, DEFAULT_WIRE_FORMAT, + DEFAULT_RULES_SETTINGS, + type RulesSettings, type EnumDefaults, type ApiPagination, type UnknownFieldsMode, DEFAULT_ENUM_DEFAULTS, } from "@metaobjectsdev/metadata"; -import { apiPaginationFromConfig, apiUnknownFieldsFromConfig, CONFIG_FILE, enumDefaultsFromConfig, loadConfig, physicalNamingFromConfig, wireFormatFromConfig, type Config, type HandEditsPolicy } from "./config.js"; +import { apiPaginationFromConfig, apiUnknownFieldsFromConfig, CONFIG_FILE, enumDefaultsFromConfig, loadConfig, physicalNamingFromConfig, rulesSettingsFromConfig, wireFormatFromConfig, type Config, type HandEditsPolicy } from "./config.js"; import { discoverCollectionRoot, exists, isDir } from "./discovery.js"; import { compileScope, matchesScope, type Scope } from "./scope.js"; import { DEFAULT_METADATA_DIR, DEFAULT_METAOBJECTS_DIR, isMetadataFile } from "./metadata-files.js"; @@ -89,6 +91,8 @@ export interface Collection { readonly physicalNaming: PhysicalNaming; /** The `wire` block of the project config (ADR-0019 Amendment 2), default when absent. */ readonly wireFormat: WireFormat; + /** The `rules` and `verify` blocks of the project config (ADR-0066), each absent key at its default. */ + readonly rulesSettings: RulesSettings; /** The `enums` block of the project config (string-stored enum defaults), none when absent. * Optional so a hand-built Collection from before the block existed still type-checks. */ readonly enumDefaults?: EnumDefaults | undefined; @@ -305,6 +309,7 @@ export async function resolveCollection( let libraries: readonly string[] = []; let physicalNaming: PhysicalNaming = DEFAULT_PHYSICAL_NAMING; let wireFormat: WireFormat = DEFAULT_WIRE_FORMAT; + let rulesSettings: RulesSettings = DEFAULT_RULES_SETTINGS; let enumDefaults: EnumDefaults = DEFAULT_ENUM_DEFAULTS; let apiPagination: ApiPagination | undefined; let apiUnknownFields: UnknownFieldsMode | undefined; @@ -329,6 +334,7 @@ export async function resolveCollection( libraries = cfg.libraries; physicalNaming = physicalNamingFromConfig(cfg); wireFormat = wireFormatFromConfig(cfg); + rulesSettings = rulesSettingsFromConfig(cfg); enumDefaults = enumDefaultsFromConfig(cfg); apiPagination = apiPaginationFromConfig(cfg); apiUnknownFields = apiUnknownFieldsFromConfig(cfg); @@ -450,6 +456,7 @@ export async function resolveCollection( libraries, physicalNaming, wireFormat, + rulesSettings, enumDefaults, apiPagination, apiUnknownFields, diff --git a/server/typescript/packages/sdk/src/config.ts b/server/typescript/packages/sdk/src/config.ts index 72cedf7170..e038df3ad7 100644 --- a/server/typescript/packages/sdk/src/config.ts +++ b/server/typescript/packages/sdk/src/config.ts @@ -23,6 +23,12 @@ import { type WireFormat, type WireNullMembers, type PhysicalNaming, + RULES_PERMISSION_NAMES, + RULES_LIFECYCLE_CREATE, + RULES_LIFECYCLE_COMMANDS, + VERIFY_LIFECYCLE_UNREACHABLE, + rulesSettingsOf, + type RulesSettings, API_KEY_PAGINATION, PAGINATION_KEY_DEFAULT_LIMIT, PAGINATION_KEY_MAX_LIMIT, @@ -241,16 +247,21 @@ export const ConfigSchema = z.object({ * `notice` lists the file and exits 0 (`--forbid-hand-edits` tightens that for one run). * Absent means `notice`, what verify has always done; `meta init` writes `fail` for a new * project. Only the TypeScript `meta verify` reads it: the other ports' verify already fails - * on any edit to a generated file. + * on any edit to a generated file. `lifecycle.unreachable`: the severity of a lifecycle state + * no transition reaches from the initial state, and of a transition that starts only from + * such states — `warn` (default), `error` or `off` (ADR-0066); read by every port's config reader. */ verify: z .strictObject({ handEdits: z.enum(HAND_EDITS_POLICIES, { message: `"verify.handEdits" must be one of ${HAND_EDITS_POLICIES.map((v) => `"${v}"`).join(", ")}`, }).optional(), + lifecycle: z.strictObject({ + unreachable: z.enum(VERIFY_LIFECYCLE_UNREACHABLE).optional(), + }).optional(), }, { error: (iss) => iss.code === "unrecognized_keys" - ? `"verify" has an unknown key "${iss.keys[0]}" (expected "handEdits")` + ? `"verify" has an unknown key "${iss.keys[0]}" (expected "handEdits" or "lifecycle")` : iss.code === "invalid_type" ? `"verify" must be an object` : undefined, }) .optional(), @@ -381,6 +392,29 @@ export const ConfigSchema = z.object({ maxLength: z.number().int().positive().optional(), }) .optional(), + /** + * ADR-0066 — the business-rules settings. Read only for a model that declares an operation + * or a transition, and every absent key takes the behaviour such a model has without it. + * `permissions.names`: `derive` (default; verify says nothing), `advise` (verify warns on an + * operation or derived transition command with no explicit `@permission`, which asks about the + * derived name `.` or `..`) or `require` (it + * fails). `lifecycle.create`: `initial` (default; a create starts a row in the lifecycle's + * initial state) or `any`; it is validated and has no effect yet, since no service shell reads + * it. `lifecycle.commands`: which transitions derive a command of their + * own, `unclaimed` (default; those no command lists in `@transitions`), `all` or `none`. + * Read by every port's config reader. + */ + rules: z + .strictObject({ + permissions: z.strictObject({ + names: z.enum(RULES_PERMISSION_NAMES).optional(), + }).optional(), + lifecycle: z.strictObject({ + create: z.enum(RULES_LIFECYCLE_CREATE).optional(), + commands: z.enum(RULES_LIFECYCLE_COMMANDS).optional(), + }).optional(), + }) + .optional(), /** * C#-scoped settings. `outDir` is where `dotnet meta gen` writes and a bare `dotnet meta * verify` diffs, relative to the directory holding `.metaobjects/`; `namespace` is the C# @@ -439,6 +473,11 @@ export function wireFormatFromConfig(cfg: Pick): WireFormat { }; } +/** The business-rules settings a config declares, each absent key at its default (ADR-0066). */ +export function rulesSettingsFromConfig(cfg: Pick): RulesSettings { + return rulesSettingsOf(cfg); +} + export const DEFAULT_CONFIG: Config = ConfigSchema.parse({ schema_version: 1 }); /** `config.json`'s basename — the single owner. `discovery.ts` and diff --git a/server/typescript/packages/sdk/src/index.ts b/server/typescript/packages/sdk/src/index.ts index 220b301311..04859f3980 100644 --- a/server/typescript/packages/sdk/src/index.ts +++ b/server/typescript/packages/sdk/src/index.ts @@ -16,7 +16,7 @@ // shows `resolveCollection`, the documented single authority for locating a project. // Config -export { ConfigSchema, DEFAULT_CONFIG, loadConfig, setConfigWarningSink, splitUnknownTopLevelKeys, CONFIG_TOP_LEVEL_KEYS, saveConfig, AllowTokenEnum, physicalNamingFromConfig, wireFormatFromConfig, enumDefaultsFromConfig, apiPaginationFromConfig, apiUnknownFieldsFromConfig, HAND_EDITS_POLICIES, type HandEditsPolicy } from "./config.js"; +export { ConfigSchema, DEFAULT_CONFIG, loadConfig, setConfigWarningSink, splitUnknownTopLevelKeys, CONFIG_TOP_LEVEL_KEYS, saveConfig, AllowTokenEnum, physicalNamingFromConfig, wireFormatFromConfig, enumDefaultsFromConfig, rulesSettingsFromConfig, apiPaginationFromConfig, apiUnknownFieldsFromConfig, HAND_EDITS_POLICIES, type HandEditsPolicy } from "./config.js"; export type { Config } from "./config.js"; // Metadata dependencies (FR-023) — the `dependencies` config key's schema, diff --git a/server/typescript/packages/sdk/test/config.test.ts b/server/typescript/packages/sdk/test/config.test.ts index 07731524b3..6121d58471 100644 --- a/server/typescript/packages/sdk/test/config.test.ts +++ b/server/typescript/packages/sdk/test/config.test.ts @@ -2,7 +2,7 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { ConfigSchema, DEFAULT_CONFIG, apiPaginationFromConfig, apiUnknownFieldsFromConfig, loadConfig, saveConfig, setConfigWarningSink, type Config } from "../src/config.js"; +import { ConfigSchema, DEFAULT_CONFIG, apiPaginationFromConfig, apiUnknownFieldsFromConfig, loadConfig, rulesSettingsFromConfig, saveConfig, setConfigWarningSink, type Config } from "../src/config.js"; let metaRoot: string; beforeEach(() => { @@ -301,6 +301,38 @@ describe("csharp.providers (read by the C# port only)", () => { }); }); +describe("ConfigSchema — rules and verify blocks (ADR-0066)", () => { + test("absent keys take the defaults, which behave as before the blocks existed", () => { + expect(rulesSettingsFromConfig(ConfigSchema.parse({ schema_version: 1 }))).toEqual({ + permissionNames: "derive", lifecycleCreate: "initial", lifecycleCommands: "unclaimed", lifecycleUnreachable: "warn", + }); + }); + + test("every key is read", () => { + const cfg = ConfigSchema.parse({ + schema_version: 1, + rules: { permissions: { names: "require" }, lifecycle: { create: "any", commands: "none" } }, + verify: { handEdits: "fail", lifecycle: { unreachable: "error" } }, + }); + expect(rulesSettingsFromConfig(cfg)).toEqual({ + permissionNames: "require", lifecycleCreate: "any", lifecycleCommands: "none", lifecycleUnreachable: "error", + }); + }); + + test.each([ + [{ rules: { permission: { names: "advise" } } }], + [{ rules: { lifecycle: { initial: "any" } } }], + [{ rules: { permissions: { names: "strict" } } }], + [{ rules: { lifecycle: { commands: true } } }], + [{ rules: "advise" }], + [{ verify: { lifecycle: { unreachable: "fail" } } }], + [{ verify: { lifecycles: {} } }], + [{ verify: { handEdits: "warn" } }], + ])("a mistake is refused, not defaulted: %j", (extra) => { + expect(ConfigSchema.safeParse({ schema_version: 1, ...extra }).success).toBe(false); + }); +}); + describe("api.pagination (the generated list routes' page size)", () => { const parse = (api: unknown) => ConfigSchema.safeParse({ schema_version: 1, api }); const messages = (api: unknown) => { diff --git a/site-reference/index.html b/site-reference/index.html index e84f2d14c5..4bf2d5e830 100644 --- a/site-reference/index.html +++ b/site-reference/index.html @@ -61,6 +61,16 @@ +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 + + +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 + + attr.base Abstract base attribute — the polymorphic/unconstrained value-type marker. Stores its value type-preserved (never stringified), accepting any type; used for an untyped attr (e.g. a field's @default, whose value-type follows the owning field's subtype). Not authored directly: a attr.base node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. types/attr.md#attrbase @@ -116,6 +126,16 @@ types/attr.md#attrstring +binding.base +Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable. +types/binding.md#bindingbase + + +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). +types/binding.md#bindingrest + + dimension.attribute A named group-by attribute of the entity that declares it (FR-044). Groups report rows by a column value as-is. @of names Entity.field: the owning entity, or the @via terminal. @via may follow only to-one hops, so grouping by a related row's column can never multiply the measured rows. types/dimension.md#dimensionattribute @@ -296,6 +316,21 @@ types/object.md#objectvalue +operation.base +Registry anchor for the attributes every operation shares (ADR-0054): not authorable. +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 + + +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 + + origin.aggregate A value reduced from the related row-set reached along a relationship path (@via) from the base entity: count/sum/avg/min/max over a column (@of); any/all predicate quantifiers over a @filter; or collect (an array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted). types/origin.md#originaggregate @@ -391,6 +426,16 @@ types/template.md#templatetoolcall +transition.action +An allowed move between two values of a field.enum, made by an operation (ADR-0066). A field.enum with at least one is a lifecycle, named after the field. Its states are the enum's @values, its initial state the enum's @default, its terminal states the members no transition leaves; none of them has vocabulary of its own. Each transition is held to become a guarded update (... WHERE id = ? AND <field> IN (@from) [AND @condition]), its own command when no declared operation claims it, its own permission point and its own wire error. No shell is generated yet: nothing is generated from this vocabulary, and the loader and verify only check it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md). +types/transition.md#transitionaction + + +transition.base +Registry anchor for the attributes every lifecycle move shares (ADR-0054): not authorable. +types/transition.md#transitionbase + + validator.array Bounds the element count of an array-valued field via @min/@max. types/validator.md#validatorarray diff --git a/site-reference/types/api.html b/site-reference/types/api.html new file mode 100644 index 0000000000..5c973e7b66 --- /dev/null +++ b/site-reference/types/api.html @@ -0,0 +1,82 @@ + + + + + + Metamodel — `api` types | MetaObjects + + + + + + + + + + +
+

Metamodel reference

+

Metamodel — api types

+

Each section below is one api.<subType>. The Attributes table lists +the subtype's own + concern-contributed attributes (provider-tagged); universal +documentation attributes are omitted here (see providers.md). +Allowed children lists the structural child rules with their cardinality +(min..max, * = unbounded).

+

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.

+

Attributes

+

No subtype-specific attributes.

+

Allowed children

+

No structural children.

+

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).

+

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).

+

When to use: 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.

+

Attributes

+

No subtype-specific attributes.

+

Allowed children

+
    +
  • operation.* — 0..*
  • +
+ +
+
+ +
+ + diff --git a/site-reference/types/binding.html b/site-reference/types/binding.html new file mode 100644 index 0000000000..030f661324 --- /dev/null +++ b/site-reference/types/binding.html @@ -0,0 +1,109 @@ + + + + + + Metamodel — `binding` types | MetaObjects + + + + + + + + + + +
+

Metamodel reference

+

Metamodel — binding types

+

Each section below is one binding.<subType>. The Attributes table lists +the subtype's own + concern-contributed attributes (provider-tagged); universal +documentation attributes are omitted here (see providers.md). +Allowed children lists the structural child rules with their cardinality +(min..max, * = unbounded).

+

binding.base

+

Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable.

+

Attributes

+

No subtype-specific attributes.

+

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).

+

When to use: An operation must keep a method or path the derived one would not give it, such as an existing public URL.

+

Attributes

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeTypeRequiredDefaultAllowed valuesProviderDescription
@methodstringnoGET, POST, PUT, PATCH, DELETE—The HTTP method. Absent: GET for a query, POST for a command.
@pathstringno—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).
+

Allowed children

+

No structural children.

+ +
+
+ +
+ + diff --git a/site-reference/types/field.html b/site-reference/types/field.html index 676cac1f74..9d83682c7b 100644 --- a/site-reference/types/field.html +++ b/site-reference/types/field.html @@ -1384,6 +1384,7 @@

field.enum

Allowed children

  • origin.* — 0..*
  • +
  • transition.* — 0..*
  • validator.* — 0..*
  • view.* — 0..*
diff --git a/site-reference/types/metadata.html b/site-reference/types/metadata.html index 33e370f706..5dc0eaff1a 100644 --- a/site-reference/types/metadata.html +++ b/site-reference/types/metadata.html @@ -56,6 +56,7 @@

metadata.root

No subtype-specific attributes.

Allowed children

    +
  • api.* — 0..*
  • field.* — 0..*
  • object.* — 0..*
  • requirement.* — 0..*
  • diff --git a/site-reference/types/operation.html b/site-reference/types/operation.html new file mode 100644 index 0000000000..9434b5301b --- /dev/null +++ b/site-reference/types/operation.html @@ -0,0 +1,290 @@ + + + + + + Metamodel — `operation` types | MetaObjects + + + + + + + + + + +
    +

    Metamodel reference

    +

    Metamodel — operation types

    +

    Each section below is one operation.<subType>. The Attributes table lists +the subtype's own + concern-contributed attributes (provider-tagged); universal +documentation attributes are omitted here (see providers.md). +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.

    +

    Attributes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeTypeRequiredDefaultAllowed valuesProviderDescription
    @inputRefstringno—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.
    @objectRefstringno—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).
    @outputRefstringno—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.
    @permissionstringno—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.
    @publicbooleanno—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.
    +

    Allowed children

    +
      +
    • binding.* — 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).

    +

    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

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeTypeRequiredDefaultAllowed valuesProviderDescription
    @errorsstring[]no—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.
    @inputRefstringno—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.
    @objectRefstringno—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).
    @outputRefstringno—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.
    @permissionstringno—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.
    @publicbooleanno—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.
    @transitionsstring[]no—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..*
    • +
    +

    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).

    +

    When to use: A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.

    +

    Attributes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeTypeRequiredDefaultAllowed valuesProviderDescription
    @inputRefstringno—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.
    @manybooleanno—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.
    @objectRefstringno—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).
    @outputRefstringno—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.
    @permissionstringno—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.
    @publicbooleanno—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.
    +

    Allowed children

    +
      +
    • binding.* — 0..*
    • +
    + +
    +
    + +
    + + diff --git a/site-reference/types/transition.html b/site-reference/types/transition.html new file mode 100644 index 0000000000..bae0bb4f1d --- /dev/null +++ b/site-reference/types/transition.html @@ -0,0 +1,167 @@ + + + + + + Metamodel — `transition` types | MetaObjects + + + + + + + + + + +
    +

    Metamodel reference

    +

    Metamodel — transition types

    +

    Each section below is one transition.<subType>. The Attributes table lists +the subtype's own + concern-contributed attributes (provider-tagged); universal +documentation attributes are omitted here (see providers.md). +Allowed children lists the structural child rules with their cardinality +(min..max, * = unbounded).

    +

    transition.action

    +

    An allowed move between two values of a field.enum, made by an operation (ADR-0066). A field.enum with at least one is a lifecycle, named after the field. Its states are the enum's @values, its initial state the enum's @default, its terminal states the members no transition leaves; none of them has vocabulary of its own. Each transition is held to become a guarded update (... WHERE id = ? AND <field> IN (@from) [AND @condition]), its own command when no declared operation claims it, its own permission point and its own wire error. No shell is generated yet: nothing is generated from this vocabulary, and the loader and verify only check it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).

    +

    Rules: Legal only under a field.enum of an object.entity (ERR_TRANSITION_NOT_ON_ENTITY). A concrete entity with a lifecycle and a source needs a writable one (ERR_TRANSITION_NOT_ON_ENTITY); on an entity with no source the lifecycle loads and is inert, deriving no command until a source is added. The field must declare @default (ERR_LIFECYCLE_NO_INITIAL). The field is not an array, and @from names at least one state (ERR_BAD_ATTR_VALUE). Names are unique across every lifecycle of the entity, compared without case, and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). A transition belongs to the entity that declares its field and to every entity extending it, never to an entity whose field merely extends that field; an inheritor that redeclares the field without extending it is ERR_LIFECYCLE_REDECLARED.

    +

    When to use: A status field whose values may only change in certain ways: a request is submitted from draft, approved or rejected from submitted. Declare each allowed move here; once a shell is generated, the generic update path will no longer write the field. A move that leaves the state where it was (from submitted to submitted) records an action that changes nothing but still happened, such as a first approval of two.

    +

    Attributes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeTypeRequiredDefaultAllowed valuesProviderDescription
    @conditionexpressionno—A guard over the entity's own fields, in the attr.expression grammar: the same name, grammar and meaning as on the cross-field validators. The shell will evaluate it against the loaded row and also put it into the guarded update's WHERE (no shell is generated yet). It cannot read the actor; that is the policy's job. A field the entity does not have, or an expression that is not boolean, is ERR_BAD_ATTR_VALUE.
    @fromstring[]yes—The states this move may start from: members of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise), at least one (ERR_BAD_ATTR_VALUE when empty). The allowed moves are the business rule itself, so they cannot be computed.
    @permissionstringno—As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name <package>.<Entity>.<transition>, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED).
    @publicbooleanno—As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT.
    @tostringyes—The state this move ends in: one member of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise). May equal a member of @from, which records an action that leaves the state where it was.
    +

    Allowed children

    +

    No structural children.

    +

    transition.base

    +

    Registry anchor for the attributes every lifecycle move shares (ADR-0054): not authorable.

    +

    Attributes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeTypeRequiredDefaultAllowed valuesProviderDescription
    @permissionstringno—As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name <package>.<Entity>.<transition>, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED).
    @publicbooleanno—As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT.
    +

    Allowed children

    +

    No structural children.

    + +
    +
    + +
    + + diff --git a/spec/decisions/ADR-0045-generated-api-surface-owns-write-semantics.md b/spec/decisions/ADR-0045-generated-api-surface-owns-write-semantics.md index eecb583a61..21b41d4ff5 100644 --- a/spec/decisions/ADR-0045-generated-api-surface-owns-write-semantics.md +++ b/spec/decisions/ADR-0045-generated-api-surface-owns-write-semantics.md @@ -2,7 +2,7 @@ ## Status -**Accepted** (2026-07-23). Fixes the Kotlin + Python legs of `field.timestamp @autoSet` (issue #203 follow-up, #229): the shipped Kotlin generated Spring controller and Python generated FastAPI router did not stamp `@autoSet` timestamps, so an adopter deploying those artifacts silently lost a semantic the changelog says shipped in all five ports. Generalizes the FR-036 decision ("constraint validation must be enforced at the wire tier, not left decorative") from validation to *all* metamodel-guaranteed write semantics. +**Accepted** (2026-07-23). Fixes the Kotlin + Python legs of `field.timestamp @autoSet` (issue #203 follow-up, #229): the shipped Kotlin generated Spring controller and Python generated FastAPI router did not stamp `@autoSet` timestamps, so an adopter deploying those artifacts silently lost a semantic the changelog says shipped in all five ports. Generalizes the FR-036 decision ("constraint validation must be enforced at the wire tier, not left decorative") from validation to *all* metamodel-guaranteed write semantics. **Amended 2026-11-13 by ADR-0067** (Amendment 1 below): the guarantee may live in a generated service shell that the outermost artifact calls. ## Context @@ -40,3 +40,27 @@ The gap survived because **no `@autoSet` scenario existed in `api-contract-confo - **FR-036** (constraint validation must be enforced at the wire tier across all ports) is the same call for the sibling write semantic; `@autoSet` and constraint-validation even interlock (every port's insert schema already makes an `@autoSet @required` field optional-on-POST *because* the server fills it). - **ADR-0023** (strict provenance) is unaffected: no new vocabulary, purely where a generator enforces an existing attr. - Ships as a coordinated bug-fix change (Kotlin controller + Python router/model + the api-contract `@autoSet` gate), landed together so no lane reds — per the repo's "never commit a scenario ports can't pass" rule. + +## Amendment 1 (2026-11-13): a generated service shell may hold the guarantee + +ADR-0067 adds a `layered` generator set whose service layer enforces declared business rules +(ADR-0066). The transport of that set calls the service and holds no rules, so the decision +sentence above no longer describes it. It is replaced with: + +**The outermost generated write-path artifact an adopter deploys must guarantee every +metamodel-declared write semantic, either itself or by calling a generated service shell that +does. No consumer-supplied seam may sit between the guarantee and the wire. A hand-written +operation body is called by the shell, inside the guarantee, and is not such a seam.** + +The rest of the decision stands: + +- The API surface stamps (item 1) in every set that has no service layer, which is the + `classic` set. +- Persistence-layer stamping stays (item 2). +- Conformance gates the wire tier (item 3). + +The first rejected alternative ("rewire the Kotlin controller to delegate to the generated +repository") was rejected because routing every controller through a lower layer "would churn +all generated output". The `layered` set does not do that. It is opt-in per package, and a +project that does not choose it keeps today's output byte for byte. So the objection does not +apply to it. It still applies to rewiring the `classic` set, which this amendment does not do. diff --git a/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md b/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md new file mode 100644 index 0000000000..cc13aa84d5 --- /dev/null +++ b/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md @@ -0,0 +1,343 @@ +# ADR-0066: Business rules: operations, permission points and lifecycles + +## Status + +**Accepted** (2026-11-13). Both vocabulary slices are agreed under ADR-0023 §3: slice A +(operations and permission points) and slice B (lifecycles). This ADR registers the names +ADR-0030 reserved, adds `transition.*`, eleven loader error codes and a `verify` gate, in all five +ports in one change. `metamodelVersion` stays `1.3`, because this lands in the unpublished 1.3.0. +It extends ADR-0030 and applies ADR-0037's procedure to each shape. Every rule reads through the +resolving accessors (ADR-0039), so a transition declared on a base entity's field applies to +every entity that extends it. ADR-0067 decides where the rules are enforced, and amends +ADR-0045 to match. + +1.3.0 ships the vocabulary, the loader rules and the `verify` checks. The generated service +shells that enforce the rules at run time (§6) are later work. Until they land, the vocabulary +generates nothing. `fixtures/codegen-noop/rules/` holds every port to that. + +**Experimental.** Decision 2 of the 1.3.0 design pass gives new vocabulary an experimental label +until it is proven in use. Everything this ADR registers — `api.*`, `operation.*`, `binding.*`, +lifecycles and the permission points — with its loader rules, `verify` checks and settings, may +change in a MINOR, including removals and renames, as a `preview` library may +(`docs/compatibility-policy.md`). It is promoted on evidence: generated services running on it +in an adopter estate with the drift gate enforced. The registry descriptions say so. + +## Context + +The model has validation, `@autoSet`, cross-field validators with `@condition`, and +requirements. It has nothing for what an application *does*: + +- no named command beyond derived CRUD; +- no place to say who may run one; +- no allowed moves between the values of a status field. + +Audits of generated-and-extended applications found the result in every build: status changes +written as plain updates with no check of the current status, raw SQL with hand-typed names, +and permission checks that were scattered or missing. + +Three constraints carry over from earlier rulings: + +- **No logic in the model.** No sequencing, branching, loops, variables or user-defined + functions. An operation may be declared, guarded, checked and announced. What it does is code. +- **ADR-0030.** The `api` subtype axis is the interaction model, never the protocol. Queries + return projections, commands take values, both act on entities. +- **ADR-0023.** Every attribute below has a written reason why its value cannot be computed. + Anything that can be computed is derived and gets no vocabulary. The first sketch had several + such things as attributes, and they were removed: the initial state, the terminal states, the + target entity in the common case, the REST path, and the permission point itself. + +## Decision + +### 1. Slice A: operations and permission points + +| Node | Parent | Status | +|---|---|---| +| `api.base` | | abstract (ADR-0054: a registry anchor, not authorable) | +| `api.operational` | `metadata.root` | concrete. A named, packaged surface whose children are operations. | +| `operation.base` | | abstract | +| `operation.command` | `api.operational` | concrete. Changes state; takes an `object.value`. | +| `operation.query` | `api.operational` | concrete. Reads; returns a projection, entity or value. | +| `binding.base` | | abstract | +| `binding.rest` | `operation.*` | concrete, **optional**. Needed only to override the derived method and path. | + +Attributes on operations: + +| Attribute | On | Can it be computed? (ADR-0023) | +|---|---|---| +| `@inputRef` (an `object.value`) | both | No. The input is a value object the author chose. A query whose only parameter is the borrowed key needs none. | +| `@outputRef` (an entity, projection or value) | both | No. Which projection a query returns is the author's choice among several over one entity. | +| `@many` (boolean) | query | No. Whether a query returns a list, and so takes the filter, sort and paging contract, is not implied by the projection. Registered on `operation.query` only, so on a command it is `ERR_UNKNOWN_ATTR`. | +| `@objectRef` (an `object.entity`) | both | **Usually computed, so optional.** The target entity is derived (§3). The attribute is for an operation with nothing to derive from, such as a command that creates or imports. It has the same name and meaning as `@objectRef` elsewhere. When it is declared and a target also derives, the two must agree. | +| `@transitions` (string list) | command | No. Which lifecycle moves a command may make is a fact of the business. Each name resolves against the target's transitions. | +| `@permission` (string) | both | No, and this is the strongest case. The name is a key into grant data. Deriving it from the operation's name would make renaming an operation a silent change of who may run it. Several operations may share one name. | +| `@public` (boolean) | both | No. A boolean exception flag (ADR-0037 2c): the shell calls no permission check. Authentication is the transport's job and is unaffected. | +| `@errors` (string list, lower snake case) | command | No. The business failures a hand-written body can return are facts of code the model cannot see. Declaring them names them in the wire contract and the typed result. | + +`binding.rest` has two attributes: + +- `@method`, from the closed set `GET`, `POST`, `PUT`, `PATCH`, `DELETE`. When absent, a query is + `GET` and a command is `POST`. +- `@path`, a path template whose `{}` placeholders must be the target's key fields. When absent, + the path is `//{id}/` for an operation that addresses one row by key, + and `//` for one that does not. + +**A permission point has no type.** Each of the following is a point by construction: + +- every operation; +- every transition that derives a command; +- in a layered service, every derived CRUD verb, when a setting turns that on. + +The enforcing shell calls the project's policy with the point's permission name, the actor, +the loaded row and the input, before anything is written. A type would only restate the +operation. The model adds two facts, the name and `@public`. Who holds a permission is data, +and what the policy decides is code. *The model names where a decision is needed, never what +the decision is.* A team that wants a policy engine wires one behind the same call, and the +vocabulary does not change. + +The derived permission name includes its owner, so a grant means one thing. A declared +operation derives `.`, with the package of its API; operation names are +unique per package across its APIs (O6), so two operations never share it by accident. The +one exception is the same operation exposed by two APIs, as a versioned API beside its +successor (ADR-0067 §2: one router per API, one service): two declarations with the same name, +subtype and contract are one operation, and share the name on purpose. A +transition's derived command derives `..`, with the concrete +entity's package and name, so `Order.cancel` and `Invoice.cancel` ask about different +permissions. With no package, the `.` prefix is dropped. A declared `@permission` is a +dotted identifier path (P2): it becomes a constant and a key into grant data, so it carries no +spaces, punctuation or path segments. A package prefix may use `::`, so a derived name can be +declared as it is. (Captain's ruling, 2026-11-13, on the independent check's call 1.) + +### 2. Slice B: lifecycles + +| Node | Parent | Status | +|---|---|---| +| `transition.base` | | abstract | +| `transition.action` | `field.enum` of an `object.entity` | concrete. A move between two members of the enum, made by an operation. | +| `transition.timed` | | **reserved, not registered.** A move made by time ("expires after 7 days") has a different generated shape: a sweep or a derived read, with no operation and no permission point. It gets its own subtype when it is designed. Authoring it today is `ERR_UNKNOWN_SUBTYPE`. | + +Attributes on `transition.action`: + +| Attribute | Can it be computed? (ADR-0023) | +|---|---| +| `@from` (string list of members) | No. The allowed moves are the business rule itself. | +| `@to` (one member) | No. It may equal a member of `@from`. That self-transition records an action that leaves the state where it was. | +| `@condition` (the existing `attr.expression` grammar, over the entity's own fields) | No, for the reason ADR-0023 Amendment 1 gave for `@condition` on validators. It has the **same name, grammar and meaning** as there, and the loader checks it with the same code. It cannot read the actor; that is the policy's job. | +| `@permission`, `@public` | As on operations. A transition that derives its own command is a permission point. | + +**Derived, with no vocabulary:** + +- **The lifecycle.** An enum field with at least one `transition.action` is a lifecycle, named + after its field. An entity may have several. +- **The states.** The enum's `@values`. +- **The initial state.** The enum's `@default`. A lifecycle with no `@default` fails to load. +- **The terminal states.** The members no transition leaves. +- **A transition's command.** Each transition that no declared `operation.command` lists in + `@transitions` gets a derived command of the same name. It takes no input beyond the key and + lives on the package's service (setting `rules.lifecycle.commands`). So a plain lifecycle + needs no `api.operational` at all. A command claims a transition for its target entity and + every entity that extends the target, so a command acting on an abstract base claims the + inherited transition of each child. + +**Whose lifecycle it is.** A transition belongs to the entity that declares its field and to +every entity that extends that entity. It does not belong to an entity whose field merely +`extends` the lifecycle field: extending a field shares its values, and a status history table +is not the thing whose status it records. An inheritor that redeclares the lifecycle field must +extend the base's field, or the base's transitions would silently stop applying to it; the +loader refuses that (L10). + +**A lifecycle on an entity with no source is inert.** It loads, like everything else on a +sourceless entity (#248): the shape rules apply (L1, L3-L10), but it derives no command, and +`verify` checks its states and skips its permission points. The writable-source check (L2) +applies when a source is added, declared or inherited. A library's core layer is sourceless by +rule, so it can declare its lifecycles there and its `db` layer makes them live. (Captain's +ruling, 2026-11-13, on the independent check's call 2.) + +### 3. The derived target of an operation + +An operation's target entity is the first of these that exists: + +1. The declared `@objectRef`. +2. The one entity whose whole primary key the `@inputRef` value borrows: each of its primary + key fields is extended by exactly one field of the value. An input that borrows part of a + composite key or one key field twice (`fromId`, `toId`) names no single row, so it borrows + nothing from that entity. An input that borrows the whole keys of two entities derives + nothing either, and the operation falls through to its output or declares `@objectRef`. +3. The `@outputRef`, when it is an entity. +4. The base entity of the `@outputRef`, when it is a projection: the entity its identity + extends, else the one entity its fields extend. + +An operation **addresses one row by key** in two cases: + +- its input borrows the target's key; +- it is a query with no `@inputRef` and no `@many` whose target comes from its output, which + is a get by key. + +### 4. ADR-0037 applied + +| Concept | Derivable? | Result | +|---|---|---| +| A named command or query | No: own signature, own shell, own binding | **type** `operation`, subtypes `command`, `query` | +| The surface holding operations | No: a named, versionable contract | **type** `api`, subtype `operational` | +| REST method and path | Yes, by default | derived; `binding.rest` overrides | +| The target entity | Yes, in the common case | derived; `@objectRef` when not | +| A permission point | Yes: every operation and derived command is one | no vocabulary | +| The permission's name; "needs no check" | No | **attributes** `@permission`, `@public` | +| Moves a command may make; its business errors | No | **attributes** `@transitions`, `@errors` | +| States, initial and terminal states, the lifecycle | Yes | derived | +| An allowed move | No: own guarded update, own error, own permission point, own derived command | **type** `transition`, subtype `action` | +| A move made by time | No: a different generated shape | **subtype** `transition.timed`, reserved | +| A guard on a move | No; reuses an existing attribute | **attribute** `@condition` | + +### 5. What the loader refuses, and what `verify` reports + +**Loader errors.** These are hard errors in all five ports, with one `fixtures/conformance/` +case each (`error-rules-*`): + +| Rule | Code | When | +|---|---|---| +| L1 | `ERR_TRANSITION_NOT_ON_ENTITY` | A transition under an enum 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, declared or inherited, but no writable one. Reported on the entity. An entity with no source at all is not refused: its lifecycle is inert (§2). | +| 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. | +| L6 | `ERR_TRANSITION_NAME_COLLISION` | Two transitions of one entity share a name across its lifecycles, compared without case. Each may derive a command, so they share one namespace. | +| L7 | `ERR_BAD_ATTR_VALUE` | A `@condition` names a field the entity does not have, or is not boolean. Same check as the validators' `@condition`. | +| L8 | `ERR_BAD_ATTR_VALUE` | A transition's `@from` is empty: it could never be made. | +| L9 | `ERR_BAD_ATTR_VALUE` | The lifecycle field is an array (`isArray`, read through the resolving accessor). A guarded update compares one state. | +| L10 | `ERR_LIFECYCLE_REDECLARED` | An entity declares a field with the name of an inherited lifecycle field and does not extend it, so the base's transitions would be lost. Reported on the field. | +| P1 | `ERR_PERMISSION_PUBLIC_CONFLICT` | `@public: true` together with `@permission`, on an operation or a transition. | +| P2 | `ERR_BAD_ATTR_VALUE` | A `@permission` is not a dotted identifier path: names of letters, digits and `_` joined by `.`, where a package prefix may use `::`. | +| O1 | `ERR_OPERATION_SHAPE` | `@inputRef` is not an `object.value`, or `@outputRef` is not an entity, projection or value. This includes a reference that does not resolve. | +| O2 | `ERR_OPERATION_TARGET_UNRESOLVED` | `@objectRef` does not name an `object.entity`, or a command lists `@transitions` and has no target. | +| O3 | `ERR_OPERATION_TARGET_MISMATCH` | A declared `@objectRef` disagrees with the derived target. | +| O4 | `ERR_OPERATION_UNKNOWN_TRANSITION` | A `@transitions` name is not a transition of the target, declared or inherited. | +| O5 | `ERR_BAD_ATTR_VALUE` | An `@errors` code is not lower snake case, is listed twice, or is a code the route answers itself: the shell's `not_found`, `forbidden`, `invalid_transition`, `transition_condition_failed` and `state_managed` (§6), and the API contract's `validation`, `invalid_json`, `invalid_id`, `method_not_allowed`, `constraint_violation` and `internal`. A body returning one would be indistinguishable on the wire from the shell. | +| O6 | `ERR_TRANSITION_NAME_COLLISION` | Two operations of one package share a name, compared without case, in one API or across the package's APIs. Each derives the permission name `.` and a file in the package's service. Not refused: two APIs declaring the same operation, meaning the same name and subtype and the same `@inputRef`, `@outputRef` and `@objectRef` (compared by the node they resolve to), `@transitions` and `@errors` (as sets), `@permission`, `@public` and `@many`. Bindings are per API and may differ. | +| B1 | `ERR_BINDING_PATH_MISMATCH` | A `binding.rest @path`'s placeholders are not exactly the target's key fields, for an operation that addresses one row by key, or are not empty, for one that does not. | +| B2 | `ERR_BINDING_PATH_MISMATCH` | Two declared bindings of one API have the same effective method (declared, else derived) and the same `@path` once placeholder names are ignored. | + +Names are compared without case (L5, L6, O0, O6) because each becomes a command, a permission +constant and a file, and those collide on a case-folding target. + +Some inputs load on purpose, and are refused elsewhere or are legal: + +- **A route collision that involves a derived path.** B2 compares declared bindings only. A + derived path, and the derived CRUD routes such as `PATCH //{id}`, depend on the + collection path and the mount point, which are transport facts the loader does not have. The + transport generator that mounts the routes refuses a collision, including a binding declared + on the method and path of a derived CRUD route. +- **One operation declared twice in one API, or one API declared twice.** Same-named + siblings merge under the loader's general rule (`WARN_DUPLICATE_DECLARATION` when the + declarations are in different files), so there is one operation and one API, O6 does not + fire, and an + `@implementedBy` claim on it resolves. `fixtures/requirement-check-conformance/claim-operation-api-in-two-files` + pins that. +- **An input that borrows the keys of two entities.** It derives no target (§3); the operation + takes its target from the output or declares `@objectRef`, and O2 refuses a command with + `@transitions` that has neither. + +Two refusals use existing codes: + +- `@many` on a command is `ERR_UNKNOWN_ATTR`, because the attribute is registered on the query + only. +- An invalid `@method` is `ERR_BAD_ATTR_VALUE`, from its closed set. + +Each broken rule yields one error, on the offending node. An operation that fails O1 is not +checked further. One that fails O2 or O3 is not checked for O4 or B1. + +**`verify` checks.** These run in every port's `verify`, with one case each in the +`fixtures/rules-check-conformance/` corpus: + +| Code | Severity | When | +|---|---|---| +| `WARN_LIFECYCLE_UNREACHABLE_STATE` | `verify.lifecycle.unreachable` (default `warn`) | A state that no chain of transitions reaches from the initial state. This is almost always a missing transition. Sometimes only seeded data uses the state, so it is not an error by default. | +| `WARN_LIFECYCLE_INITIAL_TERMINAL` | `warn` | The initial state is terminal, so nothing can ever move. | +| `WARN_TRANSITION_UNREACHABLE` | `verify.lifecycle.unreachable` | A transition whose every `@from` state is unreachable, so it can never be made. | +| `WARN_TRANSITION_PERMISSION_SHADOWED` | `warn` | A transition declares `@permission` or `@public: true` but derives no command of its own for any concrete entity with a source carrying it (claimed by a declared command, or `rules.lifecycle.commands: none`), so nothing reads the attribute. An author reading the model would believe it guards the move. | +| `WARN_PERMISSION_DERIVED_NAME` | `rules.permissions.names`: `derive` (default) skips it, `advise` warns, `require` errors | An operation, or a transition that derives a command (on a concrete entity with a source), has no `@permission` and is not `@public`. A rename would silently move access. The message names the derived name. | + +A requirement's `@implementedBy` may name an operation (`Purchasing.decide`) or a transition +(`PurchaseRequest.status.submit`), at level 5. The reference resolves like any other member +reference, so a renamed operation fails the build. This is the hook a behaviour claim needed: +something real to point at. The requirement-check and requirement-test identity corpora pin +it. + +A model that declares no operation and no transition gets no rules diagnostics, no summary +line and no gate row. The settings `rules.permissions.names`, `rules.lifecycle.create`, +`rules.lifecycle.commands` and `verify.lifecycle.unreachable` are read from +`.metaobjects/config.json` by every port. When a key is absent, the setting takes today's +behaviour. `rules.lifecycle.create` is read and validated and has **no effect yet**: the shells +will be the first to act on it, and the documentation says so until they do. + +### 6. What the enforcing shell will guarantee, for every transition + +The shells are later work. This is what they are held to: + +1. Load the row: 404 when it is absent. +2. Call the permission point: 403 `forbidden` when the policy refuses. +3. Check that the row's state is in the `@from` of a transition the operation may make: 409 + `invalid_transition`. +4. Run the hand-written body, when the operation has one. It returns one of its declared + transitions or "none", and its return type is the union of the declared names. +5. Make the guarded update: + `UPDATE ... SET = :to WHERE = :id AND IN (:from) [AND ]`. + When it matches no row, re-read once and answer 409 (`invalid_transition` or + `transition_condition_failed`), or 404 when the row is gone. +6. Run steps 4 and 5, and the event hook, in one transaction. +7. Refuse a lifecycle field on the generic update path (409 `state_managed`). + +**The guarded update is part of the store-neutral storage contract** (§8). Every store +driver, including one an adopter writes, is held to it by a persistence-conformance scenario. + +### 7. Events and invariants in 1.3.0 + +- **Events: the derived transition hook only.** Every transition already carries what an event + needs: entity, key, transition, `from`, `to`, actor and time. So the shell calls the package's + write-event hook (ADR-0067 §4) inside the transaction, with `kind: "transition"`, with no new + vocabulary. That hook is where an adopter + writes to an outbox, history table or audit log. + - **`@emits` is held.** It would decide half of ADR-0030's reserved event surface without the + other half. + - **No outbox table in core.** An outbox table is schema in a specific store. +- **Cross-object invariants are held.** A "check before commit" shell reads as a guarantee and + is not one: at the default isolation level of the common databases, two transactions can each + pass the check and together break it (write skew). The sound shape is an invariant scoped to + a composition root, with the shell locking the root row. It is a later design. + +### 8. Where the core stops + +The core is the contracts and the conformance kits; store-specific code is a supported helper. +This vocabulary, its loader rules, its `verify` checks and the corpora that pin them are core. +So is the guarded update, as part of the store-neutral storage contract. A shell for a +particular language and framework is a helper (ADR-0067). + +## Consequences + +- A project that declares none of this sees no change: no diagnostics, no output, no gate row. +- `docs/compatibility-policy.md` changes its lists: + - `api.*`, `operation.*` and `binding.*` leave the reserved list, because they are now + registered, and join the business-rules vocabulary as experimental; + - `transition.timed` and the `api` event sibling join it. +- ADR-0030's open items are settled: the error codes are in §5, `@many` is the only list + attribute, and paging follows the existing list contract. +- Each port adds a rules pass to its loader, a rules gate to its `verify`, the four settings to + its config reader, and an inert test over `fixtures/codegen-noop/rules/`. + +## Alternatives considered + +- **A `lifecycle` container type** holding the transitions and naming its field. It reads + more explicitly on its own, but it is one more type that restates its parent. +- **No transition node, with moves as attributes of operations.** This loses derived + commands, and the guarded update would no longer be one per declared move. +- **Operations without `@errors`.** Bodies would throw untyped errors and the wire would get + one generic business error. That is smaller, but the typed result and the API documentation + lose the names. +- **Operations without `@permission` and `@public`, with the policy mapping operation names + itself.** Renaming an operation would silently change who may run it. +- **A package-flat derived permission name, `.`.** Two entities' `cancel` + transitions, or two APIs' `approve` operations, would share one permission, so a grant for + orders would silently grant invoices. Refusing every repeated name in a package instead would + allow `cancel` on one entity per package. +- **Refusing a lifecycle on an entity with no source.** A library's core layer is sourceless by + rule, so its lifecycles, and requirements pointing at them, could live only in its `db` + layer. diff --git a/spec/decisions/ADR-0067-layering-and-the-service-seam.md b/spec/decisions/ADR-0067-layering-and-the-service-seam.md new file mode 100644 index 0000000000..b1906fb16b --- /dev/null +++ b/spec/decisions/ADR-0067-layering-and-the-service-seam.md @@ -0,0 +1,201 @@ +# ADR-0067: Generated code is layered, and hand-written code attaches at the service seam + +## Status + +**Accepted** (2026-11-13). This ADR decides the layers a generator set emits, where the +business rules of ADR-0066 are enforced, and how hand-written code attaches. Two answers were +ruled with it: + +- In every language, hand-written code attaches by implementing a generated interface and + being passed in. +- The service is one module per metadata package, and its surface is that package's + operations. + +It amends ADR-0045 (§6). It depends on the line between core and helpers: ADR-0034 +Amendment 3, as ADR-0066 §8 restates it. The core is the contracts and the conformance kits, +and every set below is a helper. + +Nothing in this ADR is generated yet. The layered set, its service shells and the per-package +set selection are later work. ADR-0066's vocabulary is inert until they land. + +**Experimental.** The vocabulary this design generates from is experimental (ADR-0066 Status, +`docs/compatibility-policy.md`): it may change in a MINOR, including removals and renames, until +generated services run on it in an adopter estate. The layers, the seam and the shells below are +designed against it and change with it. + +## Context + +Today's generators emit a flat shape: entity and model types, then routes or controllers that +call persistence directly. Two things break that shape: + +- **There is no place for a rule to live.** ADR-0066 declares operations, permission points and + lifecycles. Enforcing them needs code that sits between the transport and the data access. + Every caller passes through it: an HTTP request, a background job, a queue consumer, an agent + tool. +- **There is no seam for hand-written code that keeps a guarantee.** A hand-written body has to + run *inside* the checks, not around them. A generated base class to override lets an + override call around the checks. A hook that only observes cannot decide which transition + applies. + +## Decision + +### 1. The layers + +A generator set emits some or all of these layers. Each layer is a separate generator that +can be imported, ejected or replaced on its own. + +| Layer | What it holds | Regenerated | Who owns what | +|---|---|---|---| +| 0. Names | Constants for every entity, field, table, column, enum member, state, transition, permission and error | Always | Generated. This layer is the tether: hand code that uses it stops compiling when the model renames something. Every set shares it. | +| 1. Contract types | Create, update and read shapes with their validation; operation inputs and outputs; the wire error shapes | Always | Generated. Every set in a language shares it, so two sets interoperate. | +| 2. Persistence mapping | The chosen ORM's mapping | Always | Generated, replaceable | +| 3. Data access | Typed queries per entity, including the guarded update | Always | Generated, replaceable. Omitted where the ORM is already this layer. | +| 4. Service | One module per metadata package. Its surface is the package's operations: derived CRUD, derived transition commands and declared operations. Each operation is a shell that enforces the declared rules. | Shells always; bodies never | Shells generated. Bodies, policy and event handling are hand-written against generated interfaces. | +| 5. Transport | Routes or controllers | Always | Generated; run as is, extend through hooks, or own a copy. Parses the request, calls the service, maps errors to the wire contract. Holds no rules. | +| 6. Client and UI logic | Hooks, forms, grids, field metadata | Always | Generated; run as is, extend through hooks, or own a copy. TypeScript only. | + +"Replaceable" means `meta eject` and its equivalents in each port (ADR-0034): the adopter owns +the copy from then on. Generated code is real code that adopters ship. A layer is replaced +because a project wants a different shape, not because the generated one is a draft. + +### 2. The unit is the operation; the module is the package + +There is one file per operation inside a package's service folder. The service module of a +metadata package holds the operations of every `api.operational` in that package, plus the +derived ones. + +An `api.operational` node is a wire contract, and it may be versioned (`v1` and `v2` side by +side). The service is code. So there is one router per `api.operational` node, and every +router calls the same service. + +The setting `layers.service.unit` lets a project group the service per entity or per API +instead. + +### 3. How hand-written code attaches: an interface, passed in, in every language + +The pattern has three steps, in every language: + +1. The generator emits an interface for the bodies, the policy and the event hook. +2. The adopter writes a type that implements it, in a file the generator never touches. +3. The composition root passes that type to the generated service's constructor or factory. + +Regeneration replaces the interfaces and the shells. When the model adds an operation or a +permission, the adopter's implementation stops compiling. In Python the type checker and a +start-up check say what is missing. Hand-written code cannot reach the shell's internals, so it +cannot bypass the shell's guarantees with an override. + +There is no generated base class to extend, and C# does not use partial methods. A partial +class is the same class, so hand-written code would see the shell's private state and could +call around it. + +### 4. Per language + +| | TypeScript | C# | Java | Kotlin | Python | +|---|---|---|---|---|---| +| Names (0) | `const`s and literal unions | `static class` of `const string` | `final class` of `static final String`; enums for states | `object` of `const val`; enum class for states | module constants; `StrEnum` for states | +| Contract types (1) | Zod schemas, inferred types | `record`s with DataAnnotations | `record`s with Bean Validation | `data class`es with validation | Pydantic v2 models | +| Mapping (2) | Drizzle tables | EF Core entities and `AppDbContext` | JPA entities | Exposed `Table` objects | SQLAlchemy 2.0 models | +| Data access (3) | query functions taking `db` | none: the context is the data layer | Spring Data JPA repositories, with a generated `@Modifying @Query` per transition | Exposed repository functions | functions taking a `Session` | +| Service (4) | a function per operation; `createXService(deps)` | `sealed class XService`, constructor-injected `IXPolicy`, `IXBodies`, `IXEvents`; `services.AddX()` | `@Service` class implementing a generated `XOperations`; constructor injection of `XPolicy` and `XBodies`; `@Transactional` per operation | `class XService(db, policy, bodies, events)`; each operation in `transaction {}`; returns a sealed `OpResult` | a module per package, a function per operation taking an `OpContext`; bodies and policy as `Protocol`s | +| Transport (5) | Fastify routes | minimal-API route groups | Spring MVC controllers | Spring controllers | FastAPI router with `Depends` | + +These calls are recorded here: + +- **Transactions and hooks.** Every write operation of the service runs in one transaction: + derived create, update and delete, derived transition commands, and declared commands. The + shell opens it, or under `layers.transactions: "caller"` requires one passed in, for a job + that runs several operations atomically. Inside it, in this order: + 1. The shell loads the target row, with a row lock where the dialect has one. The policy + check and the state check use that row. + 2. The before hook runs (derived CRUD, when `layers.crudHooks` is `beforeAfter`). It may + return a replacement input or refuse. + 3. The shell validates and stamps the final input (ADR-0045). + 4. The write runs, or the body, then the guarded update for a transition. + 5. The after hook runs. + 6. The write-event hook runs. + + Every hook receives the transaction the write used. If a hook or body throws or refuses, the + whole transaction rolls back: the row, any cascade a hook wrote, and the event handler's own + rows (an audit row, an outbox row). A refusal is answered `409 {"error": ""}`, and a + code reserved by the shell or the API contract is refused (ADR-0066 O5). Queries open no + write transaction and call no hooks. +- **Stores without interactive transactions.** A store whose driver cannot hold a transaction + across application code declares it in the storage kit (`interactiveTransactions: false`). + Cloudflare D1 is one. On such a store the shell generator refuses hooks and events with + `ERR_STORE_NO_INTERACTIVE_TX`, naming the package and `layers.events: "off"`. + + The settings `layers.transactions`, `layers.crudHooks` and `layers.events`, the storage kit's + `interactiveTransactions` and the code `ERR_STORE_NO_INTERACTIVE_TX` are designed here and + land with the service shells; nothing in 1.3.0 reads or reports them. +- **Kotlin** returns a sealed result for declared business errors, and the transport maps it. + The setting `layers.errors` switches to exceptions. +- **Java's** generated `@Service` class is not `final`, so Spring's transaction proxy works. + It is still not meant to be extended, and its generated header says so. + +### 5. Several generator sets in one language + +A **set** is a named list of generators, each assigned to a layer. Today's flat generators +become the `classic` set, and the new one is `layered`. More sets can be added, by this project +or by adopters. + +1. **Layers 0 and 1 are shared** by every set in a language. That is what lets a transport from + one set call a service from another. +2. **The service interface is the seam.** A transport talks to layer 4 only through the + generated operations interface, or `createXService` in TypeScript. +3. **One owner per output path.** The engine already refuses two generators writing one file, + and each set writes under its own folder per package. +4. **A set is chosen per package**, in the codegen config, for example + `sets: { "billing": "layered", "*": "classic" }`. A project that names no set keeps `classic`, + exactly as it runs today. +5. **A set is a list, not a framework.** Ejecting a set ejects its generators. Replacing a + layer means replacing one entry. + +### 6. Where the business-rules shell sits, and the amendment to ADR-0045 + +The shell sits in layer 4, and only there: + +- The transport parses the request and maps errors; it holds no rules. +- Data access provides the guarded update but decides nothing. +- The shell is the only caller of data access in the `layered` set. So a job, a queue consumer + or an agent tool that calls the service gets the same checks as an HTTP request. + +The `classic` set has no service layer. A project on `classic` that declares lifecycles gets +the minimum enforcement in the generated routes: the guarded update and the `state_managed` +refusal. `verify` advises that the full shell needs `layered`. + +**ADR-0045 is amended.** Its decision sentence becomes: *"The outermost generated write-path +artifact an adopter deploys must guarantee every metamodel-declared write semantic, either +itself or by calling a generated service shell that does. No consumer-supplied seam may sit +between the guarantee and the wire. A hand-written operation body is called by the shell, +inside the guarantee, and is not such a seam."* + +ADR-0045 rejected rewiring controllers through a lower layer, because it "would churn all +generated output". That reason does not apply here: the layered set is opt-in per package, so +no existing output churns. + +## Consequences + +- Each port gains a layered set, as later work, one change per language. TypeScript goes first. +- The shared generator manifest gains a `sets` field, and the codegen config gains per-package + set selection. +- `classic` is unchanged for every project that does not opt in. +- ADR-0045's guarantee is unchanged. A semantic is still never left to a consumer-supplied seam; + this ADR adds the generated service as a place where the guarantee may live. + +## Alternatives considered + +- **A generated base class with overridable methods.** This is the most common shape in other + generators, and it is rejected: an override can call around the checks. +- **Today's flat shape, with rules in the routes.** A job or agent tool that writes without + HTTP would bypass every rule. +- **A generated hexagonal core, or a runtime rules engine.** The first is heavier than the + problem. The second is a proprietary runtime, which is out of scope. +- **One service per `api.operational` node.** Rejected as the default, because versioned + surfaces would duplicate the shells for the same business operation. It is kept as a choice + through `layers.service.unit`. +- **Hooks as events (`onBeforeCreate` style) instead of bodies.** An event can observe but + cannot decide which transition applies, so the decision would leak into an untyped place. + Events are kept for derived CRUD as optional before and after hooks per verb + (`layers.crudHooks`), inside the operation's transaction (§4). They may refuse or replace + the input, but they never choose which operation runs. +- **C# partial methods.** Rejected by the attachment ruling (§3). diff --git a/spec/decisions/README.md b/spec/decisions/README.md index 21985db21d..16443eb1ef 100644 --- a/spec/decisions/README.md +++ b/spec/decisions/README.md @@ -62,6 +62,8 @@ Write one when a decision is **cross-cutting** (affects more than one language p - [ADR-0063 — Generators own their layout; formatters are test oracles only](ADR-0063-generators-own-layout.md) — *Accepted* (a writer in each port lays generated text out and no formatter runs in generation; output aims for clean code, not parity with today's formatting; a syntax-tree ratchet holds generator source to it, with an allowlist that only shrinks) - [ADR-0064 — `gen` skips rendering when the loaded model and its generators are unchanged](ADR-0064-skip-codegen-when-nothing-changed.md) — *Accepted* (every port keys a run on the loaded model and its generator inputs, and a matching key with every generated file unchanged renders and writes nothing; the manifest is written once per run; a local `verify --codegen` may answer from the key) - [ADR-0065 — Rust is the sixth port](ADR-0065-rust-is-the-sixth-port.md) — *Proposed* (a Rust port under `server/rust/`, in preview and unpublished, on its own 0.x line when it publishes; the command is `cargo meta`; no `migrate`, Jinja refused, generated code as one crate per MetaObjects package; gated by `registry-conformance` and the metamodel corpus with a shrink-only ledger) +- [ADR-0066 — Business rules: operations, permission points and lifecycles](ADR-0066-business-rules-operations-and-lifecycles.md) — *Accepted* (registers `api.*`, `operation.*`, `binding.*` and `transition.*` in all five ports, experimental, with eleven loader errors and a rules gate in every `verify`; the lifecycle, its states and a transition's command are derived; `transition.timed` reserved; the enforcing shells are later work) +- [ADR-0067 — Generated code is layered, and hand-written code attaches at the service seam](ADR-0067-layering-and-the-service-seam.md) — *Accepted* (layers 0 to 6; a service module per metadata package whose surface is its operations; hand-written bodies, policy and event handling implement generated interfaces and are passed in, in every language; generator sets chosen per package; amends ADR-0045) > **Index gap — ADR-0031 through ADR-0051 are on disk but not listed above.** The index stopped > being maintained after ADR-0030; the files are authoritative, this list is not. Read diff --git a/spec/metamodel/api.json b/spec/metamodel/api.json new file mode 100644 index 0000000000..0f30e16e08 --- /dev/null +++ b/spec/metamodel/api.json @@ -0,0 +1,73 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "api", + "subType": "base", + "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.", + "children": [] + }, + { + "type": "api", + "subType": "operational", + "extendsBase": true, + "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).", + "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": "base", + "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "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": "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", "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." } + ] + }, + { + "type": "operation", + "subType": "query", + "extendsBase": true, + "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": "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": "binding", + "subType": "base", + "description": "Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable.", + "children": [] + }, + { + "type": "binding", + "subType": "rest", + "extendsBase": true, + "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).", + "whenToUse": "An operation must keep a method or path the derived one would not give it, such as an existing public URL.", + "children": [ + { "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)." } + ] + } + ] +} diff --git a/spec/metamodel/field.json b/spec/metamodel/field.json index 46a2f064ce..8d4c5a2185 100644 --- a/spec/metamodel/field.json +++ b/spec/metamodel/field.json @@ -149,6 +149,7 @@ "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ + { "type": "transition", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Lifecycle moves between this enum's members (ADR-0066). An enum with at least one transition.action is a lifecycle: its states are @values, its initial state @default, its terminal states the members no transition leaves." }, { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer. Justified in ADR-0023 Amendment 1." }, diff --git a/spec/metamodel/transition.json b/spec/metamodel/transition.json new file mode 100644 index 0000000000..cbac9d3ef7 --- /dev/null +++ b/spec/metamodel/transition.json @@ -0,0 +1,27 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "transition", + "subType": "base", + "description": "Registry anchor for the attributes every lifecycle move shares (ADR-0054): not authorable.", + "children": [ + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name `..`, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED)." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." } + ] + }, + { + "type": "transition", + "subType": "action", + "extendsBase": true, + "description": "An allowed move between two values of a `field.enum`, made by an operation (ADR-0066). A `field.enum` with at least one is a lifecycle, named after the field. Its states are the enum's @values, its initial state the enum's @default, its terminal states the members no transition leaves; none of them has vocabulary of its own. Each transition is held to become a guarded update (`... WHERE id = ? AND IN (@from) [AND @condition]`), its own command when no declared operation claims it, its own permission point and its own wire error. No shell is generated yet: nothing is generated from this vocabulary, and the loader and `verify` only check it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A status field whose values may only change in certain ways: a request is submitted from draft, approved or rejected from submitted. Declare each allowed move here; once a shell is generated, the generic update path will no longer write the field. A move that leaves the state where it was (from submitted to submitted) records an action that changes nothing but still happened, such as a first approval of two.", + "rules": "Legal only under a `field.enum` of an `object.entity` (ERR_TRANSITION_NOT_ON_ENTITY). A concrete entity with a lifecycle and a source needs a writable one (ERR_TRANSITION_NOT_ON_ENTITY); on an entity with no source the lifecycle loads and is inert, deriving no command until a source is added. The field must declare @default (ERR_LIFECYCLE_NO_INITIAL). The field is not an array, and @from names at least one state (ERR_BAD_ATTR_VALUE). Names are unique across every lifecycle of the entity, compared without case, and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). A transition belongs to the entity that declares its field and to every entity extending it, never to an entity whose field merely `extends` that field; an inheritor that redeclares the field without extending it is ERR_LIFECYCLE_REDECLARED.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "isArray": true, "min": 1, "max": 1, "description": "The states this move may start from: members of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise), at least one (ERR_BAD_ATTR_VALUE when empty). The allowed moves are the business rule itself, so they cannot be computed." }, + { "type": "attr", "subType": "string", "name": "to", "min": 1, "max": 1, "description": "The state this move ends in: one member of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise). May equal a member of @from, which records an action that leaves the state where it was." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "A guard over the entity's own fields, in the attr.expression grammar: the same name, grammar and meaning as on the cross-field validators. The shell will evaluate it against the loaded row and also put it into the guarded update's WHERE (no shell is generated yet). It cannot read the actor; that is the policy's job. A field the entity does not have, or an expression that is not boolean, is ERR_BAD_ATTR_VALUE." } + ] + } + ] +} diff --git a/spec/roadmap.md b/spec/roadmap.md index 7e28f6c0e5..1963f1e518 100644 --- a/spec/roadmap.md +++ b/spec/roadmap.md @@ -143,7 +143,7 @@ under **Shipped**; planned FRs under **Planned** + the **Release plan**. ✅ shi | FR-021 | api metadata + contract projections | 📋 | 1.3 | [#7](https://github.com/metaobjectsdev/metaobjects/issues/7) | | FR-022 | Contract emitters (JSON Schema/OpenAPI/protobuf) | 🔵 JSON Schema and OpenAPI 1.2.1 · protobuf 1.3 | 1.2.1 | [#8](https://github.com/metaobjectsdev/metaobjects/issues/8) | | FR-023 | Metadata dependencies (cross-repo sharing: generated shared-model artifact, `meta deps sync`, committed snapshot + lock, default exclusion of imported metadata, consumer extend/overlay across the boundary) | 🟢 Phase 1a (TS + Python) **shipped** per DESIGN §11, Java/Kotlin consume (Phase 2 S3) — the usage-aware breaking-change classifier and the packaged transports (`npm`/`python`/`maven`/`nuget`) in the Python, Java and C# check are deferred (§11.4); C# consumer shipped in Phase 2 S6 | 1.1 | [#9](https://github.com/metaobjectsdev/metaobjects/issues/9) | -| FR-024 | Entity surfaces (projection/value + declared API) | 🟢 taxonomy + B3/B4a/B4b/B5/B6 validation parity + projection codegen **shipped 5 ports (1.0)**; declared-API surface (`api.operational`/`operation`/`binding.rest`) **deferred to a later 1.x** (not in 1.1.0; foundation for FR-034) | 1.0 · 1.x (later) | [#10](https://github.com/metaobjectsdev/metaobjects/issues/10) | +| FR-024 | Entity surfaces (projection/value + declared API) | 🟢 taxonomy + B3/B4a/B4b/B5/B6 validation parity + projection codegen **shipped 5 ports (1.0)**; declared-API surface (`api.operational`/`operation`/`binding.rest`) **registered in 1.3.0** with lifecycles (`transition.action`), loader rules and a `verify` rules gate in all five ports (ADR-0066); the enforcing service shells are later work (ADR-0067) | 1.0 · 1.3 | [#10](https://github.com/metaobjectsdev/metaobjects/issues/10) | | FR-025 | Cross-port package-binding codegen config | 📋 | 1.1 | [#11](https://github.com/metaobjectsdev/metaobjects/issues/11) | | FR-026 | Forms completeness (edit forms + view parity) | 🟢 edit forms + view-kind control dispatch **shipped**; renderer parity / validator wiring / `layout.form` **deferred to a later 1.x** (not in 1.1.0) | 1.x (later) | [#12](https://github.com/metaobjectsdev/metaobjects/issues/12) | | FR-027 | DataGrid downloads (CSV/XLSX/PDF/TXT) | 📋 | 1.2 | [#13](https://github.com/metaobjectsdev/metaobjects/issues/13) |