From 28f461c252ae9e78a863afea0e6acb98bad84b73 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 12:54:46 -0500 Subject: [PATCH 01/23] feat: move reporting and requirements into their own provider packs; raise on missing template variables; refuse permission-name collisions - Reporting (object.report, dimension.*, measure.* incl. measure.derived/@expr, segment.filter, the entity's dimension/measure/segment children and @segment on origin.aggregate/origin.first) is registered by metaobjects-reporting; requirements (requirement.* and the root's requirement child) by metaobjects-requirements. Both are in the default bundle of every port (TS, C#, Java/Kotlin, Python, Rust), so existing models load and generate identically. A model that uses a left-out pack's vocabulary gets a loader error (new error-packs-left-out-*-used fixtures). The verify requirements gate reads through the pack. - A pack subtype declared with extendsBase may fold a base another provider registered (object.report folds object.base); folded attributes keep the base's owner under ADR-0062. - Core vocabulary pin, registry manifest (root requirement child gains min 0 / max null), metamodel docs, site reference and payload regenerated. - GOVERNANCE.md: an attribute promoted from a pack into core keeps its name and meaning. - B4: Mustache and Jinja raise ERR_VAR_NOT_ON_PAYLOAD for a variable or dotted path absent from the payload, in every port that renders; render runners learn expected-error.txt. - B5: rules rule P3 refuses two permission points whose names resolve equal when at least one name is derived (ERR_TRANSITION_NAME_COLLISION), in every port. - C3: Python checks @union shape and @grain views at load; both must-fail fixtures leave its expected-failures ledger. --- AGENTS.md | 2 +- CHANGELOG.md | 33 +++ GOVERNANCE.md | 3 + docs/CONFORMANCE.md | 27 +- docs/features/business-rules.md | 1 + docs/features/extending-with-providers.md | 22 +- examples/showcase/site-payload.json | 2 +- .../entity-derived-filter-gate/providers.json | 2 +- .../entity-derived-league-gate/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../error-measure-of-foreign/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../error-measure-over-object/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../expected-errors.json | 15 ++ .../input/meta.shop.json | 54 ++++ .../providers.json | 1 + .../expected-errors.json | 25 ++ .../input/meta.shop.json | 71 +++++ .../providers.json | 1 + .../expected-errors.json | 15 ++ .../input/meta.shop.json | 59 ++++ .../providers.json | 1 + .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../error-report-abstract/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../error-report-spine-to-many/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../expected-errors.json | 15 ++ .../input/meta.orders.json | 67 +++++ .../providers.json | 1 + .../expected-errors.json | 15 ++ .../input/meta.orders.json | 66 +++++ .../providers.json | 1 + .../expected-errors.json | 15 ++ .../input/meta.orders.api.json | 20 ++ .../input/meta.orders.json | 53 ++++ .../providers.json | 1 + .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../origin-filter-relative-now/providers.json | 2 +- .../providers.json | 2 +- .../origin-segment-scoped/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../reporting-boolean-measures/providers.json | 2 +- .../providers.json | 2 +- .../reporting-derived-measures/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../reporting-relative-startof/providers.json | 2 +- .../providers.json | 2 +- .../reporting-spine-inherited/providers.json | 2 +- .../providers.json | 2 +- .../reporting-vocabulary/providers.json | 2 +- .../providers.json | 2 +- .../expected-error.txt | 1 + .../meta.json | 1 + .../payload.json | 1 + .../template.jinja | 1 + .../jinja-render-variables/expected.txt | 2 +- .../jinja-render-variables/meta.json | 2 +- .../jinja-render-variables/template.jinja | 2 +- fixtures/metamodel-docs/expected/providers.md | 36 ++- .../expected/types/dimension.md | 14 +- .../metamodel-docs/expected/types/measure.md | 26 +- .../metamodel-docs/expected/types/object.md | 16 +- .../metamodel-docs/expected/types/origin.md | 4 +- .../expected/types/requirement.md | 36 +-- .../metamodel-docs/expected/types/segment.md | 4 +- .../core-vocabulary.pin.json | 93 ------- .../expected-registry.json | 4 +- fixtures/registry-conformance/providers.json | 14 + .../render-dotted-path-lookup/expected.txt | 2 - .../render-dotted-path-lookup/meta.json | 2 +- .../template.mustache | 2 - .../expected-error.txt | 1 + .../meta.json | 1 + .../payload.json | 12 + .../template.mustache | 1 + .../expected-error.txt | 1 + .../render-error-missing-variable/meta.json | 1 + .../payload.json | 1 + .../template.mustache | 1 + scripts/check-core-vocabulary-pin.ts | 3 +- .../ConformanceAdapter.cs | 2 + .../CoreTypesTests.cs | 2 +- .../FixtureDiscovery.cs | 2 + .../FullCoreRegistry.cs | 2 + .../RegistryManifestConformanceTests.cs | 4 + .../RequirementsPackLeftOutTests.cs | 78 ++++++ .../YamlConformanceTests.cs | 2 + .../RenderConformanceTests.cs | 19 +- .../MetaObjects.Render/PayloadAccessors.cs | 28 ++ server/csharp/MetaObjects.Render/Renderer.cs | 86 +++++- .../Reporting/ReportingMetaDataProvider.cs | 66 +++++ .../Core/Reporting/ReportingSchema.cs | 4 +- .../RequirementsMetaDataProvider.cs | 56 ++++ server/csharp/MetaObjects/CoreTypes.cs | 94 +------ .../Loader/ValidationPasses.Rules.cs | 51 ++++ .../Persistence/Origin/OriginSchema.cs | 12 - server/csharp/MetaObjects/Registry.cs | 19 ++ .../MetaObjects/SpecMetamodel/object.json | 19 -- .../MetaObjects/SpecMetamodel/origin.json | 4 +- .../MetaObjects/SpecMetamodel/reporting.json | 31 ++- .../SpecMetamodel/requirement.json | 7 +- .../main/java/com/metaobjects/MetaData.java | 8 +- .../main/java/com/metaobjects/MetaRoot.java | 1 - .../metaobjects/loader/RulesValidation.java | 57 ++++ .../com/metaobjects/object/MetaObject.java | 23 +- .../metaobjects/object/ReportMetaObject.java | 30 +++ .../metaobjects/origin/AggregateOrigin.java | 3 +- .../com/metaobjects/origin/FirstOrigin.java | 3 +- .../ReportingTypesMetaDataProvider.java | 15 +- .../RequirementTypesMetaDataProvider.java | 9 + .../conformance/ConformanceTest.java | 57 ++-- .../RequirementsPackLeftOutTest.java | 78 ++++++ .../java/com/metaobjects/render/Renderer.java | 59 ++++ .../render/RenderCrossPortReportTest.java | 19 ++ .../render/RenderSnapshotTest.java | 3 + .../render/TypedPayloadRenderTest.java | 11 +- .../snapshots/render-dotted-path-lookup.txt | 2 - server/python/src/metaobjects/core_types.py | 255 +----------------- .../src/metaobjects/loader/validate_rules.py | 69 ++++- .../metaobjects/loader/validation_passes.py | 115 ++++++++ .../meta/core/reporting/reporting_provider.py | 223 +++++++++++++++ .../core/requirement/requirements_provider.py | 145 ++++++++++ server/python/src/metaobjects/registry.py | 21 +- .../src/metaobjects/render/jinja_render.py | 12 +- .../python/src/metaobjects/render/renderer.py | 33 ++- .../metaobjects/spec_metamodel/object.json | 19 -- .../metaobjects/spec_metamodel/origin.json | 4 +- .../metaobjects/spec_metamodel/reporting.json | 31 ++- .../spec_metamodel/requirement.json | 7 +- .../conformance-expected-failures.json | 4 - .../tests/conformance/conformance_adapter.py | 5 + .../tests/conformance/fixture_discovery.py | 5 +- .../python/tests/render/test_jinja_engine.py | 6 +- .../tests/render/test_render_conformance.py | 25 +- .../tests/test_requirements_pack_left_out.py | 65 +++++ .../metaobjects/data/metamodel/object.json | 19 -- .../metaobjects/data/metamodel/origin.json | 4 +- .../metaobjects/data/metamodel/reporting.json | 31 ++- .../data/metamodel/requirement.json | 7 +- server/rust/metaobjects/src/providers.rs | 62 ++++- server/rust/metaobjects/src/registry.rs | 37 ++- server/rust/metaobjects/src/validate/rules.rs | 85 ++++++ .../tests/conformance-expected-failures.json | 2 +- .../tests/metamodel_conformance.rs | 2 + .../test/requirements-pack-left-out.test.ts | 67 +++++ .../packages/conformance/src/fixture.ts | 7 +- .../typescript/packages/docs-site/src/load.ts | 2 +- .../packages/metadata/src/core-types.ts | 83 +----- .../core/object/object-definition.embedded.ts | 88 ------ .../reporting-definition.embedded.ts | 126 ++++++++- .../src/core/reporting/reporting-provider.ts | 47 ++++ .../requirement-definition.embedded.ts | 17 +- .../core/requirement/requirements-provider.ts | 44 +++ .../typescript/packages/metadata/src/index.ts | 9 + .../metadata/src/loader/rules-validation.ts | 56 +++- .../metamodel-docs/provider-definitions.ts | 7 +- .../origin/origin-definition.embedded.ts | 16 -- .../packages/metadata/src/provider-data.ts | 29 +- .../packages/metadata/src/registry.ts | 23 +- .../metadata/test/conformance/adapter.ts | 4 + .../packages/metadata/test/index.test.ts | 2 + .../origin-definition-completeness.test.ts | 8 +- .../metadata/test/provider-vocabulary.test.ts | 11 +- .../packages/metadata/test/provider.test.ts | 22 +- .../packages/metadata/test/registry.test.ts | 15 +- .../packages/render/src/jinja/nunjucks.ts | 20 +- .../typescript/packages/render/src/render.ts | 30 ++- .../render/test/render-conformance.test.ts | 10 +- .../packages/render/test/render.test.ts | 17 ++ site-reference/providers.html | 30 ++- site-reference/types/dimension.html | 12 +- site-reference/types/measure.html | 23 +- site-reference/types/object.html | 16 +- site-reference/types/origin.html | 4 +- site-reference/types/requirement.html | 34 +-- site-reference/types/segment.html | 3 +- spec/metamodel/object.json | 19 -- spec/metamodel/origin.json | 4 +- spec/metamodel/reporting.json | 31 ++- spec/metamodel/requirement.json | 7 +- 249 files changed, 3187 insertions(+), 1074 deletions(-) create mode 100644 fixtures/conformance/error-packs-left-out-measure-used/expected-errors.json create mode 100644 fixtures/conformance/error-packs-left-out-measure-used/input/meta.shop.json create mode 100644 fixtures/conformance/error-packs-left-out-measure-used/providers.json create mode 100644 fixtures/conformance/error-packs-left-out-report-used/expected-errors.json create mode 100644 fixtures/conformance/error-packs-left-out-report-used/input/meta.shop.json create mode 100644 fixtures/conformance/error-packs-left-out-report-used/providers.json create mode 100644 fixtures/conformance/error-packs-left-out-requirement-used/expected-errors.json create mode 100644 fixtures/conformance/error-packs-left-out-requirement-used/input/meta.shop.json create mode 100644 fixtures/conformance/error-packs-left-out-requirement-used/providers.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-declared/expected-errors.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-declared/input/meta.orders.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-declared/providers.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-dotted/expected-errors.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-dotted/input/meta.orders.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-dotted/providers.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-package/providers.json create mode 100644 fixtures/jinja-render-conformance/jinja-render-error-missing-variable/expected-error.txt create mode 100644 fixtures/jinja-render-conformance/jinja-render-error-missing-variable/meta.json create mode 100644 fixtures/jinja-render-conformance/jinja-render-error-missing-variable/payload.json create mode 100644 fixtures/jinja-render-conformance/jinja-render-error-missing-variable/template.jinja create mode 100644 fixtures/render-conformance/render-error-missing-dotted-path/expected-error.txt create mode 100644 fixtures/render-conformance/render-error-missing-dotted-path/meta.json create mode 100644 fixtures/render-conformance/render-error-missing-dotted-path/payload.json create mode 100644 fixtures/render-conformance/render-error-missing-dotted-path/template.mustache create mode 100644 fixtures/render-conformance/render-error-missing-variable/expected-error.txt create mode 100644 fixtures/render-conformance/render-error-missing-variable/meta.json create mode 100644 fixtures/render-conformance/render-error-missing-variable/payload.json create mode 100644 fixtures/render-conformance/render-error-missing-variable/template.mustache create mode 100644 server/csharp/MetaObjects.Conformance.Tests/RequirementsPackLeftOutTests.cs create mode 100644 server/csharp/MetaObjects/Core/Reporting/ReportingMetaDataProvider.cs create mode 100644 server/csharp/MetaObjects/Core/Requirement/RequirementsMetaDataProvider.cs create mode 100644 server/java/metadata/src/test/java/com/metaobjects/requirement/RequirementsPackLeftOutTest.java create mode 100644 server/python/src/metaobjects/meta/core/reporting/reporting_provider.py create mode 100644 server/python/src/metaobjects/meta/core/requirement/requirements_provider.py create mode 100644 server/python/tests/test_requirements_pack_left_out.py create mode 100644 server/typescript/packages/cli/test/requirements-pack-left-out.test.ts create mode 100644 server/typescript/packages/metadata/src/core/reporting/reporting-provider.ts create mode 100644 server/typescript/packages/metadata/src/core/requirement/requirements-provider.ts diff --git a/AGENTS.md b/AGENTS.md index 81d09c4325..b1e90853bd 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/` (578 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. +- Metamodel: `fixtures/conformance/` (584 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 dd6d4c915c..ffbfe4287d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,39 @@ here.** exactly the reference content is left alone and reported as identical, with or without `force`. The codegen fingerprint, `metaobjects:fmt` and `metaobjects:init` also compare before they write. +||||||| parent of 10fffac63 (feat: move reporting and requirements into their own provider packs; raise on missing template variables; refuse permission-name collisions) +- **Reporting and requirements are vocabulary packs, out of core.** The reporting vocabulary + (`object.report`, `dimension.*`, `measure.*` including `measure.derived` and its `@expr`, + `segment.filter`, the entity's dimension, measure and segment children and `@segment` on + `origin.aggregate` and `origin.first`) is now registered by its own provider, + `metaobjects-reporting`. The requirements vocabulary (`requirement.functional`, + `requirement.architectural` and the root's `requirement.*` child) is registered by + `metaobjects-requirements`. Both are in the default bundle of every port, so a model that loads + today loads and generates the same. An embedder can leave either out, and a model that then uses + its types gets a loader error naming the unknown type or subtype (new fixtures + `error-packs-left-out-*-used`). The `verify` requirements gate reads the nodes the pack + registered: with the pack left out, a model with no requirements gets a silent ledger. The core + vocabulary pin loses these types and attributes, and the registry manifest changes in one row: + the root's `requirement` child rule now states `min: 0, max: null`, as `api` did when the rules + pack moved out. A subtype a pack declares with `extendsBase` may now fold a base another provider + registered (`object.report` folds `object.base`); those folded attributes stay owned by the base's + provider. GOVERNANCE.md now says an attribute promoted from a pack into core keeps its name and + meaning. +- **A template that names a variable the payload lacks fails to render, in every render path.** + Mustache and Jinja raise `render verify failed: ERR_VAR_NOT_ON_PAYLOAD ()` for a missing + variable or dotted path, where they used to render it empty. A variable that is present and null + still renders empty. Render fixtures may now carry `expected-error.txt` in place of + `expected.txt`. +- **Business rules: two operations or transitions whose permission names come out equal are + refused (rule P3).** A permission name is the declared `@permission`, or else the derived + `.` (a `::` package separator reads as `.`). When two permission points resolve to + the same name and at least one of the two names is derived, the loader reports + `ERR_TRANSITION_NAME_COLLISION` on the later one. Two equal declared names stay legal: that is a + shared permission. New fixtures `error-rules-permission-name-op-{dotted,declared,package}`. +- **Python: unions and one-row-per-list-item views are checked at load.** The two must-fail + projection fixtures (a `@union` whose branches do not line up, and a `@grain` view that breaks + its rules) now fail in Python as they do in the other ports, and leave the Python + expected-failures ledger. - **C#: a `@sequenceStart` whose migrations project lacks the design-time services line is a generation error.** When `dotnet meta gen` can see the context's `ModelSnapshot.cs` in another project and that project does not carry `[assembly: DesignTimeServicesReference]`, the next `dotnet ef migrations add` diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 460baf537d..79baa84b82 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -113,6 +113,9 @@ MetaObjects, in the way the [`library/`](library/) entries do (see what belongs in the project at all is set out in "What belongs in MetaObjects" in [docs/features/libraries.md](docs/features/libraries.md). Moving vocabulary into core is a model-format change, so it needs a core maintainer (above). +- **An attribute promoted from a pack into core keeps its name and meaning.** Promotion moves + which provider registers the attribute. It does not rename it or change what it does, so a + model that used the attribute under the pack loads and behaves the same once core owns it. ### Releases diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 91b7e8f5df..c74e6ae4a7 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,12 +26,12 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 578 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 584 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | -| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 18 | ✓ | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/jinja-render-conformance/`](../fixtures/jinja-render-conformance/) (ADR-0061 — Jinja bodies render the same in jinja2 and nunjucks) | 15 | ✓ (nunjucks) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | refuses, via Java | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | ✓ (jinja2) | +| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 20 | ✓ | ✓ | inherits via Java | ✓ | ✓ | +| [`fixtures/jinja-render-conformance/`](../fixtures/jinja-render-conformance/) (ADR-0061 — Jinja bodies render the same in jinja2 and nunjucks) | 16 | ✓ (nunjucks) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | refuses, via Java | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | ✓ (jinja2) | | [`fixtures/jinja-verify-conformance/`](../fixtures/jinja-verify-conformance/) (ADR-0061 — the payload check over a Jinja body) | 31 | ✓ | refuses Jinja | refuses, via Java | refuses Jinja | ✓ | | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | | [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | @@ -71,7 +71,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`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 (ADR-0065) is not a column yet.** The sixth port runs these corpora -today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 578 +today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 584 green, with every validation pass the TypeScript loader runs, in the same order, so `server/rust/metaobjects/tests/conformance-expected-failures.json` is empty; `rules-check-conformance` (all 16 cases, the `verify` business-rules gate); @@ -90,7 +90,7 @@ generator, and a scale gate over twenty copies of the fitness model. The ledgers only shrink; the corpora without one assert each case outright. A new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard failure when ADR-0065 turns the warning off. A regression -still fails: the ledger's `minPassing` (578) is the number of fixtures known to pass, and the +still fails: the ledger's `minPassing` (584) is the number of fixtures known to pass, and the run fails when fewer do. The column joins this table when the port runs the render, persistence and API-contract corpora. A ✓ means the port runs the corpus green; an explicit `n / m` is used where a port @@ -187,8 +187,11 @@ canonical (`fixtures/registry-conformance/expected-registry.json`). - *Implemented in TypeScript and C#* (`implementedIn: ["typescript", "csharp"]`): the rc.21 view vocabulary — `origin.function` and the `object.projection` attrs `@union`, `@unionAll`, `@grain`, `@grainOrdinal`. The TypeScript view emitter lowers them; the C# loader validates - them (mirroring the TypeScript checks message for message); the other ports load them strictly - and do not act on them yet. + them (mirroring the TypeScript checks message for message). The Java (and so Kotlin) and Python + loaders also validate the `@union` / `@unionAll` / `@grain` / `@grainOrdinal` shape rules (the + `error-projection-union-shape` and `error-projection-grain-not-object-array` fixtures fail in + every port); no port other than TypeScript lowers them to a view, and Python does not yet check + `origin.function`. - *Loads strictly in every port.* Each port registers the `metaobjects-ui-web` provider (`view.textarea @rows`, the `view.image` attrs) and `@object` / `@objectAdapter` on `object.*`, loads all three fixtures strictly, and emits `implementedIn` in its manifest, which @@ -425,7 +428,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (578) +### `fixtures/conformance/` — metamodel loader + canonical serializer (584) | Fixture prefix | Feature doc | |---|---| @@ -464,9 +467,9 @@ on a reporting measure, etc.) and 7 `error-yaml-*` fixtures that pin the YAML 1.1 coercion guards (bool / null / hex in string contexts; numeric in enum contexts; reserved-as-attr). -### `fixtures/render-conformance/` (18) +### `fixtures/render-conformance/` (20) -All 18 fixtures → [features/templates-and-payloads.md](features/templates-and-payloads.md) +All 20 fixtures → [features/templates-and-payloads.md](features/templates-and-payloads.md) (render engine output section). 5 are end-to-end shape and escape examples (prompt / email / spreadsheet / CSV-injection escape / CSV numeric-literal exemption); 13 pin Mustache-engine semantics — dotted-path lookup, parent-context fallthrough, falsy/empty-array section behavior, @@ -823,8 +826,8 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 578 + yaml 19 + verify 45 -+ render 18 + persistence 67 + api-contract 141 + source-resolution 28 + scope 10 + +The fixtures in the nine corpora mapped above (metamodel 584 + yaml 19 + verify 45 ++ render 20 + persistence 67 + api-contract 141 + source-resolution 28 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the `cube-model` corpus 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 diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index e0071d6310..bcbe91e84c 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -183,6 +183,7 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa | 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. | +| P3 | `ERR_TRANSITION_NAME_COLLISION` | Two permission points ask about one permission name and at least one name is derived: an operation named `Order.open`, one declaring `permission: p.Order.open`, or one in package `p::Order`, beside the `open` transition of `Order` in `p`. `::` and `.` compare equal. Two declared `permission` values may be equal. | | B1 | `ERR_BINDING_PATH_MISMATCH` | A `binding.rest` `path` has the wrong placeholders. | | B2 | `ERR_BINDING_PATH_MISMATCH` | Two declared bindings of one API have the same method (declared or derived) and the same path, ignoring placeholder names. | diff --git a/docs/features/extending-with-providers.md b/docs/features/extending-with-providers.md index 0445417247..880b611234 100644 --- a/docs/features/extending-with-providers.md +++ b/docs/features/extending-with-providers.md @@ -121,17 +121,19 @@ lives in an extension pack. This page does not restate it. Which mechanism to us vocabulary is [ADR-0037](../../spec/decisions/ADR-0037-metamodel-vocabulary-expansion-decision-framework.md). **Current state.** Business rules (`api`, `operation`, `binding`, `transition`, provider -`metaobjects-rules`) and the view expressions that arrived in 1.3.0 (`origin.function`, `@union`, -`@unionAll`, `@grain`, `@grainOrdinal`, provider `metaobjects-view-expressions`) are packs: each -is its own provider, in the default bundle of every port that carries it, and an embedder can -leave it out. A model that uses a left-out pack's types gets a loader error naming the unknown -type, subtype or attribute. Reporting (`dimension`, `measure`, `segment`, `object.report`) and -requirements (`requirement.*`) are still registered by `metaobjects-core-types`: they are woven -into `object.json` and read by the `verify` gate in every port, so they were not a small -mechanical move. They are the next candidates for a pack, and they are where they landed, not -where they belong. No new vocabulary should follow their example: a gate +`metaobjects-rules`), the view expressions that arrived in 1.3.0 (`origin.function`, `@union`, +`@unionAll`, `@grain`, `@grainOrdinal`, provider `metaobjects-view-expressions`), reporting +(`object.report`, `dimension.*`, `measure.*`, `segment.filter` and `@segment` on +`origin.aggregate` and `origin.first`, provider `metaobjects-reporting`) and requirements +(`requirement.*`, provider `metaobjects-requirements`) are packs: each is its own provider, in +the default bundle of every port, and an embedder can leave it out. A model that uses a left-out +pack's types gets a loader error naming the unknown type, subtype or attribute. The `verify` +requirements gate reads the requirement nodes the pack registered, so with that pack left out it +has nothing to report. `object.report` shows the one thing a pack subtype may borrow from core: +declared with `extendsBase`, it folds in `object.base`, which core registers, and those folded +attributes stay owned by core. New vocabulary follows the same path: a gate (`scripts/check-core-vocabulary-pin.ts`) pins the core provider's types and attributes, so adding -one fails with a pointer to GOVERNANCE.md and this mechanism. +one to core fails with a pointer to GOVERNANCE.md and this mechanism. You opt a concern in by **declaring**, not by configuring, and a concern your model does not declare costs nothing, generates nothing and diagnoses nothing: diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 1ba85b43c7..94f9d8136f 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 578, + "fixtures": 584, "corpora": 43, "baseTypes": 21 }, diff --git a/fixtures/conformance/entity-derived-filter-gate/providers.json b/fixtures/conformance/entity-derived-filter-gate/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/entity-derived-filter-gate/providers.json +++ b/fixtures/conformance/entity-derived-filter-gate/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/entity-derived-league-gate/providers.json b/fixtures/conformance/entity-derived-league-gate/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/entity-derived-league-gate/providers.json +++ b/fixtures/conformance/entity-derived-league-gate/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-grain-on-date/providers.json b/fixtures/conformance/error-dimension-grain-on-date/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-grain-on-date/providers.json +++ b/fixtures/conformance/error-dimension-grain-on-date/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-of-jsonb-member/providers.json b/fixtures/conformance/error-dimension-of-jsonb-member/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-of-jsonb-member/providers.json +++ b/fixtures/conformance/error-dimension-of-jsonb-member/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-of-unresolved/providers.json b/fixtures/conformance/error-dimension-of-unresolved/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-of-unresolved/providers.json +++ b/fixtures/conformance/error-dimension-of-unresolved/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-over-object/providers.json b/fixtures/conformance/error-dimension-over-object/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-over-object/providers.json +++ b/fixtures/conformance/error-dimension-over-object/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-time-not-temporal/providers.json b/fixtures/conformance/error-dimension-time-not-temporal/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-time-not-temporal/providers.json +++ b/fixtures/conformance/error-dimension-time-not-temporal/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-via-base-lacks-field/providers.json b/fixtures/conformance/error-dimension-via-base-lacks-field/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-via-base-lacks-field/providers.json +++ b/fixtures/conformance/error-dimension-via-base-lacks-field/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-via-to-many/providers.json b/fixtures/conformance/error-dimension-via-to-many/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-via-to-many/providers.json +++ b/fixtures/conformance/error-dimension-via-to-many/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-all-default-not-boolean/providers.json b/fixtures/conformance/error-measure-all-default-not-boolean/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-measure-all-default-not-boolean/providers.json +++ b/fixtures/conformance/error-measure-all-default-not-boolean/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-any-non-boolean/providers.json b/fixtures/conformance/error-measure-any-non-boolean/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-measure-any-non-boolean/providers.json +++ b/fixtures/conformance/error-measure-any-non-boolean/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-any-without-condition/providers.json b/fixtures/conformance/error-measure-any-without-condition/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-measure-any-without-condition/providers.json +++ b/fixtures/conformance/error-measure-any-without-condition/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-default-non-numeric/providers.json b/fixtures/conformance/error-measure-default-non-numeric/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-default-non-numeric/providers.json +++ b/fixtures/conformance/error-measure-default-non-numeric/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-default-not-integer/providers.json b/fixtures/conformance/error-measure-default-not-integer/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-default-not-integer/providers.json +++ b/fixtures/conformance/error-measure-default-not-integer/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-default-on-count-integral-float/providers.json b/fixtures/conformance/error-measure-default-on-count-integral-float/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-default-on-count-integral-float/providers.json +++ b/fixtures/conformance/error-measure-default-on-count-integral-float/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-default-on-count-non-numeric/providers.json b/fixtures/conformance/error-measure-default-on-count-non-numeric/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-default-on-count-non-numeric/providers.json +++ b/fixtures/conformance/error-measure-default-on-count-non-numeric/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-default-on-count/providers.json b/fixtures/conformance/error-measure-default-on-count/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-default-on-count/providers.json +++ b/fixtures/conformance/error-measure-default-on-count/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json b/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json +++ b/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-default/providers.json b/fixtures/conformance/error-measure-derived-default/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-default/providers.json +++ b/fixtures/conformance/error-measure-derived-default/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-malformed-expr/providers.json b/fixtures/conformance/error-measure-derived-malformed-expr/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-malformed-expr/providers.json +++ b/fixtures/conformance/error-measure-derived-malformed-expr/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json b/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json +++ b/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json b/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json +++ b/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-of-derived/providers.json b/fixtures/conformance/error-measure-derived-of-derived/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-of-derived/providers.json +++ b/fixtures/conformance/error-measure-derived-of-derived/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-time-dimension/providers.json b/fixtures/conformance/error-measure-derived-time-dimension/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-time-dimension/providers.json +++ b/fixtures/conformance/error-measure-derived-time-dimension/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-unknown-operand/providers.json b/fixtures/conformance/error-measure-derived-unknown-operand/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-unknown-operand/providers.json +++ b/fixtures/conformance/error-measure-derived-unknown-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-distinct-not-count/providers.json b/fixtures/conformance/error-measure-distinct-not-count/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-distinct-not-count/providers.json +++ b/fixtures/conformance/error-measure-distinct-not-count/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-of-foreign/providers.json b/fixtures/conformance/error-measure-of-foreign/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-of-foreign/providers.json +++ b/fixtures/conformance/error-measure-of-foreign/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-of-jsonb-member/providers.json b/fixtures/conformance/error-measure-of-jsonb-member/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-of-jsonb-member/providers.json +++ b/fixtures/conformance/error-measure-of-jsonb-member/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-of-member-of-scalar/providers.json b/fixtures/conformance/error-measure-of-member-of-scalar/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-of-member-of-scalar/providers.json +++ b/fixtures/conformance/error-measure-of-member-of-scalar/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-of-path-too-deep/providers.json b/fixtures/conformance/error-measure-of-path-too-deep/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-of-path-too-deep/providers.json +++ b/fixtures/conformance/error-measure-of-path-too-deep/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-of-unknown-member/providers.json b/fixtures/conformance/error-measure-of-unknown-member/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-of-unknown-member/providers.json +++ b/fixtures/conformance/error-measure-of-unknown-member/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-over-object/providers.json b/fixtures/conformance/error-measure-over-object/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-over-object/providers.json +++ b/fixtures/conformance/error-measure-over-object/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-segment-unresolved/providers.json b/fixtures/conformance/error-measure-segment-unresolved/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-segment-unresolved/providers.json +++ b/fixtures/conformance/error-measure-segment-unresolved/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-sum-non-numeric/providers.json b/fixtures/conformance/error-measure-sum-non-numeric/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-sum-non-numeric/providers.json +++ b/fixtures/conformance/error-measure-sum-non-numeric/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-sum-without-of/providers.json b/fixtures/conformance/error-measure-sum-without-of/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-measure-sum-without-of/providers.json +++ b/fixtures/conformance/error-measure-sum-without-of/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-tuple-without-distinct/providers.json b/fixtures/conformance/error-measure-tuple-without-distinct/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-tuple-without-distinct/providers.json +++ b/fixtures/conformance/error-measure-tuple-without-distinct/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-origin-correlated-operand-unknown/providers.json b/fixtures/conformance/error-origin-correlated-operand-unknown/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-origin-correlated-operand-unknown/providers.json +++ b/fixtures/conformance/error-origin-correlated-operand-unknown/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-origin-segment-flattened-of/providers.json b/fixtures/conformance/error-origin-segment-flattened-of/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-origin-segment-flattened-of/providers.json +++ b/fixtures/conformance/error-origin-segment-flattened-of/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-origin-segment-unresolved/providers.json b/fixtures/conformance/error-origin-segment-unresolved/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-origin-segment-unresolved/providers.json +++ b/fixtures/conformance/error-origin-segment-unresolved/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-packs-left-out-measure-used/expected-errors.json b/fixtures/conformance/error-packs-left-out-measure-used/expected-errors.json new file mode 100644 index 0000000000..48db587551 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-measure-used/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_TYPE", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['measure.aggregate']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-packs-left-out-measure-used/input/meta.shop.json b/fixtures/conformance/error-packs-left-out-measure-used/input/meta.shop.json new file mode 100644 index 0000000000..c2dd11647f --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-measure-used/input/meta.shop.json @@ -0,0 +1,54 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "customerId" + } + }, + { + "field.currency": { + "name": "totalCents" + } + }, + { + "field.string": { + "name": "status" + } + }, + { + "measure.aggregate": { + "name": "revenue", + "@agg": "sum", + "@of": "Order.totalCents" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-packs-left-out-measure-used/providers.json b/fixtures/conformance/error-packs-left-out-measure-used/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-measure-used/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/error-packs-left-out-report-used/expected-errors.json b/fixtures/conformance/error-packs-left-out-report-used/expected-errors.json new file mode 100644 index 0000000000..692a18d294 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-report-used/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_TYPE", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[4]['measure.aggregate']" + } + }, + { + "code": "ERR_UNKNOWN_SUBTYPE", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.report']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-packs-left-out-report-used/input/meta.shop.json b/fixtures/conformance/error-packs-left-out-report-used/input/meta.shop.json new file mode 100644 index 0000000000..ef2cfebaa8 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-report-used/input/meta.shop.json @@ -0,0 +1,71 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "customerId" + } + }, + { + "field.currency": { + "name": "totalCents" + } + }, + { + "measure.aggregate": { + "name": "revenue", + "@agg": "sum", + "@of": "Order.totalCents" + } + }, + { + "field.string": { + "name": "status" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.report": { + "name": "OrderTotals", + "@from": "Order", + "@measures": [ + "revenue" + ], + "children": [ + { + "source.rdb": { + "@table": "order_totals", + "@kind": "view" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-packs-left-out-report-used/providers.json b/fixtures/conformance/error-packs-left-out-report-used/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-report-used/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/error-packs-left-out-requirement-used/expected-errors.json b/fixtures/conformance/error-packs-left-out-requirement-used/expected-errors.json new file mode 100644 index 0000000000..f87267ffcb --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-requirement-used/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_TYPE", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[1]['requirement.functional']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-packs-left-out-requirement-used/input/meta.shop.json b/fixtures/conformance/error-packs-left-out-requirement-used/input/meta.shop.json new file mode 100644 index 0000000000..16fd670e6e --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-requirement-used/input/meta.shop.json @@ -0,0 +1,59 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "customerId" + } + }, + { + "field.currency": { + "name": "totalCents" + } + }, + { + "field.string": { + "name": "status" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "requirement.functional": { + "name": "PlaceOrder", + "@level": 4, + "@status": "live", + "@statement": "A customer places an order", + "@counterexample": "A customer cannot place an order", + "@implementedBy": [ + "acme::shop::Order" + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-packs-left-out-requirement-used/providers.json b/fixtures/conformance/error-packs-left-out-requirement-used/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-requirement-used/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/error-ratio-boolean-operand/providers.json b/fixtures/conformance/error-ratio-boolean-operand/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-ratio-boolean-operand/providers.json +++ b/fixtures/conformance/error-ratio-boolean-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-ratio-non-numeric-operand/providers.json b/fixtures/conformance/error-ratio-non-numeric-operand/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-ratio-non-numeric-operand/providers.json +++ b/fixtures/conformance/error-ratio-non-numeric-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-ratio-operand-not-aggregate/providers.json b/fixtures/conformance/error-ratio-operand-not-aggregate/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-ratio-operand-not-aggregate/providers.json +++ b/fixtures/conformance/error-ratio-operand-not-aggregate/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-relative-date-bad-duration/providers.json b/fixtures/conformance/error-relative-date-bad-duration/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-relative-date-bad-duration/providers.json +++ b/fixtures/conformance/error-relative-date-bad-duration/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-relative-date-bad-startof/providers.json b/fixtures/conformance/error-relative-date-bad-startof/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-relative-date-bad-startof/providers.json +++ b/fixtures/conformance/error-relative-date-bad-startof/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-relative-date-datagrid-host/providers.json b/fixtures/conformance/error-relative-date-datagrid-host/providers.json index ba0387a547..d0231bfd43 100644 --- a/fixtures/conformance/error-relative-date-datagrid-host/providers.json +++ b/fixtures/conformance/error-relative-date-datagrid-host/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db","metaobjects-ui"] +["metaobjects-core-types","metaobjects-db","metaobjects-ui","metaobjects-reporting"] diff --git a/fixtures/conformance/error-relative-date-extra-key/providers.json b/fixtures/conformance/error-relative-date-extra-key/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-relative-date-extra-key/providers.json +++ b/fixtures/conformance/error-relative-date-extra-key/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-relative-date-non-temporal/providers.json b/fixtures/conformance/error-relative-date-non-temporal/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-relative-date-non-temporal/providers.json +++ b/fixtures/conformance/error-relative-date-non-temporal/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-abstract/providers.json b/fixtures/conformance/error-report-abstract/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-abstract/providers.json +++ b/fixtures/conformance/error-report-abstract/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-declares-field/providers.json b/fixtures/conformance/error-report-declares-field/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-declares-field/providers.json +++ b/fixtures/conformance/error-report-declares-field/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json b/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json +++ b/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-dimension-grain/providers.json b/fixtures/conformance/error-report-dimension-grain/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-dimension-grain/providers.json +++ b/fixtures/conformance/error-report-dimension-grain/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-field-collision/providers.json b/fixtures/conformance/error-report-field-collision/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-field-collision/providers.json +++ b/fixtures/conformance/error-report-field-collision/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-foreign-measure/providers.json b/fixtures/conformance/error-report-foreign-measure/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-foreign-measure/providers.json +++ b/fixtures/conformance/error-report-foreign-measure/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-from-not-entity/providers.json b/fixtures/conformance/error-report-from-not-entity/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-from-not-entity/providers.json +++ b/fixtures/conformance/error-report-from-not-entity/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-measure-unresolved/providers.json b/fixtures/conformance/error-report-measure-unresolved/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-measure-unresolved/providers.json +++ b/fixtures/conformance/error-report-measure-unresolved/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-segment-unresolved/providers.json b/fixtures/conformance/error-report-segment-unresolved/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-segment-unresolved/providers.json +++ b/fixtures/conformance/error-report-segment-unresolved/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-source-kind-materialized-view/providers.json b/fixtures/conformance/error-report-source-kind-materialized-view/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-source-kind-materialized-view/providers.json +++ b/fixtures/conformance/error-report-source-kind-materialized-view/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-source-kind-stored-proc/providers.json b/fixtures/conformance/error-report-source-kind-stored-proc/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-source-kind-stored-proc/providers.json +++ b/fixtures/conformance/error-report-source-kind-stored-proc/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-source-kind-table-function/providers.json b/fixtures/conformance/error-report-source-kind-table-function/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-source-kind-table-function/providers.json +++ b/fixtures/conformance/error-report-source-kind-table-function/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-spine-dimension-off-spine/providers.json b/fixtures/conformance/error-report-spine-dimension-off-spine/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-spine-dimension-off-spine/providers.json +++ b/fixtures/conformance/error-report-spine-dimension-off-spine/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-spine-dimension-other-path/providers.json b/fixtures/conformance/error-report-spine-dimension-other-path/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-spine-dimension-other-path/providers.json +++ b/fixtures/conformance/error-report-spine-dimension-other-path/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-spine-no-dimensions/providers.json b/fixtures/conformance/error-report-spine-no-dimensions/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-spine-no-dimensions/providers.json +++ b/fixtures/conformance/error-report-spine-no-dimensions/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-spine-not-from/providers.json b/fixtures/conformance/error-report-spine-not-from/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-spine-not-from/providers.json +++ b/fixtures/conformance/error-report-spine-not-from/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-spine-to-many/providers.json b/fixtures/conformance/error-report-spine-to-many/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-spine-to-many/providers.json +++ b/fixtures/conformance/error-report-spine-to-many/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-two-unresolved-dimensions/providers.json b/fixtures/conformance/error-report-two-unresolved-dimensions/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-two-unresolved-dimensions/providers.json +++ b/fixtures/conformance/error-report-two-unresolved-dimensions/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json b/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json +++ b/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json b/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json +++ b/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json b/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json +++ b/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-writable-source/providers.json b/fixtures/conformance/error-report-writable-source/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-writable-source/providers.json +++ b/fixtures/conformance/error-report-writable-source/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-requirement-level-fractional/providers.json b/fixtures/conformance/error-requirement-level-fractional/providers.json index 8ec88fc091..3aea349412 100644 --- a/fixtures/conformance/error-requirement-level-fractional/providers.json +++ b/fixtures/conformance/error-requirement-level-fractional/providers.json @@ -1 +1 @@ -["metaobjects-core-types"] +["metaobjects-core-types", "metaobjects-requirements"] diff --git a/fixtures/conformance/error-requirement-status-abandoned/providers.json b/fixtures/conformance/error-requirement-status-abandoned/providers.json index 8ec88fc091..3aea349412 100644 --- a/fixtures/conformance/error-requirement-status-abandoned/providers.json +++ b/fixtures/conformance/error-requirement-status-abandoned/providers.json @@ -1 +1 @@ -["metaobjects-core-types"] +["metaobjects-core-types", "metaobjects-requirements"] diff --git a/fixtures/conformance/error-requirement-verified-by-retired/providers.json b/fixtures/conformance/error-requirement-verified-by-retired/providers.json index 8ec88fc091..3aea349412 100644 --- a/fixtures/conformance/error-requirement-verified-by-retired/providers.json +++ b/fixtures/conformance/error-requirement-verified-by-retired/providers.json @@ -1 +1 @@ -["metaobjects-core-types"] +["metaobjects-core-types", "metaobjects-requirements"] diff --git a/fixtures/conformance/error-rules-permission-name-op-declared/expected-errors.json b/fixtures/conformance/error-rules-permission-name-op-declared/expected-errors.json new file mode 100644 index 0000000000..9fb242567a --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-declared/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.orders.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.operational'].children[0]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-permission-name-op-declared/input/meta.orders.json b/fixtures/conformance/error-rules-permission-name-op-declared/input/meta.orders.json new file mode 100644 index 0000000000..906380d8c0 --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-declared/input/meta.orders.json @@ -0,0 +1,67 @@ +{ + "metadata.root": { + "package": "p", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.enum": { + "name": "status", + "@values": [ + "draft", + "open" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "open", + "@from": [ + "draft" + ], + "@to": "open" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "Orders", + "children": [ + { + "operation.query": { + "name": "confirm", + "@outputRef": "Order", + "@permission": "p.Order.open" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-name-op-declared/providers.json b/fixtures/conformance/error-rules-permission-name-op-declared/providers.json new file mode 100644 index 0000000000..f14395dbea --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-declared/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db", "metaobjects-rules"] diff --git a/fixtures/conformance/error-rules-permission-name-op-dotted/expected-errors.json b/fixtures/conformance/error-rules-permission-name-op-dotted/expected-errors.json new file mode 100644 index 0000000000..9fb242567a --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-dotted/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.orders.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.operational'].children[0]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-permission-name-op-dotted/input/meta.orders.json b/fixtures/conformance/error-rules-permission-name-op-dotted/input/meta.orders.json new file mode 100644 index 0000000000..6138b58ebe --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-dotted/input/meta.orders.json @@ -0,0 +1,66 @@ +{ + "metadata.root": { + "package": "p", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.enum": { + "name": "status", + "@values": [ + "draft", + "open" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "open", + "@from": [ + "draft" + ], + "@to": "open" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "Orders", + "children": [ + { + "operation.query": { + "name": "Order.open", + "@outputRef": "Order" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-name-op-dotted/providers.json b/fixtures/conformance/error-rules-permission-name-op-dotted/providers.json new file mode 100644 index 0000000000..f14395dbea --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-dotted/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db", "metaobjects-rules"] diff --git a/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json b/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json new file mode 100644 index 0000000000..9728c81073 --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.orders.api.json" + ], + "jsonPath": "$['metadata.root'].children[0]['api.operational'].children[0]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json b/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json new file mode 100644 index 0000000000..e2418050ac --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json @@ -0,0 +1,20 @@ +{ + "metadata.root": { + "package": "p::Order", + "children": [ + { + "api.operational": { + "name": "Orders", + "children": [ + { + "operation.query": { + "name": "open", + "@outputRef": "p::Order" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json b/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json new file mode 100644 index 0000000000..d84c0d39eb --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json @@ -0,0 +1,53 @@ +{ + "metadata.root": { + "package": "p", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.enum": { + "name": "status", + "@values": [ + "draft", + "open" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "open", + "@from": [ + "draft" + ], + "@to": "open" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-name-op-package/providers.json b/fixtures/conformance/error-rules-permission-name-op-package/providers.json new file mode 100644 index 0000000000..f14395dbea --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-package/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db", "metaobjects-rules"] diff --git a/fixtures/conformance/error-segment-filter-bad-field/providers.json b/fixtures/conformance/error-segment-filter-bad-field/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-segment-filter-bad-field/providers.json +++ b/fixtures/conformance/error-segment-filter-bad-field/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/measure-default-integral-float/providers.json b/fixtures/conformance/measure-default-integral-float/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/measure-default-integral-float/providers.json +++ b/fixtures/conformance/measure-default-integral-float/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/object-collection-name-consignments/providers.json b/fixtures/conformance/object-collection-name-consignments/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/object-collection-name-consignments/providers.json +++ b/fixtures/conformance/object-collection-name-consignments/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/origin-correlated-filter-and-segment/providers.json b/fixtures/conformance/origin-correlated-filter-and-segment/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/origin-correlated-filter-and-segment/providers.json +++ b/fixtures/conformance/origin-correlated-filter-and-segment/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/origin-filter-relative-now/providers.json b/fixtures/conformance/origin-filter-relative-now/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/origin-filter-relative-now/providers.json +++ b/fixtures/conformance/origin-filter-relative-now/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/origin-reverse-hop-collection-name/providers.json b/fixtures/conformance/origin-reverse-hop-collection-name/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/origin-reverse-hop-collection-name/providers.json +++ b/fixtures/conformance/origin-reverse-hop-collection-name/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/origin-segment-scoped/providers.json b/fixtures/conformance/origin-segment-scoped/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/origin-segment-scoped/providers.json +++ b/fixtures/conformance/origin-segment-scoped/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/overlay-explicit-package-not-applied-to-target/providers.json b/fixtures/conformance/overlay-explicit-package-not-applied-to-target/providers.json index 8ec88fc091..3aea349412 100644 --- a/fixtures/conformance/overlay-explicit-package-not-applied-to-target/providers.json +++ b/fixtures/conformance/overlay-explicit-package-not-applied-to-target/providers.json @@ -1 +1 @@ -["metaobjects-core-types"] +["metaobjects-core-types", "metaobjects-requirements"] diff --git a/fixtures/conformance/projection-filter-relative-now/providers.json b/fixtures/conformance/projection-filter-relative-now/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/projection-filter-relative-now/providers.json +++ b/fixtures/conformance/projection-filter-relative-now/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/report-dimension-required-by-model/providers.json b/fixtures/conformance/report-dimension-required-by-model/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/report-dimension-required-by-model/providers.json +++ b/fixtures/conformance/report-dimension-required-by-model/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-any-all-predicate/providers.json b/fixtures/conformance/reporting-any-all-predicate/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/reporting-any-all-predicate/providers.json +++ b/fixtures/conformance/reporting-any-all-predicate/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-boolean-measures/providers.json b/fixtures/conformance/reporting-boolean-measures/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/reporting-boolean-measures/providers.json +++ b/fixtures/conformance/reporting-boolean-measures/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-cross-package-short-names/providers.json b/fixtures/conformance/reporting-cross-package-short-names/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/reporting-cross-package-short-names/providers.json +++ b/fixtures/conformance/reporting-cross-package-short-names/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-derived-measures/providers.json b/fixtures/conformance/reporting-derived-measures/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-derived-measures/providers.json +++ b/fixtures/conformance/reporting-derived-measures/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-inherited-members/providers.json b/fixtures/conformance/reporting-inherited-members/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-inherited-members/providers.json +++ b/fixtures/conformance/reporting-inherited-members/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-ratio-numeric-min-max/providers.json b/fixtures/conformance/reporting-ratio-numeric-min-max/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/reporting-ratio-numeric-min-max/providers.json +++ b/fixtures/conformance/reporting-ratio-numeric-min-max/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-relative-startof/providers.json b/fixtures/conformance/reporting-relative-startof/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-relative-startof/providers.json +++ b/fixtures/conformance/reporting-relative-startof/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-spine-and-default/providers.json b/fixtures/conformance/reporting-spine-and-default/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-spine-and-default/providers.json +++ b/fixtures/conformance/reporting-spine-and-default/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-spine-inherited/providers.json b/fixtures/conformance/reporting-spine-inherited/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-spine-inherited/providers.json +++ b/fixtures/conformance/reporting-spine-inherited/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-value-object-members/providers.json b/fixtures/conformance/reporting-value-object-members/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-value-object-members/providers.json +++ b/fixtures/conformance/reporting-value-object-members/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-vocabulary/providers.json b/fixtures/conformance/reporting-vocabulary/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-vocabulary/providers.json +++ b/fixtures/conformance/reporting-vocabulary/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/requirement-level-integral-float/providers.json b/fixtures/conformance/requirement-level-integral-float/providers.json index 8ec88fc091..3aea349412 100644 --- a/fixtures/conformance/requirement-level-integral-float/providers.json +++ b/fixtures/conformance/requirement-level-integral-float/providers.json @@ -1 +1 @@ -["metaobjects-core-types"] +["metaobjects-core-types", "metaobjects-requirements"] diff --git a/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/expected-error.txt b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/expected-error.txt new file mode 100644 index 0000000000..1b1b47a76d --- /dev/null +++ b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/expected-error.txt @@ -0,0 +1 @@ +render verify failed: ERR_VAR_NOT_ON_PAYLOAD diff --git a/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/meta.json b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/meta.json new file mode 100644 index 0000000000..9742c6d544 --- /dev/null +++ b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "a variable absent from the payload (undefined, not null) raises; the message is matched as a prefix, since only the Mustache path can name the variable" } diff --git a/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/payload.json b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/payload.json new file mode 100644 index 0000000000..8f842fdc28 --- /dev/null +++ b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/payload.json @@ -0,0 +1 @@ +{ "name": "Ada" } diff --git a/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/template.jinja b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/template.jinja new file mode 100644 index 0000000000..54f7a86fed --- /dev/null +++ b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/template.jinja @@ -0,0 +1 @@ +Hi {{ nmae }}! diff --git a/fixtures/jinja-render-conformance/jinja-render-variables/expected.txt b/fixtures/jinja-render-conformance/jinja-render-variables/expected.txt index 374a93eb10..643c617253 100644 --- a/fixtures/jinja-render-conformance/jinja-render-variables/expected.txt +++ b/fixtures/jinja-render-conformance/jinja-render-variables/expected.txt @@ -1,4 +1,4 @@ Hello Ada count=3 ratio=2.5 whole=2 -active=true off=false none=[] missing=[] +active=true off=false none=[] first tag: math diff --git a/fixtures/jinja-render-conformance/jinja-render-variables/meta.json b/fixtures/jinja-render-conformance/jinja-render-variables/meta.json index b59e20d939..c3f2693a15 100644 --- a/fixtures/jinja-render-conformance/jinja-render-variables/meta.json +++ b/fixtures/jinja-render-conformance/jinja-render-variables/meta.json @@ -1,4 +1,4 @@ { "format": "text", - "note": "attribute and subscript access, scalar printing (bool, whole float, null, missing)" + "note": "attribute and subscript access, scalar printing (bool, whole float, null; a missing variable raises, see jinja-render-error-missing-variable)" } diff --git a/fixtures/jinja-render-conformance/jinja-render-variables/template.jinja b/fixtures/jinja-render-conformance/jinja-render-variables/template.jinja index 7b85505cc4..f99d4ec34e 100644 --- a/fixtures/jinja-render-conformance/jinja-render-variables/template.jinja +++ b/fixtures/jinja-render-conformance/jinja-render-variables/template.jinja @@ -1,4 +1,4 @@ Hello {{ user.name }} <{{ user["email"] }}> count={{ count }} ratio={{ ratio }} whole={{ whole }} -active={{ active }} off={{ off }} none=[{{ nothing }}] missing=[{{ absent }}] +active={{ active }} off={{ off }} none=[{{ nothing }}] first tag: {{ tags[0] }} diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index 068818332f..2234069901 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -13,7 +13,7 @@ provider owns. This is the ownership lens over the same vocabulary Core metaobjects metamodel types and subtypes. -**Owns (registers):** `attr.base`, `attr.boolean`, `attr.class`, `attr.double`, `attr.expression`, `attr.filter`, `attr.int`, `attr.intMap`, `attr.long`, `attr.properties`, `attr.string`, `field.base`, `field.boolean`, `field.currency`, `field.date`, `field.decimal`, `field.double`, `field.duration`, `field.enum`, `field.float`, `field.inet`, `field.int`, `field.long`, `field.map`, `field.object`, `field.string`, `field.time`, `field.timestamp`, `field.uri`, `field.uuid`, `identity.primary`, `identity.reference`, `identity.secondary`, `layout.base`, `layout.dataGrid`, `object.base`, `object.entity`, `object.projection`, `object.report`, `object.value`, `origin.aggregate`, `origin.base`, `origin.computed`, `origin.first`, `origin.passthrough`, `relationship.aggregation`, `relationship.association`, `relationship.base`, `relationship.composition`, `source.base`, `source.rdb`, `template.base`, `template.output`, `template.prompt`, `template.toolcall`, `validator.array`, `validator.atLeastOne`, `validator.base`, `validator.comparison`, `validator.exactlyOne`, `validator.length`, `validator.numeric`, `validator.presentIff`, `validator.regex`, `validator.required`, `validator.requiredWhen`, `view.base`, `view.checkbox`, `view.currency`, `view.date`, `view.dropdown`, `view.hidden`, `view.hotlink`, `view.image`, `view.month`, `view.number`, `view.password`, `view.radio`, `view.text`, `view.textarea`, `view.web` +**Owns (registers):** `attr.base`, `attr.boolean`, `attr.class`, `attr.double`, `attr.expression`, `attr.filter`, `attr.int`, `attr.intMap`, `attr.long`, `attr.properties`, `attr.string`, `field.base`, `field.boolean`, `field.currency`, `field.date`, `field.decimal`, `field.double`, `field.duration`, `field.enum`, `field.float`, `field.inet`, `field.int`, `field.long`, `field.map`, `field.object`, `field.string`, `field.time`, `field.timestamp`, `field.uri`, `field.uuid`, `identity.primary`, `identity.reference`, `identity.secondary`, `layout.base`, `layout.dataGrid`, `object.base`, `object.entity`, `object.projection`, `object.value`, `origin.aggregate`, `origin.base`, `origin.computed`, `origin.first`, `origin.passthrough`, `relationship.aggregation`, `relationship.association`, `relationship.base`, `relationship.composition`, `source.base`, `source.rdb`, `template.base`, `template.output`, `template.prompt`, `template.toolcall`, `validator.array`, `validator.atLeastOne`, `validator.base`, `validator.comparison`, `validator.exactlyOne`, `validator.length`, `validator.numeric`, `validator.presentIff`, `validator.regex`, `validator.required`, `validator.requiredWhen`, `view.base`, `view.checkbox`, `view.currency`, `view.date`, `view.dropdown`, `view.hidden`, `view.hotlink`, `view.image`, `view.month`, `view.number`, `view.password`, `view.radio`, `view.text`, `view.textarea`, `view.web` **Contributes attributes:** @@ -32,10 +32,9 @@ Core metaobjects metamodel types and subtypes. - `object.base`: `@object`, `@objectAdapter` - `object.entity`: `@collectionName`, `@discriminator`, `@discriminatorValue` - `object.projection`: `@collectionName`, `@filter` -- `object.report`: `@collectionName`, `@dimensions`, `@filter`, `@from`, `@measures`, `@segment`, `@spine` -- `origin.aggregate`: `@agg`, `@distinct`, `@filter`, `@of`, `@orderBy`, `@segment`, `@via` +- `origin.aggregate`: `@agg`, `@distinct`, `@filter`, `@of`, `@orderBy`, `@via` - `origin.computed`: `@expr` -- `origin.first`: `@filter`, `@of`, `@orderBy`, `@segment`, `@via` +- `origin.first`: `@filter`, `@of`, `@orderBy`, `@via` - `origin.passthrough`: `@convert`, `@from`, `@via` - `relationship.aggregation`: `@cardinality`, `@objectRef`, `@onDelete`, `@onUpdate`, `@sourceRefField`, `@symmetric`, `@through` - `relationship.association`: `@cardinality`, `@objectRef`, `@onDelete`, `@onUpdate`, `@sourceRefField`, `@symmetric`, `@through` @@ -127,6 +126,35 @@ Prompt / AI + serialization domain — @xmlText / @example / @instruction field - `field.uuid`: `@example`, `@instruction`, `@xmlText` - `object.value`: `@normalize` +## metaobjects-reporting + +Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first. + +**Owns (registers):** `dimension.attribute`, `dimension.time`, `measure.aggregate`, `measure.derived`, `measure.ratio`, `object.report`, `segment.filter` + +**Contributes attributes:** + +- `dimension.attribute`: `@of`, `@via` +- `dimension.time`: `@grains`, `@of`, `@via` +- `measure.aggregate`: `@agg`, `@default`, `@distinct`, `@filter`, `@of`, `@segment` +- `measure.derived`: `@expr` +- `measure.ratio`: `@default`, `@denominator`, `@numerator` +- `object.report`: `@collectionName`, `@dimensions`, `@filter`, `@from`, `@measures`, `@segment`, `@spine` +- `origin.aggregate`: `@segment` +- `origin.first`: `@segment` +- `segment.filter`: `@filter` + +## metaobjects-requirements + +Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify. + +**Owns (registers):** `requirement.architectural`, `requirement.functional` + +**Contributes attributes:** + +- `requirement.architectural`: `@counterexample`, `@disposition`, `@implementedBy`, `@level`, `@statement`, `@status`, `@supersededBy`, `@trackedBy` +- `requirement.functional`: `@counterexample`, `@disposition`, `@implementedBy`, `@level`, `@statement`, `@status`, `@supersededBy`, `@trackedBy` + ## metaobjects-rules Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum). diff --git a/fixtures/metamodel-docs/expected/types/dimension.md b/fixtures/metamodel-docs/expected/types/dimension.md index 9ccb48ae62..d588875036 100644 --- a/fixtures/metamodel-docs/expected/types/dimension.md +++ b/fixtures/metamodel-docs/expected/types/dimension.md @@ -14,14 +14,16 @@ documentation attributes are omitted here (see [providers.md](../providers.md)). 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. +**Owning provider:** metaobjects-reporting + **When to use:** A column a dashboard groups by: product, status, region. Declare it once on the fact entity and reference it by name from reports. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@of` | string | yes | | | — | Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own. | -| `@via` | string | no | | | — | Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference. | +| `@of` | string | yes | | | metaobjects-reporting | Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own. | +| `@via` | string | no | | | metaobjects-reporting | Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference. | **Allowed children** @@ -31,15 +33,17 @@ _No structural children._ 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). +**Owning provider:** metaobjects-reporting + **When to use:** Per-day, per-week or per-month series on a dashboard. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@grains` | string[] | yes | | `hour`, `day`, `week`, `month`, `quarter`, `year` | — | The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date. | -| `@of` | string | yes | | | — | Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object. | -| `@via` | string | no | | | — | Optional dotted to-one relationship path, as on dimension.attribute. | +| `@grains` | string[] | yes | | `hour`, `day`, `week`, `month`, `quarter`, `year` | metaobjects-reporting | The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date. | +| `@of` | string | yes | | | metaobjects-reporting | Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object. | +| `@via` | string | no | | | metaobjects-reporting | Optional dotted to-one relationship path, as on dimension.attribute. | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/measure.md b/fixtures/metamodel-docs/expected/types/measure.md index a4a0f90669..4e071a1a36 100644 --- a/fixtures/metamodel-docs/expected/types/measure.md +++ b/fixtures/metamodel-docs/expected/types/measure.md @@ -14,18 +14,20 @@ documentation attributes are omitted here (see [providers.md](../providers.md)). A named aggregate over the declaring entity's own rows (FR-044). @agg count without @distinct counts rows; with @distinct it counts distinct values of @of (a list in @of is a distinct count of the tuple). Unlike origin.aggregate, count is NOT distinct by default: a measure aggregates its own rows and dimensions reach only to-one paths, so no join inflates it. +**Owning provider:** metaobjects-reporting + **When to use:** A number a dashboard shows: revenue, purchases, distinct buyers, last activity. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@agg` | string | yes | | `count`, `sum`, `avg`, `min`, `max`, `any`, `all` | — | The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment. | -| `@default` | int | no | | | — | Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null), on min/max over a field that is not numeric, and on @agg any/all unless it is 0 (false) or 1 (true). A ratio's operand carries its own @default into the ratio. | -| `@distinct` | boolean | no | | | — | Count distinct values. Legal only with @agg: count. | -| `@filter` | filter | no | | | — | Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: "-P7D" }). Combines with @segment by AND. | -| `@of` | string[] | no | | | — | Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows. | -| `@segment` | string | no | | | — | Optional name of a segment declared on the same entity. Combines with @filter by AND. | +| `@agg` | string | yes | | `count`, `sum`, `avg`, `min`, `max`, `any`, `all` | metaobjects-reporting | The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment. | +| `@default` | int | no | | | metaobjects-reporting | Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null), on min/max over a field that is not numeric, and on @agg any/all unless it is 0 (false) or 1 (true). A ratio's operand carries its own @default into the ratio. | +| `@distinct` | boolean | no | | | metaobjects-reporting | Count distinct values. Legal only with @agg: count. | +| `@filter` | filter | no | | | metaobjects-reporting | Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: "-P7D" }). Combines with @segment by AND. | +| `@of` | string[] | no | | | metaobjects-reporting | Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows. | +| `@segment` | string | no | | | metaobjects-reporting | Optional name of a segment declared on the same entity. Combines with @filter by AND. | **Allowed children** @@ -35,13 +37,15 @@ _No structural children._ A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension. +**Owning provider:** metaobjects-reporting + **When to use:** A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds). **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@expr` | expression | yes | | | — | The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add \| subtract \| multiply \| divide, args: [a, b] } combines two operands. | +| `@expr` | expression | yes | | | metaobjects-reporting | The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add \| subtract \| multiply \| divide, args: [a, b] } combines two operands. | **Allowed children** @@ -51,15 +55,17 @@ _No structural children._ A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null. +**Owning provider:** metaobjects-reporting + **When to use:** Averages per unit that are not a plain avg: average days engaged per starter. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@default` | int | no | | | — | Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio. | -| `@denominator` | string | yes | | | — | Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field. | -| `@numerator` | string | yes | | | — | Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field. | +| `@default` | int | no | | | metaobjects-reporting | Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio. | +| `@denominator` | string | yes | | | metaobjects-reporting | Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field. | +| `@numerator` | string | yes | | | metaobjects-reporting | Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field. | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/object.md b/fixtures/metamodel-docs/expected/types/object.md index b24ba50219..7d06693065 100644 --- a/fixtures/metamodel-docs/expected/types/object.md +++ b/fixtures/metamodel-docs/expected/types/object.md @@ -102,7 +102,7 @@ A derived read-only representation of entities. Its fields are extends-bound / o 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. -**Owning provider:** metaobjects-core-types +**Owning provider:** metaobjects-reporting **When to use:** Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries. @@ -110,15 +110,15 @@ A declared report (FR-044): a fixed combination of dimensions and measures of ON | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@collectionName` | string | no | | | metaobjects-core-types | The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | -| `@dimensions` | string[] | no | | | metaobjects-core-types | Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row. | -| `@filter` | filter | no | | | metaobjects-core-types | Optional row scope over @from's fields; may use relative-date values. | -| `@from` | string | yes | | | metaobjects-core-types | The object.entity whose rows the report aggregates. | -| `@measures` | string[] | yes | | | metaobjects-core-types | Measure names of @from. | +| `@collectionName` | string | no | | | metaobjects-reporting | The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | +| `@dimensions` | string[] | no | | | metaobjects-reporting | Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row. | +| `@filter` | filter | no | | | metaobjects-reporting | Optional row scope over @from's fields; may use relative-date values. | +| `@from` | string | yes | | | metaobjects-reporting | The object.entity whose rows the report aggregates. | +| `@measures` | string[] | yes | | | metaobjects-reporting | Measure names of @from. | | `@object` | string | no | | | metaobjects-core-types | The native class an object binds to (ADR-0001), in place of its default runtime class: on the JVM, a fully-qualified class name. Cross-port vocabulary only Java implements so far; every port loads and type-checks it, and the others do not act on it yet. | | `@objectAdapter` | string | no | | | metaobjects-core-types | JVM-only (ADR-0005): the fully-qualified name of an ObjectAdapter that takes over value access for this object's instances. Every port loads and type-checks it; only Java and Kotlin act on it. | -| `@segment` | string | no | | | metaobjects-core-types | Optional segment of @from scoping the rows. | -| `@spine` | string | no | | | metaobjects-core-types | Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report. | +| `@segment` | string | no | | | metaobjects-reporting | Optional segment of @from scoping the rows. | +| `@spine` | string | no | | | metaobjects-reporting | Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report. | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/origin.md b/fixtures/metamodel-docs/expected/types/origin.md index a592204dfe..bf151b069e 100644 --- a/fixtures/metamodel-docs/expected/types/origin.md +++ b/fixtures/metamodel-docs/expected/types/origin.md @@ -29,7 +29,7 @@ A value reduced from the related row-set reached along a relationship path (@via | `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or — correlated-filter — { field: "" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19). | | `@of` | string | no | | | metaobjects-core-types | Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column). | | `@orderBy` | string[] | no | | | metaobjects-core-types | Ordering keys as 'field[:asc\|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax. | -| `@segment` | string | no | | | metaobjects-core-types | Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | +| `@segment` | string | no | | | metaobjects-reporting | Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | | `@via` | string | no | | | metaobjects-core-types | Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029). | **Allowed children** @@ -85,7 +85,7 @@ The single related row selected by @orderBy along @via, projecting its @of colum | `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or — correlated-filter — { field: "" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19). | | `@of` | string | yes | | | metaobjects-core-types | Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine). | | `@orderBy` | string[] | yes | | | metaobjects-core-types | Ordering keys as 'field[:asc\|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax. | -| `@segment` | string | no | | | metaobjects-core-types | Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | +| `@segment` | string | no | | | metaobjects-reporting | Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | | `@via` | string | no | | | metaobjects-core-types | Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029). | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/requirement.md b/fixtures/metamodel-docs/expected/types/requirement.md index 4942bea566..3362a94e02 100644 --- a/fixtures/metamodel-docs/expected/types/requirement.md +++ b/fixtures/metamodel-docs/expected/types/requirement.md @@ -14,20 +14,22 @@ documentation attributes are omitted here (see [providers.md](../providers.md)). How the system is built, applied uniformly across the model. Its check is UNIVERSALITY, the opposite polarity to a functional requirement. What `meta verify` enforces is that a live or partial policy is applied at all — one claiming nothing is an error — not that each node it claims complies. Flat by default and object-independent; it may optionally sit in a levelled tree when a quality taxonomy is being used to organise non-functional requirements. +**Owning provider:** metaobjects-requirements + **When to use:** Something exists because every entity here looks like this — a uuid primary key, an @autoSet createdAt, a change-attribution column, tenant scoping. The discriminator is mechanical: did this exist because someone asked for something, or because it is the architecture? For a non-functional tree, an established quality taxonomy makes a good fixed upper structure (e.g. an ISO/IEC 25010 characteristic at L1, its sub-characteristic or a control-catalogue category at L2), with the model-binding claims at L4 and L5 as usual. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@counterexample` | string | yes | | | — | What breaking it looks like — the node that would contradict it. A STATIC falsifiability test, not a state. This is what makes universality checkable. Renamed from @violation in 0.24.0, which read as a status. | -| `@disposition` | string | no | | `accepted`, `deferred` | — | As on requirement.functional. On an architectural requirement, accepted is the common and important case: a policy that is genuinely not universal, where the exceptions are known and tolerated, is more honest as partial+accepted than as a live claim nobody audits. | -| `@implementedBy` | string[] | no | | | — | FQN references to the nodes applying this policy. High fan-out is normal and expected: one uuid-primary-key requirement is claimed by every entity. | -| `@level` | int | no | | | — | OPTIONAL here, unlike on a functional requirement where it is required. ABSENT means a flat, object-independent policy that may reference the model directly — the original and still the default form. PRESENT means this node sits in a levelled tree, and then the same rules as functional apply: nesting must agree with the level, and only L4/L5 may carry @implementedBy. Levelling is opt-in so that adding a taxonomy on top of existing flat policies does not invalidate them. | -| `@statement` | string | yes | | | — | The policy, in one sentence. | -| `@status` | string | yes | | `planned`, `live`, `partial`, `retired` | — | As on requirement.functional. A live or partial architectural requirement claimed by NOTHING is an error: a policy declared and applied to nothing. planned is exempt from that check — it is not applied yet by definition — and retired is exempt because a withdrawn policy governs nothing. | -| `@supersededBy` | string | no | | | — | The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not. | -| `@trackedBy` | string[] | no | | | — | As on requirement.functional. Issue or ticket references for outstanding work; free-form, not resolved. | +| `@counterexample` | string | yes | | | metaobjects-requirements | What breaking it looks like — the node that would contradict it. A STATIC falsifiability test, not a state. This is what makes universality checkable. Renamed from @violation in 0.24.0, which read as a status. | +| `@disposition` | string | no | | `accepted`, `deferred` | metaobjects-requirements | As on requirement.functional. On an architectural requirement, accepted is the common and important case: a policy that is genuinely not universal, where the exceptions are known and tolerated, is more honest as partial+accepted than as a live claim nobody audits. | +| `@implementedBy` | string[] | no | | | metaobjects-requirements | FQN references to the nodes applying this policy. High fan-out is normal and expected: one uuid-primary-key requirement is claimed by every entity. | +| `@level` | int | no | | | metaobjects-requirements | OPTIONAL here, unlike on a functional requirement where it is required. ABSENT means a flat, object-independent policy that may reference the model directly — the original and still the default form. PRESENT means this node sits in a levelled tree, and then the same rules as functional apply: nesting must agree with the level, and only L4/L5 may carry @implementedBy. Levelling is opt-in so that adding a taxonomy on top of existing flat policies does not invalidate them. | +| `@statement` | string | yes | | | metaobjects-requirements | The policy, in one sentence. | +| `@status` | string | yes | | `planned`, `live`, `partial`, `retired` | metaobjects-requirements | As on requirement.functional. A live or partial architectural requirement claimed by NOTHING is an error: a policy declared and applied to nothing. planned is exempt from that check — it is not applied yet by definition — and retired is exempt because a withdrawn policy governs nothing. | +| `@supersededBy` | string | no | | | metaobjects-requirements | The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not. | +| `@trackedBy` | string[] | no | | | metaobjects-requirements | As on requirement.functional. Issue or ticket references for outstanding work; free-form, not resolved. | **Allowed children** @@ -37,20 +39,22 @@ How the system is built, applied uniformly across the model. Its check is UNIVER What the product does for a user, stated as one violable claim. Its check is EXISTENCE, run by `meta verify`: a live or partial claim with no implementing node anywhere in its subtree is a warning, and a named node that no longer exists is an error. Hierarchy is nesting — an L1 solution contains its L2 segments, which contain L3 services, and so on down to the levels that reference the model. +**Owning provider:** metaobjects-requirements + **When to use:** Something exists because someone asked for it. L1-L3 are levels of ABSTRACTION AND OWNERSHIP in the problem domain — whose need is this, and at what altitude — and are never a directory, package, deployable or module. Binding to technical constructs happens only at L4 (an object) and L5 (a member), which is the allocation step. Test every node: if a refactor that changes no behaviour would force it to move, its level is wrong. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@counterexample` | string | yes | | | — | What breaking it looks like, in one sentence — a STATIC falsifiability test, authored once, never a state. A requirement MUST be violable: 'every entity has a uuid primary key' is (point at one with a composite string key); 'things are persisted' is not, and is a description rather than a requirement. Renamed from @violation in 0.24.0, which read as a status. | -| `@disposition` | string | no | | `accepted`, `deferred` | — | What has been DECIDED about outstanding work — a different question from whether the work is done, which is what @status answers. accepted: the gap is understood and deliberately not being closed. deferred: it will be closed, but not now. ABSENT MEANS UNDECIDED, which is a real and useful state — it is what an unreviewed gap looks like, and it is the one a review should be able to find. Meaningful on planned and partial only; on a status with no outstanding work it is a WARNING. Deliberately NOT a workflow vocabulary: which sprint, who owns it and whether it is in progress belong in the tracker named by @trackedBy, because two systems holding that answer will drift and only one of them is refreshed daily. | -| `@implementedBy` | string[] | no | | | — | FQN references to the model nodes realising this requirement. Legal on level 4 (an object) and level 5 (a field, view or identity) only; an organisational level carrying it is ERR_REQUIREMENT_LINK_ABOVE_FLOOR. Many-to-many by construction — several requirements may name the same node. | -| `@level` | int | yes | | | — | 1 solution, 2 segment, 3 service, 4 object, 5 member. L1-L3 are levels of abstraction and ownership in the problem domain, NOT of code structure. Nesting depth must agree with it; skipping a level is legal, going back up is not. | -| `@statement` | string | yes | | | — | What the capability is, in one sentence. | -| `@status` | string | yes | | `planned`, `live`, `partial`, `retired` | — | planned intended but not built yet; live implemented and in use; partial implemented with known gaps; retired BUILT THEN DELIBERATELY REMOVED — it must not be rebuilt. A requirement is PRESCRIPTIVE: it states what SHOULD be true and never journals what happened, and retired satisfies that because it states a prohibition in force, falsifiable by the capability reappearing. On retired, @implementedBy is REFUSED at load (ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS) — a retired capability has no implementation by definition, so its references cannot dangle because they cannot exist; @supersededBy names the requirement that replaced it. A dangling @implementedBy is an ERROR on live/partial (the model moved, the requirement is stale) and ALLOWED on planned, where the nodes do not exist YET. Neither planned nor retired contributes to object coverage: planning a capability must not silence the warning that nothing implements it, and neither must retiring one. | -| `@supersededBy` | string | no | | | — | The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not. | -| `@trackedBy` | string[] | no | | | — | Issue or ticket references for outstanding work — a URL, an owner/repo#123 shorthand, or a tracker key. Free-form and NOT resolved by verify, which does not reach the network; nothing here is checked to exist. Its job is to stop a deferred gap becoming invisible, so verify warns when a deferred requirement names no ticket. Also the right place to link the ticket that a planned requirement will be built under. | +| `@counterexample` | string | yes | | | metaobjects-requirements | What breaking it looks like, in one sentence — a STATIC falsifiability test, authored once, never a state. A requirement MUST be violable: 'every entity has a uuid primary key' is (point at one with a composite string key); 'things are persisted' is not, and is a description rather than a requirement. Renamed from @violation in 0.24.0, which read as a status. | +| `@disposition` | string | no | | `accepted`, `deferred` | metaobjects-requirements | What has been DECIDED about outstanding work — a different question from whether the work is done, which is what @status answers. accepted: the gap is understood and deliberately not being closed. deferred: it will be closed, but not now. ABSENT MEANS UNDECIDED, which is a real and useful state — it is what an unreviewed gap looks like, and it is the one a review should be able to find. Meaningful on planned and partial only; on a status with no outstanding work it is a WARNING. Deliberately NOT a workflow vocabulary: which sprint, who owns it and whether it is in progress belong in the tracker named by @trackedBy, because two systems holding that answer will drift and only one of them is refreshed daily. | +| `@implementedBy` | string[] | no | | | metaobjects-requirements | FQN references to the model nodes realising this requirement. Legal on level 4 (an object) and level 5 (a field, view or identity) only; an organisational level carrying it is ERR_REQUIREMENT_LINK_ABOVE_FLOOR. Many-to-many by construction — several requirements may name the same node. | +| `@level` | int | yes | | | metaobjects-requirements | 1 solution, 2 segment, 3 service, 4 object, 5 member. L1-L3 are levels of abstraction and ownership in the problem domain, NOT of code structure. Nesting depth must agree with it; skipping a level is legal, going back up is not. | +| `@statement` | string | yes | | | metaobjects-requirements | What the capability is, in one sentence. | +| `@status` | string | yes | | `planned`, `live`, `partial`, `retired` | metaobjects-requirements | planned intended but not built yet; live implemented and in use; partial implemented with known gaps; retired BUILT THEN DELIBERATELY REMOVED — it must not be rebuilt. A requirement is PRESCRIPTIVE: it states what SHOULD be true and never journals what happened, and retired satisfies that because it states a prohibition in force, falsifiable by the capability reappearing. On retired, @implementedBy is REFUSED at load (ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS) — a retired capability has no implementation by definition, so its references cannot dangle because they cannot exist; @supersededBy names the requirement that replaced it. A dangling @implementedBy is an ERROR on live/partial (the model moved, the requirement is stale) and ALLOWED on planned, where the nodes do not exist YET. Neither planned nor retired contributes to object coverage: planning a capability must not silence the warning that nothing implements it, and neither must retiring one. | +| `@supersededBy` | string | no | | | metaobjects-requirements | The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not. | +| `@trackedBy` | string[] | no | | | metaobjects-requirements | Issue or ticket references for outstanding work — a URL, an owner/repo#123 shorthand, or a tracker key. Free-form and NOT resolved by verify, which does not reach the network; nothing here is checked to exist. Its job is to stop a deferred gap becoming invisible, so verify warns when a deferred requirement names no ticket. Also the right place to link the ticket that a planned requirement will be built under. | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/segment.md b/fixtures/metamodel-docs/expected/types/segment.md index ce9f64a6f5..2ba16ba92a 100644 --- a/fixtures/metamodel-docs/expected/types/segment.md +++ b/fixtures/metamodel-docs/expected/types/segment.md @@ -14,13 +14,15 @@ documentation attributes are omitted here (see [providers.md](../providers.md)). A named, reusable row filter on the declaring entity (FR-044). Measures and reports reference it by name; exporters emit it as a named segment. +**Owning provider:** metaobjects-reporting + **When to use:** The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@filter` | filter | yes | | | — | The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values. | +| `@filter` | filter | yes | | | metaobjects-reporting | The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values. | **Allowed children** diff --git a/fixtures/registry-conformance/core-vocabulary.pin.json b/fixtures/registry-conformance/core-vocabulary.pin.json index b668375f3b..9ad35e8985 100644 --- a/fixtures/registry-conformance/core-vocabulary.pin.json +++ b/fixtures/registry-conformance/core-vocabulary.pin.json @@ -45,21 +45,6 @@ "attrs": [], "children": [] }, - "dimension.attribute": { - "attrs": [ - "of", - "via" - ], - "children": [] - }, - "dimension.time": { - "attrs": [ - "grains", - "of", - "via" - ], - "children": [] - }, "field.base": { "attrs": [ "default", @@ -203,31 +188,6 @@ "attrs": [], "children": [] }, - "measure.aggregate": { - "attrs": [ - "agg", - "default", - "distinct", - "filter", - "of", - "segment" - ], - "children": [] - }, - "measure.derived": { - "attrs": [ - "expr" - ], - "children": [] - }, - "measure.ratio": { - "attrs": [ - "default", - "denominator", - "numerator" - ], - "children": [] - }, "object.base": { "attrs": [ "object", @@ -249,10 +209,7 @@ "discriminatorValue" ], "children": [ - "dimension.*:*", - "measure.*:*", "relationship.*:*", - "segment.*:*", "template.*:*" ] }, @@ -263,18 +220,6 @@ ], "children": [] }, - "object.report": { - "attrs": [ - "collectionName", - "dimensions", - "filter", - "from", - "measures", - "segment", - "spine" - ], - "children": [] - }, "object.value": { "attrs": [], "children": [ @@ -288,7 +233,6 @@ "filter", "of", "orderBy", - "segment", "via" ], "children": [] @@ -308,7 +252,6 @@ "filter", "of", "orderBy", - "segment", "via" ], "children": [] @@ -369,42 +312,6 @@ ], "children": [] }, - "requirement.architectural": { - "attrs": [ - "counterexample", - "disposition", - "implementedBy", - "level", - "statement", - "status", - "supersededBy", - "trackedBy" - ], - "children": [ - "requirement.*:*" - ] - }, - "requirement.functional": { - "attrs": [ - "counterexample", - "disposition", - "implementedBy", - "level", - "statement", - "status", - "supersededBy", - "trackedBy" - ], - "children": [ - "requirement.*:*" - ] - }, - "segment.filter": { - "attrs": [ - "filter" - ], - "children": [] - }, "source.base": { "attrs": [], "children": [] diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 6355711847..cb71274e0e 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -3440,7 +3440,9 @@ { "childType": "requirement", "childSubType": "*", - "childName": "*" + "childName": "*", + "min": 0, + "max": null }, { "childType": "template", diff --git a/fixtures/registry-conformance/providers.json b/fixtures/registry-conformance/providers.json index dd240c3b33..fee207043c 100644 --- a/fixtures/registry-conformance/providers.json +++ b/fixtures/registry-conformance/providers.json @@ -56,6 +56,20 @@ "object.value" ] }, + "metaobjects-reporting": { + "declaresTypes": true, + "projectsOnto": [ + "object.entity", + "origin.aggregate", + "origin.first" + ] + }, + "metaobjects-requirements": { + "declaresTypes": true, + "projectsOnto": [ + "metadata.root" + ] + }, "metaobjects-rules": { "declaresTypes": true, "projectsOnto": [ diff --git a/fixtures/render-conformance/render-dotted-path-lookup/expected.txt b/fixtures/render-conformance/render-dotted-path-lookup/expected.txt index 06ee3a698e..e051441bf1 100644 --- a/fixtures/render-conformance/render-dotted-path-lookup/expected.txt +++ b/fixtures/render-conformance/render-dotted-path-lookup/expected.txt @@ -1,5 +1,3 @@ name: Ada email: ada@example.test role: admin -missing-leaf: [] -missing-mid: [] diff --git a/fixtures/render-conformance/render-dotted-path-lookup/meta.json b/fixtures/render-conformance/render-dotted-path-lookup/meta.json index bfcc8270e1..29d3cffdeb 100644 --- a/fixtures/render-conformance/render-dotted-path-lookup/meta.json +++ b/fixtures/render-conformance/render-dotted-path-lookup/meta.json @@ -1 +1 @@ -{ "format": "text", "note": "dotted-path interpolation {{user.profile.name}} walks nested objects" } +{ "format": "text", "note": "dotted-path interpolation {{user.profile.name}} walks nested objects; a missing leaf or middle raises, see render-error-missing-dotted-path" } diff --git a/fixtures/render-conformance/render-dotted-path-lookup/template.mustache b/fixtures/render-conformance/render-dotted-path-lookup/template.mustache index f5e6c22d66..23400f6240 100644 --- a/fixtures/render-conformance/render-dotted-path-lookup/template.mustache +++ b/fixtures/render-conformance/render-dotted-path-lookup/template.mustache @@ -1,5 +1,3 @@ name: {{user.profile.name}} email: {{user.profile.email}} role: {{user.roles.primary}} -missing-leaf: [{{user.profile.missing}}] -missing-mid: [{{user.unknown.name}}] diff --git a/fixtures/render-conformance/render-error-missing-dotted-path/expected-error.txt b/fixtures/render-conformance/render-error-missing-dotted-path/expected-error.txt new file mode 100644 index 0000000000..0f0287cd3d --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-dotted-path/expected-error.txt @@ -0,0 +1 @@ +render verify failed: ERR_VAR_NOT_ON_PAYLOAD (user.profile.missing) diff --git a/fixtures/render-conformance/render-error-missing-dotted-path/meta.json b/fixtures/render-conformance/render-error-missing-dotted-path/meta.json new file mode 100644 index 0000000000..f569ca276a --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-dotted-path/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "a dotted path that fails to resolve at any step is a missing variable and raises" } diff --git a/fixtures/render-conformance/render-error-missing-dotted-path/payload.json b/fixtures/render-conformance/render-error-missing-dotted-path/payload.json new file mode 100644 index 0000000000..37b728c178 --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-dotted-path/payload.json @@ -0,0 +1,12 @@ +{ + "user": { + "profile": { + "name": "Ada", + "email": "ada@example.test" + }, + "roles": { + "primary": "admin" + } + }, + "missing": {} +} diff --git a/fixtures/render-conformance/render-error-missing-dotted-path/template.mustache b/fixtures/render-conformance/render-error-missing-dotted-path/template.mustache new file mode 100644 index 0000000000..741c7bb780 --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-dotted-path/template.mustache @@ -0,0 +1 @@ +missing-leaf: [{{user.profile.missing}}] diff --git a/fixtures/render-conformance/render-error-missing-variable/expected-error.txt b/fixtures/render-conformance/render-error-missing-variable/expected-error.txt new file mode 100644 index 0000000000..6ad3507422 --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-variable/expected-error.txt @@ -0,0 +1 @@ +render verify failed: ERR_VAR_NOT_ON_PAYLOAD (nmae) diff --git a/fixtures/render-conformance/render-error-missing-variable/meta.json b/fixtures/render-conformance/render-error-missing-variable/meta.json new file mode 100644 index 0000000000..f2aa776ebb --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-variable/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "a variable tag whose name is absent from the payload (undefined, not null) raises on the direct render path, with the same error the verify gate raises; no opt-in needed" } diff --git a/fixtures/render-conformance/render-error-missing-variable/payload.json b/fixtures/render-conformance/render-error-missing-variable/payload.json new file mode 100644 index 0000000000..8f842fdc28 --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-variable/payload.json @@ -0,0 +1 @@ +{ "name": "Ada" } diff --git a/fixtures/render-conformance/render-error-missing-variable/template.mustache b/fixtures/render-conformance/render-error-missing-variable/template.mustache new file mode 100644 index 0000000000..3fdd2536a3 --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-variable/template.mustache @@ -0,0 +1 @@ +Hi {{nmae}}! diff --git a/scripts/check-core-vocabulary-pin.ts b/scripts/check-core-vocabulary-pin.ts index 24640ace34..f3260d46c2 100644 --- a/scripts/check-core-vocabulary-pin.ts +++ b/scripts/check-core-vocabulary-pin.ts @@ -150,7 +150,8 @@ export const FAILURE_GUIDANCE = [ "needs it. Put it in a pack instead: its own provider and spec/metamodel/.json", "(provider id 'metaobjects-'), composed by default if it ships with the library, so a", "project can leave it out. See docs/features/extending-with-providers.md and the worked", - "examples (metaobjects-rules, metaobjects-view-expressions).", + "examples (metaobjects-rules, metaobjects-view-expressions, metaobjects-reporting," + + " metaobjects-requirements).", "Only if a core maintainer has decided this belongs in core, regenerate the pin with", "`bun scripts/check-core-vocabulary-pin.ts --update` and justify it in the PR.", ].join("\n"); diff --git a/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs b/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs index b71aaad737..3fb2a3e008 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs @@ -168,6 +168,8 @@ public static class ConformanceAdapter // (origin.function, @union/@grain): their own packs, outside core-types. ["metaobjects-rules"] = MetaObjects.Core.Rules.RulesMetaDataProvider.Instance, ["metaobjects-view-expressions"] = MetaObjects.Persistence.ViewExpressions.ViewExpressionsMetaDataProvider.Instance, + ["metaobjects-reporting"] = MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + ["metaobjects-requirements"] = MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, ["metaobjects-prompt"] = MetaObjects.Template.PromptMetaDataProvider.Instance, // Back-compat alias: pre-rename fixtures (and other ports' fixtures) still name the // provider "metaobjects-template"; map it to the renamed prompt provider — the same diff --git a/server/csharp/MetaObjects.Conformance.Tests/CoreTypesTests.cs b/server/csharp/MetaObjects.Conformance.Tests/CoreTypesTests.cs index a381c290a1..28675473ae 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/CoreTypesTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/CoreTypesTests.cs @@ -39,7 +39,7 @@ public void Core_provider_factory_builds_the_right_node_class() // ------------------------------------------------------------------ private static TypeRegistry ComposedRegistry() => - Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider, MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance }); [Fact] public void Core_provider_registers_correct_subtypes_for_metadata() diff --git a/server/csharp/MetaObjects.Conformance.Tests/FixtureDiscovery.cs b/server/csharp/MetaObjects.Conformance.Tests/FixtureDiscovery.cs index 0c5d588e28..5b339a88d0 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/FixtureDiscovery.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/FixtureDiscovery.cs @@ -98,6 +98,8 @@ public static class FixtureDiscovery // The business-rules and view-expressions packs are in the default bundle. "metaobjects-rules", "metaobjects-view-expressions", + "metaobjects-reporting", + "metaobjects-requirements", }; /// diff --git a/server/csharp/MetaObjects.Conformance.Tests/FullCoreRegistry.cs b/server/csharp/MetaObjects.Conformance.Tests/FullCoreRegistry.cs index 12aabca357..36836b8c5c 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/FullCoreRegistry.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/FullCoreRegistry.cs @@ -29,6 +29,8 @@ internal static class FullCoreRegistry MetaObjects.Template.PromptMetaDataProvider.Instance, MetaObjects.Core.Rules.RulesMetaDataProvider.Instance, MetaObjects.Persistence.ViewExpressions.ViewExpressionsMetaDataProvider.Instance, + MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, }; /// Compose a fresh registry from the full core bundle. diff --git a/server/csharp/MetaObjects.Conformance.Tests/RegistryManifestConformanceTests.cs b/server/csharp/MetaObjects.Conformance.Tests/RegistryManifestConformanceTests.cs index 5fd76673a0..3558da1ec1 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/RegistryManifestConformanceTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/RegistryManifestConformanceTests.cs @@ -35,6 +35,8 @@ public void Emit_matches_the_committed_cross_port_canonical() MetaObjects.Template.PromptMetaDataProvider.Instance, MetaObjects.Core.Rules.RulesMetaDataProvider.Instance, MetaObjects.Persistence.ViewExpressions.ViewExpressionsMetaDataProvider.Instance, + MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, DocumentationTypes.DocTypesProvider, }); @@ -74,6 +76,8 @@ public void Every_registered_per_type_attr_is_explicitly_classified() MetaObjects.Template.PromptMetaDataProvider.Instance, MetaObjects.Core.Rules.RulesMetaDataProvider.Instance, MetaObjects.Persistence.ViewExpressions.ViewExpressionsMetaDataProvider.Instance, + MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, DocumentationTypes.DocTypesProvider, }); diff --git a/server/csharp/MetaObjects.Conformance.Tests/RequirementsPackLeftOutTests.cs b/server/csharp/MetaObjects.Conformance.Tests/RequirementsPackLeftOutTests.cs new file mode 100644 index 0000000000..44ccf6f041 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/RequirementsPackLeftOutTests.cs @@ -0,0 +1,78 @@ +using MetaObjects.Core.Requirement; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +/// +/// The requirements vocabulary is its own pack (metaobjects-requirements), composed by default. +/// With the pack left out the gate has nothing to read and reports nothing, and a model that declares a +/// requirement fails to load instead. +/// +public class RequirementsPackLeftOutTests +{ + private const string Order = """ + - object.entity: + name: Order + children: + - source.rdb: { table: orders } + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + """; + + private const string Requirement = """ + - requirement.functional: + name: PlaceOrder + level: 4 + status: live + statement: A customer places an order + counterexample: A customer cannot place an order + implementedBy: [app::Order] + """; + + private static string Indent(string block) => + string.Join("\n", block.Split('\n').Select(l => " " + l)); + + private static LoadResult Load(TypeRegistry registry, params string[] blocks) + { + var dir = Directory.CreateTempSubdirectory("mo-req-left-out-").FullName; + try + { + File.WriteAllText(Path.Combine(dir, "meta.app.yaml"), + "metadata:\n package: app\n children:\n" + string.Join("\n", blocks.Select(Indent)) + "\n"); + return MetaDataLoader.FromDirectory(dir, registry, strict: true); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + private static TypeRegistry WithoutPack() => + Provider.ComposeRegistry(CoreTypes.LibraryProviders.Where(p => p.Id != RequirementsMetaDataProvider.ProviderId).ToList()); + + [Fact] + public void A_model_with_no_requirements_loads_and_the_gate_reports_nothing() + { + var result = Load(WithoutPack(), Order); + Assert.Empty(result.Errors.Select(e => e.Code + ": " + e.Message)); + var scan = RequirementCheck.Scan(result.Root); + Assert.Empty(RequirementCheck.Check(result.Root, scan)); + Assert.Null(RequirementCheck.Summarise(result.Root, scan)); + } + + [Fact] + public void A_model_that_declares_a_requirement_fails_to_load_with_ERR_UNKNOWN_TYPE() + { + var result = Load(WithoutPack(), Order, Requirement); + Assert.Contains(result.Errors, e => e.Code == ErrorCode.ERR_UNKNOWN_TYPE); + } + + [Fact] + public void With_the_default_bundle_the_same_requirement_reaches_the_ledger() + { + var result = Load(Provider.ComposeRegistry(CoreTypes.LibraryProviders), Order, Requirement); + Assert.Empty(result.Errors.Select(e => e.Code + ": " + e.Message)); + Assert.Equal(1, RequirementCheck.Summarise(result.Root, RequirementCheck.Scan(result.Root))?.Total); + } +} diff --git a/server/csharp/MetaObjects.Conformance.Tests/YamlConformanceTests.cs b/server/csharp/MetaObjects.Conformance.Tests/YamlConformanceTests.cs index 2cfd704947..af67e04a0d 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/YamlConformanceTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/YamlConformanceTests.cs @@ -203,6 +203,8 @@ private static void RunChecks(YamlFixture fix, List failures) var registry = Provider.ComposeRegistry([ CoreTypes.CoreTypesProvider, MetaObjects.Persistence.Db.DbMetaDataProvider.Instance, + MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, ]); var parseOpts = new ParseOptions(registry) { diff --git a/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs b/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs index 53febefead..dfdb8967c4 100644 --- a/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs +++ b/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs @@ -10,7 +10,7 @@ namespace MetaObjects.Render.Tests; /// template.mustache the entry template /// partials/*.mustache optional partials, referenced as `partials/<name>` /// payload.json the render payload (pre-formatted primitives) -/// expected.txt byte-exact expected output +/// expected.txt byte-exact expected output (or expected-error.txt: the render must fail with that text) /// The same shared corpus is rendered byte-for-byte identically by TS and C#. /// Mirrors typescript/packages/render/test/render-conformance.test.ts. /// @@ -67,9 +67,24 @@ public void RenderMatchesExpected(string name) var format = JsonDocument.Parse(metaRaw).RootElement.GetProperty("format").GetString()!; var template = File.ReadAllText(Path.Combine(dir, "template.mustache")); var payload = JsonPayload.Parse(File.ReadAllText(Path.Combine(dir, "payload.json"))); - var expected = File.ReadAllText(Path.Combine(dir, "expected.txt")); var provider = ProviderFromPartials(dir); + // expected-error.txt: the render must fail, and the message must contain the file's trimmed text. + var errorFile = Path.Combine(dir, "expected-error.txt"); + if (File.Exists(errorFile)) + { + var ex = Assert.Throws(() => Renderer.Render(new RenderRequest + { + Template = template, + Payload = payload, + Provider = provider, + Format = format, + })); + Assert.Contains(File.ReadAllText(errorFile).Trim(), ex.Message); + return; + } + var expected = File.ReadAllText(Path.Combine(dir, "expected.txt")); + var actual = Renderer.Render(new RenderRequest { Template = template, diff --git a/server/csharp/MetaObjects.Render/PayloadAccessors.cs b/server/csharp/MetaObjects.Render/PayloadAccessors.cs index 088afcd9eb..1f5bb877f3 100644 --- a/server/csharp/MetaObjects.Render/PayloadAccessors.cs +++ b/server/csharp/MetaObjects.Render/PayloadAccessors.cs @@ -200,6 +200,34 @@ private sealed class TypedView(object target, int depth, bool? last) public override string? ToString() => Target.ToString(); } + /// + /// Whether is a member of the context (a present + /// null counts as present), and its value. Used by the renderer's missing-variable check, + /// which must tell an ABSENT name from a null one. A delegate or dynamic object cannot be + /// inspected, so every name is taken as present. + /// + internal static bool TryLookup(object? ctx, string key, out object? value) + { + value = null; + switch (ctx) + { + case null: return false; + case IDictionary map: return map.TryGetValue(key, out value); + case System.Collections.IDictionary dict: + if (!dict.Contains(key)) return false; + value = dict[key]; + return true; + case TypedView view: + if (ViewLookup(view, key, false) is { } found) { value = found; return true; } + if (view.Target.GetType().GetMember(key, PublicInstance).Length > 0) return true; + return false; + case Delegate or System.Dynamic.IDynamicMetaObjectProvider: + return true; + default: + return false; + } + } + /// The overlay type is registered for. internal static Type ViewType => typeof(TypedView); diff --git a/server/csharp/MetaObjects.Render/Renderer.cs b/server/csharp/MetaObjects.Render/Renderer.cs index 1833c96599..6ac8621f6f 100644 --- a/server/csharp/MetaObjects.Render/Renderer.cs +++ b/server/csharp/MetaObjects.Render/Renderer.cs @@ -114,7 +114,9 @@ public static string Render(RenderRequest request) // Derived `has` accessors are part of the payload contract, not of the // caller's object — see PayloadAccessors. Injected here so a `{{#hasFoo}}` section // resolves the same way it does against a generated JVM payload record. - string result = stubble.Render(expanded, PayloadAccessors.WithDerivedAccessors(request.Payload)); + object? view = PayloadAccessors.WithDerivedAccessors(request.Payload); + FailOnMissingVariable(expanded, view); + string result = stubble.Render(expanded, view); if (request.MaxChars is int cap && result.Length > cap) throw new RenderException( @@ -122,4 +124,86 @@ public static string Render(RenderRequest request) return result; } + + // A variable tag whose name is ABSENT from the payload (on no frame of the context stack) is a + // missing variable and raises the message the opt-in verify gate uses, so a typo like + // `{{nmae}}` fails on every render path. A value that is present but null renders empty. + // Walks the template the way the engine renders it: a section pushes its value (each element of + // a list), an inverted section or a falsy section's body is only checked when it renders. + private static void FailOnMissingVariable(string template, object? payload) + { + List tags; + try { tags = MustacheTags.Scan(template); } + catch (MustacheSyntaxException) { return; } // the engine reports a malformed template itself + CheckTags(tags, 0, tags.Count, [payload]); + } + + private static void CheckTags(List tags, int from, int to, List stack) + { + for (int i = from; i < to; i++) + { + var tag = tags[i]; + switch (tag.Kind) + { + case MustacheTagKind.Name or MustacheTagKind.Triple or MustacheTagKind.Amp: + if (!TryResolve(stack, tag.Value, out _)) + throw new RenderException($"render verify failed: {MetaObjects.Render.Verify.ERR_VAR_NOT_ON_PAYLOAD} ({tag.Value})"); + break; + case MustacheTagKind.Section or MustacheTagKind.Inverted: + int depth = 1, close = i + 1; + for (; close < to; close++) + { + if (tags[close].Kind is MustacheTagKind.Section or MustacheTagKind.Inverted) depth++; + else if (tags[close].Kind == MustacheTagKind.Close && --depth == 0) break; + } + bool found = TryResolve(stack, tag.Value, out object? value); + if (tag.Kind == MustacheTagKind.Inverted) + { + if (!found || IsFalsy(value)) CheckTags(tags, i + 1, close, stack); + } + else if (found && !IsFalsy(value) && value is not Delegate) + { + if (value is System.Collections.IEnumerable seq and not string and not System.Collections.IDictionary) + { + foreach (var item in seq) + CheckTags(tags, i + 1, close, [.. stack, item]); + } + else CheckTags(tags, i + 1, close, [.. stack, value]); + } + i = close; + break; + } + } + } + + private static bool IsFalsy(object? v) => v switch + { + null => true, + bool b => !b, + string s => s.Length == 0, + System.Collections.IDictionary => false, + System.Collections.IEnumerable seq => !seq.GetEnumerator().MoveNext(), + _ => false, + }; + + /// Mustache's name lookup: the first segment is searched from the innermost context outward, + /// the rest walk down from it. Absent at any step is a miss; a null part-way is a present null. + private static bool TryResolve(List stack, string name, out object? value) + { + value = null; + if (name == ".") { value = stack[^1]; return true; } + string[] segs = name.Split('.'); + bool hit = false; + object? current = null; + for (int i = stack.Count - 1; i >= 0 && !hit; i--) + hit = PayloadAccessors.TryLookup(stack[i], segs[0], out current); + if (!hit) return false; + for (int s = 1; s < segs.Length; s++) + { + if (current is null) { value = null; return true; } + if (!PayloadAccessors.TryLookup(current, segs[s], out current)) return false; + } + value = current; + return true; + } } diff --git a/server/csharp/MetaObjects/Core/Reporting/ReportingMetaDataProvider.cs b/server/csharp/MetaObjects/Core/Reporting/ReportingMetaDataProvider.cs new file mode 100644 index 0000000000..038322802f --- /dev/null +++ b/server/csharp/MetaObjects/Core/Reporting/ReportingMetaDataProvider.cs @@ -0,0 +1,66 @@ +// The metaobjects-reporting pack: dimension.*, measure.*, segment.filter and object.report +// (FR-044). Its own provider so a project can leave it out; it is in the default bundle, so +// every existing model loads unchanged. Types and attrs are declared in the embedded +// reporting.json, whose `extends` also admits the vocabulary as children of object.entity +// and adds @segment to origin.aggregate / origin.first. Mirrors the TS reportingProvider. + +using MetaObjects.Core.Object; +using MetaObjects.Meta; +using MetaObjects.Registry.Spec; +using static MetaObjects.Shared.BaseTypes; + +namespace MetaObjects.Core.Reporting; + +/// The reporting pack provider (metaobjects-reporting). +public sealed class ReportingMetaDataProvider : IMetaDataTypeProvider +{ + /// The shared singleton — composed into the default registry. + public static readonly IMetaDataTypeProvider Instance = new ReportingMetaDataProvider(); + + /// The provider id — matches reporting.json's "provider" field. + public const string ProviderId = "metaobjects-reporting"; + + private static readonly Lazy Reader = new(SpecMetamodelReader.Load); + + public string Id => ProviderId; + + public string? Description => + "Reporting: dimension / measure / segment and object.report, compiled to a read-only view."; + + public IReadOnlyList Dependencies => ["metaobjects-core-types"]; + + public void RegisterTypes(TypeRegistry registry) + { + void Reg(string type, string subType, string label, List attrs, Func factory) => + registry.Register(new TypeDefinition( + typeId: new TypeId(type, subType), + description: $"{label} ({subType})", + childRules: [new ChildRule(TYPE_ATTR, CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD)], + factory: factory, + attributes: attrs)); + + foreach (string subType in ReportingConstants.DIMENSION_SUBTYPES) + Reg(TYPE_DIMENSION, subType, "Dimension", ReportingSchema.DimensionAttrsMap[subType].ToList(), (tid, n) => new MetaDimension(tid, n)); + foreach (string subType in ReportingConstants.MEASURE_SUBTYPES) + Reg(TYPE_MEASURE, subType, "Measure", ReportingSchema.MeasureAttrsMap[subType].ToList(), (tid, n) => new MetaMeasure(tid, n)); + foreach (string subType in ReportingConstants.SEGMENT_SUBTYPES) + Reg(TYPE_SEGMENT, subType, "Segment", ReportingSchema.SegmentAttrsMap[subType].ToList(), (tid, n) => new MetaSegment(tid, n)); + + // object.report extends the base another provider registered: fold that base's + // attrs and child rules in (the strict pass later rebuilds the structural rules + // from the spec, which composes the same base). + TypeDefinition objectBase = registry.Find(TYPE_OBJECT, SUBTYPE_BASE) + ?? throw new InvalidOperationException("metaobjects-reporting: object.base is not registered"); + registry.Register(new TypeDefinition( + typeId: new TypeId(TYPE_OBJECT, ObjectConstants.OBJECT_SUBTYPE_REPORT), + description: $"Object/entity ({ObjectConstants.OBJECT_SUBTYPE_REPORT})", + childRules: objectBase.ChildRules.ToList(), + factory: (tid, n) => new MetaObject(tid, n), + attributes: [.. objectBase.Attributes, .. ReportingSchema.ReportAttrs, ObjectSchema.CollectionNameAttr])); + + registry.ApplyProviderExtends( + Reader.Value, + ProviderId, + new Dictionary>(StringComparer.Ordinal)); + } +} diff --git a/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs b/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs index 101fbc6dc5..7d7534f938 100644 --- a/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs +++ b/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs @@ -1,8 +1,8 @@ // Reporting attribute schemas — the per-subtype attr sets for dimension.*, measure.* and // segment.*, plus the object.report attrs (FR-044). // -// Colocated per ADR-0003. Mirrors the canonical spec/metamodel/reporting.json and the -// object.report block of spec/metamodel/object.json (which this port embeds + reads): +// Colocated per ADR-0003. Mirrors the canonical spec/metamodel/reporting.json, which +// declares object.report too (the reporting pack; this port embeds + reads it): // DESCRIPTIONS are deliberately NOT hand-copied here — FR-033 sources every description // from the shared JSON via Registry.ApplySpecDescriptions. Only the facets the manifest // needs but the description pass does not carry (value type / array-ness / requiredness / diff --git a/server/csharp/MetaObjects/Core/Requirement/RequirementsMetaDataProvider.cs b/server/csharp/MetaObjects/Core/Requirement/RequirementsMetaDataProvider.cs new file mode 100644 index 0000000000..3d50784881 --- /dev/null +++ b/server/csharp/MetaObjects/Core/Requirement/RequirementsMetaDataProvider.cs @@ -0,0 +1,56 @@ +// The metaobjects-requirements pack: requirement.functional / requirement.architectural. +// Its own provider so a project can leave it out; it is in the default bundle, so every +// existing model loads unchanged. Types and attrs are declared in the embedded +// requirement.json, whose `extends` admits `requirement` under metadata.root. +// Mirrors the TS requirementsProvider. + +using MetaObjects.Meta; +using MetaObjects.Registry.Spec; +using static MetaObjects.Shared.BaseTypes; + +namespace MetaObjects.Core.Requirement; + +/// The requirements pack provider (metaobjects-requirements). +public sealed class RequirementsMetaDataProvider : IMetaDataTypeProvider +{ + /// The shared singleton — composed into the default registry. + public static readonly IMetaDataTypeProvider Instance = new RequirementsMetaDataProvider(); + + /// The provider id — matches requirement.json's "provider" field. + public const string ProviderId = "metaobjects-requirements"; + + private static readonly Lazy Reader = new(SpecMetamodelReader.Load); + + public string Id => ProviderId; + + public string? Description => + "Requirements: requirement.functional (existence) and requirement.architectural (universality)."; + + public IReadOnlyList Dependencies => ["metaobjects-core-types"]; + + public void RegisterTypes(TypeRegistry registry) + { + // Hierarchy IS nesting: BOTH subtypes may nest requirement children. Structural + // cardinality comes from requirement.json via ApplySpecDescriptions. + foreach (string subType in RequirementConstants.REQUIREMENT_SUBTYPES) + { + registry.Register(new TypeDefinition( + typeId: new TypeId(TYPE_REQUIREMENT, subType), + description: $"Requirement ({subType})", + childRules: + [ + new ChildRule(TYPE_ATTR, CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD), + new ChildRule(TYPE_REQUIREMENT, CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD), + ], + factory: (tid, n) => new MetaRequirement(tid, n), + attributes: RequirementSchema.RequirementAttrsMap.TryGetValue(subType, out var reqAttrs) + ? reqAttrs.ToList() + : [])); + } + + registry.ApplyProviderExtends( + Reader.Value, + ProviderId, + new Dictionary>(StringComparer.Ordinal)); + } +} diff --git a/server/csharp/MetaObjects/CoreTypes.cs b/server/csharp/MetaObjects/CoreTypes.cs index 915399f1b9..3bb30debb0 100644 --- a/server/csharp/MetaObjects/CoreTypes.cs +++ b/server/csharp/MetaObjects/CoreTypes.cs @@ -84,6 +84,8 @@ public static class CoreTypes // bundle so every existing model loads unchanged. MetaObjects.Core.Rules.RulesMetaDataProvider.Instance, MetaObjects.Persistence.ViewExpressions.ViewExpressionsMetaDataProvider.Instance, + MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, ]; /// @@ -274,8 +276,8 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) Wildcard(TYPE_ATTR), Wildcard(TYPE_VALIDATOR), Wildcard(TYPE_TEMPLATE), - // Capability requirements are declared beside the entities they describe. - Wildcard(TYPE_REQUIREMENT), + // `requirement` (the requirements pack) and `api` (the rules pack) are + // admitted by their packs' `extends`. ], (tid, n) => new MetaRoot(tid, n), [])); @@ -311,6 +313,8 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) ]; foreach (string subType in OBJECT_SUBTYPES) { + // object.report is the reporting pack's (it folds the registered base). + if (subType == OBJECT_SUBTYPE_REPORT) continue; // FR-033: object.value's @normalize (the object-level default normalization // mode for its enum fields' tolerant extract) is re-homed to the // metaobjects-prompt concern provider (reads prompt.json's object.value @@ -326,7 +330,6 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) List objectAttrs = subType switch { OBJECT_SUBTYPE_PROJECTION => [.. ObjectSchema.ObjectAttrs, ObjectSchema.ProjectionFilterAttr, ObjectSchema.CollectionNameAttr], - OBJECT_SUBTYPE_REPORT => [.. ObjectSchema.ObjectAttrs, .. ReportingSchema.ReportAttrs, ObjectSchema.CollectionNameAttr], OBJECT_SUBTYPE_ENTITY => [.. ObjectSchema.ObjectAttrs, ObjectSchema.CollectionNameAttr], _ => ObjectSchema.ObjectAttrs.ToList(), }; @@ -607,89 +610,8 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) whenToUse: "You need a DB index for query performance (fast lookups/sorts) but NOT uniqueness enforcement. @fields names the indexed columns; the db provider adds @orders / @expr / @where / @using for physical tuning.")); - // requirement — 2 subtypes. The axis is CHECK POLARITY, a genuine behaviour - // difference (ADR-0037 §2): `functional` is checked by EXISTENCE (nothing - // implements it -> fail), `architectural` by UNIVERSALITY (something violates - // it -> fail). Registered rather than hand-parsed because the capability ledger - // IS a metadata model: a closed status enum and a list of FQN references to - // model nodes are exactly `allowedValues` plus reference resolution, both of - // which this registry already owns (requirements-as-metadata ruling amendment 3). - // A single MetaRequirement class backs both subtypes (mirrors source/template). - // Descriptions + whenToUse + the structural child graph come from the embedded - // spec/metamodel/requirement.json via ApplySpecDescriptions — the placeholder - // description below is overwritten there, never the shipped prose. - foreach (string subType in REQUIREMENT_SUBTYPES) - { - // Hierarchy IS nesting, not a parent attribute: an L1 solution CONTAINS its - // L2 segments. BOTH subtypes nest — an architectural requirement is flat by - // DEFAULT rather than by rule, and may opt into a levelled tree so a quality - // taxonomy can organise the non-functional set the same way a capability - // taxonomy organises the functional one. Declaring the child rule on - // `functional` only was an omission, not a design: it made an architectural - // node nestable under a FUNCTIONAL parent but never under another - // architectural one. - List requirementRules = [Wildcard(TYPE_ATTR), Wildcard(TYPE_REQUIREMENT)]; - - registry.Register( - Def( - TYPE_REQUIREMENT, - subType, - $"Requirement ({subType})", - requirementRules, - (tid, n) => new MetaRequirement(tid, n), - RequirementSchema.RequirementAttrsMap.TryGetValue(subType, out var reqAttrs) - ? reqAttrs.ToList() - : [])); - } - - // NOTE: @implementedBy is deliberately NOT declared as a loader `references` - // descriptor. That pass always ERRORS on an unresolved target, and a - // requirement with status `planned` names nodes that do not exist YET, so declaring - // nodes that are GONE — declaring it here would make the entries that carry - // the mechanism's only controlled evidence fail to load. The loader owns what - // is unconditional (the status enum, shape, levels); `meta verify` owns the - // status-conditional resolution, where the severity actually depends on data. - - // FR-044 reporting vocabulary — dimension / measure / segment. Declared as children - // of `object.entity` (spec/metamodel/object.json), never root-level, so no root - // wildcard is added above. Three types in one provider file (reporting.json) - // because they are one vocabulary: a report names dimensions and measures, and - // both may reference a segment. `measure.derived` is FR-037 R5's first arithmetic - // wave (R13). Descriptions + whenToUse come from the embedded reporting.json via - // ApplySpecDescriptions; the placeholder descriptions below are overwritten there. - foreach (string subType in DIMENSION_SUBTYPES) - { - registry.Register( - Def( - TYPE_DIMENSION, - subType, - $"Dimension ({subType})", - [Wildcard(TYPE_ATTR)], - (tid, n) => new MetaDimension(tid, n), - ReportingSchema.DimensionAttrsMap[subType].ToList())); - } - foreach (string subType in MEASURE_SUBTYPES) - { - registry.Register( - Def( - TYPE_MEASURE, - subType, - $"Measure ({subType})", - [Wildcard(TYPE_ATTR)], - (tid, n) => new MetaMeasure(tid, n), - ReportingSchema.MeasureAttrsMap[subType].ToList())); - } - foreach (string subType in SEGMENT_SUBTYPES) - { - registry.Register( - Def( - TYPE_SEGMENT, - subType, - $"Segment ({subType})", - [Wildcard(TYPE_ATTR)], - (tid, n) => new MetaSegment(tid, n), - ReportingSchema.SegmentAttrsMap[subType].ToList())); - } + // requirement and the reporting vocabulary (dimension / measure / segment / object.report) + // are their own packs: RequirementsMetaDataProvider and ReportingMetaDataProvider. // template — fourth-pillar metatype (FR-004). prompt + output + toolcall; // attr-only children. A single MetaTemplate class backs every subtype (mirrors diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs index 7f8c7f309e..a18ad72619 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs @@ -39,6 +39,9 @@ // 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) +// P3 ERR_TRANSITION_NAME_COLLISION two permission points ask the policy about one permission name, and at +// least one of the two names is derived (two DECLARED @permission values +// may be equal: that sharing is the point) // 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 @@ -369,9 +372,57 @@ public static IReadOnlyList ValidateRules(MetaData root) } CheckApiRoutes(ops, sink); } + CheckPermissionNames(root, sink); return sink.Errors; } + private sealed record PermissionPoint(MetaData Node, bool Derived); + + /// The name a permission point asks the policy about: its @permission, else <package>.<path> + /// (the path is the operation name, or <Entity>.<transition> for a transition's command). The package + /// prefix is dropped when there is none. :: and . both separate path segments, so they compare equal. + private static (string Name, bool Derived) PermissionNameOf(MetaData node, MetaData owner, string path) + { + var declared = node.Attr(OPERATION_ATTR_PERMISSION) as string; + var pkg = NamingRefs.EffectivePackageOf(NamingRefs.TopLevelNodeOf(owner)); + var name = declared ?? (pkg.Length == 0 ? path : $"{pkg}.{path}"); + return (name.Replace("::", "."), declared is null); + } + + /// P3: two permission points, one name, at least one of the two derived. Points are every non-public + /// operation and every transition of a live concrete entity. Compared case-sensitively (a grant key is exact). + /// Transitions register first, so the error lands on the operation when an operation meets a transition. + private static void CheckPermissionNames(MetaData root, RulesErrorSink sink) + { + var byName = new Dictionary>(StringComparer.Ordinal); + void Register(MetaData node, MetaData owner, string path) + { + if (node.Attr(OPERATION_ATTR_PUBLIC) is true) return; + var (name, derived) = PermissionNameOf(node, owner, path); + if (!byName.TryGetValue(name, out var points)) byName[name] = points = []; + var clash = points.FirstOrDefault(q => + !ReferenceEquals(q.Node, node) && (derived || q.Derived) + && !(node.Type == TYPE_OPERATION && q.Node.Type == TYPE_OPERATION && SameOperation(q.Node, node))); + if (clash is not null) + { + sink.Add(node, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + $"{node.Type}.{node.SubType} \"{RulesLabel(node)}\" asks the policy about the permission name \"{name}\", which {clash.Node.Type}.{clash.Node.SubType} \"{RulesLabel(clash.Node)}\" also asks about, and one of the two names is derived rather than declared; declare a distinct @permission on one, or rename it."); + } + points.Add(new PermissionPoint(node, derived)); + } + foreach (var entity in root.Children()) + { + if (entity.Type != TYPE_OBJECT || entity.SubType != OBJECT_SUBTYPE_ENTITY) continue; + if (entity.IsAbstract || !Lifecycles.LifecycleIsLive(entity)) continue; + foreach (var t in Lifecycles.EntityTransitions(entity)) Register(t, entity, $"{entity.Name}.{t.Name}"); + } + foreach (var api in root.Children()) + { + if (api.Type != TYPE_API) continue; + foreach (var op in api.Children().Where(c => c.Type == TYPE_OPERATION)) Register(op, api, op.Name); + } + } + /// 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); diff --git a/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs b/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs index 7d2682ad0c..413070e5c1 100644 --- a/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs @@ -75,12 +75,6 @@ public static class OriginSchema IsArray: true, Description: "Ordering keys as 'field[:asc|desc]' over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only)."), - // Origin @segment. - new AttrSchema( - Name: OriginConstants.ORIGIN_ATTR_SEGMENT, - ValueType: AttrConstants.ATTR_SUBTYPE_STRING, - Required: false, - Description: "Optional name of a segment.filter declared on the related entity; its predicate scopes the related rows, ANDed with @filter."), ]; // #195 — computed: a row-level value via a structured @expr tree (attr.expression). @@ -121,12 +115,6 @@ public static class OriginSchema Required: false, Description: "Optional structured predicate scoping which related rows are eligible for selection."), - // Origin @segment. - new AttrSchema( - Name: OriginConstants.ORIGIN_ATTR_SEGMENT, - ValueType: AttrConstants.ATTR_SUBTYPE_STRING, - Required: false, - Description: "Optional name of a segment.filter declared on the related entity; its predicate scopes the related rows, ANDed with @filter."), ]; // function: a call of a database function the project owns. diff --git a/server/csharp/MetaObjects/Registry.cs b/server/csharp/MetaObjects/Registry.cs index 742b24cd88..2990893fc1 100644 --- a/server/csharp/MetaObjects/Registry.cs +++ b/server/csharp/MetaObjects/Registry.cs @@ -372,8 +372,19 @@ public void Register(TypeDefinition def) // ADR-0062: refuse a name another provider already put on a related slot, BEFORE // the definition becomes visible, so a refused registration leaves no trace. + // An attribute folded in unchanged from the registered `.base` (a pack's + // subtype with extendsBase, e.g. object.report) is the base owner's, not a new + // claim: it is not checked against the registering provider, and is stamped with + // the owner the base attribute already has. + // Reference identity, not value equality: a distinct attr that merely looks the same is a claim. + HashSet baseAttrs = def.TypeId.SubType == SUBTYPE_BASE + ? new HashSet(ReferenceEqualityComparer.Instance) + : _defs.TryGetValue($"{def.TypeId.Type}.{SUBTYPE_BASE}", out TypeDefinition? baseDef) + ? new HashSet(baseDef.Attributes, ReferenceEqualityComparer.Instance) + : new HashSet(ReferenceEqualityComparer.Instance); foreach (AttrSchema attr in def.Attributes) { + if (baseAttrs.Contains(attr)) continue; CheckAttrOwnership(def.TypeId.Type, def.TypeId.SubType, attr.Name); } @@ -384,6 +395,14 @@ public void Register(TypeDefinition def) // own AttrSchema list before calling Register()). foreach (AttrSchema attr in def.Attributes) { + if (baseAttrs.Contains(attr)) + { + if (_attrProvenance.TryGetValue((def.TypeId.Type, SUBTYPE_BASE, attr.Name), out string? baseOwner)) + { + _attrProvenance[(def.TypeId.Type, def.TypeId.SubType, attr.Name)] = baseOwner; + } + continue; + } StampAttrProvenance(def.TypeId.Type, def.TypeId.SubType, attr.Name); } diff --git a/server/csharp/MetaObjects/SpecMetamodel/object.json b/server/csharp/MetaObjects/SpecMetamodel/object.json index ddf3c6eeec..ad288e6015 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/object.json +++ b/server/csharp/MetaObjects/SpecMetamodel/object.json @@ -26,9 +26,6 @@ "children": [ { "type": "relationship", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "template", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } @@ -56,22 +53,6 @@ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] - }, - { - "type": "object", - "subType": "report", - "extendsBase": true, - "description": "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.", - "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", - "children": [ - { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, - { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, - { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, - { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } - ] } ] } diff --git a/server/csharp/MetaObjects/SpecMetamodel/origin.json b/server/csharp/MetaObjects/SpecMetamodel/origin.json index c4fde970f9..4d7e5aea16 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/origin.json +++ b/server/csharp/MetaObjects/SpecMetamodel/origin.json @@ -28,7 +28,6 @@ { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -52,8 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." } ] } ] diff --git a/server/csharp/MetaObjects/SpecMetamodel/reporting.json b/server/csharp/MetaObjects/SpecMetamodel/reporting.json index adbe87f9ed..10a888b0c3 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/reporting.json +++ b/server/csharp/MetaObjects/SpecMetamodel/reporting.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-reporting", "types": [ { "type": "dimension", "subType": "attribute", "description": "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.", @@ -46,6 +46,35 @@ "whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 1, "max": 1, "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } + ] }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "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.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, + { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, + { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, + { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + } + ], + "extends": [ + { "type": "object", "subType": "entity", "children": [ + { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null } + ] }, + { "type": "origin", "subType": "aggregate", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + ] }, + { "type": "origin", "subType": "first", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] } diff --git a/server/csharp/MetaObjects/SpecMetamodel/requirement.json b/server/csharp/MetaObjects/SpecMetamodel/requirement.json index f3017fd78d..a74ebd5758 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/requirement.json +++ b/server/csharp/MetaObjects/SpecMetamodel/requirement.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-requirements", "types": [ { "type": "requirement", @@ -185,5 +185,10 @@ } ] } + ], + "extends": [ + { "type": "metadata", "subType": "root", "children": [ + { "type": "requirement", "subType": "*", "name": "*", "min": 0, "max": null } + ] } ] } 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 3debdc38e1..ddfd1e888f 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/MetaData.java +++ b/server/java/metadata/src/main/java/com/metaobjects/MetaData.java @@ -420,18 +420,20 @@ private void validateName(String name) { // accept these; the cross-port contract requires Java match. Also // accept FQN-qualified attr names (`pkg::name::attr` form) which the // loader synthesises for cross-package attr lookups. - if ("attr".equals(type)) { + // An operation's name may be dotted too ("Order.open"): TS, C# and Python accept it, and the + // rules pass (P3) must see it to flag a derived permission name that equals a transition's. + if ("attr".equals(type) || "operation".equals(type)) { if (name.contains("::")) { for (String part : name.split("::")) { if (!part.matches("^[a-zA-Z][a-zA-Z0-9_.]*$")) { throw new IllegalArgumentException( - "Invalid attr name part '" + part + "' in '" + name + "Invalid " + type + " name part '" + part + "' in '" + name + "': must follow pattern ^[a-zA-Z][a-zA-Z0-9_.]*$"); } } } else if (!name.matches("^[a-zA-Z][a-zA-Z0-9_.]*$")) { throw new IllegalArgumentException( - "Invalid attr name '" + name + "': must follow pattern ^[a-zA-Z][a-zA-Z0-9_.]*$"); + "Invalid " + type + " name '" + name + "': must follow pattern ^[a-zA-Z][a-zA-Z0-9_.]*$"); } return; } 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..c1d632902e 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java +++ b/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java @@ -125,7 +125,6 @@ public static void registerTypes(MetaDataRegistry registry) { .optionalChild(MetaField.TYPE_FIELD, "*", "*") .optionalChild(MetaValidator.TYPE_VALIDATOR, "*", "*") .optionalChild(com.metaobjects.template.TemplateConstants.TYPE_TEMPLATE, "*", "*") - .optionalChild(com.metaobjects.requirement.MetaRequirement.TYPE_REQUIREMENT, "*", "*") .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/loader/RulesValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java index a1fb9e223a..7358a4b167 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java @@ -430,9 +430,66 @@ static List validate(MetaRoot root) { } checkApiRoutes(ops, sink); } + checkPermissionNames(root, sink); return sink.errors; } + /** One permission point: a node and whether its permission name is derived (no @permission). */ + private record PermissionPoint(MetaData node, boolean derived) {} + + /** + * P3: two permission points ask the policy about one permission name, and at least one of the two + * names is derived. Points are every non-public operation and every transition of a live concrete + * entity (a transition derives a command each). A name is the node's {@code @permission}, else + * {@code .} (the path is the operation name, or {@code Entity.transition}); {@code ::} + * and {@code .} both separate segments so they compare equal. Compared case-sensitively. Transitions + * register first, so the error lands on the operation when an operation meets a transition. Two + * DECLARED values may be equal: that sharing is the point. + */ + private static void checkPermissionNames(MetaRoot root, Sink sink) { + Map> byName = new java.util.HashMap<>(); + for (MetaData entity : root.getChildren(MetaData.class, true)) { + if (!Lifecycles.isEntity(entity) || Lifecycles.isAbstract(entity) || !Lifecycles.lifecycleIsLive(entity)) continue; + for (MetaData t : Lifecycles.entityTransitions(entity)) { + registerPermissionPoint(t, entity, entity.getShortName() + "." + t.getShortName(), byName, sink); + } + } + 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())) { + registerPermissionPoint(op, api, op.getShortName(), byName, sink); + } + } + } + } + + private static void registerPermissionPoint(MetaData node, MetaData owner, String path, + Map> byName, Sink sink) { + if (flag(node, ApiConstants.ATTR_PUBLIC)) return; + String declared = Lifecycles.stringValue(node, ApiConstants.ATTR_PERMISSION); + String pkg = References.effectivePackageOf(owner); + String raw = declared != null ? declared : pkg.isEmpty() ? path : pkg + "." + path; + String name = raw.replace("::", "."); + boolean derived = declared == null; + List points = byName.computeIfAbsent(name, k -> new ArrayList<>()); + PermissionPoint clash = null; + for (PermissionPoint q : points) { + if (q.node() == node || !(derived || q.derived())) continue; + if (ApiConstants.TYPE_OPERATION.equals(node.getType()) && ApiConstants.TYPE_OPERATION.equals(q.node().getType()) + && sameOperation(q.node(), node)) continue; + clash = q; + break; + } + if (clash != null) { + sink.add(node, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + node.getType() + "." + node.getSubType() + " \"" + label(node) + "\" asks the policy about the permission name \"" + + name + "\", which " + clash.node().getType() + "." + clash.node().getSubType() + " \"" + label(clash.node()) + + "\" also asks about, and one of the two names is derived rather than declared; declare a distinct @permission on one, or rename it."); + } + points.add(new PermissionPoint(node, derived)); + } + /** 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); diff --git a/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java b/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java index 17ccd7f67f..8ea451eef8 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java +++ b/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java @@ -259,27 +259,8 @@ public static void registerEntityValueTypes(MetaDataRegistry registry) { // (ViewExpressionsTypesMetaDataProvider), not to core. }); - // FR-044 — object.report: a fixed combination of dimensions and measures of ONE - // entity (@from), compiled to a read-only view. Its fields are DERIVED, never - // declared (rule R4 in the reporting validation pass); its structural children - // come from spec/metamodel/object.json (extendsBase), like object.projection. - registry.registerType(ReportMetaObject.class, def -> { - def.type(TYPE_OBJECT).subType(SUBTYPE_REPORT) - .description("Report object (derived, read-only) — a declared aggregation of one entity") - .inheritsFrom(TYPE_OBJECT, SUBTYPE_BASE); - def.requiredAttributeWithConstraints(ATTR_REPORT_FROM) - .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); - def.optionalAttributeWithConstraints(ATTR_REPORT_DIMENSIONS) - .ofType(StringAttribute.SUBTYPE_STRING).asArray(); - def.requiredAttributeWithConstraints(ATTR_REPORT_MEASURES) - .ofType(StringAttribute.SUBTYPE_STRING).asArray(); - def.optionalAttributeWithConstraints(ATTR_REPORT_SEGMENT) - .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); - def.optionalAttributeWithConstraints(ATTR_FILTER) - .ofType(FilterAttribute.SUBTYPE_FILTER).asSingle(); - def.optionalAttributeWithConstraints(ATTR_REPORT_SPINE) - .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); - }); + // object.report is registered by the reporting pack (ReportingTypesMetaDataProvider -> + // ReportMetaObject.registerTypes), not by core. // ADR-0006 Rule 1 — bare `object:` YAML key fuses to `object.entity`. registry.setDefaultSubType(TYPE_OBJECT, SUBTYPE_ENTITY); diff --git a/server/java/metadata/src/main/java/com/metaobjects/object/ReportMetaObject.java b/server/java/metadata/src/main/java/com/metaobjects/object/ReportMetaObject.java index a5d3f3562e..3a138fd3a2 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/object/ReportMetaObject.java +++ b/server/java/metadata/src/main/java/com/metaobjects/object/ReportMetaObject.java @@ -15,7 +15,10 @@ */ package com.metaobjects.object; +import com.metaobjects.attr.FilterAttribute; +import com.metaobjects.attr.StringAttribute; import com.metaobjects.object.value.ValueObject; +import com.metaobjects.registry.MetaDataRegistry; /** * object.report — a declared report (FR-044): a fixed combination of the dimensions and @@ -32,5 +35,32 @@ public class ReportMetaObject extends AbstractObjectRepresentation { public ReportMetaObject(String name) { super(MetaObject.SUBTYPE_REPORT, name); } protected ReportMetaObject(String subType, String name) { super(subType, name); } + + /** + * Register {@code object.report} (FR-044). Called by the reporting pack's provider, not by + * core: it inherits {@code object.base} from the object-types provider (the cross-definition + * {@code extendsBase}), so the inherited attrs are not a new claim by the reporting pack. Its + * structural children come from spec/metamodel/reporting.json (extendsBase), like + * object.projection. + */ + public static void registerTypes(MetaDataRegistry registry) { + registry.registerType(ReportMetaObject.class, def -> { + def.type(MetaObject.TYPE_OBJECT).subType(MetaObject.SUBTYPE_REPORT) + .description("Report object (derived, read-only) — a declared aggregation of one entity") + .inheritsFrom(MetaObject.TYPE_OBJECT, MetaObject.SUBTYPE_BASE); + def.requiredAttributeWithConstraints(MetaObject.ATTR_REPORT_FROM) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(MetaObject.ATTR_REPORT_DIMENSIONS) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.requiredAttributeWithConstraints(MetaObject.ATTR_REPORT_MEASURES) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.optionalAttributeWithConstraints(MetaObject.ATTR_REPORT_SEGMENT) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(MetaObject.ATTR_FILTER) + .ofType(FilterAttribute.SUBTYPE_FILTER).asSingle(); + def.optionalAttributeWithConstraints(MetaObject.ATTR_REPORT_SPINE) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + } @Override protected Class getDefaultObjectClass() { return ValueObject.class; } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/AggregateOrigin.java b/server/java/metadata/src/main/java/com/metaobjects/origin/AggregateOrigin.java index 54aa097158..9953f9de13 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/origin/AggregateOrigin.java +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/AggregateOrigin.java @@ -63,8 +63,7 @@ public static void registerTypes(MetaDataRegistry registry) { // Optional scoping filter (attr.filter object) → SQL FILTER (WHERE ...). def.optionalAttributeWithConstraints(ATTR_FILTER) .ofType(FilterAttribute.SUBTYPE_FILTER).asSingle(); - def.optionalAttributeWithConstraints(ATTR_SEGMENT) - .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + // @segment is projected onto this type by the reporting pack (reporting.json extends). // #195 collect support: @distinct (dedupe) + @orderBy (element order). def.optionalAttributeWithConstraints(ATTR_DISTINCT) .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/FirstOrigin.java b/server/java/metadata/src/main/java/com/metaobjects/origin/FirstOrigin.java index 024bc824ea..6db029b9f2 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/origin/FirstOrigin.java +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/FirstOrigin.java @@ -54,8 +54,7 @@ public static void registerTypes(MetaDataRegistry registry) { .ofType(StringAttribute.SUBTYPE_STRING).asArray(); def.optionalAttributeWithConstraints(ATTR_FILTER) .ofType(FilterAttribute.SUBTYPE_FILTER).asSingle(); - def.optionalAttributeWithConstraints(ATTR_SEGMENT) - .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + // @segment is projected onto this type by the reporting pack (reporting.json extends). }); } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java index 395ccbbe72..daaf2dc0ab 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java @@ -17,6 +17,9 @@ import com.metaobjects.registry.MetaDataRegistry; import com.metaobjects.registry.MetaDataTypeProvider; +import com.metaobjects.registry.spec.SpecMetamodelReader; + +import java.util.Map; /** * Reporting Types MetaData provider (FR-044). @@ -24,7 +27,7 @@ *

Registers the entity-member reporting vocabulary: {@code dimension.attribute}, * {@code dimension.time}, {@code measure.aggregate}, {@code measure.ratio} and * {@code segment.filter}. {@code object.report} is an object subtype and is registered by - * the object-types provider beside {@code object.projection}. {@code measure.derived} (R13) is + * this pack too (the object-types provider no longer registers it). {@code measure.derived} (R13) is * FR-037 R5's first arithmetic wave.

* *

Depends on {@code core-types} for {@code metadata.base} inheritance.

@@ -39,8 +42,16 @@ public void registerTypes(MetaDataRegistry registry) { RatioMeasure.registerTypes(registry); DerivedMeasure.registerTypes(registry); FilterSegment.registerTypes(registry); + com.metaobjects.object.ReportMetaObject.registerTypes(registry); + // The rules that admit these types on types core owns (dimension/measure/segment under + // object.entity) and the @segment attr on origin.aggregate/origin.first ride in + // reporting.json under the pack's logical id: leaving the pack out leaves none of them. + registry.applyProviderExtends(SpecMetamodelReader.load(), LOGICAL_ID, Map.of()); } + /** The pack's cross-port logical id, the {@code provider} of reporting.json. */ + public static final String LOGICAL_ID = "metaobjects-reporting"; + @Override public String getProviderId() { return "reporting-types"; @@ -48,7 +59,7 @@ public String getProviderId() { @Override public String[] getDependencies() { - return new String[]{"core-types"}; + return new String[]{"core-types", "object-types", "origin-types"}; } @Override diff --git a/server/java/metadata/src/main/java/com/metaobjects/requirement/RequirementTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/requirement/RequirementTypesMetaDataProvider.java index 5b25fb2a4b..fa99c00a7b 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/requirement/RequirementTypesMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/requirement/RequirementTypesMetaDataProvider.java @@ -17,6 +17,9 @@ import com.metaobjects.registry.MetaDataRegistry; import com.metaobjects.registry.MetaDataTypeProvider; +import com.metaobjects.registry.spec.SpecMetamodelReader; + +import java.util.Map; /** * Requirement Types MetaData provider. @@ -34,8 +37,14 @@ public class RequirementTypesMetaDataProvider implements MetaDataTypeProvider { public void registerTypes(MetaDataRegistry registry) { FunctionalRequirement.registerTypes(registry); ArchitecturalRequirement.registerTypes(registry); + // The rule that admits a requirement under metadata.root rides in requirement.json under + // the pack's logical id: leaving the pack out leaves neither the type nor the rule. + registry.applyProviderExtends(SpecMetamodelReader.load(), LOGICAL_ID, Map.of()); } + /** The pack's cross-port logical id, the {@code provider} of requirement.json. */ + public static final String LOGICAL_ID = "metaobjects-requirements"; + @Override public String getProviderId() { return "requirement-types"; 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 8d5d35b026..b642db8037 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 @@ -124,11 +124,11 @@ public class ConformanceTest { * in {@code META-INF/services/com.metaobjects.registry.MetaDataTypeProvider}.

*/ private static final java.util.Map> PROVIDER_ALIASES = - java.util.Map.of( + java.util.Map.ofEntries( // TS/C# expose one "metaobjects-core-types" provider; Java splits it // into per-concern providers (core, fields, attrs, objects, validators, // identity, relationships, sources). - "metaobjects-core-types", List.of( + java.util.Map.entry("metaobjects-core-types", List.of( "core-types", "field-types", "attribute-types", @@ -145,34 +145,40 @@ public class ConformanceTest { // full SPI superset rather than the fixture's declared set. Incomplete // AND unexercised. ProviderAliasCompletenessTest now gates it. "index-types", - "origin-types", - "requirement-types", - // FR-044 reporting vocabulary (dimension / measure / segment). + "origin-types" + )), + // The reporting vocabulary (FR-044: dimension / measure / segment / object.report) + // and the requirements ledger are their own packs, in the default bundle, left out + // of a fixture that does not name them. + java.util.Map.entry("metaobjects-reporting", List.of( "reporting-types" - ), + )), + java.util.Map.entry("metaobjects-requirements", List.of( + "requirement-types" + )), // ADR-0066 business-rules pack (api / operation / binding / transition) and the // rc.21 view-expressions pack (origin.function, @union / @grain on a projection): // their own providers, in the default bundle, left out of a fixture that does not // name them. - "metaobjects-rules", List.of( + java.util.Map.entry("metaobjects-rules", List.of( "rules-types" - ), - "metaobjects-view-expressions", List.of( + )), + java.util.Map.entry("metaobjects-view-expressions", List.of( "view-expressions-types" - ), + )), // The corpus's "metaobjects-db" provider maps to Java's // CoreDBMetaDataProvider (id "database-extensions"), which registers the // physical RDB attributes (@column / @dbType / @dbColumnType / ...). - "metaobjects-db", List.of( + java.util.Map.entry("metaobjects-db", List.of( "database-extensions" - ), + )), // Java registers the documentation provider under the canonical name, so this // is an identity mapping -- present so the map is COMPLETE, which is what // ProviderAliasCompletenessTest gates. Its absence meant a fixture naming this // logical id would not have composed on Java. - "metaobjects-documentation", List.of( + java.util.Map.entry("metaobjects-documentation", List.of( "metaobjects-documentation" - ), + )), // The corpus's "metaobjects-template" provider (TS/C#/Python expose it // under this canonical name — template.* / @responseRef / @xmlText, the // AI prompt-construction vocab) maps to Java's TemplateTypesMetaDataProvider @@ -185,25 +191,24 @@ public class ConformanceTest { // and may ride along with a "metaobjects-template" fixture. Java folds // template-types into "metaobjects-core-types"; the checks are independent // set memberships, so a fixture listing both resolves. - "metaobjects-template", List.of( + java.util.Map.entry("metaobjects-template", List.of( "template-types", "metaobjects-prompt" - ), + )), // FR-033 — the cross-port "metaobjects-ui" / "metaobjects-prompt" concern // providers. Java registers them under their own (already-canonical) ids // via the ServiceLoader SPI, so these are identity aliases documenting the // backing provider — kept explicit so the availability check is honest if // a provider id is ever renamed. - "metaobjects-ui", List.of( + java.util.Map.entry("metaobjects-ui", List.of( com.metaobjects.presentation.ui.UiTypesMetaDataProvider.PROVIDER_ID - ), - "metaobjects-ui-web", List.of( + )), + java.util.Map.entry("metaobjects-ui-web", List.of( com.metaobjects.presentation.ui.UiWebTypesMetaDataProvider.PROVIDER_ID - ), - "metaobjects-prompt", List.of( + )), + java.util.Map.entry("metaobjects-prompt", List.of( com.metaobjects.template.PromptTypesMetaDataProvider.PROVIDER_ID - ) - ); + ))); /** Provider IDs available to the Java harness (via ServiceLoader auto-discovery). */ /** @@ -388,6 +393,12 @@ static void runConformanceChecks(FixtureDiscovery.Fixture fix, if (!fix.requiredProviders.contains("metaobjects-rules")) { packsLeftOut.add("rules-types"); } + if (!fix.requiredProviders.contains("metaobjects-reporting")) { + packsLeftOut.add("reporting-types"); + } + if (!fix.requiredProviders.contains("metaobjects-requirements")) { + packsLeftOut.add("requirement-types"); + } if (!fix.requiredProviders.contains("metaobjects-view-expressions")) { packsLeftOut.add("view-expressions-types"); } diff --git a/server/java/metadata/src/test/java/com/metaobjects/requirement/RequirementsPackLeftOutTest.java b/server/java/metadata/src/test/java/com/metaobjects/requirement/RequirementsPackLeftOutTest.java new file mode 100644 index 0000000000..9815f97440 --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/requirement/RequirementsPackLeftOutTest.java @@ -0,0 +1,78 @@ +package com.metaobjects.requirement; + +import com.metaobjects.MetaDataException; +import com.metaobjects.MetaRoot; +import com.metaobjects.loader.InMemoryStringSource; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.registry.RegistryManifest; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * The requirements ledger is its own pack ({@code metaobjects-requirements}). With the pack in + * the default bundle the gate behaves as before; with it left out, a model with no requirement + * nodes gets an empty, silent ledger and a model that declares one fails at load. + */ +public class RequirementsPackLeftOutTest { + + private static final String PLAIN = """ + {"metadata.root": {"package": "p", "children": [ + {"object.value": {"name": "Thing", "children": [{"field.string": {"name": "label"}}]}} + ]}} + """; + + private static final String WITH_REQUIREMENT = """ + {"metadata.root": {"package": "p", "children": [ + {"object.value": {"name": "Thing", "children": [{"field.string": {"name": "label"}}]}}, + {"requirement.functional": {"name": "labels", "@level": 4, "@status": "planned", + "@statement": "A thing has a label.", "@counterexample": "A thing with no label."}} + ]}} + """; + + private static MetaDataLoader load(String json, boolean packIn) { + MetaDataLoader loader = new MetaDataLoader(LoaderOptions.create(false, false, true), + MetaDataLoader.SUBTYPE_MANUAL, "p"); + if (!packIn) { + loader.setTypeRegistry(RegistryManifest.composeLoaderRegistry(List.of(), List.of("requirement-types"))); + } + loader.init(); + loader.load(List.of(new InMemoryStringSource(json, "meta.p.json"))); + return loader; + } + + @Test + public void defaultBundleLoadsAndCountsTheRequirement() { + MetaRoot root = load(WITH_REQUIREMENT, true).getRoot(); + RequirementCheck.Scan scan = RequirementCheck.scan(root, new RequirementCheck.Options(null, false)); + assertEquals(1, scan.addressed().size()); + } + + @Test + public void leftOutAModelWithNoRequirementsHasAnEmptySilentLedger() { + MetaRoot root = load(PLAIN, false).getRoot(); + assertNotNull(root); + RequirementCheck.Scan scan = RequirementCheck.scan(root, new RequirementCheck.Options(null, false)); + assertTrue(scan.addressed().isEmpty()); + assertTrue(RequirementCheck.check(root, scan).isEmpty()); + } + + @Test + public void leftOutAModelThatDeclaresARequirementFailsAtLoad() { + List codes = new java.util.ArrayList<>(); + try { + for (MetaDataException e : load(WITH_REQUIREMENT, false).getErrors()) { + codes.add(e.getCode().map(Enum::name).orElse("")); + } + } catch (MetaDataException e) { + codes.add(e.getCode().map(Enum::name).orElse("")); + } + assertTrue(codes.toString(), codes.contains("ERR_UNKNOWN_TYPE") || codes.contains("ERR_UNKNOWN_SUBTYPE")); + } +} diff --git a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java index 6376f5bc8d..b2a68377da 100644 --- a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java +++ b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java @@ -2,7 +2,14 @@ import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; +import com.github.mustachejava.DefaultMustacheVisitor; import com.github.mustachejava.MustacheException; +import com.github.mustachejava.MustacheVisitor; +import com.github.mustachejava.TemplateContext; +import com.github.mustachejava.codes.ValueCode; +import com.github.mustachejava.reflect.Guard; +import com.github.mustachejava.reflect.MissingWrapper; +import com.github.mustachejava.reflect.ReflectionObjectHandler; import java.io.IOException; import java.io.StringReader; @@ -70,6 +77,16 @@ public String render(RenderRequest req) { String rendered; try { DefaultMustacheFactory factory = new DefaultMustacheFactory() { + @Override + public MustacheVisitor createMustacheVisitor() { + return new DefaultMustacheVisitor(this) { + @Override + public void value(TemplateContext tc, String variable, boolean encoded) { + list.add(new CheckedValueCode(tc, this.df, variable, encoded)); + } + }; + } + @Override public void encode(String value, Writer writer) { try { @@ -79,6 +96,7 @@ public void encode(String value, Writer writer) { } } }; + factory.setObjectHandler(new MissingVariableObjectHandler()); Mustache compiled = factory.compile(new StringReader(expanded), refOrInline(req)); StringWriter writer = new StringWriter(); // Derived `has` accessors are part of the payload contract, not of the @@ -88,6 +106,10 @@ public void encode(String value, Writer writer) { compiled.execute(writer, PayloadAccessors.withDerivedAccessors(req.payload())).flush(); rendered = writer.toString(); } catch (MustacheException | IOException e) { + // A missing variable is raised from inside the engine, which wraps it; surface it as is. + for (Throwable t = e; t != null; t = t.getCause()) { + if (t instanceof RenderException re) throw re; + } throw new RenderException("Mustache compile/execute failed", e); } @@ -175,4 +197,41 @@ private static String preExpandPartials(String text, Provider provider, Deque guards) { + return new AbsentWrapper(name, guards.toArray(new Guard[0])); + } + } + + /** + * A variable tag whose name is absent from the payload raises, with the message the opt-in + * verify gate uses, so a typo like {@code {{nmae}}} fails on every render path. Section tags + * stay silent: an absent section is simply falsy. + */ + private static final class CheckedValueCode extends ValueCode { + CheckedValueCode(TemplateContext tc, DefaultMustacheFactory df, String variable, boolean encoded) { + super(tc, df, variable, encoded); + } + + @Override + public Writer execute(Writer writer, List scopes) { + if (!returnThis && oh.find(name, scopes) instanceof AbsentWrapper) { + throw new RenderException( + "render verify failed: " + Verify.ERR_VAR_NOT_ON_PAYLOAD + " (" + name + ")"); + } + return super.execute(writer, scopes); + } + } } diff --git a/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java b/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java index 87bfc38152..e6f24e7291 100644 --- a/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java +++ b/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java @@ -18,6 +18,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; /** * Cross-port render-conformance GATE — asserts Java's render output is @@ -67,6 +69,7 @@ public static List fixtures() throws IOException { try (Stream s = Files.list(FIXTURES_DIR)) { return s.filter(Files::isDirectory) .filter(d -> Files.isRegularFile(d.resolve("expected.txt")) + || Files.isRegularFile(d.resolve("expected-error.txt")) || Files.isRegularFile(d.resolve("expected/rendered.txt"))) .sorted() .map(p -> new Object[]{p.getFileName().toString(), p}) @@ -104,6 +107,22 @@ public void compareAgainstTsBaseline() throws IOException { ? new FilesystemProvider(fixtureDir) : new InMemoryProvider(Map.of()); + // A fixture carrying expected-error.txt must FAIL to render, and the message must contain + // the file's trimmed text (a missing template variable raises on every render path). + Path expectedErrorPath = fixtureDir.resolve("expected-error.txt"); + if (Files.isRegularFile(expectedErrorPath)) { + String want = Files.readString(expectedErrorPath, StandardCharsets.UTF_8).trim(); + try { + new Renderer().render(new RenderRequest( + template, null, payload, provider, format, null, null)); + fail("fixture '" + name + "' must fail to render with: " + want); + } catch (RenderException e) { + assertTrue("error for '" + name + "' must contain '" + want + "' but was: " + e.getMessage(), + e.getMessage().contains(want)); + } + return; + } + String actual = new Renderer().render(new RenderRequest( template, null, payload, provider, format, null, null)); String expected = Files.readString(expectedPath, StandardCharsets.UTF_8); diff --git a/server/java/render/src/test/java/com/metaobjects/render/RenderSnapshotTest.java b/server/java/render/src/test/java/com/metaobjects/render/RenderSnapshotTest.java index 9c5cddda95..0c8a077723 100644 --- a/server/java/render/src/test/java/com/metaobjects/render/RenderSnapshotTest.java +++ b/server/java/render/src/test/java/com/metaobjects/render/RenderSnapshotTest.java @@ -95,6 +95,9 @@ public void rendersToSnapshot() throws IOException { ? new FilesystemProvider(fixtureDir) : new InMemoryProvider(Map.of()); + // An expected-error.txt fixture is gated by RenderCrossPortReportTest; it has no snapshot. + if (Files.isRegularFile(fixtureDir.resolve("expected-error.txt"))) return; + String actual = new Renderer().render(new RenderRequest( template, null, payload, provider, format, null, null)); diff --git a/server/java/render/src/test/java/com/metaobjects/render/TypedPayloadRenderTest.java b/server/java/render/src/test/java/com/metaobjects/render/TypedPayloadRenderTest.java index da6b8b3f15..bc7fa1b879 100644 --- a/server/java/render/src/test/java/com/metaobjects/render/TypedPayloadRenderTest.java +++ b/server/java/render/src/test/java/com/metaobjects/render/TypedPayloadRenderTest.java @@ -130,7 +130,16 @@ public void hasFieldGateWorksOnBeanElementsLikeOnMaps() { @Test public void getClassIsNotExposedOnABean() { - assertEquals("[]", "[" + render("{{class}}{{getClass}}", new BItem("a")) + "]"); + // getClass is not a payload member, so the tag is a MISSING variable and raises (it must + // not render the class name). + for (String tag : List.of("{{class}}", "{{getClass}}")) { + try { + render(tag, new BItem("a")); + org.junit.Assert.fail(tag + " must not resolve on a bean"); + } catch (RenderException e) { + org.junit.Assert.assertTrue(e.getMessage(), e.getMessage().contains("ERR_VAR_NOT_ON_PAYLOAD")); + } + } } // ---- The overlay adds names; it never takes any away ----------------------------------- diff --git a/server/java/render/src/test/resources/snapshots/render-dotted-path-lookup.txt b/server/java/render/src/test/resources/snapshots/render-dotted-path-lookup.txt index 06ee3a698e..e051441bf1 100644 --- a/server/java/render/src/test/resources/snapshots/render-dotted-path-lookup.txt +++ b/server/java/render/src/test/resources/snapshots/render-dotted-path-lookup.txt @@ -1,5 +1,3 @@ name: Ada email: ada@example.test role: admin -missing-leaf: [] -missing-mid: [] diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index 25f82745aa..72b4012a04 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -260,8 +260,6 @@ def _register_subtypes( child_rules=[ ChildRule(TYPE_FIELD, "*"), ChildRule(TYPE_OBJECT, "*"), - # Capability requirements are declared beside the entities they describe. - ChildRule(TYPE_REQUIREMENT, "*"), ChildRule(TYPE_TEMPLATE, "*"), ChildRule(TYPE_VALIDATOR, "*"), ], @@ -317,6 +315,8 @@ def _register_subtypes( # TypeRegistry.extend (prompt.json declares it on object.value), matching the TS # promptProvider split. object.value carries only the shared object attrs in core. for _obj_sub in OBJECT_SUBTYPES: + if _obj_sub == OBJECT_SUBTYPE_REPORT: + continue # object.report is the reporting pack's (reporting_provider) core_provider.add( TypeDefinition( type=TYPE_OBJECT, @@ -351,147 +351,6 @@ def _register_subtypes( ) break -# FR-044 — object.report: declared dimensions x measures of ONE entity (@from), -# compiled to a read-only view. Its fields and identity are DERIVED (the loader -# refuses declared ones, R4), so it carries the projection's child set (no -# relationship / template). object.json's report block (extendsBase) is the -# strict graph the spec pass re-derives onto this def; it declares ONLY the five -# report attrs, so the shared discriminator attrs are pruned exactly as on -# projection. Mirrors the TS object provider. -for _def in core_provider._defs: # noqa: SLF001 (provider build-time enrichment) - if _def.type == TYPE_OBJECT and _def.sub_type == OBJECT_SUBTYPE_REPORT: - _def.child_rules[:] = list(_PROJECTION_CHILD_RULES) - _def.attrs.extend( - [ - AttrSchema(name=OBJECT_REPORT_ATTR_FROM, value_type=ATTR_SUBTYPE_STRING, required=True), - AttrSchema( - name=OBJECT_REPORT_ATTR_DIMENSIONS, - value_type=ATTR_SUBTYPE_STRING, - required=False, - is_array=True, - ), - AttrSchema( - name=OBJECT_REPORT_ATTR_MEASURES, - value_type=ATTR_SUBTYPE_STRING, - required=True, - is_array=True, - ), - AttrSchema(name=OBJECT_REPORT_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), - AttrSchema(name=OBJECT_REPORT_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), - # R8: the to-one path from @from whose entity supplies the report's rows. - AttrSchema(name=OBJECT_REPORT_ATTR_SPINE, value_type=ATTR_SUBTYPE_STRING, required=False), - ] - ) - break - -# FR-044 reporting vocabulary — dimension / measure / segment. Declared as -# children of object.entity (spec/metamodel/object.json — the strict-children -# pass derives the entity's dimension/measure/segment placements from it), never -# root-level, so the root keeps its five wildcards. One vocabulary, one block: a -# report names dimensions and measures, and both may reference a segment. -# measure.derived is NOT registered (it waits for FR-037 R5). Attr scoping is -# per-subtype exactly as spec/metamodel/reporting.json declares it. -_DIMENSION_COMMON_ATTRS = [ - AttrSchema(name=REPORTING_ATTR_OF, value_type=ATTR_SUBTYPE_STRING, required=True), - AttrSchema(name=REPORTING_ATTR_VIA, value_type=ATTR_SUBTYPE_STRING, required=False), -] -core_provider.add( - TypeDefinition( - type=TYPE_DIMENSION, - sub_type=DIMENSION_SUBTYPE_ATTRIBUTE, - factory=MetaDimension, - attrs=list(_DIMENSION_COMMON_ATTRS), - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) -core_provider.add( - TypeDefinition( - type=TYPE_DIMENSION, - sub_type=DIMENSION_SUBTYPE_TIME, - factory=MetaDimension, - attrs=[ - *_DIMENSION_COMMON_ATTRS, - # Weeks start Monday (ISO-8601) in every lowering; 'hour' is refused on - # a field.date by the loader (D4), not by the closed set. - AttrSchema( - name=REPORTING_ATTR_GRAINS, - value_type=ATTR_SUBTYPE_STRING, - required=True, - is_array=True, - allowed_values=TIME_GRAINS, - ), - ], - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) -core_provider.add( - TypeDefinition( - type=TYPE_MEASURE, - sub_type=MEASURE_SUBTYPE_AGGREGATE, - factory=MetaMeasure, - attrs=[ - AttrSchema( - name=REPORTING_ATTR_AGG, - value_type=ATTR_SUBTYPE_STRING, - required=True, - allowed_values=MEASURE_AGGS, - ), - # isArray: a bare string coerces to a one-element list (the tuple form - # is a distinct count, M2). Optional (M0): only @agg any/all may omit - # it, to quantify their @filter/@segment over the rows instead of - # aggregating a column. - AttrSchema( - name=REPORTING_ATTR_OF, - value_type=ATTR_SUBTYPE_STRING, - required=False, - is_array=True, - ), - AttrSchema(name=REPORTING_ATTR_DISTINCT, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), - AttrSchema(name=REPORTING_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), - AttrSchema(name=REPORTING_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), - # What the measure reads when it would otherwise be null; M7/M8 decide where it is legal. - AttrSchema(name=REPORTING_ATTR_DEFAULT, value_type=ATTR_SUBTYPE_INT, required=False), - ], - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) -core_provider.add( - TypeDefinition( - type=TYPE_MEASURE, - sub_type=MEASURE_SUBTYPE_RATIO, - factory=MetaMeasure, - attrs=[ - AttrSchema(name=REPORTING_ATTR_NUMERATOR, value_type=ATTR_SUBTYPE_STRING, required=True), - AttrSchema(name=REPORTING_ATTR_DENOMINATOR, value_type=ATTR_SUBTYPE_STRING, required=True), - AttrSchema(name=REPORTING_ATTR_DEFAULT, value_type=ATTR_SUBTYPE_INT, required=False), - ], - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) -# FR-044 R13: measure.derived — FR-037 R5's first arithmetic wave; no @default. -core_provider.add( - TypeDefinition( - type=TYPE_MEASURE, - sub_type=MEASURE_SUBTYPE_DERIVED, - factory=MetaMeasure, - attrs=[ - AttrSchema(name=REPORTING_ATTR_EXPR, value_type=ATTR_SUBTYPE_EXPRESSION, required=True), - ], - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) -core_provider.add( - TypeDefinition( - type=TYPE_SEGMENT, - sub_type=SEGMENT_SUBTYPE_FILTER, - factory=MetaSegment, - attrs=[ - AttrSchema(name=REPORTING_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=True), - ], - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) - # 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). @@ -789,109 +648,6 @@ def _register_subtypes( ) ) -# requirement.* (functional, architectural) — the capability ledger IS a metadata -# model (requirements-as-metadata ruling, amendment 3), so it is registered -# vocabulary rather than a hand-parsed side file: @status is an allowedValues enum -# the LOADER refuses a typo on. The axis is CHECK POLARITY, a genuine behaviour -# difference (ADR-0037 §2): `functional` is checked by EXISTENCE (nothing -# implements it -> fail), `architectural` by UNIVERSALITY (something violates it -# -> fail). Architectural carries no @level — levels come from -# object-in-focus decomposition and an architectural requirement is -# object-independent by definition. -# -# Hierarchy is NESTING, not a parent attr: requirement.functional admits nested -# requirement children (the strict graph in spec/metamodel/requirement.json, which -# _apply_strict_structural_children re-derives onto this registration). -# -# @implementedBy is deliberately NOT declared as a loader `references` descriptor. -# That pass always ERRORS on an unresolved target, and a requirement with status -# `planned` names nodes that do not exist YET — declaring -# it here would make those entries fail to load. The loader owns what is -# unconditional; `verify` owns @implementedBy resolution, whose severity depends on -# @status. -_REQUIREMENT_COMMON_ATTRS = [ - AttrSchema( - name=REQUIREMENT_ATTR_STATUS, - value_type=ATTR_SUBTYPE_STRING, - required=True, - allowed_values=REQUIREMENT_STATUSES, - ), - # What was DECIDED about the outstanding work -- a different question from - # whether the work is done, which is what @status answers. ABSENT means - # UNDECIDED, a real state and the one a review exists to find. - AttrSchema( - name=REQUIREMENT_ATTR_DISPOSITION, - value_type=ATTR_SUBTYPE_STRING, - required=False, - allowed_values=REQUIREMENT_DISPOSITIONS, - ), - # Issue/ticket references for outstanding work. Free-form and never resolved: - # verify has no network, so nothing here is checked to exist. - AttrSchema( - name=REQUIREMENT_ATTR_TRACKED_BY, - value_type=ATTR_SUBTYPE_STRING, - required=False, - is_array=True, - ), - AttrSchema(name=REQUIREMENT_ATTR_STATEMENT, value_type=ATTR_SUBTYPE_STRING, required=True), - AttrSchema(name=REQUIREMENT_ATTR_COUNTEREXAMPLE, value_type=ATTR_SUBTYPE_STRING, required=True), - # FR-039 -- the requirement that REPLACED a retired one. Declared BEFORE - # @implementedBy to match the canonical spec's child order, which the registry - # manifest emits verbatim and every port byte-matches. - AttrSchema( - name=REQUIREMENT_ATTR_SUPERSEDED_BY, - value_type=ATTR_SUBTYPE_STRING, - required=False, - ), - AttrSchema( - name=REQUIREMENT_ATTR_IMPLEMENTED_BY, - value_type=ATTR_SUBTYPE_STRING, - required=False, - is_array=True, - ), -] -core_provider.add( - TypeDefinition( - type=TYPE_REQUIREMENT, - sub_type=REQUIREMENT_SUBTYPE_FUNCTIONAL, - factory=MetaRequirement, - attrs=[ - # REQUIRED on functional: levels are the object-in-focus decomposition - # and a functional requirement always sits at one. - AttrSchema(name=REQUIREMENT_ATTR_LEVEL, value_type=ATTR_SUBTYPE_INT, required=True), - *_REQUIREMENT_COMMON_ATTRS, - ], - child_rules=[ - ChildRule(TYPE_ATTR, "*"), - # Hierarchy IS nesting — an L1 solution contains its L2 segments. - ChildRule(TYPE_REQUIREMENT, "*"), - ], - ) -) -core_provider.add( - TypeDefinition( - type=TYPE_REQUIREMENT, - sub_type=REQUIREMENT_SUBTYPE_ARCHITECTURAL, - factory=MetaRequirement, - attrs=[ - # OPTIONAL on architectural: absent means a flat, object-independent - # policy (the original and still the default form); present opts the - # node into a levelled tree, e.g. a quality taxonomy over the - # non-functional set. Opt-in precisely so that adding a taxonomy over - # existing flat policies cannot invalidate them. - AttrSchema(name=REQUIREMENT_ATTR_LEVEL, value_type=ATTR_SUBTYPE_INT, required=False), - *_REQUIREMENT_COMMON_ATTRS, - ], - child_rules=[ - ChildRule(TYPE_ATTR, "*"), - # BOTH subtypes nest. Declaring this on `functional` only was an - # omission, not a design: it made an architectural node nestable under - # a FUNCTIONAL parent but never under another architectural one. - ChildRule(TYPE_REQUIREMENT, "*"), - ], - ) -) - # relationship.* (base, association, aggregation, composition). # @onDelete / @onUpdate are validated against REFERENTIAL_ACTIONS — kebab-case # values (cascade / set-null / restrict / no-action). Defaults derive from the @@ -1040,7 +796,6 @@ def _register_subtypes( AttrSchema(name=ORIGIN_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), AttrSchema(name=ORIGIN_ATTR_DISTINCT, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), AttrSchema(name=ORIGIN_ATTR_ORDER_BY, value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), - AttrSchema(name=ORIGIN_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), ], child_rules=[ChildRule(TYPE_ATTR, "*")], ) @@ -1072,7 +827,6 @@ def _register_subtypes( AttrSchema(name=ORIGIN_ATTR_VIA, value_type=ATTR_SUBTYPE_STRING, required=False), AttrSchema(name=ORIGIN_ATTR_ORDER_BY, value_type=ATTR_SUBTYPE_STRING, required=True, is_array=True), AttrSchema(name=ORIGIN_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), - AttrSchema(name=ORIGIN_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), ], child_rules=[ChildRule(TYPE_ATTR, "*")], ) @@ -1296,6 +1050,8 @@ def _register_subtypes( from .meta.persistence.view_expressions.view_expressions_provider import ( # noqa: E402 view_expressions_provider, ) +from .meta.core.reporting.reporting_provider import reporting_provider # noqa: E402 +from .meta.core.requirement.requirements_provider import requirements_provider # noqa: E402 core_providers: list[Provider] = [ core_provider, @@ -1310,6 +1066,9 @@ def _register_subtypes( # providers, in the default bundle so every existing model loads unchanged. rules_provider, view_expressions_provider, + # Reporting (FR-044) and requirements are their own packs too, in the default bundle. + reporting_provider, + requirements_provider, ] # #265 — the ids of the LIBRARY providers above, as a frozen set. Consulted by diff --git a/server/python/src/metaobjects/loader/validate_rules.py b/server/python/src/metaobjects/loader/validate_rules.py index bca8e40abb..0d37c3626c 100644 --- a/server/python/src/metaobjects/loader/validate_rules.py +++ b/server/python/src/metaobjects/loader/validate_rules.py @@ -100,7 +100,7 @@ TRANSITION_SUBTYPE_ACTION, ) from ..meta.meta_data import MetaData -from ..naming_refs import effective_package_of +from ..naming_refs import effective_package_of, top_level_node_of from ..meta.persistence.source.meta_source import MetaSource from ..shared.base_types import ( TYPE_API, @@ -494,6 +494,73 @@ def validate_rules(root: MetaData, errors: list[MetaError]) -> None: "rename one, or declare both identically to expose one operation in two APIs.", ) _check_api_routes(ops, sink) + _check_permission_names(root, sink) + + +def _permission_name_of(node: MetaData, owner: MetaData, path: str) -> tuple[str, bool]: + """The name a permission point asks the policy about: its @permission, else + ``.`` (the path is ````, or ``.`` for a + transition's command), with the package prefix dropped when there is none. ``::`` and + ``.`` both separate path segments, so ``p::Order`` + ``open`` and ``p`` + ``Order.open`` + are one name. Returns (name, derived).""" + declared = node.get_meta_attr(OPERATION_ATTR_PERMISSION) + pkg = effective_package_of(top_level_node_of(owner)) + if isinstance(declared, str): + name = declared + else: + name = path if pkg == "" else f"{pkg}.{path}" + return name.replace("::", "."), not isinstance(declared, str) + + +def _check_permission_names(root: MetaData, sink: _Sink) -> None: + """P3: two permission points, one name, at least one of them derived (ADR-0066 section 1). + Points are every non-public operation and every transition of a live concrete entity + (a transition derives a command each). Compared case-sensitively (a grant key is exact). + Transitions register first, so the error lands on the operation when one meets a transition. + Two DECLARED @permission values may be equal: that sharing is the point.""" + by_name: dict[str, list[tuple[MetaData, bool]]] = {} + + def register(node: MetaData, owner: MetaData, path: str) -> None: + if node.get_meta_attr(OPERATION_ATTR_PUBLIC) is True: + return + name, derived = _permission_name_of(node, owner, path) + points = by_name.setdefault(name, []) + clash = next( + ( + q + for q, q_derived in points + if q is not node + and (derived or q_derived) + and not ( + node.type == TYPE_OPERATION and q.type == TYPE_OPERATION and _same_operation(q, node) + ) + ), + None, + ) + if clash is not None: + sink.add( + node, + ErrorCode.ERR_TRANSITION_NAME_COLLISION, + f'{node.type}.{node.sub_type} "{_label(node)}" asks the policy about the permission name ' + f'"{name}", which {clash.type}.{clash.sub_type} "{_label(clash)}" also asks about, and one ' + "of the two names is derived rather than declared; declare a distinct @permission on one, " + "or rename it.", + ) + points.append((node, derived)) + + for entity in root.children(): + if entity.type != TYPE_OBJECT or entity.sub_type != OBJECT_SUBTYPE_ENTITY: + continue + if entity.is_abstract or not lifecycle_is_live(entity): + continue + for t in entity_transitions(entity): + register(t, entity, f"{entity.name}.{t.name}") + for api in root.children(): + if api.type != TYPE_API: + continue + for op in api.children(): + if op.type == TYPE_OPERATION: + register(op, api, op.name) def _ref_identity(op: MetaData, attr: str) -> object: diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 9205b36253..967820edc7 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -153,6 +153,10 @@ ) from ..shared.separators import PACKAGE_SEP from ..meta.core.object.object_constants import ( + OBJECT_PROJECTION_ATTR_GRAIN, + OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL, + OBJECT_PROJECTION_ATTR_UNION, + OBJECT_PROJECTION_ATTR_UNION_ALL, OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE, @@ -231,6 +235,8 @@ def run_validations( _validate_datagrid_filter_values(root, errors) # #207 — object.projection view-level @filter reference validation. _validate_projection_filter(root, errors) + # rc.21 part B — @union / @grain / @grainOrdinal shape rules on object.projection. + _validate_projection_union_and_grain(root, errors) # Origin @segment names a segment of the related entity; a correlated @filter operand names # a base-row field. _validate_origin_segments_and_correlation(root, errors) @@ -1933,6 +1939,115 @@ def _filter_keys(filter_value: object, out: list[str] | None = None) -> list[str return out +def _own_string_list(node: MetaData, name: str) -> list[str]: + # ADR-0039 sanctioned own: a projection's @union names ITS view's shape. + raw = node.attr(name) + if raw is None: + return [] + if isinstance(raw, (list, tuple)): + return [str(x) for x in raw] + return [str(raw)] + + +def _describe_union_field(f: MetaData) -> str: + """One union column as a comparable string: name, subtype, array-ness, @column and an + enum's members and value maps.""" + arr = "[]" if f.resolved_is_array() else "" + col = f.get_meta_attr("column") + out = f"{f.name}: field.{f.sub_type}{arr}" + if isinstance(col, str): + out += f" @column {col}" + if f.sub_type == FIELD_SUBTYPE_ENUM: + shape = [ + f.get_meta_attr(FIELD_ATTR_VALUES), + f.get_meta_attr(FIELD_ATTR_INT_VALUE_MAP), + f.get_meta_attr(FIELD_ATTR_STRING_VALUE_MAP), + ] + out += " " + json.dumps(shape, separators=(",", ":")) + return out + + +def _validate_projection_union_and_grain(root: MetaData, errors: list[MetaError]) -> None: + """rc.21 part B -- the projection shapes beside a plain view (mirrors TS + ``validateProjectionUnionAndGrain``): ``@union`` members share this view's effective + fields in order; ``@grain`` names a base-entity jsonb ``field.object`` array; + ``@grainOrdinal`` names a bare ``field.int``/``field.long`` of the projection. + ERR_BAD_ATTR_VALUE otherwise.""" + # ADR-0039 sanctioned own: root has no super; every projection is declared at root level. + for obj in root.own_children(): + if obj.type != TYPE_OBJECT or obj.sub_type != OBJECT_SUBTYPE_PROJECTION: + continue + + def bad(message: str, obj: MetaData = obj) -> None: + errors.append(MetaError( + f"object.projection {obj.name}: {message}", + ErrorCode.ERR_BAD_ATTR_VALUE, envelope=obj.source)) + + union_attr = OBJECT_PROJECTION_ATTR_UNION + # ADR-0039 sanctioned own: @union / @grain describe ITS view; an extender declares its own. + has_union = obj.attr(union_attr) is not None + if obj.attr(OBJECT_PROJECTION_ATTR_UNION_ALL) is not None and not has_union: + bad(f"@{OBJECT_PROJECTION_ATTR_UNION_ALL} needs @{union_attr}.") + if has_union: + referrer_pkg = obj.package or obj.file_default_package or "" + mine = [_describe_union_field(c) for c in obj.children() if c.type == TYPE_FIELD] + for name in _own_string_list(obj, union_attr): + member = resolve_object_ref(root, name, referrer_pkg) + if member is None or member.type != TYPE_OBJECT or member.sub_type != OBJECT_SUBTYPE_PROJECTION: + bad(f'@{union_attr} names "{name}", which is not an object.projection.') + continue + if member is obj: + bad(f"@{union_attr} names the projection itself.") + continue + # ADR-0039 sanctioned own: a member's own @union would be flattened away, silently. + if member.attr(union_attr) is not None: + bad(f'@{union_attr} member "{member.name}" declares its own @{union_attr}; ' + "name its members here instead.") + theirs = [_describe_union_field(c) for c in member.children() if c.type == TYPE_FIELD] + if mine != theirs: + bad(f'@{union_attr} member "{member.name}" has a different shape: ' + f"({', '.join(theirs)}) where this view is ({', '.join(mine)}). " + "A union's members have the same fields, in order.") + grain_attr = OBJECT_PROJECTION_ATTR_GRAIN + ordinal_attr = OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL + grain = obj.attr(grain_attr) + ordinal = obj.attr(ordinal_attr) + if ordinal is not None and grain is None: + bad(f"@{ordinal_attr} needs @{grain_attr}.") + if not isinstance(grain, str): + continue + base = _derive_base_entity(obj, root, obj.package or "", "@grain", obj.source, []) + field = None + if base is not None: + field = next((c for c in base.children() if c.type == TYPE_FIELD and c.name == grain), None) + storage = field.get_meta_attr(FIELD_ATTR_STORAGE) if field is not None else None + if ( + field is None + or field.sub_type != FIELD_SUBTYPE_OBJECT + or not field.resolved_is_array() + or (storage is not None and storage != "jsonb") + or bound_ref_target(field, FIELD_ATTR_OBJECT_REF) is None + ): + base_note = f' "{base.name}"' if base is not None else "" + bad(f'@{grain_attr} "{grain}" must name a field.object array (isArray, jsonb storage, ' + f"with @objectRef) of the base entity{base_note}.") + for f in (c for c in obj.children() if c.type == TYPE_FIELD): + # ADR-0039 sanctioned own: origin.* never inherits (ADR-0029). + if any(c.type == TYPE_ORIGIN and c.sub_type == ORIGIN_SUBTYPE_AGGREGATE for c in f.own_children()): + bad(f'"{f.name}" is an origin.aggregate; a @grain view has one row per element and groups nothing.') + if ordinal is not None: + f = next((c for c in obj.children() if c.type == TYPE_FIELD and c.name == ordinal), None) + # ADR-0039 sanctioned own: origin.* never inherits (ADR-0029). + if ( + f is None + or f.sub_type not in (FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG) + or any(c.type == TYPE_ORIGIN for c in f.own_children()) + or f.super_data is not None + ): + bad(f'@{ordinal_attr} "{ordinal}" must name a field.int or field.long of the ' + "projection, with no origin and no extends.") + + def _validate_projection_filter( root: MetaData, errors: list[MetaError], diff --git a/server/python/src/metaobjects/meta/core/reporting/reporting_provider.py b/server/python/src/metaobjects/meta/core/reporting/reporting_provider.py new file mode 100644 index 0000000000..4883611cff --- /dev/null +++ b/server/python/src/metaobjects/meta/core/reporting/reporting_provider.py @@ -0,0 +1,223 @@ +"""reporting_provider -- the reporting pack (cross-port ``metaobjects-reporting``). + +FR-044: ``dimension.*``, ``measure.*``, ``segment.filter`` and ``object.report``, plus +the rules that admit them on types core owns (an entity holds dimension / measure / +segment children) and the ``@segment`` attr on ``origin.aggregate`` / ``origin.first``; +those ride in ``reporting.json`` ``extends`` and are applied below. It is its OWN +provider so a project can leave it out; it is in the default bundle +(``core_providers``), so every existing model loads unchanged. ``object.report`` folds +``object.base`` (``extends_base``) from the core provider's registration. Mirrors the TS +``reportingProvider``. +""" +from __future__ import annotations + +from ....provider import Provider +from ....registry import AttrSchema, ChildRule, TypeDefinition, TypeRegistry +from ....shared.base_types import ( + TYPE_ATTR, + TYPE_DIMENSION, + TYPE_FIELD, + TYPE_IDENTITY, + TYPE_LAYOUT, + TYPE_MEASURE, + TYPE_OBJECT, + TYPE_SEGMENT, + TYPE_SOURCE, +) +from ...provider_extends import register_extends +from ..attr.attr_constants import ( + ATTR_SUBTYPE_BOOLEAN, + ATTR_SUBTYPE_EXPRESSION, + ATTR_SUBTYPE_FILTER, + ATTR_SUBTYPE_INT, + ATTR_SUBTYPE_STRING, +) +from ..object.meta_object import MetaObject +from ..object.object_constants import ( + OBJECT_REPORT_ATTR_DIMENSIONS, + OBJECT_REPORT_ATTR_FILTER, + OBJECT_REPORT_ATTR_FROM, + OBJECT_REPORT_ATTR_MEASURES, + OBJECT_REPORT_ATTR_SEGMENT, + OBJECT_REPORT_ATTR_SPINE, + OBJECT_SUBTYPE_REPORT, +) +from .meta_dimension import MetaDimension +from .meta_measure import MetaMeasure +from .meta_segment import MetaSegment +from .reporting_constants import ( + DIMENSION_SUBTYPE_ATTRIBUTE, + DIMENSION_SUBTYPE_TIME, + MEASURE_AGGS, + MEASURE_SUBTYPE_AGGREGATE, + MEASURE_SUBTYPE_DERIVED, + MEASURE_SUBTYPE_RATIO, + REPORTING_ATTR_AGG, + REPORTING_ATTR_DEFAULT, + REPORTING_ATTR_DENOMINATOR, + REPORTING_ATTR_DISTINCT, + REPORTING_ATTR_EXPR, + REPORTING_ATTR_FILTER, + REPORTING_ATTR_GRAINS, + REPORTING_ATTR_NUMERATOR, + REPORTING_ATTR_OF, + REPORTING_ATTR_SEGMENT, + REPORTING_ATTR_VIA, + SEGMENT_SUBTYPE_FILTER, + TIME_GRAINS, +) + +reporting_provider = Provider("metaobjects-reporting", dependencies=("metaobjects-core-types",)) + +# FR-044 -- object.report: declared dimensions x measures of ONE entity (@from), +# compiled to a read-only view. Its fields and identity are DERIVED (the loader +# refuses declared ones, R4), so it carries the projection's child set (no +# relationship / template). reporting.json's report block (extends_base) is the +# strict graph the spec pass re-derives onto this def; it declares ONLY the report +# attrs, so the shared discriminator attrs folded from object.base are pruned +# exactly as on projection. +reporting_provider.add( + TypeDefinition( + type=TYPE_OBJECT, + sub_type=OBJECT_SUBTYPE_REPORT, + factory=MetaObject, + extends_base=True, + child_rules=[ + ChildRule(TYPE_FIELD, "*"), + ChildRule(TYPE_IDENTITY, "*"), + ChildRule(TYPE_ATTR, "*"), + ChildRule(TYPE_SOURCE, "*"), + ChildRule(TYPE_LAYOUT, "*"), + ], + attrs=[ + AttrSchema(name=OBJECT_REPORT_ATTR_FROM, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema( + name=OBJECT_REPORT_ATTR_DIMENSIONS, + value_type=ATTR_SUBTYPE_STRING, + required=False, + is_array=True, + ), + AttrSchema( + name=OBJECT_REPORT_ATTR_MEASURES, + value_type=ATTR_SUBTYPE_STRING, + required=True, + is_array=True, + ), + AttrSchema(name=OBJECT_REPORT_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name=OBJECT_REPORT_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), + # R8: the to-one path from @from whose entity supplies the report's rows. + AttrSchema(name=OBJECT_REPORT_ATTR_SPINE, value_type=ATTR_SUBTYPE_STRING, required=False), + ], + ) +) + +# One vocabulary, one block: a report names dimensions and measures, and both may +# reference a segment. Attr scoping is per-subtype exactly as +# spec/metamodel/reporting.json declares it. +_DIMENSION_COMMON_ATTRS = [ + AttrSchema(name=REPORTING_ATTR_OF, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name=REPORTING_ATTR_VIA, value_type=ATTR_SUBTYPE_STRING, required=False), +] +reporting_provider.add( + TypeDefinition( + type=TYPE_DIMENSION, + sub_type=DIMENSION_SUBTYPE_ATTRIBUTE, + factory=MetaDimension, + attrs=list(_DIMENSION_COMMON_ATTRS), + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) +reporting_provider.add( + TypeDefinition( + type=TYPE_DIMENSION, + sub_type=DIMENSION_SUBTYPE_TIME, + factory=MetaDimension, + attrs=[ + *_DIMENSION_COMMON_ATTRS, + # Weeks start Monday (ISO-8601) in every lowering; 'hour' is refused on + # a field.date by the loader (D4), not by the closed set. + AttrSchema( + name=REPORTING_ATTR_GRAINS, + value_type=ATTR_SUBTYPE_STRING, + required=True, + is_array=True, + allowed_values=TIME_GRAINS, + ), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) +reporting_provider.add( + TypeDefinition( + type=TYPE_MEASURE, + sub_type=MEASURE_SUBTYPE_AGGREGATE, + factory=MetaMeasure, + attrs=[ + AttrSchema( + name=REPORTING_ATTR_AGG, + value_type=ATTR_SUBTYPE_STRING, + required=True, + allowed_values=MEASURE_AGGS, + ), + # isArray: a bare string coerces to a one-element list (the tuple form + # is a distinct count, M2). Optional (M0): only @agg any/all may omit + # it, to quantify their @filter/@segment over the rows instead of + # aggregating a column. + AttrSchema( + name=REPORTING_ATTR_OF, + value_type=ATTR_SUBTYPE_STRING, + required=False, + is_array=True, + ), + AttrSchema(name=REPORTING_ATTR_DISTINCT, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), + AttrSchema(name=REPORTING_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), + AttrSchema(name=REPORTING_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), + # What the measure reads when it would otherwise be null; M7/M8 decide where it is legal. + AttrSchema(name=REPORTING_ATTR_DEFAULT, value_type=ATTR_SUBTYPE_INT, required=False), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) +reporting_provider.add( + TypeDefinition( + type=TYPE_MEASURE, + sub_type=MEASURE_SUBTYPE_RATIO, + factory=MetaMeasure, + attrs=[ + AttrSchema(name=REPORTING_ATTR_NUMERATOR, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name=REPORTING_ATTR_DENOMINATOR, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name=REPORTING_ATTR_DEFAULT, value_type=ATTR_SUBTYPE_INT, required=False), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) +# FR-044 R13: measure.derived — FR-037 R5's first arithmetic wave; no @default. +reporting_provider.add( + TypeDefinition( + type=TYPE_MEASURE, + sub_type=MEASURE_SUBTYPE_DERIVED, + factory=MetaMeasure, + attrs=[ + AttrSchema(name=REPORTING_ATTR_EXPR, value_type=ATTR_SUBTYPE_EXPRESSION, required=True), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) +reporting_provider.add( + TypeDefinition( + type=TYPE_SEGMENT, + sub_type=SEGMENT_SUBTYPE_FILTER, + factory=MetaSegment, + attrs=[ + AttrSchema(name=REPORTING_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=True), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) + + +def _register(registry: TypeRegistry) -> None: + register_extends(registry, "reporting.json") + + +reporting_provider.on_register(_register) diff --git a/server/python/src/metaobjects/meta/core/requirement/requirements_provider.py b/server/python/src/metaobjects/meta/core/requirement/requirements_provider.py new file mode 100644 index 0000000000..35589b8938 --- /dev/null +++ b/server/python/src/metaobjects/meta/core/requirement/requirements_provider.py @@ -0,0 +1,145 @@ +"""requirements_provider -- the requirements pack (cross-port ``metaobjects-requirements``). + +``requirement.functional`` / ``requirement.architectural``, and the rule that admits a +``requirement`` on a document root (``requirement.json`` ``extends``, applied below). It +is its OWN provider so a project can leave it out; it is in the default bundle +(``core_providers``), so every existing model loads unchanged. Compose it out and a model +that declares a requirement fails at load; one that declares none sees nothing. Mirrors +the TS ``requirementsProvider``. +""" +from __future__ import annotations + +from ....provider import Provider +from ....registry import AttrSchema, ChildRule, TypeDefinition, TypeRegistry +from ....shared.base_types import TYPE_ATTR, TYPE_REQUIREMENT +from ...provider_extends import register_extends +from ..attr.attr_constants import ATTR_SUBTYPE_INT, ATTR_SUBTYPE_STRING +from .meta_requirement import MetaRequirement +from .requirement_constants import ( + REQUIREMENT_ATTR_COUNTEREXAMPLE, + REQUIREMENT_ATTR_DISPOSITION, + REQUIREMENT_ATTR_IMPLEMENTED_BY, + REQUIREMENT_ATTR_LEVEL, + REQUIREMENT_ATTR_STATEMENT, + REQUIREMENT_ATTR_STATUS, + REQUIREMENT_ATTR_SUPERSEDED_BY, + REQUIREMENT_ATTR_TRACKED_BY, + REQUIREMENT_DISPOSITIONS, + REQUIREMENT_STATUSES, + REQUIREMENT_SUBTYPE_ARCHITECTURAL, + REQUIREMENT_SUBTYPE_FUNCTIONAL, +) + +requirements_provider = Provider( + "metaobjects-requirements", dependencies=("metaobjects-core-types",) +) + +# requirement.* (functional, architectural) — the capability ledger IS a metadata +# model (requirements-as-metadata ruling, amendment 3), so it is registered +# vocabulary rather than a hand-parsed side file: @status is an allowedValues enum +# the LOADER refuses a typo on. The axis is CHECK POLARITY, a genuine behaviour +# difference (ADR-0037 §2): `functional` is checked by EXISTENCE (nothing +# implements it -> fail), `architectural` by UNIVERSALITY (something violates it +# -> fail). Architectural carries no @level — levels come from +# object-in-focus decomposition and an architectural requirement is +# object-independent by definition. +# +# Hierarchy is NESTING, not a parent attr: requirement.functional admits nested +# requirement children (the strict graph in spec/metamodel/requirement.json, which +# _apply_strict_structural_children re-derives onto this registration). +# +# @implementedBy is deliberately NOT declared as a loader `references` descriptor. +# That pass always ERRORS on an unresolved target, and a requirement with status +# `planned` names nodes that do not exist YET — declaring +# it here would make those entries fail to load. The loader owns what is +# unconditional; `verify` owns @implementedBy resolution, whose severity depends on +# @status. +_REQUIREMENT_COMMON_ATTRS = [ + AttrSchema( + name=REQUIREMENT_ATTR_STATUS, + value_type=ATTR_SUBTYPE_STRING, + required=True, + allowed_values=REQUIREMENT_STATUSES, + ), + # What was DECIDED about the outstanding work -- a different question from + # whether the work is done, which is what @status answers. ABSENT means + # UNDECIDED, a real state and the one a review exists to find. + AttrSchema( + name=REQUIREMENT_ATTR_DISPOSITION, + value_type=ATTR_SUBTYPE_STRING, + required=False, + allowed_values=REQUIREMENT_DISPOSITIONS, + ), + # Issue/ticket references for outstanding work. Free-form and never resolved: + # verify has no network, so nothing here is checked to exist. + AttrSchema( + name=REQUIREMENT_ATTR_TRACKED_BY, + value_type=ATTR_SUBTYPE_STRING, + required=False, + is_array=True, + ), + AttrSchema(name=REQUIREMENT_ATTR_STATEMENT, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name=REQUIREMENT_ATTR_COUNTEREXAMPLE, value_type=ATTR_SUBTYPE_STRING, required=True), + # FR-039 -- the requirement that REPLACED a retired one. Declared BEFORE + # @implementedBy to match the canonical spec's child order, which the registry + # manifest emits verbatim and every port byte-matches. + AttrSchema( + name=REQUIREMENT_ATTR_SUPERSEDED_BY, + value_type=ATTR_SUBTYPE_STRING, + required=False, + ), + AttrSchema( + name=REQUIREMENT_ATTR_IMPLEMENTED_BY, + value_type=ATTR_SUBTYPE_STRING, + required=False, + is_array=True, + ), +] +requirements_provider.add( + TypeDefinition( + type=TYPE_REQUIREMENT, + sub_type=REQUIREMENT_SUBTYPE_FUNCTIONAL, + factory=MetaRequirement, + attrs=[ + # REQUIRED on functional: levels are the object-in-focus decomposition + # and a functional requirement always sits at one. + AttrSchema(name=REQUIREMENT_ATTR_LEVEL, value_type=ATTR_SUBTYPE_INT, required=True), + *_REQUIREMENT_COMMON_ATTRS, + ], + child_rules=[ + ChildRule(TYPE_ATTR, "*"), + # Hierarchy IS nesting — an L1 solution contains its L2 segments. + ChildRule(TYPE_REQUIREMENT, "*"), + ], + ) +) +requirements_provider.add( + TypeDefinition( + type=TYPE_REQUIREMENT, + sub_type=REQUIREMENT_SUBTYPE_ARCHITECTURAL, + factory=MetaRequirement, + attrs=[ + # OPTIONAL on architectural: absent means a flat, object-independent + # policy (the original and still the default form); present opts the + # node into a levelled tree, e.g. a quality taxonomy over the + # non-functional set. Opt-in precisely so that adding a taxonomy over + # existing flat policies cannot invalidate them. + AttrSchema(name=REQUIREMENT_ATTR_LEVEL, value_type=ATTR_SUBTYPE_INT, required=False), + *_REQUIREMENT_COMMON_ATTRS, + ], + child_rules=[ + ChildRule(TYPE_ATTR, "*"), + # BOTH subtypes nest. Declaring this on `functional` only was an + # omission, not a design: it made an architectural node nestable under + # a FUNCTIONAL parent but never under another architectural one. + ChildRule(TYPE_REQUIREMENT, "*"), + ], + ) +) + + +def _register(registry: TypeRegistry) -> None: + register_extends(registry, "requirement.json") + + +requirements_provider.on_register(_register) diff --git a/server/python/src/metaobjects/registry.py b/server/python/src/metaobjects/registry.py index 160918f4ec..9e02d6b5b5 100644 --- a/server/python/src/metaobjects/registry.py +++ b/server/python/src/metaobjects/registry.py @@ -106,6 +106,10 @@ class TypeDefinition: # owns). Kept separately so the strict structural pass, which re-derives the rest # of ``child_rules`` from the shared spec, does not discard them. extended_child_rules: list[ChildRule] = field(default_factory=list) + # The type folds ``.base`` of ANOTHER provider's registration, like the + # ``extendsBase`` of a spec type: attrs it does not redeclare come from the base, + # stamped with the base's owner, never as a new claim by this provider. + extends_base: bool = False @property def key(self) -> tuple[str, str]: @@ -211,6 +215,12 @@ def _check_attr_ownership(self, type_: str, sub_type: str, name: str) -> None: def register(self, definition: TypeDefinition) -> None: self._check_not_sealed(f'register("{definition.key}")') + folded: list[AttrSchema] = [] + if definition.extends_base and definition.sub_type != SUBTYPE_BASE: + base = self._defs.get((definition.type, SUBTYPE_BASE)) + if base is not None: + own = {a.name for a in definition.attrs} + folded = [a for a in base.attrs if a.name not in own] # ADR-0062: refuse a name another provider already put on a related slot, BEFORE # the definition becomes visible, so a refused registration leaves no trace. for attr in definition.attrs: @@ -226,7 +236,7 @@ def register(self, definition: TypeDefinition) -> None: type=definition.type, sub_type=definition.sub_type, factory=definition.factory, - attrs=list(definition.attrs), + attrs=[*folded, *definition.attrs], child_rules=list(definition.child_rules), # FR-033 — carry the documentation surface + placement claim onto the # per-registry copy (copy the mutable parents list so a later extend() @@ -247,7 +257,14 @@ def register(self, definition: TypeDefinition) -> None: # TypeDefinition objects before `register()` is ever called). origin = self._current_provider_id or LIBRARY_ATTR_ORIGIN for attr in self._defs[definition.key].attrs: - self._attr_provenance[(definition.type, definition.sub_type, attr.name)] = origin + if any(attr is f for f in folded): + # Folded unchanged from the base: not this provider's claim. + base_origin = self._attr_provenance.get( + (definition.type, SUBTYPE_BASE, attr.name), LIBRARY_ATTR_ORIGIN + ) + self._attr_provenance[(definition.type, definition.sub_type, attr.name)] = base_origin + else: + self._attr_provenance[(definition.type, definition.sub_type, attr.name)] = origin def attr_origin(self, type_: str, sub_type: str, attr_name: str) -> str: """The provider id that registered/extended ``attr_name`` on ``(type_, sub_type)``, diff --git a/server/python/src/metaobjects/render/jinja_render.py b/server/python/src/metaobjects/render/jinja_render.py index a283dc215d..00a8c916cc 100644 --- a/server/python/src/metaobjects/render/jinja_render.py +++ b/server/python/src/metaobjects/render/jinja_render.py @@ -10,8 +10,9 @@ ``| e`` / ``| forceescape`` escape with that same escaper, as in nunjucks; * what a macro, a ``call`` block or a block ``set`` renders is already escaped, so printing it does not escape it again (nunjucks returns those as safe strings); -* a lookup on a missing key renders empty however deep it chains (``v.x.y``), as in - nunjucks; every engine failure surfaces as ``JinjaRenderError``; +* a lookup on a missing key chains however deep (``v.x.y``) and stays undefined, and + PRINTING an undefined value raises ``render verify failed: ERR_VAR_NOT_ON_PAYLOAD`` (a + present null prints empty); every engine failure surfaces as ``JinjaRenderError``; * a trailing newline is kept (jinja2 drops it by default; nunjucks and Mustache keep it); * the static template graph is checked first, so a cycle or a missing template fails with the Mustache path's messages (``partial cycle:``, ``unresolved partial:``). @@ -27,7 +28,7 @@ from .engine import TEMPLATE_ENGINE_JINJA, partial_engine_message, partial_engine_mismatch from .jinja_verify import jinja2_module, parse_jinja, ref_of_template_name from .renderer import _stringify -from .verify import MAX_DEPTH, Provider +from .verify import ERR_VAR_NOT_ON_PAYLOAD, MAX_DEPTH, Provider class JinjaRenderError(Exception): @@ -106,6 +107,11 @@ def escape(value: Any) -> Any: return value if isinstance(value, (Markup, _Rendered)) else forceescape(value) def finalize(value: Any) -> str: + # A value absent from the payload is a missing variable and raises, as on the + # Mustache path; a present null still prints empty. The engine does not hand the + # variable's name over at this point, so the message carries none. + if isinstance(value, jinja2.Undefined): + raise JinjaRenderError(f"render verify failed: {ERR_VAR_NOT_ON_PAYLOAD}") return str(escape(value)) def load(name: str) -> tuple[str, None, Any] | None: diff --git a/server/python/src/metaobjects/render/renderer.py b/server/python/src/metaobjects/render/renderer.py index a230dcf9ba..c8f79b9410 100644 --- a/server/python/src/metaobjects/render/renderer.py +++ b/server/python/src/metaobjects/render/renderer.py @@ -32,6 +32,7 @@ from .payload_accessors import with_derived_accessors from .verify import ( ERR_REQUIRED_SLOT_UNUSED, + ERR_VAR_NOT_ON_PAYLOAD, MAX_DEPTH, InMemoryProvider, PayloadField, @@ -333,7 +334,12 @@ def _emit( if isinstance(tok, _Text): out.append(tok.value) elif isinstance(tok, _Interp): - value = _resolve(tok.path, stack) + found, value = _resolve_found(tok.path, stack) + if not found: + # A name on no frame of the payload is a missing variable: raised on every + # render path, with the message the opt-in verify gate uses. A present null + # is a value and renders empty. + raise RenderError(f"render verify failed: {ERR_VAR_NOT_ON_PAYLOAD} ({tok.path})") if value is None or value is False: continue text = _stringify(value) @@ -369,22 +375,29 @@ def _resolve(path: str, stack: list[Any]) -> Any: """Mustache lookup: first segment walks the context stack innermost→outermost; remaining segments descend into the resolved value. Implicit iterator ``{{.}}`` returns the top of the stack.""" + return _resolve_found(path, stack)[1] + + +def _resolve_found(path: str, stack: list[Any]) -> tuple[bool, Any]: + """:func:`_resolve` that also says whether the name was FOUND: a name absent from every + frame (or a dotted path that leaves the payload, or descends through a null) is not + found; a key present with a null value is found.""" if path == ".": - return stack[-1] if stack else None + return True, (stack[-1] if stack else None) segs = path.split(".") - current = _lookup(stack, segs[0]) + found, current = _lookup(stack, segs[0]) for seg in segs[1:]: - if current is None: - return None - current = _lookup([current], seg) - return current + if not found or current is None: + return False, None + found, current = _lookup([current], seg) + return found, current -def _lookup(stack: list[Any], name: str) -> Any: +def _lookup(stack: list[Any], name: str) -> tuple[bool, Any]: for ctx in reversed(stack): if isinstance(ctx, dict) and name in ctx: - return ctx[name] - return None + return True, ctx[name] + return False, None def _truthy(value: Any) -> bool: diff --git a/server/python/src/metaobjects/spec_metamodel/object.json b/server/python/src/metaobjects/spec_metamodel/object.json index ddf3c6eeec..ad288e6015 100644 --- a/server/python/src/metaobjects/spec_metamodel/object.json +++ b/server/python/src/metaobjects/spec_metamodel/object.json @@ -26,9 +26,6 @@ "children": [ { "type": "relationship", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "template", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } @@ -56,22 +53,6 @@ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] - }, - { - "type": "object", - "subType": "report", - "extendsBase": true, - "description": "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.", - "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", - "children": [ - { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, - { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, - { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, - { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } - ] } ] } diff --git a/server/python/src/metaobjects/spec_metamodel/origin.json b/server/python/src/metaobjects/spec_metamodel/origin.json index c4fde970f9..4d7e5aea16 100644 --- a/server/python/src/metaobjects/spec_metamodel/origin.json +++ b/server/python/src/metaobjects/spec_metamodel/origin.json @@ -28,7 +28,6 @@ { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -52,8 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." } ] } ] diff --git a/server/python/src/metaobjects/spec_metamodel/reporting.json b/server/python/src/metaobjects/spec_metamodel/reporting.json index adbe87f9ed..10a888b0c3 100644 --- a/server/python/src/metaobjects/spec_metamodel/reporting.json +++ b/server/python/src/metaobjects/spec_metamodel/reporting.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-reporting", "types": [ { "type": "dimension", "subType": "attribute", "description": "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.", @@ -46,6 +46,35 @@ "whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 1, "max": 1, "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } + ] }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "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.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, + { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, + { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, + { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + } + ], + "extends": [ + { "type": "object", "subType": "entity", "children": [ + { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null } + ] }, + { "type": "origin", "subType": "aggregate", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + ] }, + { "type": "origin", "subType": "first", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] } diff --git a/server/python/src/metaobjects/spec_metamodel/requirement.json b/server/python/src/metaobjects/spec_metamodel/requirement.json index f3017fd78d..a74ebd5758 100644 --- a/server/python/src/metaobjects/spec_metamodel/requirement.json +++ b/server/python/src/metaobjects/spec_metamodel/requirement.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-requirements", "types": [ { "type": "requirement", @@ -185,5 +185,10 @@ } ] } + ], + "extends": [ + { "type": "metadata", "subType": "root", "children": [ + { "type": "requirement", "subType": "*", "name": "*", "min": 0, "max": null } + ] } ] } diff --git a/server/python/tests/conformance/conformance-expected-failures.json b/server/python/tests/conformance/conformance-expected-failures.json index 2672849cec..656792b04b 100644 --- a/server/python/tests/conformance/conformance-expected-failures.json +++ b/server/python/tests/conformance/conformance-expected-failures.json @@ -2,16 +2,12 @@ "language": "python", "fixtures": [ "error-origin-function-free-sql", - "error-projection-grain-not-object-array", - "error-projection-union-shape", "projection-view-vocabulary-rc21" ], "_comment_fr024": "FR-024 Phase-E validation parity SHIPPED in this port. The full FR-024 loader contract now holds: object.projection registration + per-subtype projection child rules + dotted Entity.child extends-resolution (type-scoped, ERR_EXTENDS_TARGET_MISMATCH), AND the validation passes \u2014 identity names required + projection identity pass-through/key-correspondence (B3), value-purity + projection-licensing subtype rules (B4a), the entity-primary-source-readonly hard cutover (B4b), @via single-hop-unique inference + origin cardinality (B5), and extends/origin agreement + derived-field providability (B6). Every former FR-024 error fixture (error-identity-name-required, error-projection-identity-not-extended, error-identity-key-mismatch, error-projection-extends-entity, error-projection-source-writable, error-value-with-identity-secondary, error-value-with-source, error-origin-via-ambiguous, error-origin-passthrough-to-many, error-origin-aggregate-no-to-many, error-extends-origin-mismatch, error-derived-field-no-read-source, error-entity-primary-source-readonly) now emits its expected code with the byte-identical source envelope and is un-ledgered.", "notes": "The Python expected failures are the keys of \"reasons\" below. The AI LLM-call trace fixtures ai-trace-prompt-nested and ai-trace-sti load + canonical-serialize cleanly in the Python port (@responseRef registered on template.prompt, carved out of the cross-port registry manifest as ExclusionReason.TS_PILOT_VOCAB until the atomic all-ports flip; template.* admitted as an object.entity child).", "reasons": { "error-origin-function-free-sql": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", - "error-projection-grain-not-object-array": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", - "error-projection-union-shape": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", "projection-view-vocabulary-rc21": "Python accepts the view functions and the cast node (C2) but not yet the rest of what this fixture declares: a dotted path in an origin.computed @expr (customerId.zip), a scalar origin.aggregate read from a computed field, a path operand in an origin.first @filter, an origin.passthrough through a path, and a derived field on an entity that declares a read source; implementedIn: typescript, csharp" } } diff --git a/server/python/tests/conformance/conformance_adapter.py b/server/python/tests/conformance/conformance_adapter.py index 94a2bf0946..92c4438173 100644 --- a/server/python/tests/conformance/conformance_adapter.py +++ b/server/python/tests/conformance/conformance_adapter.py @@ -10,6 +10,8 @@ from metaobjects import LoadResult, MetaDataLoader from metaobjects.core_types import core_provider, core_providers from metaobjects.documentation import doc_provider +from metaobjects.meta.core.reporting.reporting_provider import reporting_provider +from metaobjects.meta.core.requirement.requirements_provider import requirements_provider from metaobjects.meta.core.rules.rules_provider import rules_provider from metaobjects.meta.persistence.db.db_provider import db_provider from metaobjects.meta.persistence.view_expressions.view_expressions_provider import ( @@ -137,6 +139,9 @@ def _noop_provider(provider_id: str, *deps: str) -> Provider: # vocabulary (origin.function, projection @union / @grain), each its own pack. rules_provider.id: rules_provider, # "metaobjects-rules" view_expressions_provider.id: view_expressions_provider, # "metaobjects-view-expressions" + # Reporting (dimension / measure / segment / object.report) and requirements. + reporting_provider.id: reporting_provider, # "metaobjects-reporting" + requirements_provider.id: requirements_provider, # "metaobjects-requirements" # Back-compat alias: pre-rename fixtures (and other ports' fixtures) still name the # provider "metaobjects-template"; map it to the renamed prompt provider — the same # alias the TS adapter keeps (adapter.ts: "metaobjects-template": promptProvider). diff --git a/server/python/tests/conformance/fixture_discovery.py b/server/python/tests/conformance/fixture_discovery.py index 87b97be08c..e866228f9b 100644 --- a/server/python/tests/conformance/fixture_discovery.py +++ b/server/python/tests/conformance/fixture_discovery.py @@ -24,9 +24,12 @@ "metaobjects-ui", # view.textarea @rows and the view.image attrs are cross-port vocabulary. "metaobjects-ui-web", - # The business-rules and view-expressions packs are in the default bundle. + # The business-rules, view-expressions, reporting and requirements packs are in the default bundle. "metaobjects-rules", "metaobjects-view-expressions", + # Reporting and requirements are their own packs, in the default bundle. + "metaobjects-reporting", + "metaobjects-requirements", ) diff --git a/server/python/tests/render/test_jinja_engine.py b/server/python/tests/render/test_jinja_engine.py index bfe146bac6..cb6cd68db5 100644 --- a/server/python/tests/render/test_jinja_engine.py +++ b/server/python/tests/render/test_jinja_engine.py @@ -191,8 +191,10 @@ def test_a_payload_with_no_fields_is_refused() -> None: _jinja("{{ x }}", 5) -def test_a_missing_key_renders_empty_at_any_depth() -> None: - assert _jinja("[{{ v.x.y }}]", {"v": {}}) == "[]" +def test_a_missing_key_raises_at_any_depth_and_a_null_renders_empty() -> None: + with pytest.raises(RenderError, match="ERR_VAR_NOT_ON_PAYLOAD"): + _jinja("[{{ v.x.y }}]", {"v": {}}) + assert _jinja("[{{ v }}]", {"v": None}) == "[]" def test_an_engine_failure_is_a_render_error() -> None: diff --git a/server/python/tests/render/test_render_conformance.py b/server/python/tests/render/test_render_conformance.py index cff8e0e567..26cb30c9e9 100644 --- a/server/python/tests/render/test_render_conformance.py +++ b/server/python/tests/render/test_render_conformance.py @@ -8,7 +8,9 @@ - ``template.mustache`` the template body - ``partials/.mustache`` optional partial bodies, referenced as ``{{> partials/}}`` -- ``expected.txt`` the expected rendered output (byte-identical compare) +- ``expected.txt`` the expected rendered output (byte-identical compare), or + ``expected-error.txt``: the render must fail, and its message must contain the + file's trimmed text The same (template + payload + partials + format) MUST yield byte-identical output in TS, C#, Java, and Python. 1:1 port of @@ -24,6 +26,7 @@ from metaobjects.render.renderer import ( InMemoryProvider, + RenderError, RenderRequest, render, ) @@ -57,16 +60,16 @@ def test_render_matches_expected(fixture_dir: Path) -> None: template_path = fixture_dir / "template.mustache" payload_path = fixture_dir / "payload.json" expected_path = fixture_dir / "expected.txt" + error_path = fixture_dir / "expected-error.txt" meta_path = fixture_dir / "meta.json" partials_dir = fixture_dir / "partials" assert template_path.is_file(), f"missing template: {template_path}" assert payload_path.is_file(), f"missing payload: {payload_path}" - assert expected_path.is_file(), f"missing expected: {expected_path}" + assert expected_path.is_file() or error_path.is_file(), f"missing expected: {expected_path}" template = template_path.read_text(encoding="utf-8") payload = json.loads(payload_path.read_text(encoding="utf-8")) - expected = expected_path.read_text(encoding="utf-8") meta: dict = {} if meta_path.is_file(): @@ -88,6 +91,13 @@ def test_render_matches_expected(fixture_dir: Path) -> None: format=format_, max_chars=max_chars, ) + if error_path.is_file(): + message = error_path.read_text(encoding="utf-8").strip() + with pytest.raises(RenderError) as err: + render(req) + assert message in str(err.value) + return + expected = expected_path.read_text(encoding="utf-8") actual = render(req) assert actual == expected, ( @@ -95,3 +105,12 @@ def test_render_matches_expected(fixture_dir: Path) -> None: f"--- expected ({len(expected)} chars) ---\n{expected!r}\n" f"--- actual ({len(actual)} chars) ---\n{actual!r}" ) + + +def test_a_missing_variable_raises_and_a_null_renders_empty() -> None: + provider = InMemoryProvider({}) + with pytest.raises(RenderError, match=r"ERR_VAR_NOT_ON_PAYLOAD \(nmae\)"): + render(RenderRequest(payload={"name": "Ada"}, provider=provider, template="Hi {{nmae}}!")) + with pytest.raises(RenderError, match=r"ERR_VAR_NOT_ON_PAYLOAD \(nmae\)"): + render(RenderRequest(payload={}, provider=provider, template="Hi {{{nmae}}}!")) + assert render(RenderRequest(payload={"n": None}, provider=provider, template="Hi {{n}}!{{#x}}y{{/x}}")) == "Hi !" diff --git a/server/python/tests/test_requirements_pack_left_out.py b/server/python/tests/test_requirements_pack_left_out.py new file mode 100644 index 0000000000..0199add35c --- /dev/null +++ b/server/python/tests/test_requirements_pack_left_out.py @@ -0,0 +1,65 @@ +"""The requirements vocabulary is its own pack (``metaobjects-requirements``), composed by +default. The verify gate's ledger reads requirement nodes the pack registered, so with the +pack left out of an embedder's providers the gate has nothing to read and reports nothing, +and a model that declares a requirement fails to load instead.""" +from __future__ import annotations + +import json + +from metaobjects import MetaDataLoader +from metaobjects.core_types import core_providers +from metaobjects.requirement_check import ( + check_requirements, + scan_requirements, + summarise_requirements, +) + +ORDER = { + "object.entity": { + "name": "Order", + "children": [ + {"source.rdb": {"@table": "orders"}}, + {"field.long": {"name": "id"}}, + {"identity.primary": {"name": "pk", "@fields": ["id"]}}, + ], + } +} +REQUIREMENT = { + "requirement.functional": { + "name": "PlaceOrder", + "@level": 4, + "@status": "live", + "@statement": "A customer places an order", + "@counterexample": "A customer cannot place an order", + "@implementedBy": ["app::Order"], + } +} + + +def _model(children: list[dict]) -> str: + return json.dumps({"metadata.root": {"package": "app", "children": children}}) + + +def _load(children: list[dict], *, pack: bool): + providers = [p for p in core_providers if pack or p.id != "metaobjects-requirements"] + return MetaDataLoader.from_string(_model(children), providers=providers, strict=True) + + +def test_a_model_with_no_requirements_loads_and_the_gate_reports_nothing() -> None: + result = _load([ORDER], pack=False) + assert [str(e) for e in result.errors] == [] + scan = scan_requirements(result.root) + assert check_requirements(result.root, scan) == [] + assert summarise_requirements(result.root, scan) is None + + +def test_a_model_that_declares_a_requirement_fails_to_load() -> None: + result = _load([ORDER, REQUIREMENT], pack=False) + assert [e.code.name for e in result.errors] == ["ERR_UNKNOWN_TYPE"] + + +def test_with_the_default_bundle_the_same_requirement_reaches_the_ledger() -> None: + result = _load([ORDER, REQUIREMENT], pack=True) + assert [str(e) for e in result.errors] == [] + summary = summarise_requirements(result.root, scan_requirements(result.root)) + assert summary is not None and summary.total == 1 diff --git a/server/rust/metaobjects/data/metamodel/object.json b/server/rust/metaobjects/data/metamodel/object.json index ddf3c6eeec..ad288e6015 100644 --- a/server/rust/metaobjects/data/metamodel/object.json +++ b/server/rust/metaobjects/data/metamodel/object.json @@ -26,9 +26,6 @@ "children": [ { "type": "relationship", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "template", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } @@ -56,22 +53,6 @@ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] - }, - { - "type": "object", - "subType": "report", - "extendsBase": true, - "description": "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.", - "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", - "children": [ - { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, - { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, - { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, - { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } - ] } ] } diff --git a/server/rust/metaobjects/data/metamodel/origin.json b/server/rust/metaobjects/data/metamodel/origin.json index c4fde970f9..4d7e5aea16 100644 --- a/server/rust/metaobjects/data/metamodel/origin.json +++ b/server/rust/metaobjects/data/metamodel/origin.json @@ -28,7 +28,6 @@ { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -52,8 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." } ] } ] diff --git a/server/rust/metaobjects/data/metamodel/reporting.json b/server/rust/metaobjects/data/metamodel/reporting.json index adbe87f9ed..10a888b0c3 100644 --- a/server/rust/metaobjects/data/metamodel/reporting.json +++ b/server/rust/metaobjects/data/metamodel/reporting.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-reporting", "types": [ { "type": "dimension", "subType": "attribute", "description": "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.", @@ -46,6 +46,35 @@ "whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 1, "max": 1, "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } + ] }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "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.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, + { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, + { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, + { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + } + ], + "extends": [ + { "type": "object", "subType": "entity", "children": [ + { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null } + ] }, + { "type": "origin", "subType": "aggregate", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + ] }, + { "type": "origin", "subType": "first", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] } diff --git a/server/rust/metaobjects/data/metamodel/requirement.json b/server/rust/metaobjects/data/metamodel/requirement.json index f3017fd78d..a74ebd5758 100644 --- a/server/rust/metaobjects/data/metamodel/requirement.json +++ b/server/rust/metaobjects/data/metamodel/requirement.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-requirements", "types": [ { "type": "requirement", @@ -185,5 +185,10 @@ } ] } + ], + "extends": [ + { "type": "metadata", "subType": "root", "children": [ + { "type": "requirement", "subType": "*", "name": "*", "min": 0, "max": null } + ] } ] } diff --git a/server/rust/metaobjects/src/providers.rs b/server/rust/metaobjects/src/providers.rs index 19e21d3f80..902802afee 100644 --- a/server/rust/metaobjects/src/providers.rs +++ b/server/rust/metaobjects/src/providers.rs @@ -24,6 +24,8 @@ use crate::registry::{ pub const CORE_TYPES_ID: &str = "metaobjects-core-types"; pub const DB_ID: &str = "metaobjects-db"; pub const DOCUMENTATION_ID: &str = "metaobjects-documentation"; +pub const REPORTING_ID: &str = "metaobjects-reporting"; +pub const REQUIREMENTS_ID: &str = "metaobjects-requirements"; pub const RULES_ID: &str = "metaobjects-rules"; pub const VIEW_EXPRESSIONS_ID: &str = "metaobjects-view-expressions"; pub const PROMPT_ID: &str = "metaobjects-prompt"; @@ -89,11 +91,11 @@ const CORE_FAMILIES: &[(&str, &str)] = &[ spec!("identity"), spec!("relationship"), spec!("index"), - spec!("requirement"), - spec!("reporting"), ]; const RULES_FAMILIES: &[(&str, &str)] = &[spec!("api"), spec!("transition")]; +const REPORTING_SPEC: (&str, &str) = spec!("reporting"); +const REQUIREMENT_SPEC: (&str, &str) = spec!("requirement"); const VIEW_EXPRESSIONS_SPEC: (&str, &str) = spec!("view-expressions"); const DB_SPEC: (&str, &str) = spec!("db"); const DOCUMENTATION_SPEC: (&str, &str) = spec!("documentation"); @@ -257,6 +259,8 @@ struct Definitions { core: Vec, rules: Vec, view_expressions: ProviderDefinition, + reporting: ProviderDefinition, + requirements: ProviderDefinition, db: ProviderDefinition, documentation: ProviderDefinition, prompt: ProviderDefinition, @@ -272,6 +276,8 @@ fn definitions() -> &'static Definitions { core: CORE_FAMILIES.iter().map(|f| p(*f)).collect(), rules: RULES_FAMILIES.iter().map(|f| p(*f)).collect(), view_expressions: p(VIEW_EXPRESSIONS_SPEC), + reporting: p(REPORTING_SPEC), + requirements: p(REQUIREMENT_SPEC), db: p(DB_SPEC), documentation: p(DOCUMENTATION_SPEC), prompt: p(PROMPT_SPEC), @@ -381,7 +387,10 @@ fn child_rule_id(rule: &ChildRule) -> String { /// Lower a definition's real types (not the universal `*.*` entry) to registry /// definitions, folding `.base` into subtypes that set `extendsBase`. -fn define_from_data(data: &ProviderDefinition) -> Result, MetaError> { +fn define_from_data( + data: &ProviderDefinition, + registry: Option<&TypeRegistry>, +) -> Result, MetaError> { let real: Vec<&TypeDef> = data.types.iter().filter(|t| !is_universal(t)).collect(); let mut lowered: Vec<(String, Vec, Vec)> = Vec::new(); for t in &real { @@ -404,18 +413,26 @@ fn define_from_data(data: &ProviderDefinition) -> Result, Me let mut child_rules = own_rules.clone(); if t.extends_base && t.sub_type != SUBTYPE_BASE { let base_key = format!("{}.{SUBTYPE_BASE}", t.type_name); - if let Some((_, base_attrs, base_rules)) = - lowered.iter().find(|(k, _, _)| *k == base_key) - { + // The base is this definition's own, else one another provider registered. + let registered = || { + let b = registry?.find(&t.type_name, SUBTYPE_BASE)?; + Some((b.attributes.clone(), b.child_rules.clone())) + }; + let base = lowered + .iter() + .find(|(k, _, _)| *k == base_key) + .map(|(_, a, r)| (a.clone(), r.clone())) + .or_else(registered); + if let Some((base_attrs, base_rules)) = base { let mut have: HashSet = attributes.iter().map(|a| a.name.clone()).collect(); - for a in base_attrs { + for a in &base_attrs { if have.insert(a.name.clone()) { attributes.push(a.clone()); } } let mut have_rule: HashSet = child_rules.iter().map(child_rule_id).collect(); - for r in base_rules { + for r in &base_rules { if have_rule.insert(child_rule_id(r)) { child_rules.push(r.clone()); } @@ -442,7 +459,7 @@ fn apply_definition( registry: &mut TypeRegistry, data: &ProviderDefinition, ) -> Result<(), MetaError> { - for def in define_from_data(data)? { + for def in define_from_data(data, Some(registry))? { registry.register(def)?; } if let Some(universal) = data.types.iter().find(|t| is_universal(t)) { @@ -494,13 +511,13 @@ 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"] + root.child_rules = ["object", "field", "validator", "template"] .iter() .map(|t| ChildRule::wildcard(t)) .collect(); registry.register(root)?; for family in &definitions().core { - for def in define_from_data(family)? { + for def in define_from_data(family, None)? { registry.register(def)?; } } @@ -553,6 +570,27 @@ pub fn rules_provider() -> Provider { ) } +/// The reporting pack (FR-044): `object.report`, dimension / measure / segment, and +/// `@segment` on `origin.aggregate` / `origin.first`. +pub fn reporting_provider() -> Provider { + Provider::new( + REPORTING_ID, + &[CORE_TYPES_ID], + "Reporting: object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.", + |r| apply_definition(r, &definitions().reporting), + ) +} + +/// The requirements pack: `requirement.functional` and `requirement.architectural`. +pub fn requirements_provider() -> Provider { + Provider::new( + REQUIREMENTS_ID, + &[CORE_TYPES_ID], + "Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by verify.", + |r| apply_definition(r, &definitions().requirements), + ) +} + /// View expressions: `origin.function` and the projection `@union`/`@grain` attrs. pub fn view_expressions_provider() -> Provider { Provider::new( @@ -619,6 +657,8 @@ pub fn core_providers() -> Vec { prompt_provider(), ui_provider(), ui_web_provider(), + reporting_provider(), + requirements_provider(), ] } diff --git a/server/rust/metaobjects/src/registry.rs b/server/rust/metaobjects/src/registry.rs index 351d7186ca..f90fd1e241 100644 --- a/server/rust/metaobjects/src/registry.rs +++ b/server/rust/metaobjects/src/registry.rs @@ -4,6 +4,8 @@ //! Behaviour follows the TypeScript reference (`registry.ts`), including the //! provider attribute-ownership rules of ADR-0062 and the sealing of ADR-0023. +use std::collections::HashSet; + use indexmap::IndexMap; use serde_json::Value; @@ -309,11 +311,36 @@ impl TypeRegistry { for attr in &def.attributes { Self::check_value_type(attr, &format!("TypeRegistry.register on \"{key}\""))?; } - for attr in &def.attributes { + // An attribute folded in unchanged from the registered `.base` (a pack's + // subtype with `extendsBase`, e.g. object.report) is the base owner's, not a new + // claim: it is not checked against the registering provider, and is stamped with + // the owner the base attribute already has. + let base_names: HashSet = if def.sub_type == SUBTYPE_BASE { + HashSet::new() + } else { + self.find(&def.type_name, SUBTYPE_BASE) + .map(|b| b.attributes.iter().map(|a| a.name.clone()).collect()) + .unwrap_or_default() + }; + for attr in def.attributes.iter().filter(|a| !base_names.contains(&a.name)) { self.check_attr_ownership(&def.type_name, &def.sub_type, &attr.name)?; } let (type_name, sub_type) = (def.type_name.clone(), def.sub_type.clone()); - let names: Vec = def.attributes.iter().map(|a| a.name.clone()).collect(); + let names: Vec = def + .attributes + .iter() + .filter(|a| !base_names.contains(&a.name)) + .map(|a| a.name.clone()) + .collect(); + let inherited: Vec<(String, String)> = def + .attributes + .iter() + .filter(|a| base_names.contains(&a.name)) + .filter_map(|a| { + self.attr_owner(&type_name, SUBTYPE_BASE, &a.name) + .map(|o| (a.name.clone(), o.to_string())) + }) + .collect(); self.defs.insert(key, def); self.sub_types .entry(type_name.clone()) @@ -322,6 +349,12 @@ impl TypeRegistry { for name in names { self.stamp_attr_owner(&type_name, &sub_type, &name); } + for (name, owner) in inherited { + self.attr_owners + .entry(format!("{type_name}.{sub_type}")) + .or_default() + .insert(name, owner); + } Ok(()) } diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index cbe72cdd23..4296e5891c 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -38,6 +38,9 @@ //! 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 +//! P3 ERR_TRANSITION_NAME_COLLISION two permission points ask the policy about one permission +//! name and at least one of the two names is derived; two +//! DECLARED @permission values may be equal (shared permission) //! 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 @@ -1098,6 +1101,87 @@ fn check_api_routes(tree: &Tree, ops: &[NodeId], sink: &mut Sink<'_>) { } } +/// The name a permission point asks the policy about: its `@permission`, else +/// `.` (the package prefix is dropped when there is none). `::` and `.` +/// both separate path segments, so they compare equal. Returns the name and whether it +/// is derived. +fn permission_name_of(tree: &Tree, node: NodeId, owner: NodeId, path: &str) -> (String, bool) { + let declared = match tree.attr(node, A_PERMISSION) { + Some(Value::String(s)) => Some(s.as_str()), + _ => None, + }; + let pkg = tree.effective_package(tree.top_level_of(owner)); + let name = match declared { + Some(d) => d.to_string(), + None if pkg.is_empty() => path.to_string(), + None => format!("{pkg}.{path}"), + }; + (name.replace(PACKAGE_SEP, "."), declared.is_none()) +} + +/// P3: two permission points, one name. Points are every non-public operation and every +/// transition of a live concrete entity. Compared case-sensitively (a grant key is +/// exact). Transitions are registered first, so the error lands on the operation when an +/// operation meets a transition. +fn check_permission_names(ctx: &Ctx<'_>, top_level: &[NodeId], sink: &mut Sink<'_>) { + let tree = ctx.tree; + let mut by_name: HashMap> = HashMap::new(); + let mut register = |node: NodeId, owner: NodeId, path: &str, sink: &mut Sink<'_>| { + if is_true(tree, node, A_PUBLIC) { + return; + } + let (name, derived) = permission_name_of(tree, node, owner, path); + let points = by_name.entry(name.clone()).or_default(); + let is_op = |n: NodeId| tree.node(n).type_name == T_OPERATION; + let clash = points.iter().find(|&&(q, q_derived)| { + q != node + && (derived || q_derived) + && !(is_op(node) && is_op(q) && same_operation(ctx, q, node)) + }); + if let Some(&(q, _)) = clash { + let (n, c) = (tree.node(node), tree.node(q)); + sink.add( + node, + ERR_TRANSITION_NAME_COLLISION, + format!( + "{}.{} \"{}\" asks the policy about the permission name \"{name}\", which {}.{} \"{}\" also asks about, and one of the two names is derived rather than declared; declare a distinct @permission on one, or rename it.", + n.type_name, + n.sub_type, + label(tree, node), + c.type_name, + c.sub_type, + label(tree, q) + ), + ); + } + points.push((node, derived)); + }; + for &entity in top_level { + if !is_entity(tree, entity) || tree.node(entity).is_abstract { + continue; + } + if !tree.children(entity).iter().any(|&c| tree.node(c).type_name == T_SOURCE) { + continue; + } + let ename = tree.node(entity).name.clone(); + for t in entity_transitions(tree, entity) { + let path = format!("{ename}.{}", tree.node(t).name); + register(t, entity, &path, sink); + } + } + for &api in top_level { + if tree.node(api).type_name != T_API { + continue; + } + for &op in tree.children(api).iter() { + if tree.node(op).type_name == T_OPERATION { + let path = tree.node(op).name.clone(); + register(op, api, &path, sink); + } + } + } +} + /// 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; @@ -1175,6 +1259,7 @@ pub fn validate_rules(ctx: &Ctx<'_>, f: &mut Findings) { } check_api_routes(tree, &ops, &mut sink); } + check_permission_names(ctx, top_level, &mut sink); f.errors.extend(sink.errors); } diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json index fff5764197..7a90da6993 100644 --- a/server/rust/metaobjects/tests/conformance-expected-failures.json +++ b/server/rust/metaobjects/tests/conformance-expected-failures.json @@ -1,6 +1,6 @@ { "language": "rust", "notes": "The Rust port passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", - "minPassing": 578, + "minPassing": 584, "fixtures": [] } diff --git a/server/rust/metaobjects/tests/metamodel_conformance.rs b/server/rust/metaobjects/tests/metamodel_conformance.rs index 8cd2a820e5..ade2ad5e48 100644 --- a/server/rust/metaobjects/tests/metamodel_conformance.rs +++ b/server/rust/metaobjects/tests/metamodel_conformance.rs @@ -35,6 +35,8 @@ const DEFAULT_PROVIDERS: &[&str] = &[ "metaobjects-prompt", "metaobjects-ui", "metaobjects-ui-web", + "metaobjects-reporting", + "metaobjects-requirements", ]; fn corpus() -> PathBuf { diff --git a/server/typescript/packages/cli/test/requirements-pack-left-out.test.ts b/server/typescript/packages/cli/test/requirements-pack-left-out.test.ts new file mode 100644 index 0000000000..59cd0c3ca7 --- /dev/null +++ b/server/typescript/packages/cli/test/requirements-pack-left-out.test.ts @@ -0,0 +1,67 @@ +// The requirements vocabulary is its own pack (`metaobjects-requirements`), composed by +// default. The verify gate's ledger reads requirement nodes the pack registered, so with +// the pack left out of an embedder's registry the gate has nothing to read and reports +// nothing, and a model that declares a requirement fails to load instead. +import { describe, test, expect } from "bun:test"; +import { + MetaDataLoader, + InMemoryStringSource, + composeRegistry, + coreProviders, + REQUIREMENTS_PROVIDER_ID, +} from "@metaobjectsdev/metadata"; +import { checkRequirements, scanRequirements, summariseRequirements } from "../src/lib/requirement-check.js"; + +const ORDER = { + "object.entity": { + name: "Order", + children: [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ], + }, +}; +const REQUIREMENT = { + "requirement.functional": { + name: "PlaceOrder", + "@level": 4, + "@status": "live", + "@statement": "A customer places an order", + "@counterexample": "A customer cannot place an order", + "@implementedBy": ["app::Order"], + }, +}; + +function model(children: unknown[]): string { + return JSON.stringify({ "metadata.root": { package: "app", children } }); +} + +const withoutPack = () => composeRegistry(coreProviders.filter((p) => p.id !== REQUIREMENTS_PROVIDER_ID)); + +describe("requirements pack left out", () => { + test("a model with no requirements loads and the gate reports nothing", async () => { + const result = await new MetaDataLoader({ registry: withoutPack(), strict: true }).load([ + new InMemoryStringSource(model([ORDER]), { format: "json" }), + ]); + expect(result.errors).toEqual([]); + const scan = scanRequirements(result.root); + expect(checkRequirements(result.root, scan)).toEqual([]); + expect(summariseRequirements(result.root, scan)).toBeUndefined(); + }); + + test("a model that declares a requirement fails to load with ERR_UNKNOWN_TYPE", async () => { + const result = await new MetaDataLoader({ registry: withoutPack(), strict: true }).load([ + new InMemoryStringSource(model([ORDER, REQUIREMENT]), { format: "json" }), + ]); + expect(result.errors.map((e) => (e as { code?: string }).code)).toEqual(["ERR_UNKNOWN_TYPE"]); + }); + + test("with the default bundle the same requirement reaches the ledger", async () => { + const result = await new MetaDataLoader({ registry: composeRegistry(coreProviders), strict: true }).load([ + new InMemoryStringSource(model([ORDER, REQUIREMENT]), { format: "json" }), + ]); + expect(result.errors).toEqual([]); + expect(summariseRequirements(result.root, scanRequirements(result.root))?.total).toBe(1); + }); +}); diff --git a/server/typescript/packages/conformance/src/fixture.ts b/server/typescript/packages/conformance/src/fixture.ts index c4cfe9a09e..8d3c088d23 100644 --- a/server/typescript/packages/conformance/src/fixture.ts +++ b/server/typescript/packages/conformance/src/fixture.ts @@ -58,10 +58,13 @@ const DEFAULT_PROVIDERS = [ "metaobjects-ui", // View.textarea @rows and the view.image attrs are cross-port vocabulary. "metaobjects-ui-web", - // The business-rules and view-expressions packs are in the default bundle, so a - // fixture with no providers.json still loads every existing model. + // The business-rules, view-expressions, reporting and requirements packs are in + // the default bundle, so a fixture with no providers.json still loads every + // existing model. "metaobjects-rules", "metaobjects-view-expressions", + "metaobjects-reporting", + "metaobjects-requirements", ]; export interface Fixture { diff --git a/server/typescript/packages/docs-site/src/load.ts b/server/typescript/packages/docs-site/src/load.ts index bc8cbe7592..0c1f7bb5b6 100644 --- a/server/typescript/packages/docs-site/src/load.ts +++ b/server/typescript/packages/docs-site/src/load.ts @@ -15,7 +15,7 @@ export interface LoadedModel { * Load N metadata source dirs into ONE root via a staging dir of symlinks. * * `extraProviders` are consumer-supplied metamodel providers, composed AFTER - * the default bundle (`coreProviders`: core-types, db, doc, prompt, ui, rules, view-expressions) — mirroring + * the default bundle (`coreProviders`: core-types, db, doc, prompt, ui, ui-web, rules, view-expressions, reporting, requirements) — mirroring * `loadMemory`'s `providers` option — so a site can document metadata that uses * custom field/view/object subtypes (e.g. a project's `metaobjects.config.ts` * `providers`). Defaults to none, so config-less callers are unchanged. diff --git a/server/typescript/packages/metadata/src/core-types.ts b/server/typescript/packages/metadata/src/core-types.ts index 8bbe85b26f..48b338d92b 100644 --- a/server/typescript/packages/metadata/src/core-types.ts +++ b/server/typescript/packages/metadata/src/core-types.ts @@ -8,6 +8,8 @@ import { uiProvider } from "./presentation/ui/ui-provider.js"; import { uiWebProvider } from "./presentation/ui-web/ui-web-provider.js"; import { rulesProvider } from "./core/rules/rules-provider.js"; import { viewExpressionsProvider } from "./persistence/view-expressions/view-expressions-provider.js"; +import { reportingProvider } from "./core/reporting/reporting-provider.js"; +import { requirementsProvider } from "./core/requirement/requirements-provider.js"; import { type DataType } from "./data-type.js"; import type { MetaData } from "./shared/meta-data.js"; import { MetaRoot } from "./shared/meta-root.js"; @@ -59,18 +61,6 @@ import { TEMPLATE_SUBTYPES } from "./template/template-constants.js"; 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 { 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"; -import { MetaMeasure } from "./core/reporting/meta-measure.js"; -import { MetaSegment } from "./core/reporting/meta-segment.js"; -import { REPORTING_DEFINITION } from "./core/reporting/reporting-definition.embedded.js"; -import { - DIMENSION_SUBTYPES, - MEASURE_SUBTYPES, - SEGMENT_SUBTYPES, -} from "./core/reporting/reporting-constants.js"; import { TYPE_METADATA, TYPE_OBJECT, @@ -85,10 +75,6 @@ import { TYPE_ORIGIN, TYPE_TEMPLATE, TYPE_INDEX, - TYPE_REQUIREMENT, - TYPE_DIMENSION, - TYPE_MEASURE, - TYPE_SEGMENT, SUBTYPE_ROOT, } from "./shared/base-types.js"; import { CHILD_RULE_WILDCARD } from "./shared/structural.js"; @@ -204,8 +190,8 @@ function registerCoreTypeDefs(registry: TypeRegistry): void { wildcard(TYPE_FIELD), wildcard(TYPE_VALIDATOR), wildcard(TYPE_TEMPLATE), - // Capability requirements are declared beside the entities they describe. - wildcard(TYPE_REQUIREMENT), + // `requirement` (the requirements pack) and `api` (the rules pack) are admitted + // by their packs' `extends`, so composing a pack out removes its child rule too. ], MetaRoot), ); @@ -509,52 +495,6 @@ function registerCoreTypeDefs(registry: TypeRegistry): void { registry.register(indexDef); } - // requirement — 2 subtypes. The axis is CHECK POLARITY, a genuine behaviour - // difference (ADR-0037 §2): `functional` is checked by EXISTENCE (nothing - // implements it -> fail), `architectural` by UNIVERSALITY (something violates - // it -> fail). Registered rather than hand-parsed because the capability - // ledger IS a metadata model: a closed status enum and a list of FQN - // references to model nodes are exactly `allowedValues` plus reference - // resolution, both of which this registry already owns (ruling amendment 3). - const REQUIREMENT_FACTORIES: FactoryMap = Object.fromEntries( - REQUIREMENT_SUBTYPES.map((subType) => [ - `${TYPE_REQUIREMENT}.${subType}`, - (typeId: TypeId, name: string) => new MetaRequirement(typeId, name), - ]), - ); - for (const reqDef of defineProviderFromData(REQUIREMENT_DEFINITION, REQUIREMENT_FACTORIES)) { - registry.register(reqDef); - } - - // FR-044 reporting vocabulary — dimension / measure / segment. Declared as - // children of `object.entity` (spec/metamodel/object.json), never root-level, so - // no root wildcard is added above. Three types in one provider file because they - // are one vocabulary: a report names dimensions and measures, and both may - // reference a segment. `measure.derived` is NOT registered (waits for FR-037 R5). - const REPORTING_FACTORIES: FactoryMap = { - ...Object.fromEntries( - DIMENSION_SUBTYPES.map((subType) => [ - `${TYPE_DIMENSION}.${subType}`, - (typeId: TypeId, name: string) => new MetaDimension(typeId, name), - ]), - ), - ...Object.fromEntries( - MEASURE_SUBTYPES.map((subType) => [ - `${TYPE_MEASURE}.${subType}`, - (typeId: TypeId, name: string) => new MetaMeasure(typeId, name), - ]), - ), - ...Object.fromEntries( - SEGMENT_SUBTYPES.map((subType) => [ - `${TYPE_SEGMENT}.${subType}`, - (typeId: TypeId, name: string) => new MetaSegment(typeId, name), - ]), - ), - }; - for (const reportingDef of defineProviderFromData(REPORTING_DEFINITION, REPORTING_FACTORIES)) { - registry.register(reportingDef); - } - // 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 @@ -567,13 +507,6 @@ function registerCoreTypeDefs(registry: TypeRegistry): void { ]; } } - // NOTE: @implementedBy is deliberately NOT declared as a loader `references` - // descriptor. That pass always ERRORS on an unresolved target, and a - // requirement with status `planned` names nodes that do not exist YET, so declaring - // nodes that are GONE — declaring it here would make the entries that carry - // the mechanism's only controlled evidence fail to load. The loader owns what - // is unconditional (the status enum, shape, levels); `meta verify` owns the - // status-conditional resolution, where the severity actually depends on data. const idRefDef = registry.find(TYPE_IDENTITY, IDENTITY_SUBTYPE_REFERENCE); if (idRefDef) { idRefDef.references = [ @@ -621,9 +554,11 @@ export const coreTypesProvider: MetaDataTypeProvider = { }, }; -/** The default provider bundle — core metamodel types plus the five concern +/** The default provider bundle — core metamodel types, the five concern * providers (DB-domain attrs, documentation common-attrs, prompt/AI, the - * UI/query-surface markers, and the TS-web presentation view attrs). + * UI/query-surface markers, and the TS-web presentation view attrs), and the four + * vocabulary packs (business rules, view expressions, reporting, requirements), each + * of which an embedder may leave out. * FR-033 S1-field-A re-homed the field's filter/sort/teaching/extract/storage * attrs out of core into db/ui/prompt; the composed set is unchanged. uiWebProvider * is TS-only (the non-TS ports mirror its spec file but never apply it — see @@ -638,6 +573,8 @@ export const coreProviders: readonly MetaDataTypeProvider[] = [ uiWebProvider, rulesProvider, viewExpressionsProvider, + reportingProvider, + requirementsProvider, ]; /** diff --git a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts index 3bbec9aedc..7ab0a148b2 100644 --- a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts @@ -103,27 +103,6 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "min": 0, "max": null }, - { - "type": "dimension", - "subType": "*", - "name": "*", - "min": 0, - "max": null - }, - { - "type": "measure", - "subType": "*", - "name": "*", - "min": 0, - "max": null - }, - { - "type": "segment", - "subType": "*", - "name": "*", - "min": 0, - "max": null - }, { "type": "attr", "subType": "string", @@ -192,73 +171,6 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] - }, - { - "type": "object", - "subType": "report", - "extendsBase": true, - "description": "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.", - "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", - "children": [ - { - "type": "attr", - "subType": "string", - "name": "from", - "min": 1, - "max": 1, - "description": "The object.entity whose rows the report aggregates." - }, - { - "type": "attr", - "subType": "string", - "name": "dimensions", - "isArray": true, - "min": 0, - "max": 1, - "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." - }, - { - "type": "attr", - "subType": "string", - "name": "measures", - "isArray": true, - "min": 1, - "max": 1, - "description": "Measure names of @from." - }, - { - "type": "attr", - "subType": "string", - "name": "segment", - "min": 0, - "max": 1, - "description": "Optional segment of @from scoping the rows." - }, - { - "type": "attr", - "subType": "filter", - "name": "filter", - "min": 0, - "max": 1, - "description": "Optional row scope over @from's fields; may use relative-date values." - }, - { - "type": "attr", - "subType": "string", - "name": "spine", - "min": 0, - "max": 1, - "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." - }, - { - "type": "attr", - "subType": "string", - "name": "collectionName", - "min": 0, - "max": 1, - "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." - } - ] } ] }; diff --git a/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts b/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts index 354707a4fe..077a87326d 100644 --- a/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts @@ -7,7 +7,7 @@ import type { ProviderDefinition } from "../../provider-data.js"; export const REPORTING_DEFINITION: ProviderDefinition = { - "provider": "metaobjects-core-types", + "provider": "metaobjects-reporting", "types": [ { "type": "dimension", @@ -203,6 +203,130 @@ export const REPORTING_DEFINITION: ProviderDefinition = { "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } ] + }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "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.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "from", + "min": 1, + "max": 1, + "description": "The object.entity whose rows the report aggregates." + }, + { + "type": "attr", + "subType": "string", + "name": "dimensions", + "isArray": true, + "min": 0, + "max": 1, + "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." + }, + { + "type": "attr", + "subType": "string", + "name": "measures", + "isArray": true, + "min": 1, + "max": 1, + "description": "Measure names of @from." + }, + { + "type": "attr", + "subType": "string", + "name": "segment", + "min": 0, + "max": 1, + "description": "Optional segment of @from scoping the rows." + }, + { + "type": "attr", + "subType": "filter", + "name": "filter", + "min": 0, + "max": 1, + "description": "Optional row scope over @from's fields; may use relative-date values." + }, + { + "type": "attr", + "subType": "string", + "name": "spine", + "min": 0, + "max": 1, + "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." + }, + { + "type": "attr", + "subType": "string", + "name": "collectionName", + "min": 0, + "max": 1, + "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." + } + ] + } + ], + "extends": [ + { + "type": "object", + "subType": "entity", + "children": [ + { + "type": "dimension", + "subType": "*", + "name": "*", + "min": 0, + "max": null + }, + { + "type": "measure", + "subType": "*", + "name": "*", + "min": 0, + "max": null + }, + { + "type": "segment", + "subType": "*", + "name": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "origin", + "subType": "aggregate", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "segment", + "min": 0, + "max": 1, + "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." + } + ] + }, + { + "type": "origin", + "subType": "first", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "segment", + "min": 0, + "max": 1, + "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." + } + ] } ] }; diff --git a/server/typescript/packages/metadata/src/core/reporting/reporting-provider.ts b/server/typescript/packages/metadata/src/core/reporting/reporting-provider.ts new file mode 100644 index 0000000000..7bb7eac58e --- /dev/null +++ b/server/typescript/packages/metadata/src/core/reporting/reporting-provider.ts @@ -0,0 +1,47 @@ +// reportingProvider — the reporting pack (FR-044): `object.report` and the +// dimension / measure / segment vocabulary a report is built from, plus the `@segment` +// attribute that lets an `origin.aggregate` or `origin.first` reuse a segment. +// +// It is its OWN provider rather than part of metaobjects-core-types so a project can +// leave it out and the vocabulary can move or be versioned on its own. It is in the +// default bundle (`coreProviders`), so every existing model loads unchanged. +// GOVERNANCE.md ("Extension packs and the core metamodel"): vocabulary lives in a +// pack until a second consumer needs it in core. +// +// The pack owns its types (reporting.json) AND the rules that admit them on types +// core owns: `object.entity` holds dimensions, measures and segments, and +// `origin.aggregate` / `origin.first` carry `@segment` — all in the file's `extends`. +// `object.report` folds in the `object.base` core registered (`extendsBase`). Compose +// the pack out and `object.report`, `dimension.*`, `measure.*` and `segment.*` are +// unknown (ERR_UNKNOWN_SUBTYPE / ERR_UNKNOWN_TYPE) and `@segment` is ERR_UNKNOWN_ATTR. + +import type { MetaDataTypeProvider } from "../../provider.js"; +import type { TypeRegistry, TypeId } from "../../registry.js"; +import { applyProviderDefinition, type FactoryMap } from "../../provider-data.js"; +import { TYPE_OBJECT, TYPE_DIMENSION, TYPE_MEASURE } from "../../shared/base-types.js"; +import { MetaObject } from "../object/meta-object.js"; +import { MetaDimension } from "./meta-dimension.js"; +import { MetaMeasure } from "./meta-measure.js"; +import { MetaSegment } from "./meta-segment.js"; +import { REPORTING_DEFINITION } from "./reporting-definition.embedded.js"; + +/** The reporting pack's provider id (a logical id, shared by every port). */ +export const REPORTING_PROVIDER_ID = "metaobjects-reporting"; + +export const reportingProvider: MetaDataTypeProvider = { + id: REPORTING_PROVIDER_ID, + dependencies: ["metaobjects-core-types"], + description: + "Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.", + registerTypes(registry: TypeRegistry): void { + const factories: FactoryMap = {}; + for (const def of REPORTING_DEFINITION.types ?? []) { + const key = `${def.type}.${def.subType}`; + if (def.type === TYPE_OBJECT) factories[key] = (typeId: TypeId, name: string) => new MetaObject(typeId, name); + else if (def.type === TYPE_DIMENSION) factories[key] = (typeId: TypeId, name: string) => new MetaDimension(typeId, name); + else if (def.type === TYPE_MEASURE) factories[key] = (typeId: TypeId, name: string) => new MetaMeasure(typeId, name); + else factories[key] = (typeId: TypeId, name: string) => new MetaSegment(typeId, name); + } + applyProviderDefinition(registry, REPORTING_DEFINITION, factories); + }, +}; diff --git a/server/typescript/packages/metadata/src/core/requirement/requirement-definition.embedded.ts b/server/typescript/packages/metadata/src/core/requirement/requirement-definition.embedded.ts index 5242c1e529..9e4e220d67 100644 --- a/server/typescript/packages/metadata/src/core/requirement/requirement-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/requirement/requirement-definition.embedded.ts @@ -7,7 +7,7 @@ import type { ProviderDefinition } from "../../provider-data.js"; export const REQUIREMENT_DEFINITION: ProviderDefinition = { - "provider": "metaobjects-core-types", + "provider": "metaobjects-requirements", "types": [ { "type": "requirement", @@ -193,5 +193,20 @@ export const REQUIREMENT_DEFINITION: ProviderDefinition = { } ] } + ], + "extends": [ + { + "type": "metadata", + "subType": "root", + "children": [ + { + "type": "requirement", + "subType": "*", + "name": "*", + "min": 0, + "max": null + } + ] + } ] }; diff --git a/server/typescript/packages/metadata/src/core/requirement/requirements-provider.ts b/server/typescript/packages/metadata/src/core/requirement/requirements-provider.ts new file mode 100644 index 0000000000..628f5e672d --- /dev/null +++ b/server/typescript/packages/metadata/src/core/requirement/requirements-provider.ts @@ -0,0 +1,44 @@ +// requirementsProvider — the requirements pack: `requirement.functional` and +// `requirement.architectural`, declared beside the entities they describe. +// +// It is its OWN provider rather than part of metaobjects-core-types so a project can +// leave it out and the vocabulary can move or be versioned on its own. It is in the +// default bundle (`coreProviders`), so every existing model loads unchanged. +// GOVERNANCE.md ("Extension packs and the core metamodel"): vocabulary lives in a +// pack until a second consumer needs it in core. +// +// The pack owns its types (requirement.json) AND the child rule that admits them on +// `metadata.root` (the file's `extends`). Compose the pack out and a `requirement.*` +// node is ERR_UNKNOWN_TYPE; `meta verify`'s requirement gate then has no ledger to +// read and reports nothing. +// +// @implementedBy is deliberately NOT declared as a loader `references` descriptor. That +// pass always ERRORS on an unresolved target, and a requirement with status `planned` +// names nodes that do not exist YET (and a `retired` one names nodes that are GONE), so +// declaring it would make the entries that carry the mechanism's only controlled evidence +// fail to load. The loader owns what is unconditional (the status enum, shape, levels); +// `meta verify` owns the status-conditional resolution, where the severity depends on data. + +import type { MetaDataTypeProvider } from "../../provider.js"; +import type { TypeRegistry, TypeId } from "../../registry.js"; +import { applyProviderDefinition, type FactoryMap } from "../../provider-data.js"; +import { MetaRequirement } from "./meta-requirement.js"; +import { REQUIREMENT_DEFINITION } from "./requirement-definition.embedded.js"; + +/** The requirements pack's provider id (a logical id, shared by every port). */ +export const REQUIREMENTS_PROVIDER_ID = "metaobjects-requirements"; + +export const requirementsProvider: MetaDataTypeProvider = { + id: REQUIREMENTS_PROVIDER_ID, + dependencies: ["metaobjects-core-types"], + description: + "Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify.", + registerTypes(registry: TypeRegistry): void { + const factories: FactoryMap = {}; + for (const def of REQUIREMENT_DEFINITION.types ?? []) { + factories[`${def.type}.${def.subType}`] = (typeId: TypeId, name: string) => + new MetaRequirement(typeId, name); + } + applyProviderDefinition(registry, REQUIREMENT_DEFINITION, factories); + }, +}; diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 9df5535b5f..c372cd8245 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -262,6 +262,15 @@ export type AnyMeta = export { TypeId, TypeRegistry, childRuleMatches } from "./registry.js"; export type { AttrSchema, ChildRule, TypeDefinition } from "./registry.js"; export { registerCoreTypes, coreTypesProvider, coreProviders } from "./core-types.js"; +// The vocabulary packs in the default bundle, by id, so an embedder can leave one out: +// `composeRegistry(coreProviders.filter((p) => p.id !== REPORTING_PROVIDER_ID))`. +export { rulesProvider, RULES_PROVIDER_ID } from "./core/rules/rules-provider.js"; +export { + viewExpressionsProvider, + VIEW_EXPRESSIONS_PROVIDER_ID, +} from "./persistence/view-expressions/view-expressions-provider.js"; +export { reportingProvider, REPORTING_PROVIDER_ID } from "./core/reporting/reporting-provider.js"; +export { requirementsProvider, REQUIREMENTS_PROVIDER_ID } from "./core/requirement/requirements-provider.js"; // FR-033 — the constraint engine: additive merge + the contradiction validator. export { mergeConstraints } from "./constraint-merge.js"; diff --git a/server/typescript/packages/metadata/src/loader/rules-validation.ts b/server/typescript/packages/metadata/src/loader/rules-validation.ts index e238446ebe..ebd8494cf2 100644 --- a/server/typescript/packages/metadata/src/loader/rules-validation.ts +++ b/server/typescript/packages/metadata/src/loader/rules-validation.ts @@ -42,6 +42,11 @@ // 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) +// P3 ERR_TRANSITION_NAME_COLLISION two permission points ask the policy about one permission name, and at +// least one of the two names is derived (ADR-0066 §1): an operation +// named "Order.open", one declaring @permission "p.Order.open", or one +// in package "p::Order", beside the "open" transition of Order in "p". +// Two DECLARED @permission values may be equal: that sharing is the point. // 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 @@ -94,7 +99,7 @@ import { transitionTo, } from "../core/transition/lifecycle.js"; import { isWritableSource } from "../shared/node-guards.js"; -import { effectivePackageOf } from "../naming-refs.js"; +import { effectivePackageOf, topLevelNodeOf } from "../naming-refs.js"; import { conditionMessage } from "./validation-passes.js"; const RESERVED = new Set(RESERVED_OPERATION_NAMES); @@ -375,9 +380,58 @@ export function validateRules(root: MetaData): ParseError[] { } checkApiRoutes(ops, sink); } + checkPermissionNames(root, sink); return sink.errors; } +interface PermissionPoint { + node: MetaData; + /** True when the name is derived (no @permission), false when declared. */ + derived: boolean; +} + +/** The name a permission point asks the policy about: its @permission, else `.` + * (the path is ``, or `.` for a transition's command). The package + * prefix is dropped when there is none. `::` and `.` both separate path segments, so they compare + * equal: `p::Order` + `open` and `p` + `Order.open` are one name. */ +function permissionNameOf(node: MetaData, owner: MetaData, path: string): { name: string; derived: boolean } { + const declared = node.attr(OPERATION_ATTR_PERMISSION); + const pkg = effectivePackageOf(topLevelNodeOf(owner)); + const name = typeof declared === "string" ? declared : pkg === "" ? path : `${pkg}.${path}`; + return { name: name.replaceAll("::", "."), derived: typeof declared !== "string" }; +} + +/** P3: two permission points, one name. Points are every non-public operation and every transition + * of a live concrete entity (the transitions derive a command each). Compared case-sensitively + * (a grant key is exact). Transitions are registered first, so the error lands on the operation + * when an operation meets a transition. */ +function checkPermissionNames(root: MetaData, sink: Sink): void { + const byName = new Map(); + const register = (node: MetaData, owner: MetaData, path: string): void => { + if (node.attr(OPERATION_ATTR_PUBLIC) === true) return; + const { name, derived } = permissionNameOf(node, owner, path); + const points = byName.get(name) ?? []; + byName.set(name, points); + const clash = points.find((q) => + q.node !== node && (derived || q.derived) && + !(node.type === TYPE_OPERATION && q.node.type === TYPE_OPERATION && sameOperation(q.node, node))); + if (clash !== undefined) { + sink.add(node, "ERR_TRANSITION_NAME_COLLISION", + `${node.type}.${node.subType} "${label(node)}" asks the policy about the permission name "${name}", which ${clash.node.type}.${clash.node.subType} "${label(clash.node)}" also asks about, and one of the two names is derived rather than declared; declare a distinct @permission on one, or rename it.`); + } + points.push({ node, derived }); + }; + for (const entity of root.children()) { + if (entity.type !== TYPE_OBJECT || entity.subType !== OBJECT_SUBTYPE_ENTITY) continue; + if (entity.isAbstract || !lifecycleIsLive(entity)) continue; + for (const t of entityTransitions(entity)) register(t, entity, `${entity.name}.${t.name}`); + } + for (const api of root.children()) { + if (api.type !== TYPE_API) continue; + for (const op of api.children()) if (op.type === TYPE_OPERATION) register(op, api, op.name); + } +} + /** 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); diff --git a/server/typescript/packages/metadata/src/metamodel-docs/provider-definitions.ts b/server/typescript/packages/metadata/src/metamodel-docs/provider-definitions.ts index 318fe0867a..cc56bf2abe 100644 --- a/server/typescript/packages/metadata/src/metamodel-docs/provider-definitions.ts +++ b/server/typescript/packages/metadata/src/metamodel-docs/provider-definitions.ts @@ -29,6 +29,8 @@ import { PROMPT_DEFINITION } from "../template/prompt-definition.embedded.js"; import { API_DEFINITION } from "../core/api/api-definition.embedded.js"; import { TRANSITION_DEFINITION } from "../core/transition/transition-definition.embedded.js"; import { VIEW_EXPRESSIONS_DEFINITION } from "../persistence/view-expressions/view-expressions-definition.embedded.js"; +import { REPORTING_DEFINITION } from "../core/reporting/reporting-definition.embedded.js"; +import { REQUIREMENT_DEFINITION } from "../core/requirement/requirement-definition.embedded.js"; /** * Every embedded provider definition the core metamodel composes from. The @@ -52,8 +54,11 @@ export const ALL_PROVIDER_DEFINITIONS: readonly ProviderDefinition[] = [ UI_WEB_DEFINITION, TEMPLATE_DEFINITION, PROMPT_DEFINITION, - // The business-rules pack (metaobjects-rules) and the view-expressions pack. + // The business-rules pack (metaobjects-rules), the view-expressions pack, the + // reporting pack and the requirements pack. API_DEFINITION, TRANSITION_DEFINITION, VIEW_EXPRESSIONS_DEFINITION, + REPORTING_DEFINITION, + REQUIREMENT_DEFINITION, ]; diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts index 4b0e3618a2..5bb6b2222a 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts @@ -95,14 +95,6 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { - "type": "attr", - "subType": "string", - "name": "segment", - "min": 0, - "max": 1, - "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." - }, { "type": "attr", "subType": "boolean", @@ -177,14 +169,6 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." - }, - { - "type": "attr", - "subType": "string", - "name": "segment", - "min": 0, - "max": 1, - "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } diff --git a/server/typescript/packages/metadata/src/provider-data.ts b/server/typescript/packages/metadata/src/provider-data.ts index 7b8718435d..f94a73b78f 100644 --- a/server/typescript/packages/metadata/src/provider-data.ts +++ b/server/typescript/packages/metadata/src/provider-data.ts @@ -192,6 +192,15 @@ function isUniversalEntry(t: TypeDef): boolean { return t.type === CHILD_RULE_WILDCARD && t.subType === CHILD_RULE_WILDCARD; } +/** + * Resolves a type's `base` when it is not in the definition being lowered: a pack + * that adds a subtype to a type another provider owns (`object.report` in the + * reporting pack) inherits the base that provider registered. + */ +export type ExternalBaseLookup = ( + type: string, +) => { attributes: AttrSchema[]; childRules: ChildRule[] } | undefined; + /** * Turn a declarative `ProviderDefinition` + a code-supplied factory map into the * `TypeDefinition`s a provider passes to `registry.register()`. @@ -219,6 +228,7 @@ function isUniversalEntry(t: TypeDef): boolean { export function defineProviderFromData( data: ProviderDefinition, factories: FactoryMap, + externalBase?: ExternalBaseLookup, ): TypeDefinition[] { // Pre-compute each type's OWN lowered attrs + childRules, keyed by "type.subType", // so base-composition can fold a base's contributions into its subtypes. A @@ -252,7 +262,7 @@ export function defineProviderFromData( } const self = lowered.get(key)!; - const { attributes, childRules } = composeWithBase(t, self, lowered); + const { attributes, childRules } = composeWithBase(t, self, lowered, externalBase); return { typeId: new TypeId(t.type, t.subType), @@ -284,7 +294,16 @@ export function applyProviderDefinition( data: ProviderDefinition, factories: FactoryMap, ): void { - for (const def of defineProviderFromData(data, factories)) { + // A pack may add a subtype to a type another provider owns (the reporting pack's + // object.report): its `extendsBase` folds in that type's `base` as already + // registered, since the base is not in the pack's own definition. + const externalBase: ExternalBaseLookup = (type) => { + const base = registry.find(type, SUBTYPE_BASE); + return base === undefined + ? undefined + : { attributes: [...base.attributes], childRules: [...base.childRules] }; + }; + for (const def of defineProviderFromData(data, factories, externalBase)) { registry.register(def); } const commonAttrs = universalCommonAttrs(data); @@ -361,7 +380,8 @@ export function universalCommonAttrs(data: ProviderDefinition): AttrSchema[] { /** * Fold a real `TypeDef`'s OWN lowered attrs/childRules with its `.base`'s - * (when the definition declares one and this subtype is not itself `base`). + * (when the definition declares one, else the already-registered base `externalBase` + * returns, and this subtype is not itself `base`). * Additive: own entries win on a name (attr) / structural-shape (rule) collision; * base entries the subtype lacks are appended. A NO-OP when there is no base in * THIS definition, or when the subtype already declares the full base set. @@ -370,13 +390,14 @@ function composeWithBase( t: TypeDef, self: { attributes: AttrSchema[]; childRules: ChildRule[] }, lowered: Map, + externalBase?: ExternalBaseLookup, ): { attributes: AttrSchema[]; childRules: ChildRule[] } { // OFF by default (S0): a subtype inherits its base only when it opts in via // `extendsBase: true`. Keeps the current canonical byte-identical — no provider // sets it yet — while the rail is in place for S1. if (t.extendsBase !== true) return self; if (t.subType === SUBTYPE_BASE) return self; - const base = lowered.get(`${t.type}.${SUBTYPE_BASE}`); + const base = lowered.get(`${t.type}.${SUBTYPE_BASE}`) ?? externalBase?.(t.type); if (base === undefined) return self; const attributes = [...self.attributes]; diff --git a/server/typescript/packages/metadata/src/registry.ts b/server/typescript/packages/metadata/src/registry.ts index 1ef3500108..92e815c974 100644 --- a/server/typescript/packages/metadata/src/registry.ts +++ b/server/typescript/packages/metadata/src/registry.ts @@ -217,13 +217,17 @@ export class TypeRegistry { private stampAttrOwner(type: string, subType: string, name: string): void { if (this._currentProviderId === undefined) return; + this.setAttrOwner(type, subType, name, this._currentProviderId); + } + + private setAttrOwner(type: string, subType: string, name: string, owner: string): void { const key = `${type}.${subType}`; let owners = this._attrOwners.get(key); if (owners === undefined) { owners = new Map(); this._attrOwners.set(key, owners); } - owners.set(name, this._currentProviderId); + owners.set(name, owner); } /** @@ -316,7 +320,15 @@ export class TypeRegistry { // ADR-0062: refuse a name another provider already put on a related slot, BEFORE // the definition becomes visible, so a refused registration leaves no trace. const list = this._subTypes.get(def.typeId.type); - for (const attr of def.attributes) { + // An attribute folded in unchanged from the registered `.base` (a pack's + // subtype with `extendsBase`, e.g. object.report) is the base owner's, not a new + // claim: it is not checked against the registering provider, and is stamped with + // the owner the base attribute already has. + const baseAttrs = new Set( + def.typeId.subType === SUBTYPE_BASE ? [] : (this.find(def.typeId.type, SUBTYPE_BASE)?.attributes ?? []), + ); + const claimed = def.attributes.filter((attr) => !baseAttrs.has(attr)); + for (const attr of claimed) { this.checkAttrOwnership(def.typeId.type, def.typeId.subType, attr.name); } this._defs.set(key, def); @@ -325,9 +337,14 @@ export class TypeRegistry { } else { this._subTypes.set(def.typeId.type, [def.typeId.subType]); } - for (const attr of def.attributes) { + for (const attr of claimed) { this.stampAttrOwner(def.typeId.type, def.typeId.subType, attr.name); } + for (const attr of def.attributes) { + if (!baseAttrs.has(attr)) continue; + const baseOwner = this.attrOwner(def.typeId.type, SUBTYPE_BASE, attr.name); + if (baseOwner !== undefined) this.setAttrOwner(def.typeId.type, def.typeId.subType, attr.name, baseOwner); + } } find(type: string, subType: string): TypeDefinition | undefined { diff --git a/server/typescript/packages/metadata/test/conformance/adapter.ts b/server/typescript/packages/metadata/test/conformance/adapter.ts index ab88935953..97bfd692b3 100644 --- a/server/typescript/packages/metadata/test/conformance/adapter.ts +++ b/server/typescript/packages/metadata/test/conformance/adapter.ts @@ -23,6 +23,8 @@ import { uiProvider } from "../../src/presentation/ui/ui-provider.js"; import { uiWebProvider } from "../../src/presentation/ui-web/ui-web-provider.js"; import { rulesProvider } from "../../src/core/rules/rules-provider.js"; import { viewExpressionsProvider } from "../../src/persistence/view-expressions/view-expressions-provider.js"; +import { reportingProvider } from "../../src/core/reporting/reporting-provider.js"; +import { requirementsProvider } from "../../src/core/requirement/requirements-provider.js"; import { MetaDataLoader } from "../../src/loader/meta-data-loader.js"; import type { MetaData } from "../../src/shared/meta-data.js"; import { canonicalSerialize, canonicalSerializeEffective } from "../../src/serializer-json.js"; @@ -163,6 +165,8 @@ export const PROVIDERS: Readonly> = { [uiWebProvider.id]: uiWebProvider, // "metaobjects-ui-web" (view control attrs) [rulesProvider.id]: rulesProvider, // "metaobjects-rules" (api/operation/binding/transition) [viewExpressionsProvider.id]: viewExpressionsProvider, // "metaobjects-view-expressions" (origin.function, @union/@grain) + [reportingProvider.id]: reportingProvider, // "metaobjects-reporting" (object.report, dimension/measure/segment) + [requirementsProvider.id]: requirementsProvider, // "metaobjects-requirements" (requirement.*) // Test-only — provider-extension-* fixtures. "example-template-briefing": exampleTemplateBriefingProvider, "example-custom-vocabulary": exampleCustomVocabularyProvider, diff --git a/server/typescript/packages/metadata/test/index.test.ts b/server/typescript/packages/metadata/test/index.test.ts index 3f0ca21a8a..abfd54a117 100644 --- a/server/typescript/packages/metadata/test/index.test.ts +++ b/server/typescript/packages/metadata/test/index.test.ts @@ -141,6 +141,8 @@ describe("Public API surface — @metaobjectsdev/metadata index", () => { if (t === "origin") continue; // The business-rules pack (metaobjects-rules) owns these; core alone has none. if (t === "api" || t === "operation" || t === "binding" || t === "transition") continue; + // The reporting and requirements packs own these; core alone has none. + if (t === "dimension" || t === "measure" || t === "segment" || t === "requirement") continue; const subs = registry.allSubTypesOf(t); expect(subs.length).toBeGreaterThan(0); } diff --git a/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts b/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts index 3a567083a5..44770973d9 100644 --- a/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts @@ -16,15 +16,17 @@ import { describe, test, expect } from "bun:test"; import { composeRegistry } from "../src/provider.js"; import { coreTypesProvider } from "../src/core-types.js"; import { viewExpressionsProvider } from "../src/persistence/view-expressions/view-expressions-provider.js"; +import { reportingProvider } from "../src/core/reporting/reporting-provider.js"; import { TYPE_ORIGIN } from "../src/shared/base-types.js"; import { ORIGIN_SUBTYPES } from "../src/persistence/origin/origin-constants.js"; -// Compose with ONLY the core-types provider and the view-expressions pack (which -// owns origin.function) — so `def.attributes` reflects +// Compose with ONLY the core-types provider, the view-expressions pack (which +// owns origin.function) and the reporting pack (which adds @segment to +// origin.aggregate and origin.first) — so `def.attributes` reflects // exactly what the ORIGIN provider registered, not the doc-domain attrs that // other providers add via registry.extend(). This isolates the externalization // gate. -const registry = composeRegistry([coreTypesProvider, viewExpressionsProvider]); +const registry = composeRegistry([coreTypesProvider, viewExpressionsProvider, reportingProvider]); type ExpectedAttr = { valueType: string; diff --git a/server/typescript/packages/metadata/test/provider-vocabulary.test.ts b/server/typescript/packages/metadata/test/provider-vocabulary.test.ts index 18e77e9051..24b785bfb6 100644 --- a/server/typescript/packages/metadata/test/provider-vocabulary.test.ts +++ b/server/typescript/packages/metadata/test/provider-vocabulary.test.ts @@ -74,15 +74,18 @@ describe("logical provider vocabulary", () => { for (const p of coreProviders) expect(Object.keys(canonical.providers)).toContain(p.id); }); - test("only core and the two named packs declare types; the rest are pure projections", () => { + test("only core and the four named packs declare types; the rest are pure projections", () => { // The shape ADR-0050 describes, asserted rather than assumed. A type-declaring - // provider beyond these three appearing fails this loudly, which is the moment to + // provider beyond these five appearing fails this loudly, which is the moment to // decide whether the OWN/PROJECTED split still holds. The packs - // (metaobjects-rules, metaobjects-view-expressions) own their types and project - // onto core's; see GOVERNANCE.md, "Extension packs and the core metamodel". + // (metaobjects-reporting, metaobjects-requirements, metaobjects-rules, + // metaobjects-view-expressions) own their types and project onto core's; see + // GOVERNANCE.md, "Extension packs and the core metamodel". const declaring = Object.entries(canonical.providers).filter(([, v]) => v.declaresTypes); expect(declaring.map(([k]) => k)).toEqual([ "metaobjects-core-types", + "metaobjects-reporting", + "metaobjects-requirements", "metaobjects-rules", "metaobjects-view-expressions", ]); diff --git a/server/typescript/packages/metadata/test/provider.test.ts b/server/typescript/packages/metadata/test/provider.test.ts index 349d7a18cd..8c9d6e6543 100644 --- a/server/typescript/packages/metadata/test/provider.test.ts +++ b/server/typescript/packages/metadata/test/provider.test.ts @@ -8,6 +8,8 @@ import { uiProvider } from "../src/presentation/ui/ui-provider.js"; import { uiWebProvider } from "../src/presentation/ui-web/ui-web-provider.js"; import { rulesProvider } from "../src/core/rules/rules-provider.js"; import { viewExpressionsProvider } from "../src/persistence/view-expressions/view-expressions-provider.js"; +import { reportingProvider } from "../src/core/reporting/reporting-provider.js"; +import { requirementsProvider } from "../src/core/requirement/requirements-provider.js"; import { TypeRegistry, TypeId } from "../src/registry.js"; import { MetaField } from "../src/core/field/meta-field.js"; import { @@ -99,7 +101,7 @@ describe("coreTypesProvider", () => { expect(registry.defaultSubTypeOf(TYPE_METADATA)).toBe(SUBTYPE_ROOT); }); - it("coreProviders is an eight-provider bundle: coreTypesProvider + dbProvider + docProvider + promptProvider + uiProvider + uiWebProvider + rulesProvider + viewExpressionsProvider", () => { + it("coreProviders is a ten-provider bundle: coreTypesProvider + dbProvider + docProvider + promptProvider + uiProvider + uiWebProvider + rulesProvider + viewExpressionsProvider + reportingProvider + requirementsProvider", () => { // FR-033 S1-field-A re-homed the field's filter/sort/teaching/extract/storage // attrs out of core into the concern providers. promptProvider (renamed from // templateProvider; id metaobjects-prompt) carries @xmlText/@example/@instruction @@ -112,8 +114,10 @@ describe("coreTypesProvider", () => { // PresentationOnly-excluded rows, so the manifest itself is unaffected. // rulesProvider (metaobjects-rules) and viewExpressionsProvider // (metaobjects-view-expressions) are packs split out of core in 1.3.0; they are in - // the default bundle so no model changes, and each can be composed out. - expect(coreProviders).toHaveLength(8); + // the default bundle so no model changes, and each can be composed out. So are + // reportingProvider (metaobjects-reporting) and requirementsProvider + // (metaobjects-requirements), split out the same way. + expect(coreProviders).toHaveLength(10); expect(coreProviders[0]).toBe(coreTypesProvider); expect(coreProviders[1]).toBe(dbProvider); expect(coreProviders[2]).toBe(docProvider); @@ -122,6 +126,8 @@ describe("coreTypesProvider", () => { expect(coreProviders[5]).toBe(uiWebProvider); expect(coreProviders[6]).toBe(rulesProvider); expect(coreProviders[7]).toBe(viewExpressionsProvider); + expect(coreProviders[8]).toBe(reportingProvider); + expect(coreProviders[9]).toBe(requirementsProvider); }); it("registerCoreTypes registers the structural types but not the DB-domain attrs", () => { @@ -133,10 +139,14 @@ describe("coreTypesProvider", () => { const viaProviders = composeRegistry(coreProviders); // dbProvider only extends and adds no types, so the only types composeRegistry adds - // over core alone are the two packs' (business rules, origin.function). - const packTypes = ["api", "operation", "binding", "transition"]; + // over core alone are the packs' (business rules, origin.function, reporting, + // requirements). + const packTypes = ["api", "operation", "binding", "transition", "dimension", "measure", "segment", "requirement"]; const coreOnly = viaProviders.allTypes().filter( - (t) => !packTypes.includes(t.type) && !(t.type === "origin" && t.subType === "function"), + (t) => + !packTypes.includes(t.type) && + !(t.type === "origin" && t.subType === "function") && + !(t.type === "object" && t.subType === "report"), ); expect(viaWrapper.allTypes().length).toBe(coreOnly.length); diff --git a/server/typescript/packages/metadata/test/registry.test.ts b/server/typescript/packages/metadata/test/registry.test.ts index 81532a91b2..f38462ef7c 100644 --- a/server/typescript/packages/metadata/test/registry.test.ts +++ b/server/typescript/packages/metadata/test/registry.test.ts @@ -16,7 +16,7 @@ import { TYPE_SOURCE, TYPE_ORIGIN, TYPE_TEMPLATE, - TYPE_REQUIREMENT, + OBJECT_SUBTYPE_REPORT, TYPE_API, SUBTYPE_BASE, SUBTYPE_ROOT, @@ -326,9 +326,9 @@ describe("registerCoreTypes", () => { expect(registry.allSubTypesOf(TYPE_METADATA).sort()).toEqual([SUBTYPE_ROOT]); }); - it("registers the correct subtypes for 'object'", () => { + it("registers the correct subtypes for 'object' (core alone: object.report is the reporting pack's)", () => { expect(registry.allSubTypesOf(TYPE_OBJECT).sort()).toEqual( - [...OBJECT_SUBTYPES].sort(), + OBJECT_SUBTYPES.filter((subType) => subType !== OBJECT_SUBTYPE_REPORT).sort(), ); }); @@ -450,15 +450,14 @@ describe("registerCoreTypes", () => { expect(def!.childRules).toHaveLength(0); }); - it("metadata.root (core alone) allows object, field, validator, template and requirement children (NOT a bare attr, and no api: the business-rules pack adds that)", () => { + it("metadata.root (core alone) allows object, field, validator and template children (NOT a bare attr; requirement and api come from their packs)", () => { // 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 - // requirements are declared beside the entities they describe. + // genuinely-open structural wildcards stay. `requirement` (the requirements + // pack) and `api` (the business-rules pack) are admitted by their packs. 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].sort()); }); // 6. attr.* has empty child rules diff --git a/server/typescript/packages/render/src/jinja/nunjucks.ts b/server/typescript/packages/render/src/jinja/nunjucks.ts index bc73ba2f71..4be140871a 100644 --- a/server/typescript/packages/render/src/jinja/nunjucks.ts +++ b/server/typescript/packages/render/src/jinja/nunjucks.ts @@ -7,6 +7,7 @@ import nunjucks from "nunjucks"; import { JINJA_EXTENSIONS } from "../engine.js"; +import { ERR_VAR_NOT_ON_PAYLOAD } from "../verify-shared.js"; import type { Provider } from "../provider.js"; /** A parsed nunjucks node. `fields` names the node's own child slots, in order. */ @@ -26,6 +27,7 @@ interface NunjucksInternals { parser: { parse(src: string): NjNode }; lib: { escape(value: string): string }; compiler: { Compiler: { prototype: CaptureCompiler } }; + runtime: { ensureDefined(value: unknown, lineno: number, colno: number): unknown }; } const internals = nunjucks as unknown as NunjucksInternals; @@ -95,12 +97,25 @@ function environment(provider: Provider): nunjucks.Environment { }; return new nunjucks.Environment(loader as unknown as nunjucks.ILoader, { autoescape: true, - throwOnUndefined: false, + throwOnUndefined: true, // `{{ x }}` on an undefined value raises; see `ensureDefinedOnly` trimBlocks: false, lstripBlocks: false, }); } +/** + * nunjucks' own `throwOnUndefined` check also refuses `null`, which Mustache (and Jinja's + * default) render as empty. Narrowed to `undefined` only, so a missing variable raises the + * same error the Mustache path does and a present `null` still renders empty. The engine + * does not know the variable's name at this point, so the message carries none. + */ +function ensureDefinedOnly(value: unknown): unknown { + if (value === undefined) { + throw new Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`); + } + return value; +} + /** Render Jinja `text` against `context`, escaping every `{{ … }}` with `escaper`. */ export function renderJinjaText( text: string, @@ -116,6 +131,8 @@ export function renderJinjaText( const compiler = internals.compiler.Compiler.prototype; const prevEscape = internals.lib.escape; const prevCapture = compiler.compileCapture; + const prevEnsure = internals.runtime.ensureDefined; + internals.runtime.ensureDefined = ensureDefinedOnly; internals.lib.escape = (v: unknown) => escaper(typeof v === "string" ? v : String(v)); compiler.compileCapture = safeCapture(prevCapture); try { @@ -123,5 +140,6 @@ export function renderJinjaText( } finally { internals.lib.escape = prevEscape; compiler.compileCapture = prevCapture; + internals.runtime.ensureDefined = prevEnsure; } } diff --git a/server/typescript/packages/render/src/render.ts b/server/typescript/packages/render/src/render.ts index 86209fb919..951ee731c9 100644 --- a/server/typescript/packages/render/src/render.ts +++ b/server/typescript/packages/render/src/render.ts @@ -19,7 +19,7 @@ import { type TemplateEngine, } from "./engine.js"; import { renderJinja } from "./jinja/render.js"; -import { MAX_DEPTH } from "./verify-shared.js"; +import { MAX_DEPTH, ERR_VAR_NOT_ON_PAYLOAD } from "./verify-shared.js"; // Resolve `{{> group/source }}` partials by inlining their text, recursively, // BEFORE Mustache parses — giving us deterministic whitespace and true, @@ -110,12 +110,39 @@ export function render(o: RenderOptions): string { return result; } +// A variable tag that resolves to `undefined` (the name is on no frame of the payload) is a +// missing variable. `null` is a present value and renders empty. Raised with the message the +// opt-in `verify` gate uses, so a typo like `{{nmae}}` fails on every render path. +interface WriterInternals { + prototype: Record<"escapedValue" | "unescapedValue", (token: unknown[], context: { lookup(n: string): unknown }, ...r: unknown[]) => unknown>; +} + +function failOnMissingVariable(): () => void { + const proto = (Mustache as unknown as { Writer: WriterInternals }).Writer.prototype; + const prev = { escapedValue: proto.escapedValue, unescapedValue: proto.unescapedValue }; + for (const key of ["escapedValue", "unescapedValue"] as const) { + const original = prev[key]; + proto[key] = function (this: unknown, token, context, ...rest) { + const name = String(token[1]); + if (context.lookup(name) === undefined) { + throw new Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`); + } + return original.call(this, token, context, ...rest); + }; + } + return () => { + proto.escapedValue = prev.escapedValue; + proto.unescapedValue = prev.unescapedValue; + }; +} + function renderMustache(body: string, o: RenderOptions, escaper: (s: string) => string): string { const expanded = expand(body, o.provider, o.ref !== undefined ? [o.ref] : []); const prev = Mustache.escape; Mustache.escape = (v: unknown) => escaper(typeof v === "string" ? v : String(v)); let result: string; + const restore = failOnMissingVariable(); try { // Derived `has` accessors are part of the payload contract, not of the // caller's object — see payload-accessors.ts. Injected here so a `{{#hasFoo}}` @@ -123,6 +150,7 @@ function renderMustache(body: string, o: RenderOptions, escaper: (s: string) => result = Mustache.render(expanded, withDerivedAccessors(o.payload), {}); } finally { Mustache.escape = prev; + restore(); } return result; } diff --git a/server/typescript/packages/render/test/render-conformance.test.ts b/server/typescript/packages/render/test/render-conformance.test.ts index a8efa43395..aa130789ba 100644 --- a/server/typescript/packages/render/test/render-conformance.test.ts +++ b/server/typescript/packages/render/test/render-conformance.test.ts @@ -8,7 +8,7 @@ import { render, InMemoryProvider, type RenderFormat } from "../src/index.js"; // template.mustache the entry template // partials/*.mustache optional partials, referenced as `partials/` // payload.json the render payload (pre-formatted primitives) -// expected.txt byte-exact expected output +// expected.txt byte-exact expected output, or expected-error.txt: the exact error message // The same (payload + template) MUST produce expected.txt byte-for-byte. const CORPUS = join(import.meta.dir, "../../../../../fixtures/render-conformance"); @@ -42,8 +42,14 @@ describe("render-conformance corpus", () => { const meta = JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")) as { format: RenderFormat }; const template = readFileSync(join(dir, "template.mustache"), "utf8"); const payload = JSON.parse(readFileSync(join(dir, "payload.json"), "utf8")); - const expected = readFileSync(join(dir, "expected.txt"), "utf8"); const provider = providerFromPartials(dir); + // expected-error.txt (instead of expected.txt): the exact message the render must throw. + if (existsSync(join(dir, "expected-error.txt"))) { + const message = readFileSync(join(dir, "expected-error.txt"), "utf8").replace(/\n$/, ""); + expect(() => render({ template, payload, provider, format: meta.format })).toThrow(message); + return; + } + const expected = readFileSync(join(dir, "expected.txt"), "utf8"); const actual = render({ template, payload, provider, format: meta.format }); expect(actual).toBe(expected); // determinism: identical across runs diff --git a/server/typescript/packages/render/test/render.test.ts b/server/typescript/packages/render/test/render.test.ts index f29fb633ba..565355f9c2 100644 --- a/server/typescript/packages/render/test/render.test.ts +++ b/server/typescript/packages/render/test/render.test.ts @@ -144,3 +144,20 @@ describe("render — maxChars output budget", () => { expect(render({ template: "{{x}}", payload: { x: long }, provider: P({}) })).toBe(long); }); }); + +describe("a missing variable raises on every render path", () => { + test("mustache: a variable absent from the payload throws the verify error by default", () => { + expect(() => render({ template: "Hi {{nmae}}!", payload: { name: "Ada" }, provider: P({}) })).toThrow( + "render verify failed: ERR_VAR_NOT_ON_PAYLOAD (nmae)", + ); + expect(() => render({ template: "Hi {{{nmae}}}!", payload: {}, provider: P({}) })).toThrow(/ERR_VAR_NOT_ON_PAYLOAD \(nmae\)/); + }); + test("mustache: null is present and renders empty; absent sections stay legal", () => { + expect(render({ template: "Hi {{n}}!{{#x}}y{{/x}}", payload: { n: null }, provider: P({}) })).toBe("Hi !"); + }); + test("jinja: a variable absent from the payload throws", () => { + expect(() => render({ template: "Hi {{ nmae }}!", payload: { name: "Ada" }, provider: P({}), engine: "jinja" })).toThrow( + /ERR_VAR_NOT_ON_PAYLOAD/, + ); + }); +}); diff --git a/site-reference/providers.html b/site-reference/providers.html index 2f4e15ae08..2c55cd7c41 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -51,7 +51,7 @@ INDEX.md lists by type.

metaobjects-core-types

Core metaobjects metamodel types and subtypes.

-

Owns (registers): attr.base, attr.boolean, attr.class, attr.double, attr.expression, attr.filter, attr.int, attr.intMap, attr.long, attr.properties, attr.string, field.base, field.boolean, field.currency, field.date, field.decimal, field.double, field.duration, field.enum, field.float, field.inet, field.int, field.long, field.map, field.object, field.string, field.time, field.timestamp, field.uri, field.uuid, identity.primary, identity.reference, identity.secondary, layout.base, layout.dataGrid, object.base, object.entity, object.projection, object.report, object.value, origin.aggregate, origin.base, origin.computed, origin.first, origin.passthrough, relationship.aggregation, relationship.association, relationship.base, relationship.composition, source.base, source.rdb, template.base, template.output, template.prompt, template.toolcall, validator.array, validator.atLeastOne, validator.base, validator.comparison, validator.exactlyOne, validator.length, validator.numeric, validator.presentIff, validator.regex, validator.required, validator.requiredWhen, view.base, view.checkbox, view.currency, view.date, view.dropdown, view.hidden, view.hotlink, view.image, view.month, view.number, view.password, view.radio, view.text, view.textarea, view.web

+

Owns (registers): attr.base, attr.boolean, attr.class, attr.double, attr.expression, attr.filter, attr.int, attr.intMap, attr.long, attr.properties, attr.string, field.base, field.boolean, field.currency, field.date, field.decimal, field.double, field.duration, field.enum, field.float, field.inet, field.int, field.long, field.map, field.object, field.string, field.time, field.timestamp, field.uri, field.uuid, identity.primary, identity.reference, identity.secondary, layout.base, layout.dataGrid, object.base, object.entity, object.projection, object.value, origin.aggregate, origin.base, origin.computed, origin.first, origin.passthrough, relationship.aggregation, relationship.association, relationship.base, relationship.composition, source.base, source.rdb, template.base, template.output, template.prompt, template.toolcall, validator.array, validator.atLeastOne, validator.base, validator.comparison, validator.exactlyOne, validator.length, validator.numeric, validator.presentIff, validator.regex, validator.required, validator.requiredWhen, view.base, view.checkbox, view.currency, view.date, view.dropdown, view.hidden, view.hotlink, view.image, view.month, view.number, view.password, view.radio, view.text, view.textarea, view.web

Contributes attributes:

  • field.base: @default, @mutability, @required, @unique
  • @@ -69,10 +69,9 @@

    metaobjects-core-types

  • object.base: @object, @objectAdapter
  • object.entity: @collectionName, @discriminator, @discriminatorValue
  • object.projection: @collectionName, @filter
  • -
  • object.report: @collectionName, @dimensions, @filter, @from, @measures, @segment, @spine
  • -
  • origin.aggregate: @agg, @distinct, @filter, @of, @orderBy, @segment, @via
  • +
  • origin.aggregate: @agg, @distinct, @filter, @of, @orderBy, @via
  • origin.computed: @expr
  • -
  • origin.first: @filter, @of, @orderBy, @segment, @via
  • +
  • origin.first: @filter, @of, @orderBy, @via
  • origin.passthrough: @convert, @from, @via
  • relationship.aggregation: @cardinality, @objectRef, @onDelete, @onUpdate, @sourceRefField, @symmetric, @through
  • relationship.association: @cardinality, @objectRef, @onDelete, @onUpdate, @sourceRefField, @symmetric, @through
  • @@ -157,6 +156,29 @@

    metaobjects-prompt

  • field.uuid: @example, @instruction, @xmlText
  • object.value: @normalize
+

metaobjects-reporting

+

Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.

+

Owns (registers): dimension.attribute, dimension.time, measure.aggregate, measure.derived, measure.ratio, object.report, segment.filter

+

Contributes attributes:

+
    +
  • dimension.attribute: @of, @via
  • +
  • dimension.time: @grains, @of, @via
  • +
  • measure.aggregate: @agg, @default, @distinct, @filter, @of, @segment
  • +
  • measure.derived: @expr
  • +
  • measure.ratio: @default, @denominator, @numerator
  • +
  • object.report: @collectionName, @dimensions, @filter, @from, @measures, @segment, @spine
  • +
  • origin.aggregate: @segment
  • +
  • origin.first: @segment
  • +
  • segment.filter: @filter
  • +
+

metaobjects-requirements

+

Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify.

+

Owns (registers): requirement.architectural, requirement.functional

+

Contributes attributes:

+
    +
  • requirement.architectural: @counterexample, @disposition, @implementedBy, @level, @statement, @status, @supersededBy, @trackedBy
  • +
  • requirement.functional: @counterexample, @disposition, @implementedBy, @level, @statement, @status, @supersededBy, @trackedBy
  • +

metaobjects-rules

Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).

Owns (registers): api.base, api.operational, binding.base, binding.rest, operation.base, operation.command, operation.query, transition.action, transition.base

diff --git a/site-reference/types/dimension.html b/site-reference/types/dimension.html index e033e0e119..2c9acd6c0d 100644 --- a/site-reference/types/dimension.html +++ b/site-reference/types/dimension.html @@ -52,6 +52,7 @@ (min..max, * = unbounded).

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.

+

Owning provider: metaobjects-reporting

When to use: A column a dashboard groups by: product, status, region. Declare it once on the fact entity and reference it by name from reports.

Attributes

@@ -72,7 +73,7 @@

dimension.attribute

- + @@ -81,7 +82,7 @@

dimension.attribute

- +
yes —metaobjects-reporting Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own.
no —metaobjects-reporting Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference.
@@ -89,6 +90,7 @@

dimension.attribute

No structural children.

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

+

Owning provider: metaobjects-reporting

When to use: Per-day, per-week or per-month series on a dashboard.

Attributes

@@ -109,7 +111,7 @@

dimension.time

- + @@ -118,7 +120,7 @@

dimension.time

- + @@ -127,7 +129,7 @@

dimension.time

- +
yes hour, day, week, month, quarter, year—metaobjects-reporting The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date.
yes —metaobjects-reporting Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object.
no —metaobjects-reporting Optional dotted to-one relationship path, as on dimension.attribute.
diff --git a/site-reference/types/measure.html b/site-reference/types/measure.html index 08479ad7ad..e5d2c731d4 100644 --- a/site-reference/types/measure.html +++ b/site-reference/types/measure.html @@ -52,6 +52,7 @@ (min..max, * = unbounded).

measure.aggregate

A named aggregate over the declaring entity's own rows (FR-044). @agg count without @distinct counts rows; with @distinct it counts distinct values of @of (a list in @of is a distinct count of the tuple). Unlike origin.aggregate, count is NOT distinct by default: a measure aggregates its own rows and dimensions reach only to-one paths, so no join inflates it.

+

Owning provider: metaobjects-reporting

When to use: A number a dashboard shows: revenue, purchases, distinct buyers, last activity.

Attributes

@@ -72,7 +73,7 @@

measure.aggregate

- + @@ -81,7 +82,7 @@

measure.aggregate

- + @@ -90,7 +91,7 @@

measure.aggregate

- + @@ -99,7 +100,7 @@

measure.aggregate

- + @@ -108,7 +109,7 @@

measure.aggregate

- + @@ -117,7 +118,7 @@

measure.aggregate

- +
yes count, sum, avg, min, max, any, all—metaobjects-reporting The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment.
no —metaobjects-reporting Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null), on min/max over a field that is not numeric, and on @agg any/all unless it is 0 (false) or 1 (true). A ratio's operand carries its own @default into the ratio.
no —metaobjects-reporting Count distinct values. Legal only with @agg: count.
no —metaobjects-reporting Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: "-P7D" }). Combines with @segment by AND.
no —metaobjects-reporting Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows.
no —metaobjects-reporting Optional name of a segment declared on the same entity. Combines with @filter by AND.
@@ -125,6 +126,7 @@

measure.aggregate

No structural children.

measure.derived

A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.

+

Owning provider: metaobjects-reporting

When to use: A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).

Attributes

@@ -145,7 +147,7 @@

measure.derived

- +
yes —metaobjects-reporting The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands.
@@ -153,6 +155,7 @@

measure.derived

No structural children.

measure.ratio

A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null.

+

Owning provider: metaobjects-reporting

When to use: Averages per unit that are not a plain avg: average days engaged per starter.

Attributes

@@ -173,7 +176,7 @@

measure.ratio

- + @@ -182,7 +185,7 @@

measure.ratio

- + @@ -191,7 +194,7 @@

measure.ratio

- +
no —metaobjects-reporting Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio.
yes —metaobjects-reporting Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field.
yes —metaobjects-reporting Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field.
diff --git a/site-reference/types/object.html b/site-reference/types/object.html index 88ec8d0e73..51afe20081 100644 --- a/site-reference/types/object.html +++ b/site-reference/types/object.html @@ -274,7 +274,7 @@

object.projection

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.

-

Owning provider: metaobjects-core-types

+

Owning provider: metaobjects-reporting

When to use: Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.

Attributes

@@ -295,7 +295,7 @@

object.report

- + @@ -304,7 +304,7 @@

object.report

- + @@ -313,7 +313,7 @@

object.report

- + @@ -322,7 +322,7 @@

object.report

- + @@ -331,7 +331,7 @@

object.report

- + @@ -358,7 +358,7 @@

object.report

- + @@ -367,7 +367,7 @@

object.report

- +
no metaobjects-core-typesmetaobjects-reporting The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own).
no metaobjects-core-typesmetaobjects-reporting Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row.
no metaobjects-core-typesmetaobjects-reporting Optional row scope over @from's fields; may use relative-date values.
yes metaobjects-core-typesmetaobjects-reporting The object.entity whose rows the report aggregates.
yes metaobjects-core-typesmetaobjects-reporting Measure names of @from.
no metaobjects-core-typesmetaobjects-reporting Optional segment of @from scoping the rows.
no metaobjects-core-typesmetaobjects-reporting Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report.
diff --git a/site-reference/types/origin.html b/site-reference/types/origin.html index c04fac091c..5b2c9b8464 100644 --- a/site-reference/types/origin.html +++ b/site-reference/types/origin.html @@ -119,7 +119,7 @@

origin.aggregate

no -metaobjects-core-types +metaobjects-reporting Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. @@ -221,7 +221,7 @@

origin.first

no -metaobjects-core-types +metaobjects-reporting Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. diff --git a/site-reference/types/requirement.html b/site-reference/types/requirement.html index be6dfd9d4e..b8216fd7ad 100644 --- a/site-reference/types/requirement.html +++ b/site-reference/types/requirement.html @@ -52,6 +52,7 @@ (min..max, * = unbounded).

requirement.architectural

How the system is built, applied uniformly across the model. Its check is UNIVERSALITY, the opposite polarity to a functional requirement. What meta verify enforces is that a live or partial policy is applied at all — one claiming nothing is an error — not that each node it claims complies. Flat by default and object-independent; it may optionally sit in a levelled tree when a quality taxonomy is being used to organise non-functional requirements.

+

Owning provider: metaobjects-requirements

When to use: Something exists because every entity here looks like this — a uuid primary key, an @autoSet createdAt, a change-attribution column, tenant scoping. The discriminator is mechanical: did this exist because someone asked for something, or because it is the architecture? For a non-functional tree, an established quality taxonomy makes a good fixed upper structure (e.g. an ISO/IEC 25010 characteristic at L1, its sub-characteristic or a control-catalogue category at L2), with the model-binding claims at L4 and L5 as usual.

Attributes

@@ -72,7 +73,7 @@

requirement.architectural

- + @@ -81,7 +82,7 @@

requirement.architectural

- + @@ -90,7 +91,7 @@

requirement.architectural

- + @@ -99,7 +100,7 @@

requirement.architectural

- + @@ -108,7 +109,7 @@

requirement.architectural

- + @@ -117,7 +118,7 @@

requirement.architectural

- + @@ -126,7 +127,7 @@

requirement.architectural

- + @@ -135,7 +136,7 @@

requirement.architectural

- +
yes —metaobjects-requirements What breaking it looks like — the node that would contradict it. A STATIC falsifiability test, not a state. This is what makes universality checkable. Renamed from @violation in 0.24.0, which read as a status.
no accepted, deferred—metaobjects-requirements As on requirement.functional. On an architectural requirement, accepted is the common and important case: a policy that is genuinely not universal, where the exceptions are known and tolerated, is more honest as partial+accepted than as a live claim nobody audits.
no —metaobjects-requirements FQN references to the nodes applying this policy. High fan-out is normal and expected: one uuid-primary-key requirement is claimed by every entity.
no —metaobjects-requirements OPTIONAL here, unlike on a functional requirement where it is required. ABSENT means a flat, object-independent policy that may reference the model directly — the original and still the default form. PRESENT means this node sits in a levelled tree, and then the same rules as functional apply: nesting must agree with the level, and only L4/L5 may carry @implementedBy. Levelling is opt-in so that adding a taxonomy on top of existing flat policies does not invalidate them.
yes —metaobjects-requirements The policy, in one sentence.
yes planned, live, partial, retired—metaobjects-requirements As on requirement.functional. A live or partial architectural requirement claimed by NOTHING is an error: a policy declared and applied to nothing. planned is exempt from that check — it is not applied yet by definition — and retired is exempt because a withdrawn policy governs nothing.
no —metaobjects-requirements The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not.
no —metaobjects-requirements As on requirement.functional. Issue or ticket references for outstanding work; free-form, not resolved.
@@ -145,6 +146,7 @@

requirement.architectural

requirement.functional

What the product does for a user, stated as one violable claim. Its check is EXISTENCE, run by meta verify: a live or partial claim with no implementing node anywhere in its subtree is a warning, and a named node that no longer exists is an error. Hierarchy is nesting — an L1 solution contains its L2 segments, which contain L3 services, and so on down to the levels that reference the model.

+

Owning provider: metaobjects-requirements

When to use: Something exists because someone asked for it. L1-L3 are levels of ABSTRACTION AND OWNERSHIP in the problem domain — whose need is this, and at what altitude — and are never a directory, package, deployable or module. Binding to technical constructs happens only at L4 (an object) and L5 (a member), which is the allocation step. Test every node: if a refactor that changes no behaviour would force it to move, its level is wrong.

Attributes

@@ -165,7 +167,7 @@

requirement.functional

- + @@ -174,7 +176,7 @@

requirement.functional

- + @@ -183,7 +185,7 @@

requirement.functional

- + @@ -192,7 +194,7 @@

requirement.functional

- + @@ -201,7 +203,7 @@

requirement.functional

- + @@ -210,7 +212,7 @@

requirement.functional

- + @@ -219,7 +221,7 @@

requirement.functional

- + @@ -228,7 +230,7 @@

requirement.functional

- +
yes —metaobjects-requirements What breaking it looks like, in one sentence — a STATIC falsifiability test, authored once, never a state. A requirement MUST be violable: 'every entity has a uuid primary key' is (point at one with a composite string key); 'things are persisted' is not, and is a description rather than a requirement. Renamed from @violation in 0.24.0, which read as a status.
no accepted, deferred—metaobjects-requirements What has been DECIDED about outstanding work — a different question from whether the work is done, which is what @status answers. accepted: the gap is understood and deliberately not being closed. deferred: it will be closed, but not now. ABSENT MEANS UNDECIDED, which is a real and useful state — it is what an unreviewed gap looks like, and it is the one a review should be able to find. Meaningful on planned and partial only; on a status with no outstanding work it is a WARNING. Deliberately NOT a workflow vocabulary: which sprint, who owns it and whether it is in progress belong in the tracker named by @trackedBy, because two systems holding that answer will drift and only one of them is refreshed daily.
no —metaobjects-requirements FQN references to the model nodes realising this requirement. Legal on level 4 (an object) and level 5 (a field, view or identity) only; an organisational level carrying it is ERR_REQUIREMENT_LINK_ABOVE_FLOOR. Many-to-many by construction — several requirements may name the same node.
yes —metaobjects-requirements 1 solution, 2 segment, 3 service, 4 object, 5 member. L1-L3 are levels of abstraction and ownership in the problem domain, NOT of code structure. Nesting depth must agree with it; skipping a level is legal, going back up is not.
yes —metaobjects-requirements What the capability is, in one sentence.
yes planned, live, partial, retired—metaobjects-requirements planned intended but not built yet; live implemented and in use; partial implemented with known gaps; retired BUILT THEN DELIBERATELY REMOVED — it must not be rebuilt. A requirement is PRESCRIPTIVE: it states what SHOULD be true and never journals what happened, and retired satisfies that because it states a prohibition in force, falsifiable by the capability reappearing. On retired, @implementedBy is REFUSED at load (ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS) — a retired capability has no implementation by definition, so its references cannot dangle because they cannot exist; @supersededBy names the requirement that replaced it. A dangling @implementedBy is an ERROR on live/partial (the model moved, the requirement is stale) and ALLOWED on planned, where the nodes do not exist YET. Neither planned nor retired contributes to object coverage: planning a capability must not silence the warning that nothing implements it, and neither must retiring one.
no —metaobjects-requirements The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not.
no —metaobjects-requirements Issue or ticket references for outstanding work — a URL, an owner/repo#123 shorthand, or a tracker key. Free-form and NOT resolved by verify, which does not reach the network; nothing here is checked to exist. Its job is to stop a deferred gap becoming invisible, so verify warns when a deferred requirement names no ticket. Also the right place to link the ticket that a planned requirement will be built under.
diff --git a/site-reference/types/segment.html b/site-reference/types/segment.html index 7c956d2e60..1ca0e1f6ea 100644 --- a/site-reference/types/segment.html +++ b/site-reference/types/segment.html @@ -52,6 +52,7 @@ (min..max, * = unbounded).

segment.filter

A named, reusable row filter on the declaring entity (FR-044). Measures and reports reference it by name; exporters emit it as a named segment.

+

Owning provider: metaobjects-reporting

When to use: The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.

Attributes

@@ -72,7 +73,7 @@

segment.filter

- +
yes —metaobjects-reporting The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values.
diff --git a/spec/metamodel/object.json b/spec/metamodel/object.json index ddf3c6eeec..ad288e6015 100644 --- a/spec/metamodel/object.json +++ b/spec/metamodel/object.json @@ -26,9 +26,6 @@ "children": [ { "type": "relationship", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "template", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } @@ -56,22 +53,6 @@ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] - }, - { - "type": "object", - "subType": "report", - "extendsBase": true, - "description": "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.", - "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", - "children": [ - { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, - { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, - { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, - { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } - ] } ] } diff --git a/spec/metamodel/origin.json b/spec/metamodel/origin.json index c4fde970f9..4d7e5aea16 100644 --- a/spec/metamodel/origin.json +++ b/spec/metamodel/origin.json @@ -28,7 +28,6 @@ { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -52,8 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." } ] } ] diff --git a/spec/metamodel/reporting.json b/spec/metamodel/reporting.json index adbe87f9ed..10a888b0c3 100644 --- a/spec/metamodel/reporting.json +++ b/spec/metamodel/reporting.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-reporting", "types": [ { "type": "dimension", "subType": "attribute", "description": "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.", @@ -46,6 +46,35 @@ "whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 1, "max": 1, "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } + ] }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "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.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, + { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, + { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, + { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + } + ], + "extends": [ + { "type": "object", "subType": "entity", "children": [ + { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null } + ] }, + { "type": "origin", "subType": "aggregate", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + ] }, + { "type": "origin", "subType": "first", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] } diff --git a/spec/metamodel/requirement.json b/spec/metamodel/requirement.json index f3017fd78d..a74ebd5758 100644 --- a/spec/metamodel/requirement.json +++ b/spec/metamodel/requirement.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-requirements", "types": [ { "type": "requirement", @@ -185,5 +185,10 @@ } ] } + ], + "extends": [ + { "type": "metadata", "subType": "root", "children": [ + { "type": "requirement", "subType": "*", "name": "*", "min": 0, "max": null } + ] } ] } From 113703d468179c89421c4ec5d861d9a53889f885 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 13:30:44 -0500 Subject: [PATCH 02/23] fix(rules): compare P3 permission names exactly, so '::' and '.' are not one name The P3 collision check rewrote '::' to '.' before comparing, so a derived p::Order.open counted as a collision with the transition's p.Order.open. They are different names in the metadata and the policy receives them as written. Removed the rewrite in TS, C#, Java, Python and Rust. The former error-rules-permission-name-op-package fixture becomes rules-permission-name-package-separator-distinct, which every port's conformance runner now loads clean. --- CHANGELOG.md | 6 +- docs/features/business-rules.md | 2 +- .../expected-errors.json | 15 ----- .../expected.json | 67 +++++++++++++++++++ .../input/meta.orders.api.json | 0 .../input/meta.orders.json | 0 .../providers.json | 0 .../Loader/ValidationPasses.Rules.cs | 5 +- .../metaobjects/loader/RulesValidation.java | 5 +- .../src/metaobjects/loader/validate_rules.py | 8 +-- server/rust/metaobjects/src/validate/rules.rs | 9 +-- .../metadata/src/loader/rules-validation.ts | 7 +- 12 files changed, 91 insertions(+), 33 deletions(-) delete mode 100644 fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json create mode 100644 fixtures/conformance/rules-permission-name-package-separator-distinct/expected.json rename fixtures/conformance/{error-rules-permission-name-op-package => rules-permission-name-package-separator-distinct}/input/meta.orders.api.json (100%) rename fixtures/conformance/{error-rules-permission-name-op-package => rules-permission-name-package-separator-distinct}/input/meta.orders.json (100%) rename fixtures/conformance/{error-rules-permission-name-op-package => rules-permission-name-package-separator-distinct}/providers.json (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffbfe4287d..482423104b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,10 +57,12 @@ here.** `expected.txt`. - **Business rules: two operations or transitions whose permission names come out equal are refused (rule P3).** A permission name is the declared `@permission`, or else the derived - `.` (a `::` package separator reads as `.`). When two permission points resolve to + `.`, compared exactly as the policy receives it, so `p::Order.open` and + `p.Order.open` are two names. When two permission points resolve to the same name and at least one of the two names is derived, the loader reports `ERR_TRANSITION_NAME_COLLISION` on the later one. Two equal declared names stay legal: that is a - shared permission. New fixtures `error-rules-permission-name-op-{dotted,declared,package}`. + shared permission. New fixtures `error-rules-permission-name-op-{dotted,declared}` and + `rules-permission-name-package-separator-distinct`. - **Python: unions and one-row-per-list-item views are checked at load.** The two must-fail projection fixtures (a `@union` whose branches do not line up, and a `@grain` view that breaks its rules) now fail in Python as they do in the other ports, and leave the Python diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index bcbe91e84c..1bcfb355e6 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -183,7 +183,7 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa | 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. | -| P3 | `ERR_TRANSITION_NAME_COLLISION` | Two permission points ask about one permission name and at least one name is derived: an operation named `Order.open`, one declaring `permission: p.Order.open`, or one in package `p::Order`, beside the `open` transition of `Order` in `p`. `::` and `.` compare equal. Two declared `permission` values may be equal. | +| P3 | `ERR_TRANSITION_NAME_COLLISION` | Two permission points ask about one permission name and at least one name is derived: an operation named `Order.open`, or one declaring `permission: p.Order.open`, beside the `open` transition of `Order` in `p`. Names are compared exactly as the policy receives them: `::` and `.` are different things in the metadata, so an `open` operation in package `p::Order` (`p::Order.open`) does not collide with that transition (`p.Order.open`). Two declared `permission` values may be equal. | | B1 | `ERR_BINDING_PATH_MISMATCH` | A `binding.rest` `path` has the wrong placeholders. | | B2 | `ERR_BINDING_PATH_MISMATCH` | Two declared bindings of one API have the same method (declared or derived) and the same path, ignoring placeholder names. | diff --git a/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json b/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json deleted file mode 100644 index 9728c81073..0000000000 --- a/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "errors": [ - { - "code": "ERR_TRANSITION_NAME_COLLISION", - "source": { - "format": "json", - "files": [ - "meta.orders.api.json" - ], - "jsonPath": "$['metadata.root'].children[0]['api.operational'].children[0]['operation.query']" - } - } - ], - "warnings": [] -} diff --git a/fixtures/conformance/rules-permission-name-package-separator-distinct/expected.json b/fixtures/conformance/rules-permission-name-package-separator-distinct/expected.json new file mode 100644 index 0000000000..4e90e966c3 --- /dev/null +++ b/fixtures/conformance/rules-permission-name-package-separator-distinct/expected.json @@ -0,0 +1,67 @@ +{ + "metadata.root": { + "children": [ + { + "api.operational": { + "name": "Orders", + "package": "p::Order", + "children": [ + { + "operation.query": { + "name": "open", + "@outputRef": "p::Order" + } + } + ] + } + }, + { + "object.entity": { + "name": "Order", + "package": "p", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.enum": { + "name": "status", + "@default": "draft", + "@values": [ + "draft", + "open" + ], + "children": [ + { + "transition.action": { + "name": "open", + "@from": [ + "draft" + ], + "@to": "open" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json b/fixtures/conformance/rules-permission-name-package-separator-distinct/input/meta.orders.api.json similarity index 100% rename from fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json rename to fixtures/conformance/rules-permission-name-package-separator-distinct/input/meta.orders.api.json diff --git a/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json b/fixtures/conformance/rules-permission-name-package-separator-distinct/input/meta.orders.json similarity index 100% rename from fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json rename to fixtures/conformance/rules-permission-name-package-separator-distinct/input/meta.orders.json diff --git a/fixtures/conformance/error-rules-permission-name-op-package/providers.json b/fixtures/conformance/rules-permission-name-package-separator-distinct/providers.json similarity index 100% rename from fixtures/conformance/error-rules-permission-name-op-package/providers.json rename to fixtures/conformance/rules-permission-name-package-separator-distinct/providers.json diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs index a18ad72619..2c0b2c601d 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs @@ -380,13 +380,14 @@ private sealed record PermissionPoint(MetaData Node, bool Derived); /// The name a permission point asks the policy about: its @permission, else <package>.<path> /// (the path is the operation name, or <Entity>.<transition> for a transition's command). The package - /// prefix is dropped when there is none. :: and . both separate path segments, so they compare equal. + /// prefix is dropped when there is none. The name is compared exactly as the policy receives it: :: and . + /// are different things in the metadata, so p::Order.open and p.Order.open are two names. private static (string Name, bool Derived) PermissionNameOf(MetaData node, MetaData owner, string path) { var declared = node.Attr(OPERATION_ATTR_PERMISSION) as string; var pkg = NamingRefs.EffectivePackageOf(NamingRefs.TopLevelNodeOf(owner)); var name = declared ?? (pkg.Length == 0 ? path : $"{pkg}.{path}"); - return (name.Replace("::", "."), declared is null); + return (name, declared is null); } /// P3: two permission points, one name, at least one of the two derived. Points are every non-public diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java index 7358a4b167..74b0451f3d 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java @@ -469,8 +469,9 @@ private static void registerPermissionPoint(MetaData node, MetaData owner, Strin if (flag(node, ApiConstants.ATTR_PUBLIC)) return; String declared = Lifecycles.stringValue(node, ApiConstants.ATTR_PERMISSION); String pkg = References.effectivePackageOf(owner); - String raw = declared != null ? declared : pkg.isEmpty() ? path : pkg + "." + path; - String name = raw.replace("::", "."); + // Compared exactly as the policy receives it: "::" and "." are different things in the + // metadata, so "p::Order.open" and "p.Order.open" are two names. + String name = declared != null ? declared : pkg.isEmpty() ? path : pkg + "." + path; boolean derived = declared == null; List points = byName.computeIfAbsent(name, k -> new ArrayList<>()); PermissionPoint clash = null; diff --git a/server/python/src/metaobjects/loader/validate_rules.py b/server/python/src/metaobjects/loader/validate_rules.py index 0d37c3626c..ead5659bd2 100644 --- a/server/python/src/metaobjects/loader/validate_rules.py +++ b/server/python/src/metaobjects/loader/validate_rules.py @@ -500,16 +500,16 @@ def validate_rules(root: MetaData, errors: list[MetaError]) -> None: def _permission_name_of(node: MetaData, owner: MetaData, path: str) -> tuple[str, bool]: """The name a permission point asks the policy about: its @permission, else ``.`` (the path is ````, or ``.`` for a - transition's command), with the package prefix dropped when there is none. ``::`` and - ``.`` both separate path segments, so ``p::Order`` + ``open`` and ``p`` + ``Order.open`` - are one name. Returns (name, derived).""" + transition's command), with the package prefix dropped when there is none. The name is + compared exactly as the policy receives it: ``::`` and ``.`` are different things in the + metadata, so ``p::Order.open`` and ``p.Order.open`` are two names. Returns (name, derived).""" declared = node.get_meta_attr(OPERATION_ATTR_PERMISSION) pkg = effective_package_of(top_level_node_of(owner)) if isinstance(declared, str): name = declared else: name = path if pkg == "" else f"{pkg}.{path}" - return name.replace("::", "."), not isinstance(declared, str) + return name, not isinstance(declared, str) def _check_permission_names(root: MetaData, sink: _Sink) -> None: diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index 4296e5891c..7a66656fcc 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -1102,9 +1102,10 @@ fn check_api_routes(tree: &Tree, ops: &[NodeId], sink: &mut Sink<'_>) { } /// The name a permission point asks the policy about: its `@permission`, else -/// `.` (the package prefix is dropped when there is none). `::` and `.` -/// both separate path segments, so they compare equal. Returns the name and whether it -/// is derived. +/// `.` (the package prefix is dropped when there is none). The name is +/// compared exactly as the policy receives it: `::` and `.` are different things in the +/// metadata, so `p::Order.open` and `p.Order.open` are two names. Returns the name and +/// whether it is derived. fn permission_name_of(tree: &Tree, node: NodeId, owner: NodeId, path: &str) -> (String, bool) { let declared = match tree.attr(node, A_PERMISSION) { Some(Value::String(s)) => Some(s.as_str()), @@ -1116,7 +1117,7 @@ fn permission_name_of(tree: &Tree, node: NodeId, owner: NodeId, path: &str) -> ( None if pkg.is_empty() => path.to_string(), None => format!("{pkg}.{path}"), }; - (name.replace(PACKAGE_SEP, "."), declared.is_none()) + (name, declared.is_none()) } /// P3: two permission points, one name. Points are every non-public operation and every diff --git a/server/typescript/packages/metadata/src/loader/rules-validation.ts b/server/typescript/packages/metadata/src/loader/rules-validation.ts index ebd8494cf2..669c7698ff 100644 --- a/server/typescript/packages/metadata/src/loader/rules-validation.ts +++ b/server/typescript/packages/metadata/src/loader/rules-validation.ts @@ -392,13 +392,14 @@ interface PermissionPoint { /** The name a permission point asks the policy about: its @permission, else `.` * (the path is ``, or `.` for a transition's command). The package - * prefix is dropped when there is none. `::` and `.` both separate path segments, so they compare - * equal: `p::Order` + `open` and `p` + `Order.open` are one name. */ + * prefix is dropped when there is none. The name is compared exactly as the policy receives it: + * `::` and `.` are different things in the metadata, so `p::Order.open` and `p.Order.open` are + * two names, not one. */ function permissionNameOf(node: MetaData, owner: MetaData, path: string): { name: string; derived: boolean } { const declared = node.attr(OPERATION_ATTR_PERMISSION); const pkg = effectivePackageOf(topLevelNodeOf(owner)); const name = typeof declared === "string" ? declared : pkg === "" ? path : `${pkg}.${path}`; - return { name: name.replaceAll("::", "."), derived: typeof declared !== "string" }; + return { name, derived: typeof declared !== "string" }; } /** P3: two permission points, one name. Points are every non-public operation and every transition From 6e3d6cfd0888dea6e081cd9ee5041314b8f566b7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:41:12 -0500 Subject: [PATCH 03/23] docs(changelog): drop a leftover rebase marker --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 482423104b..ed1cb63747 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,7 +32,6 @@ here.** exactly the reference content is left alone and reported as identical, with or without `force`. The codegen fingerprint, `metaobjects:fmt` and `metaobjects:init` also compare before they write. -||||||| parent of 10fffac63 (feat: move reporting and requirements into their own provider packs; raise on missing template variables; refuse permission-name collisions) - **Reporting and requirements are vocabulary packs, out of core.** The reporting vocabulary (`object.report`, `dimension.*`, `measure.*` including `measure.derived` and its `@expr`, `segment.filter`, the entity's dimension, measure and segment children and `@segment` on From 50d14e1f75673d60b2096dff796a9c697276a4c3 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:44:15 -0500 Subject: [PATCH 04/23] no-mistakes(review): apply reviewer inline fixes --- .../src/main/java/com/metaobjects/loader/RulesValidation.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java index 74b0451f3d..b4f8dac5c7 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java @@ -441,8 +441,8 @@ private record PermissionPoint(MetaData node, boolean derived) {} * P3: two permission points ask the policy about one permission name, and at least one of the two * names is derived. Points are every non-public operation and every transition of a live concrete * entity (a transition derives a command each). A name is the node's {@code @permission}, else - * {@code .} (the path is the operation name, or {@code Entity.transition}); {@code ::} - * and {@code .} both separate segments so they compare equal. Compared case-sensitively. Transitions + * {@code .} (the path is the operation name, or {@code Entity.transition}); the name is + * compared exactly, so {@code ::} and {@code .} are different and never equal. Compared case-sensitively. Transitions * register first, so the error lands on the operation when an operation meets a transition. Two * DECLARED values may be equal: that sharing is the point. */ From f3226cd9fa6d5166dbdc89bdf0b9f4cf35d6e0e4 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 16:01:50 -0500 Subject: [PATCH 05/23] no-mistakes(test): Wrap two rustfmt-flagged lines in Rust registry and rules --- server/rust/metaobjects/src/registry.rs | 6 +++++- server/rust/metaobjects/src/validate/rules.rs | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/server/rust/metaobjects/src/registry.rs b/server/rust/metaobjects/src/registry.rs index f90fd1e241..0746c02f6e 100644 --- a/server/rust/metaobjects/src/registry.rs +++ b/server/rust/metaobjects/src/registry.rs @@ -322,7 +322,11 @@ impl TypeRegistry { .map(|b| b.attributes.iter().map(|a| a.name.clone()).collect()) .unwrap_or_default() }; - for attr in def.attributes.iter().filter(|a| !base_names.contains(&a.name)) { + for attr in def + .attributes + .iter() + .filter(|a| !base_names.contains(&a.name)) + { self.check_attr_ownership(&def.type_name, &def.sub_type, &attr.name)?; } let (type_name, sub_type) = (def.type_name.clone(), def.sub_type.clone()); diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index 7a66656fcc..72079bc5d4 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -1161,7 +1161,11 @@ fn check_permission_names(ctx: &Ctx<'_>, top_level: &[NodeId], sink: &mut Sink<' if !is_entity(tree, entity) || tree.node(entity).is_abstract { continue; } - if !tree.children(entity).iter().any(|&c| tree.node(c).type_name == T_SOURCE) { + if !tree + .children(entity) + .iter() + .any(|&c| tree.node(c).type_name == T_SOURCE) + { continue; } let ename = tree.node(entity).name.clone(); From 36ee0a6bdde795eba14617fa606c032ca65dd57e Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 16:19:19 -0500 Subject: [PATCH 06/23] no-mistakes(document): sync docs with packs, render errors, P3 --- CHANGELOG.md | 3 +- docs/CONFORMANCE.md | 13 ++++++--- docs/features/business-rules.md | 5 ++-- docs/features/libraries.md | 3 +- docs/features/reporting.md | 3 ++ docs/features/requirements.md | 5 +++- docs/features/templates-and-payloads.md | 29 +++++++++++-------- .../ADR-0061-per-port-template-engines.md | 14 +++++++-- .../ADR-0062-provider-attribute-ownership.md | 20 ++++++++++++- 9 files changed, 71 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed1cb63747..bd3636c852 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,7 +61,8 @@ here.** the same name and at least one of the two names is derived, the loader reports `ERR_TRANSITION_NAME_COLLISION` on the later one. Two equal declared names stay legal: that is a shared permission. New fixtures `error-rules-permission-name-op-{dotted,declared}` and - `rules-permission-name-package-separator-distinct`. + `rules-permission-name-package-separator-distinct`. Java now accepts dotted operation names + (`Order.open`), as TypeScript, C# and Python already did. - **Python: unions and one-row-per-list-item views are checked at load.** The two must-fail projection fixtures (a `@union` whose branches do not line up, and a `@grain` view that breaks its rules) now fail in Python as they do in the other ports, and leave the Python diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index c74e6ae4a7..76a1071a9e 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -475,15 +475,20 @@ spreadsheet / CSV-injection escape / CSV numeric-literal exemption); 13 pin Must semantics — dotted-path lookup, parent-context fallthrough, falsy/empty-array section behavior, inverted sections, nested partials, a comment tag beside a partial, standalone-tag whitespace stripping, raw-HTML bypass, trailing-newline preservation, unicode multibyte handling, the derived -`has` accessor, and the `-last` list-separator accessor. +`has` accessor, and the `-last` list-separator accessor. The last 2 are error cases: a fixture +that must refuse carries `expected-error.txt` in place of `expected.txt`, holding the error text +the render must raise (`render verify failed: ERR_VAR_NOT_ON_PAYLOAD ()`). Every port that runs +this corpus reads that convention; TypeScript compares the text exactly, and Python and C# +require it to appear in the raised message. -### `fixtures/jinja-render-conformance/` (15) and `fixtures/jinja-verify-conformance/` (31) +### `fixtures/jinja-render-conformance/` (16) and `fixtures/jinja-verify-conformance/` (31) Both → [features/templates-and-payloads.md](features/templates-and-payloads.md) (Jinja templates section, [ADR-0061](../spec/decisions/ADR-0061-per-port-template-engines.md)). Run by Python (jinja2) and TypeScript (nunjucks) only; Java, Kotlin and C# refuse a Jinja body with -`ERR_TEMPLATE_ENGINE_UNSUPPORTED` instead. The render corpus holds 13 output cases and 2 error -cases (an include cycle and an unresolved include), each with the same Mustache-path message. +`ERR_TEMPLATE_ENGINE_UNSUPPORTED` instead. The render corpus holds 13 output cases and 3 error +cases (an include cycle, an unresolved include and a missing variable), each with the same +Mustache-path message. The verify corpus reuses `verify-conformance/`'s `payload.json` field-tree shape; an `ERR_TEMPLATE_SYNTAX` finding's path is the parser's own message, so runners compare it as empty. diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 1bcfb355e6..cd36f47fe6 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -187,8 +187,9 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa | 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. +Names are compared without case (L5 and O0, L6, O6) because each one becomes a command, a permission +constant and a file, and those collide on a case-folding target. P3 compares permission names +exactly, as the policy receives them. Some refusals come from the registry: diff --git a/docs/features/libraries.md b/docs/features/libraries.md index a35f53be36..437c05780c 100644 --- a/docs/features/libraries.md +++ b/docs/features/libraries.md @@ -175,7 +175,8 @@ Anything else stays with the adopter (policy, presentation, branding, scheduling separate project. **Worked example, reporting** ([reporting.md](reporting.md)). The vocabulary (dimensions, -measures, segments, `object.report`) is core. The planned `reporting` library holds +measures, segments, `object.report`) is the `metaobjects-reporting` provider pack, in the default +bundle ([extending-with-providers.md](extending-with-providers.md)). The planned `reporting` library holds metadata only, so opting in adds no code. Exporting to another tool and dashboards are catalog generators, one per heavy format, so an adopter never takes a dependency they did not wire: `cube-model` ships today, a dashboard generator does not exist yet. diff --git a/docs/features/reporting.md b/docs/features/reporting.md index 7f56862391..4501205705 100644 --- a/docs/features/reporting.md +++ b/docs/features/reporting.md @@ -48,6 +48,9 @@ mean what they appear to mean: a measure of one table in a report over another, ## What is registered +They are registered by the `metaobjects-reporting` provider pack, which the default bundle +composes; an embedder can leave it out ([extending-with-providers.md](extending-with-providers.md)). + Exactly these names, and nothing else: | Node | Lives on | Attributes | diff --git a/docs/features/requirements.md b/docs/features/requirements.md index 9b04b916fc..646cc09d5b 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -5,7 +5,10 @@ supposed to do, as metadata, checked by `verify` in every port._ **Status:** registered vocabulary in all five ports (TypeScript, Java, C#, Python, Kotlin). The requirement gate runs in every port's `verify`, and every port ships a -`requirement-tests` generator. The authoring lint is TypeScript-only. +`requirement-tests` generator. The authoring lint is TypeScript-only. The vocabulary is the +`metaobjects-requirements` provider pack, in the default bundle. With the pack left out, a +`requirement.*` node is a loader error, and a model with none gets a silent, empty ledger +([extending-with-providers.md](extending-with-providers.md)). **Entirely opt-in.** A model with no `requirement.*` nodes gets no diagnostics, generates nothing, and reads nothing — no codegen, migrate or runtime path touches the type. You opt in diff --git a/docs/features/templates-and-payloads.md b/docs/features/templates-and-payloads.md index faef254739..757f238cfa 100644 --- a/docs/features/templates-and-payloads.md +++ b/docs/features/templates-and-payloads.md @@ -228,7 +228,9 @@ Hi {{ displayName | title }}, you have {{ postCount }} posts. ``` Python and TypeScript render the shared Jinja vocabulary identically -(`fixtures/jinja-render-conformance/`). Outside it the two engines differ: an empty list is +(`fixtures/jinja-render-conformance/`), and both raise `ERR_VAR_NOT_ON_PAYLOAD` on a printed name +the payload lacks, while a present null prints empty. Outside it the two engines differ: an empty +list is false in jinja2 and true in nunjucks (write `{% if items | length %}`), a printed list or dict is engine-specific text, and Python-only syntax (`{% with %}`, `name.upper()`, `True`) does not run in nunjucks. Looping over a null value renders nothing in nunjucks and fails the @@ -714,16 +716,17 @@ and checks each one exists on the payload VO. If a template references body (Python and TypeScript) is checked the same way; see [Jinja templates](#jinja-templates-python-and-typescript). -**The same check runs at render time in every generated render helper** (the `template.output` -helper and the `template.prompt` handle, in all five ports). The helper carries its payload's -field tree, so text edited or served after codegen that names a variable the payload lacks -(`{{nmae}}` for `name`) raises `ERR_VAR_NOT_ON_PAYLOAD` instead of rendering as an empty -string. Before this, the TypeScript `promptRender()` handle, the Python helper on a Mustache -body, and the Java and Kotlin helpers rendered it silently. Calling the engine's `render()` -directly with no declared payload keeps the engine's default, since there is nothing to compare -against; ask for the check by passing the field tree (`verify` in TypeScript, Java, Kotlin and -C#; `verify=` in Python). Pinned by -[`fixtures/template-output-render-conformance/runtime-drift/`](../../fixtures/template-output-render-conformance/runtime-drift/). +**A variable the payload lacks fails at render time, on every render path.** Text edited or +served after codegen that names a variable the payload lacks (`{{nmae}}` for `name`) raises +`ERR_VAR_NOT_ON_PAYLOAD` instead of rendering as an empty string. The engine's `render()` raises +it for a Mustache body in TypeScript, C#, Java (and so Kotlin) and Python, and for a Jinja body in +TypeScript and Python. A present `null` still renders empty, and a section over an absent name +still renders nothing. The generated render helpers (the `template.output` helper and the +`template.prompt` handle, in all five ports) carry the payload's field tree, so the same miss is +caught in text served after codegen. Passing the field tree to the engine (`verify` in TypeScript, +Java, Kotlin and C#; `verify=` in Python) also checks names against the declared fields. Pinned by +[`fixtures/template-output-render-conformance/runtime-drift/`](../../fixtures/template-output-render-conformance/runtime-drift/), +and by the `render-error-missing-variable` and `render-error-missing-dotted-path` render fixtures. A bare `verify` also checks generated code and the requirement ledger; name the template check to run it alone. Java and Python skip this check with a note when no template root is @@ -789,6 +792,8 @@ for payload typing per #270) **Render engine semantics** — Mustache-spec behavior pinned cross-port (every port's renderer must emit byte-identical output) - [`fixtures/render-conformance/render-dotted-path-lookup/`](../../fixtures/render-conformance/render-dotted-path-lookup/) — `{{a.b.c}}` traversal across nested objects +- [`fixtures/render-conformance/render-error-missing-variable/`](../../fixtures/render-conformance/render-error-missing-variable/) — a `{{name}}` the payload lacks raises `ERR_VAR_NOT_ON_PAYLOAD` (`expected-error.txt`, in place of `expected.txt`) +- [`fixtures/render-conformance/render-error-missing-dotted-path/`](../../fixtures/render-conformance/render-error-missing-dotted-path/) — a dotted path whose leaf the payload lacks raises the same error - [`fixtures/render-conformance/render-parent-context-fallthrough/`](../../fixtures/render-conformance/render-parent-context-fallthrough/) — a key missing in the current section falls through to the parent context - [`fixtures/render-conformance/render-empty-array-falsiness/`](../../fixtures/render-conformance/render-empty-array-falsiness/) — `{{#xs}}…{{/xs}}` over an empty array renders nothing (vs. iterates) - [`fixtures/render-conformance/render-falsy-values/`](../../fixtures/render-conformance/render-falsy-values/) — `false`, `null`, empty string, `0` — which are truthy for `{{#x}}` sections (per Mustache spec, not JS truthiness) @@ -806,7 +811,7 @@ for the per-port pass/skip ledger. **Jinja bodies (Python and TypeScript, ADR-0061)** -- [`fixtures/jinja-render-conformance/`](../../fixtures/jinja-render-conformance/) — 15 cases: variables, loops, conditionals, `set` and macros, `include` and `import`, filters, html and json escaping (with and without `| escape`), whitespace control, `raw` and comments, plus an include cycle and an unresolved include. Byte-identical output from jinja2 and nunjucks. +- [`fixtures/jinja-render-conformance/`](../../fixtures/jinja-render-conformance/) — 16 cases: variables, loops, conditionals, `set` and macros, `include` and `import`, filters, html and json escaping (with and without `| escape`), whitespace control, `raw` and comments, plus an include cycle, an unresolved include and a missing variable. Byte-identical output from jinja2 and nunjucks. - [`fixtures/jinja-verify-conformance/`](../../fixtures/jinja-verify-conformance/) — 31 cases: the payload check over the parsed template (paths, loop targets, locals, filters, includes, imports, `extends` blocks, `ERR_TEMPLATE_NOT_STATIC`, `ERR_TEMPLATE_SYNTAX`, required slots and tags). ## See also diff --git a/spec/decisions/ADR-0061-per-port-template-engines.md b/spec/decisions/ADR-0061-per-port-template-engines.md index 031bfaf518..6e88cd9e86 100644 --- a/spec/decisions/ADR-0061-per-port-template-engines.md +++ b/spec/decisions/ADR-0061-per-port-template-engines.md @@ -109,8 +109,8 @@ that must render the same in both ports should stay inside the corpus vocabulary `loop.last`). Printed scalars are normalized in both ports to the Mustache renderer's form: `true`/`false`, -a whole float as an integer, and `None`/`undefined` as empty text. A lookup on a missing key -renders empty however deep it chains (`v.x.y`). +a whole float as an integer, and a present `None`/`null` as empty text. A lookup on a missing key +stays missing however deep it chains (`v.x.y`), and printing it raises (Amendment 1). ## Consequences @@ -121,3 +121,13 @@ renders empty however deep it chains (`v.x.y`). - A model whose templates are Jinja renders in Python and TypeScript only. That is by design: the engine is a property of the port, and the refusal in the other three ports says so by code. - The migration analyzer, the other option in #483, is not built. + +## Amendments + +### Amendment 1 (2026-11-21) — a variable the payload lacks raises, in both engines + +Printing a name absent from the payload raises `render verify failed: ERR_VAR_NOT_ON_PAYLOAD` in +the Jinja engines (jinja2 and nunjucks) and in every port's Mustache engine (Rust renders no +template). It is the message the Mustache path raises, and it applies on every render path. A present null still prints empty, and a section over an absent name still +renders nothing. Corpus: `fixtures/jinja-render-conformance/jinja-render-error-missing-variable/` and +`fixtures/render-conformance/render-error-missing-variable/`. diff --git a/spec/decisions/ADR-0062-provider-attribute-ownership.md b/spec/decisions/ADR-0062-provider-attribute-ownership.md index 7df201d68d..991d8ca0e5 100644 --- a/spec/decisions/ADR-0062-provider-attribute-ownership.md +++ b/spec/decisions/ADR-0062-provider-attribute-ownership.md @@ -4,7 +4,9 @@ **Accepted** (2026-11-04). Registers no vocabulary: `metamodelVersion` is unchanged. Adds one error code, `ERR_PROVIDER_ATTR_SHADOW`, and records which provider registered each attribute. -Amends nothing; it states how ADR-0007 and ADR-0018 are meant to scale. Closes #527. +Amends nothing in its decision; it states how ADR-0007 and ADR-0018 are meant to scale. Closes #527. +[Amendment 1](#amendment-1-2026-11-21--an-attribute-folded-from-the-base-is-not-a-new-claim) +records the one exception the rule has since gained. ## Context @@ -95,3 +97,19 @@ a collision. - **Last registration wins** — what happened before; the result depends on provider order. - **One new code for all three cases** — would have changed the established `ERR_PROVIDER_ATTR_CONFLICT` fixture and message for existing consumers. + +## Amendments + +### Amendment 1 (2026-11-21) — an attribute folded from the base is not a new claim + +A subtype declared with `extendsBase: true` folds in the attributes of its registered +`.base`. `object.report`, registered by the reporting pack, is the first. A folded +attribute is the base provider's, not a claim by the provider that registers the subtype. The +registry does not run the rule above on it, and the base provider stays the owner in `meta types` +and in any error message. Nothing else is excepted: a subtype that declares its own attribute, +under a name another provider holds on the base or on a related slot, is still refused. + +Matching is by object identity in TypeScript, C# and Python: the folded definition holds the base's +attribute object. Rust matches by name. The two differ only when a subtype redeclares a base +attribute with the same name; Rust then reads the redeclaration as folded, and the other ports read +it as a new claim. That difference is accepted. From e6e35d9742c494c09d65a1e820869965edc30d04 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 16:21:34 -0500 Subject: [PATCH 07/23] no-mistakes(document): point pack docs at vocabulary owner --- docs/features/business-rules.md | 2 ++ docs/features/extending-with-providers.md | 5 ++--- docs/features/libraries.md | 6 +++--- docs/features/reporting.md | 5 +++-- docs/features/requirements.md | 7 +++---- 5 files changed, 13 insertions(+), 12 deletions(-) diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index cd36f47fe6..6fa651ae1f 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -10,6 +10,8 @@ The model never says *how* an operation works. That is code. The model says wher 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. +It is a provider pack, composed by default: see +[Where vocabulary lives](extending-with-providers.md#where-vocabulary-lives). The Rust port loads the vocabulary and runs the same loader rules, and its `verify` runs the same rules gate, held to `fixtures/rules-check-conformance/` ([Rust port](../ports/rust.md)). A requirement can claim an operation or a transition. Nothing is generated from the vocabulary diff --git a/docs/features/extending-with-providers.md b/docs/features/extending-with-providers.md index 880b611234..e951fc77c7 100644 --- a/docs/features/extending-with-providers.md +++ b/docs/features/extending-with-providers.md @@ -127,9 +127,8 @@ vocabulary is [ADR-0037](../../spec/decisions/ADR-0037-metamodel-vocabulary-expa `origin.aggregate` and `origin.first`, provider `metaobjects-reporting`) and requirements (`requirement.*`, provider `metaobjects-requirements`) are packs: each is its own provider, in the default bundle of every port, and an embedder can leave it out. A model that uses a left-out -pack's types gets a loader error naming the unknown type, subtype or attribute. The `verify` -requirements gate reads the requirement nodes the pack registered, so with that pack left out it -has nothing to report. `object.report` shows the one thing a pack subtype may borrow from core: +pack's types gets a loader error naming the unknown type, subtype or attribute. With the +requirements pack left out, a model with no `requirement.*` node gets an empty `verify` ledger. `object.report` shows the one thing a pack subtype may borrow from core: declared with `extendsBase`, it folds in `object.base`, which core registers, and those folded attributes stay owned by core. New vocabulary follows the same path: a gate (`scripts/check-core-vocabulary-pin.ts`) pins the core provider's types and attributes, so adding diff --git a/docs/features/libraries.md b/docs/features/libraries.md index 437c05780c..c8996cb762 100644 --- a/docs/features/libraries.md +++ b/docs/features/libraries.md @@ -157,7 +157,7 @@ MetaObjects ships four kinds of package. They differ in who owns the result: | kind | what it is | ownership | |---|---|---| -| **Vocabulary** | metamodel types and attributes | core, not ejectable: the metadata you write with it is already yours | +| **Vocabulary** | metamodel types and attributes | core or a provider pack, not ejectable: the metadata you write with it is already yours | | **Library** | `library//` with a `library.json`: metadata and requirements (`iam`, `ai`) | `meta eject ` (above) | | **Catalog generator** | a row in `meta gen --list` | import it as shipped, or eject it, except `template` and the package-only rows ([ADR-0034](../../spec/decisions/ADR-0034-codegen-scaffold-and-own.md), Amendment 5). A library may imply one only when it anchors on a library node (above). | | **Runtime helper** | an Apache-2.0 per-port package that generated code imports | copied by the route generator's eject, helper runtime included ([ADR-0034](../../spec/decisions/ADR-0034-codegen-scaffold-and-own.md), Amendment 3) | @@ -175,8 +175,8 @@ Anything else stays with the adopter (policy, presentation, branding, scheduling separate project. **Worked example, reporting** ([reporting.md](reporting.md)). The vocabulary (dimensions, -measures, segments, `object.report`) is the `metaobjects-reporting` provider pack, in the default -bundle ([extending-with-providers.md](extending-with-providers.md)). The planned `reporting` library holds +measures, segments, `object.report`) is a provider pack, composed by default +([Where vocabulary lives](extending-with-providers.md#where-vocabulary-lives)). The planned `reporting` library holds metadata only, so opting in adds no code. Exporting to another tool and dashboards are catalog generators, one per heavy format, so an adopter never takes a dependency they did not wire: `cube-model` ships today, a dashboard generator does not exist yet. diff --git a/docs/features/reporting.md b/docs/features/reporting.md index 4501205705..cb14321e1c 100644 --- a/docs/features/reporting.md +++ b/docs/features/reporting.md @@ -48,8 +48,9 @@ mean what they appear to mean: a measure of one table in a report over another, ## What is registered -They are registered by the `metaobjects-reporting` provider pack, which the default bundle -composes; an embedder can leave it out ([extending-with-providers.md](extending-with-providers.md)). +They are a provider pack, composed by default and removable by an embedder; the pack's +identity and what leaving it out does are in +[Where vocabulary lives](extending-with-providers.md#where-vocabulary-lives). Exactly these names, and nothing else: diff --git a/docs/features/requirements.md b/docs/features/requirements.md index 646cc09d5b..2722832195 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -5,10 +5,9 @@ supposed to do, as metadata, checked by `verify` in every port._ **Status:** registered vocabulary in all five ports (TypeScript, Java, C#, Python, Kotlin). The requirement gate runs in every port's `verify`, and every port ships a -`requirement-tests` generator. The authoring lint is TypeScript-only. The vocabulary is the -`metaobjects-requirements` provider pack, in the default bundle. With the pack left out, a -`requirement.*` node is a loader error, and a model with none gets a silent, empty ledger -([extending-with-providers.md](extending-with-providers.md)). +`requirement-tests` generator. The authoring lint is TypeScript-only. The vocabulary is a +provider pack, composed by default; what leaving it out does is in +[Where vocabulary lives](extending-with-providers.md#where-vocabulary-lives). **Entirely opt-in.** A model with no `requirement.*` nodes gets no diagnostics, generates nothing, and reads nothing — no codegen, migrate or runtime path touches the type. You opt in From 60741f48869c9129d69769ec45df0d3a0f8b81dc Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 12:54:46 -0500 Subject: [PATCH 08/23] feat: move reporting and requirements into their own provider packs; raise on missing template variables; refuse permission-name collisions - Reporting (object.report, dimension.*, measure.* incl. measure.derived/@expr, segment.filter, the entity's dimension/measure/segment children and @segment on origin.aggregate/origin.first) is registered by metaobjects-reporting; requirements (requirement.* and the root's requirement child) by metaobjects-requirements. Both are in the default bundle of every port (TS, C#, Java/Kotlin, Python, Rust), so existing models load and generate identically. A model that uses a left-out pack's vocabulary gets a loader error (new error-packs-left-out-*-used fixtures). The verify requirements gate reads through the pack. - A pack subtype declared with extendsBase may fold a base another provider registered (object.report folds object.base); folded attributes keep the base's owner under ADR-0062. - Core vocabulary pin, registry manifest (root requirement child gains min 0 / max null), metamodel docs, site reference and payload regenerated. - GOVERNANCE.md: an attribute promoted from a pack into core keeps its name and meaning. - B4: Mustache and Jinja raise ERR_VAR_NOT_ON_PAYLOAD for a variable or dotted path absent from the payload, in every port that renders; render runners learn expected-error.txt. - B5: rules rule P3 refuses two permission points whose names resolve equal when at least one name is derived (ERR_TRANSITION_NAME_COLLISION), in every port. - C3: Python checks @union shape and @grain views at load; both must-fail fixtures leave its expected-failures ledger. --- AGENTS.md | 2 +- CHANGELOG.md | 32 +++ GOVERNANCE.md | 3 + docs/CONFORMANCE.md | 37 +-- docs/features/business-rules.md | 1 + docs/features/extending-with-providers.md | 22 +- examples/showcase/site-payload.json | 4 +- .../entity-derived-filter-gate/providers.json | 2 +- .../entity-derived-league-gate/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../error-measure-of-foreign/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../error-measure-over-object/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../expected-errors.json | 15 ++ .../input/meta.shop.json | 54 ++++ .../providers.json | 1 + .../expected-errors.json | 25 ++ .../input/meta.shop.json | 71 +++++ .../providers.json | 1 + .../expected-errors.json | 15 ++ .../input/meta.shop.json | 59 ++++ .../providers.json | 1 + .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../error-report-abstract/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../error-report-spine-to-many/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../expected-errors.json | 15 ++ .../input/meta.orders.json | 67 +++++ .../providers.json | 1 + .../expected-errors.json | 15 ++ .../input/meta.orders.json | 66 +++++ .../providers.json | 1 + .../expected-errors.json | 15 ++ .../input/meta.orders.api.json | 20 ++ .../input/meta.orders.json | 53 ++++ .../providers.json | 1 + .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../origin-filter-relative-now/providers.json | 2 +- .../providers.json | 2 +- .../origin-segment-scoped/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../reporting-boolean-measures/providers.json | 2 +- .../providers.json | 2 +- .../reporting-derived-measures/providers.json | 2 +- .../providers.json | 2 +- .../providers.json | 2 +- .../reporting-relative-startof/providers.json | 2 +- .../providers.json | 2 +- .../reporting-spine-inherited/providers.json | 2 +- .../providers.json | 2 +- .../reporting-vocabulary/providers.json | 2 +- .../providers.json | 2 +- .../expected-error.txt | 1 + .../meta.json | 1 + .../payload.json | 1 + .../template.jinja | 1 + .../jinja-render-variables/expected.txt | 2 +- .../jinja-render-variables/meta.json | 2 +- .../jinja-render-variables/template.jinja | 2 +- fixtures/metamodel-docs/expected/providers.md | 36 ++- .../expected/types/dimension.md | 14 +- .../metamodel-docs/expected/types/measure.md | 26 +- .../metamodel-docs/expected/types/object.md | 16 +- .../metamodel-docs/expected/types/origin.md | 4 +- .../expected/types/requirement.md | 36 +-- .../metamodel-docs/expected/types/segment.md | 4 +- .../core-vocabulary.pin.json | 93 ------- .../expected-registry.json | 4 +- fixtures/registry-conformance/providers.json | 14 + .../render-dotted-path-lookup/expected.txt | 2 - .../render-dotted-path-lookup/meta.json | 2 +- .../template.mustache | 2 - .../expected-error.txt | 1 + .../meta.json | 1 + .../payload.json | 12 + .../template.mustache | 1 + .../expected-error.txt | 1 + .../render-error-missing-variable/meta.json | 1 + .../payload.json | 1 + .../template.mustache | 1 + scripts/check-core-vocabulary-pin.ts | 3 +- .../ConformanceAdapter.cs | 2 + .../CoreTypesTests.cs | 2 +- .../FixtureDiscovery.cs | 2 + .../FullCoreRegistry.cs | 2 + .../RegistryManifestConformanceTests.cs | 4 + .../RequirementsPackLeftOutTests.cs | 78 ++++++ .../YamlConformanceTests.cs | 2 + .../RenderConformanceTests.cs | 19 +- .../MetaObjects.Render/PayloadAccessors.cs | 28 ++ server/csharp/MetaObjects.Render/Renderer.cs | 86 +++++- .../Reporting/ReportingMetaDataProvider.cs | 66 +++++ .../Core/Reporting/ReportingSchema.cs | 4 +- .../RequirementsMetaDataProvider.cs | 56 ++++ server/csharp/MetaObjects/CoreTypes.cs | 94 +------ .../Loader/ValidationPasses.Rules.cs | 51 ++++ .../Persistence/Origin/OriginSchema.cs | 12 - server/csharp/MetaObjects/Registry.cs | 19 ++ .../MetaObjects/SpecMetamodel/object.json | 19 -- .../MetaObjects/SpecMetamodel/origin.json | 4 +- .../MetaObjects/SpecMetamodel/reporting.json | 31 ++- .../SpecMetamodel/requirement.json | 7 +- .../main/java/com/metaobjects/MetaData.java | 8 +- .../main/java/com/metaobjects/MetaRoot.java | 1 - .../metaobjects/loader/RulesValidation.java | 57 ++++ .../com/metaobjects/object/MetaObject.java | 23 +- .../metaobjects/object/ReportMetaObject.java | 30 +++ .../metaobjects/origin/AggregateOrigin.java | 3 +- .../com/metaobjects/origin/FirstOrigin.java | 3 +- .../ReportingTypesMetaDataProvider.java | 15 +- .../RequirementTypesMetaDataProvider.java | 9 + .../conformance/ConformanceTest.java | 57 ++-- .../RequirementsPackLeftOutTest.java | 78 ++++++ .../java/com/metaobjects/render/Renderer.java | 59 ++++ .../render/RenderCrossPortReportTest.java | 19 ++ .../render/RenderSnapshotTest.java | 3 + .../render/TypedPayloadRenderTest.java | 11 +- .../snapshots/render-dotted-path-lookup.txt | 2 - server/python/src/metaobjects/core_types.py | 255 +----------------- .../src/metaobjects/loader/validate_rules.py | 69 ++++- .../metaobjects/loader/validation_passes.py | 115 ++++++++ .../meta/core/reporting/reporting_provider.py | 223 +++++++++++++++ .../core/requirement/requirements_provider.py | 145 ++++++++++ server/python/src/metaobjects/registry.py | 21 +- .../src/metaobjects/render/jinja_render.py | 12 +- .../python/src/metaobjects/render/renderer.py | 33 ++- .../metaobjects/spec_metamodel/object.json | 19 -- .../metaobjects/spec_metamodel/origin.json | 4 +- .../metaobjects/spec_metamodel/reporting.json | 31 ++- .../spec_metamodel/requirement.json | 7 +- .../conformance-expected-failures.json | 4 - .../tests/conformance/conformance_adapter.py | 5 + .../tests/conformance/fixture_discovery.py | 5 +- .../python/tests/render/test_jinja_engine.py | 6 +- .../tests/render/test_render_conformance.py | 25 +- .../tests/test_requirements_pack_left_out.py | 65 +++++ .../metaobjects/data/metamodel/object.json | 19 -- .../metaobjects/data/metamodel/origin.json | 4 +- .../metaobjects/data/metamodel/reporting.json | 31 ++- .../data/metamodel/requirement.json | 7 +- server/rust/metaobjects/src/providers.rs | 62 ++++- server/rust/metaobjects/src/registry.rs | 37 ++- server/rust/metaobjects/src/validate/rules.rs | 85 ++++++ .../tests/conformance-expected-failures.json | 2 +- .../tests/metamodel_conformance.rs | 2 + .../test/requirements-pack-left-out.test.ts | 67 +++++ .../packages/conformance/src/fixture.ts | 7 +- .../typescript/packages/docs-site/src/load.ts | 2 +- .../packages/metadata/src/core-types.ts | 83 +----- .../core/object/object-definition.embedded.ts | 88 ------ .../reporting-definition.embedded.ts | 126 ++++++++- .../src/core/reporting/reporting-provider.ts | 47 ++++ .../requirement-definition.embedded.ts | 17 +- .../core/requirement/requirements-provider.ts | 44 +++ .../typescript/packages/metadata/src/index.ts | 9 + .../metadata/src/loader/rules-validation.ts | 56 +++- .../metamodel-docs/provider-definitions.ts | 7 +- .../origin/origin-definition.embedded.ts | 16 -- .../packages/metadata/src/provider-data.ts | 29 +- .../packages/metadata/src/registry.ts | 23 +- .../metadata/test/conformance/adapter.ts | 4 + .../packages/metadata/test/index.test.ts | 2 + .../origin-definition-completeness.test.ts | 8 +- .../metadata/test/provider-vocabulary.test.ts | 11 +- .../packages/metadata/test/provider.test.ts | 22 +- .../packages/metadata/test/registry.test.ts | 15 +- .../packages/render/src/jinja/nunjucks.ts | 20 +- .../typescript/packages/render/src/render.ts | 30 ++- .../render/test/render-conformance.test.ts | 10 +- .../packages/render/test/render.test.ts | 17 ++ site-reference/providers.html | 30 ++- site-reference/types/dimension.html | 12 +- site-reference/types/measure.html | 23 +- site-reference/types/object.html | 16 +- site-reference/types/origin.html | 4 +- site-reference/types/requirement.html | 34 +-- site-reference/types/segment.html | 3 +- spec/metamodel/object.json | 19 -- spec/metamodel/origin.json | 4 +- spec/metamodel/reporting.json | 31 ++- spec/metamodel/requirement.json | 7 +- 249 files changed, 3193 insertions(+), 1079 deletions(-) create mode 100644 fixtures/conformance/error-packs-left-out-measure-used/expected-errors.json create mode 100644 fixtures/conformance/error-packs-left-out-measure-used/input/meta.shop.json create mode 100644 fixtures/conformance/error-packs-left-out-measure-used/providers.json create mode 100644 fixtures/conformance/error-packs-left-out-report-used/expected-errors.json create mode 100644 fixtures/conformance/error-packs-left-out-report-used/input/meta.shop.json create mode 100644 fixtures/conformance/error-packs-left-out-report-used/providers.json create mode 100644 fixtures/conformance/error-packs-left-out-requirement-used/expected-errors.json create mode 100644 fixtures/conformance/error-packs-left-out-requirement-used/input/meta.shop.json create mode 100644 fixtures/conformance/error-packs-left-out-requirement-used/providers.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-declared/expected-errors.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-declared/input/meta.orders.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-declared/providers.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-dotted/expected-errors.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-dotted/input/meta.orders.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-dotted/providers.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json create mode 100644 fixtures/conformance/error-rules-permission-name-op-package/providers.json create mode 100644 fixtures/jinja-render-conformance/jinja-render-error-missing-variable/expected-error.txt create mode 100644 fixtures/jinja-render-conformance/jinja-render-error-missing-variable/meta.json create mode 100644 fixtures/jinja-render-conformance/jinja-render-error-missing-variable/payload.json create mode 100644 fixtures/jinja-render-conformance/jinja-render-error-missing-variable/template.jinja create mode 100644 fixtures/render-conformance/render-error-missing-dotted-path/expected-error.txt create mode 100644 fixtures/render-conformance/render-error-missing-dotted-path/meta.json create mode 100644 fixtures/render-conformance/render-error-missing-dotted-path/payload.json create mode 100644 fixtures/render-conformance/render-error-missing-dotted-path/template.mustache create mode 100644 fixtures/render-conformance/render-error-missing-variable/expected-error.txt create mode 100644 fixtures/render-conformance/render-error-missing-variable/meta.json create mode 100644 fixtures/render-conformance/render-error-missing-variable/payload.json create mode 100644 fixtures/render-conformance/render-error-missing-variable/template.mustache create mode 100644 server/csharp/MetaObjects.Conformance.Tests/RequirementsPackLeftOutTests.cs create mode 100644 server/csharp/MetaObjects/Core/Reporting/ReportingMetaDataProvider.cs create mode 100644 server/csharp/MetaObjects/Core/Requirement/RequirementsMetaDataProvider.cs create mode 100644 server/java/metadata/src/test/java/com/metaobjects/requirement/RequirementsPackLeftOutTest.java create mode 100644 server/python/src/metaobjects/meta/core/reporting/reporting_provider.py create mode 100644 server/python/src/metaobjects/meta/core/requirement/requirements_provider.py create mode 100644 server/python/tests/test_requirements_pack_left_out.py create mode 100644 server/typescript/packages/cli/test/requirements-pack-left-out.test.ts create mode 100644 server/typescript/packages/metadata/src/core/reporting/reporting-provider.ts create mode 100644 server/typescript/packages/metadata/src/core/requirement/requirements-provider.ts diff --git a/AGENTS.md b/AGENTS.md index beb954aed3..b818c72d79 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/` (578 fixtures; 45 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/` (584 fixtures; 45 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 534327d4c4..e3a7f53bab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -134,6 +134,38 @@ here.** included every filterable text field, and an int-backed (`@intValueMap`) enum is an integer column, so Postgres refused the ILIKE. Search now covers only fields whose operator band includes `like`. +- **Reporting and requirements are vocabulary packs, out of core.** The reporting vocabulary + (`object.report`, `dimension.*`, `measure.*` including `measure.derived` and its `@expr`, + `segment.filter`, the entity's dimension, measure and segment children and `@segment` on + `origin.aggregate` and `origin.first`) is now registered by its own provider, + `metaobjects-reporting`. The requirements vocabulary (`requirement.functional`, + `requirement.architectural` and the root's `requirement.*` child) is registered by + `metaobjects-requirements`. Both are in the default bundle of every port, so a model that loads + today loads and generates the same. An embedder can leave either out, and a model that then uses + its types gets a loader error naming the unknown type or subtype (new fixtures + `error-packs-left-out-*-used`). The `verify` requirements gate reads the nodes the pack + registered: with the pack left out, a model with no requirements gets a silent ledger. The core + vocabulary pin loses these types and attributes, and the registry manifest changes in one row: + the root's `requirement` child rule now states `min: 0, max: null`, as `api` did when the rules + pack moved out. A subtype a pack declares with `extendsBase` may now fold a base another provider + registered (`object.report` folds `object.base`); those folded attributes stay owned by the base's + provider. GOVERNANCE.md now says an attribute promoted from a pack into core keeps its name and + meaning. +- **A template that names a variable the payload lacks fails to render, in every render path.** + Mustache and Jinja raise `render verify failed: ERR_VAR_NOT_ON_PAYLOAD ()` for a missing + variable or dotted path, where they used to render it empty. A variable that is present and null + still renders empty. Render fixtures may now carry `expected-error.txt` in place of + `expected.txt`. +- **Business rules: two operations or transitions whose permission names come out equal are + refused (rule P3).** A permission name is the declared `@permission`, or else the derived + `.` (a `::` package separator reads as `.`). When two permission points resolve to + the same name and at least one of the two names is derived, the loader reports + `ERR_TRANSITION_NAME_COLLISION` on the later one. Two equal declared names stay legal: that is a + shared permission. New fixtures `error-rules-permission-name-op-{dotted,declared,package}`. +- **Python: unions and one-row-per-list-item views are checked at load.** The two must-fail + projection fixtures (a `@union` whose branches do not line up, and a `@grain` view that breaks + its rules) now fail in Python as they do in the other ports, and leave the Python + expected-failures ledger. - **C#: a `@sequenceStart` whose migrations project lacks the design-time services line is a generation error.** When `dotnet meta gen` can see the context's `ModelSnapshot.cs` in another project and that project does not carry `[assembly: DesignTimeServicesReference]`, the next `dotnet ef migrations add` diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 460baf537d..79baa84b82 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -113,6 +113,9 @@ MetaObjects, in the way the [`library/`](library/) entries do (see what belongs in the project at all is set out in "What belongs in MetaObjects" in [docs/features/libraries.md](docs/features/libraries.md). Moving vocabulary into core is a model-format change, so it needs a core maintainer (above). +- **An attribute promoted from a pack into core keeps its name and meaning.** Promotion moves + which provider registers the attribute. It does not rename it or change what it does, so a + model that used the attribute under the pack loads and behaves the same once core owns it. ### Releases diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 7d8211268b..72a05dd3da 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,12 +26,12 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 578 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 584 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | -| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 21 | ✓ | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/jinja-render-conformance/`](../fixtures/jinja-render-conformance/) (ADR-0061 — Jinja bodies render the same in jinja2 and nunjucks) | 15 | ✓ (nunjucks) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | refuses, via Java | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | ✓ (jinja2) | +| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 23 | ✓ | ✓ | inherits via Java | ✓ | ✓ | +| [`fixtures/jinja-render-conformance/`](../fixtures/jinja-render-conformance/) (ADR-0061 — Jinja bodies render the same in jinja2 and nunjucks) | 16 | ✓ (nunjucks) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | refuses, via Java | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | ✓ (jinja2) | | [`fixtures/jinja-verify-conformance/`](../fixtures/jinja-verify-conformance/) (ADR-0061 — the payload check over a Jinja body) | 31 | ✓ | refuses Jinja | refuses, via Java | refuses Jinja | ✓ | | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | | [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | @@ -73,7 +73,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`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 (ADR-0065) is not a column yet.** The sixth port runs these corpora -today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 578 +today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 584 green, with every validation pass the TypeScript loader runs, in the same order, so `server/rust/metaobjects/tests/conformance-expected-failures.json` is empty; `rules-check-conformance` (all 16 cases, the `verify` business-rules gate); @@ -94,7 +94,7 @@ generator, and a scale gate over twenty copies of the fitness model. The ledgers only shrink; the corpora without one assert each case outright. A new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard failure when ADR-0065 turns the warning off. A regression -still fails: the ledger's `minPassing` (578) is the number of fixtures known to pass, and the +still fails: the ledger's `minPassing` (584) is the number of fixtures known to pass, and the run fails when fewer do. The column joins this table when the port runs the persistence and API-contract corpora. A ✓ means the port runs the corpus green; an explicit `n / m` is used where a port @@ -192,8 +192,11 @@ canonical (`fixtures/registry-conformance/expected-registry.json`). - *Implemented in TypeScript and C#* (`implementedIn: ["typescript", "csharp"]`): the rc.21 view vocabulary — `origin.function` and the `object.projection` attrs `@union`, `@unionAll`, `@grain`, `@grainOrdinal`. The TypeScript view emitter lowers them; the C# loader validates - them (mirroring the TypeScript checks message for message); the other ports load them strictly - and do not act on them yet. + them (mirroring the TypeScript checks message for message). The Java (and so Kotlin) and Python + loaders also validate the `@union` / `@unionAll` / `@grain` / `@grainOrdinal` shape rules (the + `error-projection-union-shape` and `error-projection-grain-not-object-array` fixtures fail in + every port); no port other than TypeScript lowers them to a view, and Python does not yet check + `origin.function`. - *Loads strictly in every port.* Each port registers the `metaobjects-ui-web` provider (`view.textarea @rows`, the `view.image` attrs) and `@object` / `@objectAdapter` on `object.*`, loads all three fixtures strictly, and emits `implementedIn` in its manifest, which @@ -430,7 +433,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (578) +### `fixtures/conformance/` — metamodel loader + canonical serializer (584) | Fixture prefix | Feature doc | |---|---| @@ -469,24 +472,26 @@ on a reporting measure, etc.) and 7 `error-yaml-*` fixtures that pin the YAML 1.1 coercion guards (bool / null / hex in string contexts; numeric in enum contexts; reserved-as-attr). -### `fixtures/render-conformance/` (21) +### `fixtures/render-conformance/` (23) -All 21 fixtures → [features/templates-and-payloads.md](features/templates-and-payloads.md) +All 23 fixtures → [features/templates-and-payloads.md](features/templates-and-payloads.md) (render engine output section). 5 are end-to-end shape and escape examples (prompt / email / spreadsheet / CSV-injection escape / CSV numeric-literal exemption); 16 pin Mustache-engine semantics — dotted-path lookup, parent-context fallthrough, falsy/empty-array section behavior, inverted sections, nested partials, a comment tag beside a partial, standalone-tag whitespace stripping (including two standalone tags in a row, a standalone tag at the end of the file and an indented standalone tag, which shared docs templates rely on), raw-HTML bypass, trailing-newline preservation, unicode multibyte handling, the derived -`has` accessor, and the `-last` list-separator accessor. +`has` accessor, and the `-last` list-separator accessor; 2 refuse a variable missing from the +payload, a plain name and a dotted path (`ERR_VAR_NOT_ON_PAYLOAD`, pinned by `expected-error.txt`). -### `fixtures/jinja-render-conformance/` (15) and `fixtures/jinja-verify-conformance/` (31) +### `fixtures/jinja-render-conformance/` (16) and `fixtures/jinja-verify-conformance/` (31) Both → [features/templates-and-payloads.md](features/templates-and-payloads.md) (Jinja templates section, [ADR-0061](../spec/decisions/ADR-0061-per-port-template-engines.md)). Run by Python (jinja2) and TypeScript (nunjucks) only; Java, Kotlin and C# refuse a Jinja body with -`ERR_TEMPLATE_ENGINE_UNSUPPORTED` instead. The render corpus holds 13 output cases and 2 error -cases (an include cycle and an unresolved include), each with the same Mustache-path message. +`ERR_TEMPLATE_ENGINE_UNSUPPORTED` instead. The render corpus holds 13 output cases and 3 error +cases (an include cycle, an unresolved include and a variable missing from the payload), each +with the same Mustache-path message. The verify corpus reuses `verify-conformance/`'s `payload.json` field-tree shape; an `ERR_TEMPLATE_SYNTAX` finding's path is the parser's own message, so runners compare it as empty. @@ -859,8 +864,8 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 578 + yaml 19 + verify 45 -+ render 21 + persistence 67 + api-contract 161 + source-resolution 28 + scope 10 + +The fixtures in the nine corpora mapped above (metamodel 584 + yaml 19 + verify 45 ++ render 23 + persistence 67 + api-contract 161 + source-resolution 28 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the `cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining corpora in the totals table gate tooling contracts (registry manifests, provider diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index fc86d1cc4d..c5f7ef7395 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -186,6 +186,7 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa | 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. | +| P3 | `ERR_TRANSITION_NAME_COLLISION` | Two permission points ask about one permission name and at least one name is derived: an operation named `Order.open`, one declaring `permission: p.Order.open`, or one in package `p::Order`, beside the `open` transition of `Order` in `p`. `::` and `.` compare equal. Two declared `permission` values may be equal. | | B1 | `ERR_BINDING_PATH_MISMATCH` | A `binding.rest` `path` has the wrong placeholders. | | B2 | `ERR_BINDING_PATH_MISMATCH` | Two declared bindings of one API have the same method (declared or derived) and the same path, ignoring placeholder names. | diff --git a/docs/features/extending-with-providers.md b/docs/features/extending-with-providers.md index 0445417247..880b611234 100644 --- a/docs/features/extending-with-providers.md +++ b/docs/features/extending-with-providers.md @@ -121,17 +121,19 @@ lives in an extension pack. This page does not restate it. Which mechanism to us vocabulary is [ADR-0037](../../spec/decisions/ADR-0037-metamodel-vocabulary-expansion-decision-framework.md). **Current state.** Business rules (`api`, `operation`, `binding`, `transition`, provider -`metaobjects-rules`) and the view expressions that arrived in 1.3.0 (`origin.function`, `@union`, -`@unionAll`, `@grain`, `@grainOrdinal`, provider `metaobjects-view-expressions`) are packs: each -is its own provider, in the default bundle of every port that carries it, and an embedder can -leave it out. A model that uses a left-out pack's types gets a loader error naming the unknown -type, subtype or attribute. Reporting (`dimension`, `measure`, `segment`, `object.report`) and -requirements (`requirement.*`) are still registered by `metaobjects-core-types`: they are woven -into `object.json` and read by the `verify` gate in every port, so they were not a small -mechanical move. They are the next candidates for a pack, and they are where they landed, not -where they belong. No new vocabulary should follow their example: a gate +`metaobjects-rules`), the view expressions that arrived in 1.3.0 (`origin.function`, `@union`, +`@unionAll`, `@grain`, `@grainOrdinal`, provider `metaobjects-view-expressions`), reporting +(`object.report`, `dimension.*`, `measure.*`, `segment.filter` and `@segment` on +`origin.aggregate` and `origin.first`, provider `metaobjects-reporting`) and requirements +(`requirement.*`, provider `metaobjects-requirements`) are packs: each is its own provider, in +the default bundle of every port, and an embedder can leave it out. A model that uses a left-out +pack's types gets a loader error naming the unknown type, subtype or attribute. The `verify` +requirements gate reads the requirement nodes the pack registered, so with that pack left out it +has nothing to report. `object.report` shows the one thing a pack subtype may borrow from core: +declared with `extendsBase`, it folds in `object.base`, which core registers, and those folded +attributes stay owned by core. New vocabulary follows the same path: a gate (`scripts/check-core-vocabulary-pin.ts`) pins the core provider's types and attributes, so adding -one fails with a pointer to GOVERNANCE.md and this mechanism. +one to core fails with a pointer to GOVERNANCE.md and this mechanism. You opt a concern in by **declaring**, not by configuring, and a concern your model does not declare costs nothing, generates nothing and diagnoses nothing: diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index ad7b2811ca..94f9d8136f 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,8 +7,8 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 578, - "corpora": 45, + "fixtures": 584, + "corpora": 43, "baseTypes": 21 }, "snippets": { diff --git a/fixtures/conformance/entity-derived-filter-gate/providers.json b/fixtures/conformance/entity-derived-filter-gate/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/entity-derived-filter-gate/providers.json +++ b/fixtures/conformance/entity-derived-filter-gate/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/entity-derived-league-gate/providers.json b/fixtures/conformance/entity-derived-league-gate/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/entity-derived-league-gate/providers.json +++ b/fixtures/conformance/entity-derived-league-gate/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-grain-on-date/providers.json b/fixtures/conformance/error-dimension-grain-on-date/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-grain-on-date/providers.json +++ b/fixtures/conformance/error-dimension-grain-on-date/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-of-jsonb-member/providers.json b/fixtures/conformance/error-dimension-of-jsonb-member/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-of-jsonb-member/providers.json +++ b/fixtures/conformance/error-dimension-of-jsonb-member/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-of-unresolved/providers.json b/fixtures/conformance/error-dimension-of-unresolved/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-of-unresolved/providers.json +++ b/fixtures/conformance/error-dimension-of-unresolved/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-over-object/providers.json b/fixtures/conformance/error-dimension-over-object/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-over-object/providers.json +++ b/fixtures/conformance/error-dimension-over-object/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-time-not-temporal/providers.json b/fixtures/conformance/error-dimension-time-not-temporal/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-time-not-temporal/providers.json +++ b/fixtures/conformance/error-dimension-time-not-temporal/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-via-base-lacks-field/providers.json b/fixtures/conformance/error-dimension-via-base-lacks-field/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-via-base-lacks-field/providers.json +++ b/fixtures/conformance/error-dimension-via-base-lacks-field/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-dimension-via-to-many/providers.json b/fixtures/conformance/error-dimension-via-to-many/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-dimension-via-to-many/providers.json +++ b/fixtures/conformance/error-dimension-via-to-many/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-all-default-not-boolean/providers.json b/fixtures/conformance/error-measure-all-default-not-boolean/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-measure-all-default-not-boolean/providers.json +++ b/fixtures/conformance/error-measure-all-default-not-boolean/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-any-non-boolean/providers.json b/fixtures/conformance/error-measure-any-non-boolean/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-measure-any-non-boolean/providers.json +++ b/fixtures/conformance/error-measure-any-non-boolean/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-any-without-condition/providers.json b/fixtures/conformance/error-measure-any-without-condition/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-measure-any-without-condition/providers.json +++ b/fixtures/conformance/error-measure-any-without-condition/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-default-non-numeric/providers.json b/fixtures/conformance/error-measure-default-non-numeric/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-default-non-numeric/providers.json +++ b/fixtures/conformance/error-measure-default-non-numeric/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-default-not-integer/providers.json b/fixtures/conformance/error-measure-default-not-integer/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-default-not-integer/providers.json +++ b/fixtures/conformance/error-measure-default-not-integer/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-default-on-count-integral-float/providers.json b/fixtures/conformance/error-measure-default-on-count-integral-float/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-default-on-count-integral-float/providers.json +++ b/fixtures/conformance/error-measure-default-on-count-integral-float/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-default-on-count-non-numeric/providers.json b/fixtures/conformance/error-measure-default-on-count-non-numeric/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-default-on-count-non-numeric/providers.json +++ b/fixtures/conformance/error-measure-default-on-count-non-numeric/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-default-on-count/providers.json b/fixtures/conformance/error-measure-default-on-count/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-default-on-count/providers.json +++ b/fixtures/conformance/error-measure-default-on-count/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json b/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json +++ b/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-default/providers.json b/fixtures/conformance/error-measure-derived-default/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-default/providers.json +++ b/fixtures/conformance/error-measure-derived-default/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-malformed-expr/providers.json b/fixtures/conformance/error-measure-derived-malformed-expr/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-malformed-expr/providers.json +++ b/fixtures/conformance/error-measure-derived-malformed-expr/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json b/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json +++ b/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json b/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json +++ b/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-of-derived/providers.json b/fixtures/conformance/error-measure-derived-of-derived/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-of-derived/providers.json +++ b/fixtures/conformance/error-measure-derived-of-derived/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-time-dimension/providers.json b/fixtures/conformance/error-measure-derived-time-dimension/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-time-dimension/providers.json +++ b/fixtures/conformance/error-measure-derived-time-dimension/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-derived-unknown-operand/providers.json b/fixtures/conformance/error-measure-derived-unknown-operand/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-derived-unknown-operand/providers.json +++ b/fixtures/conformance/error-measure-derived-unknown-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-distinct-not-count/providers.json b/fixtures/conformance/error-measure-distinct-not-count/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-distinct-not-count/providers.json +++ b/fixtures/conformance/error-measure-distinct-not-count/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-of-foreign/providers.json b/fixtures/conformance/error-measure-of-foreign/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-of-foreign/providers.json +++ b/fixtures/conformance/error-measure-of-foreign/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-of-jsonb-member/providers.json b/fixtures/conformance/error-measure-of-jsonb-member/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-of-jsonb-member/providers.json +++ b/fixtures/conformance/error-measure-of-jsonb-member/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-of-member-of-scalar/providers.json b/fixtures/conformance/error-measure-of-member-of-scalar/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-of-member-of-scalar/providers.json +++ b/fixtures/conformance/error-measure-of-member-of-scalar/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-of-path-too-deep/providers.json b/fixtures/conformance/error-measure-of-path-too-deep/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-of-path-too-deep/providers.json +++ b/fixtures/conformance/error-measure-of-path-too-deep/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-of-unknown-member/providers.json b/fixtures/conformance/error-measure-of-unknown-member/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-of-unknown-member/providers.json +++ b/fixtures/conformance/error-measure-of-unknown-member/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-over-object/providers.json b/fixtures/conformance/error-measure-over-object/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-over-object/providers.json +++ b/fixtures/conformance/error-measure-over-object/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-segment-unresolved/providers.json b/fixtures/conformance/error-measure-segment-unresolved/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-segment-unresolved/providers.json +++ b/fixtures/conformance/error-measure-segment-unresolved/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-sum-non-numeric/providers.json b/fixtures/conformance/error-measure-sum-non-numeric/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-sum-non-numeric/providers.json +++ b/fixtures/conformance/error-measure-sum-non-numeric/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-sum-without-of/providers.json b/fixtures/conformance/error-measure-sum-without-of/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-measure-sum-without-of/providers.json +++ b/fixtures/conformance/error-measure-sum-without-of/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-measure-tuple-without-distinct/providers.json b/fixtures/conformance/error-measure-tuple-without-distinct/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-measure-tuple-without-distinct/providers.json +++ b/fixtures/conformance/error-measure-tuple-without-distinct/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-origin-correlated-operand-unknown/providers.json b/fixtures/conformance/error-origin-correlated-operand-unknown/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-origin-correlated-operand-unknown/providers.json +++ b/fixtures/conformance/error-origin-correlated-operand-unknown/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-origin-segment-flattened-of/providers.json b/fixtures/conformance/error-origin-segment-flattened-of/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-origin-segment-flattened-of/providers.json +++ b/fixtures/conformance/error-origin-segment-flattened-of/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-origin-segment-unresolved/providers.json b/fixtures/conformance/error-origin-segment-unresolved/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-origin-segment-unresolved/providers.json +++ b/fixtures/conformance/error-origin-segment-unresolved/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-packs-left-out-measure-used/expected-errors.json b/fixtures/conformance/error-packs-left-out-measure-used/expected-errors.json new file mode 100644 index 0000000000..48db587551 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-measure-used/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_TYPE", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['measure.aggregate']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-packs-left-out-measure-used/input/meta.shop.json b/fixtures/conformance/error-packs-left-out-measure-used/input/meta.shop.json new file mode 100644 index 0000000000..c2dd11647f --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-measure-used/input/meta.shop.json @@ -0,0 +1,54 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "customerId" + } + }, + { + "field.currency": { + "name": "totalCents" + } + }, + { + "field.string": { + "name": "status" + } + }, + { + "measure.aggregate": { + "name": "revenue", + "@agg": "sum", + "@of": "Order.totalCents" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-packs-left-out-measure-used/providers.json b/fixtures/conformance/error-packs-left-out-measure-used/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-measure-used/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/error-packs-left-out-report-used/expected-errors.json b/fixtures/conformance/error-packs-left-out-report-used/expected-errors.json new file mode 100644 index 0000000000..692a18d294 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-report-used/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_TYPE", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[4]['measure.aggregate']" + } + }, + { + "code": "ERR_UNKNOWN_SUBTYPE", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.report']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-packs-left-out-report-used/input/meta.shop.json b/fixtures/conformance/error-packs-left-out-report-used/input/meta.shop.json new file mode 100644 index 0000000000..ef2cfebaa8 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-report-used/input/meta.shop.json @@ -0,0 +1,71 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "customerId" + } + }, + { + "field.currency": { + "name": "totalCents" + } + }, + { + "measure.aggregate": { + "name": "revenue", + "@agg": "sum", + "@of": "Order.totalCents" + } + }, + { + "field.string": { + "name": "status" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.report": { + "name": "OrderTotals", + "@from": "Order", + "@measures": [ + "revenue" + ], + "children": [ + { + "source.rdb": { + "@table": "order_totals", + "@kind": "view" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-packs-left-out-report-used/providers.json b/fixtures/conformance/error-packs-left-out-report-used/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-report-used/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/error-packs-left-out-requirement-used/expected-errors.json b/fixtures/conformance/error-packs-left-out-requirement-used/expected-errors.json new file mode 100644 index 0000000000..f87267ffcb --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-requirement-used/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_TYPE", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[1]['requirement.functional']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-packs-left-out-requirement-used/input/meta.shop.json b/fixtures/conformance/error-packs-left-out-requirement-used/input/meta.shop.json new file mode 100644 index 0000000000..16fd670e6e --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-requirement-used/input/meta.shop.json @@ -0,0 +1,59 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "customerId" + } + }, + { + "field.currency": { + "name": "totalCents" + } + }, + { + "field.string": { + "name": "status" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "requirement.functional": { + "name": "PlaceOrder", + "@level": 4, + "@status": "live", + "@statement": "A customer places an order", + "@counterexample": "A customer cannot place an order", + "@implementedBy": [ + "acme::shop::Order" + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-packs-left-out-requirement-used/providers.json b/fixtures/conformance/error-packs-left-out-requirement-used/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-packs-left-out-requirement-used/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/error-ratio-boolean-operand/providers.json b/fixtures/conformance/error-ratio-boolean-operand/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-ratio-boolean-operand/providers.json +++ b/fixtures/conformance/error-ratio-boolean-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-ratio-non-numeric-operand/providers.json b/fixtures/conformance/error-ratio-non-numeric-operand/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/error-ratio-non-numeric-operand/providers.json +++ b/fixtures/conformance/error-ratio-non-numeric-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/error-ratio-operand-not-aggregate/providers.json b/fixtures/conformance/error-ratio-operand-not-aggregate/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-ratio-operand-not-aggregate/providers.json +++ b/fixtures/conformance/error-ratio-operand-not-aggregate/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-relative-date-bad-duration/providers.json b/fixtures/conformance/error-relative-date-bad-duration/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-relative-date-bad-duration/providers.json +++ b/fixtures/conformance/error-relative-date-bad-duration/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-relative-date-bad-startof/providers.json b/fixtures/conformance/error-relative-date-bad-startof/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-relative-date-bad-startof/providers.json +++ b/fixtures/conformance/error-relative-date-bad-startof/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-relative-date-datagrid-host/providers.json b/fixtures/conformance/error-relative-date-datagrid-host/providers.json index ba0387a547..d0231bfd43 100644 --- a/fixtures/conformance/error-relative-date-datagrid-host/providers.json +++ b/fixtures/conformance/error-relative-date-datagrid-host/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db","metaobjects-ui"] +["metaobjects-core-types","metaobjects-db","metaobjects-ui","metaobjects-reporting"] diff --git a/fixtures/conformance/error-relative-date-extra-key/providers.json b/fixtures/conformance/error-relative-date-extra-key/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-relative-date-extra-key/providers.json +++ b/fixtures/conformance/error-relative-date-extra-key/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-relative-date-non-temporal/providers.json b/fixtures/conformance/error-relative-date-non-temporal/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-relative-date-non-temporal/providers.json +++ b/fixtures/conformance/error-relative-date-non-temporal/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-abstract/providers.json b/fixtures/conformance/error-report-abstract/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-abstract/providers.json +++ b/fixtures/conformance/error-report-abstract/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-declares-field/providers.json b/fixtures/conformance/error-report-declares-field/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-declares-field/providers.json +++ b/fixtures/conformance/error-report-declares-field/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json b/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json +++ b/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-dimension-grain/providers.json b/fixtures/conformance/error-report-dimension-grain/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-dimension-grain/providers.json +++ b/fixtures/conformance/error-report-dimension-grain/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-field-collision/providers.json b/fixtures/conformance/error-report-field-collision/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-field-collision/providers.json +++ b/fixtures/conformance/error-report-field-collision/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-foreign-measure/providers.json b/fixtures/conformance/error-report-foreign-measure/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-foreign-measure/providers.json +++ b/fixtures/conformance/error-report-foreign-measure/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-from-not-entity/providers.json b/fixtures/conformance/error-report-from-not-entity/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-from-not-entity/providers.json +++ b/fixtures/conformance/error-report-from-not-entity/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-measure-unresolved/providers.json b/fixtures/conformance/error-report-measure-unresolved/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-measure-unresolved/providers.json +++ b/fixtures/conformance/error-report-measure-unresolved/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-segment-unresolved/providers.json b/fixtures/conformance/error-report-segment-unresolved/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-segment-unresolved/providers.json +++ b/fixtures/conformance/error-report-segment-unresolved/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-source-kind-materialized-view/providers.json b/fixtures/conformance/error-report-source-kind-materialized-view/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-source-kind-materialized-view/providers.json +++ b/fixtures/conformance/error-report-source-kind-materialized-view/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-source-kind-stored-proc/providers.json b/fixtures/conformance/error-report-source-kind-stored-proc/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-source-kind-stored-proc/providers.json +++ b/fixtures/conformance/error-report-source-kind-stored-proc/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-source-kind-table-function/providers.json b/fixtures/conformance/error-report-source-kind-table-function/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-source-kind-table-function/providers.json +++ b/fixtures/conformance/error-report-source-kind-table-function/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-spine-dimension-off-spine/providers.json b/fixtures/conformance/error-report-spine-dimension-off-spine/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-spine-dimension-off-spine/providers.json +++ b/fixtures/conformance/error-report-spine-dimension-off-spine/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-spine-dimension-other-path/providers.json b/fixtures/conformance/error-report-spine-dimension-other-path/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-spine-dimension-other-path/providers.json +++ b/fixtures/conformance/error-report-spine-dimension-other-path/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-spine-no-dimensions/providers.json b/fixtures/conformance/error-report-spine-no-dimensions/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-spine-no-dimensions/providers.json +++ b/fixtures/conformance/error-report-spine-no-dimensions/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-spine-not-from/providers.json b/fixtures/conformance/error-report-spine-not-from/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-spine-not-from/providers.json +++ b/fixtures/conformance/error-report-spine-not-from/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-spine-to-many/providers.json b/fixtures/conformance/error-report-spine-to-many/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-spine-to-many/providers.json +++ b/fixtures/conformance/error-report-spine-to-many/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-two-unresolved-dimensions/providers.json b/fixtures/conformance/error-report-two-unresolved-dimensions/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-two-unresolved-dimensions/providers.json +++ b/fixtures/conformance/error-report-two-unresolved-dimensions/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json b/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json +++ b/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json b/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json +++ b/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json b/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json +++ b/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-report-writable-source/providers.json b/fixtures/conformance/error-report-writable-source/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-report-writable-source/providers.json +++ b/fixtures/conformance/error-report-writable-source/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/error-requirement-level-fractional/providers.json b/fixtures/conformance/error-requirement-level-fractional/providers.json index 8ec88fc091..3aea349412 100644 --- a/fixtures/conformance/error-requirement-level-fractional/providers.json +++ b/fixtures/conformance/error-requirement-level-fractional/providers.json @@ -1 +1 @@ -["metaobjects-core-types"] +["metaobjects-core-types", "metaobjects-requirements"] diff --git a/fixtures/conformance/error-requirement-status-abandoned/providers.json b/fixtures/conformance/error-requirement-status-abandoned/providers.json index 8ec88fc091..3aea349412 100644 --- a/fixtures/conformance/error-requirement-status-abandoned/providers.json +++ b/fixtures/conformance/error-requirement-status-abandoned/providers.json @@ -1 +1 @@ -["metaobjects-core-types"] +["metaobjects-core-types", "metaobjects-requirements"] diff --git a/fixtures/conformance/error-requirement-verified-by-retired/providers.json b/fixtures/conformance/error-requirement-verified-by-retired/providers.json index 8ec88fc091..3aea349412 100644 --- a/fixtures/conformance/error-requirement-verified-by-retired/providers.json +++ b/fixtures/conformance/error-requirement-verified-by-retired/providers.json @@ -1 +1 @@ -["metaobjects-core-types"] +["metaobjects-core-types", "metaobjects-requirements"] diff --git a/fixtures/conformance/error-rules-permission-name-op-declared/expected-errors.json b/fixtures/conformance/error-rules-permission-name-op-declared/expected-errors.json new file mode 100644 index 0000000000..9fb242567a --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-declared/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.orders.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.operational'].children[0]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-permission-name-op-declared/input/meta.orders.json b/fixtures/conformance/error-rules-permission-name-op-declared/input/meta.orders.json new file mode 100644 index 0000000000..906380d8c0 --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-declared/input/meta.orders.json @@ -0,0 +1,67 @@ +{ + "metadata.root": { + "package": "p", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.enum": { + "name": "status", + "@values": [ + "draft", + "open" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "open", + "@from": [ + "draft" + ], + "@to": "open" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "Orders", + "children": [ + { + "operation.query": { + "name": "confirm", + "@outputRef": "Order", + "@permission": "p.Order.open" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-name-op-declared/providers.json b/fixtures/conformance/error-rules-permission-name-op-declared/providers.json new file mode 100644 index 0000000000..f14395dbea --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-declared/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db", "metaobjects-rules"] diff --git a/fixtures/conformance/error-rules-permission-name-op-dotted/expected-errors.json b/fixtures/conformance/error-rules-permission-name-op-dotted/expected-errors.json new file mode 100644 index 0000000000..9fb242567a --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-dotted/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.orders.json" + ], + "jsonPath": "$['metadata.root'].children[1]['api.operational'].children[0]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-permission-name-op-dotted/input/meta.orders.json b/fixtures/conformance/error-rules-permission-name-op-dotted/input/meta.orders.json new file mode 100644 index 0000000000..6138b58ebe --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-dotted/input/meta.orders.json @@ -0,0 +1,66 @@ +{ + "metadata.root": { + "package": "p", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.enum": { + "name": "status", + "@values": [ + "draft", + "open" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "open", + "@from": [ + "draft" + ], + "@to": "open" + } + } + ] + } + } + ] + } + }, + { + "api.operational": { + "name": "Orders", + "children": [ + { + "operation.query": { + "name": "Order.open", + "@outputRef": "Order" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-name-op-dotted/providers.json b/fixtures/conformance/error-rules-permission-name-op-dotted/providers.json new file mode 100644 index 0000000000..f14395dbea --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-dotted/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db", "metaobjects-rules"] diff --git a/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json b/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json new file mode 100644 index 0000000000..9728c81073 --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_TRANSITION_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.orders.api.json" + ], + "jsonPath": "$['metadata.root'].children[0]['api.operational'].children[0]['operation.query']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json b/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json new file mode 100644 index 0000000000..e2418050ac --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json @@ -0,0 +1,20 @@ +{ + "metadata.root": { + "package": "p::Order", + "children": [ + { + "api.operational": { + "name": "Orders", + "children": [ + { + "operation.query": { + "name": "open", + "@outputRef": "p::Order" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json b/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json new file mode 100644 index 0000000000..d84c0d39eb --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json @@ -0,0 +1,53 @@ +{ + "metadata.root": { + "package": "p", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.enum": { + "name": "status", + "@values": [ + "draft", + "open" + ], + "@default": "draft", + "children": [ + { + "transition.action": { + "name": "open", + "@from": [ + "draft" + ], + "@to": "open" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-name-op-package/providers.json b/fixtures/conformance/error-rules-permission-name-op-package/providers.json new file mode 100644 index 0000000000..f14395dbea --- /dev/null +++ b/fixtures/conformance/error-rules-permission-name-op-package/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db", "metaobjects-rules"] diff --git a/fixtures/conformance/error-segment-filter-bad-field/providers.json b/fixtures/conformance/error-segment-filter-bad-field/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/error-segment-filter-bad-field/providers.json +++ b/fixtures/conformance/error-segment-filter-bad-field/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/measure-default-integral-float/providers.json b/fixtures/conformance/measure-default-integral-float/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/measure-default-integral-float/providers.json +++ b/fixtures/conformance/measure-default-integral-float/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/object-collection-name-consignments/providers.json b/fixtures/conformance/object-collection-name-consignments/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/object-collection-name-consignments/providers.json +++ b/fixtures/conformance/object-collection-name-consignments/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/origin-correlated-filter-and-segment/providers.json b/fixtures/conformance/origin-correlated-filter-and-segment/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/origin-correlated-filter-and-segment/providers.json +++ b/fixtures/conformance/origin-correlated-filter-and-segment/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/origin-filter-relative-now/providers.json b/fixtures/conformance/origin-filter-relative-now/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/origin-filter-relative-now/providers.json +++ b/fixtures/conformance/origin-filter-relative-now/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/origin-reverse-hop-collection-name/providers.json b/fixtures/conformance/origin-reverse-hop-collection-name/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/origin-reverse-hop-collection-name/providers.json +++ b/fixtures/conformance/origin-reverse-hop-collection-name/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/origin-segment-scoped/providers.json b/fixtures/conformance/origin-segment-scoped/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/origin-segment-scoped/providers.json +++ b/fixtures/conformance/origin-segment-scoped/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/overlay-explicit-package-not-applied-to-target/providers.json b/fixtures/conformance/overlay-explicit-package-not-applied-to-target/providers.json index 8ec88fc091..3aea349412 100644 --- a/fixtures/conformance/overlay-explicit-package-not-applied-to-target/providers.json +++ b/fixtures/conformance/overlay-explicit-package-not-applied-to-target/providers.json @@ -1 +1 @@ -["metaobjects-core-types"] +["metaobjects-core-types", "metaobjects-requirements"] diff --git a/fixtures/conformance/projection-filter-relative-now/providers.json b/fixtures/conformance/projection-filter-relative-now/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/projection-filter-relative-now/providers.json +++ b/fixtures/conformance/projection-filter-relative-now/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/report-dimension-required-by-model/providers.json b/fixtures/conformance/report-dimension-required-by-model/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/report-dimension-required-by-model/providers.json +++ b/fixtures/conformance/report-dimension-required-by-model/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-any-all-predicate/providers.json b/fixtures/conformance/reporting-any-all-predicate/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/reporting-any-all-predicate/providers.json +++ b/fixtures/conformance/reporting-any-all-predicate/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-boolean-measures/providers.json b/fixtures/conformance/reporting-boolean-measures/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/reporting-boolean-measures/providers.json +++ b/fixtures/conformance/reporting-boolean-measures/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-cross-package-short-names/providers.json b/fixtures/conformance/reporting-cross-package-short-names/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/reporting-cross-package-short-names/providers.json +++ b/fixtures/conformance/reporting-cross-package-short-names/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-derived-measures/providers.json b/fixtures/conformance/reporting-derived-measures/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-derived-measures/providers.json +++ b/fixtures/conformance/reporting-derived-measures/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-inherited-members/providers.json b/fixtures/conformance/reporting-inherited-members/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-inherited-members/providers.json +++ b/fixtures/conformance/reporting-inherited-members/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-ratio-numeric-min-max/providers.json b/fixtures/conformance/reporting-ratio-numeric-min-max/providers.json index aefa027b6a..1b9cc9ba66 100644 --- a/fixtures/conformance/reporting-ratio-numeric-min-max/providers.json +++ b/fixtures/conformance/reporting-ratio-numeric-min-max/providers.json @@ -1 +1 @@ -["metaobjects-core-types", "metaobjects-db"] +["metaobjects-core-types", "metaobjects-db", "metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-relative-startof/providers.json b/fixtures/conformance/reporting-relative-startof/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-relative-startof/providers.json +++ b/fixtures/conformance/reporting-relative-startof/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-spine-and-default/providers.json b/fixtures/conformance/reporting-spine-and-default/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-spine-and-default/providers.json +++ b/fixtures/conformance/reporting-spine-and-default/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-spine-inherited/providers.json b/fixtures/conformance/reporting-spine-inherited/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-spine-inherited/providers.json +++ b/fixtures/conformance/reporting-spine-inherited/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-value-object-members/providers.json b/fixtures/conformance/reporting-value-object-members/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-value-object-members/providers.json +++ b/fixtures/conformance/reporting-value-object-members/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/reporting-vocabulary/providers.json b/fixtures/conformance/reporting-vocabulary/providers.json index f9bb435a37..ab8afbe5b5 100644 --- a/fixtures/conformance/reporting-vocabulary/providers.json +++ b/fixtures/conformance/reporting-vocabulary/providers.json @@ -1 +1 @@ -["metaobjects-core-types","metaobjects-db"] +["metaobjects-core-types","metaobjects-db","metaobjects-reporting"] diff --git a/fixtures/conformance/requirement-level-integral-float/providers.json b/fixtures/conformance/requirement-level-integral-float/providers.json index 8ec88fc091..3aea349412 100644 --- a/fixtures/conformance/requirement-level-integral-float/providers.json +++ b/fixtures/conformance/requirement-level-integral-float/providers.json @@ -1 +1 @@ -["metaobjects-core-types"] +["metaobjects-core-types", "metaobjects-requirements"] diff --git a/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/expected-error.txt b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/expected-error.txt new file mode 100644 index 0000000000..1b1b47a76d --- /dev/null +++ b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/expected-error.txt @@ -0,0 +1 @@ +render verify failed: ERR_VAR_NOT_ON_PAYLOAD diff --git a/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/meta.json b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/meta.json new file mode 100644 index 0000000000..9742c6d544 --- /dev/null +++ b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "a variable absent from the payload (undefined, not null) raises; the message is matched as a prefix, since only the Mustache path can name the variable" } diff --git a/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/payload.json b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/payload.json new file mode 100644 index 0000000000..8f842fdc28 --- /dev/null +++ b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/payload.json @@ -0,0 +1 @@ +{ "name": "Ada" } diff --git a/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/template.jinja b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/template.jinja new file mode 100644 index 0000000000..54f7a86fed --- /dev/null +++ b/fixtures/jinja-render-conformance/jinja-render-error-missing-variable/template.jinja @@ -0,0 +1 @@ +Hi {{ nmae }}! diff --git a/fixtures/jinja-render-conformance/jinja-render-variables/expected.txt b/fixtures/jinja-render-conformance/jinja-render-variables/expected.txt index 374a93eb10..643c617253 100644 --- a/fixtures/jinja-render-conformance/jinja-render-variables/expected.txt +++ b/fixtures/jinja-render-conformance/jinja-render-variables/expected.txt @@ -1,4 +1,4 @@ Hello Ada count=3 ratio=2.5 whole=2 -active=true off=false none=[] missing=[] +active=true off=false none=[] first tag: math diff --git a/fixtures/jinja-render-conformance/jinja-render-variables/meta.json b/fixtures/jinja-render-conformance/jinja-render-variables/meta.json index b59e20d939..c3f2693a15 100644 --- a/fixtures/jinja-render-conformance/jinja-render-variables/meta.json +++ b/fixtures/jinja-render-conformance/jinja-render-variables/meta.json @@ -1,4 +1,4 @@ { "format": "text", - "note": "attribute and subscript access, scalar printing (bool, whole float, null, missing)" + "note": "attribute and subscript access, scalar printing (bool, whole float, null; a missing variable raises, see jinja-render-error-missing-variable)" } diff --git a/fixtures/jinja-render-conformance/jinja-render-variables/template.jinja b/fixtures/jinja-render-conformance/jinja-render-variables/template.jinja index 7b85505cc4..f99d4ec34e 100644 --- a/fixtures/jinja-render-conformance/jinja-render-variables/template.jinja +++ b/fixtures/jinja-render-conformance/jinja-render-variables/template.jinja @@ -1,4 +1,4 @@ Hello {{ user.name }} <{{ user["email"] }}> count={{ count }} ratio={{ ratio }} whole={{ whole }} -active={{ active }} off={{ off }} none=[{{ nothing }}] missing=[{{ absent }}] +active={{ active }} off={{ off }} none=[{{ nothing }}] first tag: {{ tags[0] }} diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index 068818332f..2234069901 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -13,7 +13,7 @@ provider owns. This is the ownership lens over the same vocabulary Core metaobjects metamodel types and subtypes. -**Owns (registers):** `attr.base`, `attr.boolean`, `attr.class`, `attr.double`, `attr.expression`, `attr.filter`, `attr.int`, `attr.intMap`, `attr.long`, `attr.properties`, `attr.string`, `field.base`, `field.boolean`, `field.currency`, `field.date`, `field.decimal`, `field.double`, `field.duration`, `field.enum`, `field.float`, `field.inet`, `field.int`, `field.long`, `field.map`, `field.object`, `field.string`, `field.time`, `field.timestamp`, `field.uri`, `field.uuid`, `identity.primary`, `identity.reference`, `identity.secondary`, `layout.base`, `layout.dataGrid`, `object.base`, `object.entity`, `object.projection`, `object.report`, `object.value`, `origin.aggregate`, `origin.base`, `origin.computed`, `origin.first`, `origin.passthrough`, `relationship.aggregation`, `relationship.association`, `relationship.base`, `relationship.composition`, `source.base`, `source.rdb`, `template.base`, `template.output`, `template.prompt`, `template.toolcall`, `validator.array`, `validator.atLeastOne`, `validator.base`, `validator.comparison`, `validator.exactlyOne`, `validator.length`, `validator.numeric`, `validator.presentIff`, `validator.regex`, `validator.required`, `validator.requiredWhen`, `view.base`, `view.checkbox`, `view.currency`, `view.date`, `view.dropdown`, `view.hidden`, `view.hotlink`, `view.image`, `view.month`, `view.number`, `view.password`, `view.radio`, `view.text`, `view.textarea`, `view.web` +**Owns (registers):** `attr.base`, `attr.boolean`, `attr.class`, `attr.double`, `attr.expression`, `attr.filter`, `attr.int`, `attr.intMap`, `attr.long`, `attr.properties`, `attr.string`, `field.base`, `field.boolean`, `field.currency`, `field.date`, `field.decimal`, `field.double`, `field.duration`, `field.enum`, `field.float`, `field.inet`, `field.int`, `field.long`, `field.map`, `field.object`, `field.string`, `field.time`, `field.timestamp`, `field.uri`, `field.uuid`, `identity.primary`, `identity.reference`, `identity.secondary`, `layout.base`, `layout.dataGrid`, `object.base`, `object.entity`, `object.projection`, `object.value`, `origin.aggregate`, `origin.base`, `origin.computed`, `origin.first`, `origin.passthrough`, `relationship.aggregation`, `relationship.association`, `relationship.base`, `relationship.composition`, `source.base`, `source.rdb`, `template.base`, `template.output`, `template.prompt`, `template.toolcall`, `validator.array`, `validator.atLeastOne`, `validator.base`, `validator.comparison`, `validator.exactlyOne`, `validator.length`, `validator.numeric`, `validator.presentIff`, `validator.regex`, `validator.required`, `validator.requiredWhen`, `view.base`, `view.checkbox`, `view.currency`, `view.date`, `view.dropdown`, `view.hidden`, `view.hotlink`, `view.image`, `view.month`, `view.number`, `view.password`, `view.radio`, `view.text`, `view.textarea`, `view.web` **Contributes attributes:** @@ -32,10 +32,9 @@ Core metaobjects metamodel types and subtypes. - `object.base`: `@object`, `@objectAdapter` - `object.entity`: `@collectionName`, `@discriminator`, `@discriminatorValue` - `object.projection`: `@collectionName`, `@filter` -- `object.report`: `@collectionName`, `@dimensions`, `@filter`, `@from`, `@measures`, `@segment`, `@spine` -- `origin.aggregate`: `@agg`, `@distinct`, `@filter`, `@of`, `@orderBy`, `@segment`, `@via` +- `origin.aggregate`: `@agg`, `@distinct`, `@filter`, `@of`, `@orderBy`, `@via` - `origin.computed`: `@expr` -- `origin.first`: `@filter`, `@of`, `@orderBy`, `@segment`, `@via` +- `origin.first`: `@filter`, `@of`, `@orderBy`, `@via` - `origin.passthrough`: `@convert`, `@from`, `@via` - `relationship.aggregation`: `@cardinality`, `@objectRef`, `@onDelete`, `@onUpdate`, `@sourceRefField`, `@symmetric`, `@through` - `relationship.association`: `@cardinality`, `@objectRef`, `@onDelete`, `@onUpdate`, `@sourceRefField`, `@symmetric`, `@through` @@ -127,6 +126,35 @@ Prompt / AI + serialization domain — @xmlText / @example / @instruction field - `field.uuid`: `@example`, `@instruction`, `@xmlText` - `object.value`: `@normalize` +## metaobjects-reporting + +Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first. + +**Owns (registers):** `dimension.attribute`, `dimension.time`, `measure.aggregate`, `measure.derived`, `measure.ratio`, `object.report`, `segment.filter` + +**Contributes attributes:** + +- `dimension.attribute`: `@of`, `@via` +- `dimension.time`: `@grains`, `@of`, `@via` +- `measure.aggregate`: `@agg`, `@default`, `@distinct`, `@filter`, `@of`, `@segment` +- `measure.derived`: `@expr` +- `measure.ratio`: `@default`, `@denominator`, `@numerator` +- `object.report`: `@collectionName`, `@dimensions`, `@filter`, `@from`, `@measures`, `@segment`, `@spine` +- `origin.aggregate`: `@segment` +- `origin.first`: `@segment` +- `segment.filter`: `@filter` + +## metaobjects-requirements + +Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify. + +**Owns (registers):** `requirement.architectural`, `requirement.functional` + +**Contributes attributes:** + +- `requirement.architectural`: `@counterexample`, `@disposition`, `@implementedBy`, `@level`, `@statement`, `@status`, `@supersededBy`, `@trackedBy` +- `requirement.functional`: `@counterexample`, `@disposition`, `@implementedBy`, `@level`, `@statement`, `@status`, `@supersededBy`, `@trackedBy` + ## metaobjects-rules Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum). diff --git a/fixtures/metamodel-docs/expected/types/dimension.md b/fixtures/metamodel-docs/expected/types/dimension.md index 9ccb48ae62..d588875036 100644 --- a/fixtures/metamodel-docs/expected/types/dimension.md +++ b/fixtures/metamodel-docs/expected/types/dimension.md @@ -14,14 +14,16 @@ documentation attributes are omitted here (see [providers.md](../providers.md)). 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. +**Owning provider:** metaobjects-reporting + **When to use:** A column a dashboard groups by: product, status, region. Declare it once on the fact entity and reference it by name from reports. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@of` | string | yes | | | — | Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own. | -| `@via` | string | no | | | — | Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference. | +| `@of` | string | yes | | | metaobjects-reporting | Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own. | +| `@via` | string | no | | | metaobjects-reporting | Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference. | **Allowed children** @@ -31,15 +33,17 @@ _No structural children._ 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). +**Owning provider:** metaobjects-reporting + **When to use:** Per-day, per-week or per-month series on a dashboard. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@grains` | string[] | yes | | `hour`, `day`, `week`, `month`, `quarter`, `year` | — | The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date. | -| `@of` | string | yes | | | — | Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object. | -| `@via` | string | no | | | — | Optional dotted to-one relationship path, as on dimension.attribute. | +| `@grains` | string[] | yes | | `hour`, `day`, `week`, `month`, `quarter`, `year` | metaobjects-reporting | The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date. | +| `@of` | string | yes | | | metaobjects-reporting | Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object. | +| `@via` | string | no | | | metaobjects-reporting | Optional dotted to-one relationship path, as on dimension.attribute. | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/measure.md b/fixtures/metamodel-docs/expected/types/measure.md index a4a0f90669..4e071a1a36 100644 --- a/fixtures/metamodel-docs/expected/types/measure.md +++ b/fixtures/metamodel-docs/expected/types/measure.md @@ -14,18 +14,20 @@ documentation attributes are omitted here (see [providers.md](../providers.md)). A named aggregate over the declaring entity's own rows (FR-044). @agg count without @distinct counts rows; with @distinct it counts distinct values of @of (a list in @of is a distinct count of the tuple). Unlike origin.aggregate, count is NOT distinct by default: a measure aggregates its own rows and dimensions reach only to-one paths, so no join inflates it. +**Owning provider:** metaobjects-reporting + **When to use:** A number a dashboard shows: revenue, purchases, distinct buyers, last activity. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@agg` | string | yes | | `count`, `sum`, `avg`, `min`, `max`, `any`, `all` | — | The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment. | -| `@default` | int | no | | | — | Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null), on min/max over a field that is not numeric, and on @agg any/all unless it is 0 (false) or 1 (true). A ratio's operand carries its own @default into the ratio. | -| `@distinct` | boolean | no | | | — | Count distinct values. Legal only with @agg: count. | -| `@filter` | filter | no | | | — | Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: "-P7D" }). Combines with @segment by AND. | -| `@of` | string[] | no | | | — | Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows. | -| `@segment` | string | no | | | — | Optional name of a segment declared on the same entity. Combines with @filter by AND. | +| `@agg` | string | yes | | `count`, `sum`, `avg`, `min`, `max`, `any`, `all` | metaobjects-reporting | The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment. | +| `@default` | int | no | | | metaobjects-reporting | Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null), on min/max over a field that is not numeric, and on @agg any/all unless it is 0 (false) or 1 (true). A ratio's operand carries its own @default into the ratio. | +| `@distinct` | boolean | no | | | metaobjects-reporting | Count distinct values. Legal only with @agg: count. | +| `@filter` | filter | no | | | metaobjects-reporting | Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: "-P7D" }). Combines with @segment by AND. | +| `@of` | string[] | no | | | metaobjects-reporting | Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows. | +| `@segment` | string | no | | | metaobjects-reporting | Optional name of a segment declared on the same entity. Combines with @filter by AND. | **Allowed children** @@ -35,13 +37,15 @@ _No structural children._ A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension. +**Owning provider:** metaobjects-reporting + **When to use:** A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds). **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@expr` | expression | yes | | | — | The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add \| subtract \| multiply \| divide, args: [a, b] } combines two operands. | +| `@expr` | expression | yes | | | metaobjects-reporting | The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add \| subtract \| multiply \| divide, args: [a, b] } combines two operands. | **Allowed children** @@ -51,15 +55,17 @@ _No structural children._ A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null. +**Owning provider:** metaobjects-reporting + **When to use:** Averages per unit that are not a plain avg: average days engaged per starter. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@default` | int | no | | | — | Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio. | -| `@denominator` | string | yes | | | — | Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field. | -| `@numerator` | string | yes | | | — | Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field. | +| `@default` | int | no | | | metaobjects-reporting | Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio. | +| `@denominator` | string | yes | | | metaobjects-reporting | Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field. | +| `@numerator` | string | yes | | | metaobjects-reporting | Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field. | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/object.md b/fixtures/metamodel-docs/expected/types/object.md index b24ba50219..7d06693065 100644 --- a/fixtures/metamodel-docs/expected/types/object.md +++ b/fixtures/metamodel-docs/expected/types/object.md @@ -102,7 +102,7 @@ A derived read-only representation of entities. Its fields are extends-bound / o 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. -**Owning provider:** metaobjects-core-types +**Owning provider:** metaobjects-reporting **When to use:** Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries. @@ -110,15 +110,15 @@ A declared report (FR-044): a fixed combination of dimensions and measures of ON | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@collectionName` | string | no | | | metaobjects-core-types | The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | -| `@dimensions` | string[] | no | | | metaobjects-core-types | Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row. | -| `@filter` | filter | no | | | metaobjects-core-types | Optional row scope over @from's fields; may use relative-date values. | -| `@from` | string | yes | | | metaobjects-core-types | The object.entity whose rows the report aggregates. | -| `@measures` | string[] | yes | | | metaobjects-core-types | Measure names of @from. | +| `@collectionName` | string | no | | | metaobjects-reporting | The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | +| `@dimensions` | string[] | no | | | metaobjects-reporting | Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row. | +| `@filter` | filter | no | | | metaobjects-reporting | Optional row scope over @from's fields; may use relative-date values. | +| `@from` | string | yes | | | metaobjects-reporting | The object.entity whose rows the report aggregates. | +| `@measures` | string[] | yes | | | metaobjects-reporting | Measure names of @from. | | `@object` | string | no | | | metaobjects-core-types | The native class an object binds to (ADR-0001), in place of its default runtime class: on the JVM, a fully-qualified class name. Cross-port vocabulary only Java implements so far; every port loads and type-checks it, and the others do not act on it yet. | | `@objectAdapter` | string | no | | | metaobjects-core-types | JVM-only (ADR-0005): the fully-qualified name of an ObjectAdapter that takes over value access for this object's instances. Every port loads and type-checks it; only Java and Kotlin act on it. | -| `@segment` | string | no | | | metaobjects-core-types | Optional segment of @from scoping the rows. | -| `@spine` | string | no | | | metaobjects-core-types | Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report. | +| `@segment` | string | no | | | metaobjects-reporting | Optional segment of @from scoping the rows. | +| `@spine` | string | no | | | metaobjects-reporting | Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report. | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/origin.md b/fixtures/metamodel-docs/expected/types/origin.md index a592204dfe..bf151b069e 100644 --- a/fixtures/metamodel-docs/expected/types/origin.md +++ b/fixtures/metamodel-docs/expected/types/origin.md @@ -29,7 +29,7 @@ A value reduced from the related row-set reached along a relationship path (@via | `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or — correlated-filter — { field: "" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19). | | `@of` | string | no | | | metaobjects-core-types | Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column). | | `@orderBy` | string[] | no | | | metaobjects-core-types | Ordering keys as 'field[:asc\|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax. | -| `@segment` | string | no | | | metaobjects-core-types | Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | +| `@segment` | string | no | | | metaobjects-reporting | Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | | `@via` | string | no | | | metaobjects-core-types | Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029). | **Allowed children** @@ -85,7 +85,7 @@ The single related row selected by @orderBy along @via, projecting its @of colum | `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or — correlated-filter — { field: "" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19). | | `@of` | string | yes | | | metaobjects-core-types | Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine). | | `@orderBy` | string[] | yes | | | metaobjects-core-types | Ordering keys as 'field[:asc\|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax. | -| `@segment` | string | no | | | metaobjects-core-types | Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | +| `@segment` | string | no | | | metaobjects-reporting | Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | | `@via` | string | no | | | metaobjects-core-types | Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029). | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/requirement.md b/fixtures/metamodel-docs/expected/types/requirement.md index 4942bea566..3362a94e02 100644 --- a/fixtures/metamodel-docs/expected/types/requirement.md +++ b/fixtures/metamodel-docs/expected/types/requirement.md @@ -14,20 +14,22 @@ documentation attributes are omitted here (see [providers.md](../providers.md)). How the system is built, applied uniformly across the model. Its check is UNIVERSALITY, the opposite polarity to a functional requirement. What `meta verify` enforces is that a live or partial policy is applied at all — one claiming nothing is an error — not that each node it claims complies. Flat by default and object-independent; it may optionally sit in a levelled tree when a quality taxonomy is being used to organise non-functional requirements. +**Owning provider:** metaobjects-requirements + **When to use:** Something exists because every entity here looks like this — a uuid primary key, an @autoSet createdAt, a change-attribution column, tenant scoping. The discriminator is mechanical: did this exist because someone asked for something, or because it is the architecture? For a non-functional tree, an established quality taxonomy makes a good fixed upper structure (e.g. an ISO/IEC 25010 characteristic at L1, its sub-characteristic or a control-catalogue category at L2), with the model-binding claims at L4 and L5 as usual. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@counterexample` | string | yes | | | — | What breaking it looks like — the node that would contradict it. A STATIC falsifiability test, not a state. This is what makes universality checkable. Renamed from @violation in 0.24.0, which read as a status. | -| `@disposition` | string | no | | `accepted`, `deferred` | — | As on requirement.functional. On an architectural requirement, accepted is the common and important case: a policy that is genuinely not universal, where the exceptions are known and tolerated, is more honest as partial+accepted than as a live claim nobody audits. | -| `@implementedBy` | string[] | no | | | — | FQN references to the nodes applying this policy. High fan-out is normal and expected: one uuid-primary-key requirement is claimed by every entity. | -| `@level` | int | no | | | — | OPTIONAL here, unlike on a functional requirement where it is required. ABSENT means a flat, object-independent policy that may reference the model directly — the original and still the default form. PRESENT means this node sits in a levelled tree, and then the same rules as functional apply: nesting must agree with the level, and only L4/L5 may carry @implementedBy. Levelling is opt-in so that adding a taxonomy on top of existing flat policies does not invalidate them. | -| `@statement` | string | yes | | | — | The policy, in one sentence. | -| `@status` | string | yes | | `planned`, `live`, `partial`, `retired` | — | As on requirement.functional. A live or partial architectural requirement claimed by NOTHING is an error: a policy declared and applied to nothing. planned is exempt from that check — it is not applied yet by definition — and retired is exempt because a withdrawn policy governs nothing. | -| `@supersededBy` | string | no | | | — | The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not. | -| `@trackedBy` | string[] | no | | | — | As on requirement.functional. Issue or ticket references for outstanding work; free-form, not resolved. | +| `@counterexample` | string | yes | | | metaobjects-requirements | What breaking it looks like — the node that would contradict it. A STATIC falsifiability test, not a state. This is what makes universality checkable. Renamed from @violation in 0.24.0, which read as a status. | +| `@disposition` | string | no | | `accepted`, `deferred` | metaobjects-requirements | As on requirement.functional. On an architectural requirement, accepted is the common and important case: a policy that is genuinely not universal, where the exceptions are known and tolerated, is more honest as partial+accepted than as a live claim nobody audits. | +| `@implementedBy` | string[] | no | | | metaobjects-requirements | FQN references to the nodes applying this policy. High fan-out is normal and expected: one uuid-primary-key requirement is claimed by every entity. | +| `@level` | int | no | | | metaobjects-requirements | OPTIONAL here, unlike on a functional requirement where it is required. ABSENT means a flat, object-independent policy that may reference the model directly — the original and still the default form. PRESENT means this node sits in a levelled tree, and then the same rules as functional apply: nesting must agree with the level, and only L4/L5 may carry @implementedBy. Levelling is opt-in so that adding a taxonomy on top of existing flat policies does not invalidate them. | +| `@statement` | string | yes | | | metaobjects-requirements | The policy, in one sentence. | +| `@status` | string | yes | | `planned`, `live`, `partial`, `retired` | metaobjects-requirements | As on requirement.functional. A live or partial architectural requirement claimed by NOTHING is an error: a policy declared and applied to nothing. planned is exempt from that check — it is not applied yet by definition — and retired is exempt because a withdrawn policy governs nothing. | +| `@supersededBy` | string | no | | | metaobjects-requirements | The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not. | +| `@trackedBy` | string[] | no | | | metaobjects-requirements | As on requirement.functional. Issue or ticket references for outstanding work; free-form, not resolved. | **Allowed children** @@ -37,20 +39,22 @@ How the system is built, applied uniformly across the model. Its check is UNIVER What the product does for a user, stated as one violable claim. Its check is EXISTENCE, run by `meta verify`: a live or partial claim with no implementing node anywhere in its subtree is a warning, and a named node that no longer exists is an error. Hierarchy is nesting — an L1 solution contains its L2 segments, which contain L3 services, and so on down to the levels that reference the model. +**Owning provider:** metaobjects-requirements + **When to use:** Something exists because someone asked for it. L1-L3 are levels of ABSTRACTION AND OWNERSHIP in the problem domain — whose need is this, and at what altitude — and are never a directory, package, deployable or module. Binding to technical constructs happens only at L4 (an object) and L5 (a member), which is the allocation step. Test every node: if a refactor that changes no behaviour would force it to move, its level is wrong. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@counterexample` | string | yes | | | — | What breaking it looks like, in one sentence — a STATIC falsifiability test, authored once, never a state. A requirement MUST be violable: 'every entity has a uuid primary key' is (point at one with a composite string key); 'things are persisted' is not, and is a description rather than a requirement. Renamed from @violation in 0.24.0, which read as a status. | -| `@disposition` | string | no | | `accepted`, `deferred` | — | What has been DECIDED about outstanding work — a different question from whether the work is done, which is what @status answers. accepted: the gap is understood and deliberately not being closed. deferred: it will be closed, but not now. ABSENT MEANS UNDECIDED, which is a real and useful state — it is what an unreviewed gap looks like, and it is the one a review should be able to find. Meaningful on planned and partial only; on a status with no outstanding work it is a WARNING. Deliberately NOT a workflow vocabulary: which sprint, who owns it and whether it is in progress belong in the tracker named by @trackedBy, because two systems holding that answer will drift and only one of them is refreshed daily. | -| `@implementedBy` | string[] | no | | | — | FQN references to the model nodes realising this requirement. Legal on level 4 (an object) and level 5 (a field, view or identity) only; an organisational level carrying it is ERR_REQUIREMENT_LINK_ABOVE_FLOOR. Many-to-many by construction — several requirements may name the same node. | -| `@level` | int | yes | | | — | 1 solution, 2 segment, 3 service, 4 object, 5 member. L1-L3 are levels of abstraction and ownership in the problem domain, NOT of code structure. Nesting depth must agree with it; skipping a level is legal, going back up is not. | -| `@statement` | string | yes | | | — | What the capability is, in one sentence. | -| `@status` | string | yes | | `planned`, `live`, `partial`, `retired` | — | planned intended but not built yet; live implemented and in use; partial implemented with known gaps; retired BUILT THEN DELIBERATELY REMOVED — it must not be rebuilt. A requirement is PRESCRIPTIVE: it states what SHOULD be true and never journals what happened, and retired satisfies that because it states a prohibition in force, falsifiable by the capability reappearing. On retired, @implementedBy is REFUSED at load (ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS) — a retired capability has no implementation by definition, so its references cannot dangle because they cannot exist; @supersededBy names the requirement that replaced it. A dangling @implementedBy is an ERROR on live/partial (the model moved, the requirement is stale) and ALLOWED on planned, where the nodes do not exist YET. Neither planned nor retired contributes to object coverage: planning a capability must not silence the warning that nothing implements it, and neither must retiring one. | -| `@supersededBy` | string | no | | | — | The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not. | -| `@trackedBy` | string[] | no | | | — | Issue or ticket references for outstanding work — a URL, an owner/repo#123 shorthand, or a tracker key. Free-form and NOT resolved by verify, which does not reach the network; nothing here is checked to exist. Its job is to stop a deferred gap becoming invisible, so verify warns when a deferred requirement names no ticket. Also the right place to link the ticket that a planned requirement will be built under. | +| `@counterexample` | string | yes | | | metaobjects-requirements | What breaking it looks like, in one sentence — a STATIC falsifiability test, authored once, never a state. A requirement MUST be violable: 'every entity has a uuid primary key' is (point at one with a composite string key); 'things are persisted' is not, and is a description rather than a requirement. Renamed from @violation in 0.24.0, which read as a status. | +| `@disposition` | string | no | | `accepted`, `deferred` | metaobjects-requirements | What has been DECIDED about outstanding work — a different question from whether the work is done, which is what @status answers. accepted: the gap is understood and deliberately not being closed. deferred: it will be closed, but not now. ABSENT MEANS UNDECIDED, which is a real and useful state — it is what an unreviewed gap looks like, and it is the one a review should be able to find. Meaningful on planned and partial only; on a status with no outstanding work it is a WARNING. Deliberately NOT a workflow vocabulary: which sprint, who owns it and whether it is in progress belong in the tracker named by @trackedBy, because two systems holding that answer will drift and only one of them is refreshed daily. | +| `@implementedBy` | string[] | no | | | metaobjects-requirements | FQN references to the model nodes realising this requirement. Legal on level 4 (an object) and level 5 (a field, view or identity) only; an organisational level carrying it is ERR_REQUIREMENT_LINK_ABOVE_FLOOR. Many-to-many by construction — several requirements may name the same node. | +| `@level` | int | yes | | | metaobjects-requirements | 1 solution, 2 segment, 3 service, 4 object, 5 member. L1-L3 are levels of abstraction and ownership in the problem domain, NOT of code structure. Nesting depth must agree with it; skipping a level is legal, going back up is not. | +| `@statement` | string | yes | | | metaobjects-requirements | What the capability is, in one sentence. | +| `@status` | string | yes | | `planned`, `live`, `partial`, `retired` | metaobjects-requirements | planned intended but not built yet; live implemented and in use; partial implemented with known gaps; retired BUILT THEN DELIBERATELY REMOVED — it must not be rebuilt. A requirement is PRESCRIPTIVE: it states what SHOULD be true and never journals what happened, and retired satisfies that because it states a prohibition in force, falsifiable by the capability reappearing. On retired, @implementedBy is REFUSED at load (ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS) — a retired capability has no implementation by definition, so its references cannot dangle because they cannot exist; @supersededBy names the requirement that replaced it. A dangling @implementedBy is an ERROR on live/partial (the model moved, the requirement is stale) and ALLOWED on planned, where the nodes do not exist YET. Neither planned nor retired contributes to object coverage: planning a capability must not silence the warning that nothing implements it, and neither must retiring one. | +| `@supersededBy` | string | no | | | metaobjects-requirements | The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not. | +| `@trackedBy` | string[] | no | | | metaobjects-requirements | Issue or ticket references for outstanding work — a URL, an owner/repo#123 shorthand, or a tracker key. Free-form and NOT resolved by verify, which does not reach the network; nothing here is checked to exist. Its job is to stop a deferred gap becoming invisible, so verify warns when a deferred requirement names no ticket. Also the right place to link the ticket that a planned requirement will be built under. | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/segment.md b/fixtures/metamodel-docs/expected/types/segment.md index ce9f64a6f5..2ba16ba92a 100644 --- a/fixtures/metamodel-docs/expected/types/segment.md +++ b/fixtures/metamodel-docs/expected/types/segment.md @@ -14,13 +14,15 @@ documentation attributes are omitted here (see [providers.md](../providers.md)). A named, reusable row filter on the declaring entity (FR-044). Measures and reports reference it by name; exporters emit it as a named segment. +**Owning provider:** metaobjects-reporting + **When to use:** The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports. **Attributes** | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@filter` | filter | yes | | | — | The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values. | +| `@filter` | filter | yes | | | metaobjects-reporting | The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values. | **Allowed children** diff --git a/fixtures/registry-conformance/core-vocabulary.pin.json b/fixtures/registry-conformance/core-vocabulary.pin.json index b668375f3b..9ad35e8985 100644 --- a/fixtures/registry-conformance/core-vocabulary.pin.json +++ b/fixtures/registry-conformance/core-vocabulary.pin.json @@ -45,21 +45,6 @@ "attrs": [], "children": [] }, - "dimension.attribute": { - "attrs": [ - "of", - "via" - ], - "children": [] - }, - "dimension.time": { - "attrs": [ - "grains", - "of", - "via" - ], - "children": [] - }, "field.base": { "attrs": [ "default", @@ -203,31 +188,6 @@ "attrs": [], "children": [] }, - "measure.aggregate": { - "attrs": [ - "agg", - "default", - "distinct", - "filter", - "of", - "segment" - ], - "children": [] - }, - "measure.derived": { - "attrs": [ - "expr" - ], - "children": [] - }, - "measure.ratio": { - "attrs": [ - "default", - "denominator", - "numerator" - ], - "children": [] - }, "object.base": { "attrs": [ "object", @@ -249,10 +209,7 @@ "discriminatorValue" ], "children": [ - "dimension.*:*", - "measure.*:*", "relationship.*:*", - "segment.*:*", "template.*:*" ] }, @@ -263,18 +220,6 @@ ], "children": [] }, - "object.report": { - "attrs": [ - "collectionName", - "dimensions", - "filter", - "from", - "measures", - "segment", - "spine" - ], - "children": [] - }, "object.value": { "attrs": [], "children": [ @@ -288,7 +233,6 @@ "filter", "of", "orderBy", - "segment", "via" ], "children": [] @@ -308,7 +252,6 @@ "filter", "of", "orderBy", - "segment", "via" ], "children": [] @@ -369,42 +312,6 @@ ], "children": [] }, - "requirement.architectural": { - "attrs": [ - "counterexample", - "disposition", - "implementedBy", - "level", - "statement", - "status", - "supersededBy", - "trackedBy" - ], - "children": [ - "requirement.*:*" - ] - }, - "requirement.functional": { - "attrs": [ - "counterexample", - "disposition", - "implementedBy", - "level", - "statement", - "status", - "supersededBy", - "trackedBy" - ], - "children": [ - "requirement.*:*" - ] - }, - "segment.filter": { - "attrs": [ - "filter" - ], - "children": [] - }, "source.base": { "attrs": [], "children": [] diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 6355711847..cb71274e0e 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -3440,7 +3440,9 @@ { "childType": "requirement", "childSubType": "*", - "childName": "*" + "childName": "*", + "min": 0, + "max": null }, { "childType": "template", diff --git a/fixtures/registry-conformance/providers.json b/fixtures/registry-conformance/providers.json index dd240c3b33..fee207043c 100644 --- a/fixtures/registry-conformance/providers.json +++ b/fixtures/registry-conformance/providers.json @@ -56,6 +56,20 @@ "object.value" ] }, + "metaobjects-reporting": { + "declaresTypes": true, + "projectsOnto": [ + "object.entity", + "origin.aggregate", + "origin.first" + ] + }, + "metaobjects-requirements": { + "declaresTypes": true, + "projectsOnto": [ + "metadata.root" + ] + }, "metaobjects-rules": { "declaresTypes": true, "projectsOnto": [ diff --git a/fixtures/render-conformance/render-dotted-path-lookup/expected.txt b/fixtures/render-conformance/render-dotted-path-lookup/expected.txt index 06ee3a698e..e051441bf1 100644 --- a/fixtures/render-conformance/render-dotted-path-lookup/expected.txt +++ b/fixtures/render-conformance/render-dotted-path-lookup/expected.txt @@ -1,5 +1,3 @@ name: Ada email: ada@example.test role: admin -missing-leaf: [] -missing-mid: [] diff --git a/fixtures/render-conformance/render-dotted-path-lookup/meta.json b/fixtures/render-conformance/render-dotted-path-lookup/meta.json index bfcc8270e1..29d3cffdeb 100644 --- a/fixtures/render-conformance/render-dotted-path-lookup/meta.json +++ b/fixtures/render-conformance/render-dotted-path-lookup/meta.json @@ -1 +1 @@ -{ "format": "text", "note": "dotted-path interpolation {{user.profile.name}} walks nested objects" } +{ "format": "text", "note": "dotted-path interpolation {{user.profile.name}} walks nested objects; a missing leaf or middle raises, see render-error-missing-dotted-path" } diff --git a/fixtures/render-conformance/render-dotted-path-lookup/template.mustache b/fixtures/render-conformance/render-dotted-path-lookup/template.mustache index f5e6c22d66..23400f6240 100644 --- a/fixtures/render-conformance/render-dotted-path-lookup/template.mustache +++ b/fixtures/render-conformance/render-dotted-path-lookup/template.mustache @@ -1,5 +1,3 @@ name: {{user.profile.name}} email: {{user.profile.email}} role: {{user.roles.primary}} -missing-leaf: [{{user.profile.missing}}] -missing-mid: [{{user.unknown.name}}] diff --git a/fixtures/render-conformance/render-error-missing-dotted-path/expected-error.txt b/fixtures/render-conformance/render-error-missing-dotted-path/expected-error.txt new file mode 100644 index 0000000000..0f0287cd3d --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-dotted-path/expected-error.txt @@ -0,0 +1 @@ +render verify failed: ERR_VAR_NOT_ON_PAYLOAD (user.profile.missing) diff --git a/fixtures/render-conformance/render-error-missing-dotted-path/meta.json b/fixtures/render-conformance/render-error-missing-dotted-path/meta.json new file mode 100644 index 0000000000..f569ca276a --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-dotted-path/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "a dotted path that fails to resolve at any step is a missing variable and raises" } diff --git a/fixtures/render-conformance/render-error-missing-dotted-path/payload.json b/fixtures/render-conformance/render-error-missing-dotted-path/payload.json new file mode 100644 index 0000000000..37b728c178 --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-dotted-path/payload.json @@ -0,0 +1,12 @@ +{ + "user": { + "profile": { + "name": "Ada", + "email": "ada@example.test" + }, + "roles": { + "primary": "admin" + } + }, + "missing": {} +} diff --git a/fixtures/render-conformance/render-error-missing-dotted-path/template.mustache b/fixtures/render-conformance/render-error-missing-dotted-path/template.mustache new file mode 100644 index 0000000000..741c7bb780 --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-dotted-path/template.mustache @@ -0,0 +1 @@ +missing-leaf: [{{user.profile.missing}}] diff --git a/fixtures/render-conformance/render-error-missing-variable/expected-error.txt b/fixtures/render-conformance/render-error-missing-variable/expected-error.txt new file mode 100644 index 0000000000..6ad3507422 --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-variable/expected-error.txt @@ -0,0 +1 @@ +render verify failed: ERR_VAR_NOT_ON_PAYLOAD (nmae) diff --git a/fixtures/render-conformance/render-error-missing-variable/meta.json b/fixtures/render-conformance/render-error-missing-variable/meta.json new file mode 100644 index 0000000000..f2aa776ebb --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-variable/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "a variable tag whose name is absent from the payload (undefined, not null) raises on the direct render path, with the same error the verify gate raises; no opt-in needed" } diff --git a/fixtures/render-conformance/render-error-missing-variable/payload.json b/fixtures/render-conformance/render-error-missing-variable/payload.json new file mode 100644 index 0000000000..8f842fdc28 --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-variable/payload.json @@ -0,0 +1 @@ +{ "name": "Ada" } diff --git a/fixtures/render-conformance/render-error-missing-variable/template.mustache b/fixtures/render-conformance/render-error-missing-variable/template.mustache new file mode 100644 index 0000000000..3fdd2536a3 --- /dev/null +++ b/fixtures/render-conformance/render-error-missing-variable/template.mustache @@ -0,0 +1 @@ +Hi {{nmae}}! diff --git a/scripts/check-core-vocabulary-pin.ts b/scripts/check-core-vocabulary-pin.ts index 24640ace34..f3260d46c2 100644 --- a/scripts/check-core-vocabulary-pin.ts +++ b/scripts/check-core-vocabulary-pin.ts @@ -150,7 +150,8 @@ export const FAILURE_GUIDANCE = [ "needs it. Put it in a pack instead: its own provider and spec/metamodel/.json", "(provider id 'metaobjects-'), composed by default if it ships with the library, so a", "project can leave it out. See docs/features/extending-with-providers.md and the worked", - "examples (metaobjects-rules, metaobjects-view-expressions).", + "examples (metaobjects-rules, metaobjects-view-expressions, metaobjects-reporting," + + " metaobjects-requirements).", "Only if a core maintainer has decided this belongs in core, regenerate the pin with", "`bun scripts/check-core-vocabulary-pin.ts --update` and justify it in the PR.", ].join("\n"); diff --git a/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs b/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs index b71aaad737..3fb2a3e008 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs @@ -168,6 +168,8 @@ public static class ConformanceAdapter // (origin.function, @union/@grain): their own packs, outside core-types. ["metaobjects-rules"] = MetaObjects.Core.Rules.RulesMetaDataProvider.Instance, ["metaobjects-view-expressions"] = MetaObjects.Persistence.ViewExpressions.ViewExpressionsMetaDataProvider.Instance, + ["metaobjects-reporting"] = MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + ["metaobjects-requirements"] = MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, ["metaobjects-prompt"] = MetaObjects.Template.PromptMetaDataProvider.Instance, // Back-compat alias: pre-rename fixtures (and other ports' fixtures) still name the // provider "metaobjects-template"; map it to the renamed prompt provider — the same diff --git a/server/csharp/MetaObjects.Conformance.Tests/CoreTypesTests.cs b/server/csharp/MetaObjects.Conformance.Tests/CoreTypesTests.cs index a381c290a1..28675473ae 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/CoreTypesTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/CoreTypesTests.cs @@ -39,7 +39,7 @@ public void Core_provider_factory_builds_the_right_node_class() // ------------------------------------------------------------------ private static TypeRegistry ComposedRegistry() => - Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider, MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance }); [Fact] public void Core_provider_registers_correct_subtypes_for_metadata() diff --git a/server/csharp/MetaObjects.Conformance.Tests/FixtureDiscovery.cs b/server/csharp/MetaObjects.Conformance.Tests/FixtureDiscovery.cs index 0c5d588e28..5b339a88d0 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/FixtureDiscovery.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/FixtureDiscovery.cs @@ -98,6 +98,8 @@ public static class FixtureDiscovery // The business-rules and view-expressions packs are in the default bundle. "metaobjects-rules", "metaobjects-view-expressions", + "metaobjects-reporting", + "metaobjects-requirements", }; /// diff --git a/server/csharp/MetaObjects.Conformance.Tests/FullCoreRegistry.cs b/server/csharp/MetaObjects.Conformance.Tests/FullCoreRegistry.cs index 12aabca357..36836b8c5c 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/FullCoreRegistry.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/FullCoreRegistry.cs @@ -29,6 +29,8 @@ internal static class FullCoreRegistry MetaObjects.Template.PromptMetaDataProvider.Instance, MetaObjects.Core.Rules.RulesMetaDataProvider.Instance, MetaObjects.Persistence.ViewExpressions.ViewExpressionsMetaDataProvider.Instance, + MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, }; /// Compose a fresh registry from the full core bundle. diff --git a/server/csharp/MetaObjects.Conformance.Tests/RegistryManifestConformanceTests.cs b/server/csharp/MetaObjects.Conformance.Tests/RegistryManifestConformanceTests.cs index 5fd76673a0..3558da1ec1 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/RegistryManifestConformanceTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/RegistryManifestConformanceTests.cs @@ -35,6 +35,8 @@ public void Emit_matches_the_committed_cross_port_canonical() MetaObjects.Template.PromptMetaDataProvider.Instance, MetaObjects.Core.Rules.RulesMetaDataProvider.Instance, MetaObjects.Persistence.ViewExpressions.ViewExpressionsMetaDataProvider.Instance, + MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, DocumentationTypes.DocTypesProvider, }); @@ -74,6 +76,8 @@ public void Every_registered_per_type_attr_is_explicitly_classified() MetaObjects.Template.PromptMetaDataProvider.Instance, MetaObjects.Core.Rules.RulesMetaDataProvider.Instance, MetaObjects.Persistence.ViewExpressions.ViewExpressionsMetaDataProvider.Instance, + MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, DocumentationTypes.DocTypesProvider, }); diff --git a/server/csharp/MetaObjects.Conformance.Tests/RequirementsPackLeftOutTests.cs b/server/csharp/MetaObjects.Conformance.Tests/RequirementsPackLeftOutTests.cs new file mode 100644 index 0000000000..44ccf6f041 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/RequirementsPackLeftOutTests.cs @@ -0,0 +1,78 @@ +using MetaObjects.Core.Requirement; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +/// +/// The requirements vocabulary is its own pack (metaobjects-requirements), composed by default. +/// With the pack left out the gate has nothing to read and reports nothing, and a model that declares a +/// requirement fails to load instead. +/// +public class RequirementsPackLeftOutTests +{ + private const string Order = """ + - object.entity: + name: Order + children: + - source.rdb: { table: orders } + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + """; + + private const string Requirement = """ + - requirement.functional: + name: PlaceOrder + level: 4 + status: live + statement: A customer places an order + counterexample: A customer cannot place an order + implementedBy: [app::Order] + """; + + private static string Indent(string block) => + string.Join("\n", block.Split('\n').Select(l => " " + l)); + + private static LoadResult Load(TypeRegistry registry, params string[] blocks) + { + var dir = Directory.CreateTempSubdirectory("mo-req-left-out-").FullName; + try + { + File.WriteAllText(Path.Combine(dir, "meta.app.yaml"), + "metadata:\n package: app\n children:\n" + string.Join("\n", blocks.Select(Indent)) + "\n"); + return MetaDataLoader.FromDirectory(dir, registry, strict: true); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + private static TypeRegistry WithoutPack() => + Provider.ComposeRegistry(CoreTypes.LibraryProviders.Where(p => p.Id != RequirementsMetaDataProvider.ProviderId).ToList()); + + [Fact] + public void A_model_with_no_requirements_loads_and_the_gate_reports_nothing() + { + var result = Load(WithoutPack(), Order); + Assert.Empty(result.Errors.Select(e => e.Code + ": " + e.Message)); + var scan = RequirementCheck.Scan(result.Root); + Assert.Empty(RequirementCheck.Check(result.Root, scan)); + Assert.Null(RequirementCheck.Summarise(result.Root, scan)); + } + + [Fact] + public void A_model_that_declares_a_requirement_fails_to_load_with_ERR_UNKNOWN_TYPE() + { + var result = Load(WithoutPack(), Order, Requirement); + Assert.Contains(result.Errors, e => e.Code == ErrorCode.ERR_UNKNOWN_TYPE); + } + + [Fact] + public void With_the_default_bundle_the_same_requirement_reaches_the_ledger() + { + var result = Load(Provider.ComposeRegistry(CoreTypes.LibraryProviders), Order, Requirement); + Assert.Empty(result.Errors.Select(e => e.Code + ": " + e.Message)); + Assert.Equal(1, RequirementCheck.Summarise(result.Root, RequirementCheck.Scan(result.Root))?.Total); + } +} diff --git a/server/csharp/MetaObjects.Conformance.Tests/YamlConformanceTests.cs b/server/csharp/MetaObjects.Conformance.Tests/YamlConformanceTests.cs index 2cfd704947..af67e04a0d 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/YamlConformanceTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/YamlConformanceTests.cs @@ -203,6 +203,8 @@ private static void RunChecks(YamlFixture fix, List failures) var registry = Provider.ComposeRegistry([ CoreTypes.CoreTypesProvider, MetaObjects.Persistence.Db.DbMetaDataProvider.Instance, + MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, ]); var parseOpts = new ParseOptions(registry) { diff --git a/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs b/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs index 53febefead..dfdb8967c4 100644 --- a/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs +++ b/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs @@ -10,7 +10,7 @@ namespace MetaObjects.Render.Tests; /// template.mustache the entry template /// partials/*.mustache optional partials, referenced as `partials/<name>` /// payload.json the render payload (pre-formatted primitives) -/// expected.txt byte-exact expected output +/// expected.txt byte-exact expected output (or expected-error.txt: the render must fail with that text) /// The same shared corpus is rendered byte-for-byte identically by TS and C#. /// Mirrors typescript/packages/render/test/render-conformance.test.ts. /// @@ -67,9 +67,24 @@ public void RenderMatchesExpected(string name) var format = JsonDocument.Parse(metaRaw).RootElement.GetProperty("format").GetString()!; var template = File.ReadAllText(Path.Combine(dir, "template.mustache")); var payload = JsonPayload.Parse(File.ReadAllText(Path.Combine(dir, "payload.json"))); - var expected = File.ReadAllText(Path.Combine(dir, "expected.txt")); var provider = ProviderFromPartials(dir); + // expected-error.txt: the render must fail, and the message must contain the file's trimmed text. + var errorFile = Path.Combine(dir, "expected-error.txt"); + if (File.Exists(errorFile)) + { + var ex = Assert.Throws(() => Renderer.Render(new RenderRequest + { + Template = template, + Payload = payload, + Provider = provider, + Format = format, + })); + Assert.Contains(File.ReadAllText(errorFile).Trim(), ex.Message); + return; + } + var expected = File.ReadAllText(Path.Combine(dir, "expected.txt")); + var actual = Renderer.Render(new RenderRequest { Template = template, diff --git a/server/csharp/MetaObjects.Render/PayloadAccessors.cs b/server/csharp/MetaObjects.Render/PayloadAccessors.cs index 088afcd9eb..1f5bb877f3 100644 --- a/server/csharp/MetaObjects.Render/PayloadAccessors.cs +++ b/server/csharp/MetaObjects.Render/PayloadAccessors.cs @@ -200,6 +200,34 @@ private sealed class TypedView(object target, int depth, bool? last) public override string? ToString() => Target.ToString(); } + /// + /// Whether is a member of the context (a present + /// null counts as present), and its value. Used by the renderer's missing-variable check, + /// which must tell an ABSENT name from a null one. A delegate or dynamic object cannot be + /// inspected, so every name is taken as present. + /// + internal static bool TryLookup(object? ctx, string key, out object? value) + { + value = null; + switch (ctx) + { + case null: return false; + case IDictionary map: return map.TryGetValue(key, out value); + case System.Collections.IDictionary dict: + if (!dict.Contains(key)) return false; + value = dict[key]; + return true; + case TypedView view: + if (ViewLookup(view, key, false) is { } found) { value = found; return true; } + if (view.Target.GetType().GetMember(key, PublicInstance).Length > 0) return true; + return false; + case Delegate or System.Dynamic.IDynamicMetaObjectProvider: + return true; + default: + return false; + } + } + /// The overlay type is registered for. internal static Type ViewType => typeof(TypedView); diff --git a/server/csharp/MetaObjects.Render/Renderer.cs b/server/csharp/MetaObjects.Render/Renderer.cs index 1833c96599..6ac8621f6f 100644 --- a/server/csharp/MetaObjects.Render/Renderer.cs +++ b/server/csharp/MetaObjects.Render/Renderer.cs @@ -114,7 +114,9 @@ public static string Render(RenderRequest request) // Derived `has` accessors are part of the payload contract, not of the // caller's object — see PayloadAccessors. Injected here so a `{{#hasFoo}}` section // resolves the same way it does against a generated JVM payload record. - string result = stubble.Render(expanded, PayloadAccessors.WithDerivedAccessors(request.Payload)); + object? view = PayloadAccessors.WithDerivedAccessors(request.Payload); + FailOnMissingVariable(expanded, view); + string result = stubble.Render(expanded, view); if (request.MaxChars is int cap && result.Length > cap) throw new RenderException( @@ -122,4 +124,86 @@ public static string Render(RenderRequest request) return result; } + + // A variable tag whose name is ABSENT from the payload (on no frame of the context stack) is a + // missing variable and raises the message the opt-in verify gate uses, so a typo like + // `{{nmae}}` fails on every render path. A value that is present but null renders empty. + // Walks the template the way the engine renders it: a section pushes its value (each element of + // a list), an inverted section or a falsy section's body is only checked when it renders. + private static void FailOnMissingVariable(string template, object? payload) + { + List tags; + try { tags = MustacheTags.Scan(template); } + catch (MustacheSyntaxException) { return; } // the engine reports a malformed template itself + CheckTags(tags, 0, tags.Count, [payload]); + } + + private static void CheckTags(List tags, int from, int to, List stack) + { + for (int i = from; i < to; i++) + { + var tag = tags[i]; + switch (tag.Kind) + { + case MustacheTagKind.Name or MustacheTagKind.Triple or MustacheTagKind.Amp: + if (!TryResolve(stack, tag.Value, out _)) + throw new RenderException($"render verify failed: {MetaObjects.Render.Verify.ERR_VAR_NOT_ON_PAYLOAD} ({tag.Value})"); + break; + case MustacheTagKind.Section or MustacheTagKind.Inverted: + int depth = 1, close = i + 1; + for (; close < to; close++) + { + if (tags[close].Kind is MustacheTagKind.Section or MustacheTagKind.Inverted) depth++; + else if (tags[close].Kind == MustacheTagKind.Close && --depth == 0) break; + } + bool found = TryResolve(stack, tag.Value, out object? value); + if (tag.Kind == MustacheTagKind.Inverted) + { + if (!found || IsFalsy(value)) CheckTags(tags, i + 1, close, stack); + } + else if (found && !IsFalsy(value) && value is not Delegate) + { + if (value is System.Collections.IEnumerable seq and not string and not System.Collections.IDictionary) + { + foreach (var item in seq) + CheckTags(tags, i + 1, close, [.. stack, item]); + } + else CheckTags(tags, i + 1, close, [.. stack, value]); + } + i = close; + break; + } + } + } + + private static bool IsFalsy(object? v) => v switch + { + null => true, + bool b => !b, + string s => s.Length == 0, + System.Collections.IDictionary => false, + System.Collections.IEnumerable seq => !seq.GetEnumerator().MoveNext(), + _ => false, + }; + + /// Mustache's name lookup: the first segment is searched from the innermost context outward, + /// the rest walk down from it. Absent at any step is a miss; a null part-way is a present null. + private static bool TryResolve(List stack, string name, out object? value) + { + value = null; + if (name == ".") { value = stack[^1]; return true; } + string[] segs = name.Split('.'); + bool hit = false; + object? current = null; + for (int i = stack.Count - 1; i >= 0 && !hit; i--) + hit = PayloadAccessors.TryLookup(stack[i], segs[0], out current); + if (!hit) return false; + for (int s = 1; s < segs.Length; s++) + { + if (current is null) { value = null; return true; } + if (!PayloadAccessors.TryLookup(current, segs[s], out current)) return false; + } + value = current; + return true; + } } diff --git a/server/csharp/MetaObjects/Core/Reporting/ReportingMetaDataProvider.cs b/server/csharp/MetaObjects/Core/Reporting/ReportingMetaDataProvider.cs new file mode 100644 index 0000000000..038322802f --- /dev/null +++ b/server/csharp/MetaObjects/Core/Reporting/ReportingMetaDataProvider.cs @@ -0,0 +1,66 @@ +// The metaobjects-reporting pack: dimension.*, measure.*, segment.filter and object.report +// (FR-044). Its own provider so a project can leave it out; it is in the default bundle, so +// every existing model loads unchanged. Types and attrs are declared in the embedded +// reporting.json, whose `extends` also admits the vocabulary as children of object.entity +// and adds @segment to origin.aggregate / origin.first. Mirrors the TS reportingProvider. + +using MetaObjects.Core.Object; +using MetaObjects.Meta; +using MetaObjects.Registry.Spec; +using static MetaObjects.Shared.BaseTypes; + +namespace MetaObjects.Core.Reporting; + +/// The reporting pack provider (metaobjects-reporting). +public sealed class ReportingMetaDataProvider : IMetaDataTypeProvider +{ + /// The shared singleton — composed into the default registry. + public static readonly IMetaDataTypeProvider Instance = new ReportingMetaDataProvider(); + + /// The provider id — matches reporting.json's "provider" field. + public const string ProviderId = "metaobjects-reporting"; + + private static readonly Lazy Reader = new(SpecMetamodelReader.Load); + + public string Id => ProviderId; + + public string? Description => + "Reporting: dimension / measure / segment and object.report, compiled to a read-only view."; + + public IReadOnlyList Dependencies => ["metaobjects-core-types"]; + + public void RegisterTypes(TypeRegistry registry) + { + void Reg(string type, string subType, string label, List attrs, Func factory) => + registry.Register(new TypeDefinition( + typeId: new TypeId(type, subType), + description: $"{label} ({subType})", + childRules: [new ChildRule(TYPE_ATTR, CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD)], + factory: factory, + attributes: attrs)); + + foreach (string subType in ReportingConstants.DIMENSION_SUBTYPES) + Reg(TYPE_DIMENSION, subType, "Dimension", ReportingSchema.DimensionAttrsMap[subType].ToList(), (tid, n) => new MetaDimension(tid, n)); + foreach (string subType in ReportingConstants.MEASURE_SUBTYPES) + Reg(TYPE_MEASURE, subType, "Measure", ReportingSchema.MeasureAttrsMap[subType].ToList(), (tid, n) => new MetaMeasure(tid, n)); + foreach (string subType in ReportingConstants.SEGMENT_SUBTYPES) + Reg(TYPE_SEGMENT, subType, "Segment", ReportingSchema.SegmentAttrsMap[subType].ToList(), (tid, n) => new MetaSegment(tid, n)); + + // object.report extends the base another provider registered: fold that base's + // attrs and child rules in (the strict pass later rebuilds the structural rules + // from the spec, which composes the same base). + TypeDefinition objectBase = registry.Find(TYPE_OBJECT, SUBTYPE_BASE) + ?? throw new InvalidOperationException("metaobjects-reporting: object.base is not registered"); + registry.Register(new TypeDefinition( + typeId: new TypeId(TYPE_OBJECT, ObjectConstants.OBJECT_SUBTYPE_REPORT), + description: $"Object/entity ({ObjectConstants.OBJECT_SUBTYPE_REPORT})", + childRules: objectBase.ChildRules.ToList(), + factory: (tid, n) => new MetaObject(tid, n), + attributes: [.. objectBase.Attributes, .. ReportingSchema.ReportAttrs, ObjectSchema.CollectionNameAttr])); + + registry.ApplyProviderExtends( + Reader.Value, + ProviderId, + new Dictionary>(StringComparer.Ordinal)); + } +} diff --git a/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs b/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs index 101fbc6dc5..7d7534f938 100644 --- a/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs +++ b/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs @@ -1,8 +1,8 @@ // Reporting attribute schemas — the per-subtype attr sets for dimension.*, measure.* and // segment.*, plus the object.report attrs (FR-044). // -// Colocated per ADR-0003. Mirrors the canonical spec/metamodel/reporting.json and the -// object.report block of spec/metamodel/object.json (which this port embeds + reads): +// Colocated per ADR-0003. Mirrors the canonical spec/metamodel/reporting.json, which +// declares object.report too (the reporting pack; this port embeds + reads it): // DESCRIPTIONS are deliberately NOT hand-copied here — FR-033 sources every description // from the shared JSON via Registry.ApplySpecDescriptions. Only the facets the manifest // needs but the description pass does not carry (value type / array-ness / requiredness / diff --git a/server/csharp/MetaObjects/Core/Requirement/RequirementsMetaDataProvider.cs b/server/csharp/MetaObjects/Core/Requirement/RequirementsMetaDataProvider.cs new file mode 100644 index 0000000000..3d50784881 --- /dev/null +++ b/server/csharp/MetaObjects/Core/Requirement/RequirementsMetaDataProvider.cs @@ -0,0 +1,56 @@ +// The metaobjects-requirements pack: requirement.functional / requirement.architectural. +// Its own provider so a project can leave it out; it is in the default bundle, so every +// existing model loads unchanged. Types and attrs are declared in the embedded +// requirement.json, whose `extends` admits `requirement` under metadata.root. +// Mirrors the TS requirementsProvider. + +using MetaObjects.Meta; +using MetaObjects.Registry.Spec; +using static MetaObjects.Shared.BaseTypes; + +namespace MetaObjects.Core.Requirement; + +/// The requirements pack provider (metaobjects-requirements). +public sealed class RequirementsMetaDataProvider : IMetaDataTypeProvider +{ + /// The shared singleton — composed into the default registry. + public static readonly IMetaDataTypeProvider Instance = new RequirementsMetaDataProvider(); + + /// The provider id — matches requirement.json's "provider" field. + public const string ProviderId = "metaobjects-requirements"; + + private static readonly Lazy Reader = new(SpecMetamodelReader.Load); + + public string Id => ProviderId; + + public string? Description => + "Requirements: requirement.functional (existence) and requirement.architectural (universality)."; + + public IReadOnlyList Dependencies => ["metaobjects-core-types"]; + + public void RegisterTypes(TypeRegistry registry) + { + // Hierarchy IS nesting: BOTH subtypes may nest requirement children. Structural + // cardinality comes from requirement.json via ApplySpecDescriptions. + foreach (string subType in RequirementConstants.REQUIREMENT_SUBTYPES) + { + registry.Register(new TypeDefinition( + typeId: new TypeId(TYPE_REQUIREMENT, subType), + description: $"Requirement ({subType})", + childRules: + [ + new ChildRule(TYPE_ATTR, CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD), + new ChildRule(TYPE_REQUIREMENT, CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD), + ], + factory: (tid, n) => new MetaRequirement(tid, n), + attributes: RequirementSchema.RequirementAttrsMap.TryGetValue(subType, out var reqAttrs) + ? reqAttrs.ToList() + : [])); + } + + registry.ApplyProviderExtends( + Reader.Value, + ProviderId, + new Dictionary>(StringComparer.Ordinal)); + } +} diff --git a/server/csharp/MetaObjects/CoreTypes.cs b/server/csharp/MetaObjects/CoreTypes.cs index 915399f1b9..3bb30debb0 100644 --- a/server/csharp/MetaObjects/CoreTypes.cs +++ b/server/csharp/MetaObjects/CoreTypes.cs @@ -84,6 +84,8 @@ public static class CoreTypes // bundle so every existing model loads unchanged. MetaObjects.Core.Rules.RulesMetaDataProvider.Instance, MetaObjects.Persistence.ViewExpressions.ViewExpressionsMetaDataProvider.Instance, + MetaObjects.Core.Reporting.ReportingMetaDataProvider.Instance, + MetaObjects.Core.Requirement.RequirementsMetaDataProvider.Instance, ]; /// @@ -274,8 +276,8 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) Wildcard(TYPE_ATTR), Wildcard(TYPE_VALIDATOR), Wildcard(TYPE_TEMPLATE), - // Capability requirements are declared beside the entities they describe. - Wildcard(TYPE_REQUIREMENT), + // `requirement` (the requirements pack) and `api` (the rules pack) are + // admitted by their packs' `extends`. ], (tid, n) => new MetaRoot(tid, n), [])); @@ -311,6 +313,8 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) ]; foreach (string subType in OBJECT_SUBTYPES) { + // object.report is the reporting pack's (it folds the registered base). + if (subType == OBJECT_SUBTYPE_REPORT) continue; // FR-033: object.value's @normalize (the object-level default normalization // mode for its enum fields' tolerant extract) is re-homed to the // metaobjects-prompt concern provider (reads prompt.json's object.value @@ -326,7 +330,6 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) List objectAttrs = subType switch { OBJECT_SUBTYPE_PROJECTION => [.. ObjectSchema.ObjectAttrs, ObjectSchema.ProjectionFilterAttr, ObjectSchema.CollectionNameAttr], - OBJECT_SUBTYPE_REPORT => [.. ObjectSchema.ObjectAttrs, .. ReportingSchema.ReportAttrs, ObjectSchema.CollectionNameAttr], OBJECT_SUBTYPE_ENTITY => [.. ObjectSchema.ObjectAttrs, ObjectSchema.CollectionNameAttr], _ => ObjectSchema.ObjectAttrs.ToList(), }; @@ -607,89 +610,8 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) whenToUse: "You need a DB index for query performance (fast lookups/sorts) but NOT uniqueness enforcement. @fields names the indexed columns; the db provider adds @orders / @expr / @where / @using for physical tuning.")); - // requirement — 2 subtypes. The axis is CHECK POLARITY, a genuine behaviour - // difference (ADR-0037 §2): `functional` is checked by EXISTENCE (nothing - // implements it -> fail), `architectural` by UNIVERSALITY (something violates - // it -> fail). Registered rather than hand-parsed because the capability ledger - // IS a metadata model: a closed status enum and a list of FQN references to - // model nodes are exactly `allowedValues` plus reference resolution, both of - // which this registry already owns (requirements-as-metadata ruling amendment 3). - // A single MetaRequirement class backs both subtypes (mirrors source/template). - // Descriptions + whenToUse + the structural child graph come from the embedded - // spec/metamodel/requirement.json via ApplySpecDescriptions — the placeholder - // description below is overwritten there, never the shipped prose. - foreach (string subType in REQUIREMENT_SUBTYPES) - { - // Hierarchy IS nesting, not a parent attribute: an L1 solution CONTAINS its - // L2 segments. BOTH subtypes nest — an architectural requirement is flat by - // DEFAULT rather than by rule, and may opt into a levelled tree so a quality - // taxonomy can organise the non-functional set the same way a capability - // taxonomy organises the functional one. Declaring the child rule on - // `functional` only was an omission, not a design: it made an architectural - // node nestable under a FUNCTIONAL parent but never under another - // architectural one. - List requirementRules = [Wildcard(TYPE_ATTR), Wildcard(TYPE_REQUIREMENT)]; - - registry.Register( - Def( - TYPE_REQUIREMENT, - subType, - $"Requirement ({subType})", - requirementRules, - (tid, n) => new MetaRequirement(tid, n), - RequirementSchema.RequirementAttrsMap.TryGetValue(subType, out var reqAttrs) - ? reqAttrs.ToList() - : [])); - } - - // NOTE: @implementedBy is deliberately NOT declared as a loader `references` - // descriptor. That pass always ERRORS on an unresolved target, and a - // requirement with status `planned` names nodes that do not exist YET, so declaring - // nodes that are GONE — declaring it here would make the entries that carry - // the mechanism's only controlled evidence fail to load. The loader owns what - // is unconditional (the status enum, shape, levels); `meta verify` owns the - // status-conditional resolution, where the severity actually depends on data. - - // FR-044 reporting vocabulary — dimension / measure / segment. Declared as children - // of `object.entity` (spec/metamodel/object.json), never root-level, so no root - // wildcard is added above. Three types in one provider file (reporting.json) - // because they are one vocabulary: a report names dimensions and measures, and - // both may reference a segment. `measure.derived` is FR-037 R5's first arithmetic - // wave (R13). Descriptions + whenToUse come from the embedded reporting.json via - // ApplySpecDescriptions; the placeholder descriptions below are overwritten there. - foreach (string subType in DIMENSION_SUBTYPES) - { - registry.Register( - Def( - TYPE_DIMENSION, - subType, - $"Dimension ({subType})", - [Wildcard(TYPE_ATTR)], - (tid, n) => new MetaDimension(tid, n), - ReportingSchema.DimensionAttrsMap[subType].ToList())); - } - foreach (string subType in MEASURE_SUBTYPES) - { - registry.Register( - Def( - TYPE_MEASURE, - subType, - $"Measure ({subType})", - [Wildcard(TYPE_ATTR)], - (tid, n) => new MetaMeasure(tid, n), - ReportingSchema.MeasureAttrsMap[subType].ToList())); - } - foreach (string subType in SEGMENT_SUBTYPES) - { - registry.Register( - Def( - TYPE_SEGMENT, - subType, - $"Segment ({subType})", - [Wildcard(TYPE_ATTR)], - (tid, n) => new MetaSegment(tid, n), - ReportingSchema.SegmentAttrsMap[subType].ToList())); - } + // requirement and the reporting vocabulary (dimension / measure / segment / object.report) + // are their own packs: RequirementsMetaDataProvider and ReportingMetaDataProvider. // template — fourth-pillar metatype (FR-004). prompt + output + toolcall; // attr-only children. A single MetaTemplate class backs every subtype (mirrors diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs index 7f8c7f309e..a18ad72619 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs @@ -39,6 +39,9 @@ // 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) +// P3 ERR_TRANSITION_NAME_COLLISION two permission points ask the policy about one permission name, and at +// least one of the two names is derived (two DECLARED @permission values +// may be equal: that sharing is the point) // 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 @@ -369,9 +372,57 @@ public static IReadOnlyList ValidateRules(MetaData root) } CheckApiRoutes(ops, sink); } + CheckPermissionNames(root, sink); return sink.Errors; } + private sealed record PermissionPoint(MetaData Node, bool Derived); + + /// The name a permission point asks the policy about: its @permission, else <package>.<path> + /// (the path is the operation name, or <Entity>.<transition> for a transition's command). The package + /// prefix is dropped when there is none. :: and . both separate path segments, so they compare equal. + private static (string Name, bool Derived) PermissionNameOf(MetaData node, MetaData owner, string path) + { + var declared = node.Attr(OPERATION_ATTR_PERMISSION) as string; + var pkg = NamingRefs.EffectivePackageOf(NamingRefs.TopLevelNodeOf(owner)); + var name = declared ?? (pkg.Length == 0 ? path : $"{pkg}.{path}"); + return (name.Replace("::", "."), declared is null); + } + + /// P3: two permission points, one name, at least one of the two derived. Points are every non-public + /// operation and every transition of a live concrete entity. Compared case-sensitively (a grant key is exact). + /// Transitions register first, so the error lands on the operation when an operation meets a transition. + private static void CheckPermissionNames(MetaData root, RulesErrorSink sink) + { + var byName = new Dictionary>(StringComparer.Ordinal); + void Register(MetaData node, MetaData owner, string path) + { + if (node.Attr(OPERATION_ATTR_PUBLIC) is true) return; + var (name, derived) = PermissionNameOf(node, owner, path); + if (!byName.TryGetValue(name, out var points)) byName[name] = points = []; + var clash = points.FirstOrDefault(q => + !ReferenceEquals(q.Node, node) && (derived || q.Derived) + && !(node.Type == TYPE_OPERATION && q.Node.Type == TYPE_OPERATION && SameOperation(q.Node, node))); + if (clash is not null) + { + sink.Add(node, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + $"{node.Type}.{node.SubType} \"{RulesLabel(node)}\" asks the policy about the permission name \"{name}\", which {clash.Node.Type}.{clash.Node.SubType} \"{RulesLabel(clash.Node)}\" also asks about, and one of the two names is derived rather than declared; declare a distinct @permission on one, or rename it."); + } + points.Add(new PermissionPoint(node, derived)); + } + foreach (var entity in root.Children()) + { + if (entity.Type != TYPE_OBJECT || entity.SubType != OBJECT_SUBTYPE_ENTITY) continue; + if (entity.IsAbstract || !Lifecycles.LifecycleIsLive(entity)) continue; + foreach (var t in Lifecycles.EntityTransitions(entity)) Register(t, entity, $"{entity.Name}.{t.Name}"); + } + foreach (var api in root.Children()) + { + if (api.Type != TYPE_API) continue; + foreach (var op in api.Children().Where(c => c.Type == TYPE_OPERATION)) Register(op, api, op.Name); + } + } + /// 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); diff --git a/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs b/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs index 7d2682ad0c..413070e5c1 100644 --- a/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs @@ -75,12 +75,6 @@ public static class OriginSchema IsArray: true, Description: "Ordering keys as 'field[:asc|desc]' over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only)."), - // Origin @segment. - new AttrSchema( - Name: OriginConstants.ORIGIN_ATTR_SEGMENT, - ValueType: AttrConstants.ATTR_SUBTYPE_STRING, - Required: false, - Description: "Optional name of a segment.filter declared on the related entity; its predicate scopes the related rows, ANDed with @filter."), ]; // #195 — computed: a row-level value via a structured @expr tree (attr.expression). @@ -121,12 +115,6 @@ public static class OriginSchema Required: false, Description: "Optional structured predicate scoping which related rows are eligible for selection."), - // Origin @segment. - new AttrSchema( - Name: OriginConstants.ORIGIN_ATTR_SEGMENT, - ValueType: AttrConstants.ATTR_SUBTYPE_STRING, - Required: false, - Description: "Optional name of a segment.filter declared on the related entity; its predicate scopes the related rows, ANDed with @filter."), ]; // function: a call of a database function the project owns. diff --git a/server/csharp/MetaObjects/Registry.cs b/server/csharp/MetaObjects/Registry.cs index 742b24cd88..2990893fc1 100644 --- a/server/csharp/MetaObjects/Registry.cs +++ b/server/csharp/MetaObjects/Registry.cs @@ -372,8 +372,19 @@ public void Register(TypeDefinition def) // ADR-0062: refuse a name another provider already put on a related slot, BEFORE // the definition becomes visible, so a refused registration leaves no trace. + // An attribute folded in unchanged from the registered `.base` (a pack's + // subtype with extendsBase, e.g. object.report) is the base owner's, not a new + // claim: it is not checked against the registering provider, and is stamped with + // the owner the base attribute already has. + // Reference identity, not value equality: a distinct attr that merely looks the same is a claim. + HashSet baseAttrs = def.TypeId.SubType == SUBTYPE_BASE + ? new HashSet(ReferenceEqualityComparer.Instance) + : _defs.TryGetValue($"{def.TypeId.Type}.{SUBTYPE_BASE}", out TypeDefinition? baseDef) + ? new HashSet(baseDef.Attributes, ReferenceEqualityComparer.Instance) + : new HashSet(ReferenceEqualityComparer.Instance); foreach (AttrSchema attr in def.Attributes) { + if (baseAttrs.Contains(attr)) continue; CheckAttrOwnership(def.TypeId.Type, def.TypeId.SubType, attr.Name); } @@ -384,6 +395,14 @@ public void Register(TypeDefinition def) // own AttrSchema list before calling Register()). foreach (AttrSchema attr in def.Attributes) { + if (baseAttrs.Contains(attr)) + { + if (_attrProvenance.TryGetValue((def.TypeId.Type, SUBTYPE_BASE, attr.Name), out string? baseOwner)) + { + _attrProvenance[(def.TypeId.Type, def.TypeId.SubType, attr.Name)] = baseOwner; + } + continue; + } StampAttrProvenance(def.TypeId.Type, def.TypeId.SubType, attr.Name); } diff --git a/server/csharp/MetaObjects/SpecMetamodel/object.json b/server/csharp/MetaObjects/SpecMetamodel/object.json index ddf3c6eeec..ad288e6015 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/object.json +++ b/server/csharp/MetaObjects/SpecMetamodel/object.json @@ -26,9 +26,6 @@ "children": [ { "type": "relationship", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "template", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } @@ -56,22 +53,6 @@ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] - }, - { - "type": "object", - "subType": "report", - "extendsBase": true, - "description": "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.", - "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", - "children": [ - { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, - { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, - { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, - { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } - ] } ] } diff --git a/server/csharp/MetaObjects/SpecMetamodel/origin.json b/server/csharp/MetaObjects/SpecMetamodel/origin.json index c4fde970f9..4d7e5aea16 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/origin.json +++ b/server/csharp/MetaObjects/SpecMetamodel/origin.json @@ -28,7 +28,6 @@ { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -52,8 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." } ] } ] diff --git a/server/csharp/MetaObjects/SpecMetamodel/reporting.json b/server/csharp/MetaObjects/SpecMetamodel/reporting.json index adbe87f9ed..10a888b0c3 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/reporting.json +++ b/server/csharp/MetaObjects/SpecMetamodel/reporting.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-reporting", "types": [ { "type": "dimension", "subType": "attribute", "description": "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.", @@ -46,6 +46,35 @@ "whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 1, "max": 1, "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } + ] }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "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.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, + { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, + { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, + { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + } + ], + "extends": [ + { "type": "object", "subType": "entity", "children": [ + { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null } + ] }, + { "type": "origin", "subType": "aggregate", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + ] }, + { "type": "origin", "subType": "first", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] } diff --git a/server/csharp/MetaObjects/SpecMetamodel/requirement.json b/server/csharp/MetaObjects/SpecMetamodel/requirement.json index f3017fd78d..a74ebd5758 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/requirement.json +++ b/server/csharp/MetaObjects/SpecMetamodel/requirement.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-requirements", "types": [ { "type": "requirement", @@ -185,5 +185,10 @@ } ] } + ], + "extends": [ + { "type": "metadata", "subType": "root", "children": [ + { "type": "requirement", "subType": "*", "name": "*", "min": 0, "max": null } + ] } ] } 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 3debdc38e1..ddfd1e888f 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/MetaData.java +++ b/server/java/metadata/src/main/java/com/metaobjects/MetaData.java @@ -420,18 +420,20 @@ private void validateName(String name) { // accept these; the cross-port contract requires Java match. Also // accept FQN-qualified attr names (`pkg::name::attr` form) which the // loader synthesises for cross-package attr lookups. - if ("attr".equals(type)) { + // An operation's name may be dotted too ("Order.open"): TS, C# and Python accept it, and the + // rules pass (P3) must see it to flag a derived permission name that equals a transition's. + if ("attr".equals(type) || "operation".equals(type)) { if (name.contains("::")) { for (String part : name.split("::")) { if (!part.matches("^[a-zA-Z][a-zA-Z0-9_.]*$")) { throw new IllegalArgumentException( - "Invalid attr name part '" + part + "' in '" + name + "Invalid " + type + " name part '" + part + "' in '" + name + "': must follow pattern ^[a-zA-Z][a-zA-Z0-9_.]*$"); } } } else if (!name.matches("^[a-zA-Z][a-zA-Z0-9_.]*$")) { throw new IllegalArgumentException( - "Invalid attr name '" + name + "': must follow pattern ^[a-zA-Z][a-zA-Z0-9_.]*$"); + "Invalid " + type + " name '" + name + "': must follow pattern ^[a-zA-Z][a-zA-Z0-9_.]*$"); } return; } 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..c1d632902e 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java +++ b/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java @@ -125,7 +125,6 @@ public static void registerTypes(MetaDataRegistry registry) { .optionalChild(MetaField.TYPE_FIELD, "*", "*") .optionalChild(MetaValidator.TYPE_VALIDATOR, "*", "*") .optionalChild(com.metaobjects.template.TemplateConstants.TYPE_TEMPLATE, "*", "*") - .optionalChild(com.metaobjects.requirement.MetaRequirement.TYPE_REQUIREMENT, "*", "*") .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/loader/RulesValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java index a1fb9e223a..7358a4b167 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java @@ -430,9 +430,66 @@ static List validate(MetaRoot root) { } checkApiRoutes(ops, sink); } + checkPermissionNames(root, sink); return sink.errors; } + /** One permission point: a node and whether its permission name is derived (no @permission). */ + private record PermissionPoint(MetaData node, boolean derived) {} + + /** + * P3: two permission points ask the policy about one permission name, and at least one of the two + * names is derived. Points are every non-public operation and every transition of a live concrete + * entity (a transition derives a command each). A name is the node's {@code @permission}, else + * {@code .} (the path is the operation name, or {@code Entity.transition}); {@code ::} + * and {@code .} both separate segments so they compare equal. Compared case-sensitively. Transitions + * register first, so the error lands on the operation when an operation meets a transition. Two + * DECLARED values may be equal: that sharing is the point. + */ + private static void checkPermissionNames(MetaRoot root, Sink sink) { + Map> byName = new java.util.HashMap<>(); + for (MetaData entity : root.getChildren(MetaData.class, true)) { + if (!Lifecycles.isEntity(entity) || Lifecycles.isAbstract(entity) || !Lifecycles.lifecycleIsLive(entity)) continue; + for (MetaData t : Lifecycles.entityTransitions(entity)) { + registerPermissionPoint(t, entity, entity.getShortName() + "." + t.getShortName(), byName, sink); + } + } + 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())) { + registerPermissionPoint(op, api, op.getShortName(), byName, sink); + } + } + } + } + + private static void registerPermissionPoint(MetaData node, MetaData owner, String path, + Map> byName, Sink sink) { + if (flag(node, ApiConstants.ATTR_PUBLIC)) return; + String declared = Lifecycles.stringValue(node, ApiConstants.ATTR_PERMISSION); + String pkg = References.effectivePackageOf(owner); + String raw = declared != null ? declared : pkg.isEmpty() ? path : pkg + "." + path; + String name = raw.replace("::", "."); + boolean derived = declared == null; + List points = byName.computeIfAbsent(name, k -> new ArrayList<>()); + PermissionPoint clash = null; + for (PermissionPoint q : points) { + if (q.node() == node || !(derived || q.derived())) continue; + if (ApiConstants.TYPE_OPERATION.equals(node.getType()) && ApiConstants.TYPE_OPERATION.equals(q.node().getType()) + && sameOperation(q.node(), node)) continue; + clash = q; + break; + } + if (clash != null) { + sink.add(node, ErrorCode.ERR_TRANSITION_NAME_COLLISION, + node.getType() + "." + node.getSubType() + " \"" + label(node) + "\" asks the policy about the permission name \"" + + name + "\", which " + clash.node().getType() + "." + clash.node().getSubType() + " \"" + label(clash.node()) + + "\" also asks about, and one of the two names is derived rather than declared; declare a distinct @permission on one, or rename it."); + } + points.add(new PermissionPoint(node, derived)); + } + /** 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); diff --git a/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java b/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java index 17ccd7f67f..8ea451eef8 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java +++ b/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java @@ -259,27 +259,8 @@ public static void registerEntityValueTypes(MetaDataRegistry registry) { // (ViewExpressionsTypesMetaDataProvider), not to core. }); - // FR-044 — object.report: a fixed combination of dimensions and measures of ONE - // entity (@from), compiled to a read-only view. Its fields are DERIVED, never - // declared (rule R4 in the reporting validation pass); its structural children - // come from spec/metamodel/object.json (extendsBase), like object.projection. - registry.registerType(ReportMetaObject.class, def -> { - def.type(TYPE_OBJECT).subType(SUBTYPE_REPORT) - .description("Report object (derived, read-only) — a declared aggregation of one entity") - .inheritsFrom(TYPE_OBJECT, SUBTYPE_BASE); - def.requiredAttributeWithConstraints(ATTR_REPORT_FROM) - .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); - def.optionalAttributeWithConstraints(ATTR_REPORT_DIMENSIONS) - .ofType(StringAttribute.SUBTYPE_STRING).asArray(); - def.requiredAttributeWithConstraints(ATTR_REPORT_MEASURES) - .ofType(StringAttribute.SUBTYPE_STRING).asArray(); - def.optionalAttributeWithConstraints(ATTR_REPORT_SEGMENT) - .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); - def.optionalAttributeWithConstraints(ATTR_FILTER) - .ofType(FilterAttribute.SUBTYPE_FILTER).asSingle(); - def.optionalAttributeWithConstraints(ATTR_REPORT_SPINE) - .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); - }); + // object.report is registered by the reporting pack (ReportingTypesMetaDataProvider -> + // ReportMetaObject.registerTypes), not by core. // ADR-0006 Rule 1 — bare `object:` YAML key fuses to `object.entity`. registry.setDefaultSubType(TYPE_OBJECT, SUBTYPE_ENTITY); diff --git a/server/java/metadata/src/main/java/com/metaobjects/object/ReportMetaObject.java b/server/java/metadata/src/main/java/com/metaobjects/object/ReportMetaObject.java index a5d3f3562e..3a138fd3a2 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/object/ReportMetaObject.java +++ b/server/java/metadata/src/main/java/com/metaobjects/object/ReportMetaObject.java @@ -15,7 +15,10 @@ */ package com.metaobjects.object; +import com.metaobjects.attr.FilterAttribute; +import com.metaobjects.attr.StringAttribute; import com.metaobjects.object.value.ValueObject; +import com.metaobjects.registry.MetaDataRegistry; /** * object.report — a declared report (FR-044): a fixed combination of the dimensions and @@ -32,5 +35,32 @@ public class ReportMetaObject extends AbstractObjectRepresentation { public ReportMetaObject(String name) { super(MetaObject.SUBTYPE_REPORT, name); } protected ReportMetaObject(String subType, String name) { super(subType, name); } + + /** + * Register {@code object.report} (FR-044). Called by the reporting pack's provider, not by + * core: it inherits {@code object.base} from the object-types provider (the cross-definition + * {@code extendsBase}), so the inherited attrs are not a new claim by the reporting pack. Its + * structural children come from spec/metamodel/reporting.json (extendsBase), like + * object.projection. + */ + public static void registerTypes(MetaDataRegistry registry) { + registry.registerType(ReportMetaObject.class, def -> { + def.type(MetaObject.TYPE_OBJECT).subType(MetaObject.SUBTYPE_REPORT) + .description("Report object (derived, read-only) — a declared aggregation of one entity") + .inheritsFrom(MetaObject.TYPE_OBJECT, MetaObject.SUBTYPE_BASE); + def.requiredAttributeWithConstraints(MetaObject.ATTR_REPORT_FROM) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(MetaObject.ATTR_REPORT_DIMENSIONS) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.requiredAttributeWithConstraints(MetaObject.ATTR_REPORT_MEASURES) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.optionalAttributeWithConstraints(MetaObject.ATTR_REPORT_SEGMENT) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(MetaObject.ATTR_FILTER) + .ofType(FilterAttribute.SUBTYPE_FILTER).asSingle(); + def.optionalAttributeWithConstraints(MetaObject.ATTR_REPORT_SPINE) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + } @Override protected Class getDefaultObjectClass() { return ValueObject.class; } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/AggregateOrigin.java b/server/java/metadata/src/main/java/com/metaobjects/origin/AggregateOrigin.java index 54aa097158..9953f9de13 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/origin/AggregateOrigin.java +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/AggregateOrigin.java @@ -63,8 +63,7 @@ public static void registerTypes(MetaDataRegistry registry) { // Optional scoping filter (attr.filter object) → SQL FILTER (WHERE ...). def.optionalAttributeWithConstraints(ATTR_FILTER) .ofType(FilterAttribute.SUBTYPE_FILTER).asSingle(); - def.optionalAttributeWithConstraints(ATTR_SEGMENT) - .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + // @segment is projected onto this type by the reporting pack (reporting.json extends). // #195 collect support: @distinct (dedupe) + @orderBy (element order). def.optionalAttributeWithConstraints(ATTR_DISTINCT) .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/FirstOrigin.java b/server/java/metadata/src/main/java/com/metaobjects/origin/FirstOrigin.java index 024bc824ea..6db029b9f2 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/origin/FirstOrigin.java +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/FirstOrigin.java @@ -54,8 +54,7 @@ public static void registerTypes(MetaDataRegistry registry) { .ofType(StringAttribute.SUBTYPE_STRING).asArray(); def.optionalAttributeWithConstraints(ATTR_FILTER) .ofType(FilterAttribute.SUBTYPE_FILTER).asSingle(); - def.optionalAttributeWithConstraints(ATTR_SEGMENT) - .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + // @segment is projected onto this type by the reporting pack (reporting.json extends). }); } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java index 395ccbbe72..daaf2dc0ab 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java @@ -17,6 +17,9 @@ import com.metaobjects.registry.MetaDataRegistry; import com.metaobjects.registry.MetaDataTypeProvider; +import com.metaobjects.registry.spec.SpecMetamodelReader; + +import java.util.Map; /** * Reporting Types MetaData provider (FR-044). @@ -24,7 +27,7 @@ *

Registers the entity-member reporting vocabulary: {@code dimension.attribute}, * {@code dimension.time}, {@code measure.aggregate}, {@code measure.ratio} and * {@code segment.filter}. {@code object.report} is an object subtype and is registered by - * the object-types provider beside {@code object.projection}. {@code measure.derived} (R13) is + * this pack too (the object-types provider no longer registers it). {@code measure.derived} (R13) is * FR-037 R5's first arithmetic wave.

* *

Depends on {@code core-types} for {@code metadata.base} inheritance.

@@ -39,8 +42,16 @@ public void registerTypes(MetaDataRegistry registry) { RatioMeasure.registerTypes(registry); DerivedMeasure.registerTypes(registry); FilterSegment.registerTypes(registry); + com.metaobjects.object.ReportMetaObject.registerTypes(registry); + // The rules that admit these types on types core owns (dimension/measure/segment under + // object.entity) and the @segment attr on origin.aggregate/origin.first ride in + // reporting.json under the pack's logical id: leaving the pack out leaves none of them. + registry.applyProviderExtends(SpecMetamodelReader.load(), LOGICAL_ID, Map.of()); } + /** The pack's cross-port logical id, the {@code provider} of reporting.json. */ + public static final String LOGICAL_ID = "metaobjects-reporting"; + @Override public String getProviderId() { return "reporting-types"; @@ -48,7 +59,7 @@ public String getProviderId() { @Override public String[] getDependencies() { - return new String[]{"core-types"}; + return new String[]{"core-types", "object-types", "origin-types"}; } @Override diff --git a/server/java/metadata/src/main/java/com/metaobjects/requirement/RequirementTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/requirement/RequirementTypesMetaDataProvider.java index 5b25fb2a4b..fa99c00a7b 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/requirement/RequirementTypesMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/requirement/RequirementTypesMetaDataProvider.java @@ -17,6 +17,9 @@ import com.metaobjects.registry.MetaDataRegistry; import com.metaobjects.registry.MetaDataTypeProvider; +import com.metaobjects.registry.spec.SpecMetamodelReader; + +import java.util.Map; /** * Requirement Types MetaData provider. @@ -34,8 +37,14 @@ public class RequirementTypesMetaDataProvider implements MetaDataTypeProvider { public void registerTypes(MetaDataRegistry registry) { FunctionalRequirement.registerTypes(registry); ArchitecturalRequirement.registerTypes(registry); + // The rule that admits a requirement under metadata.root rides in requirement.json under + // the pack's logical id: leaving the pack out leaves neither the type nor the rule. + registry.applyProviderExtends(SpecMetamodelReader.load(), LOGICAL_ID, Map.of()); } + /** The pack's cross-port logical id, the {@code provider} of requirement.json. */ + public static final String LOGICAL_ID = "metaobjects-requirements"; + @Override public String getProviderId() { return "requirement-types"; 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 8d5d35b026..b642db8037 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 @@ -124,11 +124,11 @@ public class ConformanceTest { * in {@code META-INF/services/com.metaobjects.registry.MetaDataTypeProvider}.

*/ private static final java.util.Map> PROVIDER_ALIASES = - java.util.Map.of( + java.util.Map.ofEntries( // TS/C# expose one "metaobjects-core-types" provider; Java splits it // into per-concern providers (core, fields, attrs, objects, validators, // identity, relationships, sources). - "metaobjects-core-types", List.of( + java.util.Map.entry("metaobjects-core-types", List.of( "core-types", "field-types", "attribute-types", @@ -145,34 +145,40 @@ public class ConformanceTest { // full SPI superset rather than the fixture's declared set. Incomplete // AND unexercised. ProviderAliasCompletenessTest now gates it. "index-types", - "origin-types", - "requirement-types", - // FR-044 reporting vocabulary (dimension / measure / segment). + "origin-types" + )), + // The reporting vocabulary (FR-044: dimension / measure / segment / object.report) + // and the requirements ledger are their own packs, in the default bundle, left out + // of a fixture that does not name them. + java.util.Map.entry("metaobjects-reporting", List.of( "reporting-types" - ), + )), + java.util.Map.entry("metaobjects-requirements", List.of( + "requirement-types" + )), // ADR-0066 business-rules pack (api / operation / binding / transition) and the // rc.21 view-expressions pack (origin.function, @union / @grain on a projection): // their own providers, in the default bundle, left out of a fixture that does not // name them. - "metaobjects-rules", List.of( + java.util.Map.entry("metaobjects-rules", List.of( "rules-types" - ), - "metaobjects-view-expressions", List.of( + )), + java.util.Map.entry("metaobjects-view-expressions", List.of( "view-expressions-types" - ), + )), // The corpus's "metaobjects-db" provider maps to Java's // CoreDBMetaDataProvider (id "database-extensions"), which registers the // physical RDB attributes (@column / @dbType / @dbColumnType / ...). - "metaobjects-db", List.of( + java.util.Map.entry("metaobjects-db", List.of( "database-extensions" - ), + )), // Java registers the documentation provider under the canonical name, so this // is an identity mapping -- present so the map is COMPLETE, which is what // ProviderAliasCompletenessTest gates. Its absence meant a fixture naming this // logical id would not have composed on Java. - "metaobjects-documentation", List.of( + java.util.Map.entry("metaobjects-documentation", List.of( "metaobjects-documentation" - ), + )), // The corpus's "metaobjects-template" provider (TS/C#/Python expose it // under this canonical name — template.* / @responseRef / @xmlText, the // AI prompt-construction vocab) maps to Java's TemplateTypesMetaDataProvider @@ -185,25 +191,24 @@ public class ConformanceTest { // and may ride along with a "metaobjects-template" fixture. Java folds // template-types into "metaobjects-core-types"; the checks are independent // set memberships, so a fixture listing both resolves. - "metaobjects-template", List.of( + java.util.Map.entry("metaobjects-template", List.of( "template-types", "metaobjects-prompt" - ), + )), // FR-033 — the cross-port "metaobjects-ui" / "metaobjects-prompt" concern // providers. Java registers them under their own (already-canonical) ids // via the ServiceLoader SPI, so these are identity aliases documenting the // backing provider — kept explicit so the availability check is honest if // a provider id is ever renamed. - "metaobjects-ui", List.of( + java.util.Map.entry("metaobjects-ui", List.of( com.metaobjects.presentation.ui.UiTypesMetaDataProvider.PROVIDER_ID - ), - "metaobjects-ui-web", List.of( + )), + java.util.Map.entry("metaobjects-ui-web", List.of( com.metaobjects.presentation.ui.UiWebTypesMetaDataProvider.PROVIDER_ID - ), - "metaobjects-prompt", List.of( + )), + java.util.Map.entry("metaobjects-prompt", List.of( com.metaobjects.template.PromptTypesMetaDataProvider.PROVIDER_ID - ) - ); + ))); /** Provider IDs available to the Java harness (via ServiceLoader auto-discovery). */ /** @@ -388,6 +393,12 @@ static void runConformanceChecks(FixtureDiscovery.Fixture fix, if (!fix.requiredProviders.contains("metaobjects-rules")) { packsLeftOut.add("rules-types"); } + if (!fix.requiredProviders.contains("metaobjects-reporting")) { + packsLeftOut.add("reporting-types"); + } + if (!fix.requiredProviders.contains("metaobjects-requirements")) { + packsLeftOut.add("requirement-types"); + } if (!fix.requiredProviders.contains("metaobjects-view-expressions")) { packsLeftOut.add("view-expressions-types"); } diff --git a/server/java/metadata/src/test/java/com/metaobjects/requirement/RequirementsPackLeftOutTest.java b/server/java/metadata/src/test/java/com/metaobjects/requirement/RequirementsPackLeftOutTest.java new file mode 100644 index 0000000000..9815f97440 --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/requirement/RequirementsPackLeftOutTest.java @@ -0,0 +1,78 @@ +package com.metaobjects.requirement; + +import com.metaobjects.MetaDataException; +import com.metaobjects.MetaRoot; +import com.metaobjects.loader.InMemoryStringSource; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.registry.RegistryManifest; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * The requirements ledger is its own pack ({@code metaobjects-requirements}). With the pack in + * the default bundle the gate behaves as before; with it left out, a model with no requirement + * nodes gets an empty, silent ledger and a model that declares one fails at load. + */ +public class RequirementsPackLeftOutTest { + + private static final String PLAIN = """ + {"metadata.root": {"package": "p", "children": [ + {"object.value": {"name": "Thing", "children": [{"field.string": {"name": "label"}}]}} + ]}} + """; + + private static final String WITH_REQUIREMENT = """ + {"metadata.root": {"package": "p", "children": [ + {"object.value": {"name": "Thing", "children": [{"field.string": {"name": "label"}}]}}, + {"requirement.functional": {"name": "labels", "@level": 4, "@status": "planned", + "@statement": "A thing has a label.", "@counterexample": "A thing with no label."}} + ]}} + """; + + private static MetaDataLoader load(String json, boolean packIn) { + MetaDataLoader loader = new MetaDataLoader(LoaderOptions.create(false, false, true), + MetaDataLoader.SUBTYPE_MANUAL, "p"); + if (!packIn) { + loader.setTypeRegistry(RegistryManifest.composeLoaderRegistry(List.of(), List.of("requirement-types"))); + } + loader.init(); + loader.load(List.of(new InMemoryStringSource(json, "meta.p.json"))); + return loader; + } + + @Test + public void defaultBundleLoadsAndCountsTheRequirement() { + MetaRoot root = load(WITH_REQUIREMENT, true).getRoot(); + RequirementCheck.Scan scan = RequirementCheck.scan(root, new RequirementCheck.Options(null, false)); + assertEquals(1, scan.addressed().size()); + } + + @Test + public void leftOutAModelWithNoRequirementsHasAnEmptySilentLedger() { + MetaRoot root = load(PLAIN, false).getRoot(); + assertNotNull(root); + RequirementCheck.Scan scan = RequirementCheck.scan(root, new RequirementCheck.Options(null, false)); + assertTrue(scan.addressed().isEmpty()); + assertTrue(RequirementCheck.check(root, scan).isEmpty()); + } + + @Test + public void leftOutAModelThatDeclaresARequirementFailsAtLoad() { + List codes = new java.util.ArrayList<>(); + try { + for (MetaDataException e : load(WITH_REQUIREMENT, false).getErrors()) { + codes.add(e.getCode().map(Enum::name).orElse("")); + } + } catch (MetaDataException e) { + codes.add(e.getCode().map(Enum::name).orElse("")); + } + assertTrue(codes.toString(), codes.contains("ERR_UNKNOWN_TYPE") || codes.contains("ERR_UNKNOWN_SUBTYPE")); + } +} diff --git a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java index 8941f9319f..6bbde3ff4d 100644 --- a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java +++ b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java @@ -2,7 +2,14 @@ import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; +import com.github.mustachejava.DefaultMustacheVisitor; import com.github.mustachejava.MustacheException; +import com.github.mustachejava.MustacheVisitor; +import com.github.mustachejava.TemplateContext; +import com.github.mustachejava.codes.ValueCode; +import com.github.mustachejava.reflect.Guard; +import com.github.mustachejava.reflect.MissingWrapper; +import com.github.mustachejava.reflect.ReflectionObjectHandler; import java.io.IOException; import java.io.StringReader; @@ -75,6 +82,16 @@ public String render(RenderRequest req) { String rendered; try { DefaultMustacheFactory factory = new DefaultMustacheFactory() { + @Override + public MustacheVisitor createMustacheVisitor() { + return new DefaultMustacheVisitor(this) { + @Override + public void value(TemplateContext tc, String variable, boolean encoded) { + list.add(new CheckedValueCode(tc, this.df, variable, encoded)); + } + }; + } + @Override public void encode(String value, Writer writer) { try { @@ -84,6 +101,7 @@ public void encode(String value, Writer writer) { } } }; + factory.setObjectHandler(new MissingVariableObjectHandler()); Mustache compiled = factory.compile(new StringReader(expanded), refOrInline(req)); StringWriter writer = new StringWriter(); // Derived `has` accessors are part of the payload contract, not of the @@ -93,6 +111,10 @@ public void encode(String value, Writer writer) { compiled.execute(writer, PayloadAccessors.withDerivedAccessors(req.payload())).flush(); rendered = writer.toString(); } catch (MustacheException | IOException e) { + // A missing variable is raised from inside the engine, which wraps it; surface it as is. + for (Throwable t = e; t != null; t = t.getCause()) { + if (t instanceof RenderException re) throw re; + } throw new RenderException("Mustache compile/execute failed", e); } @@ -180,4 +202,41 @@ private static String preExpandPartials(String text, Provider provider, Deque guards) { + return new AbsentWrapper(name, guards.toArray(new Guard[0])); + } + } + + /** + * A variable tag whose name is absent from the payload raises, with the message the opt-in + * verify gate uses, so a typo like {@code {{nmae}}} fails on every render path. Section tags + * stay silent: an absent section is simply falsy. + */ + private static final class CheckedValueCode extends ValueCode { + CheckedValueCode(TemplateContext tc, DefaultMustacheFactory df, String variable, boolean encoded) { + super(tc, df, variable, encoded); + } + + @Override + public Writer execute(Writer writer, List scopes) { + if (!returnThis && oh.find(name, scopes) instanceof AbsentWrapper) { + throw new RenderException( + "render verify failed: " + Verify.ERR_VAR_NOT_ON_PAYLOAD + " (" + name + ")"); + } + return super.execute(writer, scopes); + } + } } diff --git a/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java b/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java index 9171911c6d..0b404b074e 100644 --- a/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java +++ b/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java @@ -18,6 +18,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; /** * Cross-port render-conformance GATE — asserts Java's render output is @@ -63,6 +65,7 @@ public static List fixtures() throws IOException { try (Stream s = Files.list(FIXTURES_DIR)) { return s.filter(Files::isDirectory) .filter(d -> Files.isRegularFile(d.resolve("expected.txt")) + || Files.isRegularFile(d.resolve("expected-error.txt")) || Files.isRegularFile(d.resolve("expected/rendered.txt"))) .sorted() .map(p -> new Object[]{p.getFileName().toString(), p}) @@ -100,6 +103,22 @@ public void compareAgainstTsBaseline() throws IOException { ? new FilesystemProvider(fixtureDir) : new InMemoryProvider(Map.of()); + // A fixture carrying expected-error.txt must FAIL to render, and the message must contain + // the file's trimmed text (a missing template variable raises on every render path). + Path expectedErrorPath = fixtureDir.resolve("expected-error.txt"); + if (Files.isRegularFile(expectedErrorPath)) { + String want = Files.readString(expectedErrorPath, StandardCharsets.UTF_8).trim(); + try { + new Renderer().render(new RenderRequest( + template, null, payload, provider, format, null, null)); + fail("fixture '" + name + "' must fail to render with: " + want); + } catch (RenderException e) { + assertTrue("error for '" + name + "' must contain '" + want + "' but was: " + e.getMessage(), + e.getMessage().contains(want)); + } + return; + } + String actual = new Renderer().render(new RenderRequest( template, null, payload, provider, format, null, null)); String expected = Files.readString(expectedPath, StandardCharsets.UTF_8); diff --git a/server/java/render/src/test/java/com/metaobjects/render/RenderSnapshotTest.java b/server/java/render/src/test/java/com/metaobjects/render/RenderSnapshotTest.java index 9c5cddda95..0c8a077723 100644 --- a/server/java/render/src/test/java/com/metaobjects/render/RenderSnapshotTest.java +++ b/server/java/render/src/test/java/com/metaobjects/render/RenderSnapshotTest.java @@ -95,6 +95,9 @@ public void rendersToSnapshot() throws IOException { ? new FilesystemProvider(fixtureDir) : new InMemoryProvider(Map.of()); + // An expected-error.txt fixture is gated by RenderCrossPortReportTest; it has no snapshot. + if (Files.isRegularFile(fixtureDir.resolve("expected-error.txt"))) return; + String actual = new Renderer().render(new RenderRequest( template, null, payload, provider, format, null, null)); diff --git a/server/java/render/src/test/java/com/metaobjects/render/TypedPayloadRenderTest.java b/server/java/render/src/test/java/com/metaobjects/render/TypedPayloadRenderTest.java index da6b8b3f15..bc7fa1b879 100644 --- a/server/java/render/src/test/java/com/metaobjects/render/TypedPayloadRenderTest.java +++ b/server/java/render/src/test/java/com/metaobjects/render/TypedPayloadRenderTest.java @@ -130,7 +130,16 @@ public void hasFieldGateWorksOnBeanElementsLikeOnMaps() { @Test public void getClassIsNotExposedOnABean() { - assertEquals("[]", "[" + render("{{class}}{{getClass}}", new BItem("a")) + "]"); + // getClass is not a payload member, so the tag is a MISSING variable and raises (it must + // not render the class name). + for (String tag : List.of("{{class}}", "{{getClass}}")) { + try { + render(tag, new BItem("a")); + org.junit.Assert.fail(tag + " must not resolve on a bean"); + } catch (RenderException e) { + org.junit.Assert.assertTrue(e.getMessage(), e.getMessage().contains("ERR_VAR_NOT_ON_PAYLOAD")); + } + } } // ---- The overlay adds names; it never takes any away ----------------------------------- diff --git a/server/java/render/src/test/resources/snapshots/render-dotted-path-lookup.txt b/server/java/render/src/test/resources/snapshots/render-dotted-path-lookup.txt index 06ee3a698e..e051441bf1 100644 --- a/server/java/render/src/test/resources/snapshots/render-dotted-path-lookup.txt +++ b/server/java/render/src/test/resources/snapshots/render-dotted-path-lookup.txt @@ -1,5 +1,3 @@ name: Ada email: ada@example.test role: admin -missing-leaf: [] -missing-mid: [] diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index 25f82745aa..72b4012a04 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -260,8 +260,6 @@ def _register_subtypes( child_rules=[ ChildRule(TYPE_FIELD, "*"), ChildRule(TYPE_OBJECT, "*"), - # Capability requirements are declared beside the entities they describe. - ChildRule(TYPE_REQUIREMENT, "*"), ChildRule(TYPE_TEMPLATE, "*"), ChildRule(TYPE_VALIDATOR, "*"), ], @@ -317,6 +315,8 @@ def _register_subtypes( # TypeRegistry.extend (prompt.json declares it on object.value), matching the TS # promptProvider split. object.value carries only the shared object attrs in core. for _obj_sub in OBJECT_SUBTYPES: + if _obj_sub == OBJECT_SUBTYPE_REPORT: + continue # object.report is the reporting pack's (reporting_provider) core_provider.add( TypeDefinition( type=TYPE_OBJECT, @@ -351,147 +351,6 @@ def _register_subtypes( ) break -# FR-044 — object.report: declared dimensions x measures of ONE entity (@from), -# compiled to a read-only view. Its fields and identity are DERIVED (the loader -# refuses declared ones, R4), so it carries the projection's child set (no -# relationship / template). object.json's report block (extendsBase) is the -# strict graph the spec pass re-derives onto this def; it declares ONLY the five -# report attrs, so the shared discriminator attrs are pruned exactly as on -# projection. Mirrors the TS object provider. -for _def in core_provider._defs: # noqa: SLF001 (provider build-time enrichment) - if _def.type == TYPE_OBJECT and _def.sub_type == OBJECT_SUBTYPE_REPORT: - _def.child_rules[:] = list(_PROJECTION_CHILD_RULES) - _def.attrs.extend( - [ - AttrSchema(name=OBJECT_REPORT_ATTR_FROM, value_type=ATTR_SUBTYPE_STRING, required=True), - AttrSchema( - name=OBJECT_REPORT_ATTR_DIMENSIONS, - value_type=ATTR_SUBTYPE_STRING, - required=False, - is_array=True, - ), - AttrSchema( - name=OBJECT_REPORT_ATTR_MEASURES, - value_type=ATTR_SUBTYPE_STRING, - required=True, - is_array=True, - ), - AttrSchema(name=OBJECT_REPORT_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), - AttrSchema(name=OBJECT_REPORT_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), - # R8: the to-one path from @from whose entity supplies the report's rows. - AttrSchema(name=OBJECT_REPORT_ATTR_SPINE, value_type=ATTR_SUBTYPE_STRING, required=False), - ] - ) - break - -# FR-044 reporting vocabulary — dimension / measure / segment. Declared as -# children of object.entity (spec/metamodel/object.json — the strict-children -# pass derives the entity's dimension/measure/segment placements from it), never -# root-level, so the root keeps its five wildcards. One vocabulary, one block: a -# report names dimensions and measures, and both may reference a segment. -# measure.derived is NOT registered (it waits for FR-037 R5). Attr scoping is -# per-subtype exactly as spec/metamodel/reporting.json declares it. -_DIMENSION_COMMON_ATTRS = [ - AttrSchema(name=REPORTING_ATTR_OF, value_type=ATTR_SUBTYPE_STRING, required=True), - AttrSchema(name=REPORTING_ATTR_VIA, value_type=ATTR_SUBTYPE_STRING, required=False), -] -core_provider.add( - TypeDefinition( - type=TYPE_DIMENSION, - sub_type=DIMENSION_SUBTYPE_ATTRIBUTE, - factory=MetaDimension, - attrs=list(_DIMENSION_COMMON_ATTRS), - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) -core_provider.add( - TypeDefinition( - type=TYPE_DIMENSION, - sub_type=DIMENSION_SUBTYPE_TIME, - factory=MetaDimension, - attrs=[ - *_DIMENSION_COMMON_ATTRS, - # Weeks start Monday (ISO-8601) in every lowering; 'hour' is refused on - # a field.date by the loader (D4), not by the closed set. - AttrSchema( - name=REPORTING_ATTR_GRAINS, - value_type=ATTR_SUBTYPE_STRING, - required=True, - is_array=True, - allowed_values=TIME_GRAINS, - ), - ], - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) -core_provider.add( - TypeDefinition( - type=TYPE_MEASURE, - sub_type=MEASURE_SUBTYPE_AGGREGATE, - factory=MetaMeasure, - attrs=[ - AttrSchema( - name=REPORTING_ATTR_AGG, - value_type=ATTR_SUBTYPE_STRING, - required=True, - allowed_values=MEASURE_AGGS, - ), - # isArray: a bare string coerces to a one-element list (the tuple form - # is a distinct count, M2). Optional (M0): only @agg any/all may omit - # it, to quantify their @filter/@segment over the rows instead of - # aggregating a column. - AttrSchema( - name=REPORTING_ATTR_OF, - value_type=ATTR_SUBTYPE_STRING, - required=False, - is_array=True, - ), - AttrSchema(name=REPORTING_ATTR_DISTINCT, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), - AttrSchema(name=REPORTING_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), - AttrSchema(name=REPORTING_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), - # What the measure reads when it would otherwise be null; M7/M8 decide where it is legal. - AttrSchema(name=REPORTING_ATTR_DEFAULT, value_type=ATTR_SUBTYPE_INT, required=False), - ], - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) -core_provider.add( - TypeDefinition( - type=TYPE_MEASURE, - sub_type=MEASURE_SUBTYPE_RATIO, - factory=MetaMeasure, - attrs=[ - AttrSchema(name=REPORTING_ATTR_NUMERATOR, value_type=ATTR_SUBTYPE_STRING, required=True), - AttrSchema(name=REPORTING_ATTR_DENOMINATOR, value_type=ATTR_SUBTYPE_STRING, required=True), - AttrSchema(name=REPORTING_ATTR_DEFAULT, value_type=ATTR_SUBTYPE_INT, required=False), - ], - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) -# FR-044 R13: measure.derived — FR-037 R5's first arithmetic wave; no @default. -core_provider.add( - TypeDefinition( - type=TYPE_MEASURE, - sub_type=MEASURE_SUBTYPE_DERIVED, - factory=MetaMeasure, - attrs=[ - AttrSchema(name=REPORTING_ATTR_EXPR, value_type=ATTR_SUBTYPE_EXPRESSION, required=True), - ], - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) -core_provider.add( - TypeDefinition( - type=TYPE_SEGMENT, - sub_type=SEGMENT_SUBTYPE_FILTER, - factory=MetaSegment, - attrs=[ - AttrSchema(name=REPORTING_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=True), - ], - child_rules=[ChildRule(TYPE_ATTR, "*")], - ) -) - # 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). @@ -789,109 +648,6 @@ def _register_subtypes( ) ) -# requirement.* (functional, architectural) — the capability ledger IS a metadata -# model (requirements-as-metadata ruling, amendment 3), so it is registered -# vocabulary rather than a hand-parsed side file: @status is an allowedValues enum -# the LOADER refuses a typo on. The axis is CHECK POLARITY, a genuine behaviour -# difference (ADR-0037 §2): `functional` is checked by EXISTENCE (nothing -# implements it -> fail), `architectural` by UNIVERSALITY (something violates it -# -> fail). Architectural carries no @level — levels come from -# object-in-focus decomposition and an architectural requirement is -# object-independent by definition. -# -# Hierarchy is NESTING, not a parent attr: requirement.functional admits nested -# requirement children (the strict graph in spec/metamodel/requirement.json, which -# _apply_strict_structural_children re-derives onto this registration). -# -# @implementedBy is deliberately NOT declared as a loader `references` descriptor. -# That pass always ERRORS on an unresolved target, and a requirement with status -# `planned` names nodes that do not exist YET — declaring -# it here would make those entries fail to load. The loader owns what is -# unconditional; `verify` owns @implementedBy resolution, whose severity depends on -# @status. -_REQUIREMENT_COMMON_ATTRS = [ - AttrSchema( - name=REQUIREMENT_ATTR_STATUS, - value_type=ATTR_SUBTYPE_STRING, - required=True, - allowed_values=REQUIREMENT_STATUSES, - ), - # What was DECIDED about the outstanding work -- a different question from - # whether the work is done, which is what @status answers. ABSENT means - # UNDECIDED, a real state and the one a review exists to find. - AttrSchema( - name=REQUIREMENT_ATTR_DISPOSITION, - value_type=ATTR_SUBTYPE_STRING, - required=False, - allowed_values=REQUIREMENT_DISPOSITIONS, - ), - # Issue/ticket references for outstanding work. Free-form and never resolved: - # verify has no network, so nothing here is checked to exist. - AttrSchema( - name=REQUIREMENT_ATTR_TRACKED_BY, - value_type=ATTR_SUBTYPE_STRING, - required=False, - is_array=True, - ), - AttrSchema(name=REQUIREMENT_ATTR_STATEMENT, value_type=ATTR_SUBTYPE_STRING, required=True), - AttrSchema(name=REQUIREMENT_ATTR_COUNTEREXAMPLE, value_type=ATTR_SUBTYPE_STRING, required=True), - # FR-039 -- the requirement that REPLACED a retired one. Declared BEFORE - # @implementedBy to match the canonical spec's child order, which the registry - # manifest emits verbatim and every port byte-matches. - AttrSchema( - name=REQUIREMENT_ATTR_SUPERSEDED_BY, - value_type=ATTR_SUBTYPE_STRING, - required=False, - ), - AttrSchema( - name=REQUIREMENT_ATTR_IMPLEMENTED_BY, - value_type=ATTR_SUBTYPE_STRING, - required=False, - is_array=True, - ), -] -core_provider.add( - TypeDefinition( - type=TYPE_REQUIREMENT, - sub_type=REQUIREMENT_SUBTYPE_FUNCTIONAL, - factory=MetaRequirement, - attrs=[ - # REQUIRED on functional: levels are the object-in-focus decomposition - # and a functional requirement always sits at one. - AttrSchema(name=REQUIREMENT_ATTR_LEVEL, value_type=ATTR_SUBTYPE_INT, required=True), - *_REQUIREMENT_COMMON_ATTRS, - ], - child_rules=[ - ChildRule(TYPE_ATTR, "*"), - # Hierarchy IS nesting — an L1 solution contains its L2 segments. - ChildRule(TYPE_REQUIREMENT, "*"), - ], - ) -) -core_provider.add( - TypeDefinition( - type=TYPE_REQUIREMENT, - sub_type=REQUIREMENT_SUBTYPE_ARCHITECTURAL, - factory=MetaRequirement, - attrs=[ - # OPTIONAL on architectural: absent means a flat, object-independent - # policy (the original and still the default form); present opts the - # node into a levelled tree, e.g. a quality taxonomy over the - # non-functional set. Opt-in precisely so that adding a taxonomy over - # existing flat policies cannot invalidate them. - AttrSchema(name=REQUIREMENT_ATTR_LEVEL, value_type=ATTR_SUBTYPE_INT, required=False), - *_REQUIREMENT_COMMON_ATTRS, - ], - child_rules=[ - ChildRule(TYPE_ATTR, "*"), - # BOTH subtypes nest. Declaring this on `functional` only was an - # omission, not a design: it made an architectural node nestable under - # a FUNCTIONAL parent but never under another architectural one. - ChildRule(TYPE_REQUIREMENT, "*"), - ], - ) -) - # relationship.* (base, association, aggregation, composition). # @onDelete / @onUpdate are validated against REFERENTIAL_ACTIONS — kebab-case # values (cascade / set-null / restrict / no-action). Defaults derive from the @@ -1040,7 +796,6 @@ def _register_subtypes( AttrSchema(name=ORIGIN_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), AttrSchema(name=ORIGIN_ATTR_DISTINCT, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), AttrSchema(name=ORIGIN_ATTR_ORDER_BY, value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), - AttrSchema(name=ORIGIN_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), ], child_rules=[ChildRule(TYPE_ATTR, "*")], ) @@ -1072,7 +827,6 @@ def _register_subtypes( AttrSchema(name=ORIGIN_ATTR_VIA, value_type=ATTR_SUBTYPE_STRING, required=False), AttrSchema(name=ORIGIN_ATTR_ORDER_BY, value_type=ATTR_SUBTYPE_STRING, required=True, is_array=True), AttrSchema(name=ORIGIN_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), - AttrSchema(name=ORIGIN_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), ], child_rules=[ChildRule(TYPE_ATTR, "*")], ) @@ -1296,6 +1050,8 @@ def _register_subtypes( from .meta.persistence.view_expressions.view_expressions_provider import ( # noqa: E402 view_expressions_provider, ) +from .meta.core.reporting.reporting_provider import reporting_provider # noqa: E402 +from .meta.core.requirement.requirements_provider import requirements_provider # noqa: E402 core_providers: list[Provider] = [ core_provider, @@ -1310,6 +1066,9 @@ def _register_subtypes( # providers, in the default bundle so every existing model loads unchanged. rules_provider, view_expressions_provider, + # Reporting (FR-044) and requirements are their own packs too, in the default bundle. + reporting_provider, + requirements_provider, ] # #265 — the ids of the LIBRARY providers above, as a frozen set. Consulted by diff --git a/server/python/src/metaobjects/loader/validate_rules.py b/server/python/src/metaobjects/loader/validate_rules.py index bca8e40abb..0d37c3626c 100644 --- a/server/python/src/metaobjects/loader/validate_rules.py +++ b/server/python/src/metaobjects/loader/validate_rules.py @@ -100,7 +100,7 @@ TRANSITION_SUBTYPE_ACTION, ) from ..meta.meta_data import MetaData -from ..naming_refs import effective_package_of +from ..naming_refs import effective_package_of, top_level_node_of from ..meta.persistence.source.meta_source import MetaSource from ..shared.base_types import ( TYPE_API, @@ -494,6 +494,73 @@ def validate_rules(root: MetaData, errors: list[MetaError]) -> None: "rename one, or declare both identically to expose one operation in two APIs.", ) _check_api_routes(ops, sink) + _check_permission_names(root, sink) + + +def _permission_name_of(node: MetaData, owner: MetaData, path: str) -> tuple[str, bool]: + """The name a permission point asks the policy about: its @permission, else + ``.`` (the path is ````, or ``.`` for a + transition's command), with the package prefix dropped when there is none. ``::`` and + ``.`` both separate path segments, so ``p::Order`` + ``open`` and ``p`` + ``Order.open`` + are one name. Returns (name, derived).""" + declared = node.get_meta_attr(OPERATION_ATTR_PERMISSION) + pkg = effective_package_of(top_level_node_of(owner)) + if isinstance(declared, str): + name = declared + else: + name = path if pkg == "" else f"{pkg}.{path}" + return name.replace("::", "."), not isinstance(declared, str) + + +def _check_permission_names(root: MetaData, sink: _Sink) -> None: + """P3: two permission points, one name, at least one of them derived (ADR-0066 section 1). + Points are every non-public operation and every transition of a live concrete entity + (a transition derives a command each). Compared case-sensitively (a grant key is exact). + Transitions register first, so the error lands on the operation when one meets a transition. + Two DECLARED @permission values may be equal: that sharing is the point.""" + by_name: dict[str, list[tuple[MetaData, bool]]] = {} + + def register(node: MetaData, owner: MetaData, path: str) -> None: + if node.get_meta_attr(OPERATION_ATTR_PUBLIC) is True: + return + name, derived = _permission_name_of(node, owner, path) + points = by_name.setdefault(name, []) + clash = next( + ( + q + for q, q_derived in points + if q is not node + and (derived or q_derived) + and not ( + node.type == TYPE_OPERATION and q.type == TYPE_OPERATION and _same_operation(q, node) + ) + ), + None, + ) + if clash is not None: + sink.add( + node, + ErrorCode.ERR_TRANSITION_NAME_COLLISION, + f'{node.type}.{node.sub_type} "{_label(node)}" asks the policy about the permission name ' + f'"{name}", which {clash.type}.{clash.sub_type} "{_label(clash)}" also asks about, and one ' + "of the two names is derived rather than declared; declare a distinct @permission on one, " + "or rename it.", + ) + points.append((node, derived)) + + for entity in root.children(): + if entity.type != TYPE_OBJECT or entity.sub_type != OBJECT_SUBTYPE_ENTITY: + continue + if entity.is_abstract or not lifecycle_is_live(entity): + continue + for t in entity_transitions(entity): + register(t, entity, f"{entity.name}.{t.name}") + for api in root.children(): + if api.type != TYPE_API: + continue + for op in api.children(): + if op.type == TYPE_OPERATION: + register(op, api, op.name) def _ref_identity(op: MetaData, attr: str) -> object: diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 9205b36253..967820edc7 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -153,6 +153,10 @@ ) from ..shared.separators import PACKAGE_SEP from ..meta.core.object.object_constants import ( + OBJECT_PROJECTION_ATTR_GRAIN, + OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL, + OBJECT_PROJECTION_ATTR_UNION, + OBJECT_PROJECTION_ATTR_UNION_ALL, OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE, @@ -231,6 +235,8 @@ def run_validations( _validate_datagrid_filter_values(root, errors) # #207 — object.projection view-level @filter reference validation. _validate_projection_filter(root, errors) + # rc.21 part B — @union / @grain / @grainOrdinal shape rules on object.projection. + _validate_projection_union_and_grain(root, errors) # Origin @segment names a segment of the related entity; a correlated @filter operand names # a base-row field. _validate_origin_segments_and_correlation(root, errors) @@ -1933,6 +1939,115 @@ def _filter_keys(filter_value: object, out: list[str] | None = None) -> list[str return out +def _own_string_list(node: MetaData, name: str) -> list[str]: + # ADR-0039 sanctioned own: a projection's @union names ITS view's shape. + raw = node.attr(name) + if raw is None: + return [] + if isinstance(raw, (list, tuple)): + return [str(x) for x in raw] + return [str(raw)] + + +def _describe_union_field(f: MetaData) -> str: + """One union column as a comparable string: name, subtype, array-ness, @column and an + enum's members and value maps.""" + arr = "[]" if f.resolved_is_array() else "" + col = f.get_meta_attr("column") + out = f"{f.name}: field.{f.sub_type}{arr}" + if isinstance(col, str): + out += f" @column {col}" + if f.sub_type == FIELD_SUBTYPE_ENUM: + shape = [ + f.get_meta_attr(FIELD_ATTR_VALUES), + f.get_meta_attr(FIELD_ATTR_INT_VALUE_MAP), + f.get_meta_attr(FIELD_ATTR_STRING_VALUE_MAP), + ] + out += " " + json.dumps(shape, separators=(",", ":")) + return out + + +def _validate_projection_union_and_grain(root: MetaData, errors: list[MetaError]) -> None: + """rc.21 part B -- the projection shapes beside a plain view (mirrors TS + ``validateProjectionUnionAndGrain``): ``@union`` members share this view's effective + fields in order; ``@grain`` names a base-entity jsonb ``field.object`` array; + ``@grainOrdinal`` names a bare ``field.int``/``field.long`` of the projection. + ERR_BAD_ATTR_VALUE otherwise.""" + # ADR-0039 sanctioned own: root has no super; every projection is declared at root level. + for obj in root.own_children(): + if obj.type != TYPE_OBJECT or obj.sub_type != OBJECT_SUBTYPE_PROJECTION: + continue + + def bad(message: str, obj: MetaData = obj) -> None: + errors.append(MetaError( + f"object.projection {obj.name}: {message}", + ErrorCode.ERR_BAD_ATTR_VALUE, envelope=obj.source)) + + union_attr = OBJECT_PROJECTION_ATTR_UNION + # ADR-0039 sanctioned own: @union / @grain describe ITS view; an extender declares its own. + has_union = obj.attr(union_attr) is not None + if obj.attr(OBJECT_PROJECTION_ATTR_UNION_ALL) is not None and not has_union: + bad(f"@{OBJECT_PROJECTION_ATTR_UNION_ALL} needs @{union_attr}.") + if has_union: + referrer_pkg = obj.package or obj.file_default_package or "" + mine = [_describe_union_field(c) for c in obj.children() if c.type == TYPE_FIELD] + for name in _own_string_list(obj, union_attr): + member = resolve_object_ref(root, name, referrer_pkg) + if member is None or member.type != TYPE_OBJECT or member.sub_type != OBJECT_SUBTYPE_PROJECTION: + bad(f'@{union_attr} names "{name}", which is not an object.projection.') + continue + if member is obj: + bad(f"@{union_attr} names the projection itself.") + continue + # ADR-0039 sanctioned own: a member's own @union would be flattened away, silently. + if member.attr(union_attr) is not None: + bad(f'@{union_attr} member "{member.name}" declares its own @{union_attr}; ' + "name its members here instead.") + theirs = [_describe_union_field(c) for c in member.children() if c.type == TYPE_FIELD] + if mine != theirs: + bad(f'@{union_attr} member "{member.name}" has a different shape: ' + f"({', '.join(theirs)}) where this view is ({', '.join(mine)}). " + "A union's members have the same fields, in order.") + grain_attr = OBJECT_PROJECTION_ATTR_GRAIN + ordinal_attr = OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL + grain = obj.attr(grain_attr) + ordinal = obj.attr(ordinal_attr) + if ordinal is not None and grain is None: + bad(f"@{ordinal_attr} needs @{grain_attr}.") + if not isinstance(grain, str): + continue + base = _derive_base_entity(obj, root, obj.package or "", "@grain", obj.source, []) + field = None + if base is not None: + field = next((c for c in base.children() if c.type == TYPE_FIELD and c.name == grain), None) + storage = field.get_meta_attr(FIELD_ATTR_STORAGE) if field is not None else None + if ( + field is None + or field.sub_type != FIELD_SUBTYPE_OBJECT + or not field.resolved_is_array() + or (storage is not None and storage != "jsonb") + or bound_ref_target(field, FIELD_ATTR_OBJECT_REF) is None + ): + base_note = f' "{base.name}"' if base is not None else "" + bad(f'@{grain_attr} "{grain}" must name a field.object array (isArray, jsonb storage, ' + f"with @objectRef) of the base entity{base_note}.") + for f in (c for c in obj.children() if c.type == TYPE_FIELD): + # ADR-0039 sanctioned own: origin.* never inherits (ADR-0029). + if any(c.type == TYPE_ORIGIN and c.sub_type == ORIGIN_SUBTYPE_AGGREGATE for c in f.own_children()): + bad(f'"{f.name}" is an origin.aggregate; a @grain view has one row per element and groups nothing.') + if ordinal is not None: + f = next((c for c in obj.children() if c.type == TYPE_FIELD and c.name == ordinal), None) + # ADR-0039 sanctioned own: origin.* never inherits (ADR-0029). + if ( + f is None + or f.sub_type not in (FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG) + or any(c.type == TYPE_ORIGIN for c in f.own_children()) + or f.super_data is not None + ): + bad(f'@{ordinal_attr} "{ordinal}" must name a field.int or field.long of the ' + "projection, with no origin and no extends.") + + def _validate_projection_filter( root: MetaData, errors: list[MetaError], diff --git a/server/python/src/metaobjects/meta/core/reporting/reporting_provider.py b/server/python/src/metaobjects/meta/core/reporting/reporting_provider.py new file mode 100644 index 0000000000..4883611cff --- /dev/null +++ b/server/python/src/metaobjects/meta/core/reporting/reporting_provider.py @@ -0,0 +1,223 @@ +"""reporting_provider -- the reporting pack (cross-port ``metaobjects-reporting``). + +FR-044: ``dimension.*``, ``measure.*``, ``segment.filter`` and ``object.report``, plus +the rules that admit them on types core owns (an entity holds dimension / measure / +segment children) and the ``@segment`` attr on ``origin.aggregate`` / ``origin.first``; +those ride in ``reporting.json`` ``extends`` and are applied below. It is its OWN +provider so a project can leave it out; it is in the default bundle +(``core_providers``), so every existing model loads unchanged. ``object.report`` folds +``object.base`` (``extends_base``) from the core provider's registration. Mirrors the TS +``reportingProvider``. +""" +from __future__ import annotations + +from ....provider import Provider +from ....registry import AttrSchema, ChildRule, TypeDefinition, TypeRegistry +from ....shared.base_types import ( + TYPE_ATTR, + TYPE_DIMENSION, + TYPE_FIELD, + TYPE_IDENTITY, + TYPE_LAYOUT, + TYPE_MEASURE, + TYPE_OBJECT, + TYPE_SEGMENT, + TYPE_SOURCE, +) +from ...provider_extends import register_extends +from ..attr.attr_constants import ( + ATTR_SUBTYPE_BOOLEAN, + ATTR_SUBTYPE_EXPRESSION, + ATTR_SUBTYPE_FILTER, + ATTR_SUBTYPE_INT, + ATTR_SUBTYPE_STRING, +) +from ..object.meta_object import MetaObject +from ..object.object_constants import ( + OBJECT_REPORT_ATTR_DIMENSIONS, + OBJECT_REPORT_ATTR_FILTER, + OBJECT_REPORT_ATTR_FROM, + OBJECT_REPORT_ATTR_MEASURES, + OBJECT_REPORT_ATTR_SEGMENT, + OBJECT_REPORT_ATTR_SPINE, + OBJECT_SUBTYPE_REPORT, +) +from .meta_dimension import MetaDimension +from .meta_measure import MetaMeasure +from .meta_segment import MetaSegment +from .reporting_constants import ( + DIMENSION_SUBTYPE_ATTRIBUTE, + DIMENSION_SUBTYPE_TIME, + MEASURE_AGGS, + MEASURE_SUBTYPE_AGGREGATE, + MEASURE_SUBTYPE_DERIVED, + MEASURE_SUBTYPE_RATIO, + REPORTING_ATTR_AGG, + REPORTING_ATTR_DEFAULT, + REPORTING_ATTR_DENOMINATOR, + REPORTING_ATTR_DISTINCT, + REPORTING_ATTR_EXPR, + REPORTING_ATTR_FILTER, + REPORTING_ATTR_GRAINS, + REPORTING_ATTR_NUMERATOR, + REPORTING_ATTR_OF, + REPORTING_ATTR_SEGMENT, + REPORTING_ATTR_VIA, + SEGMENT_SUBTYPE_FILTER, + TIME_GRAINS, +) + +reporting_provider = Provider("metaobjects-reporting", dependencies=("metaobjects-core-types",)) + +# FR-044 -- object.report: declared dimensions x measures of ONE entity (@from), +# compiled to a read-only view. Its fields and identity are DERIVED (the loader +# refuses declared ones, R4), so it carries the projection's child set (no +# relationship / template). reporting.json's report block (extends_base) is the +# strict graph the spec pass re-derives onto this def; it declares ONLY the report +# attrs, so the shared discriminator attrs folded from object.base are pruned +# exactly as on projection. +reporting_provider.add( + TypeDefinition( + type=TYPE_OBJECT, + sub_type=OBJECT_SUBTYPE_REPORT, + factory=MetaObject, + extends_base=True, + child_rules=[ + ChildRule(TYPE_FIELD, "*"), + ChildRule(TYPE_IDENTITY, "*"), + ChildRule(TYPE_ATTR, "*"), + ChildRule(TYPE_SOURCE, "*"), + ChildRule(TYPE_LAYOUT, "*"), + ], + attrs=[ + AttrSchema(name=OBJECT_REPORT_ATTR_FROM, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema( + name=OBJECT_REPORT_ATTR_DIMENSIONS, + value_type=ATTR_SUBTYPE_STRING, + required=False, + is_array=True, + ), + AttrSchema( + name=OBJECT_REPORT_ATTR_MEASURES, + value_type=ATTR_SUBTYPE_STRING, + required=True, + is_array=True, + ), + AttrSchema(name=OBJECT_REPORT_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name=OBJECT_REPORT_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), + # R8: the to-one path from @from whose entity supplies the report's rows. + AttrSchema(name=OBJECT_REPORT_ATTR_SPINE, value_type=ATTR_SUBTYPE_STRING, required=False), + ], + ) +) + +# One vocabulary, one block: a report names dimensions and measures, and both may +# reference a segment. Attr scoping is per-subtype exactly as +# spec/metamodel/reporting.json declares it. +_DIMENSION_COMMON_ATTRS = [ + AttrSchema(name=REPORTING_ATTR_OF, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name=REPORTING_ATTR_VIA, value_type=ATTR_SUBTYPE_STRING, required=False), +] +reporting_provider.add( + TypeDefinition( + type=TYPE_DIMENSION, + sub_type=DIMENSION_SUBTYPE_ATTRIBUTE, + factory=MetaDimension, + attrs=list(_DIMENSION_COMMON_ATTRS), + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) +reporting_provider.add( + TypeDefinition( + type=TYPE_DIMENSION, + sub_type=DIMENSION_SUBTYPE_TIME, + factory=MetaDimension, + attrs=[ + *_DIMENSION_COMMON_ATTRS, + # Weeks start Monday (ISO-8601) in every lowering; 'hour' is refused on + # a field.date by the loader (D4), not by the closed set. + AttrSchema( + name=REPORTING_ATTR_GRAINS, + value_type=ATTR_SUBTYPE_STRING, + required=True, + is_array=True, + allowed_values=TIME_GRAINS, + ), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) +reporting_provider.add( + TypeDefinition( + type=TYPE_MEASURE, + sub_type=MEASURE_SUBTYPE_AGGREGATE, + factory=MetaMeasure, + attrs=[ + AttrSchema( + name=REPORTING_ATTR_AGG, + value_type=ATTR_SUBTYPE_STRING, + required=True, + allowed_values=MEASURE_AGGS, + ), + # isArray: a bare string coerces to a one-element list (the tuple form + # is a distinct count, M2). Optional (M0): only @agg any/all may omit + # it, to quantify their @filter/@segment over the rows instead of + # aggregating a column. + AttrSchema( + name=REPORTING_ATTR_OF, + value_type=ATTR_SUBTYPE_STRING, + required=False, + is_array=True, + ), + AttrSchema(name=REPORTING_ATTR_DISTINCT, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), + AttrSchema(name=REPORTING_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=False), + AttrSchema(name=REPORTING_ATTR_SEGMENT, value_type=ATTR_SUBTYPE_STRING, required=False), + # What the measure reads when it would otherwise be null; M7/M8 decide where it is legal. + AttrSchema(name=REPORTING_ATTR_DEFAULT, value_type=ATTR_SUBTYPE_INT, required=False), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) +reporting_provider.add( + TypeDefinition( + type=TYPE_MEASURE, + sub_type=MEASURE_SUBTYPE_RATIO, + factory=MetaMeasure, + attrs=[ + AttrSchema(name=REPORTING_ATTR_NUMERATOR, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name=REPORTING_ATTR_DENOMINATOR, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name=REPORTING_ATTR_DEFAULT, value_type=ATTR_SUBTYPE_INT, required=False), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) +# FR-044 R13: measure.derived — FR-037 R5's first arithmetic wave; no @default. +reporting_provider.add( + TypeDefinition( + type=TYPE_MEASURE, + sub_type=MEASURE_SUBTYPE_DERIVED, + factory=MetaMeasure, + attrs=[ + AttrSchema(name=REPORTING_ATTR_EXPR, value_type=ATTR_SUBTYPE_EXPRESSION, required=True), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) +reporting_provider.add( + TypeDefinition( + type=TYPE_SEGMENT, + sub_type=SEGMENT_SUBTYPE_FILTER, + factory=MetaSegment, + attrs=[ + AttrSchema(name=REPORTING_ATTR_FILTER, value_type=ATTR_SUBTYPE_FILTER, required=True), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) + + +def _register(registry: TypeRegistry) -> None: + register_extends(registry, "reporting.json") + + +reporting_provider.on_register(_register) diff --git a/server/python/src/metaobjects/meta/core/requirement/requirements_provider.py b/server/python/src/metaobjects/meta/core/requirement/requirements_provider.py new file mode 100644 index 0000000000..35589b8938 --- /dev/null +++ b/server/python/src/metaobjects/meta/core/requirement/requirements_provider.py @@ -0,0 +1,145 @@ +"""requirements_provider -- the requirements pack (cross-port ``metaobjects-requirements``). + +``requirement.functional`` / ``requirement.architectural``, and the rule that admits a +``requirement`` on a document root (``requirement.json`` ``extends``, applied below). It +is its OWN provider so a project can leave it out; it is in the default bundle +(``core_providers``), so every existing model loads unchanged. Compose it out and a model +that declares a requirement fails at load; one that declares none sees nothing. Mirrors +the TS ``requirementsProvider``. +""" +from __future__ import annotations + +from ....provider import Provider +from ....registry import AttrSchema, ChildRule, TypeDefinition, TypeRegistry +from ....shared.base_types import TYPE_ATTR, TYPE_REQUIREMENT +from ...provider_extends import register_extends +from ..attr.attr_constants import ATTR_SUBTYPE_INT, ATTR_SUBTYPE_STRING +from .meta_requirement import MetaRequirement +from .requirement_constants import ( + REQUIREMENT_ATTR_COUNTEREXAMPLE, + REQUIREMENT_ATTR_DISPOSITION, + REQUIREMENT_ATTR_IMPLEMENTED_BY, + REQUIREMENT_ATTR_LEVEL, + REQUIREMENT_ATTR_STATEMENT, + REQUIREMENT_ATTR_STATUS, + REQUIREMENT_ATTR_SUPERSEDED_BY, + REQUIREMENT_ATTR_TRACKED_BY, + REQUIREMENT_DISPOSITIONS, + REQUIREMENT_STATUSES, + REQUIREMENT_SUBTYPE_ARCHITECTURAL, + REQUIREMENT_SUBTYPE_FUNCTIONAL, +) + +requirements_provider = Provider( + "metaobjects-requirements", dependencies=("metaobjects-core-types",) +) + +# requirement.* (functional, architectural) — the capability ledger IS a metadata +# model (requirements-as-metadata ruling, amendment 3), so it is registered +# vocabulary rather than a hand-parsed side file: @status is an allowedValues enum +# the LOADER refuses a typo on. The axis is CHECK POLARITY, a genuine behaviour +# difference (ADR-0037 §2): `functional` is checked by EXISTENCE (nothing +# implements it -> fail), `architectural` by UNIVERSALITY (something violates it +# -> fail). Architectural carries no @level — levels come from +# object-in-focus decomposition and an architectural requirement is +# object-independent by definition. +# +# Hierarchy is NESTING, not a parent attr: requirement.functional admits nested +# requirement children (the strict graph in spec/metamodel/requirement.json, which +# _apply_strict_structural_children re-derives onto this registration). +# +# @implementedBy is deliberately NOT declared as a loader `references` descriptor. +# That pass always ERRORS on an unresolved target, and a requirement with status +# `planned` names nodes that do not exist YET — declaring +# it here would make those entries fail to load. The loader owns what is +# unconditional; `verify` owns @implementedBy resolution, whose severity depends on +# @status. +_REQUIREMENT_COMMON_ATTRS = [ + AttrSchema( + name=REQUIREMENT_ATTR_STATUS, + value_type=ATTR_SUBTYPE_STRING, + required=True, + allowed_values=REQUIREMENT_STATUSES, + ), + # What was DECIDED about the outstanding work -- a different question from + # whether the work is done, which is what @status answers. ABSENT means + # UNDECIDED, a real state and the one a review exists to find. + AttrSchema( + name=REQUIREMENT_ATTR_DISPOSITION, + value_type=ATTR_SUBTYPE_STRING, + required=False, + allowed_values=REQUIREMENT_DISPOSITIONS, + ), + # Issue/ticket references for outstanding work. Free-form and never resolved: + # verify has no network, so nothing here is checked to exist. + AttrSchema( + name=REQUIREMENT_ATTR_TRACKED_BY, + value_type=ATTR_SUBTYPE_STRING, + required=False, + is_array=True, + ), + AttrSchema(name=REQUIREMENT_ATTR_STATEMENT, value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name=REQUIREMENT_ATTR_COUNTEREXAMPLE, value_type=ATTR_SUBTYPE_STRING, required=True), + # FR-039 -- the requirement that REPLACED a retired one. Declared BEFORE + # @implementedBy to match the canonical spec's child order, which the registry + # manifest emits verbatim and every port byte-matches. + AttrSchema( + name=REQUIREMENT_ATTR_SUPERSEDED_BY, + value_type=ATTR_SUBTYPE_STRING, + required=False, + ), + AttrSchema( + name=REQUIREMENT_ATTR_IMPLEMENTED_BY, + value_type=ATTR_SUBTYPE_STRING, + required=False, + is_array=True, + ), +] +requirements_provider.add( + TypeDefinition( + type=TYPE_REQUIREMENT, + sub_type=REQUIREMENT_SUBTYPE_FUNCTIONAL, + factory=MetaRequirement, + attrs=[ + # REQUIRED on functional: levels are the object-in-focus decomposition + # and a functional requirement always sits at one. + AttrSchema(name=REQUIREMENT_ATTR_LEVEL, value_type=ATTR_SUBTYPE_INT, required=True), + *_REQUIREMENT_COMMON_ATTRS, + ], + child_rules=[ + ChildRule(TYPE_ATTR, "*"), + # Hierarchy IS nesting — an L1 solution contains its L2 segments. + ChildRule(TYPE_REQUIREMENT, "*"), + ], + ) +) +requirements_provider.add( + TypeDefinition( + type=TYPE_REQUIREMENT, + sub_type=REQUIREMENT_SUBTYPE_ARCHITECTURAL, + factory=MetaRequirement, + attrs=[ + # OPTIONAL on architectural: absent means a flat, object-independent + # policy (the original and still the default form); present opts the + # node into a levelled tree, e.g. a quality taxonomy over the + # non-functional set. Opt-in precisely so that adding a taxonomy over + # existing flat policies cannot invalidate them. + AttrSchema(name=REQUIREMENT_ATTR_LEVEL, value_type=ATTR_SUBTYPE_INT, required=False), + *_REQUIREMENT_COMMON_ATTRS, + ], + child_rules=[ + ChildRule(TYPE_ATTR, "*"), + # BOTH subtypes nest. Declaring this on `functional` only was an + # omission, not a design: it made an architectural node nestable under + # a FUNCTIONAL parent but never under another architectural one. + ChildRule(TYPE_REQUIREMENT, "*"), + ], + ) +) + + +def _register(registry: TypeRegistry) -> None: + register_extends(registry, "requirement.json") + + +requirements_provider.on_register(_register) diff --git a/server/python/src/metaobjects/registry.py b/server/python/src/metaobjects/registry.py index 160918f4ec..9e02d6b5b5 100644 --- a/server/python/src/metaobjects/registry.py +++ b/server/python/src/metaobjects/registry.py @@ -106,6 +106,10 @@ class TypeDefinition: # owns). Kept separately so the strict structural pass, which re-derives the rest # of ``child_rules`` from the shared spec, does not discard them. extended_child_rules: list[ChildRule] = field(default_factory=list) + # The type folds ``.base`` of ANOTHER provider's registration, like the + # ``extendsBase`` of a spec type: attrs it does not redeclare come from the base, + # stamped with the base's owner, never as a new claim by this provider. + extends_base: bool = False @property def key(self) -> tuple[str, str]: @@ -211,6 +215,12 @@ def _check_attr_ownership(self, type_: str, sub_type: str, name: str) -> None: def register(self, definition: TypeDefinition) -> None: self._check_not_sealed(f'register("{definition.key}")') + folded: list[AttrSchema] = [] + if definition.extends_base and definition.sub_type != SUBTYPE_BASE: + base = self._defs.get((definition.type, SUBTYPE_BASE)) + if base is not None: + own = {a.name for a in definition.attrs} + folded = [a for a in base.attrs if a.name not in own] # ADR-0062: refuse a name another provider already put on a related slot, BEFORE # the definition becomes visible, so a refused registration leaves no trace. for attr in definition.attrs: @@ -226,7 +236,7 @@ def register(self, definition: TypeDefinition) -> None: type=definition.type, sub_type=definition.sub_type, factory=definition.factory, - attrs=list(definition.attrs), + attrs=[*folded, *definition.attrs], child_rules=list(definition.child_rules), # FR-033 — carry the documentation surface + placement claim onto the # per-registry copy (copy the mutable parents list so a later extend() @@ -247,7 +257,14 @@ def register(self, definition: TypeDefinition) -> None: # TypeDefinition objects before `register()` is ever called). origin = self._current_provider_id or LIBRARY_ATTR_ORIGIN for attr in self._defs[definition.key].attrs: - self._attr_provenance[(definition.type, definition.sub_type, attr.name)] = origin + if any(attr is f for f in folded): + # Folded unchanged from the base: not this provider's claim. + base_origin = self._attr_provenance.get( + (definition.type, SUBTYPE_BASE, attr.name), LIBRARY_ATTR_ORIGIN + ) + self._attr_provenance[(definition.type, definition.sub_type, attr.name)] = base_origin + else: + self._attr_provenance[(definition.type, definition.sub_type, attr.name)] = origin def attr_origin(self, type_: str, sub_type: str, attr_name: str) -> str: """The provider id that registered/extended ``attr_name`` on ``(type_, sub_type)``, diff --git a/server/python/src/metaobjects/render/jinja_render.py b/server/python/src/metaobjects/render/jinja_render.py index a283dc215d..00a8c916cc 100644 --- a/server/python/src/metaobjects/render/jinja_render.py +++ b/server/python/src/metaobjects/render/jinja_render.py @@ -10,8 +10,9 @@ ``| e`` / ``| forceescape`` escape with that same escaper, as in nunjucks; * what a macro, a ``call`` block or a block ``set`` renders is already escaped, so printing it does not escape it again (nunjucks returns those as safe strings); -* a lookup on a missing key renders empty however deep it chains (``v.x.y``), as in - nunjucks; every engine failure surfaces as ``JinjaRenderError``; +* a lookup on a missing key chains however deep (``v.x.y``) and stays undefined, and + PRINTING an undefined value raises ``render verify failed: ERR_VAR_NOT_ON_PAYLOAD`` (a + present null prints empty); every engine failure surfaces as ``JinjaRenderError``; * a trailing newline is kept (jinja2 drops it by default; nunjucks and Mustache keep it); * the static template graph is checked first, so a cycle or a missing template fails with the Mustache path's messages (``partial cycle:``, ``unresolved partial:``). @@ -27,7 +28,7 @@ from .engine import TEMPLATE_ENGINE_JINJA, partial_engine_message, partial_engine_mismatch from .jinja_verify import jinja2_module, parse_jinja, ref_of_template_name from .renderer import _stringify -from .verify import MAX_DEPTH, Provider +from .verify import ERR_VAR_NOT_ON_PAYLOAD, MAX_DEPTH, Provider class JinjaRenderError(Exception): @@ -106,6 +107,11 @@ def escape(value: Any) -> Any: return value if isinstance(value, (Markup, _Rendered)) else forceescape(value) def finalize(value: Any) -> str: + # A value absent from the payload is a missing variable and raises, as on the + # Mustache path; a present null still prints empty. The engine does not hand the + # variable's name over at this point, so the message carries none. + if isinstance(value, jinja2.Undefined): + raise JinjaRenderError(f"render verify failed: {ERR_VAR_NOT_ON_PAYLOAD}") return str(escape(value)) def load(name: str) -> tuple[str, None, Any] | None: diff --git a/server/python/src/metaobjects/render/renderer.py b/server/python/src/metaobjects/render/renderer.py index a230dcf9ba..c8f79b9410 100644 --- a/server/python/src/metaobjects/render/renderer.py +++ b/server/python/src/metaobjects/render/renderer.py @@ -32,6 +32,7 @@ from .payload_accessors import with_derived_accessors from .verify import ( ERR_REQUIRED_SLOT_UNUSED, + ERR_VAR_NOT_ON_PAYLOAD, MAX_DEPTH, InMemoryProvider, PayloadField, @@ -333,7 +334,12 @@ def _emit( if isinstance(tok, _Text): out.append(tok.value) elif isinstance(tok, _Interp): - value = _resolve(tok.path, stack) + found, value = _resolve_found(tok.path, stack) + if not found: + # A name on no frame of the payload is a missing variable: raised on every + # render path, with the message the opt-in verify gate uses. A present null + # is a value and renders empty. + raise RenderError(f"render verify failed: {ERR_VAR_NOT_ON_PAYLOAD} ({tok.path})") if value is None or value is False: continue text = _stringify(value) @@ -369,22 +375,29 @@ def _resolve(path: str, stack: list[Any]) -> Any: """Mustache lookup: first segment walks the context stack innermost→outermost; remaining segments descend into the resolved value. Implicit iterator ``{{.}}`` returns the top of the stack.""" + return _resolve_found(path, stack)[1] + + +def _resolve_found(path: str, stack: list[Any]) -> tuple[bool, Any]: + """:func:`_resolve` that also says whether the name was FOUND: a name absent from every + frame (or a dotted path that leaves the payload, or descends through a null) is not + found; a key present with a null value is found.""" if path == ".": - return stack[-1] if stack else None + return True, (stack[-1] if stack else None) segs = path.split(".") - current = _lookup(stack, segs[0]) + found, current = _lookup(stack, segs[0]) for seg in segs[1:]: - if current is None: - return None - current = _lookup([current], seg) - return current + if not found or current is None: + return False, None + found, current = _lookup([current], seg) + return found, current -def _lookup(stack: list[Any], name: str) -> Any: +def _lookup(stack: list[Any], name: str) -> tuple[bool, Any]: for ctx in reversed(stack): if isinstance(ctx, dict) and name in ctx: - return ctx[name] - return None + return True, ctx[name] + return False, None def _truthy(value: Any) -> bool: diff --git a/server/python/src/metaobjects/spec_metamodel/object.json b/server/python/src/metaobjects/spec_metamodel/object.json index ddf3c6eeec..ad288e6015 100644 --- a/server/python/src/metaobjects/spec_metamodel/object.json +++ b/server/python/src/metaobjects/spec_metamodel/object.json @@ -26,9 +26,6 @@ "children": [ { "type": "relationship", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "template", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } @@ -56,22 +53,6 @@ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] - }, - { - "type": "object", - "subType": "report", - "extendsBase": true, - "description": "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.", - "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", - "children": [ - { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, - { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, - { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, - { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } - ] } ] } diff --git a/server/python/src/metaobjects/spec_metamodel/origin.json b/server/python/src/metaobjects/spec_metamodel/origin.json index c4fde970f9..4d7e5aea16 100644 --- a/server/python/src/metaobjects/spec_metamodel/origin.json +++ b/server/python/src/metaobjects/spec_metamodel/origin.json @@ -28,7 +28,6 @@ { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -52,8 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." } ] } ] diff --git a/server/python/src/metaobjects/spec_metamodel/reporting.json b/server/python/src/metaobjects/spec_metamodel/reporting.json index adbe87f9ed..10a888b0c3 100644 --- a/server/python/src/metaobjects/spec_metamodel/reporting.json +++ b/server/python/src/metaobjects/spec_metamodel/reporting.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-reporting", "types": [ { "type": "dimension", "subType": "attribute", "description": "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.", @@ -46,6 +46,35 @@ "whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 1, "max": 1, "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } + ] }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "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.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, + { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, + { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, + { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + } + ], + "extends": [ + { "type": "object", "subType": "entity", "children": [ + { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null } + ] }, + { "type": "origin", "subType": "aggregate", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + ] }, + { "type": "origin", "subType": "first", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] } diff --git a/server/python/src/metaobjects/spec_metamodel/requirement.json b/server/python/src/metaobjects/spec_metamodel/requirement.json index f3017fd78d..a74ebd5758 100644 --- a/server/python/src/metaobjects/spec_metamodel/requirement.json +++ b/server/python/src/metaobjects/spec_metamodel/requirement.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-requirements", "types": [ { "type": "requirement", @@ -185,5 +185,10 @@ } ] } + ], + "extends": [ + { "type": "metadata", "subType": "root", "children": [ + { "type": "requirement", "subType": "*", "name": "*", "min": 0, "max": null } + ] } ] } diff --git a/server/python/tests/conformance/conformance-expected-failures.json b/server/python/tests/conformance/conformance-expected-failures.json index 2672849cec..656792b04b 100644 --- a/server/python/tests/conformance/conformance-expected-failures.json +++ b/server/python/tests/conformance/conformance-expected-failures.json @@ -2,16 +2,12 @@ "language": "python", "fixtures": [ "error-origin-function-free-sql", - "error-projection-grain-not-object-array", - "error-projection-union-shape", "projection-view-vocabulary-rc21" ], "_comment_fr024": "FR-024 Phase-E validation parity SHIPPED in this port. The full FR-024 loader contract now holds: object.projection registration + per-subtype projection child rules + dotted Entity.child extends-resolution (type-scoped, ERR_EXTENDS_TARGET_MISMATCH), AND the validation passes \u2014 identity names required + projection identity pass-through/key-correspondence (B3), value-purity + projection-licensing subtype rules (B4a), the entity-primary-source-readonly hard cutover (B4b), @via single-hop-unique inference + origin cardinality (B5), and extends/origin agreement + derived-field providability (B6). Every former FR-024 error fixture (error-identity-name-required, error-projection-identity-not-extended, error-identity-key-mismatch, error-projection-extends-entity, error-projection-source-writable, error-value-with-identity-secondary, error-value-with-source, error-origin-via-ambiguous, error-origin-passthrough-to-many, error-origin-aggregate-no-to-many, error-extends-origin-mismatch, error-derived-field-no-read-source, error-entity-primary-source-readonly) now emits its expected code with the byte-identical source envelope and is un-ledgered.", "notes": "The Python expected failures are the keys of \"reasons\" below. The AI LLM-call trace fixtures ai-trace-prompt-nested and ai-trace-sti load + canonical-serialize cleanly in the Python port (@responseRef registered on template.prompt, carved out of the cross-port registry manifest as ExclusionReason.TS_PILOT_VOCAB until the atomic all-ports flip; template.* admitted as an object.entity child).", "reasons": { "error-origin-function-free-sql": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", - "error-projection-grain-not-object-array": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", - "error-projection-union-shape": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", "projection-view-vocabulary-rc21": "Python accepts the view functions and the cast node (C2) but not yet the rest of what this fixture declares: a dotted path in an origin.computed @expr (customerId.zip), a scalar origin.aggregate read from a computed field, a path operand in an origin.first @filter, an origin.passthrough through a path, and a derived field on an entity that declares a read source; implementedIn: typescript, csharp" } } diff --git a/server/python/tests/conformance/conformance_adapter.py b/server/python/tests/conformance/conformance_adapter.py index 94a2bf0946..92c4438173 100644 --- a/server/python/tests/conformance/conformance_adapter.py +++ b/server/python/tests/conformance/conformance_adapter.py @@ -10,6 +10,8 @@ from metaobjects import LoadResult, MetaDataLoader from metaobjects.core_types import core_provider, core_providers from metaobjects.documentation import doc_provider +from metaobjects.meta.core.reporting.reporting_provider import reporting_provider +from metaobjects.meta.core.requirement.requirements_provider import requirements_provider from metaobjects.meta.core.rules.rules_provider import rules_provider from metaobjects.meta.persistence.db.db_provider import db_provider from metaobjects.meta.persistence.view_expressions.view_expressions_provider import ( @@ -137,6 +139,9 @@ def _noop_provider(provider_id: str, *deps: str) -> Provider: # vocabulary (origin.function, projection @union / @grain), each its own pack. rules_provider.id: rules_provider, # "metaobjects-rules" view_expressions_provider.id: view_expressions_provider, # "metaobjects-view-expressions" + # Reporting (dimension / measure / segment / object.report) and requirements. + reporting_provider.id: reporting_provider, # "metaobjects-reporting" + requirements_provider.id: requirements_provider, # "metaobjects-requirements" # Back-compat alias: pre-rename fixtures (and other ports' fixtures) still name the # provider "metaobjects-template"; map it to the renamed prompt provider — the same # alias the TS adapter keeps (adapter.ts: "metaobjects-template": promptProvider). diff --git a/server/python/tests/conformance/fixture_discovery.py b/server/python/tests/conformance/fixture_discovery.py index 87b97be08c..e866228f9b 100644 --- a/server/python/tests/conformance/fixture_discovery.py +++ b/server/python/tests/conformance/fixture_discovery.py @@ -24,9 +24,12 @@ "metaobjects-ui", # view.textarea @rows and the view.image attrs are cross-port vocabulary. "metaobjects-ui-web", - # The business-rules and view-expressions packs are in the default bundle. + # The business-rules, view-expressions, reporting and requirements packs are in the default bundle. "metaobjects-rules", "metaobjects-view-expressions", + # Reporting and requirements are their own packs, in the default bundle. + "metaobjects-reporting", + "metaobjects-requirements", ) diff --git a/server/python/tests/render/test_jinja_engine.py b/server/python/tests/render/test_jinja_engine.py index bfe146bac6..cb6cd68db5 100644 --- a/server/python/tests/render/test_jinja_engine.py +++ b/server/python/tests/render/test_jinja_engine.py @@ -191,8 +191,10 @@ def test_a_payload_with_no_fields_is_refused() -> None: _jinja("{{ x }}", 5) -def test_a_missing_key_renders_empty_at_any_depth() -> None: - assert _jinja("[{{ v.x.y }}]", {"v": {}}) == "[]" +def test_a_missing_key_raises_at_any_depth_and_a_null_renders_empty() -> None: + with pytest.raises(RenderError, match="ERR_VAR_NOT_ON_PAYLOAD"): + _jinja("[{{ v.x.y }}]", {"v": {}}) + assert _jinja("[{{ v }}]", {"v": None}) == "[]" def test_an_engine_failure_is_a_render_error() -> None: diff --git a/server/python/tests/render/test_render_conformance.py b/server/python/tests/render/test_render_conformance.py index cff8e0e567..26cb30c9e9 100644 --- a/server/python/tests/render/test_render_conformance.py +++ b/server/python/tests/render/test_render_conformance.py @@ -8,7 +8,9 @@ - ``template.mustache`` the template body - ``partials/.mustache`` optional partial bodies, referenced as ``{{> partials/}}`` -- ``expected.txt`` the expected rendered output (byte-identical compare) +- ``expected.txt`` the expected rendered output (byte-identical compare), or + ``expected-error.txt``: the render must fail, and its message must contain the + file's trimmed text The same (template + payload + partials + format) MUST yield byte-identical output in TS, C#, Java, and Python. 1:1 port of @@ -24,6 +26,7 @@ from metaobjects.render.renderer import ( InMemoryProvider, + RenderError, RenderRequest, render, ) @@ -57,16 +60,16 @@ def test_render_matches_expected(fixture_dir: Path) -> None: template_path = fixture_dir / "template.mustache" payload_path = fixture_dir / "payload.json" expected_path = fixture_dir / "expected.txt" + error_path = fixture_dir / "expected-error.txt" meta_path = fixture_dir / "meta.json" partials_dir = fixture_dir / "partials" assert template_path.is_file(), f"missing template: {template_path}" assert payload_path.is_file(), f"missing payload: {payload_path}" - assert expected_path.is_file(), f"missing expected: {expected_path}" + assert expected_path.is_file() or error_path.is_file(), f"missing expected: {expected_path}" template = template_path.read_text(encoding="utf-8") payload = json.loads(payload_path.read_text(encoding="utf-8")) - expected = expected_path.read_text(encoding="utf-8") meta: dict = {} if meta_path.is_file(): @@ -88,6 +91,13 @@ def test_render_matches_expected(fixture_dir: Path) -> None: format=format_, max_chars=max_chars, ) + if error_path.is_file(): + message = error_path.read_text(encoding="utf-8").strip() + with pytest.raises(RenderError) as err: + render(req) + assert message in str(err.value) + return + expected = expected_path.read_text(encoding="utf-8") actual = render(req) assert actual == expected, ( @@ -95,3 +105,12 @@ def test_render_matches_expected(fixture_dir: Path) -> None: f"--- expected ({len(expected)} chars) ---\n{expected!r}\n" f"--- actual ({len(actual)} chars) ---\n{actual!r}" ) + + +def test_a_missing_variable_raises_and_a_null_renders_empty() -> None: + provider = InMemoryProvider({}) + with pytest.raises(RenderError, match=r"ERR_VAR_NOT_ON_PAYLOAD \(nmae\)"): + render(RenderRequest(payload={"name": "Ada"}, provider=provider, template="Hi {{nmae}}!")) + with pytest.raises(RenderError, match=r"ERR_VAR_NOT_ON_PAYLOAD \(nmae\)"): + render(RenderRequest(payload={}, provider=provider, template="Hi {{{nmae}}}!")) + assert render(RenderRequest(payload={"n": None}, provider=provider, template="Hi {{n}}!{{#x}}y{{/x}}")) == "Hi !" diff --git a/server/python/tests/test_requirements_pack_left_out.py b/server/python/tests/test_requirements_pack_left_out.py new file mode 100644 index 0000000000..0199add35c --- /dev/null +++ b/server/python/tests/test_requirements_pack_left_out.py @@ -0,0 +1,65 @@ +"""The requirements vocabulary is its own pack (``metaobjects-requirements``), composed by +default. The verify gate's ledger reads requirement nodes the pack registered, so with the +pack left out of an embedder's providers the gate has nothing to read and reports nothing, +and a model that declares a requirement fails to load instead.""" +from __future__ import annotations + +import json + +from metaobjects import MetaDataLoader +from metaobjects.core_types import core_providers +from metaobjects.requirement_check import ( + check_requirements, + scan_requirements, + summarise_requirements, +) + +ORDER = { + "object.entity": { + "name": "Order", + "children": [ + {"source.rdb": {"@table": "orders"}}, + {"field.long": {"name": "id"}}, + {"identity.primary": {"name": "pk", "@fields": ["id"]}}, + ], + } +} +REQUIREMENT = { + "requirement.functional": { + "name": "PlaceOrder", + "@level": 4, + "@status": "live", + "@statement": "A customer places an order", + "@counterexample": "A customer cannot place an order", + "@implementedBy": ["app::Order"], + } +} + + +def _model(children: list[dict]) -> str: + return json.dumps({"metadata.root": {"package": "app", "children": children}}) + + +def _load(children: list[dict], *, pack: bool): + providers = [p for p in core_providers if pack or p.id != "metaobjects-requirements"] + return MetaDataLoader.from_string(_model(children), providers=providers, strict=True) + + +def test_a_model_with_no_requirements_loads_and_the_gate_reports_nothing() -> None: + result = _load([ORDER], pack=False) + assert [str(e) for e in result.errors] == [] + scan = scan_requirements(result.root) + assert check_requirements(result.root, scan) == [] + assert summarise_requirements(result.root, scan) is None + + +def test_a_model_that_declares_a_requirement_fails_to_load() -> None: + result = _load([ORDER, REQUIREMENT], pack=False) + assert [e.code.name for e in result.errors] == ["ERR_UNKNOWN_TYPE"] + + +def test_with_the_default_bundle_the_same_requirement_reaches_the_ledger() -> None: + result = _load([ORDER, REQUIREMENT], pack=True) + assert [str(e) for e in result.errors] == [] + summary = summarise_requirements(result.root, scan_requirements(result.root)) + assert summary is not None and summary.total == 1 diff --git a/server/rust/metaobjects/data/metamodel/object.json b/server/rust/metaobjects/data/metamodel/object.json index ddf3c6eeec..ad288e6015 100644 --- a/server/rust/metaobjects/data/metamodel/object.json +++ b/server/rust/metaobjects/data/metamodel/object.json @@ -26,9 +26,6 @@ "children": [ { "type": "relationship", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "template", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } @@ -56,22 +53,6 @@ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] - }, - { - "type": "object", - "subType": "report", - "extendsBase": true, - "description": "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.", - "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", - "children": [ - { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, - { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, - { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, - { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } - ] } ] } diff --git a/server/rust/metaobjects/data/metamodel/origin.json b/server/rust/metaobjects/data/metamodel/origin.json index c4fde970f9..4d7e5aea16 100644 --- a/server/rust/metaobjects/data/metamodel/origin.json +++ b/server/rust/metaobjects/data/metamodel/origin.json @@ -28,7 +28,6 @@ { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -52,8 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." } ] } ] diff --git a/server/rust/metaobjects/data/metamodel/reporting.json b/server/rust/metaobjects/data/metamodel/reporting.json index adbe87f9ed..10a888b0c3 100644 --- a/server/rust/metaobjects/data/metamodel/reporting.json +++ b/server/rust/metaobjects/data/metamodel/reporting.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-reporting", "types": [ { "type": "dimension", "subType": "attribute", "description": "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.", @@ -46,6 +46,35 @@ "whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 1, "max": 1, "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } + ] }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "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.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, + { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, + { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, + { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + } + ], + "extends": [ + { "type": "object", "subType": "entity", "children": [ + { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null } + ] }, + { "type": "origin", "subType": "aggregate", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + ] }, + { "type": "origin", "subType": "first", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] } diff --git a/server/rust/metaobjects/data/metamodel/requirement.json b/server/rust/metaobjects/data/metamodel/requirement.json index f3017fd78d..a74ebd5758 100644 --- a/server/rust/metaobjects/data/metamodel/requirement.json +++ b/server/rust/metaobjects/data/metamodel/requirement.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-requirements", "types": [ { "type": "requirement", @@ -185,5 +185,10 @@ } ] } + ], + "extends": [ + { "type": "metadata", "subType": "root", "children": [ + { "type": "requirement", "subType": "*", "name": "*", "min": 0, "max": null } + ] } ] } diff --git a/server/rust/metaobjects/src/providers.rs b/server/rust/metaobjects/src/providers.rs index 19e21d3f80..902802afee 100644 --- a/server/rust/metaobjects/src/providers.rs +++ b/server/rust/metaobjects/src/providers.rs @@ -24,6 +24,8 @@ use crate::registry::{ pub const CORE_TYPES_ID: &str = "metaobjects-core-types"; pub const DB_ID: &str = "metaobjects-db"; pub const DOCUMENTATION_ID: &str = "metaobjects-documentation"; +pub const REPORTING_ID: &str = "metaobjects-reporting"; +pub const REQUIREMENTS_ID: &str = "metaobjects-requirements"; pub const RULES_ID: &str = "metaobjects-rules"; pub const VIEW_EXPRESSIONS_ID: &str = "metaobjects-view-expressions"; pub const PROMPT_ID: &str = "metaobjects-prompt"; @@ -89,11 +91,11 @@ const CORE_FAMILIES: &[(&str, &str)] = &[ spec!("identity"), spec!("relationship"), spec!("index"), - spec!("requirement"), - spec!("reporting"), ]; const RULES_FAMILIES: &[(&str, &str)] = &[spec!("api"), spec!("transition")]; +const REPORTING_SPEC: (&str, &str) = spec!("reporting"); +const REQUIREMENT_SPEC: (&str, &str) = spec!("requirement"); const VIEW_EXPRESSIONS_SPEC: (&str, &str) = spec!("view-expressions"); const DB_SPEC: (&str, &str) = spec!("db"); const DOCUMENTATION_SPEC: (&str, &str) = spec!("documentation"); @@ -257,6 +259,8 @@ struct Definitions { core: Vec, rules: Vec, view_expressions: ProviderDefinition, + reporting: ProviderDefinition, + requirements: ProviderDefinition, db: ProviderDefinition, documentation: ProviderDefinition, prompt: ProviderDefinition, @@ -272,6 +276,8 @@ fn definitions() -> &'static Definitions { core: CORE_FAMILIES.iter().map(|f| p(*f)).collect(), rules: RULES_FAMILIES.iter().map(|f| p(*f)).collect(), view_expressions: p(VIEW_EXPRESSIONS_SPEC), + reporting: p(REPORTING_SPEC), + requirements: p(REQUIREMENT_SPEC), db: p(DB_SPEC), documentation: p(DOCUMENTATION_SPEC), prompt: p(PROMPT_SPEC), @@ -381,7 +387,10 @@ fn child_rule_id(rule: &ChildRule) -> String { /// Lower a definition's real types (not the universal `*.*` entry) to registry /// definitions, folding `.base` into subtypes that set `extendsBase`. -fn define_from_data(data: &ProviderDefinition) -> Result, MetaError> { +fn define_from_data( + data: &ProviderDefinition, + registry: Option<&TypeRegistry>, +) -> Result, MetaError> { let real: Vec<&TypeDef> = data.types.iter().filter(|t| !is_universal(t)).collect(); let mut lowered: Vec<(String, Vec, Vec)> = Vec::new(); for t in &real { @@ -404,18 +413,26 @@ fn define_from_data(data: &ProviderDefinition) -> Result, Me let mut child_rules = own_rules.clone(); if t.extends_base && t.sub_type != SUBTYPE_BASE { let base_key = format!("{}.{SUBTYPE_BASE}", t.type_name); - if let Some((_, base_attrs, base_rules)) = - lowered.iter().find(|(k, _, _)| *k == base_key) - { + // The base is this definition's own, else one another provider registered. + let registered = || { + let b = registry?.find(&t.type_name, SUBTYPE_BASE)?; + Some((b.attributes.clone(), b.child_rules.clone())) + }; + let base = lowered + .iter() + .find(|(k, _, _)| *k == base_key) + .map(|(_, a, r)| (a.clone(), r.clone())) + .or_else(registered); + if let Some((base_attrs, base_rules)) = base { let mut have: HashSet = attributes.iter().map(|a| a.name.clone()).collect(); - for a in base_attrs { + for a in &base_attrs { if have.insert(a.name.clone()) { attributes.push(a.clone()); } } let mut have_rule: HashSet = child_rules.iter().map(child_rule_id).collect(); - for r in base_rules { + for r in &base_rules { if have_rule.insert(child_rule_id(r)) { child_rules.push(r.clone()); } @@ -442,7 +459,7 @@ fn apply_definition( registry: &mut TypeRegistry, data: &ProviderDefinition, ) -> Result<(), MetaError> { - for def in define_from_data(data)? { + for def in define_from_data(data, Some(registry))? { registry.register(def)?; } if let Some(universal) = data.types.iter().find(|t| is_universal(t)) { @@ -494,13 +511,13 @@ 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"] + root.child_rules = ["object", "field", "validator", "template"] .iter() .map(|t| ChildRule::wildcard(t)) .collect(); registry.register(root)?; for family in &definitions().core { - for def in define_from_data(family)? { + for def in define_from_data(family, None)? { registry.register(def)?; } } @@ -553,6 +570,27 @@ pub fn rules_provider() -> Provider { ) } +/// The reporting pack (FR-044): `object.report`, dimension / measure / segment, and +/// `@segment` on `origin.aggregate` / `origin.first`. +pub fn reporting_provider() -> Provider { + Provider::new( + REPORTING_ID, + &[CORE_TYPES_ID], + "Reporting: object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.", + |r| apply_definition(r, &definitions().reporting), + ) +} + +/// The requirements pack: `requirement.functional` and `requirement.architectural`. +pub fn requirements_provider() -> Provider { + Provider::new( + REQUIREMENTS_ID, + &[CORE_TYPES_ID], + "Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by verify.", + |r| apply_definition(r, &definitions().requirements), + ) +} + /// View expressions: `origin.function` and the projection `@union`/`@grain` attrs. pub fn view_expressions_provider() -> Provider { Provider::new( @@ -619,6 +657,8 @@ pub fn core_providers() -> Vec { prompt_provider(), ui_provider(), ui_web_provider(), + reporting_provider(), + requirements_provider(), ] } diff --git a/server/rust/metaobjects/src/registry.rs b/server/rust/metaobjects/src/registry.rs index 351d7186ca..f90fd1e241 100644 --- a/server/rust/metaobjects/src/registry.rs +++ b/server/rust/metaobjects/src/registry.rs @@ -4,6 +4,8 @@ //! Behaviour follows the TypeScript reference (`registry.ts`), including the //! provider attribute-ownership rules of ADR-0062 and the sealing of ADR-0023. +use std::collections::HashSet; + use indexmap::IndexMap; use serde_json::Value; @@ -309,11 +311,36 @@ impl TypeRegistry { for attr in &def.attributes { Self::check_value_type(attr, &format!("TypeRegistry.register on \"{key}\""))?; } - for attr in &def.attributes { + // An attribute folded in unchanged from the registered `.base` (a pack's + // subtype with `extendsBase`, e.g. object.report) is the base owner's, not a new + // claim: it is not checked against the registering provider, and is stamped with + // the owner the base attribute already has. + let base_names: HashSet = if def.sub_type == SUBTYPE_BASE { + HashSet::new() + } else { + self.find(&def.type_name, SUBTYPE_BASE) + .map(|b| b.attributes.iter().map(|a| a.name.clone()).collect()) + .unwrap_or_default() + }; + for attr in def.attributes.iter().filter(|a| !base_names.contains(&a.name)) { self.check_attr_ownership(&def.type_name, &def.sub_type, &attr.name)?; } let (type_name, sub_type) = (def.type_name.clone(), def.sub_type.clone()); - let names: Vec = def.attributes.iter().map(|a| a.name.clone()).collect(); + let names: Vec = def + .attributes + .iter() + .filter(|a| !base_names.contains(&a.name)) + .map(|a| a.name.clone()) + .collect(); + let inherited: Vec<(String, String)> = def + .attributes + .iter() + .filter(|a| base_names.contains(&a.name)) + .filter_map(|a| { + self.attr_owner(&type_name, SUBTYPE_BASE, &a.name) + .map(|o| (a.name.clone(), o.to_string())) + }) + .collect(); self.defs.insert(key, def); self.sub_types .entry(type_name.clone()) @@ -322,6 +349,12 @@ impl TypeRegistry { for name in names { self.stamp_attr_owner(&type_name, &sub_type, &name); } + for (name, owner) in inherited { + self.attr_owners + .entry(format!("{type_name}.{sub_type}")) + .or_default() + .insert(name, owner); + } Ok(()) } diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index cbe72cdd23..4296e5891c 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -38,6 +38,9 @@ //! 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 +//! P3 ERR_TRANSITION_NAME_COLLISION two permission points ask the policy about one permission +//! name and at least one of the two names is derived; two +//! DECLARED @permission values may be equal (shared permission) //! 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 @@ -1098,6 +1101,87 @@ fn check_api_routes(tree: &Tree, ops: &[NodeId], sink: &mut Sink<'_>) { } } +/// The name a permission point asks the policy about: its `@permission`, else +/// `.` (the package prefix is dropped when there is none). `::` and `.` +/// both separate path segments, so they compare equal. Returns the name and whether it +/// is derived. +fn permission_name_of(tree: &Tree, node: NodeId, owner: NodeId, path: &str) -> (String, bool) { + let declared = match tree.attr(node, A_PERMISSION) { + Some(Value::String(s)) => Some(s.as_str()), + _ => None, + }; + let pkg = tree.effective_package(tree.top_level_of(owner)); + let name = match declared { + Some(d) => d.to_string(), + None if pkg.is_empty() => path.to_string(), + None => format!("{pkg}.{path}"), + }; + (name.replace(PACKAGE_SEP, "."), declared.is_none()) +} + +/// P3: two permission points, one name. Points are every non-public operation and every +/// transition of a live concrete entity. Compared case-sensitively (a grant key is +/// exact). Transitions are registered first, so the error lands on the operation when an +/// operation meets a transition. +fn check_permission_names(ctx: &Ctx<'_>, top_level: &[NodeId], sink: &mut Sink<'_>) { + let tree = ctx.tree; + let mut by_name: HashMap> = HashMap::new(); + let mut register = |node: NodeId, owner: NodeId, path: &str, sink: &mut Sink<'_>| { + if is_true(tree, node, A_PUBLIC) { + return; + } + let (name, derived) = permission_name_of(tree, node, owner, path); + let points = by_name.entry(name.clone()).or_default(); + let is_op = |n: NodeId| tree.node(n).type_name == T_OPERATION; + let clash = points.iter().find(|&&(q, q_derived)| { + q != node + && (derived || q_derived) + && !(is_op(node) && is_op(q) && same_operation(ctx, q, node)) + }); + if let Some(&(q, _)) = clash { + let (n, c) = (tree.node(node), tree.node(q)); + sink.add( + node, + ERR_TRANSITION_NAME_COLLISION, + format!( + "{}.{} \"{}\" asks the policy about the permission name \"{name}\", which {}.{} \"{}\" also asks about, and one of the two names is derived rather than declared; declare a distinct @permission on one, or rename it.", + n.type_name, + n.sub_type, + label(tree, node), + c.type_name, + c.sub_type, + label(tree, q) + ), + ); + } + points.push((node, derived)); + }; + for &entity in top_level { + if !is_entity(tree, entity) || tree.node(entity).is_abstract { + continue; + } + if !tree.children(entity).iter().any(|&c| tree.node(c).type_name == T_SOURCE) { + continue; + } + let ename = tree.node(entity).name.clone(); + for t in entity_transitions(tree, entity) { + let path = format!("{ename}.{}", tree.node(t).name); + register(t, entity, &path, sink); + } + } + for &api in top_level { + if tree.node(api).type_name != T_API { + continue; + } + for &op in tree.children(api).iter() { + if tree.node(op).type_name == T_OPERATION { + let path = tree.node(op).name.clone(); + register(op, api, &path, sink); + } + } + } +} + /// 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; @@ -1175,6 +1259,7 @@ pub fn validate_rules(ctx: &Ctx<'_>, f: &mut Findings) { } check_api_routes(tree, &ops, &mut sink); } + check_permission_names(ctx, top_level, &mut sink); f.errors.extend(sink.errors); } diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json index fff5764197..7a90da6993 100644 --- a/server/rust/metaobjects/tests/conformance-expected-failures.json +++ b/server/rust/metaobjects/tests/conformance-expected-failures.json @@ -1,6 +1,6 @@ { "language": "rust", "notes": "The Rust port passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", - "minPassing": 578, + "minPassing": 584, "fixtures": [] } diff --git a/server/rust/metaobjects/tests/metamodel_conformance.rs b/server/rust/metaobjects/tests/metamodel_conformance.rs index 8cd2a820e5..ade2ad5e48 100644 --- a/server/rust/metaobjects/tests/metamodel_conformance.rs +++ b/server/rust/metaobjects/tests/metamodel_conformance.rs @@ -35,6 +35,8 @@ const DEFAULT_PROVIDERS: &[&str] = &[ "metaobjects-prompt", "metaobjects-ui", "metaobjects-ui-web", + "metaobjects-reporting", + "metaobjects-requirements", ]; fn corpus() -> PathBuf { diff --git a/server/typescript/packages/cli/test/requirements-pack-left-out.test.ts b/server/typescript/packages/cli/test/requirements-pack-left-out.test.ts new file mode 100644 index 0000000000..59cd0c3ca7 --- /dev/null +++ b/server/typescript/packages/cli/test/requirements-pack-left-out.test.ts @@ -0,0 +1,67 @@ +// The requirements vocabulary is its own pack (`metaobjects-requirements`), composed by +// default. The verify gate's ledger reads requirement nodes the pack registered, so with +// the pack left out of an embedder's registry the gate has nothing to read and reports +// nothing, and a model that declares a requirement fails to load instead. +import { describe, test, expect } from "bun:test"; +import { + MetaDataLoader, + InMemoryStringSource, + composeRegistry, + coreProviders, + REQUIREMENTS_PROVIDER_ID, +} from "@metaobjectsdev/metadata"; +import { checkRequirements, scanRequirements, summariseRequirements } from "../src/lib/requirement-check.js"; + +const ORDER = { + "object.entity": { + name: "Order", + children: [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ], + }, +}; +const REQUIREMENT = { + "requirement.functional": { + name: "PlaceOrder", + "@level": 4, + "@status": "live", + "@statement": "A customer places an order", + "@counterexample": "A customer cannot place an order", + "@implementedBy": ["app::Order"], + }, +}; + +function model(children: unknown[]): string { + return JSON.stringify({ "metadata.root": { package: "app", children } }); +} + +const withoutPack = () => composeRegistry(coreProviders.filter((p) => p.id !== REQUIREMENTS_PROVIDER_ID)); + +describe("requirements pack left out", () => { + test("a model with no requirements loads and the gate reports nothing", async () => { + const result = await new MetaDataLoader({ registry: withoutPack(), strict: true }).load([ + new InMemoryStringSource(model([ORDER]), { format: "json" }), + ]); + expect(result.errors).toEqual([]); + const scan = scanRequirements(result.root); + expect(checkRequirements(result.root, scan)).toEqual([]); + expect(summariseRequirements(result.root, scan)).toBeUndefined(); + }); + + test("a model that declares a requirement fails to load with ERR_UNKNOWN_TYPE", async () => { + const result = await new MetaDataLoader({ registry: withoutPack(), strict: true }).load([ + new InMemoryStringSource(model([ORDER, REQUIREMENT]), { format: "json" }), + ]); + expect(result.errors.map((e) => (e as { code?: string }).code)).toEqual(["ERR_UNKNOWN_TYPE"]); + }); + + test("with the default bundle the same requirement reaches the ledger", async () => { + const result = await new MetaDataLoader({ registry: composeRegistry(coreProviders), strict: true }).load([ + new InMemoryStringSource(model([ORDER, REQUIREMENT]), { format: "json" }), + ]); + expect(result.errors).toEqual([]); + expect(summariseRequirements(result.root, scanRequirements(result.root))?.total).toBe(1); + }); +}); diff --git a/server/typescript/packages/conformance/src/fixture.ts b/server/typescript/packages/conformance/src/fixture.ts index c4cfe9a09e..8d3c088d23 100644 --- a/server/typescript/packages/conformance/src/fixture.ts +++ b/server/typescript/packages/conformance/src/fixture.ts @@ -58,10 +58,13 @@ const DEFAULT_PROVIDERS = [ "metaobjects-ui", // View.textarea @rows and the view.image attrs are cross-port vocabulary. "metaobjects-ui-web", - // The business-rules and view-expressions packs are in the default bundle, so a - // fixture with no providers.json still loads every existing model. + // The business-rules, view-expressions, reporting and requirements packs are in + // the default bundle, so a fixture with no providers.json still loads every + // existing model. "metaobjects-rules", "metaobjects-view-expressions", + "metaobjects-reporting", + "metaobjects-requirements", ]; export interface Fixture { diff --git a/server/typescript/packages/docs-site/src/load.ts b/server/typescript/packages/docs-site/src/load.ts index bc8cbe7592..0c1f7bb5b6 100644 --- a/server/typescript/packages/docs-site/src/load.ts +++ b/server/typescript/packages/docs-site/src/load.ts @@ -15,7 +15,7 @@ export interface LoadedModel { * Load N metadata source dirs into ONE root via a staging dir of symlinks. * * `extraProviders` are consumer-supplied metamodel providers, composed AFTER - * the default bundle (`coreProviders`: core-types, db, doc, prompt, ui, rules, view-expressions) — mirroring + * the default bundle (`coreProviders`: core-types, db, doc, prompt, ui, ui-web, rules, view-expressions, reporting, requirements) — mirroring * `loadMemory`'s `providers` option — so a site can document metadata that uses * custom field/view/object subtypes (e.g. a project's `metaobjects.config.ts` * `providers`). Defaults to none, so config-less callers are unchanged. diff --git a/server/typescript/packages/metadata/src/core-types.ts b/server/typescript/packages/metadata/src/core-types.ts index 8bbe85b26f..48b338d92b 100644 --- a/server/typescript/packages/metadata/src/core-types.ts +++ b/server/typescript/packages/metadata/src/core-types.ts @@ -8,6 +8,8 @@ import { uiProvider } from "./presentation/ui/ui-provider.js"; import { uiWebProvider } from "./presentation/ui-web/ui-web-provider.js"; import { rulesProvider } from "./core/rules/rules-provider.js"; import { viewExpressionsProvider } from "./persistence/view-expressions/view-expressions-provider.js"; +import { reportingProvider } from "./core/reporting/reporting-provider.js"; +import { requirementsProvider } from "./core/requirement/requirements-provider.js"; import { type DataType } from "./data-type.js"; import type { MetaData } from "./shared/meta-data.js"; import { MetaRoot } from "./shared/meta-root.js"; @@ -59,18 +61,6 @@ import { TEMPLATE_SUBTYPES } from "./template/template-constants.js"; 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 { 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"; -import { MetaMeasure } from "./core/reporting/meta-measure.js"; -import { MetaSegment } from "./core/reporting/meta-segment.js"; -import { REPORTING_DEFINITION } from "./core/reporting/reporting-definition.embedded.js"; -import { - DIMENSION_SUBTYPES, - MEASURE_SUBTYPES, - SEGMENT_SUBTYPES, -} from "./core/reporting/reporting-constants.js"; import { TYPE_METADATA, TYPE_OBJECT, @@ -85,10 +75,6 @@ import { TYPE_ORIGIN, TYPE_TEMPLATE, TYPE_INDEX, - TYPE_REQUIREMENT, - TYPE_DIMENSION, - TYPE_MEASURE, - TYPE_SEGMENT, SUBTYPE_ROOT, } from "./shared/base-types.js"; import { CHILD_RULE_WILDCARD } from "./shared/structural.js"; @@ -204,8 +190,8 @@ function registerCoreTypeDefs(registry: TypeRegistry): void { wildcard(TYPE_FIELD), wildcard(TYPE_VALIDATOR), wildcard(TYPE_TEMPLATE), - // Capability requirements are declared beside the entities they describe. - wildcard(TYPE_REQUIREMENT), + // `requirement` (the requirements pack) and `api` (the rules pack) are admitted + // by their packs' `extends`, so composing a pack out removes its child rule too. ], MetaRoot), ); @@ -509,52 +495,6 @@ function registerCoreTypeDefs(registry: TypeRegistry): void { registry.register(indexDef); } - // requirement — 2 subtypes. The axis is CHECK POLARITY, a genuine behaviour - // difference (ADR-0037 §2): `functional` is checked by EXISTENCE (nothing - // implements it -> fail), `architectural` by UNIVERSALITY (something violates - // it -> fail). Registered rather than hand-parsed because the capability - // ledger IS a metadata model: a closed status enum and a list of FQN - // references to model nodes are exactly `allowedValues` plus reference - // resolution, both of which this registry already owns (ruling amendment 3). - const REQUIREMENT_FACTORIES: FactoryMap = Object.fromEntries( - REQUIREMENT_SUBTYPES.map((subType) => [ - `${TYPE_REQUIREMENT}.${subType}`, - (typeId: TypeId, name: string) => new MetaRequirement(typeId, name), - ]), - ); - for (const reqDef of defineProviderFromData(REQUIREMENT_DEFINITION, REQUIREMENT_FACTORIES)) { - registry.register(reqDef); - } - - // FR-044 reporting vocabulary — dimension / measure / segment. Declared as - // children of `object.entity` (spec/metamodel/object.json), never root-level, so - // no root wildcard is added above. Three types in one provider file because they - // are one vocabulary: a report names dimensions and measures, and both may - // reference a segment. `measure.derived` is NOT registered (waits for FR-037 R5). - const REPORTING_FACTORIES: FactoryMap = { - ...Object.fromEntries( - DIMENSION_SUBTYPES.map((subType) => [ - `${TYPE_DIMENSION}.${subType}`, - (typeId: TypeId, name: string) => new MetaDimension(typeId, name), - ]), - ), - ...Object.fromEntries( - MEASURE_SUBTYPES.map((subType) => [ - `${TYPE_MEASURE}.${subType}`, - (typeId: TypeId, name: string) => new MetaMeasure(typeId, name), - ]), - ), - ...Object.fromEntries( - SEGMENT_SUBTYPES.map((subType) => [ - `${TYPE_SEGMENT}.${subType}`, - (typeId: TypeId, name: string) => new MetaSegment(typeId, name), - ]), - ), - }; - for (const reportingDef of defineProviderFromData(REPORTING_DEFINITION, REPORTING_FACTORIES)) { - registry.register(reportingDef); - } - // 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 @@ -567,13 +507,6 @@ function registerCoreTypeDefs(registry: TypeRegistry): void { ]; } } - // NOTE: @implementedBy is deliberately NOT declared as a loader `references` - // descriptor. That pass always ERRORS on an unresolved target, and a - // requirement with status `planned` names nodes that do not exist YET, so declaring - // nodes that are GONE — declaring it here would make the entries that carry - // the mechanism's only controlled evidence fail to load. The loader owns what - // is unconditional (the status enum, shape, levels); `meta verify` owns the - // status-conditional resolution, where the severity actually depends on data. const idRefDef = registry.find(TYPE_IDENTITY, IDENTITY_SUBTYPE_REFERENCE); if (idRefDef) { idRefDef.references = [ @@ -621,9 +554,11 @@ export const coreTypesProvider: MetaDataTypeProvider = { }, }; -/** The default provider bundle — core metamodel types plus the five concern +/** The default provider bundle — core metamodel types, the five concern * providers (DB-domain attrs, documentation common-attrs, prompt/AI, the - * UI/query-surface markers, and the TS-web presentation view attrs). + * UI/query-surface markers, and the TS-web presentation view attrs), and the four + * vocabulary packs (business rules, view expressions, reporting, requirements), each + * of which an embedder may leave out. * FR-033 S1-field-A re-homed the field's filter/sort/teaching/extract/storage * attrs out of core into db/ui/prompt; the composed set is unchanged. uiWebProvider * is TS-only (the non-TS ports mirror its spec file but never apply it — see @@ -638,6 +573,8 @@ export const coreProviders: readonly MetaDataTypeProvider[] = [ uiWebProvider, rulesProvider, viewExpressionsProvider, + reportingProvider, + requirementsProvider, ]; /** diff --git a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts index 3bbec9aedc..7ab0a148b2 100644 --- a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts @@ -103,27 +103,6 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "min": 0, "max": null }, - { - "type": "dimension", - "subType": "*", - "name": "*", - "min": 0, - "max": null - }, - { - "type": "measure", - "subType": "*", - "name": "*", - "min": 0, - "max": null - }, - { - "type": "segment", - "subType": "*", - "name": "*", - "min": 0, - "max": null - }, { "type": "attr", "subType": "string", @@ -192,73 +171,6 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] - }, - { - "type": "object", - "subType": "report", - "extendsBase": true, - "description": "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.", - "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", - "children": [ - { - "type": "attr", - "subType": "string", - "name": "from", - "min": 1, - "max": 1, - "description": "The object.entity whose rows the report aggregates." - }, - { - "type": "attr", - "subType": "string", - "name": "dimensions", - "isArray": true, - "min": 0, - "max": 1, - "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." - }, - { - "type": "attr", - "subType": "string", - "name": "measures", - "isArray": true, - "min": 1, - "max": 1, - "description": "Measure names of @from." - }, - { - "type": "attr", - "subType": "string", - "name": "segment", - "min": 0, - "max": 1, - "description": "Optional segment of @from scoping the rows." - }, - { - "type": "attr", - "subType": "filter", - "name": "filter", - "min": 0, - "max": 1, - "description": "Optional row scope over @from's fields; may use relative-date values." - }, - { - "type": "attr", - "subType": "string", - "name": "spine", - "min": 0, - "max": 1, - "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." - }, - { - "type": "attr", - "subType": "string", - "name": "collectionName", - "min": 0, - "max": 1, - "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." - } - ] } ] }; diff --git a/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts b/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts index 354707a4fe..077a87326d 100644 --- a/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts @@ -7,7 +7,7 @@ import type { ProviderDefinition } from "../../provider-data.js"; export const REPORTING_DEFINITION: ProviderDefinition = { - "provider": "metaobjects-core-types", + "provider": "metaobjects-reporting", "types": [ { "type": "dimension", @@ -203,6 +203,130 @@ export const REPORTING_DEFINITION: ProviderDefinition = { "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } ] + }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "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.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "from", + "min": 1, + "max": 1, + "description": "The object.entity whose rows the report aggregates." + }, + { + "type": "attr", + "subType": "string", + "name": "dimensions", + "isArray": true, + "min": 0, + "max": 1, + "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." + }, + { + "type": "attr", + "subType": "string", + "name": "measures", + "isArray": true, + "min": 1, + "max": 1, + "description": "Measure names of @from." + }, + { + "type": "attr", + "subType": "string", + "name": "segment", + "min": 0, + "max": 1, + "description": "Optional segment of @from scoping the rows." + }, + { + "type": "attr", + "subType": "filter", + "name": "filter", + "min": 0, + "max": 1, + "description": "Optional row scope over @from's fields; may use relative-date values." + }, + { + "type": "attr", + "subType": "string", + "name": "spine", + "min": 0, + "max": 1, + "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." + }, + { + "type": "attr", + "subType": "string", + "name": "collectionName", + "min": 0, + "max": 1, + "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." + } + ] + } + ], + "extends": [ + { + "type": "object", + "subType": "entity", + "children": [ + { + "type": "dimension", + "subType": "*", + "name": "*", + "min": 0, + "max": null + }, + { + "type": "measure", + "subType": "*", + "name": "*", + "min": 0, + "max": null + }, + { + "type": "segment", + "subType": "*", + "name": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "origin", + "subType": "aggregate", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "segment", + "min": 0, + "max": 1, + "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." + } + ] + }, + { + "type": "origin", + "subType": "first", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "segment", + "min": 0, + "max": 1, + "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." + } + ] } ] }; diff --git a/server/typescript/packages/metadata/src/core/reporting/reporting-provider.ts b/server/typescript/packages/metadata/src/core/reporting/reporting-provider.ts new file mode 100644 index 0000000000..7bb7eac58e --- /dev/null +++ b/server/typescript/packages/metadata/src/core/reporting/reporting-provider.ts @@ -0,0 +1,47 @@ +// reportingProvider — the reporting pack (FR-044): `object.report` and the +// dimension / measure / segment vocabulary a report is built from, plus the `@segment` +// attribute that lets an `origin.aggregate` or `origin.first` reuse a segment. +// +// It is its OWN provider rather than part of metaobjects-core-types so a project can +// leave it out and the vocabulary can move or be versioned on its own. It is in the +// default bundle (`coreProviders`), so every existing model loads unchanged. +// GOVERNANCE.md ("Extension packs and the core metamodel"): vocabulary lives in a +// pack until a second consumer needs it in core. +// +// The pack owns its types (reporting.json) AND the rules that admit them on types +// core owns: `object.entity` holds dimensions, measures and segments, and +// `origin.aggregate` / `origin.first` carry `@segment` — all in the file's `extends`. +// `object.report` folds in the `object.base` core registered (`extendsBase`). Compose +// the pack out and `object.report`, `dimension.*`, `measure.*` and `segment.*` are +// unknown (ERR_UNKNOWN_SUBTYPE / ERR_UNKNOWN_TYPE) and `@segment` is ERR_UNKNOWN_ATTR. + +import type { MetaDataTypeProvider } from "../../provider.js"; +import type { TypeRegistry, TypeId } from "../../registry.js"; +import { applyProviderDefinition, type FactoryMap } from "../../provider-data.js"; +import { TYPE_OBJECT, TYPE_DIMENSION, TYPE_MEASURE } from "../../shared/base-types.js"; +import { MetaObject } from "../object/meta-object.js"; +import { MetaDimension } from "./meta-dimension.js"; +import { MetaMeasure } from "./meta-measure.js"; +import { MetaSegment } from "./meta-segment.js"; +import { REPORTING_DEFINITION } from "./reporting-definition.embedded.js"; + +/** The reporting pack's provider id (a logical id, shared by every port). */ +export const REPORTING_PROVIDER_ID = "metaobjects-reporting"; + +export const reportingProvider: MetaDataTypeProvider = { + id: REPORTING_PROVIDER_ID, + dependencies: ["metaobjects-core-types"], + description: + "Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.", + registerTypes(registry: TypeRegistry): void { + const factories: FactoryMap = {}; + for (const def of REPORTING_DEFINITION.types ?? []) { + const key = `${def.type}.${def.subType}`; + if (def.type === TYPE_OBJECT) factories[key] = (typeId: TypeId, name: string) => new MetaObject(typeId, name); + else if (def.type === TYPE_DIMENSION) factories[key] = (typeId: TypeId, name: string) => new MetaDimension(typeId, name); + else if (def.type === TYPE_MEASURE) factories[key] = (typeId: TypeId, name: string) => new MetaMeasure(typeId, name); + else factories[key] = (typeId: TypeId, name: string) => new MetaSegment(typeId, name); + } + applyProviderDefinition(registry, REPORTING_DEFINITION, factories); + }, +}; diff --git a/server/typescript/packages/metadata/src/core/requirement/requirement-definition.embedded.ts b/server/typescript/packages/metadata/src/core/requirement/requirement-definition.embedded.ts index 5242c1e529..9e4e220d67 100644 --- a/server/typescript/packages/metadata/src/core/requirement/requirement-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/requirement/requirement-definition.embedded.ts @@ -7,7 +7,7 @@ import type { ProviderDefinition } from "../../provider-data.js"; export const REQUIREMENT_DEFINITION: ProviderDefinition = { - "provider": "metaobjects-core-types", + "provider": "metaobjects-requirements", "types": [ { "type": "requirement", @@ -193,5 +193,20 @@ export const REQUIREMENT_DEFINITION: ProviderDefinition = { } ] } + ], + "extends": [ + { + "type": "metadata", + "subType": "root", + "children": [ + { + "type": "requirement", + "subType": "*", + "name": "*", + "min": 0, + "max": null + } + ] + } ] }; diff --git a/server/typescript/packages/metadata/src/core/requirement/requirements-provider.ts b/server/typescript/packages/metadata/src/core/requirement/requirements-provider.ts new file mode 100644 index 0000000000..628f5e672d --- /dev/null +++ b/server/typescript/packages/metadata/src/core/requirement/requirements-provider.ts @@ -0,0 +1,44 @@ +// requirementsProvider — the requirements pack: `requirement.functional` and +// `requirement.architectural`, declared beside the entities they describe. +// +// It is its OWN provider rather than part of metaobjects-core-types so a project can +// leave it out and the vocabulary can move or be versioned on its own. It is in the +// default bundle (`coreProviders`), so every existing model loads unchanged. +// GOVERNANCE.md ("Extension packs and the core metamodel"): vocabulary lives in a +// pack until a second consumer needs it in core. +// +// The pack owns its types (requirement.json) AND the child rule that admits them on +// `metadata.root` (the file's `extends`). Compose the pack out and a `requirement.*` +// node is ERR_UNKNOWN_TYPE; `meta verify`'s requirement gate then has no ledger to +// read and reports nothing. +// +// @implementedBy is deliberately NOT declared as a loader `references` descriptor. That +// pass always ERRORS on an unresolved target, and a requirement with status `planned` +// names nodes that do not exist YET (and a `retired` one names nodes that are GONE), so +// declaring it would make the entries that carry the mechanism's only controlled evidence +// fail to load. The loader owns what is unconditional (the status enum, shape, levels); +// `meta verify` owns the status-conditional resolution, where the severity depends on data. + +import type { MetaDataTypeProvider } from "../../provider.js"; +import type { TypeRegistry, TypeId } from "../../registry.js"; +import { applyProviderDefinition, type FactoryMap } from "../../provider-data.js"; +import { MetaRequirement } from "./meta-requirement.js"; +import { REQUIREMENT_DEFINITION } from "./requirement-definition.embedded.js"; + +/** The requirements pack's provider id (a logical id, shared by every port). */ +export const REQUIREMENTS_PROVIDER_ID = "metaobjects-requirements"; + +export const requirementsProvider: MetaDataTypeProvider = { + id: REQUIREMENTS_PROVIDER_ID, + dependencies: ["metaobjects-core-types"], + description: + "Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify.", + registerTypes(registry: TypeRegistry): void { + const factories: FactoryMap = {}; + for (const def of REQUIREMENT_DEFINITION.types ?? []) { + factories[`${def.type}.${def.subType}`] = (typeId: TypeId, name: string) => + new MetaRequirement(typeId, name); + } + applyProviderDefinition(registry, REQUIREMENT_DEFINITION, factories); + }, +}; diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 9df5535b5f..c372cd8245 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -262,6 +262,15 @@ export type AnyMeta = export { TypeId, TypeRegistry, childRuleMatches } from "./registry.js"; export type { AttrSchema, ChildRule, TypeDefinition } from "./registry.js"; export { registerCoreTypes, coreTypesProvider, coreProviders } from "./core-types.js"; +// The vocabulary packs in the default bundle, by id, so an embedder can leave one out: +// `composeRegistry(coreProviders.filter((p) => p.id !== REPORTING_PROVIDER_ID))`. +export { rulesProvider, RULES_PROVIDER_ID } from "./core/rules/rules-provider.js"; +export { + viewExpressionsProvider, + VIEW_EXPRESSIONS_PROVIDER_ID, +} from "./persistence/view-expressions/view-expressions-provider.js"; +export { reportingProvider, REPORTING_PROVIDER_ID } from "./core/reporting/reporting-provider.js"; +export { requirementsProvider, REQUIREMENTS_PROVIDER_ID } from "./core/requirement/requirements-provider.js"; // FR-033 — the constraint engine: additive merge + the contradiction validator. export { mergeConstraints } from "./constraint-merge.js"; diff --git a/server/typescript/packages/metadata/src/loader/rules-validation.ts b/server/typescript/packages/metadata/src/loader/rules-validation.ts index e238446ebe..ebd8494cf2 100644 --- a/server/typescript/packages/metadata/src/loader/rules-validation.ts +++ b/server/typescript/packages/metadata/src/loader/rules-validation.ts @@ -42,6 +42,11 @@ // 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) +// P3 ERR_TRANSITION_NAME_COLLISION two permission points ask the policy about one permission name, and at +// least one of the two names is derived (ADR-0066 §1): an operation +// named "Order.open", one declaring @permission "p.Order.open", or one +// in package "p::Order", beside the "open" transition of Order in "p". +// Two DECLARED @permission values may be equal: that sharing is the point. // 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 @@ -94,7 +99,7 @@ import { transitionTo, } from "../core/transition/lifecycle.js"; import { isWritableSource } from "../shared/node-guards.js"; -import { effectivePackageOf } from "../naming-refs.js"; +import { effectivePackageOf, topLevelNodeOf } from "../naming-refs.js"; import { conditionMessage } from "./validation-passes.js"; const RESERVED = new Set(RESERVED_OPERATION_NAMES); @@ -375,9 +380,58 @@ export function validateRules(root: MetaData): ParseError[] { } checkApiRoutes(ops, sink); } + checkPermissionNames(root, sink); return sink.errors; } +interface PermissionPoint { + node: MetaData; + /** True when the name is derived (no @permission), false when declared. */ + derived: boolean; +} + +/** The name a permission point asks the policy about: its @permission, else `.` + * (the path is ``, or `.` for a transition's command). The package + * prefix is dropped when there is none. `::` and `.` both separate path segments, so they compare + * equal: `p::Order` + `open` and `p` + `Order.open` are one name. */ +function permissionNameOf(node: MetaData, owner: MetaData, path: string): { name: string; derived: boolean } { + const declared = node.attr(OPERATION_ATTR_PERMISSION); + const pkg = effectivePackageOf(topLevelNodeOf(owner)); + const name = typeof declared === "string" ? declared : pkg === "" ? path : `${pkg}.${path}`; + return { name: name.replaceAll("::", "."), derived: typeof declared !== "string" }; +} + +/** P3: two permission points, one name. Points are every non-public operation and every transition + * of a live concrete entity (the transitions derive a command each). Compared case-sensitively + * (a grant key is exact). Transitions are registered first, so the error lands on the operation + * when an operation meets a transition. */ +function checkPermissionNames(root: MetaData, sink: Sink): void { + const byName = new Map(); + const register = (node: MetaData, owner: MetaData, path: string): void => { + if (node.attr(OPERATION_ATTR_PUBLIC) === true) return; + const { name, derived } = permissionNameOf(node, owner, path); + const points = byName.get(name) ?? []; + byName.set(name, points); + const clash = points.find((q) => + q.node !== node && (derived || q.derived) && + !(node.type === TYPE_OPERATION && q.node.type === TYPE_OPERATION && sameOperation(q.node, node))); + if (clash !== undefined) { + sink.add(node, "ERR_TRANSITION_NAME_COLLISION", + `${node.type}.${node.subType} "${label(node)}" asks the policy about the permission name "${name}", which ${clash.node.type}.${clash.node.subType} "${label(clash.node)}" also asks about, and one of the two names is derived rather than declared; declare a distinct @permission on one, or rename it.`); + } + points.push({ node, derived }); + }; + for (const entity of root.children()) { + if (entity.type !== TYPE_OBJECT || entity.subType !== OBJECT_SUBTYPE_ENTITY) continue; + if (entity.isAbstract || !lifecycleIsLive(entity)) continue; + for (const t of entityTransitions(entity)) register(t, entity, `${entity.name}.${t.name}`); + } + for (const api of root.children()) { + if (api.type !== TYPE_API) continue; + for (const op of api.children()) if (op.type === TYPE_OPERATION) register(op, api, op.name); + } +} + /** 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); diff --git a/server/typescript/packages/metadata/src/metamodel-docs/provider-definitions.ts b/server/typescript/packages/metadata/src/metamodel-docs/provider-definitions.ts index 318fe0867a..cc56bf2abe 100644 --- a/server/typescript/packages/metadata/src/metamodel-docs/provider-definitions.ts +++ b/server/typescript/packages/metadata/src/metamodel-docs/provider-definitions.ts @@ -29,6 +29,8 @@ import { PROMPT_DEFINITION } from "../template/prompt-definition.embedded.js"; import { API_DEFINITION } from "../core/api/api-definition.embedded.js"; import { TRANSITION_DEFINITION } from "../core/transition/transition-definition.embedded.js"; import { VIEW_EXPRESSIONS_DEFINITION } from "../persistence/view-expressions/view-expressions-definition.embedded.js"; +import { REPORTING_DEFINITION } from "../core/reporting/reporting-definition.embedded.js"; +import { REQUIREMENT_DEFINITION } from "../core/requirement/requirement-definition.embedded.js"; /** * Every embedded provider definition the core metamodel composes from. The @@ -52,8 +54,11 @@ export const ALL_PROVIDER_DEFINITIONS: readonly ProviderDefinition[] = [ UI_WEB_DEFINITION, TEMPLATE_DEFINITION, PROMPT_DEFINITION, - // The business-rules pack (metaobjects-rules) and the view-expressions pack. + // The business-rules pack (metaobjects-rules), the view-expressions pack, the + // reporting pack and the requirements pack. API_DEFINITION, TRANSITION_DEFINITION, VIEW_EXPRESSIONS_DEFINITION, + REPORTING_DEFINITION, + REQUIREMENT_DEFINITION, ]; diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts index 4b0e3618a2..5bb6b2222a 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts @@ -95,14 +95,6 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { - "type": "attr", - "subType": "string", - "name": "segment", - "min": 0, - "max": 1, - "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." - }, { "type": "attr", "subType": "boolean", @@ -177,14 +169,6 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." - }, - { - "type": "attr", - "subType": "string", - "name": "segment", - "min": 0, - "max": 1, - "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } diff --git a/server/typescript/packages/metadata/src/provider-data.ts b/server/typescript/packages/metadata/src/provider-data.ts index 7b8718435d..f94a73b78f 100644 --- a/server/typescript/packages/metadata/src/provider-data.ts +++ b/server/typescript/packages/metadata/src/provider-data.ts @@ -192,6 +192,15 @@ function isUniversalEntry(t: TypeDef): boolean { return t.type === CHILD_RULE_WILDCARD && t.subType === CHILD_RULE_WILDCARD; } +/** + * Resolves a type's `base` when it is not in the definition being lowered: a pack + * that adds a subtype to a type another provider owns (`object.report` in the + * reporting pack) inherits the base that provider registered. + */ +export type ExternalBaseLookup = ( + type: string, +) => { attributes: AttrSchema[]; childRules: ChildRule[] } | undefined; + /** * Turn a declarative `ProviderDefinition` + a code-supplied factory map into the * `TypeDefinition`s a provider passes to `registry.register()`. @@ -219,6 +228,7 @@ function isUniversalEntry(t: TypeDef): boolean { export function defineProviderFromData( data: ProviderDefinition, factories: FactoryMap, + externalBase?: ExternalBaseLookup, ): TypeDefinition[] { // Pre-compute each type's OWN lowered attrs + childRules, keyed by "type.subType", // so base-composition can fold a base's contributions into its subtypes. A @@ -252,7 +262,7 @@ export function defineProviderFromData( } const self = lowered.get(key)!; - const { attributes, childRules } = composeWithBase(t, self, lowered); + const { attributes, childRules } = composeWithBase(t, self, lowered, externalBase); return { typeId: new TypeId(t.type, t.subType), @@ -284,7 +294,16 @@ export function applyProviderDefinition( data: ProviderDefinition, factories: FactoryMap, ): void { - for (const def of defineProviderFromData(data, factories)) { + // A pack may add a subtype to a type another provider owns (the reporting pack's + // object.report): its `extendsBase` folds in that type's `base` as already + // registered, since the base is not in the pack's own definition. + const externalBase: ExternalBaseLookup = (type) => { + const base = registry.find(type, SUBTYPE_BASE); + return base === undefined + ? undefined + : { attributes: [...base.attributes], childRules: [...base.childRules] }; + }; + for (const def of defineProviderFromData(data, factories, externalBase)) { registry.register(def); } const commonAttrs = universalCommonAttrs(data); @@ -361,7 +380,8 @@ export function universalCommonAttrs(data: ProviderDefinition): AttrSchema[] { /** * Fold a real `TypeDef`'s OWN lowered attrs/childRules with its `.base`'s - * (when the definition declares one and this subtype is not itself `base`). + * (when the definition declares one, else the already-registered base `externalBase` + * returns, and this subtype is not itself `base`). * Additive: own entries win on a name (attr) / structural-shape (rule) collision; * base entries the subtype lacks are appended. A NO-OP when there is no base in * THIS definition, or when the subtype already declares the full base set. @@ -370,13 +390,14 @@ function composeWithBase( t: TypeDef, self: { attributes: AttrSchema[]; childRules: ChildRule[] }, lowered: Map, + externalBase?: ExternalBaseLookup, ): { attributes: AttrSchema[]; childRules: ChildRule[] } { // OFF by default (S0): a subtype inherits its base only when it opts in via // `extendsBase: true`. Keeps the current canonical byte-identical — no provider // sets it yet — while the rail is in place for S1. if (t.extendsBase !== true) return self; if (t.subType === SUBTYPE_BASE) return self; - const base = lowered.get(`${t.type}.${SUBTYPE_BASE}`); + const base = lowered.get(`${t.type}.${SUBTYPE_BASE}`) ?? externalBase?.(t.type); if (base === undefined) return self; const attributes = [...self.attributes]; diff --git a/server/typescript/packages/metadata/src/registry.ts b/server/typescript/packages/metadata/src/registry.ts index 1ef3500108..92e815c974 100644 --- a/server/typescript/packages/metadata/src/registry.ts +++ b/server/typescript/packages/metadata/src/registry.ts @@ -217,13 +217,17 @@ export class TypeRegistry { private stampAttrOwner(type: string, subType: string, name: string): void { if (this._currentProviderId === undefined) return; + this.setAttrOwner(type, subType, name, this._currentProviderId); + } + + private setAttrOwner(type: string, subType: string, name: string, owner: string): void { const key = `${type}.${subType}`; let owners = this._attrOwners.get(key); if (owners === undefined) { owners = new Map(); this._attrOwners.set(key, owners); } - owners.set(name, this._currentProviderId); + owners.set(name, owner); } /** @@ -316,7 +320,15 @@ export class TypeRegistry { // ADR-0062: refuse a name another provider already put on a related slot, BEFORE // the definition becomes visible, so a refused registration leaves no trace. const list = this._subTypes.get(def.typeId.type); - for (const attr of def.attributes) { + // An attribute folded in unchanged from the registered `.base` (a pack's + // subtype with `extendsBase`, e.g. object.report) is the base owner's, not a new + // claim: it is not checked against the registering provider, and is stamped with + // the owner the base attribute already has. + const baseAttrs = new Set( + def.typeId.subType === SUBTYPE_BASE ? [] : (this.find(def.typeId.type, SUBTYPE_BASE)?.attributes ?? []), + ); + const claimed = def.attributes.filter((attr) => !baseAttrs.has(attr)); + for (const attr of claimed) { this.checkAttrOwnership(def.typeId.type, def.typeId.subType, attr.name); } this._defs.set(key, def); @@ -325,9 +337,14 @@ export class TypeRegistry { } else { this._subTypes.set(def.typeId.type, [def.typeId.subType]); } - for (const attr of def.attributes) { + for (const attr of claimed) { this.stampAttrOwner(def.typeId.type, def.typeId.subType, attr.name); } + for (const attr of def.attributes) { + if (!baseAttrs.has(attr)) continue; + const baseOwner = this.attrOwner(def.typeId.type, SUBTYPE_BASE, attr.name); + if (baseOwner !== undefined) this.setAttrOwner(def.typeId.type, def.typeId.subType, attr.name, baseOwner); + } } find(type: string, subType: string): TypeDefinition | undefined { diff --git a/server/typescript/packages/metadata/test/conformance/adapter.ts b/server/typescript/packages/metadata/test/conformance/adapter.ts index ab88935953..97bfd692b3 100644 --- a/server/typescript/packages/metadata/test/conformance/adapter.ts +++ b/server/typescript/packages/metadata/test/conformance/adapter.ts @@ -23,6 +23,8 @@ import { uiProvider } from "../../src/presentation/ui/ui-provider.js"; import { uiWebProvider } from "../../src/presentation/ui-web/ui-web-provider.js"; import { rulesProvider } from "../../src/core/rules/rules-provider.js"; import { viewExpressionsProvider } from "../../src/persistence/view-expressions/view-expressions-provider.js"; +import { reportingProvider } from "../../src/core/reporting/reporting-provider.js"; +import { requirementsProvider } from "../../src/core/requirement/requirements-provider.js"; import { MetaDataLoader } from "../../src/loader/meta-data-loader.js"; import type { MetaData } from "../../src/shared/meta-data.js"; import { canonicalSerialize, canonicalSerializeEffective } from "../../src/serializer-json.js"; @@ -163,6 +165,8 @@ export const PROVIDERS: Readonly> = { [uiWebProvider.id]: uiWebProvider, // "metaobjects-ui-web" (view control attrs) [rulesProvider.id]: rulesProvider, // "metaobjects-rules" (api/operation/binding/transition) [viewExpressionsProvider.id]: viewExpressionsProvider, // "metaobjects-view-expressions" (origin.function, @union/@grain) + [reportingProvider.id]: reportingProvider, // "metaobjects-reporting" (object.report, dimension/measure/segment) + [requirementsProvider.id]: requirementsProvider, // "metaobjects-requirements" (requirement.*) // Test-only — provider-extension-* fixtures. "example-template-briefing": exampleTemplateBriefingProvider, "example-custom-vocabulary": exampleCustomVocabularyProvider, diff --git a/server/typescript/packages/metadata/test/index.test.ts b/server/typescript/packages/metadata/test/index.test.ts index 3f0ca21a8a..abfd54a117 100644 --- a/server/typescript/packages/metadata/test/index.test.ts +++ b/server/typescript/packages/metadata/test/index.test.ts @@ -141,6 +141,8 @@ describe("Public API surface — @metaobjectsdev/metadata index", () => { if (t === "origin") continue; // The business-rules pack (metaobjects-rules) owns these; core alone has none. if (t === "api" || t === "operation" || t === "binding" || t === "transition") continue; + // The reporting and requirements packs own these; core alone has none. + if (t === "dimension" || t === "measure" || t === "segment" || t === "requirement") continue; const subs = registry.allSubTypesOf(t); expect(subs.length).toBeGreaterThan(0); } diff --git a/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts b/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts index 3a567083a5..44770973d9 100644 --- a/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts @@ -16,15 +16,17 @@ import { describe, test, expect } from "bun:test"; import { composeRegistry } from "../src/provider.js"; import { coreTypesProvider } from "../src/core-types.js"; import { viewExpressionsProvider } from "../src/persistence/view-expressions/view-expressions-provider.js"; +import { reportingProvider } from "../src/core/reporting/reporting-provider.js"; import { TYPE_ORIGIN } from "../src/shared/base-types.js"; import { ORIGIN_SUBTYPES } from "../src/persistence/origin/origin-constants.js"; -// Compose with ONLY the core-types provider and the view-expressions pack (which -// owns origin.function) — so `def.attributes` reflects +// Compose with ONLY the core-types provider, the view-expressions pack (which +// owns origin.function) and the reporting pack (which adds @segment to +// origin.aggregate and origin.first) — so `def.attributes` reflects // exactly what the ORIGIN provider registered, not the doc-domain attrs that // other providers add via registry.extend(). This isolates the externalization // gate. -const registry = composeRegistry([coreTypesProvider, viewExpressionsProvider]); +const registry = composeRegistry([coreTypesProvider, viewExpressionsProvider, reportingProvider]); type ExpectedAttr = { valueType: string; diff --git a/server/typescript/packages/metadata/test/provider-vocabulary.test.ts b/server/typescript/packages/metadata/test/provider-vocabulary.test.ts index 18e77e9051..24b785bfb6 100644 --- a/server/typescript/packages/metadata/test/provider-vocabulary.test.ts +++ b/server/typescript/packages/metadata/test/provider-vocabulary.test.ts @@ -74,15 +74,18 @@ describe("logical provider vocabulary", () => { for (const p of coreProviders) expect(Object.keys(canonical.providers)).toContain(p.id); }); - test("only core and the two named packs declare types; the rest are pure projections", () => { + test("only core and the four named packs declare types; the rest are pure projections", () => { // The shape ADR-0050 describes, asserted rather than assumed. A type-declaring - // provider beyond these three appearing fails this loudly, which is the moment to + // provider beyond these five appearing fails this loudly, which is the moment to // decide whether the OWN/PROJECTED split still holds. The packs - // (metaobjects-rules, metaobjects-view-expressions) own their types and project - // onto core's; see GOVERNANCE.md, "Extension packs and the core metamodel". + // (metaobjects-reporting, metaobjects-requirements, metaobjects-rules, + // metaobjects-view-expressions) own their types and project onto core's; see + // GOVERNANCE.md, "Extension packs and the core metamodel". const declaring = Object.entries(canonical.providers).filter(([, v]) => v.declaresTypes); expect(declaring.map(([k]) => k)).toEqual([ "metaobjects-core-types", + "metaobjects-reporting", + "metaobjects-requirements", "metaobjects-rules", "metaobjects-view-expressions", ]); diff --git a/server/typescript/packages/metadata/test/provider.test.ts b/server/typescript/packages/metadata/test/provider.test.ts index 349d7a18cd..8c9d6e6543 100644 --- a/server/typescript/packages/metadata/test/provider.test.ts +++ b/server/typescript/packages/metadata/test/provider.test.ts @@ -8,6 +8,8 @@ import { uiProvider } from "../src/presentation/ui/ui-provider.js"; import { uiWebProvider } from "../src/presentation/ui-web/ui-web-provider.js"; import { rulesProvider } from "../src/core/rules/rules-provider.js"; import { viewExpressionsProvider } from "../src/persistence/view-expressions/view-expressions-provider.js"; +import { reportingProvider } from "../src/core/reporting/reporting-provider.js"; +import { requirementsProvider } from "../src/core/requirement/requirements-provider.js"; import { TypeRegistry, TypeId } from "../src/registry.js"; import { MetaField } from "../src/core/field/meta-field.js"; import { @@ -99,7 +101,7 @@ describe("coreTypesProvider", () => { expect(registry.defaultSubTypeOf(TYPE_METADATA)).toBe(SUBTYPE_ROOT); }); - it("coreProviders is an eight-provider bundle: coreTypesProvider + dbProvider + docProvider + promptProvider + uiProvider + uiWebProvider + rulesProvider + viewExpressionsProvider", () => { + it("coreProviders is a ten-provider bundle: coreTypesProvider + dbProvider + docProvider + promptProvider + uiProvider + uiWebProvider + rulesProvider + viewExpressionsProvider + reportingProvider + requirementsProvider", () => { // FR-033 S1-field-A re-homed the field's filter/sort/teaching/extract/storage // attrs out of core into the concern providers. promptProvider (renamed from // templateProvider; id metaobjects-prompt) carries @xmlText/@example/@instruction @@ -112,8 +114,10 @@ describe("coreTypesProvider", () => { // PresentationOnly-excluded rows, so the manifest itself is unaffected. // rulesProvider (metaobjects-rules) and viewExpressionsProvider // (metaobjects-view-expressions) are packs split out of core in 1.3.0; they are in - // the default bundle so no model changes, and each can be composed out. - expect(coreProviders).toHaveLength(8); + // the default bundle so no model changes, and each can be composed out. So are + // reportingProvider (metaobjects-reporting) and requirementsProvider + // (metaobjects-requirements), split out the same way. + expect(coreProviders).toHaveLength(10); expect(coreProviders[0]).toBe(coreTypesProvider); expect(coreProviders[1]).toBe(dbProvider); expect(coreProviders[2]).toBe(docProvider); @@ -122,6 +126,8 @@ describe("coreTypesProvider", () => { expect(coreProviders[5]).toBe(uiWebProvider); expect(coreProviders[6]).toBe(rulesProvider); expect(coreProviders[7]).toBe(viewExpressionsProvider); + expect(coreProviders[8]).toBe(reportingProvider); + expect(coreProviders[9]).toBe(requirementsProvider); }); it("registerCoreTypes registers the structural types but not the DB-domain attrs", () => { @@ -133,10 +139,14 @@ describe("coreTypesProvider", () => { const viaProviders = composeRegistry(coreProviders); // dbProvider only extends and adds no types, so the only types composeRegistry adds - // over core alone are the two packs' (business rules, origin.function). - const packTypes = ["api", "operation", "binding", "transition"]; + // over core alone are the packs' (business rules, origin.function, reporting, + // requirements). + const packTypes = ["api", "operation", "binding", "transition", "dimension", "measure", "segment", "requirement"]; const coreOnly = viaProviders.allTypes().filter( - (t) => !packTypes.includes(t.type) && !(t.type === "origin" && t.subType === "function"), + (t) => + !packTypes.includes(t.type) && + !(t.type === "origin" && t.subType === "function") && + !(t.type === "object" && t.subType === "report"), ); expect(viaWrapper.allTypes().length).toBe(coreOnly.length); diff --git a/server/typescript/packages/metadata/test/registry.test.ts b/server/typescript/packages/metadata/test/registry.test.ts index 81532a91b2..f38462ef7c 100644 --- a/server/typescript/packages/metadata/test/registry.test.ts +++ b/server/typescript/packages/metadata/test/registry.test.ts @@ -16,7 +16,7 @@ import { TYPE_SOURCE, TYPE_ORIGIN, TYPE_TEMPLATE, - TYPE_REQUIREMENT, + OBJECT_SUBTYPE_REPORT, TYPE_API, SUBTYPE_BASE, SUBTYPE_ROOT, @@ -326,9 +326,9 @@ describe("registerCoreTypes", () => { expect(registry.allSubTypesOf(TYPE_METADATA).sort()).toEqual([SUBTYPE_ROOT]); }); - it("registers the correct subtypes for 'object'", () => { + it("registers the correct subtypes for 'object' (core alone: object.report is the reporting pack's)", () => { expect(registry.allSubTypesOf(TYPE_OBJECT).sort()).toEqual( - [...OBJECT_SUBTYPES].sort(), + OBJECT_SUBTYPES.filter((subType) => subType !== OBJECT_SUBTYPE_REPORT).sort(), ); }); @@ -450,15 +450,14 @@ describe("registerCoreTypes", () => { expect(def!.childRules).toHaveLength(0); }); - it("metadata.root (core alone) allows object, field, validator, template and requirement children (NOT a bare attr, and no api: the business-rules pack adds that)", () => { + it("metadata.root (core alone) allows object, field, validator and template children (NOT a bare attr; requirement and api come from their packs)", () => { // 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 - // requirements are declared beside the entities they describe. + // genuinely-open structural wildcards stay. `requirement` (the requirements + // pack) and `api` (the business-rules pack) are admitted by their packs. 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].sort()); }); // 6. attr.* has empty child rules diff --git a/server/typescript/packages/render/src/jinja/nunjucks.ts b/server/typescript/packages/render/src/jinja/nunjucks.ts index bc73ba2f71..4be140871a 100644 --- a/server/typescript/packages/render/src/jinja/nunjucks.ts +++ b/server/typescript/packages/render/src/jinja/nunjucks.ts @@ -7,6 +7,7 @@ import nunjucks from "nunjucks"; import { JINJA_EXTENSIONS } from "../engine.js"; +import { ERR_VAR_NOT_ON_PAYLOAD } from "../verify-shared.js"; import type { Provider } from "../provider.js"; /** A parsed nunjucks node. `fields` names the node's own child slots, in order. */ @@ -26,6 +27,7 @@ interface NunjucksInternals { parser: { parse(src: string): NjNode }; lib: { escape(value: string): string }; compiler: { Compiler: { prototype: CaptureCompiler } }; + runtime: { ensureDefined(value: unknown, lineno: number, colno: number): unknown }; } const internals = nunjucks as unknown as NunjucksInternals; @@ -95,12 +97,25 @@ function environment(provider: Provider): nunjucks.Environment { }; return new nunjucks.Environment(loader as unknown as nunjucks.ILoader, { autoescape: true, - throwOnUndefined: false, + throwOnUndefined: true, // `{{ x }}` on an undefined value raises; see `ensureDefinedOnly` trimBlocks: false, lstripBlocks: false, }); } +/** + * nunjucks' own `throwOnUndefined` check also refuses `null`, which Mustache (and Jinja's + * default) render as empty. Narrowed to `undefined` only, so a missing variable raises the + * same error the Mustache path does and a present `null` still renders empty. The engine + * does not know the variable's name at this point, so the message carries none. + */ +function ensureDefinedOnly(value: unknown): unknown { + if (value === undefined) { + throw new Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`); + } + return value; +} + /** Render Jinja `text` against `context`, escaping every `{{ … }}` with `escaper`. */ export function renderJinjaText( text: string, @@ -116,6 +131,8 @@ export function renderJinjaText( const compiler = internals.compiler.Compiler.prototype; const prevEscape = internals.lib.escape; const prevCapture = compiler.compileCapture; + const prevEnsure = internals.runtime.ensureDefined; + internals.runtime.ensureDefined = ensureDefinedOnly; internals.lib.escape = (v: unknown) => escaper(typeof v === "string" ? v : String(v)); compiler.compileCapture = safeCapture(prevCapture); try { @@ -123,5 +140,6 @@ export function renderJinjaText( } finally { internals.lib.escape = prevEscape; compiler.compileCapture = prevCapture; + internals.runtime.ensureDefined = prevEnsure; } } diff --git a/server/typescript/packages/render/src/render.ts b/server/typescript/packages/render/src/render.ts index 86209fb919..951ee731c9 100644 --- a/server/typescript/packages/render/src/render.ts +++ b/server/typescript/packages/render/src/render.ts @@ -19,7 +19,7 @@ import { type TemplateEngine, } from "./engine.js"; import { renderJinja } from "./jinja/render.js"; -import { MAX_DEPTH } from "./verify-shared.js"; +import { MAX_DEPTH, ERR_VAR_NOT_ON_PAYLOAD } from "./verify-shared.js"; // Resolve `{{> group/source }}` partials by inlining their text, recursively, // BEFORE Mustache parses — giving us deterministic whitespace and true, @@ -110,12 +110,39 @@ export function render(o: RenderOptions): string { return result; } +// A variable tag that resolves to `undefined` (the name is on no frame of the payload) is a +// missing variable. `null` is a present value and renders empty. Raised with the message the +// opt-in `verify` gate uses, so a typo like `{{nmae}}` fails on every render path. +interface WriterInternals { + prototype: Record<"escapedValue" | "unescapedValue", (token: unknown[], context: { lookup(n: string): unknown }, ...r: unknown[]) => unknown>; +} + +function failOnMissingVariable(): () => void { + const proto = (Mustache as unknown as { Writer: WriterInternals }).Writer.prototype; + const prev = { escapedValue: proto.escapedValue, unescapedValue: proto.unescapedValue }; + for (const key of ["escapedValue", "unescapedValue"] as const) { + const original = prev[key]; + proto[key] = function (this: unknown, token, context, ...rest) { + const name = String(token[1]); + if (context.lookup(name) === undefined) { + throw new Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`); + } + return original.call(this, token, context, ...rest); + }; + } + return () => { + proto.escapedValue = prev.escapedValue; + proto.unescapedValue = prev.unescapedValue; + }; +} + function renderMustache(body: string, o: RenderOptions, escaper: (s: string) => string): string { const expanded = expand(body, o.provider, o.ref !== undefined ? [o.ref] : []); const prev = Mustache.escape; Mustache.escape = (v: unknown) => escaper(typeof v === "string" ? v : String(v)); let result: string; + const restore = failOnMissingVariable(); try { // Derived `has` accessors are part of the payload contract, not of the // caller's object — see payload-accessors.ts. Injected here so a `{{#hasFoo}}` @@ -123,6 +150,7 @@ function renderMustache(body: string, o: RenderOptions, escaper: (s: string) => result = Mustache.render(expanded, withDerivedAccessors(o.payload), {}); } finally { Mustache.escape = prev; + restore(); } return result; } diff --git a/server/typescript/packages/render/test/render-conformance.test.ts b/server/typescript/packages/render/test/render-conformance.test.ts index a8efa43395..aa130789ba 100644 --- a/server/typescript/packages/render/test/render-conformance.test.ts +++ b/server/typescript/packages/render/test/render-conformance.test.ts @@ -8,7 +8,7 @@ import { render, InMemoryProvider, type RenderFormat } from "../src/index.js"; // template.mustache the entry template // partials/*.mustache optional partials, referenced as `partials/` // payload.json the render payload (pre-formatted primitives) -// expected.txt byte-exact expected output +// expected.txt byte-exact expected output, or expected-error.txt: the exact error message // The same (payload + template) MUST produce expected.txt byte-for-byte. const CORPUS = join(import.meta.dir, "../../../../../fixtures/render-conformance"); @@ -42,8 +42,14 @@ describe("render-conformance corpus", () => { const meta = JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")) as { format: RenderFormat }; const template = readFileSync(join(dir, "template.mustache"), "utf8"); const payload = JSON.parse(readFileSync(join(dir, "payload.json"), "utf8")); - const expected = readFileSync(join(dir, "expected.txt"), "utf8"); const provider = providerFromPartials(dir); + // expected-error.txt (instead of expected.txt): the exact message the render must throw. + if (existsSync(join(dir, "expected-error.txt"))) { + const message = readFileSync(join(dir, "expected-error.txt"), "utf8").replace(/\n$/, ""); + expect(() => render({ template, payload, provider, format: meta.format })).toThrow(message); + return; + } + const expected = readFileSync(join(dir, "expected.txt"), "utf8"); const actual = render({ template, payload, provider, format: meta.format }); expect(actual).toBe(expected); // determinism: identical across runs diff --git a/server/typescript/packages/render/test/render.test.ts b/server/typescript/packages/render/test/render.test.ts index f29fb633ba..565355f9c2 100644 --- a/server/typescript/packages/render/test/render.test.ts +++ b/server/typescript/packages/render/test/render.test.ts @@ -144,3 +144,20 @@ describe("render — maxChars output budget", () => { expect(render({ template: "{{x}}", payload: { x: long }, provider: P({}) })).toBe(long); }); }); + +describe("a missing variable raises on every render path", () => { + test("mustache: a variable absent from the payload throws the verify error by default", () => { + expect(() => render({ template: "Hi {{nmae}}!", payload: { name: "Ada" }, provider: P({}) })).toThrow( + "render verify failed: ERR_VAR_NOT_ON_PAYLOAD (nmae)", + ); + expect(() => render({ template: "Hi {{{nmae}}}!", payload: {}, provider: P({}) })).toThrow(/ERR_VAR_NOT_ON_PAYLOAD \(nmae\)/); + }); + test("mustache: null is present and renders empty; absent sections stay legal", () => { + expect(render({ template: "Hi {{n}}!{{#x}}y{{/x}}", payload: { n: null }, provider: P({}) })).toBe("Hi !"); + }); + test("jinja: a variable absent from the payload throws", () => { + expect(() => render({ template: "Hi {{ nmae }}!", payload: { name: "Ada" }, provider: P({}), engine: "jinja" })).toThrow( + /ERR_VAR_NOT_ON_PAYLOAD/, + ); + }); +}); diff --git a/site-reference/providers.html b/site-reference/providers.html index 2f4e15ae08..2c55cd7c41 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -51,7 +51,7 @@ INDEX.md lists by type.

metaobjects-core-types

Core metaobjects metamodel types and subtypes.

-

Owns (registers): attr.base, attr.boolean, attr.class, attr.double, attr.expression, attr.filter, attr.int, attr.intMap, attr.long, attr.properties, attr.string, field.base, field.boolean, field.currency, field.date, field.decimal, field.double, field.duration, field.enum, field.float, field.inet, field.int, field.long, field.map, field.object, field.string, field.time, field.timestamp, field.uri, field.uuid, identity.primary, identity.reference, identity.secondary, layout.base, layout.dataGrid, object.base, object.entity, object.projection, object.report, object.value, origin.aggregate, origin.base, origin.computed, origin.first, origin.passthrough, relationship.aggregation, relationship.association, relationship.base, relationship.composition, source.base, source.rdb, template.base, template.output, template.prompt, template.toolcall, validator.array, validator.atLeastOne, validator.base, validator.comparison, validator.exactlyOne, validator.length, validator.numeric, validator.presentIff, validator.regex, validator.required, validator.requiredWhen, view.base, view.checkbox, view.currency, view.date, view.dropdown, view.hidden, view.hotlink, view.image, view.month, view.number, view.password, view.radio, view.text, view.textarea, view.web

+

Owns (registers): attr.base, attr.boolean, attr.class, attr.double, attr.expression, attr.filter, attr.int, attr.intMap, attr.long, attr.properties, attr.string, field.base, field.boolean, field.currency, field.date, field.decimal, field.double, field.duration, field.enum, field.float, field.inet, field.int, field.long, field.map, field.object, field.string, field.time, field.timestamp, field.uri, field.uuid, identity.primary, identity.reference, identity.secondary, layout.base, layout.dataGrid, object.base, object.entity, object.projection, object.value, origin.aggregate, origin.base, origin.computed, origin.first, origin.passthrough, relationship.aggregation, relationship.association, relationship.base, relationship.composition, source.base, source.rdb, template.base, template.output, template.prompt, template.toolcall, validator.array, validator.atLeastOne, validator.base, validator.comparison, validator.exactlyOne, validator.length, validator.numeric, validator.presentIff, validator.regex, validator.required, validator.requiredWhen, view.base, view.checkbox, view.currency, view.date, view.dropdown, view.hidden, view.hotlink, view.image, view.month, view.number, view.password, view.radio, view.text, view.textarea, view.web

Contributes attributes:

  • field.base: @default, @mutability, @required, @unique
  • @@ -69,10 +69,9 @@

    metaobjects-core-types

  • object.base: @object, @objectAdapter
  • object.entity: @collectionName, @discriminator, @discriminatorValue
  • object.projection: @collectionName, @filter
  • -
  • object.report: @collectionName, @dimensions, @filter, @from, @measures, @segment, @spine
  • -
  • origin.aggregate: @agg, @distinct, @filter, @of, @orderBy, @segment, @via
  • +
  • origin.aggregate: @agg, @distinct, @filter, @of, @orderBy, @via
  • origin.computed: @expr
  • -
  • origin.first: @filter, @of, @orderBy, @segment, @via
  • +
  • origin.first: @filter, @of, @orderBy, @via
  • origin.passthrough: @convert, @from, @via
  • relationship.aggregation: @cardinality, @objectRef, @onDelete, @onUpdate, @sourceRefField, @symmetric, @through
  • relationship.association: @cardinality, @objectRef, @onDelete, @onUpdate, @sourceRefField, @symmetric, @through
  • @@ -157,6 +156,29 @@

    metaobjects-prompt

  • field.uuid: @example, @instruction, @xmlText
  • object.value: @normalize
+

metaobjects-reporting

+

Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.

+

Owns (registers): dimension.attribute, dimension.time, measure.aggregate, measure.derived, measure.ratio, object.report, segment.filter

+

Contributes attributes:

+
    +
  • dimension.attribute: @of, @via
  • +
  • dimension.time: @grains, @of, @via
  • +
  • measure.aggregate: @agg, @default, @distinct, @filter, @of, @segment
  • +
  • measure.derived: @expr
  • +
  • measure.ratio: @default, @denominator, @numerator
  • +
  • object.report: @collectionName, @dimensions, @filter, @from, @measures, @segment, @spine
  • +
  • origin.aggregate: @segment
  • +
  • origin.first: @segment
  • +
  • segment.filter: @filter
  • +
+

metaobjects-requirements

+

Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify.

+

Owns (registers): requirement.architectural, requirement.functional

+

Contributes attributes:

+
    +
  • requirement.architectural: @counterexample, @disposition, @implementedBy, @level, @statement, @status, @supersededBy, @trackedBy
  • +
  • requirement.functional: @counterexample, @disposition, @implementedBy, @level, @statement, @status, @supersededBy, @trackedBy
  • +

metaobjects-rules

Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).

Owns (registers): api.base, api.operational, binding.base, binding.rest, operation.base, operation.command, operation.query, transition.action, transition.base

diff --git a/site-reference/types/dimension.html b/site-reference/types/dimension.html index e033e0e119..2c9acd6c0d 100644 --- a/site-reference/types/dimension.html +++ b/site-reference/types/dimension.html @@ -52,6 +52,7 @@ (min..max, * = unbounded).

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.

+

Owning provider: metaobjects-reporting

When to use: A column a dashboard groups by: product, status, region. Declare it once on the fact entity and reference it by name from reports.

Attributes

@@ -72,7 +73,7 @@

dimension.attribute

- + @@ -81,7 +82,7 @@

dimension.attribute

- +
yes —metaobjects-reporting Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own.
no —metaobjects-reporting Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference.
@@ -89,6 +90,7 @@

dimension.attribute

No structural children.

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

+

Owning provider: metaobjects-reporting

When to use: Per-day, per-week or per-month series on a dashboard.

Attributes

@@ -109,7 +111,7 @@

dimension.time

- + @@ -118,7 +120,7 @@

dimension.time

- + @@ -127,7 +129,7 @@

dimension.time

- +
yes hour, day, week, month, quarter, year—metaobjects-reporting The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date.
yes —metaobjects-reporting Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object.
no —metaobjects-reporting Optional dotted to-one relationship path, as on dimension.attribute.
diff --git a/site-reference/types/measure.html b/site-reference/types/measure.html index 08479ad7ad..e5d2c731d4 100644 --- a/site-reference/types/measure.html +++ b/site-reference/types/measure.html @@ -52,6 +52,7 @@ (min..max, * = unbounded).

measure.aggregate

A named aggregate over the declaring entity's own rows (FR-044). @agg count without @distinct counts rows; with @distinct it counts distinct values of @of (a list in @of is a distinct count of the tuple). Unlike origin.aggregate, count is NOT distinct by default: a measure aggregates its own rows and dimensions reach only to-one paths, so no join inflates it.

+

Owning provider: metaobjects-reporting

When to use: A number a dashboard shows: revenue, purchases, distinct buyers, last activity.

Attributes

@@ -72,7 +73,7 @@

measure.aggregate

- + @@ -81,7 +82,7 @@

measure.aggregate

- + @@ -90,7 +91,7 @@

measure.aggregate

- + @@ -99,7 +100,7 @@

measure.aggregate

- + @@ -108,7 +109,7 @@

measure.aggregate

- + @@ -117,7 +118,7 @@

measure.aggregate

- +
yes count, sum, avg, min, max, any, all—metaobjects-reporting The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment.
no —metaobjects-reporting Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null), on min/max over a field that is not numeric, and on @agg any/all unless it is 0 (false) or 1 (true). A ratio's operand carries its own @default into the ratio.
no —metaobjects-reporting Count distinct values. Legal only with @agg: count.
no —metaobjects-reporting Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: "-P7D" }). Combines with @segment by AND.
no —metaobjects-reporting Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows.
no —metaobjects-reporting Optional name of a segment declared on the same entity. Combines with @filter by AND.
@@ -125,6 +126,7 @@

measure.aggregate

No structural children.

measure.derived

A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.

+

Owning provider: metaobjects-reporting

When to use: A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).

Attributes

@@ -145,7 +147,7 @@

measure.derived

- +
yes —metaobjects-reporting The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands.
@@ -153,6 +155,7 @@

measure.derived

No structural children.

measure.ratio

A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null.

+

Owning provider: metaobjects-reporting

When to use: Averages per unit that are not a plain avg: average days engaged per starter.

Attributes

@@ -173,7 +176,7 @@

measure.ratio

- + @@ -182,7 +185,7 @@

measure.ratio

- + @@ -191,7 +194,7 @@

measure.ratio

- +
no —metaobjects-reporting Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio.
yes —metaobjects-reporting Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field.
yes —metaobjects-reporting Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field.
diff --git a/site-reference/types/object.html b/site-reference/types/object.html index 88ec8d0e73..51afe20081 100644 --- a/site-reference/types/object.html +++ b/site-reference/types/object.html @@ -274,7 +274,7 @@

object.projection

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.

-

Owning provider: metaobjects-core-types

+

Owning provider: metaobjects-reporting

When to use: Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.

Attributes

@@ -295,7 +295,7 @@

object.report

- + @@ -304,7 +304,7 @@

object.report

- + @@ -313,7 +313,7 @@

object.report

- + @@ -322,7 +322,7 @@

object.report

- + @@ -331,7 +331,7 @@

object.report

- + @@ -358,7 +358,7 @@

object.report

- + @@ -367,7 +367,7 @@

object.report

- +
no metaobjects-core-typesmetaobjects-reporting The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own).
no metaobjects-core-typesmetaobjects-reporting Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row.
no metaobjects-core-typesmetaobjects-reporting Optional row scope over @from's fields; may use relative-date values.
yes metaobjects-core-typesmetaobjects-reporting The object.entity whose rows the report aggregates.
yes metaobjects-core-typesmetaobjects-reporting Measure names of @from.
no metaobjects-core-typesmetaobjects-reporting Optional segment of @from scoping the rows.
no metaobjects-core-typesmetaobjects-reporting Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report.
diff --git a/site-reference/types/origin.html b/site-reference/types/origin.html index c04fac091c..5b2c9b8464 100644 --- a/site-reference/types/origin.html +++ b/site-reference/types/origin.html @@ -119,7 +119,7 @@

origin.aggregate

no -metaobjects-core-types +metaobjects-reporting Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. @@ -221,7 +221,7 @@

origin.first

no -metaobjects-core-types +metaobjects-reporting Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. diff --git a/site-reference/types/requirement.html b/site-reference/types/requirement.html index be6dfd9d4e..b8216fd7ad 100644 --- a/site-reference/types/requirement.html +++ b/site-reference/types/requirement.html @@ -52,6 +52,7 @@ (min..max, * = unbounded).

requirement.architectural

How the system is built, applied uniformly across the model. Its check is UNIVERSALITY, the opposite polarity to a functional requirement. What meta verify enforces is that a live or partial policy is applied at all — one claiming nothing is an error — not that each node it claims complies. Flat by default and object-independent; it may optionally sit in a levelled tree when a quality taxonomy is being used to organise non-functional requirements.

+

Owning provider: metaobjects-requirements

When to use: Something exists because every entity here looks like this — a uuid primary key, an @autoSet createdAt, a change-attribution column, tenant scoping. The discriminator is mechanical: did this exist because someone asked for something, or because it is the architecture? For a non-functional tree, an established quality taxonomy makes a good fixed upper structure (e.g. an ISO/IEC 25010 characteristic at L1, its sub-characteristic or a control-catalogue category at L2), with the model-binding claims at L4 and L5 as usual.

Attributes

@@ -72,7 +73,7 @@

requirement.architectural

- + @@ -81,7 +82,7 @@

requirement.architectural

- + @@ -90,7 +91,7 @@

requirement.architectural

- + @@ -99,7 +100,7 @@

requirement.architectural

- + @@ -108,7 +109,7 @@

requirement.architectural

- + @@ -117,7 +118,7 @@

requirement.architectural

- + @@ -126,7 +127,7 @@

requirement.architectural

- + @@ -135,7 +136,7 @@

requirement.architectural

- +
yes —metaobjects-requirements What breaking it looks like — the node that would contradict it. A STATIC falsifiability test, not a state. This is what makes universality checkable. Renamed from @violation in 0.24.0, which read as a status.
no accepted, deferred—metaobjects-requirements As on requirement.functional. On an architectural requirement, accepted is the common and important case: a policy that is genuinely not universal, where the exceptions are known and tolerated, is more honest as partial+accepted than as a live claim nobody audits.
no —metaobjects-requirements FQN references to the nodes applying this policy. High fan-out is normal and expected: one uuid-primary-key requirement is claimed by every entity.
no —metaobjects-requirements OPTIONAL here, unlike on a functional requirement where it is required. ABSENT means a flat, object-independent policy that may reference the model directly — the original and still the default form. PRESENT means this node sits in a levelled tree, and then the same rules as functional apply: nesting must agree with the level, and only L4/L5 may carry @implementedBy. Levelling is opt-in so that adding a taxonomy on top of existing flat policies does not invalidate them.
yes —metaobjects-requirements The policy, in one sentence.
yes planned, live, partial, retired—metaobjects-requirements As on requirement.functional. A live or partial architectural requirement claimed by NOTHING is an error: a policy declared and applied to nothing. planned is exempt from that check — it is not applied yet by definition — and retired is exempt because a withdrawn policy governs nothing.
no —metaobjects-requirements The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not.
no —metaobjects-requirements As on requirement.functional. Issue or ticket references for outstanding work; free-form, not resolved.
@@ -145,6 +146,7 @@

requirement.architectural

requirement.functional

What the product does for a user, stated as one violable claim. Its check is EXISTENCE, run by meta verify: a live or partial claim with no implementing node anywhere in its subtree is a warning, and a named node that no longer exists is an error. Hierarchy is nesting — an L1 solution contains its L2 segments, which contain L3 services, and so on down to the levels that reference the model.

+

Owning provider: metaobjects-requirements

When to use: Something exists because someone asked for it. L1-L3 are levels of ABSTRACTION AND OWNERSHIP in the problem domain — whose need is this, and at what altitude — and are never a directory, package, deployable or module. Binding to technical constructs happens only at L4 (an object) and L5 (a member), which is the allocation step. Test every node: if a refactor that changes no behaviour would force it to move, its level is wrong.

Attributes

@@ -165,7 +167,7 @@

requirement.functional

- + @@ -174,7 +176,7 @@

requirement.functional

- + @@ -183,7 +185,7 @@

requirement.functional

- + @@ -192,7 +194,7 @@

requirement.functional

- + @@ -201,7 +203,7 @@

requirement.functional

- + @@ -210,7 +212,7 @@

requirement.functional

- + @@ -219,7 +221,7 @@

requirement.functional

- + @@ -228,7 +230,7 @@

requirement.functional

- +
yes —metaobjects-requirements What breaking it looks like, in one sentence — a STATIC falsifiability test, authored once, never a state. A requirement MUST be violable: 'every entity has a uuid primary key' is (point at one with a composite string key); 'things are persisted' is not, and is a description rather than a requirement. Renamed from @violation in 0.24.0, which read as a status.
no accepted, deferred—metaobjects-requirements What has been DECIDED about outstanding work — a different question from whether the work is done, which is what @status answers. accepted: the gap is understood and deliberately not being closed. deferred: it will be closed, but not now. ABSENT MEANS UNDECIDED, which is a real and useful state — it is what an unreviewed gap looks like, and it is the one a review should be able to find. Meaningful on planned and partial only; on a status with no outstanding work it is a WARNING. Deliberately NOT a workflow vocabulary: which sprint, who owns it and whether it is in progress belong in the tracker named by @trackedBy, because two systems holding that answer will drift and only one of them is refreshed daily.
no —metaobjects-requirements FQN references to the model nodes realising this requirement. Legal on level 4 (an object) and level 5 (a field, view or identity) only; an organisational level carrying it is ERR_REQUIREMENT_LINK_ABOVE_FLOOR. Many-to-many by construction — several requirements may name the same node.
yes —metaobjects-requirements 1 solution, 2 segment, 3 service, 4 object, 5 member. L1-L3 are levels of abstraction and ownership in the problem domain, NOT of code structure. Nesting depth must agree with it; skipping a level is legal, going back up is not.
yes —metaobjects-requirements What the capability is, in one sentence.
yes planned, live, partial, retired—metaobjects-requirements planned intended but not built yet; live implemented and in use; partial implemented with known gaps; retired BUILT THEN DELIBERATELY REMOVED — it must not be rebuilt. A requirement is PRESCRIPTIVE: it states what SHOULD be true and never journals what happened, and retired satisfies that because it states a prohibition in force, falsifiable by the capability reappearing. On retired, @implementedBy is REFUSED at load (ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS) — a retired capability has no implementation by definition, so its references cannot dangle because they cannot exist; @supersededBy names the requirement that replaced it. A dangling @implementedBy is an ERROR on live/partial (the model moved, the requirement is stale) and ALLOWED on planned, where the nodes do not exist YET. Neither planned nor retired contributes to object coverage: planning a capability must not silence the warning that nothing implements it, and neither must retiring one.
no —metaobjects-requirements The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not.
no —metaobjects-requirements Issue or ticket references for outstanding work — a URL, an owner/repo#123 shorthand, or a tracker key. Free-form and NOT resolved by verify, which does not reach the network; nothing here is checked to exist. Its job is to stop a deferred gap becoming invisible, so verify warns when a deferred requirement names no ticket. Also the right place to link the ticket that a planned requirement will be built under.
diff --git a/site-reference/types/segment.html b/site-reference/types/segment.html index 7c956d2e60..1ca0e1f6ea 100644 --- a/site-reference/types/segment.html +++ b/site-reference/types/segment.html @@ -52,6 +52,7 @@ (min..max, * = unbounded).

segment.filter

A named, reusable row filter on the declaring entity (FR-044). Measures and reports reference it by name; exporters emit it as a named segment.

+

Owning provider: metaobjects-reporting

When to use: The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.

Attributes

@@ -72,7 +73,7 @@

segment.filter

- +
yes —metaobjects-reporting The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values.
diff --git a/spec/metamodel/object.json b/spec/metamodel/object.json index ddf3c6eeec..ad288e6015 100644 --- a/spec/metamodel/object.json +++ b/spec/metamodel/object.json @@ -26,9 +26,6 @@ "children": [ { "type": "relationship", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "template", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } @@ -56,22 +53,6 @@ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] - }, - { - "type": "object", - "subType": "report", - "extendsBase": true, - "description": "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.", - "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", - "children": [ - { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, - { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, - { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, - { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } - ] } ] } diff --git a/spec/metamodel/origin.json b/spec/metamodel/origin.json index c4fde970f9..4d7e5aea16 100644 --- a/spec/metamodel/origin.json +++ b/spec/metamodel/origin.json @@ -28,7 +28,6 @@ { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -52,8 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." } ] } ] diff --git a/spec/metamodel/reporting.json b/spec/metamodel/reporting.json index adbe87f9ed..10a888b0c3 100644 --- a/spec/metamodel/reporting.json +++ b/spec/metamodel/reporting.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-reporting", "types": [ { "type": "dimension", "subType": "attribute", "description": "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.", @@ -46,6 +46,35 @@ "whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 1, "max": 1, "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } + ] }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "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.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, + { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, + { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, + { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + } + ], + "extends": [ + { "type": "object", "subType": "entity", "children": [ + { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null } + ] }, + { "type": "origin", "subType": "aggregate", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + ] }, + { "type": "origin", "subType": "first", "children": [ + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] } diff --git a/spec/metamodel/requirement.json b/spec/metamodel/requirement.json index f3017fd78d..a74ebd5758 100644 --- a/spec/metamodel/requirement.json +++ b/spec/metamodel/requirement.json @@ -1,5 +1,5 @@ { - "provider": "metaobjects-core-types", + "provider": "metaobjects-requirements", "types": [ { "type": "requirement", @@ -185,5 +185,10 @@ } ] } + ], + "extends": [ + { "type": "metadata", "subType": "root", "children": [ + { "type": "requirement", "subType": "*", "name": "*", "min": 0, "max": null } + ] } ] } From 9384916a332fd69527ef7bc9ae892e74b3671412 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 13:30:44 -0500 Subject: [PATCH 09/23] fix(rules): compare P3 permission names exactly, so '::' and '.' are not one name The P3 collision check rewrote '::' to '.' before comparing, so a derived p::Order.open counted as a collision with the transition's p.Order.open. They are different names in the metadata and the policy receives them as written. Removed the rewrite in TS, C#, Java, Python and Rust. The former error-rules-permission-name-op-package fixture becomes rules-permission-name-package-separator-distinct, which every port's conformance runner now loads clean. --- CHANGELOG.md | 6 +- docs/features/business-rules.md | 2 +- .../expected-errors.json | 15 ----- .../expected.json | 67 +++++++++++++++++++ .../input/meta.orders.api.json | 0 .../input/meta.orders.json | 0 .../providers.json | 0 .../Loader/ValidationPasses.Rules.cs | 5 +- .../metaobjects/loader/RulesValidation.java | 5 +- .../src/metaobjects/loader/validate_rules.py | 8 +-- server/rust/metaobjects/src/validate/rules.rs | 9 +-- .../metadata/src/loader/rules-validation.ts | 7 +- 12 files changed, 91 insertions(+), 33 deletions(-) delete mode 100644 fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json create mode 100644 fixtures/conformance/rules-permission-name-package-separator-distinct/expected.json rename fixtures/conformance/{error-rules-permission-name-op-package => rules-permission-name-package-separator-distinct}/input/meta.orders.api.json (100%) rename fixtures/conformance/{error-rules-permission-name-op-package => rules-permission-name-package-separator-distinct}/input/meta.orders.json (100%) rename fixtures/conformance/{error-rules-permission-name-op-package => rules-permission-name-package-separator-distinct}/providers.json (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3a7f53bab..e59f8614b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -158,10 +158,12 @@ here.** `expected.txt`. - **Business rules: two operations or transitions whose permission names come out equal are refused (rule P3).** A permission name is the declared `@permission`, or else the derived - `.` (a `::` package separator reads as `.`). When two permission points resolve to + `.`, compared exactly as the policy receives it, so `p::Order.open` and + `p.Order.open` are two names. When two permission points resolve to the same name and at least one of the two names is derived, the loader reports `ERR_TRANSITION_NAME_COLLISION` on the later one. Two equal declared names stay legal: that is a - shared permission. New fixtures `error-rules-permission-name-op-{dotted,declared,package}`. + shared permission. New fixtures `error-rules-permission-name-op-{dotted,declared}` and + `rules-permission-name-package-separator-distinct`. - **Python: unions and one-row-per-list-item views are checked at load.** The two must-fail projection fixtures (a `@union` whose branches do not line up, and a `@grain` view that breaks its rules) now fail in Python as they do in the other ports, and leave the Python diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index c5f7ef7395..cc8dc8bfdd 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -186,7 +186,7 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa | 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. | -| P3 | `ERR_TRANSITION_NAME_COLLISION` | Two permission points ask about one permission name and at least one name is derived: an operation named `Order.open`, one declaring `permission: p.Order.open`, or one in package `p::Order`, beside the `open` transition of `Order` in `p`. `::` and `.` compare equal. Two declared `permission` values may be equal. | +| P3 | `ERR_TRANSITION_NAME_COLLISION` | Two permission points ask about one permission name and at least one name is derived: an operation named `Order.open`, or one declaring `permission: p.Order.open`, beside the `open` transition of `Order` in `p`. Names are compared exactly as the policy receives them: `::` and `.` are different things in the metadata, so an `open` operation in package `p::Order` (`p::Order.open`) does not collide with that transition (`p.Order.open`). Two declared `permission` values may be equal. | | B1 | `ERR_BINDING_PATH_MISMATCH` | A `binding.rest` `path` has the wrong placeholders. | | B2 | `ERR_BINDING_PATH_MISMATCH` | Two declared bindings of one API have the same method (declared or derived) and the same path, ignoring placeholder names. | diff --git a/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json b/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json deleted file mode 100644 index 9728c81073..0000000000 --- a/fixtures/conformance/error-rules-permission-name-op-package/expected-errors.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "errors": [ - { - "code": "ERR_TRANSITION_NAME_COLLISION", - "source": { - "format": "json", - "files": [ - "meta.orders.api.json" - ], - "jsonPath": "$['metadata.root'].children[0]['api.operational'].children[0]['operation.query']" - } - } - ], - "warnings": [] -} diff --git a/fixtures/conformance/rules-permission-name-package-separator-distinct/expected.json b/fixtures/conformance/rules-permission-name-package-separator-distinct/expected.json new file mode 100644 index 0000000000..4e90e966c3 --- /dev/null +++ b/fixtures/conformance/rules-permission-name-package-separator-distinct/expected.json @@ -0,0 +1,67 @@ +{ + "metadata.root": { + "children": [ + { + "api.operational": { + "name": "Orders", + "package": "p::Order", + "children": [ + { + "operation.query": { + "name": "open", + "@outputRef": "p::Order" + } + } + ] + } + }, + { + "object.entity": { + "name": "Order", + "package": "p", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "field.enum": { + "name": "status", + "@default": "draft", + "@values": [ + "draft", + "open" + ], + "children": [ + { + "transition.action": { + "name": "open", + "@from": [ + "draft" + ], + "@to": "open" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json b/fixtures/conformance/rules-permission-name-package-separator-distinct/input/meta.orders.api.json similarity index 100% rename from fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.api.json rename to fixtures/conformance/rules-permission-name-package-separator-distinct/input/meta.orders.api.json diff --git a/fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json b/fixtures/conformance/rules-permission-name-package-separator-distinct/input/meta.orders.json similarity index 100% rename from fixtures/conformance/error-rules-permission-name-op-package/input/meta.orders.json rename to fixtures/conformance/rules-permission-name-package-separator-distinct/input/meta.orders.json diff --git a/fixtures/conformance/error-rules-permission-name-op-package/providers.json b/fixtures/conformance/rules-permission-name-package-separator-distinct/providers.json similarity index 100% rename from fixtures/conformance/error-rules-permission-name-op-package/providers.json rename to fixtures/conformance/rules-permission-name-package-separator-distinct/providers.json diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs index a18ad72619..2c0b2c601d 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Rules.cs @@ -380,13 +380,14 @@ private sealed record PermissionPoint(MetaData Node, bool Derived); /// The name a permission point asks the policy about: its @permission, else <package>.<path> /// (the path is the operation name, or <Entity>.<transition> for a transition's command). The package - /// prefix is dropped when there is none. :: and . both separate path segments, so they compare equal. + /// prefix is dropped when there is none. The name is compared exactly as the policy receives it: :: and . + /// are different things in the metadata, so p::Order.open and p.Order.open are two names. private static (string Name, bool Derived) PermissionNameOf(MetaData node, MetaData owner, string path) { var declared = node.Attr(OPERATION_ATTR_PERMISSION) as string; var pkg = NamingRefs.EffectivePackageOf(NamingRefs.TopLevelNodeOf(owner)); var name = declared ?? (pkg.Length == 0 ? path : $"{pkg}.{path}"); - return (name.Replace("::", "."), declared is null); + return (name, declared is null); } /// P3: two permission points, one name, at least one of the two derived. Points are every non-public diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java index 7358a4b167..74b0451f3d 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java @@ -469,8 +469,9 @@ private static void registerPermissionPoint(MetaData node, MetaData owner, Strin if (flag(node, ApiConstants.ATTR_PUBLIC)) return; String declared = Lifecycles.stringValue(node, ApiConstants.ATTR_PERMISSION); String pkg = References.effectivePackageOf(owner); - String raw = declared != null ? declared : pkg.isEmpty() ? path : pkg + "." + path; - String name = raw.replace("::", "."); + // Compared exactly as the policy receives it: "::" and "." are different things in the + // metadata, so "p::Order.open" and "p.Order.open" are two names. + String name = declared != null ? declared : pkg.isEmpty() ? path : pkg + "." + path; boolean derived = declared == null; List points = byName.computeIfAbsent(name, k -> new ArrayList<>()); PermissionPoint clash = null; diff --git a/server/python/src/metaobjects/loader/validate_rules.py b/server/python/src/metaobjects/loader/validate_rules.py index 0d37c3626c..ead5659bd2 100644 --- a/server/python/src/metaobjects/loader/validate_rules.py +++ b/server/python/src/metaobjects/loader/validate_rules.py @@ -500,16 +500,16 @@ def validate_rules(root: MetaData, errors: list[MetaError]) -> None: def _permission_name_of(node: MetaData, owner: MetaData, path: str) -> tuple[str, bool]: """The name a permission point asks the policy about: its @permission, else ``.`` (the path is ````, or ``.`` for a - transition's command), with the package prefix dropped when there is none. ``::`` and - ``.`` both separate path segments, so ``p::Order`` + ``open`` and ``p`` + ``Order.open`` - are one name. Returns (name, derived).""" + transition's command), with the package prefix dropped when there is none. The name is + compared exactly as the policy receives it: ``::`` and ``.`` are different things in the + metadata, so ``p::Order.open`` and ``p.Order.open`` are two names. Returns (name, derived).""" declared = node.get_meta_attr(OPERATION_ATTR_PERMISSION) pkg = effective_package_of(top_level_node_of(owner)) if isinstance(declared, str): name = declared else: name = path if pkg == "" else f"{pkg}.{path}" - return name.replace("::", "."), not isinstance(declared, str) + return name, not isinstance(declared, str) def _check_permission_names(root: MetaData, sink: _Sink) -> None: diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index 4296e5891c..7a66656fcc 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -1102,9 +1102,10 @@ fn check_api_routes(tree: &Tree, ops: &[NodeId], sink: &mut Sink<'_>) { } /// The name a permission point asks the policy about: its `@permission`, else -/// `.` (the package prefix is dropped when there is none). `::` and `.` -/// both separate path segments, so they compare equal. Returns the name and whether it -/// is derived. +/// `.` (the package prefix is dropped when there is none). The name is +/// compared exactly as the policy receives it: `::` and `.` are different things in the +/// metadata, so `p::Order.open` and `p.Order.open` are two names. Returns the name and +/// whether it is derived. fn permission_name_of(tree: &Tree, node: NodeId, owner: NodeId, path: &str) -> (String, bool) { let declared = match tree.attr(node, A_PERMISSION) { Some(Value::String(s)) => Some(s.as_str()), @@ -1116,7 +1117,7 @@ fn permission_name_of(tree: &Tree, node: NodeId, owner: NodeId, path: &str) -> ( None if pkg.is_empty() => path.to_string(), None => format!("{pkg}.{path}"), }; - (name.replace(PACKAGE_SEP, "."), declared.is_none()) + (name, declared.is_none()) } /// P3: two permission points, one name. Points are every non-public operation and every diff --git a/server/typescript/packages/metadata/src/loader/rules-validation.ts b/server/typescript/packages/metadata/src/loader/rules-validation.ts index ebd8494cf2..669c7698ff 100644 --- a/server/typescript/packages/metadata/src/loader/rules-validation.ts +++ b/server/typescript/packages/metadata/src/loader/rules-validation.ts @@ -392,13 +392,14 @@ interface PermissionPoint { /** The name a permission point asks the policy about: its @permission, else `.` * (the path is ``, or `.` for a transition's command). The package - * prefix is dropped when there is none. `::` and `.` both separate path segments, so they compare - * equal: `p::Order` + `open` and `p` + `Order.open` are one name. */ + * prefix is dropped when there is none. The name is compared exactly as the policy receives it: + * `::` and `.` are different things in the metadata, so `p::Order.open` and `p.Order.open` are + * two names, not one. */ function permissionNameOf(node: MetaData, owner: MetaData, path: string): { name: string; derived: boolean } { const declared = node.attr(OPERATION_ATTR_PERMISSION); const pkg = effectivePackageOf(topLevelNodeOf(owner)); const name = typeof declared === "string" ? declared : pkg === "" ? path : `${pkg}.${path}`; - return { name: name.replaceAll("::", "."), derived: typeof declared !== "string" }; + return { name, derived: typeof declared !== "string" }; } /** P3: two permission points, one name. Points are every non-public operation and every transition From 2822a9baf654b83319fa911bd54d3c543bfbff0b Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:44:15 -0500 Subject: [PATCH 10/23] no-mistakes(review): apply reviewer inline fixes --- .../src/main/java/com/metaobjects/loader/RulesValidation.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java index 74b0451f3d..b4f8dac5c7 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/RulesValidation.java @@ -441,8 +441,8 @@ private record PermissionPoint(MetaData node, boolean derived) {} * P3: two permission points ask the policy about one permission name, and at least one of the two * names is derived. Points are every non-public operation and every transition of a live concrete * entity (a transition derives a command each). A name is the node's {@code @permission}, else - * {@code .} (the path is the operation name, or {@code Entity.transition}); {@code ::} - * and {@code .} both separate segments so they compare equal. Compared case-sensitively. Transitions + * {@code .} (the path is the operation name, or {@code Entity.transition}); the name is + * compared exactly, so {@code ::} and {@code .} are different and never equal. Compared case-sensitively. Transitions * register first, so the error lands on the operation when an operation meets a transition. Two * DECLARED values may be equal: that sharing is the point. */ From 07127364fd3e380390fdcec19b48599c40f4fe5c Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 16:01:50 -0500 Subject: [PATCH 11/23] no-mistakes(test): Wrap two rustfmt-flagged lines in Rust registry and rules --- server/rust/metaobjects/src/registry.rs | 6 +++++- server/rust/metaobjects/src/validate/rules.rs | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/server/rust/metaobjects/src/registry.rs b/server/rust/metaobjects/src/registry.rs index f90fd1e241..0746c02f6e 100644 --- a/server/rust/metaobjects/src/registry.rs +++ b/server/rust/metaobjects/src/registry.rs @@ -322,7 +322,11 @@ impl TypeRegistry { .map(|b| b.attributes.iter().map(|a| a.name.clone()).collect()) .unwrap_or_default() }; - for attr in def.attributes.iter().filter(|a| !base_names.contains(&a.name)) { + for attr in def + .attributes + .iter() + .filter(|a| !base_names.contains(&a.name)) + { self.check_attr_ownership(&def.type_name, &def.sub_type, &attr.name)?; } let (type_name, sub_type) = (def.type_name.clone(), def.sub_type.clone()); diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index 7a66656fcc..72079bc5d4 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -1161,7 +1161,11 @@ fn check_permission_names(ctx: &Ctx<'_>, top_level: &[NodeId], sink: &mut Sink<' if !is_entity(tree, entity) || tree.node(entity).is_abstract { continue; } - if !tree.children(entity).iter().any(|&c| tree.node(c).type_name == T_SOURCE) { + if !tree + .children(entity) + .iter() + .any(|&c| tree.node(c).type_name == T_SOURCE) + { continue; } let ename = tree.node(entity).name.clone(); From 997e403944fa4022dc40e300b13436d048a503ce Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 16:19:19 -0500 Subject: [PATCH 12/23] no-mistakes(document): sync docs with packs, render errors, P3 --- CHANGELOG.md | 3 +- docs/CONFORMANCE.md | 11 ++++--- docs/features/business-rules.md | 5 ++-- docs/features/libraries.md | 3 +- docs/features/reporting.md | 3 ++ docs/features/requirements.md | 5 +++- docs/features/templates-and-payloads.md | 29 +++++++++++-------- .../ADR-0061-per-port-template-engines.md | 14 +++++++-- .../ADR-0062-provider-attribute-ownership.md | 20 ++++++++++++- 9 files changed, 69 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e59f8614b5..354f5cad06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -163,7 +163,8 @@ here.** the same name and at least one of the two names is derived, the loader reports `ERR_TRANSITION_NAME_COLLISION` on the later one. Two equal declared names stay legal: that is a shared permission. New fixtures `error-rules-permission-name-op-{dotted,declared}` and - `rules-permission-name-package-separator-distinct`. + `rules-permission-name-package-separator-distinct`. Java now accepts dotted operation names + (`Order.open`), as TypeScript, C# and Python already did. - **Python: unions and one-row-per-list-item views are checked at load.** The two must-fail projection fixtures (a `@union` whose branches do not line up, and a `@grain` view that breaks its rules) now fail in Python as they do in the other ports, and leave the Python diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 72a05dd3da..21991dc0eb 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -481,8 +481,11 @@ semantics — dotted-path lookup, parent-context fallthrough, falsy/empty-array inverted sections, nested partials, a comment tag beside a partial, standalone-tag whitespace stripping (including two standalone tags in a row, a standalone tag at the end of the file and an indented standalone tag, which shared docs templates rely on), raw-HTML bypass, trailing-newline preservation, unicode multibyte handling, the derived -`has` accessor, and the `-last` list-separator accessor; 2 refuse a variable missing from the -payload, a plain name and a dotted path (`ERR_VAR_NOT_ON_PAYLOAD`, pinned by `expected-error.txt`). +`has` accessor, and the `-last` list-separator accessor. 2 are error cases: a fixture +that must refuse carries `expected-error.txt` in place of `expected.txt`, holding the error text +the render must raise (`render verify failed: ERR_VAR_NOT_ON_PAYLOAD ()`). Every port that runs +this corpus reads that convention; TypeScript compares the text exactly, and Python, C# and Rust +require it to appear in the raised message. ### `fixtures/jinja-render-conformance/` (16) and `fixtures/jinja-verify-conformance/` (31) @@ -490,8 +493,8 @@ Both → [features/templates-and-payloads.md](features/templates-and-payloads.md templates section, [ADR-0061](../spec/decisions/ADR-0061-per-port-template-engines.md)). Run by Python (jinja2) and TypeScript (nunjucks) only; Java, Kotlin and C# refuse a Jinja body with `ERR_TEMPLATE_ENGINE_UNSUPPORTED` instead. The render corpus holds 13 output cases and 3 error -cases (an include cycle, an unresolved include and a variable missing from the payload), each -with the same Mustache-path message. +cases (an include cycle, an unresolved include and a missing variable), each with the same +Mustache-path message. The verify corpus reuses `verify-conformance/`'s `payload.json` field-tree shape; an `ERR_TEMPLATE_SYNTAX` finding's path is the parser's own message, so runners compare it as empty. diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index cc8dc8bfdd..e5db044802 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -190,8 +190,9 @@ setting `rules.permissions.names` makes `verify` warn about derived names, or fa | 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. +Names are compared without case (L5 and O0, L6, O6) because each one becomes a command, a permission +constant and a file, and those collide on a case-folding target. P3 compares permission names +exactly, as the policy receives them. Some refusals come from the registry: diff --git a/docs/features/libraries.md b/docs/features/libraries.md index a35f53be36..437c05780c 100644 --- a/docs/features/libraries.md +++ b/docs/features/libraries.md @@ -175,7 +175,8 @@ Anything else stays with the adopter (policy, presentation, branding, scheduling separate project. **Worked example, reporting** ([reporting.md](reporting.md)). The vocabulary (dimensions, -measures, segments, `object.report`) is core. The planned `reporting` library holds +measures, segments, `object.report`) is the `metaobjects-reporting` provider pack, in the default +bundle ([extending-with-providers.md](extending-with-providers.md)). The planned `reporting` library holds metadata only, so opting in adds no code. Exporting to another tool and dashboards are catalog generators, one per heavy format, so an adopter never takes a dependency they did not wire: `cube-model` ships today, a dashboard generator does not exist yet. diff --git a/docs/features/reporting.md b/docs/features/reporting.md index 7f56862391..4501205705 100644 --- a/docs/features/reporting.md +++ b/docs/features/reporting.md @@ -48,6 +48,9 @@ mean what they appear to mean: a measure of one table in a report over another, ## What is registered +They are registered by the `metaobjects-reporting` provider pack, which the default bundle +composes; an embedder can leave it out ([extending-with-providers.md](extending-with-providers.md)). + Exactly these names, and nothing else: | Node | Lives on | Attributes | diff --git a/docs/features/requirements.md b/docs/features/requirements.md index 9b04b916fc..646cc09d5b 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -5,7 +5,10 @@ supposed to do, as metadata, checked by `verify` in every port._ **Status:** registered vocabulary in all five ports (TypeScript, Java, C#, Python, Kotlin). The requirement gate runs in every port's `verify`, and every port ships a -`requirement-tests` generator. The authoring lint is TypeScript-only. +`requirement-tests` generator. The authoring lint is TypeScript-only. The vocabulary is the +`metaobjects-requirements` provider pack, in the default bundle. With the pack left out, a +`requirement.*` node is a loader error, and a model with none gets a silent, empty ledger +([extending-with-providers.md](extending-with-providers.md)). **Entirely opt-in.** A model with no `requirement.*` nodes gets no diagnostics, generates nothing, and reads nothing — no codegen, migrate or runtime path touches the type. You opt in diff --git a/docs/features/templates-and-payloads.md b/docs/features/templates-and-payloads.md index ea012f5ae1..3653daa5ce 100644 --- a/docs/features/templates-and-payloads.md +++ b/docs/features/templates-and-payloads.md @@ -228,7 +228,9 @@ Hi {{ displayName | title }}, you have {{ postCount }} posts. ``` Python and TypeScript render the shared Jinja vocabulary identically -(`fixtures/jinja-render-conformance/`). Outside it the two engines differ: an empty list is +(`fixtures/jinja-render-conformance/`), and both raise `ERR_VAR_NOT_ON_PAYLOAD` on a printed name +the payload lacks, while a present null prints empty. Outside it the two engines differ: an empty +list is false in jinja2 and true in nunjucks (write `{% if items | length %}`), a printed list or dict is engine-specific text, and Python-only syntax (`{% with %}`, `name.upper()`, `True`) does not run in nunjucks. Looping over a null value renders nothing in nunjucks and fails the @@ -714,16 +716,17 @@ and checks each one exists on the payload VO. If a template references body (Python and TypeScript) is checked the same way; see [Jinja templates](#jinja-templates-python-and-typescript). -**The same check runs at render time in every generated render helper** (the `template.output` -helper and the `template.prompt` handle, in all five ports). The helper carries its payload's -field tree, so text edited or served after codegen that names a variable the payload lacks -(`{{nmae}}` for `name`) raises `ERR_VAR_NOT_ON_PAYLOAD` instead of rendering as an empty -string. Before this, the TypeScript `promptRender()` handle, the Python helper on a Mustache -body, and the Java and Kotlin helpers rendered it silently. Calling the engine's `render()` -directly with no declared payload keeps the engine's default, since there is nothing to compare -against; ask for the check by passing the field tree (`verify` in TypeScript, Java, Kotlin and -C#; `verify=` in Python). Pinned by -[`fixtures/template-output-render-conformance/runtime-drift/`](../../fixtures/template-output-render-conformance/runtime-drift/). +**A variable the payload lacks fails at render time, on every render path.** Text edited or +served after codegen that names a variable the payload lacks (`{{nmae}}` for `name`) raises +`ERR_VAR_NOT_ON_PAYLOAD` instead of rendering as an empty string. The engine's `render()` raises +it for a Mustache body in TypeScript, C#, Java (and so Kotlin) and Python, and for a Jinja body in +TypeScript and Python. A present `null` still renders empty, and a section over an absent name +still renders nothing. The generated render helpers (the `template.output` helper and the +`template.prompt` handle, in all five ports) carry the payload's field tree, so the same miss is +caught in text served after codegen. Passing the field tree to the engine (`verify` in TypeScript, +Java, Kotlin and C#; `verify=` in Python) also checks names against the declared fields. Pinned by +[`fixtures/template-output-render-conformance/runtime-drift/`](../../fixtures/template-output-render-conformance/runtime-drift/), +and by the `render-error-missing-variable` and `render-error-missing-dotted-path` render fixtures. A bare `verify` also checks generated code and the requirement ledger; name the template check to run it alone. Java and Python skip this check with a note when no template root is @@ -789,6 +792,8 @@ for payload typing per #270) **Render engine semantics** — Mustache-spec behavior pinned cross-port (every port's renderer must emit byte-identical output) - [`fixtures/render-conformance/render-dotted-path-lookup/`](../../fixtures/render-conformance/render-dotted-path-lookup/) — `{{a.b.c}}` traversal across nested objects +- [`fixtures/render-conformance/render-error-missing-variable/`](../../fixtures/render-conformance/render-error-missing-variable/) — a `{{name}}` the payload lacks raises `ERR_VAR_NOT_ON_PAYLOAD` (`expected-error.txt`, in place of `expected.txt`) +- [`fixtures/render-conformance/render-error-missing-dotted-path/`](../../fixtures/render-conformance/render-error-missing-dotted-path/) — a dotted path whose leaf the payload lacks raises the same error - [`fixtures/render-conformance/render-parent-context-fallthrough/`](../../fixtures/render-conformance/render-parent-context-fallthrough/) — a key missing in the current section falls through to the parent context - [`fixtures/render-conformance/render-empty-array-falsiness/`](../../fixtures/render-conformance/render-empty-array-falsiness/) — `{{#xs}}…{{/xs}}` over an empty array renders nothing (vs. iterates) - [`fixtures/render-conformance/render-falsy-values/`](../../fixtures/render-conformance/render-falsy-values/) — `false`, `null`, empty string, `0` — which are truthy for `{{#x}}` sections (per Mustache spec, not JS truthiness) @@ -807,7 +812,7 @@ for the per-port pass/skip ledger. **Jinja bodies (Python and TypeScript, ADR-0061)** -- [`fixtures/jinja-render-conformance/`](../../fixtures/jinja-render-conformance/) — 15 cases: variables, loops, conditionals, `set` and macros, `include` and `import`, filters, html and json escaping (with and without `| escape`), whitespace control, `raw` and comments, plus an include cycle and an unresolved include. Byte-identical output from jinja2 and nunjucks. +- [`fixtures/jinja-render-conformance/`](../../fixtures/jinja-render-conformance/) — 16 cases: variables, loops, conditionals, `set` and macros, `include` and `import`, filters, html and json escaping (with and without `| escape`), whitespace control, `raw` and comments, plus an include cycle, an unresolved include and a missing variable. Byte-identical output from jinja2 and nunjucks. - [`fixtures/jinja-verify-conformance/`](../../fixtures/jinja-verify-conformance/) — 31 cases: the payload check over the parsed template (paths, loop targets, locals, filters, includes, imports, `extends` blocks, `ERR_TEMPLATE_NOT_STATIC`, `ERR_TEMPLATE_SYNTAX`, required slots and tags). ## See also diff --git a/spec/decisions/ADR-0061-per-port-template-engines.md b/spec/decisions/ADR-0061-per-port-template-engines.md index 031bfaf518..6e88cd9e86 100644 --- a/spec/decisions/ADR-0061-per-port-template-engines.md +++ b/spec/decisions/ADR-0061-per-port-template-engines.md @@ -109,8 +109,8 @@ that must render the same in both ports should stay inside the corpus vocabulary `loop.last`). Printed scalars are normalized in both ports to the Mustache renderer's form: `true`/`false`, -a whole float as an integer, and `None`/`undefined` as empty text. A lookup on a missing key -renders empty however deep it chains (`v.x.y`). +a whole float as an integer, and a present `None`/`null` as empty text. A lookup on a missing key +stays missing however deep it chains (`v.x.y`), and printing it raises (Amendment 1). ## Consequences @@ -121,3 +121,13 @@ renders empty however deep it chains (`v.x.y`). - A model whose templates are Jinja renders in Python and TypeScript only. That is by design: the engine is a property of the port, and the refusal in the other three ports says so by code. - The migration analyzer, the other option in #483, is not built. + +## Amendments + +### Amendment 1 (2026-11-21) — a variable the payload lacks raises, in both engines + +Printing a name absent from the payload raises `render verify failed: ERR_VAR_NOT_ON_PAYLOAD` in +the Jinja engines (jinja2 and nunjucks) and in every port's Mustache engine (Rust renders no +template). It is the message the Mustache path raises, and it applies on every render path. A present null still prints empty, and a section over an absent name still +renders nothing. Corpus: `fixtures/jinja-render-conformance/jinja-render-error-missing-variable/` and +`fixtures/render-conformance/render-error-missing-variable/`. diff --git a/spec/decisions/ADR-0062-provider-attribute-ownership.md b/spec/decisions/ADR-0062-provider-attribute-ownership.md index 7df201d68d..991d8ca0e5 100644 --- a/spec/decisions/ADR-0062-provider-attribute-ownership.md +++ b/spec/decisions/ADR-0062-provider-attribute-ownership.md @@ -4,7 +4,9 @@ **Accepted** (2026-11-04). Registers no vocabulary: `metamodelVersion` is unchanged. Adds one error code, `ERR_PROVIDER_ATTR_SHADOW`, and records which provider registered each attribute. -Amends nothing; it states how ADR-0007 and ADR-0018 are meant to scale. Closes #527. +Amends nothing in its decision; it states how ADR-0007 and ADR-0018 are meant to scale. Closes #527. +[Amendment 1](#amendment-1-2026-11-21--an-attribute-folded-from-the-base-is-not-a-new-claim) +records the one exception the rule has since gained. ## Context @@ -95,3 +97,19 @@ a collision. - **Last registration wins** — what happened before; the result depends on provider order. - **One new code for all three cases** — would have changed the established `ERR_PROVIDER_ATTR_CONFLICT` fixture and message for existing consumers. + +## Amendments + +### Amendment 1 (2026-11-21) — an attribute folded from the base is not a new claim + +A subtype declared with `extendsBase: true` folds in the attributes of its registered +`.base`. `object.report`, registered by the reporting pack, is the first. A folded +attribute is the base provider's, not a claim by the provider that registers the subtype. The +registry does not run the rule above on it, and the base provider stays the owner in `meta types` +and in any error message. Nothing else is excepted: a subtype that declares its own attribute, +under a name another provider holds on the base or on a related slot, is still refused. + +Matching is by object identity in TypeScript, C# and Python: the folded definition holds the base's +attribute object. Rust matches by name. The two differ only when a subtype redeclares a base +attribute with the same name; Rust then reads the redeclaration as folded, and the other ports read +it as a new claim. That difference is accepted. From 9f55a8499e79aad6e57aa4ca77625efda200c76e Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 16:21:34 -0500 Subject: [PATCH 13/23] no-mistakes(document): point pack docs at vocabulary owner --- docs/features/business-rules.md | 2 ++ docs/features/extending-with-providers.md | 5 ++--- docs/features/libraries.md | 6 +++--- docs/features/reporting.md | 5 +++-- docs/features/requirements.md | 7 +++---- 5 files changed, 13 insertions(+), 12 deletions(-) diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index e5db044802..0784c1bb05 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -10,6 +10,8 @@ The model never says *how* an operation works. That is code. The model says wher 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. +It is a provider pack, composed by default: see +[Where vocabulary lives](extending-with-providers.md#where-vocabulary-lives). The Rust port loads the vocabulary and runs the same loader rules, and its `verify` runs the same rules gate, held to `fixtures/rules-check-conformance/` ([Rust port](../ports/rust.md)). A requirement can claim an operation or a transition. The flat generators generate nothing from diff --git a/docs/features/extending-with-providers.md b/docs/features/extending-with-providers.md index 880b611234..e951fc77c7 100644 --- a/docs/features/extending-with-providers.md +++ b/docs/features/extending-with-providers.md @@ -127,9 +127,8 @@ vocabulary is [ADR-0037](../../spec/decisions/ADR-0037-metamodel-vocabulary-expa `origin.aggregate` and `origin.first`, provider `metaobjects-reporting`) and requirements (`requirement.*`, provider `metaobjects-requirements`) are packs: each is its own provider, in the default bundle of every port, and an embedder can leave it out. A model that uses a left-out -pack's types gets a loader error naming the unknown type, subtype or attribute. The `verify` -requirements gate reads the requirement nodes the pack registered, so with that pack left out it -has nothing to report. `object.report` shows the one thing a pack subtype may borrow from core: +pack's types gets a loader error naming the unknown type, subtype or attribute. With the +requirements pack left out, a model with no `requirement.*` node gets an empty `verify` ledger. `object.report` shows the one thing a pack subtype may borrow from core: declared with `extendsBase`, it folds in `object.base`, which core registers, and those folded attributes stay owned by core. New vocabulary follows the same path: a gate (`scripts/check-core-vocabulary-pin.ts`) pins the core provider's types and attributes, so adding diff --git a/docs/features/libraries.md b/docs/features/libraries.md index 437c05780c..c8996cb762 100644 --- a/docs/features/libraries.md +++ b/docs/features/libraries.md @@ -157,7 +157,7 @@ MetaObjects ships four kinds of package. They differ in who owns the result: | kind | what it is | ownership | |---|---|---| -| **Vocabulary** | metamodel types and attributes | core, not ejectable: the metadata you write with it is already yours | +| **Vocabulary** | metamodel types and attributes | core or a provider pack, not ejectable: the metadata you write with it is already yours | | **Library** | `library//` with a `library.json`: metadata and requirements (`iam`, `ai`) | `meta eject ` (above) | | **Catalog generator** | a row in `meta gen --list` | import it as shipped, or eject it, except `template` and the package-only rows ([ADR-0034](../../spec/decisions/ADR-0034-codegen-scaffold-and-own.md), Amendment 5). A library may imply one only when it anchors on a library node (above). | | **Runtime helper** | an Apache-2.0 per-port package that generated code imports | copied by the route generator's eject, helper runtime included ([ADR-0034](../../spec/decisions/ADR-0034-codegen-scaffold-and-own.md), Amendment 3) | @@ -175,8 +175,8 @@ Anything else stays with the adopter (policy, presentation, branding, scheduling separate project. **Worked example, reporting** ([reporting.md](reporting.md)). The vocabulary (dimensions, -measures, segments, `object.report`) is the `metaobjects-reporting` provider pack, in the default -bundle ([extending-with-providers.md](extending-with-providers.md)). The planned `reporting` library holds +measures, segments, `object.report`) is a provider pack, composed by default +([Where vocabulary lives](extending-with-providers.md#where-vocabulary-lives)). The planned `reporting` library holds metadata only, so opting in adds no code. Exporting to another tool and dashboards are catalog generators, one per heavy format, so an adopter never takes a dependency they did not wire: `cube-model` ships today, a dashboard generator does not exist yet. diff --git a/docs/features/reporting.md b/docs/features/reporting.md index 4501205705..cb14321e1c 100644 --- a/docs/features/reporting.md +++ b/docs/features/reporting.md @@ -48,8 +48,9 @@ mean what they appear to mean: a measure of one table in a report over another, ## What is registered -They are registered by the `metaobjects-reporting` provider pack, which the default bundle -composes; an embedder can leave it out ([extending-with-providers.md](extending-with-providers.md)). +They are a provider pack, composed by default and removable by an embedder; the pack's +identity and what leaving it out does are in +[Where vocabulary lives](extending-with-providers.md#where-vocabulary-lives). Exactly these names, and nothing else: diff --git a/docs/features/requirements.md b/docs/features/requirements.md index 646cc09d5b..2722832195 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -5,10 +5,9 @@ supposed to do, as metadata, checked by `verify` in every port._ **Status:** registered vocabulary in all five ports (TypeScript, Java, C#, Python, Kotlin). The requirement gate runs in every port's `verify`, and every port ships a -`requirement-tests` generator. The authoring lint is TypeScript-only. The vocabulary is the -`metaobjects-requirements` provider pack, in the default bundle. With the pack left out, a -`requirement.*` node is a loader error, and a model with none gets a silent, empty ledger -([extending-with-providers.md](extending-with-providers.md)). +`requirement-tests` generator. The authoring lint is TypeScript-only. The vocabulary is a +provider pack, composed by default; what leaving it out does is in +[Where vocabulary lives](extending-with-providers.md#where-vocabulary-lives). **Entirely opt-in.** A model with no `requirement.*` nodes gets no diagnostics, generates nothing, and reads nothing — no codegen, migrate or runtime path touches the type. You opt in From 57831cf9c628b75bc90dead01e0d8321ca219201 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 16:32:13 -0500 Subject: [PATCH 14/23] feat(rust): raise ERR_VAR_NOT_ON_PAYLOAD in the Rust renderer The rebase onto main brought in the metaobjects-render crate (#630), whose corpus runner read expected.txt for every render case. This branch adds two render-conformance cases that expect a missing-variable error instead, so the Rust renderer now refuses an interpolated name the payload lacks, with the same message and the same rules as the reference (sections over an absent name stay legal, null is present, only rendered bodies are checked), and the runner learns the expected-error.txt convention. --- CHANGELOG.md | 4 +- docs/features/templates-and-payloads.md | 4 +- server/rust/metaobjects-render/src/lib.rs | 4 +- .../rust/metaobjects-render/src/presence.rs | 180 ++++++++++++++++++ server/rust/metaobjects-render/src/render.rs | 12 +- .../tests/render_conformance.rs | 27 ++- 6 files changed, 219 insertions(+), 12 deletions(-) create mode 100644 server/rust/metaobjects-render/src/presence.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 354f5cad06..aed5925878 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -154,8 +154,8 @@ here.** - **A template that names a variable the payload lacks fails to render, in every render path.** Mustache and Jinja raise `render verify failed: ERR_VAR_NOT_ON_PAYLOAD ()` for a missing variable or dotted path, where they used to render it empty. A variable that is present and null - still renders empty. Render fixtures may now carry `expected-error.txt` in place of - `expected.txt`. + still renders empty. The Rust `metaobjects-render` crate raises it too, so all six renderers + agree. Render fixtures may now carry `expected-error.txt` in place of `expected.txt`. - **Business rules: two operations or transitions whose permission names come out equal are refused (rule P3).** A permission name is the declared `@permission`, or else the derived `.`, compared exactly as the policy receives it, so `p::Order.open` and diff --git a/docs/features/templates-and-payloads.md b/docs/features/templates-and-payloads.md index 3653daa5ce..3b57158f33 100644 --- a/docs/features/templates-and-payloads.md +++ b/docs/features/templates-and-payloads.md @@ -719,8 +719,8 @@ body (Python and TypeScript) is checked the same way; see **A variable the payload lacks fails at render time, on every render path.** Text edited or served after codegen that names a variable the payload lacks (`{{nmae}}` for `name`) raises `ERR_VAR_NOT_ON_PAYLOAD` instead of rendering as an empty string. The engine's `render()` raises -it for a Mustache body in TypeScript, C#, Java (and so Kotlin) and Python, and for a Jinja body in -TypeScript and Python. A present `null` still renders empty, and a section over an absent name +it for a Mustache body in TypeScript, C#, Java (and so Kotlin), Python and Rust (the +`metaobjects-render` crate), and for a Jinja body in TypeScript and Python. A present `null` still renders empty, and a section over an absent name still renders nothing. The generated render helpers (the `template.output` helper and the `template.prompt` handle, in all five ports) carry the payload's field tree, so the same miss is caught in text served after codegen. Passing the field tree to the engine (`verify` in TypeScript, diff --git a/server/rust/metaobjects-render/src/lib.rs b/server/rust/metaobjects-render/src/lib.rs index 80d4615020..cdb9328952 100644 --- a/server/rust/metaobjects-render/src/lib.rs +++ b/server/rust/metaobjects-render/src/lib.rs @@ -3,7 +3,8 @@ //! A `template.*` body is plain Mustache. [`render`] renders it over a JSON payload the //! same way every MetaObjects port does: partials expanded ahead of time, every //! `{{value}}` escaped for the template's format, derived `has` and `-last` -//! accessors on the payload, and a fail-closed `maxChars` budget. The engine underneath is +//! accessors on the payload, a fail-closed `maxChars` budget, and a variable missing from +//! the payload refused rather than rendered empty (`ERR_VAR_NOT_ON_PAYLOAD`). The engine underneath is //! the `mustache-ng` crate; what is specific to MetaObjects sits here, on top of it. The //! shared `fixtures/render-conformance/` corpus holds this crate to the other ports. //! @@ -14,6 +15,7 @@ pub mod accessors; pub mod escapers; pub mod extract; +pub mod presence; pub mod prompt; pub mod render; pub mod tags; diff --git a/server/rust/metaobjects-render/src/presence.rs b/server/rust/metaobjects-render/src/presence.rs new file mode 100644 index 0000000000..1635b919cd --- /dev/null +++ b/server/rust/metaobjects-render/src/presence.rs @@ -0,0 +1,180 @@ +//! A template variable missing from the payload fails the render (`ERR_VAR_NOT_ON_PAYLOAD`). +//! +//! The engine renders an absent name as empty text, so a typo (`{{nmae}}`) or a payload +//! field that was renamed would ship a prompt with a silent hole in it. Every port refuses +//! that instead, with one message. This walk runs ahead of the engine, over the template +//! with its partials already expanded, and follows the same rules as the reference (the +//! TypeScript renderer's check on mustache.js's context lookup): +//! +//! - Only interpolations are checked (`{{x}}`, `{{{x}}}`, `{{&x}}`). A section or inverted +//! section over an absent name is legal and is simply falsy. +//! - A name resolves against the context stack from the innermost context outwards. A +//! dotted name is tried whole against each context in turn, and is present when its last +//! segment exists on the value its leading segments reach. +//! - A `null` value is present (it renders empty). `.` is always present. +//! - Only what would render is checked: the body of a falsy section and of a truthy +//! inverted section is skipped, and a list section checks its body once per element. + +use serde_json::Value; + +use crate::tags::{Tag, TagKind}; + +/// The error code every port raises for a variable that is not on the payload. +pub const ERR_VAR_NOT_ON_PAYLOAD: &str = "ERR_VAR_NOT_ON_PAYLOAD"; + +/// The current-context name. +const IMPLICIT_ITERATOR: &str = "."; + +/// The first interpolated name in `tags` that the payload does not carry, if any. +#[must_use] +pub fn first_missing(tags: &[Tag], payload: &Value) -> Option { + let mut stack = vec![payload]; + walk(tags, &mut stack) +} + +fn walk<'a>(tags: &[Tag], stack: &mut Vec<&'a Value>) -> Option { + let mut i = 0; + while i < tags.len() { + let tag = &tags[i]; + match tag.kind { + TagKind::Name | TagKind::Triple | TagKind::Amp => { + if lookup(&tag.value, stack).is_none() { + return Some(tag.value.clone()); + } + } + TagKind::Section | TagKind::Inverted => { + let close = matching_close(tags, i); + let body = &tags[i + 1..close]; + let value = lookup(&tag.value, stack); + let truthy = value.is_some_and(is_truthy); + if tag.kind == TagKind::Inverted { + let missing = if truthy { None } else { walk(body, stack) }; + if missing.is_some() { + return missing; + } + } else if let Some(value) = value.filter(|v| is_truthy(v)) { + let contexts: Vec<&'a Value> = match value { + Value::Array(items) => items.iter().collect(), + other => vec![other], + }; + for context in contexts { + stack.push(context); + let missing = walk(body, stack); + stack.pop(); + if missing.is_some() { + return missing; + } + } + } + i = close; + } + TagKind::Close | TagKind::Partial | TagKind::Comment | TagKind::Delimiters => {} + } + i += 1; + } + None +} + +/// The index of the close tag that ends the section opened at `open`. The scanner has +/// already refused unbalanced sections, so a close always exists; the end of the list is +/// the fallback. +fn matching_close(tags: &[Tag], open: usize) -> usize { + let mut depth = 0usize; + for (offset, tag) in tags[open + 1..].iter().enumerate() { + match tag.kind { + TagKind::Section | TagKind::Inverted => depth += 1, + TagKind::Close if depth == 0 => return open + 1 + offset, + TagKind::Close => depth -= 1, + _ => {} + } + } + tags.len() +} + +/// `name` resolved against the context stack, innermost first. `None` means absent. +fn lookup<'a>(name: &str, stack: &[&'a Value]) -> Option<&'a Value> { + if name == IMPLICIT_ITERATOR { + return stack.last().copied(); + } + let segments: Vec<&str> = name.split('.').collect(); + stack + .iter() + .rev() + .find_map(|context| resolve(context, &segments)) +} + +fn resolve<'a>(context: &'a Value, segments: &[&str]) -> Option<&'a Value> { + segments + .iter() + .try_fold(context, |value, segment| property(value, segment)) +} + +/// One property of a JSON value, as a JavaScript property read would find it: an object's +/// key, or a list's index. +fn property<'a>(value: &'a Value, key: &str) -> Option<&'a Value> { + match value { + Value::Object(map) => map.get(key), + Value::Array(items) => key.parse::().ok().and_then(|i| items.get(i)), + _ => None, + } +} + +/// Mustache truthiness as the reference engine reads it: `false`, `null`, `0`, `""` and an +/// empty list are falsy. +fn is_truthy(value: &Value) -> bool { + match value { + Value::Null => false, + Value::Bool(b) => *b, + Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0), + Value::String(s) => !s.is_empty(), + Value::Array(items) => !items.is_empty(), + Value::Object(_) => true, + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::first_missing; + use crate::tags::scan; + + fn missing(template: &str, payload: &serde_json::Value) -> Option { + first_missing(&scan(template).expect("scan"), payload) + } + + #[test] + fn absent_names_are_reported_and_present_ones_are_not() { + let payload = + json!({ "name": "Ada", "note": null, "user": { "profile": { "name": "Ada" } } }); + assert_eq!(missing("Hi {{nmae}}", &payload), Some("nmae".to_string())); + assert_eq!(missing("{{{name}}} {{¬e}} {{.}}", &payload), None); + assert_eq!(missing("{{user.profile.name}}", &payload), None); + assert_eq!( + missing("{{user.profile.email}}", &payload), + Some("user.profile.email".to_string()) + ); + } + + #[test] + fn sections_over_absent_names_are_legal_and_skip_their_body() { + let payload = json!({ "flag": false, "items": [] }); + assert_eq!(missing("{{#nope}}{{gone}}{{/nope}}", &payload), None); + assert_eq!(missing("{{#flag}}{{gone}}{{/flag}}", &payload), None); + assert_eq!(missing("{{#items}}{{gone}}{{/items}}", &payload), None); + assert_eq!( + missing("{{^nope}}{{gone}}{{/nope}}", &payload), + Some("gone".to_string()) + ); + } + + #[test] + fn list_elements_and_outer_contexts_both_resolve() { + let payload = json!({ "title": "T", "items": [{ "name": "a" }, { "other": 1 }] }); + assert_eq!(missing("{{#items}}{{title}}{{/items}}", &payload), None); + assert_eq!( + missing("{{#items}}{{name}}{{/items}}", &payload), + Some("name".to_string()) + ); + } +} diff --git a/server/rust/metaobjects-render/src/render.rs b/server/rust/metaobjects-render/src/render.rs index aedb0fdcea..f6569a3430 100644 --- a/server/rust/metaobjects-render/src/render.rs +++ b/server/rust/metaobjects-render/src/render.rs @@ -21,6 +21,7 @@ use serde_json::Value; use crate::accessors::with_derived_accessors; use crate::escapers::{self, FORMAT_TEXT}; +use crate::presence::{ERR_VAR_NOT_ON_PAYLOAD, first_missing}; use crate::tags::{self, TagKind}; /// How deep partials may nest before the render fails. @@ -133,7 +134,8 @@ impl<'a> RenderRequest<'a> { /// # Errors /// An unknown format, an unresolved body or partial, a partial cycle or one nested deeper /// than [`MAX_DEPTH`], a Jinja partial, a template syntax error, a set-delimiter tag, a -/// marker character in the template or payload, or output over the `maxChars` budget. +/// marker character in the template or payload, an interpolated name the payload does +/// not carry (`ERR_VAR_NOT_ON_PAYLOAD`), or output over the `maxChars` budget. pub fn render(request: &RenderRequest<'_>) -> Result { if !escapers::is_format(request.format) { return err(format!("unknown render format \"{}\"", request.format)); @@ -149,8 +151,14 @@ pub fn render(request: &RenderRequest<'_>) -> Result { } }; let expanded = pre_expand_partials(&body, request.provider, &mut Vec::new())?; - let source = mark_escaped_tags(&expanded, request.format)?; let payload = with_derived_accessors(request.payload); + let found = tags::scan(&expanded).map_err(|e| syntax(&e))?; + if let Some(name) = first_missing(&found, &payload) { + return err(format!( + "render verify failed: {ERR_VAR_NOT_ON_PAYLOAD} ({name})" + )); + } + let source = mark_escaped_tags(&expanded, request.format)?; let data = to_data(&payload)?; let template = mustache::compile_str(&source) .map_err(|e| RenderError(format!("template syntax error: {e}")))?; diff --git a/server/rust/metaobjects-render/tests/render_conformance.rs b/server/rust/metaobjects-render/tests/render_conformance.rs index 2b19db4852..dfc52664a2 100644 --- a/server/rust/metaobjects-render/tests/render_conformance.rs +++ b/server/rust/metaobjects-render/tests/render_conformance.rs @@ -1,7 +1,9 @@ //! The shared render corpus (`fixtures/render-conformance/`): the same template, payload, //! partials and format give the same bytes in every port. //! -//! Each case directory holds `template.mustache`, `payload.json`, `expected.txt`, an +//! Each case directory holds `template.mustache`, `payload.json`, either `expected.txt` +//! (byte-identical output) or `expected-error.txt` (the render must fail, with a message +//! containing the file's trimmed text), an //! optional `meta.json` (`format`, `maxChars`) and optional `partials/.mustache`, //! referenced as `{{> partials/}}`. A sub-corpus with no `template.mustache` of its //! own (`template-generator/`, which drives the codegen `template` generator) has its own @@ -26,7 +28,10 @@ fn run_case(dir: &Path) -> Result<(), String> { let template = read(&dir.join("template.mustache")); let payload: Value = serde_json::from_str(&read(&dir.join("payload.json"))) .map_err(|e| format!("payload.json: {e}"))?; - let expected = read(&dir.join("expected.txt")); + let error_path = dir.join("expected-error.txt"); + let expected_error = error_path + .is_file() + .then(|| read(&error_path).trim().to_string()); let meta: Value = if dir.join("meta.json").is_file() { serde_json::from_str(&read(&dir.join("meta.json"))).map_err(|e| e.to_string())? } else { @@ -49,12 +54,24 @@ fn run_case(dir: &Path) -> Result<(), String> { } } let provider = InMemoryProvider::new(partials); - let actual = render( + let result = render( &RenderRequest::new(Body::Inline(&template), &payload, &provider) .format(format) .max_chars(max_chars), - ) - .map_err(|e| e.to_string())?; + ); + if let Some(wanted) = expected_error { + return match result { + Err(e) if e.to_string().contains(&wanted) => Ok(()), + Err(e) => Err(format!( + "expected an error containing {wanted:?}\n actual {e}" + )), + Ok(out) => Err(format!( + "expected an error containing {wanted:?}\n rendered {out:?}" + )), + }; + } + let expected = read(&dir.join("expected.txt")); + let actual = result.map_err(|e| e.to_string())?; if actual == expected { Ok(()) } else { From 1af8904763a63ddffc11ee0483773a7dbea23b9c Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 18:46:14 -0500 Subject: [PATCH 15/23] docs(conformance): recount render and Jinja cases after rebasing onto #634 Main's #634 added render-conformance cases and two corpora while this branch added two render error cases and a Jinja error case; the counts and the showcase payload are recomputed from the fixtures on disk. --- docs/CONFORMANCE.md | 2 +- examples/showcase/site-payload.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 21991dc0eb..6d92d55198 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -484,7 +484,7 @@ indented standalone tag, which shared docs templates rely on), raw-HTML bypass, `has` accessor, and the `-last` list-separator accessor. 2 are error cases: a fixture that must refuse carries `expected-error.txt` in place of `expected.txt`, holding the error text the render must raise (`render verify failed: ERR_VAR_NOT_ON_PAYLOAD ()`). Every port that runs -this corpus reads that convention; TypeScript compares the text exactly, and Python, C# and Rust +this corpus reads that convention; TypeScript compares the text exactly, and Java, Python, C# and Rust require it to appear in the raised message. ### `fixtures/jinja-render-conformance/` (16) and `fixtures/jinja-verify-conformance/` (31) diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 94f9d8136f..2854e92c2c 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -8,7 +8,7 @@ }, "counts": { "fixtures": 584, - "corpora": 43, + "corpora": 45, "baseTypes": 21 }, "snippets": { From 19dc25d14cb8215159da63474b2391aac8d5cf3f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 07:06:06 -0500 Subject: [PATCH 16/23] fix(render): check missing variables with the reference's whole-path lookup in every port The B4 missing-variable check follows TypeScript on mustache.js: a dotted name is tried whole against each context from the innermost outward, and a list's length is a property. Python and C# now resolve that way; the Java check pass falls back to a whole-path lookup before raising; the Rust check pass counts a list's length as present. So no port raises ERR_VAR_NOT_ON_PAYLOAD on a name TypeScript renders. What the C#, Java and Rust engines then print for those names is a separate parity question. --- server/csharp/MetaObjects.Render/Renderer.cs | 43 ++++++++++++++----- .../java/com/metaobjects/render/Renderer.java | 27 +++++++++++- .../com/metaobjects/render/RendererTest.java | 18 ++++++++ .../python/src/metaobjects/render/renderer.py | 35 +++++++++------ .../rust/metaobjects-render/src/presence.rs | 25 ++++++++--- 5 files changed, 119 insertions(+), 29 deletions(-) diff --git a/server/csharp/MetaObjects.Render/Renderer.cs b/server/csharp/MetaObjects.Render/Renderer.cs index 6ac8621f6f..edc6796709 100644 --- a/server/csharp/MetaObjects.Render/Renderer.cs +++ b/server/csharp/MetaObjects.Render/Renderer.cs @@ -186,24 +186,45 @@ private static void CheckTags(List tags, int from, int to, List false, }; - /// Mustache's name lookup: the first segment is searched from the innermost context outward, - /// the rest walk down from it. Absent at any step is a miss; a null part-way is a present null. + /// Mustache's name lookup, as mustache.js does it: the WHOLE (possibly dotted) name is + /// tried against each context from the innermost outward, and the first context on which the full + /// path resolves wins. A context that has the first segment but not the rest is skipped, not a + /// stop; a path that descends through a null does not resolve there. private static bool TryResolve(List stack, string name, out object? value) { value = null; if (name == ".") { value = stack[^1]; return true; } string[] segs = name.Split('.'); - bool hit = false; - object? current = null; - for (int i = stack.Count - 1; i >= 0 && !hit; i--) - hit = PayloadAccessors.TryLookup(stack[i], segs[0], out current); - if (!hit) return false; - for (int s = 1; s < segs.Length; s++) + for (int i = stack.Count - 1; i >= 0; i--) { - if (current is null) { value = null; return true; } - if (!PayloadAccessors.TryLookup(current, segs[s], out current)) return false; + if (TryWalk(stack[i], segs, out value)) return true; + } + value = null; + return false; + } + + private static bool TryWalk(object? ctx, string[] segs, out object? value) + { + value = ctx; + foreach (string seg in segs) + { + if (!TryProperty(value, seg, out value)) return false; } - value = current; return true; } + + // One property read, as JavaScript finds it: a payload member, or a list's `length`. + private static bool TryProperty(object? ctx, string key, out object? value) + { + if (PayloadAccessors.TryLookup(ctx, key, out value)) return true; + if (key == LengthProperty && ctx is System.Collections.ICollection list + and not System.Collections.IDictionary) + { + value = list.Count; + return true; + } + return false; + } + + private const string LengthProperty = "length"; } diff --git a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java index 6bbde3ff4d..bdffad7244 100644 --- a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java +++ b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java @@ -232,11 +232,36 @@ private static final class CheckedValueCode extends ValueCode { @Override public Writer execute(Writer writer, List scopes) { - if (!returnThis && oh.find(name, scopes) instanceof AbsentWrapper) { + if (!returnThis && oh.find(name, scopes) instanceof AbsentWrapper && !presentWholePath(scopes)) { throw new RenderException( "render verify failed: " + Verify.ERR_VAR_NOT_ON_PAYLOAD + " (" + name + ")"); } return super.execute(writer, scopes); } + + /** + * The reference check (TypeScript on mustache.js) tries the WHOLE dotted name against each + * context from the innermost outward, and reads a list's {@code length} as a property. The + * engine's own lookup stops at the first context holding the first segment, so without this + * a name TypeScript renders (a shadowed prefix, {@code items.length}) would raise here. + */ + private boolean presentWholePath(List scopes) { + int dot = name.lastIndexOf('.'); + for (int i = scopes.size() - 1; i >= 0; i--) { + List one = java.util.Collections.singletonList(scopes.get(i)); + if (!(oh.find(name, one) instanceof AbsentWrapper)) return true; + if (dot > 0 && "length".equals(name.substring(dot + 1))) { + com.github.mustachejava.util.Wrapper w = oh.find(name.substring(0, dot), one); + if (w instanceof AbsentWrapper) continue; + try { + Object v = w.call(one); + if (v instanceof java.util.Collection || (v != null && v.getClass().isArray())) return true; + } catch (com.github.mustachejava.util.GuardException e) { + // not resolvable on this context; try the next one out + } + } + } + return false; + } } } diff --git a/server/java/render/src/test/java/com/metaobjects/render/RendererTest.java b/server/java/render/src/test/java/com/metaobjects/render/RendererTest.java index d4e5aea534..072562b992 100644 --- a/server/java/render/src/test/java/com/metaobjects/render/RendererTest.java +++ b/server/java/render/src/test/java/com/metaobjects/render/RendererTest.java @@ -27,6 +27,24 @@ public void sectionIteration() { assertEquals("- a\n- b\n- c\n", new Renderer().render(req)); } + @Test + public void namesTheReferenceResolvesDoNotRaiseAsMissing() { + // The missing-variable check follows the reference (TypeScript on mustache.js): a dotted + // name is tried whole against each context, and a list's length is a property. What the + // engine then prints for these is a separate, open parity question, so only the absence of + // ERR_VAR_NOT_ON_PAYLOAD is pinned here. + var shadowed = new RenderRequest( + "{{#items}}[{{a.b}}]{{/items}}", null, + Map.of("a", Map.of("b", 1), "items", List.of(Map.of("a", Map.of("c", 2)))), + new InMemoryProvider(Map.of()), "text", null, null); + new Renderer().render(shadowed); + + var length = new RenderRequest( + "count: {{items.length}}", null, Map.of("items", List.of(1, 2, 3)), + new InMemoryProvider(Map.of()), "text", null, null); + new Renderer().render(length); + } + /** A value object's generated record, as a template's payload (ADR-0056). */ public record Tag(String label) {} public record Profile(String bio, Integer count, List tags, Tag sponsor) {} diff --git a/server/python/src/metaobjects/render/renderer.py b/server/python/src/metaobjects/render/renderer.py index c8f79b9410..3b4f2970d5 100644 --- a/server/python/src/metaobjects/render/renderer.py +++ b/server/python/src/metaobjects/render/renderer.py @@ -372,9 +372,10 @@ def _emit( def _resolve(path: str, stack: list[Any]) -> Any: - """Mustache lookup: first segment walks the context stack innermost→outermost; - remaining segments descend into the resolved value. Implicit iterator - ``{{.}}`` returns the top of the stack.""" + """Mustache lookup, as mustache.js does it: the WHOLE (possibly dotted) name is tried + against each context from the innermost outward, and the first context on which the full + path resolves wins. A context that has the first segment but not the rest is skipped, not + a stop. Implicit iterator ``{{.}}`` returns the top of the stack.""" return _resolve_found(path, stack)[1] @@ -385,18 +386,28 @@ def _resolve_found(path: str, stack: list[Any]) -> tuple[bool, Any]: if path == ".": return True, (stack[-1] if stack else None) segs = path.split(".") - found, current = _lookup(stack, segs[0]) - for seg in segs[1:]: - if not found or current is None: + for ctx in reversed(stack): + found, value = _walk(ctx, segs) + if found: + return True, value + return False, None + + +def _walk(ctx: Any, segs: list[str]) -> tuple[bool, Any]: + current = ctx + for seg in segs: + found, current = _property(current, seg) + if not found: return False, None - found, current = _lookup([current], seg) - return found, current + return True, current -def _lookup(stack: list[Any], name: str) -> tuple[bool, Any]: - for ctx in reversed(stack): - if isinstance(ctx, dict) and name in ctx: - return True, ctx[name] +def _property(value: Any, name: str) -> tuple[bool, Any]: + """One property read, as JavaScript finds it: a mapping's key, or a list's ``length``.""" + if isinstance(value, dict): + return (True, value[name]) if name in value else (False, None) + if isinstance(value, list) and name == "length": + return True, len(value) return False, None diff --git a/server/rust/metaobjects-render/src/presence.rs b/server/rust/metaobjects-render/src/presence.rs index 1635b919cd..6d293e3dac 100644 --- a/server/rust/metaobjects-render/src/presence.rs +++ b/server/rust/metaobjects-render/src/presence.rs @@ -10,7 +10,8 @@ //! section over an absent name is legal and is simply falsy. //! - A name resolves against the context stack from the innermost context outwards. A //! dotted name is tried whole against each context in turn, and is present when its last -//! segment exists on the value its leading segments reach. +//! segment exists on the value its leading segments reach. A list's `length` is present, +//! as it is to a JavaScript property read. //! - A `null` value is present (it renders empty). `.` is always present. //! - Only what would render is checked: the body of a falsy section and of a truthy //! inverted section is skipped, and a list section checks its body once per element. @@ -104,13 +105,19 @@ fn lookup<'a>(name: &str, stack: &[&'a Value]) -> Option<&'a Value> { } fn resolve<'a>(context: &'a Value, segments: &[&str]) -> Option<&'a Value> { - segments - .iter() - .try_fold(context, |value, segment| property(value, segment)) + segments.iter().try_fold(context, |value, segment| { + property(value, segment).or_else(|| { + let items = value.as_array().filter(|_| *segment == LENGTH)?; + Some(if items.is_empty() { &LENGTH_ZERO } else { &LENGTH_NONZERO }) + }) + }) } +/// The list property JavaScript exposes and the reference check therefore treats as present. +const LENGTH: &str = "length"; + /// One property of a JSON value, as a JavaScript property read would find it: an object's -/// key, or a list's index. +/// key, or a list's index. (A list's `length` is handled by `resolve`.) fn property<'a>(value: &'a Value, key: &str) -> Option<&'a Value> { match value { Value::Object(map) => map.get(key), @@ -119,6 +126,12 @@ fn property<'a>(value: &'a Value, key: &str) -> Option<&'a Value> { } } +/// Placeholders for a list's `length`, which is a property in JavaScript and so is present to the +/// reference check. The value is never rendered; only presence and truthiness matter, so an empty +/// list's length stands as falsy and any other as a truthy `true`. +static LENGTH_ZERO: Value = Value::Bool(false); +static LENGTH_NONZERO: Value = Value::Bool(true); + /// Mustache truthiness as the reference engine reads it: `false`, `null`, `0`, `""` and an /// empty list are falsy. fn is_truthy(value: &Value) -> bool { @@ -162,6 +175,8 @@ mod tests { assert_eq!(missing("{{#nope}}{{gone}}{{/nope}}", &payload), None); assert_eq!(missing("{{#flag}}{{gone}}{{/flag}}", &payload), None); assert_eq!(missing("{{#items}}{{gone}}{{/items}}", &payload), None); + assert_eq!(missing("{{items.length}}", &payload), None); + assert_eq!(missing("{{#items.length}}{{gone}}{{/items.length}}", &payload), None); assert_eq!( missing("{{^nope}}{{gone}}{{/nope}}", &payload), Some("gone".to_string()) From 4ca898b1618ed35dedad080e058e267e40920b01 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Tue, 24 Nov 2026 15:04:49 -0500 Subject: [PATCH 17/23] fix(render): treat 0 as falsy in Python sections and the C# check pass, as mustache.js does An empty list's length now resolves, so {{#items.length}} on an empty list rendered its body in Python. mustache.js tests sections with JavaScript falsiness, where 0 and NaN are falsy; Python's section test and the C# check pass now do the same. Adds a Python test pinning the shadowed-prefix, length, zero and null-mid-path cases against the TypeScript output. Also tidies the Java whole-path fallback (imports, a named length constant, loop-invariant work hoisted) and the C# lookup (using, a redundant assignment). --- server/csharp/MetaObjects.Render/Renderer.cs | 10 ++++--- .../java/com/metaobjects/render/Renderer.java | 27 ++++++++++++------- .../python/src/metaobjects/render/renderer.py | 4 +++ .../tests/render/test_render_conformance.py | 17 ++++++++++++ 4 files changed, 45 insertions(+), 13 deletions(-) diff --git a/server/csharp/MetaObjects.Render/Renderer.cs b/server/csharp/MetaObjects.Render/Renderer.cs index edc6796709..05679032bb 100644 --- a/server/csharp/MetaObjects.Render/Renderer.cs +++ b/server/csharp/MetaObjects.Render/Renderer.cs @@ -9,6 +9,7 @@ // The render-time `verify` guard (FR-004 Plan #3) is wired: a request carrying the payload field // tree verifies the resolved body before it renders, and a mismatch throws RenderException. +using System.Collections; using Stubble.Core.Builders; using Stubble.Core.Settings; @@ -181,6 +182,11 @@ private static void CheckTags(List tags, int from, int to, List true, bool b => !b, string s => s.Length == 0, + // JavaScript falsiness, as mustache.js reads it: 0 and NaN are falsy. + int or long or short or sbyte or byte or uint or ulong or ushort => Convert.ToDecimal(v) == 0m, + double d => d == 0 || double.IsNaN(d), + float f => f == 0 || float.IsNaN(f), + decimal m => m == 0m, System.Collections.IDictionary => false, System.Collections.IEnumerable seq => !seq.GetEnumerator().MoveNext(), _ => false, @@ -199,7 +205,6 @@ private static bool TryResolve(List stack, string name, out object? val { if (TryWalk(stack[i], segs, out value)) return true; } - value = null; return false; } @@ -217,8 +222,7 @@ private static bool TryWalk(object? ctx, string[] segs, out object? value) private static bool TryProperty(object? ctx, string key, out object? value) { if (PayloadAccessors.TryLookup(ctx, key, out value)) return true; - if (key == LengthProperty && ctx is System.Collections.ICollection list - and not System.Collections.IDictionary) + if (key == LengthProperty && ctx is ICollection list and not IDictionary) { value = list.Count; return true; diff --git a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java index bdffad7244..6a5e67735f 100644 --- a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java +++ b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java @@ -10,12 +10,16 @@ import com.github.mustachejava.reflect.Guard; import com.github.mustachejava.reflect.MissingWrapper; import com.github.mustachejava.reflect.ReflectionObjectHandler; +import com.github.mustachejava.util.GuardException; +import com.github.mustachejava.util.Wrapper; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayDeque; +import java.util.Collection; +import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.function.Function; @@ -245,20 +249,23 @@ public Writer execute(Writer writer, List scopes) { * engine's own lookup stops at the first context holding the first segment, so without this * a name TypeScript renders (a shadowed prefix, {@code items.length}) would raise here. */ + /** The list property JavaScript exposes, and the reference check therefore treats as present. */ + private static final String LENGTH_PROPERTY = "length"; + private boolean presentWholePath(List scopes) { int dot = name.lastIndexOf('.'); + String listName = dot > 0 && LENGTH_PROPERTY.equals(name.substring(dot + 1)) ? name.substring(0, dot) : null; for (int i = scopes.size() - 1; i >= 0; i--) { - List one = java.util.Collections.singletonList(scopes.get(i)); + List one = Collections.singletonList(scopes.get(i)); if (!(oh.find(name, one) instanceof AbsentWrapper)) return true; - if (dot > 0 && "length".equals(name.substring(dot + 1))) { - com.github.mustachejava.util.Wrapper w = oh.find(name.substring(0, dot), one); - if (w instanceof AbsentWrapper) continue; - try { - Object v = w.call(one); - if (v instanceof java.util.Collection || (v != null && v.getClass().isArray())) return true; - } catch (com.github.mustachejava.util.GuardException e) { - // not resolvable on this context; try the next one out - } + if (listName == null) continue; + Wrapper w = oh.find(listName, one); + if (w instanceof AbsentWrapper) continue; + try { + Object v = w.call(one); + if (v instanceof Collection || (v != null && v.getClass().isArray())) return true; + } catch (GuardException e) { + // not resolvable on this context; try the next one out } } return false; diff --git a/server/python/src/metaobjects/render/renderer.py b/server/python/src/metaobjects/render/renderer.py index 3b4f2970d5..4d9e73d916 100644 --- a/server/python/src/metaobjects/render/renderer.py +++ b/server/python/src/metaobjects/render/renderer.py @@ -418,6 +418,10 @@ def _truthy(value: Any) -> bool: return False if isinstance(value, str) and not value: return False + # JavaScript falsiness, as mustache.js reads it: 0 and NaN are falsy (so is an empty + # list's ``length``). ``bool`` is an ``int`` subclass and was handled above. + if isinstance(value, (int, float)) and (value == 0 or value != value): + return False return True diff --git a/server/python/tests/render/test_render_conformance.py b/server/python/tests/render/test_render_conformance.py index 26cb30c9e9..170dd9d9c6 100644 --- a/server/python/tests/render/test_render_conformance.py +++ b/server/python/tests/render/test_render_conformance.py @@ -114,3 +114,20 @@ def test_a_missing_variable_raises_and_a_null_renders_empty() -> None: with pytest.raises(RenderError, match=r"ERR_VAR_NOT_ON_PAYLOAD \(nmae\)"): render(RenderRequest(payload={}, provider=provider, template="Hi {{{nmae}}}!")) assert render(RenderRequest(payload={"n": None}, provider=provider, template="Hi {{n}}!{{#x}}y{{/x}}")) == "Hi !" + + +def test_names_resolve_and_sections_test_as_mustache_js_does() -> None: + # The reference (TypeScript on mustache.js) tries a dotted name whole against each + # context, reads a list's length as a property, and treats 0 as falsy. + provider = InMemoryProvider({}) + + def run(template: str, payload: dict) -> str: + return render(RenderRequest(payload=payload, provider=provider, template=template)) + + shadowed = {"a": {"b": 1}, "items": [{"a": {"c": 2}}]} + assert run("{{#items}}[{{a.b}}]{{/items}}", shadowed) == "[1]" + assert run("count: {{items.length}}", {"items": [1, 2, 3]}) == "count: 3" + assert run("{{#items.length}}has{{/items.length}}{{^items.length}}none{{/items.length}}", {"items": []}) == "none" + assert run("{{#n}}yes{{/n}}{{^n}}zero{{/n}}", {"n": 0}) == "zero" + with pytest.raises(RenderError, match=r"ERR_VAR_NOT_ON_PAYLOAD \(address.street\)"): + run("{{address.street}}", {"address": None}) From 05a1eda33c716ed436c769062b4aa6cdf6fff63d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Tue, 24 Nov 2026 16:17:20 -0500 Subject: [PATCH 18/23] no-mistakes(review): Pin render parity with shared fixtures --- docs/CONFORMANCE.md | 21 ++- docs/features/templates-and-payloads.md | 15 ++- .../render-list-length/expected.txt | 4 + .../render-list-length/meta.json | 1 + .../render-list-length/payload.json | 4 + .../render-list-length/template.mustache | 4 + .../expected.txt | 2 + .../render-shadowed-dotted-prefix/meta.json | 1 + .../payload.json | 8 ++ .../template.mustache | 2 + .../render-zero-falsiness/expected.txt | 2 + .../render-zero-falsiness/meta.json | 1 + .../render-zero-falsiness/payload.json | 4 + .../render-zero-falsiness/template.mustache | 2 + .../RenderConformanceTests.cs | 16 +++ server/csharp/MetaObjects.Render/Renderer.cs | 7 +- .../java/com/metaobjects/render/Renderer.java | 123 ++++++++++++------ .../com/metaobjects/render/RendererTest.java | 26 +++- .../snapshots/render-list-length.txt | 4 + .../render-shadowed-dotted-prefix.txt | 2 + .../snapshots/render-zero-falsiness.txt | 2 + .../tests/render_conformance.rs | 30 +++++ 22 files changed, 228 insertions(+), 53 deletions(-) create mode 100644 fixtures/render-conformance/render-list-length/expected.txt create mode 100644 fixtures/render-conformance/render-list-length/meta.json create mode 100644 fixtures/render-conformance/render-list-length/payload.json create mode 100644 fixtures/render-conformance/render-list-length/template.mustache create mode 100644 fixtures/render-conformance/render-shadowed-dotted-prefix/expected.txt create mode 100644 fixtures/render-conformance/render-shadowed-dotted-prefix/meta.json create mode 100644 fixtures/render-conformance/render-shadowed-dotted-prefix/payload.json create mode 100644 fixtures/render-conformance/render-shadowed-dotted-prefix/template.mustache create mode 100644 fixtures/render-conformance/render-zero-falsiness/expected.txt create mode 100644 fixtures/render-conformance/render-zero-falsiness/meta.json create mode 100644 fixtures/render-conformance/render-zero-falsiness/payload.json create mode 100644 fixtures/render-conformance/render-zero-falsiness/template.mustache create mode 100644 server/java/render/src/test/resources/snapshots/render-list-length.txt create mode 100644 server/java/render/src/test/resources/snapshots/render-shadowed-dotted-prefix.txt create mode 100644 server/java/render/src/test/resources/snapshots/render-zero-falsiness.txt diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 38f6c55490..89f83e5810 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -30,7 +30,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | -| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 23 | ✓ | ✓ | inherits via Java | ✓ | ✓ | +| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 26 | ✓ | ✓ | inherits via Java | 25 / 26 (1 ledgered: `render-shadowed-dotted-prefix`, Stubble stops a dotted name at the first context holding its first segment) | ✓ | | [`fixtures/jinja-render-conformance/`](../fixtures/jinja-render-conformance/) (ADR-0061 — Jinja bodies render the same in jinja2 and nunjucks) | 16 | ✓ (nunjucks) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | refuses, via Java | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | ✓ (jinja2) | | [`fixtures/jinja-verify-conformance/`](../fixtures/jinja-verify-conformance/) (ADR-0061 — the payload check over a Jinja body) | 31 | ✓ | refuses Jinja | refuses, via Java | refuses Jinja | ✓ | | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | @@ -86,7 +86,7 @@ cases); `naming-conformance` (all of it); `codegen-skip-conformance` (ADR-0064), about templates and one about the three-way merge, are named with their reason in its runner); `validation-conformance`, every case, through the generated `validate()`; `decimal-wire` and `duration-wire`, every vector, against the code the generated support -crate carries; `render-conformance`, every case byte-identical, `extract-conformance`, all 58 +crate carries; `render-conformance`, every case but the three ledgered below (`mustache-ng` has its own name lookup, data model and truthiness), `extract-conformance`, all 58 cases, and `output-prompt-conformance`, all 17 in all three styles with the round trip, in the `metaobjects-render` crate; the `core` cases of `writer-conformance` (ADR-0063); and `generator-registry-conformance`, with the eject contract's census, completeness and depth @@ -474,12 +474,12 @@ on a reporting measure, etc.) and 7 `error-yaml-*` fixtures that pin the YAML 1.1 coercion guards (bool / null / hex in string contexts; numeric in enum contexts; reserved-as-attr). -### `fixtures/render-conformance/` (23) +### `fixtures/render-conformance/` (26) -All 23 fixtures → [features/templates-and-payloads.md](features/templates-and-payloads.md) +All 26 fixtures → [features/templates-and-payloads.md](features/templates-and-payloads.md) (render engine output section). 5 are end-to-end shape and escape examples (prompt / email / -spreadsheet / CSV-injection escape / CSV numeric-literal exemption); 16 pin Mustache-engine -semantics — dotted-path lookup, parent-context fallthrough, falsy/empty-array section behavior, +spreadsheet / CSV-injection escape / CSV numeric-literal exemption); 19 pin Mustache-engine +semantics — dotted-path lookup (including a shadowed prefix and a list's `length`), parent-context fallthrough, falsy/empty-array/zero section behavior, inverted sections, nested partials, a comment tag beside a partial, standalone-tag whitespace stripping (including two standalone tags in a row, a standalone tag at the end of the file and an indented standalone tag, which shared docs templates rely on), raw-HTML bypass, trailing-newline preservation, unicode multibyte handling, the derived @@ -489,6 +489,15 @@ the render must raise (`render verify failed: ERR_VAR_NOT_ON_PAYLOAD ()`). this corpus reads that convention; TypeScript compares the text exactly, and Java, Python, C# and Rust require it to appear in the raised message. +Two engines read a case differently from the shared baseline (the TypeScript renderer on +mustache.js), and each runner ledgers the case instead of skipping it, asserting it STILL +differs so the ledger only shrinks. C# (Stubble) ledgers `render-shadowed-dotted-prefix`: it stops +a dotted name at the first context holding its first segment. Rust (`mustache-ng`) ledgers that +case, `render-list-length` (a list's `length` is not a property of its data) and +`render-zero-falsiness` (numbers reach the engine as text, so 0 is truthy). Closing a Rust entry +means resolving names and truthiness in the crate instead of the engine, which is larger than a +localized change and is not done here. + ### `fixtures/jinja-render-conformance/` (16) and `fixtures/jinja-verify-conformance/` (31) Both → [features/templates-and-payloads.md](features/templates-and-payloads.md) (Jinja diff --git a/docs/features/templates-and-payloads.md b/docs/features/templates-and-payloads.md index 3b57158f33..0c3f61a459 100644 --- a/docs/features/templates-and-payloads.md +++ b/docs/features/templates-and-payloads.md @@ -796,7 +796,10 @@ for payload typing per #270) - [`fixtures/render-conformance/render-error-missing-dotted-path/`](../../fixtures/render-conformance/render-error-missing-dotted-path/) — a dotted path whose leaf the payload lacks raises the same error - [`fixtures/render-conformance/render-parent-context-fallthrough/`](../../fixtures/render-conformance/render-parent-context-fallthrough/) — a key missing in the current section falls through to the parent context - [`fixtures/render-conformance/render-empty-array-falsiness/`](../../fixtures/render-conformance/render-empty-array-falsiness/) — `{{#xs}}…{{/xs}}` over an empty array renders nothing (vs. iterates) -- [`fixtures/render-conformance/render-falsy-values/`](../../fixtures/render-conformance/render-falsy-values/) — `false`, `null`, empty string, `0` — which are truthy for `{{#x}}` sections (per Mustache spec, not JS truthiness) +- [`fixtures/render-conformance/render-falsy-values/`](../../fixtures/render-conformance/render-falsy-values/) — `false`, `null`, an empty string and an empty array are falsy for `{{#x}}` sections; a non-empty object renders its body once +- [`fixtures/render-conformance/render-zero-falsiness/`](../../fixtures/render-conformance/render-zero-falsiness/) — `0` is falsy for a section too, as JavaScript truthiness reads it (mustache.js, not the Mustache spec text), and still prints as `0`. NaN is falsy the same way in TypeScript, Java, Kotlin and Python; no JSON payload can carry it, and the C# engine reads it as truthy +- [`fixtures/render-conformance/render-shadowed-dotted-prefix/`](../../fixtures/render-conformance/render-shadowed-dotted-prefix/) — a dotted name, printed or as a section, is tried whole against each context from the innermost outward: `{{a.b}}` inside `{{#items}}` falls through to the enclosing context when the item's `a` has no `b`, and a path that reaches a null does not resolve there +- [`fixtures/render-conformance/render-list-length/`](../../fixtures/render-conformance/render-list-length/) — a list's `length` reads as a number: printed, and as a section and an inverted section - [`fixtures/render-conformance/render-inverted-section/`](../../fixtures/render-conformance/render-inverted-section/) — `{{^x}}…{{/x}}` renders when `x` is falsy/absent - [`fixtures/render-conformance/render-list-separator/`](../../fixtures/render-conformance/render-list-separator/) — the `-last` positional accessor: `{{^-last}}, {{/-last}}` separators, nested lists, single-element and empty lists, a scalar conditional and a single nested object inside a list, an authored key - [`fixtures/render-conformance/render-nested-partials/`](../../fixtures/render-conformance/render-nested-partials/) — `{{>partial}}` resolves through the provider, supports nesting @@ -807,9 +810,17 @@ for payload typing per #270) - [`fixtures/render-conformance/render-unicode-multibyte/`](../../fixtures/render-conformance/render-unicode-multibyte/) — multibyte input handled without truncation or re-encoding Cross-port runner coverage: TS / Java / Kotlin / C# / Python all execute these -via their respective conformance runners. See [`docs/CONFORMANCE.md`](../CONFORMANCE.md) +via their respective conformance runners (Kotlin on the Java engine), and so does the Rust +`metaobjects-render` crate. See [`docs/CONFORMANCE.md`](../CONFORMANCE.md) for the per-port pass/skip ledger. +Two renderers still drift on a case their engine reads differently, and ledger it rather than +skip it: C# on `render-shadowed-dotted-prefix` (Stubble stops a dotted name at the first context +holding its first part), and Rust on that case, `render-list-length` and `render-zero-falsiness` +(the `mustache-ng` engine's own name lookup, data model and truthiness). A ledgered case must +still differ from the baseline, so an engine that comes into agreement fails its runner until the +entry leaves the ledger. + **Jinja bodies (Python and TypeScript, ADR-0061)** - [`fixtures/jinja-render-conformance/`](../../fixtures/jinja-render-conformance/) — 16 cases: variables, loops, conditionals, `set` and macros, `include` and `import`, filters, html and json escaping (with and without `| escape`), whitespace control, `raw` and comments, plus an include cycle, an unresolved include and a missing variable. Byte-identical output from jinja2 and nunjucks. diff --git a/fixtures/render-conformance/render-list-length/expected.txt b/fixtures/render-conformance/render-list-length/expected.txt new file mode 100644 index 0000000000..81aaf28810 --- /dev/null +++ b/fixtures/render-conformance/render-list-length/expected.txt @@ -0,0 +1,4 @@ +count: 3 +non-empty: [has] +empty: [none] +empty count: 0 \ No newline at end of file diff --git a/fixtures/render-conformance/render-list-length/meta.json b/fixtures/render-conformance/render-list-length/meta.json new file mode 100644 index 0000000000..7049a1ded9 --- /dev/null +++ b/fixtures/render-conformance/render-list-length/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "a list's length reads as a number, as a JavaScript property read finds it: printed, as a section and as an inverted section; an empty list's length is 0 and so falsy" } diff --git a/fixtures/render-conformance/render-list-length/payload.json b/fixtures/render-conformance/render-list-length/payload.json new file mode 100644 index 0000000000..6dcac462d9 --- /dev/null +++ b/fixtures/render-conformance/render-list-length/payload.json @@ -0,0 +1,4 @@ +{ + "items": [1, 2, 3], + "empty": [] +} diff --git a/fixtures/render-conformance/render-list-length/template.mustache b/fixtures/render-conformance/render-list-length/template.mustache new file mode 100644 index 0000000000..e63fbcb30a --- /dev/null +++ b/fixtures/render-conformance/render-list-length/template.mustache @@ -0,0 +1,4 @@ +count: {{items.length}} +non-empty: [{{#items.length}}has{{/items.length}}{{^items.length}}none{{/items.length}}] +empty: [{{#empty.length}}has{{/empty.length}}{{^empty.length}}none{{/empty.length}}] +empty count: {{empty.length}} \ No newline at end of file diff --git a/fixtures/render-conformance/render-shadowed-dotted-prefix/expected.txt b/fixtures/render-conformance/render-shadowed-dotted-prefix/expected.txt new file mode 100644 index 0000000000..562262c337 --- /dev/null +++ b/fixtures/render-conformance/render-shadowed-dotted-prefix/expected.txt @@ -0,0 +1,2 @@ +[1][8][1] +(v=1)(v=8)(v=1) \ No newline at end of file diff --git a/fixtures/render-conformance/render-shadowed-dotted-prefix/meta.json b/fixtures/render-conformance/render-shadowed-dotted-prefix/meta.json new file mode 100644 index 0000000000..4b0ab1d8b1 --- /dev/null +++ b/fixtures/render-conformance/render-shadowed-dotted-prefix/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "a dotted name, printed or as a section, is tried whole against each context from the innermost outward: the first context on which the full path resolves wins, and one that holds the first segment but not the rest, or that reaches a null, is skipped, not a stop" } diff --git a/fixtures/render-conformance/render-shadowed-dotted-prefix/payload.json b/fixtures/render-conformance/render-shadowed-dotted-prefix/payload.json new file mode 100644 index 0000000000..938e3f9e5c --- /dev/null +++ b/fixtures/render-conformance/render-shadowed-dotted-prefix/payload.json @@ -0,0 +1,8 @@ +{ + "a": { "b": { "v": 1 } }, + "items": [ + { "a": { "c": 2 } }, + { "a": { "b": { "v": 8 } } }, + { "a": null } + ] +} diff --git a/fixtures/render-conformance/render-shadowed-dotted-prefix/template.mustache b/fixtures/render-conformance/render-shadowed-dotted-prefix/template.mustache new file mode 100644 index 0000000000..5c2bd9042a --- /dev/null +++ b/fixtures/render-conformance/render-shadowed-dotted-prefix/template.mustache @@ -0,0 +1,2 @@ +{{#items}}[{{a.b.v}}]{{/items}} +{{#items}}({{#a.b}}v={{v}}{{/a.b}}){{/items}} \ No newline at end of file diff --git a/fixtures/render-conformance/render-zero-falsiness/expected.txt b/fixtures/render-conformance/render-zero-falsiness/expected.txt new file mode 100644 index 0000000000..d5c8dacca6 --- /dev/null +++ b/fixtures/render-conformance/render-zero-falsiness/expected.txt @@ -0,0 +1,2 @@ +zero: [zero] printed: 0 +one: [yes] printed: 1 \ No newline at end of file diff --git a/fixtures/render-conformance/render-zero-falsiness/meta.json b/fixtures/render-conformance/render-zero-falsiness/meta.json new file mode 100644 index 0000000000..1809254adf --- /dev/null +++ b/fixtures/render-conformance/render-zero-falsiness/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "0 is falsy for a section, as JavaScript truthiness reads it, and still prints as 0; a non-zero number renders the body once" } diff --git a/fixtures/render-conformance/render-zero-falsiness/payload.json b/fixtures/render-conformance/render-zero-falsiness/payload.json new file mode 100644 index 0000000000..284529b8eb --- /dev/null +++ b/fixtures/render-conformance/render-zero-falsiness/payload.json @@ -0,0 +1,4 @@ +{ + "n": 0, + "m": 1 +} diff --git a/fixtures/render-conformance/render-zero-falsiness/template.mustache b/fixtures/render-conformance/render-zero-falsiness/template.mustache new file mode 100644 index 0000000000..ee2ab9edb8 --- /dev/null +++ b/fixtures/render-conformance/render-zero-falsiness/template.mustache @@ -0,0 +1,2 @@ +zero: [{{#n}}yes{{/n}}{{^n}}zero{{/n}}] printed: {{n}} +one: [{{#m}}yes{{/m}}{{^m}}zero{{/m}}] printed: {{m}} \ No newline at end of file diff --git a/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs b/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs index dfdb8967c4..8ec1754aa8 100644 --- a/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs +++ b/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs @@ -16,6 +16,16 @@ namespace MetaObjects.Render.Tests; /// public class RenderConformanceTests { + /// + /// Fixtures the engine (Stubble) renders differently from the shared baseline, with the reason + /// in docs/CONFORMANCE.md. Each is asserted to STILL differ, so an engine that comes + /// into agreement fails here and prompts removing the entry. The ledger only shrinks. + /// + private static readonly HashSet KnownDrift = new(StringComparer.Ordinal) + { + "render-shadowed-dotted-prefix", + }; + private static string CorpusRoot() { string root = AppContext.BaseDirectory; @@ -93,6 +103,12 @@ public void RenderMatchesExpected(string name) Format = format, }); + if (KnownDrift.Contains(name)) + { + Assert.False(expected == actual, $"'{name}' now matches the shared baseline — remove it from KnownDrift"); + return; + } + Assert.Equal(expected, actual); // Determinism: identical across runs. diff --git a/server/csharp/MetaObjects.Render/Renderer.cs b/server/csharp/MetaObjects.Render/Renderer.cs index 05679032bb..aae4dcef09 100644 --- a/server/csharp/MetaObjects.Render/Renderer.cs +++ b/server/csharp/MetaObjects.Render/Renderer.cs @@ -106,10 +106,15 @@ public static string Render(RenderRequest request) string expanded = Expand(body, request.Provider, startPath); var escaper = Escapers.For(request.Format); + // Every list the view carries is a List (see PayloadAccessors.Derive). A list's + // `length` is a property to a JavaScript read, so the engine answers it here. + var elementAt = RendererSettingsDefaults.DefaultValueGetters()[typeof(System.Collections.IList)]; var stubble = new StubbleBuilder() .Configure(settings => settings .SetEncodingFunction(v => escaper(v)) - .AddValueGetter(PayloadAccessors.ViewType, PayloadAccessors.ViewLookup)) + .AddValueGetter(PayloadAccessors.ViewType, PayloadAccessors.ViewLookup) + .AddValueGetter(typeof(List), (value, key, ignoreCase) => + key == LengthProperty ? ((System.Collections.IList)value).Count : elementAt(value, key, ignoreCase))) .Build(); // Derived `has` accessors are part of the payload contract, not of the diff --git a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java index 6a5e67735f..0e3cd08874 100644 --- a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java +++ b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java @@ -1,13 +1,13 @@ package com.metaobjects.render; import com.github.mustachejava.DefaultMustacheFactory; +import com.github.mustachejava.Iteration; import com.github.mustachejava.Mustache; import com.github.mustachejava.DefaultMustacheVisitor; import com.github.mustachejava.MustacheException; import com.github.mustachejava.MustacheVisitor; import com.github.mustachejava.TemplateContext; import com.github.mustachejava.codes.ValueCode; -import com.github.mustachejava.reflect.Guard; import com.github.mustachejava.reflect.MissingWrapper; import com.github.mustachejava.reflect.ReflectionObjectHandler; import com.github.mustachejava.util.GuardException; @@ -17,6 +17,8 @@ import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; +import java.lang.reflect.Array; +import java.math.BigDecimal; import java.util.ArrayDeque; import java.util.Collection; import java.util.Collections; @@ -207,23 +209,6 @@ private static String preExpandPartials(String text, Provider provider, Deque guards) { - return new AbsentWrapper(name, guards.toArray(new Guard[0])); - } - } - /** * A variable tag whose name is absent from the payload raises, with the message the opt-in * verify gate uses, so a typo like {@code {{nmae}}} fails on every render path. Section tags @@ -236,39 +221,101 @@ private static final class CheckedValueCode extends ValueCode { @Override public Writer execute(Writer writer, List scopes) { - if (!returnThis && oh.find(name, scopes) instanceof AbsentWrapper && !presentWholePath(scopes)) { + if (!returnThis && ((MissingVariableObjectHandler) oh).absent(name, scopes)) { throw new RenderException( "render verify failed: " + Verify.ERR_VAR_NOT_ON_PAYLOAD + " (" + name + ")"); } return super.execute(writer, scopes); } + } - /** - * The reference check (TypeScript on mustache.js) tries the WHOLE dotted name against each - * context from the innermost outward, and reads a list's {@code length} as a property. The - * engine's own lookup stops at the first context holding the first segment, so without this - * a name TypeScript renders (a shadowed prefix, {@code items.length}) would raise here. - */ - /** The list property JavaScript exposes, and the reference check therefore treats as present. */ + /** + * The engine's object handler, reading four rules the way the reference renderer does + * (TypeScript on mustache.js) wherever the engine alone reads them differently: + * + *
    + *
  • a name on no scope is missing, while a key present with a null value is not;
  • + *
  • a dotted name is tried WHOLE against each context from the innermost outward, and + * the first context on which the full path resolves wins. The engine alone stops at + * the first context holding the first segment;
  • + *
  • a list's {@code length} is a property, as it is to a JavaScript read;
  • + *
  • a zero or NaN number is falsy for a section.
  • + *
+ */ + private static final class MissingVariableObjectHandler extends ReflectionObjectHandler { + /** Marks a value the context does not carry, as distinct from a key present with a null value. */ + private static final Object ABSENT = new Object(); + + /** The list property JavaScript exposes. */ private static final String LENGTH_PROPERTY = "length"; - private boolean presentWholePath(List scopes) { - int dot = name.lastIndexOf('.'); - String listName = dot > 0 && LENGTH_PROPERTY.equals(name.substring(dot + 1)) ? name.substring(0, dot) : null; + /** Whether {@code name} is on no scope of the payload. */ + boolean absent(String name, List scopes) { + return name.indexOf('.') < 0 + ? super.find(name, scopes) instanceof MissingWrapper + : resolve(name.split("\\.", -1), scopes) == ABSENT; + } + + @Override + public Wrapper find(String name, List scopes) { + if (name.indexOf('.') < 0) return super.find(name, scopes); + String[] parts = name.split("\\.", -1); + // Resolved against the scopes it is CALLED with, so the engine may cache it. + return calledWith -> valueOf(parts, calledWith); + } + + private Object valueOf(String[] parts, List scopes) { + Object value = resolve(parts, scopes); + return value == ABSENT ? null : value; + } + + /** The whole of {@code parts} against each scope from the innermost outward. */ + private Object resolve(String[] parts, List scopes) { for (int i = scopes.size() - 1; i >= 0; i--) { - List one = Collections.singletonList(scopes.get(i)); - if (!(oh.find(name, one) instanceof AbsentWrapper)) return true; - if (listName == null) continue; - Wrapper w = oh.find(listName, one); - if (w instanceof AbsentWrapper) continue; + Object value = scopes.get(i); + for (String part : parts) { + value = property(value, part); + if (value == ABSENT) break; + } + if (value != ABSENT) return value; + } + return ABSENT; + } + + /** One property read, as JavaScript finds it: the engine's own member lookup, or a list's length. */ + private Object property(Object scope, String part) { + if (scope == null) return ABSENT; + List one = Collections.singletonList(scope); + Wrapper wrapper = super.find(part, one); + if (!(wrapper instanceof MissingWrapper)) { try { - Object v = w.call(one); - if (v instanceof Collection || (v != null && v.getClass().isArray())) return true; + return coerce(wrapper.call(one)); } catch (GuardException e) { - // not resolvable on this context; try the next one out + return ABSENT; } } - return false; + if (LENGTH_PROPERTY.equals(part)) { + if (scope instanceof Collection collection) return collection.size(); + if (scope.getClass().isArray()) return Array.getLength(scope); + } + return ABSENT; + } + + @Override + public Writer iterate(Iteration iteration, Writer writer, Object object, List scopes) { + return super.iterate(iteration, writer, falsyNumber(object) ? null : object, scopes); + } + + @Override + public Writer falsey(Iteration iteration, Writer writer, Object object, List scopes) { + return super.falsey(iteration, writer, falsyNumber(object) ? null : object, scopes); + } + + private static boolean falsyNumber(Object value) { + if (value instanceof BigDecimal decimal) return decimal.signum() == 0; + if (!(value instanceof Number number)) return false; + double d = number.doubleValue(); + return d == 0 || d != d; } } } diff --git a/server/java/render/src/test/java/com/metaobjects/render/RendererTest.java b/server/java/render/src/test/java/com/metaobjects/render/RendererTest.java index 072562b992..93ade85a37 100644 --- a/server/java/render/src/test/java/com/metaobjects/render/RendererTest.java +++ b/server/java/render/src/test/java/com/metaobjects/render/RendererTest.java @@ -29,20 +29,34 @@ public void sectionIteration() { @Test public void namesTheReferenceResolvesDoNotRaiseAsMissing() { - // The missing-variable check follows the reference (TypeScript on mustache.js): a dotted - // name is tried whole against each context, and a list's length is a property. What the - // engine then prints for these is a separate, open parity question, so only the absence of - // ERR_VAR_NOT_ON_PAYLOAD is pinned here. + // The engine follows the reference (TypeScript on mustache.js): a dotted name is tried + // whole against each context, and a list's length is a property. var shadowed = new RenderRequest( "{{#items}}[{{a.b}}]{{/items}}", null, Map.of("a", Map.of("b", 1), "items", List.of(Map.of("a", Map.of("c", 2)))), new InMemoryProvider(Map.of()), "text", null, null); - new Renderer().render(shadowed); + assertEquals("[1]", new Renderer().render(shadowed)); var length = new RenderRequest( "count: {{items.length}}", null, Map.of("items", List.of(1, 2, 3)), new InMemoryProvider(Map.of()), "text", null, null); - new Renderer().render(length); + assertEquals("count: 3", new Renderer().render(length)); + } + + @Test + public void aZeroOrNaNNumberIsFalsyForASection() { + var zero = new RenderRequest( + "{{#n}}yes{{/n}}{{^n}}zero{{/n}} printed: {{n}}", null, + Map.of("n", 0), + new InMemoryProvider(Map.of()), "text", null, null); + assertEquals("zero printed: 0", new Renderer().render(zero)); + + // No JSON payload can carry NaN, so the shared corpus cannot pin it. + var nan = new RenderRequest( + "{{#n}}yes{{/n}}{{^n}}zero{{/n}}", null, + Map.of("n", Double.NaN), + new InMemoryProvider(Map.of()), "text", null, null); + assertEquals("zero", new Renderer().render(nan)); } /** A value object's generated record, as a template's payload (ADR-0056). */ diff --git a/server/java/render/src/test/resources/snapshots/render-list-length.txt b/server/java/render/src/test/resources/snapshots/render-list-length.txt new file mode 100644 index 0000000000..81aaf28810 --- /dev/null +++ b/server/java/render/src/test/resources/snapshots/render-list-length.txt @@ -0,0 +1,4 @@ +count: 3 +non-empty: [has] +empty: [none] +empty count: 0 \ No newline at end of file diff --git a/server/java/render/src/test/resources/snapshots/render-shadowed-dotted-prefix.txt b/server/java/render/src/test/resources/snapshots/render-shadowed-dotted-prefix.txt new file mode 100644 index 0000000000..562262c337 --- /dev/null +++ b/server/java/render/src/test/resources/snapshots/render-shadowed-dotted-prefix.txt @@ -0,0 +1,2 @@ +[1][8][1] +(v=1)(v=8)(v=1) \ No newline at end of file diff --git a/server/java/render/src/test/resources/snapshots/render-zero-falsiness.txt b/server/java/render/src/test/resources/snapshots/render-zero-falsiness.txt new file mode 100644 index 0000000000..d5c8dacca6 --- /dev/null +++ b/server/java/render/src/test/resources/snapshots/render-zero-falsiness.txt @@ -0,0 +1,2 @@ +zero: [zero] printed: 0 +one: [yes] printed: 1 \ No newline at end of file diff --git a/server/rust/metaobjects-render/tests/render_conformance.rs b/server/rust/metaobjects-render/tests/render_conformance.rs index dfc52664a2..3211f02b49 100644 --- a/server/rust/metaobjects-render/tests/render_conformance.rs +++ b/server/rust/metaobjects-render/tests/render_conformance.rs @@ -8,6 +8,9 @@ //! referenced as `{{> partials/}}`. A sub-corpus with no `template.mustache` of its //! own (`template-generator/`, which drives the codegen `template` generator) has its own //! harness and is not a render case. +//! +//! [`KNOWN_DRIFT`] lists the cases the engine renders differently from the shared baseline. A +//! listed case must STILL differ, so the ledger cannot go stale, and it only shrinks. use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -16,6 +19,24 @@ use serde_json::Value; use metaobjects_render::{Body, InMemoryProvider, RenderRequest, render}; +/// Cases the `mustache-ng` engine renders differently from the shared baseline, each with the +/// rule it does not implement. Closing them means resolving names and section truthiness in this +/// crate instead of the engine. +const KNOWN_DRIFT: &[(&str, &str)] = &[ + ( + "render-shadowed-dotted-prefix", + "the engine stops a dotted name at the first context holding its first segment", + ), + ( + "render-list-length", + "a list's `length` is not a property of the engine's data", + ), + ( + "render-zero-falsiness", + "numbers reach the engine as text, so 0 is truthy", + ), +]; + fn corpus() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/render-conformance") } @@ -72,7 +93,16 @@ fn run_case(dir: &Path) -> Result<(), String> { } let expected = read(&dir.join("expected.txt")); let actual = result.map_err(|e| e.to_string())?; + let name = dir.file_name().unwrap().to_string_lossy(); + let drift = KNOWN_DRIFT.iter().find(|(case, _)| *case == name); if actual == expected { + if let Some((_, rule)) = drift { + return Err(format!( + "matches the shared baseline; remove it from KNOWN_DRIFT ({rule})" + )); + } + Ok(()) + } else if drift.is_some() { Ok(()) } else { Err(format!("expected {expected:?}\n actual {actual:?}")) From b01e77eb44d96ef217197fed1f32480ff90142d6 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Tue, 24 Nov 2026 16:52:15 -0500 Subject: [PATCH 19/23] no-mistakes(review): apply reviewer inline fixes --- docs/CONFORMANCE.md | 2 +- server/csharp/MetaObjects/CoreTypes.cs | 10 +++++----- .../src/main/java/com/metaobjects/MetaRoot.java | 13 +++++++------ server/python/src/metaobjects/core_types.py | 9 +++++---- .../decisions/ADR-0061-per-port-template-engines.md | 4 ++-- 5 files changed, 20 insertions(+), 18 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 89f83e5810..39efecfe4f 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -879,7 +879,7 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) The fixtures in the nine corpora mapped above (metamodel 584 + yaml 19 + verify 45 -+ render 23 + persistence 68 + api-contract 179 + source-resolution 28 + scope 10 + ++ render 26 + persistence 68 + api-contract 179 + source-resolution 28 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the `cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining corpora in the totals table gate tooling contracts (registry manifests, provider diff --git a/server/csharp/MetaObjects/CoreTypes.cs b/server/csharp/MetaObjects/CoreTypes.cs index 3bb30debb0..eedcecca78 100644 --- a/server/csharp/MetaObjects/CoreTypes.cs +++ b/server/csharp/MetaObjects/CoreTypes.cs @@ -282,7 +282,8 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) (tid, n) => new MetaRoot(tid, n), [])); - // object — 5 subtypes (base, entity, value, projection, report) + // object — 4 subtypes registered here (base, entity, value, projection); report is the + // reporting pack's (ReportingMetaDataProvider) List objectRules = [ Wildcard(TYPE_FIELD), @@ -323,10 +324,9 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) // attr.filter object lowered to a view-level WHERE). Strict attr scoping // (from spec object.json's projection allow-list) keeps it here and prunes // the discriminator attrs, which projection does not declare. - // FR-044: object.report carries @from / @dimensions / @measures / @segment / - // @filter. Strict attr scoping (from spec object.json's report allow-list) - // keeps those and prunes the discriminator attrs, which a report does not - // declare; its structural child graph also comes from the spec. + // FR-044: object.report (@from / @dimensions / @measures / @segment / @filter / + // @spine) is registered by the reporting pack from spec reporting.json, not + // in this loop. List objectAttrs = subType switch { OBJECT_SUBTYPE_PROJECTION => [.. ObjectSchema.ObjectAttrs, ObjectSchema.ProjectionFilterAttr, ObjectSchema.CollectionNameAttr], 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 c1d632902e..7b817b6e8b 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java +++ b/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java @@ -100,13 +100,14 @@ public static void registerTypes(MetaDataRegistry registry) { // the TS reference HAND-CODE the root; it is the single documented // hand-coded exception to the JSON-sourced model). The manifest's // STRUCTURAL children block must byte-match the cross-port golden: - // description "Root metadata document" and EXACTLY the five genuinely-open - // structural wildcards a document root legitimately holds — object / field - // / validator / template / requirement (mirrors the TS reference - // core-types.ts `def(TYPE_METADATA, SUBTYPE_ROOT, "Root metadata document", + // description "Root metadata document" and EXACTLY the four genuinely-open + // structural wildcards core itself registers — object / field / validator / + // template (mirrors the TS reference core-types.ts + // `def(TYPE_METADATA, SUBTYPE_ROOT, "Root metadata document", // [wildcard(TYPE_OBJECT), wildcard(TYPE_FIELD), wildcard(TYPE_VALIDATOR), - // wildcard(TYPE_TEMPLATE), wildcard(TYPE_REQUIREMENT)])`; capability - // requirements are declared beside the entities they describe). The + // wildcard(TYPE_TEMPLATE)])`. A `requirement` child is admitted by the + // requirements pack (requirement.json `extends`, applied by + // RequirementTypesMetaDataProvider), beside the entities it describes. The // previously-registered // view/identity/relationship/layout STRUCTURAL root wildcards are removed // to match the strict contract. diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index 72b4012a04..09da5c036f 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -244,10 +244,11 @@ def _register_subtypes( # NOT declared in any spec/metamodel/*.json provider file; both this port and the TS # reference HAND-CODE the root (the single documented hand-coded exception to the # JSON-sourced model). Its STRUCTURAL children must byte-match the cross-port golden: -# description "Root metadata document" and EXACTLY the five genuinely-open structural -# wildcards a document root legitimately holds — field / object / requirement / -# template / validator -# (mirrors the TS core-types.ts root def and the Java MetaRoot registration). Because +# description "Root metadata document" and EXACTLY the four genuinely-open structural +# wildcards core itself registers — field / object / template / validator +# (mirrors the TS core-types.ts root def and the Java MetaRoot registration). A +# `requirement` child is admitted by the requirements pack (requirement.json +# `extends`), beside the entities it describes. Because # it is undeclared in the JSON, the strict-children pass leaves it untouched, so the # children registered HERE are emitted verbatim. The any-attr wildcard is intentionally # omitted — the golden carries attrs:[] for the root (no metadata-attr vocabulary). diff --git a/spec/decisions/ADR-0061-per-port-template-engines.md b/spec/decisions/ADR-0061-per-port-template-engines.md index 6e88cd9e86..f53d5897a1 100644 --- a/spec/decisions/ADR-0061-per-port-template-engines.md +++ b/spec/decisions/ADR-0061-per-port-template-engines.md @@ -128,6 +128,6 @@ stays missing however deep it chains (`v.x.y`), and printing it raises (Amendmen Printing a name absent from the payload raises `render verify failed: ERR_VAR_NOT_ON_PAYLOAD` in the Jinja engines (jinja2 and nunjucks) and in every port's Mustache engine (Rust renders no -template). It is the message the Mustache path raises, and it applies on every render path. A present null still prints empty, and a section over an absent name still -renders nothing. Corpus: `fixtures/jinja-render-conformance/jinja-render-error-missing-variable/` and +Jinja template). It is the message the Mustache path raises, and it applies on every render +path. A present null still prints empty, and a section over an absent name still renders nothing. Corpus: `fixtures/jinja-render-conformance/jinja-render-error-missing-variable/` and `fixtures/render-conformance/render-error-missing-variable/`. From abd6a1189a7618361f66aac34faea8ccfe756b76 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Tue, 24 Nov 2026 17:13:13 -0500 Subject: [PATCH 20/23] no-mistakes(test): apply changes made during test validation --- server/rust/metaobjects-render/src/presence.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/server/rust/metaobjects-render/src/presence.rs b/server/rust/metaobjects-render/src/presence.rs index 6d293e3dac..28a89add4d 100644 --- a/server/rust/metaobjects-render/src/presence.rs +++ b/server/rust/metaobjects-render/src/presence.rs @@ -108,7 +108,11 @@ fn resolve<'a>(context: &'a Value, segments: &[&str]) -> Option<&'a Value> { segments.iter().try_fold(context, |value, segment| { property(value, segment).or_else(|| { let items = value.as_array().filter(|_| *segment == LENGTH)?; - Some(if items.is_empty() { &LENGTH_ZERO } else { &LENGTH_NONZERO }) + Some(if items.is_empty() { + &LENGTH_ZERO + } else { + &LENGTH_NONZERO + }) }) }) } @@ -176,7 +180,10 @@ mod tests { assert_eq!(missing("{{#flag}}{{gone}}{{/flag}}", &payload), None); assert_eq!(missing("{{#items}}{{gone}}{{/items}}", &payload), None); assert_eq!(missing("{{items.length}}", &payload), None); - assert_eq!(missing("{{#items.length}}{{gone}}{{/items.length}}", &payload), None); + assert_eq!( + missing("{{#items.length}}{{gone}}{{/items.length}}", &payload), + None + ); assert_eq!( missing("{{^nope}}{{gone}}{{/nope}}", &payload), Some("gone".to_string()) From 67177db07673162d0cb9c7bd0c673188832d340e Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Tue, 24 Nov 2026 21:03:24 -0500 Subject: [PATCH 21/23] no-mistakes(review): apply reviewer inline fixes --- .../packages/metadata/src/loader/rules-validation.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/server/typescript/packages/metadata/src/loader/rules-validation.ts b/server/typescript/packages/metadata/src/loader/rules-validation.ts index 669c7698ff..408ff3bb19 100644 --- a/server/typescript/packages/metadata/src/loader/rules-validation.ts +++ b/server/typescript/packages/metadata/src/loader/rules-validation.ts @@ -44,8 +44,10 @@ // one the route answers itself (RESERVED_ERROR_CODES) // P3 ERR_TRANSITION_NAME_COLLISION two permission points ask the policy about one permission name, and at // least one of the two names is derived (ADR-0066 §1): an operation -// named "Order.open", one declaring @permission "p.Order.open", or one -// in package "p::Order", beside the "open" transition of Order in "p". +// named "Order.open", or one declaring @permission "p.Order.open", +// beside the "open" transition of Order in "p". Names are compared +// exactly: an "open" operation in package "p::Order" is "p::Order.open", +// a different name, and does not collide. // Two DECLARED @permission values may be equal: that sharing is the point. // 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) From 193c15fc1146ded9458f5fde5af65d5f4eb5937a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Tue, 24 Nov 2026 21:08:59 -0500 Subject: [PATCH 22/23] no-mistakes(review): Exempt only folded base attrs from Rust ownership check --- AGENTS.md | 2 +- docs/CONFORMANCE.md | 3 +- server/rust/metaobjects/src/providers.rs | 1 + server/rust/metaobjects/src/registry.rs | 5 ++- .../tests/registry_base_ownership.rs | 40 +++++++++++++++++++ .../render/test/render-conformance.test.ts | 4 +- 6 files changed, 49 insertions(+), 6 deletions(-) create mode 100644 server/rust/metaobjects/tests/registry_base_ownership.rs diff --git a/AGENTS.md b/AGENTS.md index dbcf400a88..8149e58836 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,7 +75,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. **Cross-port conformance corpora** (every port runs the shared corpus): - Metamodel: `fixtures/conformance/` (584 fixtures; 46 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. +- Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python byte-identical; C# and Rust each carry a `KnownDrift` render ledger, recorded in `docs/CONFORMANCE.md`. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (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. - YAML / verify corpora green across the ports that ship those layers. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 39efecfe4f..aefc273daf 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -486,8 +486,7 @@ indented standalone tag, which shared docs templates rely on), raw-HTML bypass, `has` accessor, and the `-last` list-separator accessor. 2 are error cases: a fixture that must refuse carries `expected-error.txt` in place of `expected.txt`, holding the error text the render must raise (`render verify failed: ERR_VAR_NOT_ON_PAYLOAD ()`). Every port that runs -this corpus reads that convention; TypeScript compares the text exactly, and Java, Python, C# and Rust -require it to appear in the raised message. +this corpus reads that convention; every port requires it to appear in the raised message (Python's jinja runner compares it exactly). Two engines read a case differently from the shared baseline (the TypeScript renderer on mustache.js), and each runner ledgers the case instead of skipping it, asserting it STILL diff --git a/server/rust/metaobjects/src/providers.rs b/server/rust/metaobjects/src/providers.rs index 902802afee..27352af63f 100644 --- a/server/rust/metaobjects/src/providers.rs +++ b/server/rust/metaobjects/src/providers.rs @@ -450,6 +450,7 @@ fn define_from_data( def.implemented_in = t.implemented_in.clone(); def.max_occurs = t.max_occurs; def.default_name = t.default_name.clone(); + def.extends_base = t.extends_base; out.push(def); } Ok(out) diff --git a/server/rust/metaobjects/src/registry.rs b/server/rust/metaobjects/src/registry.rs index 0746c02f6e..1f816a7f5c 100644 --- a/server/rust/metaobjects/src/registry.rs +++ b/server/rust/metaobjects/src/registry.rs @@ -132,6 +132,8 @@ pub struct TypeDefinition { pub max_occurs: Option, pub default_name: Option, pub references: Vec, + /// The attributes of the registered `.base` were folded into this definition. + pub extends_base: bool, } impl TypeDefinition { @@ -151,6 +153,7 @@ impl TypeDefinition { max_occurs: None, default_name: None, references: Vec::new(), + extends_base: false, } } @@ -315,7 +318,7 @@ impl TypeRegistry { // subtype with `extendsBase`, e.g. object.report) is the base owner's, not a new // claim: it is not checked against the registering provider, and is stamped with // the owner the base attribute already has. - let base_names: HashSet = if def.sub_type == SUBTYPE_BASE { + let base_names: HashSet = if def.sub_type == SUBTYPE_BASE || !def.extends_base { HashSet::new() } else { self.find(&def.type_name, SUBTYPE_BASE) diff --git a/server/rust/metaobjects/tests/registry_base_ownership.rs b/server/rust/metaobjects/tests/registry_base_ownership.rs new file mode 100644 index 0000000000..4e4cb92479 --- /dev/null +++ b/server/rust/metaobjects/tests/registry_base_ownership.rs @@ -0,0 +1,40 @@ +//! ADR-0062: an attribute folded in from `.base` is the base owner's; one a +//! provider declares itself under the same name is a claim, and is refused. + +use metaobjects::errors::ERR_PROVIDER_ATTR_SHADOW; +use metaobjects::registry::{AttrSchema, TypeDefinition, TypeRegistry}; + +fn with_base() -> TypeRegistry { + let mut r = TypeRegistry::new(); + r.run_as_provider("core", |r| { + let mut base = TypeDefinition::new("object", "base", "base"); + base.attributes + .push(AttrSchema::simple("discriminator", Some("string"), "d")); + r.register(base).expect("base registers"); + }); + r +} + +fn subtype(extends_base: bool) -> TypeDefinition { + let mut def = TypeDefinition::new("object", "foo", "foo"); + def.attributes + .push(AttrSchema::simple("discriminator", Some("string"), "d")); + def.extends_base = extends_base; + def +} + +#[test] +fn a_folded_base_attribute_is_not_a_claim() { + let mut r = with_base(); + r.run_as_provider("pack", |r| r.register(subtype(true))) + .expect("a folded attribute is the base owner's"); +} + +#[test] +fn a_redeclared_base_attribute_is_refused() { + let mut r = with_base(); + let err = r + .run_as_provider("pack", |r| r.register(subtype(false))) + .expect_err("a second provider may not claim the base attribute"); + assert_eq!(err.code, ERR_PROVIDER_ATTR_SHADOW, "{err:?}"); +} diff --git a/server/typescript/packages/render/test/render-conformance.test.ts b/server/typescript/packages/render/test/render-conformance.test.ts index aa130789ba..a3c6499402 100644 --- a/server/typescript/packages/render/test/render-conformance.test.ts +++ b/server/typescript/packages/render/test/render-conformance.test.ts @@ -8,7 +8,7 @@ import { render, InMemoryProvider, type RenderFormat } from "../src/index.js"; // template.mustache the entry template // partials/*.mustache optional partials, referenced as `partials/` // payload.json the render payload (pre-formatted primitives) -// expected.txt byte-exact expected output, or expected-error.txt: the exact error message +// expected.txt byte-exact expected output, or expected-error.txt: a message the thrown error must contain // The same (payload + template) MUST produce expected.txt byte-for-byte. const CORPUS = join(import.meta.dir, "../../../../../fixtures/render-conformance"); @@ -43,7 +43,7 @@ describe("render-conformance corpus", () => { const template = readFileSync(join(dir, "template.mustache"), "utf8"); const payload = JSON.parse(readFileSync(join(dir, "payload.json"), "utf8")); const provider = providerFromPartials(dir); - // expected-error.txt (instead of expected.txt): the exact message the render must throw. + // expected-error.txt (instead of expected.txt): a message the render's thrown error must contain. if (existsSync(join(dir, "expected-error.txt"))) { const message = readFileSync(join(dir, "expected-error.txt"), "utf8").replace(/\n$/, ""); expect(() => render({ template, payload, provider, format: meta.format })).toThrow(message); From f8bae36dfbe903fd92d4c4c55fe4ae826e97616f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Tue, 24 Nov 2026 21:42:46 -0500 Subject: [PATCH 23/23] no-mistakes(document): Docs: Rust ledger, render parity, pack counts --- README.md | 2 +- docs/CONFORMANCE.md | 1 + docs/features/codegen-concepts.md | 5 +++-- docs/features/templates-and-payloads.md | 6 +++--- docs/ports/rust.md | 11 ++++++----- spec/roadmap.md | 2 +- 6 files changed, 15 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e68c94f233..fa659e4d84 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,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 | **Crates ready to publish, not yet published** — loader (JSON + YAML), project and source resolution, naming and all 41 validation passes; 578 / 578 metamodel conformance; prompt render and the reply parser (`metaobjects-render`); `cargo meta init` / `gen` / `verify` / `eject` with the `entity`, `client` and `commands` generators (ADR-0065). Schema migrations stay with the Node `meta` tool | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | +| Rust | **Crates ready to publish, not yet published** — loader (JSON + YAML), project and source resolution, naming and all 41 validation passes; 584 / 584 metamodel conformance; prompt render and the reply parser (`metaobjects-render`); `cargo meta init` / `gen` / `verify` / `eject` with the `entity`, `client` and `commands` generators (ADR-0065). Schema migrations stay with the Node `meta` tool | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | ## Capability matrix diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index aefc273daf..e637ae10b0 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -461,6 +461,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. | `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) | +| `error-packs-left-out-*` | [features/extending-with-providers.md](features/extending-with-providers.md) ([Where vocabulary lives](features/extending-with-providers.md#where-vocabulary-lives): a model that uses a left-out pack's type fails to load, naming the unknown type or subtype) | | `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) | diff --git a/docs/features/codegen-concepts.md b/docs/features/codegen-concepts.md index a1a6dc89c9..b21be285aa 100644 --- a/docs/features/codegen-concepts.md +++ b/docs/features/codegen-concepts.md @@ -66,7 +66,7 @@ each: | Mechanism | Speed | Readability of output shape | Travels across ports? | Reach for it when… | |---|---|---|---|---| | **Direct code** (TS/Java/C#/Python/Kotlin generator) | **Fastest** | Lower — the output is assembled in code; you don't *see* the shape at a glance | No (port-bound) | You want speed + full programmatic power, and complex logic | -| **Mustache template** | Slower | **Highest** — the output shape is right there in the template; easy to read + review | **Yes** — byte-identical across every port's render engine | The output shape matters more than raw speed; you want one template to serve several languages | +| **Mustache template** | Slower | **Highest** — the output shape is right there in the template; easy to read + review | **Yes** — byte-identical across every port's render engine (two engines ledger a handful of engine-specific cases; [`docs/CONFORMANCE.md`](../CONFORMANCE.md) records them) | The output shape matters more than raw speed; you want one template to serve several languages | | **Groovy** (JVM) | Slower | Medium | JVM | Scriptable JVM authoring without a compile step | | **Cross-language** (TS/Python emitting Java/C#) | — | — | Yes | One team authors all generators in their preferred language for any target | @@ -75,7 +75,8 @@ template is *cleaner to look at* — the generated shape is visible in the templ instead of buried in string assembly. Pick speed (direct) when the logic is gnarly or the run is hot; pick a template (Mustache) when the shape is what you're iterating on, or when you want the same output across languages. Mustache is also the natural -cross-language bridge: the render engine is byte-identical in every port, so one +cross-language bridge: the render engine is byte-identical in every port (a +handful of engine-specific cases sit on C#'s and Rust's ledgers), so one template emits identical output anywhere. ## 4. Regeneration strategy — the run skips itself diff --git a/docs/features/templates-and-payloads.md b/docs/features/templates-and-payloads.md index 0c3f61a459..717538fdcf 100644 --- a/docs/features/templates-and-payloads.md +++ b/docs/features/templates-and-payloads.md @@ -782,14 +782,14 @@ for payload typing per #270) - [`fixtures/conformance/error-origin-passthrough-array-mismatch/`](../../fixtures/conformance/error-origin-passthrough-array-mismatch/) — a `passthrough` field whose array-ness differs from its `@from` source fails with `ERR_PASSTHROUGH_TYPE_MISMATCH` - [`fixtures/conformance/origin-passthrough-convert-optout/`](../../fixtures/conformance/origin-passthrough-convert-optout/) — `@convert: true` acknowledges a deliberate type divergence (no cast generated) -**Render engine output (`fixtures/render-conformance/`)** — byte-identical Mustache output across ports +**Render engine output (`fixtures/render-conformance/`)** — byte-identical Mustache output across ports, except the two engines' ledgered cases recorded at the end of this section - [`fixtures/render-conformance/render-example-prompt/`](../../fixtures/render-conformance/render-example-prompt/) — `template.prompt` end-to-end render - [`fixtures/render-conformance/render-example-email/`](../../fixtures/render-conformance/render-example-email/) — `template.output @format=html` (transactional email) - [`fixtures/render-conformance/render-example-spreadsheet/`](../../fixtures/render-conformance/render-example-spreadsheet/) — `@format=csv` with header row - [`fixtures/render-conformance/render-csv-injection/`](../../fixtures/render-conformance/render-csv-injection/) — OWASP CSV-injection escaping (leading `= + - @ \t \r`) -**Render engine semantics** — Mustache-spec behavior pinned cross-port (every port's renderer must emit byte-identical output) +**Render engine semantics** — Mustache-spec behavior pinned cross-port (byte-identical output, the ledgered engine differences recorded below aside) - [`fixtures/render-conformance/render-dotted-path-lookup/`](../../fixtures/render-conformance/render-dotted-path-lookup/) — `{{a.b.c}}` traversal across nested objects - [`fixtures/render-conformance/render-error-missing-variable/`](../../fixtures/render-conformance/render-error-missing-variable/) — a `{{name}}` the payload lacks raises `ERR_VAR_NOT_ON_PAYLOAD` (`expected-error.txt`, in place of `expected.txt`) @@ -797,7 +797,7 @@ for payload typing per #270) - [`fixtures/render-conformance/render-parent-context-fallthrough/`](../../fixtures/render-conformance/render-parent-context-fallthrough/) — a key missing in the current section falls through to the parent context - [`fixtures/render-conformance/render-empty-array-falsiness/`](../../fixtures/render-conformance/render-empty-array-falsiness/) — `{{#xs}}…{{/xs}}` over an empty array renders nothing (vs. iterates) - [`fixtures/render-conformance/render-falsy-values/`](../../fixtures/render-conformance/render-falsy-values/) — `false`, `null`, an empty string and an empty array are falsy for `{{#x}}` sections; a non-empty object renders its body once -- [`fixtures/render-conformance/render-zero-falsiness/`](../../fixtures/render-conformance/render-zero-falsiness/) — `0` is falsy for a section too, as JavaScript truthiness reads it (mustache.js, not the Mustache spec text), and still prints as `0`. NaN is falsy the same way in TypeScript, Java, Kotlin and Python; no JSON payload can carry it, and the C# engine reads it as truthy +- [`fixtures/render-conformance/render-zero-falsiness/`](../../fixtures/render-conformance/render-zero-falsiness/) — `0` is falsy for a section too, as JavaScript truthiness reads it (mustache.js, not the Mustache spec text), and still prints as `0`. NaN is falsy the same way in TypeScript, Java, Kotlin and Python; no JSON payload can carry it, and the C# engine reads NaN as truthy - [`fixtures/render-conformance/render-shadowed-dotted-prefix/`](../../fixtures/render-conformance/render-shadowed-dotted-prefix/) — a dotted name, printed or as a section, is tried whole against each context from the innermost outward: `{{a.b}}` inside `{{#items}}` falls through to the enclosing context when the item's `a` has no `b`, and a path that reaches a null does not resolve there - [`fixtures/render-conformance/render-list-length/`](../../fixtures/render-conformance/render-list-length/) — a list's `length` reads as a number: printed, and as a section and an inverted section - [`fixtures/render-conformance/render-inverted-section/`](../../fixtures/render-conformance/render-inverted-section/) — `{{^x}}…{{/x}}` renders when `x` is falsy/absent diff --git a/docs/ports/rust.md b/docs/ports/rust.md index e4b494e021..b1a6528b2d 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -263,16 +263,17 @@ root), and a git URL names a repository and an optional revision. ### Conformance -The port runs the shared corpora below. Four of them keep a ledger: a fixture that fails and is not on +The port runs the shared corpora below. Five of them keep a ledger: a fixture that fails and is not on the port's ledger prints a warning and does not fail the `rust` lane until ADR-0065 turns the warning off; a -fixture that passed and regresses still fails it, because each ledger records how many fixtures must -pass (`minPassing`) and may only shrink. The others have no ledger: each case asserts its result +fixture that passed and regresses still fails it, because each ledger records what the port passes +today — a `minPassing` count, or (the render corpus) the cases that must still differ — and may only +shrink. The others have no ledger: each case asserts its result outright. | Corpus | Rust today | |---|---| | `registry-conformance` | byte-identical manifest | -| `conformance` (the metamodel corpus) | **578 of 578**, and the ledger is empty | +| `conformance` (the metamodel corpus) | **584 of 584**, 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 | @@ -282,7 +283,7 @@ outright. | `decimal-wire`, `duration-wire` | every vector, against the code the support crate carries | | `writer-conformance` | every `core` case of the code writer ([ADR-0063](../../spec/decisions/ADR-0063-generators-own-layout.md)) | | `generator-registry-conformance` | the shipped generators are exactly the registry's `rust` entries, with its tier and layer, and the eject contract's census, completeness and depth hold (ADR-0034 Amendment 8) | -| `render-conformance` | every case, byte-identical, through `metaobjects_render::render` (the Mustache engine underneath is `mustache-ng`) | +| `render-conformance` | every case but the three the ledger holds — `render-shadowed-dotted-prefix`, `render-list-length`, `render-zero-falsiness` (`mustache-ng` has its own name lookup, data model and truthiness); a ledgered case must still differ, the rest render byte-identical through `metaobjects_render::render` (the Mustache engine underneath is `mustache-ng`) | | `extract-conformance` | all 58 cases, through `metaobjects_render::extract::extract` | | `output-prompt-conformance` | all 17 cases in all three `@promptStyle` styles, with the extract round trip, through `metaobjects_render::prompt::render_output_format` | diff --git a/spec/roadmap.md b/spec/roadmap.md index e996724a35..e3a1a96f7b 100644 --- a/spec/roadmap.md +++ b/spec/roadmap.md @@ -161,7 +161,7 @@ under **Shipped**; planned FRs under **Planned** + the **Release plan**. ✅ shi | FR-041 | Public A/B drift benchmark — coding agents with vs without MetaObjects, pre-registered, friction-first | 📋 **design settled 2026-09-12, unbuilt** — the "proving the value" work; it is what licenses the claims FR-042 §4 withholds. Revised after an adversarial two-reviewer design review (spec §14): the scored task set is now held out from the friction pass (the draft tuned Arm B on the tasks it would later be scored on, with no symmetric loop for the control), Arm A is derived from Arm B's generated output so the seeds differ only in the model and the gate, `n` is calibrated from a pilot instead of asserted (one identical config measured 25/51/28 turns at temperature 0 — 41% CV), H2 is time-to-**correct** rather than time-to-done, the primary is analysed intention-to-treat so an arm cannot win by not finishing, and escaped defects are reported split by whether `meta verify` already covers the invariant class (it covers four of five, so H1 is partly definitional for those). First deliverable is the Phase 0b friction log. Design: `docs/superpowers/specs/2026-09-11-fr-041-drift-ab-benchmark-design.md` | 1.x | — | | FR-042 | First-touch positioning — one typed model, two verbs (README, llms, sites) | 🟢 shipped on the four first-touch surfaces — pitch **locked** 2026-09-12 (two verbs: Generate + Verify; requirements fold into Verify; H1 model-first), Verify clause amended 2026-09-14 to "fails or warns", six pillars carry maturity labels, do-not-say list gated in the `gates` lane. **Remaining:** the drift terminal recording for the .dev hero, and the drift-demo page its CTA should point at (spec §8). Design: `docs/superpowers/specs/2026-09-11-fr-042-first-touch-positioning-design.md` | — | — | | FR-043 | **Libraries** — reusable declared design: model metadata + the requirements that make it checkable (+ an implied generator selection), opted into by name | 🟢 **design approved 2026-09-13, un-deferred** — proposed as a SIXTH pillar. Not greenfield: `library/ai/llm-call.yaml` already ships one (opt-in via the loader's `libraries: ["ai"]`, embedded per port under an `embedded-library drift` gate, with `trace-helper` codegen beside it). Generalises it — requirements as a component, discovery through the codegen catalog's `kind: "library"`, declared package→generator coupling replacing `trace-helper`'s hard-coded `LlmCallBase`, `overlay: true` as the adaptation door and `meta eject` for repackaging. **No new metamodel vocabulary; `metamodelVersion` does not move.** Second library `iam` (users, typed nestable groups, roles as permission bundles, global and group-scoped grants) ships `stability: preview`; its model is verified to load clean under strict. Phase 2: third-party authoring over FR-023's deferred transports. Design: `docs/superpowers/specs/2026-09-13-fr-043-feature-and-nfr-packages-design.md` | 1.1 | — | -| FR-044 | **Core reporting** — declared measures, dimensions, segments and reports (compiled to SQL views in every port), plus Cube and dbt MetricFlow exporters | 🟢 **Plans 1–4 of 5 shipped on `main` (Plan 1 2026-10-03, Plan 2 2026-10-04, Plan 3 2026-10-05; Plan 4 with the Cube exporter)** — the vocabulary (`dimension.attribute`, `dimension.time`, `measure.aggregate`, `measure.ratio`, `segment.filter`, `object.report`, plus the relative-date filter value) is registered and loader-validated in all five ports, gated by 27 new conformance fixtures and the new `codegen-noop` corpus; decisions D1–D6 are settled. `metamodelVersion` reads **`1.2`** on `main` (`startOf` on relative dates; [reporting.md](../docs/features/reporting.md#compatibility) has the history). **Plan 2 lowered the view-backed report**: a report that declares a read-only `source.rdb @kind: view` becomes that view in `meta migrate` (Postgres / SQLite / D1; MySQL through `buildReportViews` + the recipe), every port's runtime reads it (six shared persistence scenarios, columns pinned by `report-shapes.json`), C# generates a keyless EF Core row and Kotlin an Exposed table object. **Plan 3 served it**: every port's generators write a read-only list route (filter, sort and paging on the derived fields, `POST` answers 405, no `/{id}`), gated by the api-contract `report/` sub-corpus, with a docs page for each served report and, in TypeScript, the list hook. **Plan 4 added the Cube exporter**: the TypeScript reference generator `cube-model` writes the vocabulary as Cube data-model files (a cube per entity, joins, dimensions, measures, segments and a rollup per served report), gated by the 44-case `fixtures/cube-model/` corpus and a `cube` lane that loads the output into a real Cube and compares each report's Cube query with its view. **The zero-rows / measure-defaults build** (`2026-10-09-fr-044-zero-rows-and-measure-defaults.md`, #415) added `@spine` (rows from a dimension's entity) and an integer `@default` on a measure, in all five ports, and the exporter maps both: a `@spine` report is a Cube view over a scoped facts cube, a defaulted measure a `COALESCE`. **Still to come:** Plan 5, the `reporting` library; the dbt MetricFlow exporter, built on first adopter demand (D5); `measure.derived` stays unregistered until FR-037 R5. A query-time engine remains parked with its re-entry trigger. Feature docs: `docs/features/reporting.md`, `docs/features/cube-export.md`. Design: `docs/superpowers/specs/2026-10-02-fr-044-core-reporting-design.md` | 1.1 | [#391](https://github.com/metaobjectsdev/metaobjects/issues/391) | +| FR-044 | **Core reporting** — declared measures, dimensions, segments and reports (compiled to SQL views in every port), plus Cube and dbt MetricFlow exporters | 🟢 **Plans 1–4 of 5 shipped on `main` (Plan 1 2026-10-03, Plan 2 2026-10-04, Plan 3 2026-10-05; Plan 4 with the Cube exporter)** — the vocabulary (`dimension.attribute`, `dimension.time`, `measure.aggregate`, `measure.ratio`, `segment.filter`, `object.report`, plus the relative-date filter value) is registered and loader-validated in all five ports, gated by 27 new conformance fixtures and the new `codegen-noop` corpus; decisions D1–D6 are settled. `metamodelVersion` reads **`1.2`** on `main` (`startOf` on relative dates; [reporting.md](../docs/features/reporting.md#compatibility) has the history). **Plan 2 lowered the view-backed report**: a report that declares a read-only `source.rdb @kind: view` becomes that view in `meta migrate` (Postgres / SQLite / D1; MySQL through `buildReportViews` + the recipe), every port's runtime reads it (six shared persistence scenarios, columns pinned by `report-shapes.json`), C# generates a keyless EF Core row and Kotlin an Exposed table object. **Plan 3 served it**: every port's generators write a read-only list route (filter, sort and paging on the derived fields, `POST` answers 405, no `/{id}`), gated by the api-contract `report/` sub-corpus, with a docs page for each served report and, in TypeScript, the list hook. **Plan 4 added the Cube exporter**: the TypeScript reference generator `cube-model` writes the vocabulary as Cube data-model files (a cube per entity, joins, dimensions, measures, segments and a rollup per served report), gated by the 44-case `fixtures/cube-model/` corpus and a `cube` lane that loads the output into a real Cube and compares each report's Cube query with its view. **The zero-rows / measure-defaults build** (`2026-10-09-fr-044-zero-rows-and-measure-defaults.md`, #415) added `@spine` (rows from a dimension's entity) and an integer `@default` on a measure, in all five ports, and the exporter maps both: a `@spine` report is a Cube view over a scoped facts cube, a defaulted measure a `COALESCE`. **Still to come:** Plan 5, the `reporting` library; the dbt MetricFlow exporter, built on first adopter demand (D5). A query-time engine remains parked with its re-entry trigger. Feature docs: `docs/features/reporting.md`, `docs/features/cube-export.md`. Design: `docs/superpowers/specs/2026-10-02-fr-044-core-reporting-design.md` | 1.1 | [#391](https://github.com/metaobjectsdev/metaobjects/issues/391) | _(FR-001 was the original metamodel foundation — pre-dates the FR-numbered tracking.)_ _(FR-032 was developed under the working number "FR-026" — see commit history; renumbered to avoid the FR-026=Forms collision. Design: `docs/superpowers/specs/2026-06-13-fr-032-canonical-fqn-refs-design.md`, ADR-0032.)_