From 521b1c140d4203e9dbf9fe27b4944267aac647c6 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Mon, 2 Nov 2026 06:47:57 -0500 Subject: [PATCH 01/51] fix(metadata): resolve bare root-level @objectRef in Java loader (#525) * fix(metadata): root-level node resolves a bare @objectRef in its own package (#522); one bump rule for a new attribute (#523) * chore(site): refresh payload fixture count --- AGENTS.md | 2 +- CHANGELOG.md | 8 +++ docs/1.0-readiness.md | 2 +- docs/CONFORMANCE.md | 6 +-- docs/RELEASING.md | 2 +- examples/showcase/site-payload.json | 2 +- .../expected-errors.json | 15 ++++++ .../input/meta.json | 14 +++++ .../providers.json | 1 + .../expected.json | 51 +++++++++++++++++++ .../input/meta.json | 32 ++++++++++++ .../providers.json | 1 + .../validation/RegisteredValidation.java | 10 +++- 13 files changed, 137 insertions(+), 9 deletions(-) create mode 100644 fixtures/conformance/error-root-level-field-objectref-unresolved/expected-errors.json create mode 100644 fixtures/conformance/error-root-level-field-objectref-unresolved/input/meta.json create mode 100644 fixtures/conformance/error-root-level-field-objectref-unresolved/providers.json create mode 100644 fixtures/conformance/root-level-field-object-bare-ref/expected.json create mode 100644 fixtures/conformance/root-level-field-object-bare-ref/input/meta.json create mode 100644 fixtures/conformance/root-level-field-object-bare-ref/providers.json diff --git a/AGENTS.md b/AGENTS.md index 1ce9781050..31c4c7fa80 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,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/` (421 fixtures; 35 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/` (423 fixtures; 35 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 3631b5903c..b7b19f608f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,14 @@ here.** It now generates `tags: list[str] = []`, from the same four spellings TypeScript accepts, or from a native YAML list such as `default: [a, b]`. A default Python cannot spell as a list is left to the database. +- **Java: a bare `@objectRef` on a field declared directly under `metadata.root` now resolves.** + A root-level `field.object` (the reusable template other fields `extends`) with + `@objectRef: "Address"` failed to load in Java even when `Address` sat in the same package, + while TypeScript loaded it. A root-level node now resolves a bare reference in its own + package, as ADR-0042 specifies, and a real miss still fails with `ERR_UNRESOLVED_OBJECT_REF`. + The error no longer names the loader as the owner of a root-level node. Two new conformance + fixtures (`root-level-field-object-bare-ref`, `error-root-level-field-objectref-unresolved`) + hold every port to it; C#, Python and TypeScript already passed. ## [1.2.0] — 2026-10-30 diff --git a/docs/1.0-readiness.md b/docs/1.0-readiness.md index ced552c54c..b54be142ed 100644 --- a/docs/1.0-readiness.md +++ b/docs/1.0-readiness.md @@ -117,7 +117,7 @@ Status legend: ✅ done · 🔶 in progress · ⬜ not started · ❓ **[RATIFY] (attribute ⇒ PATCH, top-level type ⇒ MINOR, subtype ⇒ PATCH when inert), and Amendment 2 separates the package and metamodel axes. Trigger is *new public surface, not code size*: package **MINOR** only for newly-dependable - surface (codegen output, CLI flag, a newly-supported vocab member); package **PATCH** + surface (codegen-engine surface, CLI flag, a new top-level type); package **PATCH** for bugfix/refactor; the **Metamodel spec version** bumps only on a shared vocabulary/wire change. The fast `7.3→7.7` minor run was breaking *velocity*; decouple + this rule ends the churn. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 73b8182683..d7e9157567 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 421 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 423 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -285,7 +285,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (421) +### `fixtures/conformance/` — metamodel loader + canonical serializer (423) | Fixture prefix | Feature doc | |---|---| @@ -611,7 +611,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 421 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 423 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 4a8f6df227..5006db9ed3 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -266,7 +266,7 @@ what they render is generator output and does not.) | Codegen **ENGINE** public surface **additive** (new `render*` primitive, new `GenContext` field, optional param) | new `render*` primitive | PATCH (MINOR if it headlines a feature release) | MINOR | | Codegen **ENGINE** public surface **breaking**, or changed **CLI semantics** | `relativeModuleSpecifier` +required param | **MINOR** | MAJOR | | A **runtime library**'s public surface (`runtime-ts`, `render`, OMDB, ObjectManager, web client) — additive / breaking | a new mount option / a removed export | PATCH / **MINOR** | MINOR / MAJOR | -| New **attribute** on an existing type/subtype | `@intValueMap`, `@lenient`, `@maxTokens` | **PATCH** | MINOR | +| New **attribute** on an existing type/subtype | `@intValueMap`, `@lenient`, `@maxTokens` | **PATCH** | **PATCH** | | New **subtype** of an existing type | `field.uri`, `index.lookup`, `attr.intMap` | **PATCH** when inert (see the vocabulary rule below); **MINOR** when it changes existing metadata's meaning/output, narrows something previously permitted, or headlines a feature | MINOR | | New top-level metadata **type** | `requirement.*`, `index.*`, `api.*` | **MINOR** | MINOR | | **Breaking** metamodel-vocabulary change (retire an attr/subtype/type; narrow what is permitted) | FR-037 `@readOnly`, FR-038 `@verifiedBy`, ADR-0052 `@promptStyle` re-homing | **MINOR** (pre-1.0 MINOR *is* the breaking slot) | **`metamodelVersion` MAJOR**, package MINOR (ADR-0035 Am. 2) | diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 82e51fcbdd..6e9ec3f63d 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.2" }, "counts": { - "fixtures": 421, + "fixtures": 423, "corpora": 35, "baseTypes": 17 }, diff --git a/fixtures/conformance/error-root-level-field-objectref-unresolved/expected-errors.json b/fixtures/conformance/error-root-level-field-objectref-unresolved/expected-errors.json new file mode 100644 index 0000000000..3c510ca24d --- /dev/null +++ b/fixtures/conformance/error-root-level-field-objectref-unresolved/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_UNRESOLVED_OBJECT_REF", + "source": { + "format": "json", + "files": [ + "meta.json" + ], + "jsonPath": "$['metadata.root'].children[0]['field.object']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-root-level-field-objectref-unresolved/input/meta.json b/fixtures/conformance/error-root-level-field-objectref-unresolved/input/meta.json new file mode 100644 index 0000000000..e0afebb868 --- /dev/null +++ b/fixtures/conformance/error-root-level-field-objectref-unresolved/input/meta.json @@ -0,0 +1,14 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "field.object": { + "name": "AddrTemplate", + "abstract": true, + "@objectRef": "Missing" + } + } + ] + } +} diff --git a/fixtures/conformance/error-root-level-field-objectref-unresolved/providers.json b/fixtures/conformance/error-root-level-field-objectref-unresolved/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-root-level-field-objectref-unresolved/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/root-level-field-object-bare-ref/expected.json b/fixtures/conformance/root-level-field-object-bare-ref/expected.json new file mode 100644 index 0000000000..b8f056a7c3 --- /dev/null +++ b/fixtures/conformance/root-level-field-object-bare-ref/expected.json @@ -0,0 +1,51 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.value": { + "name": "Address", + "children": [ + { + "field.string": { + "name": "street" + } + }, + { + "field.string": { + "name": "city" + } + } + ] + } + }, + { + "field.object": { + "name": "AddrTemplate", + "package": "acme::shop", + "abstract": true, + "@objectRef": "acme::shop::Address" + } + }, + { + "object.value": { + "name": "Contact", + "children": [ + { + "field.string": { + "name": "name" + } + }, + { + "field.object": { + "name": "billing", + "extends": "acme::shop::AddrTemplate" + } + } + ] + } + } + ] + } +} + diff --git a/fixtures/conformance/root-level-field-object-bare-ref/input/meta.json b/fixtures/conformance/root-level-field-object-bare-ref/input/meta.json new file mode 100644 index 0000000000..39fbb18e57 --- /dev/null +++ b/fixtures/conformance/root-level-field-object-bare-ref/input/meta.json @@ -0,0 +1,32 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.value": { + "name": "Address", + "children": [ + { "field.string": { "name": "street" } }, + { "field.string": { "name": "city" } } + ] + } + }, + { + "field.object": { + "name": "AddrTemplate", + "abstract": true, + "@objectRef": "Address" + } + }, + { + "object.value": { + "name": "Contact", + "children": [ + { "field.string": { "name": "name" } }, + { "field.object": { "name": "billing", "extends": "AddrTemplate" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/root-level-field-object-bare-ref/providers.json b/fixtures/conformance/root-level-field-object-bare-ref/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/root-level-field-object-bare-ref/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java index 99cf268c8c..c9656f581c 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java @@ -40,7 +40,10 @@ private static void walk(MetaData node, MetaDataRegistry registry, ValidationCon // BARE refs against it. Nested nodes carry no package of their own, so they inherit the // enclosing object's. Mirrors TS validation-registry.ts. String pkg = referrerPkg; - if (node instanceof MetaObject) { + // A root-level node of any type (e.g. an abstract field.object template that other + // fields extend) is a top-level declaration too: it carries its own package and its + // bare refs resolve in it, not against the empty context. + if (node instanceof MetaObject || node.getParent() instanceof MetaRoot) { String p = node.getPackage(); pkg = (p != null && !p.isEmpty()) ? p : referrerPkg; } @@ -64,7 +67,10 @@ private static void walk(MetaData node, MetaDataRegistry registry, ValidationCon MetaObject target = ctx.symbols().resolveObject(entityRef, pkg); // Qualify the node name with its owning entity (e.g. "Order.items") so the // error is locatable from the message alone, not just the source envelope. - String qname = (node.getParent() != null && node.getParent().getShortName() != null + // A root-level node has no owning entity: the parent is the loader/root, whose + // name must not be printed as an owner. + String qname = (node.getParent() != null && !(node.getParent() instanceof MetaRoot) + && node.getParent().getShortName() != null && !node.getParent().getShortName().isEmpty()) ? node.getParent().getShortName() + "." + node.getShortName() : node.getShortName(); From 27cfc4bf55ad0be5bc0b6d707070802be37256b8 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Mon, 2 Nov 2026 10:42:49 -0500 Subject: [PATCH 02/51] fix(migrate-ts): block unowned view column drops and restore SQLite drop-column rollback (#526) * fix(migrate): refuse a column drop under an unowned view; SQLite down re-adds the column A live view the tool does not own (@unmanaged, or outside the scoped schemas) that still reads a dropped column now blocks the drop at plan time, naming the view (--allow drop-column-read-by-view to proceed). The SQLite/D1 down for drop-column re-adds the column instead of writing a TODO. Docs note: edit an @sql body when removing a column it reads. * no-mistakes(review): Omit non-constant defaults in SQLite drop-column rollback * no-mistakes(test): Block drop-column read by unowned or hand-made views * no-mistakes(test): Fix allow-hint test typecheck; unowned-view block verified live * no-mistakes(document): Docs current; SQLite rollback default omission documented in migrations-and-drift.md. --- CHANGELOG.md | 16 ++ .../references/read-views-and-projections.md | 7 + docs/features/migrations-and-drift.md | 22 +++ .../references/read-views-and-projections.md | 7 + .../references/read-views-and-projections.md | 7 + .../references/read-views-and-projections.md | 7 + .../references/read-views-and-projections.md | 7 + .../references/read-views-and-projections.md | 7 + server/typescript/packages/cli/README.md | 2 +- .../packages/cli/src/commands/migrate.ts | 2 +- server/typescript/packages/cli/src/index.ts | 2 +- .../typescript/packages/cli/src/lib/allow.ts | 7 +- .../typescript/packages/cli/src/lib/args.ts | 4 + .../cli/test/__snapshots__/cli.test.ts.snap | 2 +- .../cli/test/allow-hint-tokens.test.ts | 15 ++ .../test/drop-column-view-pg.test.ts | 116 +++++++++++++++ .../test/drop-column-view-sqlite.test.ts | 138 ++++++++++++++++++ .../packages/migrate-ts/src/diff/index.ts | 38 +++++ .../packages/migrate-ts/src/diff/status.ts | 14 +- .../packages/migrate-ts/src/emit/sqlite.ts | 29 +++- .../packages/migrate-ts/src/types.ts | 18 ++- .../test/drop-column-unowned-view.test.ts | 138 ++++++++++++++++++ server/typescript/packages/sdk/src/config.ts | 1 + 23 files changed, 597 insertions(+), 9 deletions(-) create mode 100644 server/typescript/packages/integration-tests/test/drop-column-view-pg.test.ts create mode 100644 server/typescript/packages/integration-tests/test/drop-column-view-sqlite.test.ts create mode 100644 server/typescript/packages/migrate-ts/test/drop-column-unowned-view.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index b7b19f608f..8b13247ac0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,22 @@ here.** ## [Unreleased] +### Fixed + +- **`meta migrate` refuses, at plan time, to drop a column a view it does not own still reads.** + With `--from-db`, a declared-`@unmanaged` view or one outside the scoped schemas whose live body + names the dropped column now blocks the `drop-column`, and the message names the view and the + column. Before, the migration was written and failed at apply on both Postgres (`cannot drop + column … other objects depend on it`) and SQLite (`error in view … after drop column`). A view with + no recorded body is not matched, and an offline run cannot see live views. Pass + `--allow drop-column-read-by-view` (config token `drop-column-read-by-view`) to proceed. +- **The SQLite and D1 down migration for `drop-column` re-adds the column.** It wrote a TODO comment + and still recreated the view with the old SQL, so the view failed with `no such column` after a + rollback. It now runs `ADD COLUMN` from the recorded column, as Postgres does; the data is not + restored, and a `NOT NULL` column with no default comes back nullable, which is all SQLite allows. +- **Docs: edit an `@sql` body when you remove a column it reads.** The tool never parses the body; + Postgres fails at apply and SQLite applies and leaves a broken view. + ### Added - **Contract emitters: JSON Schema and OpenAPI generators (FR-022).** `jsonSchemaFile()` diff --git a/agent-context/skills/metaobjects-authoring/references/read-views-and-projections.md b/agent-context/skills/metaobjects-authoring/references/read-views-and-projections.md index c58b0e5adc..06d2ccf2e8 100644 --- a/agent-context/skills/metaobjects-authoring/references/read-views-and-projections.md +++ b/agent-context/skills/metaobjects-authoring/references/read-views-and-projections.md @@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo - Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc / tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`). +**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never +parses an `@sql` body, so it cannot see that the body still names the column. The migration +is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it +applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten +either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads +and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first. + **A `passthrough` field must match its `@from` source's type.** A passthrough forwards the source value unchanged, so the projection field's `field.` and array-ness must be identical to the source field's — a `field.uuid` source diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 790692ea09..7e38e0aea7 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -632,6 +632,28 @@ migrate` never creates, drops, or drift-checks it, and `meta verify --db` report *external (declared)*. The two are mutually exclusive. See [ADR-0043](../../spec/decisions/ADR-0043-ddl-ownership-escape-valves.md). +**Removing a column a view reads.** For a view the tool derives, `meta migrate` finds the +views that read the column and drops and recreates them around the change. Two kinds of view +are not rewritten, so you edit them yourself: + +- **An `@sql` body.** The tool never parses it, so it cannot know the body still names a + column you removed. **Edit the body in the same change that removes the column.** Left + alone, the migration is still written. On Postgres it then fails at apply with `column + "…" does not exist`. On SQLite it applies and leaves a view that errors when queried. +- **An `@unmanaged` view, or a hand-made one.** With `--from-db`, `meta migrate` reads the + live view bodies. If one it does not own names the column the plan drops, the drop is + blocked at plan time and the message names the view and the column; otherwise Postgres + fails at apply (`cannot drop column … because other objects depend on it`) and SQLite + fails with `error in view … after drop column`. Change the view first, or pass `--allow + drop-column-read-by-view` to proceed anyway. A view with no recorded body cannot be + matched, and an offline run (no database) cannot see live views, so neither is checked. + +A rollback of a dropped column re-adds it on every engine, with its type, but the data is +not restored. On SQLite a column that was `NOT NULL` with no default comes back nullable, +because SQLite cannot add it any other way. SQLite also cannot add a column with an +expression default (or a `uuid` identity default) to a populated table, so the rollback +omits that default and says so in a `NOTE`. + ## Verified by The following conformance fixtures gate this feature's behavior across ports: diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md index c58b0e5adc..06d2ccf2e8 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md @@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo - Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc / tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`). +**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never +parses an `@sql` body, so it cannot see that the body still names the column. The migration +is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it +applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten +either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads +and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first. + **A `passthrough` field must match its `@from` source's type.** A passthrough forwards the source value unchanged, so the projection field's `field.` and array-ness must be identical to the source field's — a `field.uuid` source diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md index c58b0e5adc..06d2ccf2e8 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md @@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo - Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc / tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`). +**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never +parses an `@sql` body, so it cannot see that the body still names the column. The migration +is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it +applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten +either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads +and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first. + **A `passthrough` field must match its `@from` source's type.** A passthrough forwards the source value unchanged, so the projection field's `field.` and array-ness must be identical to the source field's — a `field.uuid` source diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md index c58b0e5adc..06d2ccf2e8 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md @@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo - Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc / tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`). +**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never +parses an `@sql` body, so it cannot see that the body still names the column. The migration +is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it +applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten +either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads +and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first. + **A `passthrough` field must match its `@from` source's type.** A passthrough forwards the source value unchanged, so the projection field's `field.` and array-ness must be identical to the source field's — a `field.uuid` source diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md index c58b0e5adc..06d2ccf2e8 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md @@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo - Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc / tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`). +**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never +parses an `@sql` body, so it cannot see that the body still names the column. The migration +is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it +applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten +either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads +and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first. + **A `passthrough` field must match its `@from` source's type.** A passthrough forwards the source value unchanged, so the projection field's `field.` and array-ness must be identical to the source field's — a `field.uuid` source diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md index c58b0e5adc..06d2ccf2e8 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md @@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo - Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc / tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`). +**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never +parses an `@sql` body, so it cannot see that the body still names the column. The migration +is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it +applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten +either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads +and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first. + **A `passthrough` field must match its `@from` source's type.** A passthrough forwards the source value unchanged, so the projection field's `field.` and array-ness must be identical to the source field's — a `field.uuid` source diff --git a/server/typescript/packages/cli/README.md b/server/typescript/packages/cli/README.md index cae4c2ba87..25e779ad6d 100644 --- a/server/typescript/packages/cli/README.md +++ b/server/typescript/packages/cli/README.md @@ -176,7 +176,7 @@ Flags: - `--shadow-db ` — Postgres scratch database the expected schema is applied to for `--from-db` / `--apply` drift (also `SHADOW_DATABASE_URL` or `migrate.shadowDatabaseUrl`). Read [How CHECK constraints and expression indexes are compared](../../../../docs/features/migrations-and-drift.md#how-check-constraints-and-expression-indexes-are-compared) for the three paths. - `--out-dir ` (default `./.metaobjects/migrations`) - `--slug ` — required when changes are pending (e.g., `add-user-shipping`) -- `--allow ` — destructive-change permissions: `drop-column,drop-table,type-change,drop-index,drop-fk,drop-check,drop-view,drop-view-cascade,adopt-view,nullable-to-not-null,drop-identity-default,drop-unmanaged,drop-comment` +- `--allow ` — destructive-change permissions: `drop-column,drop-table,type-change,drop-index,drop-fk,drop-check,drop-view,drop-view-cascade,drop-column-read-by-view,adopt-view,nullable-to-not-null,drop-identity-default,drop-unmanaged,drop-comment` - `--on-ambiguous abort|rename|drop-add` (default `abort`) — non-interactive - `--rename-table [schema.]old=new` / `--rename-column [schema.]table.old=new` — declare a rename (repeatable), so the migration is `RENAME` instead of drop+add whatever the rename heuristic makes of the names. Refused if nothing matches. See [Renames and populated tables](../../../../docs/features/migrations-and-drift.md#renames-and-populated-tables). - `--dry-run` — print the SQL pair, write nothing (under `--format json|toon` the pair is the document's `sql` field, so stdout stays one parseable document) diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts index ae661808de..a5d8bc30da 100644 --- a/server/typescript/packages/cli/src/commands/migrate.ts +++ b/server/typescript/packages/cli/src/commands/migrate.ts @@ -120,7 +120,7 @@ MIGRATE FLAGS: --slug Required to WRITE a migration (not for --dry-run) (e.g., --slug add-user-shipping) --allow Comma-separated destructive-change permissions: drop-column,drop-table,type-change,drop-index,drop-fk, - drop-check,drop-view,drop-view-cascade, + drop-check,drop-view,drop-view-cascade,drop-column-read-by-view, adopt-view,nullable-to-not-null,drop-identity-default, drop-unmanaged,drop-comment drop-column DELETES the column and every value in it. If diff --git a/server/typescript/packages/cli/src/index.ts b/server/typescript/packages/cli/src/index.ts index a294da47d0..d63cc68585 100644 --- a/server/typescript/packages/cli/src/index.ts +++ b/server/typescript/packages/cli/src/index.ts @@ -176,7 +176,7 @@ MIGRATE FLAGS: --slug Required when changes are present (e.g., add-user-shipping) --allow Comma-separated destructive-change permissions: drop-column,drop-table,type-change,drop-index,drop-fk, - drop-check,drop-view,drop-view-cascade, + drop-check,drop-view,drop-view-cascade,drop-column-read-by-view, adopt-view,nullable-to-not-null,drop-identity-default, drop-comment,drop-unmanaged drop-column DELETES the column's data; for a renamed diff --git a/server/typescript/packages/cli/src/lib/allow.ts b/server/typescript/packages/cli/src/lib/allow.ts index f1a7bc7c88..a6db944138 100644 --- a/server/typescript/packages/cli/src/lib/allow.ts +++ b/server/typescript/packages/cli/src/lib/allow.ts @@ -27,6 +27,8 @@ export const ALLOW_TOKEN_MAP: Record = { "drop-view": "dropView", // Gates DROP VIEW ... CASCADE. Additional to drop-view, never implied by it. "drop-view-cascade": "dropViewCascade", + // Gates dropping a column a view this tool does not own still reads. + "drop-column-read-by-view": "dropColumnReadByView", // Gates overwriting an unfingerprinted (hand-written or pre-fingerprint) view. "adopt-view": "adoptView", "nullable-to-not-null": "nullableToNotNull", @@ -66,7 +68,10 @@ export function describeChange(c: Change): string { case "drop-table": return c.table; case "rename-table": return `${c.from} → ${c.to}`; case "add-column": return `${c.table}.${c.column.name}`; - case "drop-column": return `${c.table}.${c.column}`; + case "drop-column": + return c.readBy === undefined || c.readBy.length === 0 + ? `${c.table}.${c.column}` + : `${c.table}.${c.column} (read by view ${c.readBy.join(", ")})`; case "rename-column": return `${c.table}.${c.from} → ${c.table}.${c.to}`; case "change-column-type": { // A type change carries its column's default change, so the default is reported here. diff --git a/server/typescript/packages/cli/src/lib/args.ts b/server/typescript/packages/cli/src/lib/args.ts index 0280813a89..7155271048 100644 --- a/server/typescript/packages/cli/src/lib/args.ts +++ b/server/typescript/packages/cli/src/lib/args.ts @@ -314,6 +314,10 @@ export const ALLOW_TOKENS = [ // views and materialized views owned by OTHER applications, which this tool // neither manages nor can restore. `--allow drop-view` alone never cascades. "drop-view-cascade", + // drop-column-read-by-view permits dropping a column that a live view this tool + // does not own (`@unmanaged`, or outside the scoped schemas) still reads. The tool + // never rewrites such a view, so without this `migrate` refuses at plan time. + "drop-column-read-by-view", // adopt-view permits overwriting an existing view that carries no MetaObjects // fingerprint — i.e. taking ownership of a hand-written view, or of one created // before fingerprinting existed. Every environment upgrading from an older diff --git a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap index 06921804fb..6e8edb3474 100644 --- a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap +++ b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap @@ -156,7 +156,7 @@ MIGRATE FLAGS: --slug Required when changes are present (e.g., add-user-shipping) --allow Comma-separated destructive-change permissions: drop-column,drop-table,type-change,drop-index,drop-fk, - drop-check,drop-view,drop-view-cascade, + drop-check,drop-view,drop-view-cascade,drop-column-read-by-view, adopt-view,nullable-to-not-null,drop-identity-default, drop-comment,drop-unmanaged drop-column DELETES the column's data; for a renamed diff --git a/server/typescript/packages/cli/test/allow-hint-tokens.test.ts b/server/typescript/packages/cli/test/allow-hint-tokens.test.ts index f0c9cf94af..2213ab9f06 100644 --- a/server/typescript/packages/cli/test/allow-hint-tokens.test.ts +++ b/server/typescript/packages/cli/test/allow-hint-tokens.test.ts @@ -142,3 +142,18 @@ describe("following the hints unblocks the change", () => { expect(await blocked(scenario, ["drop-view-cascade", "adopt-view"])).toEqual([]); }); }); + +describe("a drop-column held by a view the tool does not own", () => { + test("the blocked entry names the view that reads the column", async () => { + const r = await diff({ + expected: snap([T({ columns: [T().columns[0]!] })]), + actual: snap([T()], [{ name: "v_hand", sql: "SELECT id, label FROM t" }]), + dialect: "sqlite", + allow: { dropColumn: true }, + }); + const entries = blockedEntriesFor(r.blocked, r.changes); + const entry = entries.find((e) => e.kind === "drop-column"); + expect(entry?.description).toBe("t.label (read by view v_hand)"); + expect(entry?.allowFlag).toBe("drop-column-read-by-view"); + }); +}); diff --git a/server/typescript/packages/integration-tests/test/drop-column-view-pg.test.ts b/server/typescript/packages/integration-tests/test/drop-column-view-pg.test.ts new file mode 100644 index 0000000000..a56de0d046 --- /dev/null +++ b/server/typescript/packages/integration-tests/test/drop-column-view-pg.test.ts @@ -0,0 +1,116 @@ +/** + * Dropping a column under a view the tool does not own, against a real Postgres. + * + * An `@unmanaged` view that still reads the dropped column is refused at plan time and + * named (Postgres otherwise fails at apply: "cannot drop column … other objects depend on + * it"); one that does not read it is not blocked, and applies. + */ +import { splitSqlStatements } from "@metaobjectsdev/migrate-ts"; +import { describe, test, expect, beforeAll, afterAll, beforeEach } from "bun:test"; +import { + buildExpectedSchema, collectUnmanagedNames, diff, emit, introspectPostgres, postgresViewReplaceProbe, + type AllowOptions, +} from "@metaobjectsdev/migrate-ts"; +import { buildProjectionViews } from "@metaobjectsdev/codegen-ts"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { Kysely, PostgresDialect, sql } from "kysely"; +import { Pool } from "pg"; +import { startPostgres, type RunningPg } from "../src/postgres-container.ts"; + +function literalColumns(root: T): T { + (root as unknown as { physicalNaming: unknown }).physicalNaming = { columns: "literal", tables: "snake_case" }; + return root; +} + +const NICKNAME = `{ "field.string": { "name": "nickname" } }`; +const NICKNAME_VIEW = `{ "field.string": { "name": "nickname", "extends": "Account.nickname" } }`; + +function meta(withNickname: boolean, extra: string[] = []): string { + return `{ "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Account", "children": [ + { "source.rdb": { "@table": "accounts" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "name" } }, + ${withNickname ? NICKNAME + "," : ""} + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } + ] } }, + { "object.projection": { "name": "AccountView", "children": [ + { "source.rdb": { "@kind": "view", "@table": "v_account" } }, + { "identity.primary": { "name": "id", "extends": "Account.id", "@fields": "id" } }, + { "field.long": { "name": "id", "extends": "Account.id" } }, + { "field.string": { "name": "name", "extends": "Account.name" } } + ${withNickname ? "," + NICKNAME_VIEW : ""} + ] } } + ${extra.map((e) => "," + e).join("\n")} + ] } }`; +} + +// A view declared @unmanaged: someone else owns its DDL, so migrate never rewrites it. +const UNMANAGED_VIEW = `{ "object.projection": { "name": "HandView", "children": [ + { "source.rdb": { "@kind": "view", "@table": "v_hand", "@unmanaged": true } }, + { "identity.primary": { "name": "id", "extends": "Account.id", "@fields": "id" } }, + { "field.long": { "name": "id", "extends": "Account.id" } } +] } }`; + +let pg: RunningPg; +let k: Kysely>; + +beforeAll(async () => { + pg = await startPostgres(); + k = new Kysely>({ + dialect: new PostgresDialect({ pool: new Pool({ connectionString: pg.connectionUri }) }), + }); +}, 120_000); +afterAll(async () => { + await k.destroy(); + await pg.stop(); +}, 60_000); +beforeEach(async () => { + await sql.raw("DROP SCHEMA public CASCADE").execute(k); + await sql.raw("CREATE SCHEMA public").execute(k); +}); + +async function applyRaw(text: string): Promise { + for (const stmt of splitSqlStatements(text)) await sql.raw(stmt.endsWith(";") ? stmt : `${stmt};`).execute(k); +} + +async function migrate(metaJson: string, allow: AllowOptions = {}) { + const root = (await new MetaDataLoader().load([new InMemoryStringSource(metaJson)])).root; + const expected = buildExpectedSchema(literalColumns(root), { + views: buildProjectionViews(literalColumns(root), { dialect: "postgres" }), + }); + const result = await diff({ + expected, actual: await introspectPostgres(k), dialect: "postgres", + viewReplaceProbe: postgresViewReplaceProbe(k), allow, unmanagedNames: collectUnmanagedNames(root), + }); + const emittable = result.changes.filter((c) => c.status.state !== "blocked"); + const out = emittable.length === 0 ? { up: "", down: "" } : emit(emittable, { dialect: "postgres" }); + if (result.blocked.length === 0 && out.up.trim().length > 0) await applyRaw(out.up); + return { result, ...out }; +} + +describe("drop-column under a view the tool does not own — real Postgres", () => { + test("an unmanaged view that reads the dropped column is blocked and named; the DB is untouched", async () => { + await migrate(meta(true, [UNMANAGED_VIEW])); + await sql.raw(`CREATE VIEW "v_hand" AS SELECT "id", "nickname" FROM "accounts"`).execute(k); + + const { result } = await migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true }); + const blocked = result.blocked.find((c) => c.kind === "drop-column"); + expect(blocked?.status).toMatchObject({ state: "blocked", blockedBy: "dropColumnReadByView" }); + expect(blocked?.status.blockedReason).toContain("v_hand"); + expect(blocked?.status.blockedReason).toContain("accounts.nickname"); + + // The plan it refused is the one Postgres fails at apply. + await expect(migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true, dropColumnReadByView: true })) + .rejects.toThrow(/depend on it/); + }, 60_000); + + test("an unmanaged view that does not read the dropped column is not blocked", async () => { + await migrate(meta(true, [UNMANAGED_VIEW])); + await sql.raw(`CREATE VIEW "v_hand" AS SELECT "id", "name" FROM "accounts"`).execute(k); + + const { result } = await migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true }); + expect(result.blocked).toEqual([]); + await sql.raw(`SELECT * FROM "v_hand"`).execute(k); + }, 60_000); +}); diff --git a/server/typescript/packages/integration-tests/test/drop-column-view-sqlite.test.ts b/server/typescript/packages/integration-tests/test/drop-column-view-sqlite.test.ts new file mode 100644 index 0000000000..3d41581b3b --- /dev/null +++ b/server/typescript/packages/integration-tests/test/drop-column-view-sqlite.test.ts @@ -0,0 +1,138 @@ +/** + * Dropping a column under a view, against a real SQLite. + * + * - A view the tool does not own (`@unmanaged`) that still reads the dropped column is + * refused at plan time and named; one that does not read it is not. + * - The down of a `drop-column` re-adds the column, so rolling back leaves the managed view + * the migration dropped and recreated queryable again. (D1 renders through the same path.) + */ +import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Kysely, sql } from "kysely"; +import { LibsqlDialect } from "@libsql/kysely-libsql"; +import { + buildExpectedSchema, collectUnmanagedNames, diff, emit, introspectSqlite, type AllowOptions, +} from "@metaobjectsdev/migrate-ts"; +import { buildProjectionViews } from "@metaobjectsdev/codegen-ts"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; + +function literalColumns(root: T): T { + (root as unknown as { physicalNaming: unknown }).physicalNaming = { columns: "literal", tables: "snake_case" }; + return root; +} + +const TIMEOUT_MS = 60_000; +const NICKNAME = `{ "field.string": { "name": "nickname" } }`; +const NICKNAME_VIEW = `{ "field.string": { "name": "nickname", "extends": "Account.nickname" } }`; + +function meta(withNickname: boolean, extra: string[] = []): string { + return `{ "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Account", "children": [ + { "source.rdb": { "@table": "accounts" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "name" } }, + ${withNickname ? NICKNAME + "," : ""} + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } + ] } }, + { "object.projection": { "name": "AccountView", "children": [ + { "source.rdb": { "@kind": "view", "@table": "v_account" } }, + { "identity.primary": { "name": "id", "extends": "Account.id", "@fields": "id" } }, + { "field.long": { "name": "id", "extends": "Account.id" } }, + { "field.string": { "name": "name", "extends": "Account.name" } } + ${withNickname ? "," + NICKNAME_VIEW : ""} + ] } } + ${extra.map((e) => "," + e).join("\n")} + ] } }`; +} + +// A view declared @unmanaged: someone else owns its DDL, so migrate never rewrites it. +const UNMANAGED_VIEW = `{ "object.projection": { "name": "HandView", "children": [ + { "source.rdb": { "@kind": "view", "@table": "v_hand", "@unmanaged": true } }, + { "identity.primary": { "name": "id", "extends": "Account.id", "@fields": "id" } }, + { "field.long": { "name": "id", "extends": "Account.id" } } +] } }`; + +let tmpDir: string; +let k: Kysely>; + +beforeEach(() => { + tmpDir = mkdtempSync(join(tmpdir(), "drop-column-view-sqlite-")); + k = new Kysely({ dialect: new LibsqlDialect({ url: `file:${join(tmpDir, "test.db")}` }) }); +}); +afterEach(async () => { + await k.destroy(); + rmSync(tmpDir, { recursive: true, force: true }); +}); + +// libsql execute() is single-statement; no emitted body here carries an inner ";". +async function applyRaw(text: string): Promise { + for (const stmt of text.split("\n").filter((l) => !l.startsWith("--")).join("\n").split(";").map((s) => s.trim()).filter(Boolean)) { + await sql.raw(stmt).execute(k); + } +} + +async function migrate(metaJson: string, allow: AllowOptions = {}) { + const root = (await new MetaDataLoader().load([new InMemoryStringSource(metaJson)])).root; + const expected = buildExpectedSchema(literalColumns(root), { + dialect: "sqlite", + views: buildProjectionViews(literalColumns(root), { dialect: "sqlite" }), + }); + const actual = await introspectSqlite(k); + const result = await diff({ expected, actual, dialect: "sqlite", allow, unmanagedNames: collectUnmanagedNames(root) }); + const emittable = result.changes.filter((c) => c.status.state !== "blocked"); + const out = emittable.length === 0 + ? { up: "", down: "" } + : emit(emittable, { + dialect: "sqlite", expectedSchema: expected, actualSchema: actual, + ...(actual.meta !== undefined && { actualMeta: actual.meta }), + }); + if (result.blocked.length === 0 && out.up.trim().length > 0) await applyRaw(out.up); + return { result, ...out }; +} + +describe("drop-column under a view — real SQLite", () => { + test("an unmanaged view that reads the dropped column is blocked and named; the DB is untouched", async () => { + await migrate(meta(true, [UNMANAGED_VIEW])); + await sql.raw(`CREATE VIEW "v_hand" AS SELECT "id", "nickname" FROM "accounts"`).execute(k); + + const { result } = await migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true }); + const blocked = result.blocked.find((c) => c.kind === "drop-column"); + expect(blocked?.status).toMatchObject({ state: "blocked", blockedBy: "dropColumnReadByView" }); + expect(blocked?.status.blockedReason).toContain("v_hand"); + expect(blocked?.status.blockedReason).toContain("accounts.nickname"); + + // With the flag the plan is allowed through. + await expect(migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true, dropColumnReadByView: true })) + .rejects.toThrow(/v_hand/); // SQLite then refuses the drop at apply: the view still reads it + }, TIMEOUT_MS); + + test("an unmanaged view that does not read the dropped column is not blocked", async () => { + await migrate(meta(true, [UNMANAGED_VIEW])); + await sql.raw(`CREATE VIEW "v_hand" AS SELECT "id", "name" FROM "accounts"`).execute(k); + + const { result } = await migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true }); + expect(result.blocked).toEqual([]); + await sql.raw(`SELECT * FROM "v_hand"`).execute(k); + }, TIMEOUT_MS); + + test("rolling back a drop-column re-adds it, and the managed view is queryable again", async () => { + await migrate(meta(true)); + await sql.raw(`INSERT INTO "accounts" ("id","name","nickname") VALUES (1,'a','n1'),(2,'b','n2')`).execute(k); + + const { result, down } = await migrate(meta(false), { dropColumn: true, dropView: true }); + expect(result.blocked).toEqual([]); + expect(down).toContain(`ADD COLUMN "nickname"`); + // Applied: the column and the view's column are gone. + await expect(sql.raw(`SELECT "nickname" FROM "v_account"`).execute(k)).rejects.toThrow(); + + await applyRaw(down); + const rows = await sql.raw(`SELECT * FROM "v_account" ORDER BY "id"`).execute(k); + expect(rows.rows).toHaveLength(2); + expect(Object.keys(rows.rows[0] as object)).toContain("nickname"); + // The data is not restored, and the migration says so. + expect((rows.rows[0] as { nickname: unknown }).nickname).toBeNull(); + expect(down).toMatch(/column data is not restored/i); + }, TIMEOUT_MS); +}); diff --git a/server/typescript/packages/migrate-ts/src/diff/index.ts b/server/typescript/packages/migrate-ts/src/diff/index.ts index d73e4b0c30..ef9640c4b8 100644 --- a/server/typescript/packages/migrate-ts/src/diff/index.ts +++ b/server/typescript/packages/migrate-ts/src/diff/index.ts @@ -317,6 +317,12 @@ export async function diff( // that is exactly the object a cascade must not destroy silently. annotateViewDropDependents(args.actual.views, changes); + // A live view this tool neither rewrites nor drops stays in place and blocks a column drop + // at apply. Whether a planned drop-view/replace-view is itself blocked is decided by the + // statuses, so assign them first; applyStatus below assigns them again over the final list. + applyStatus(changes, args.allow ?? {}); + annotateUnownedColumnReaders(args.actual.views, changes); + // Pass 3: column renames (table renames were resolved in Pass 1c). await detectColumnRenames(changes, args.onAmbiguous, args.renames); // Pass 3b: a renamed column carries the constraints and indexes named after it. @@ -1249,6 +1255,38 @@ function annotateViewDropDependents(actual: readonly ViewDescriptor[], changes: } } +/** + * Mark each `drop-column` that a live view this migration leaves in place still reads. + * + * A view with a drop-view or replace-view in `changes` that is not blocked is dropped or + * rewritten around the change, so it does not strand the drop. Every other live view + * does: a declared-`@unmanaged` one, one in a schema the model does not scope, a hand-made + * one whose drop-view is blocked. A view with no recorded body cannot be matched, so it is + * not blocked on. + */ +function annotateUnownedColumnReaders( + actual: readonly ViewDescriptor[], + changes: Change[], +): void { + const handled = new Set(); + for (const c of changes) { + if (c.status.state === "blocked") continue; + if (c.kind === "drop-view") handled.add(viewIdentity({ name: c.view, ...schemaSpread(c.schema) })); + else if (c.kind === "replace-view") handled.add(viewIdentity({ name: c.view.name, ...schemaSpread(c.schema) })); + } + const unowned = actual.filter((v) => v.sql !== undefined && !handled.has(viewIdentity(v))); + if (unowned.length === 0) return; + const liveName = liveTableNames(changes); + for (const c of changes) { + if (c.kind !== "drop-column") continue; + const table = liveName(c.table); + const readBy = unowned + .filter((v) => sqlNamesIdentifier(v.sql!, table) && sqlNamesIdentifier(v.sql!, c.column)) + .map((v) => (v.schema !== undefined ? `${v.schema}.${v.name}` : v.name)); + if (readBy.length > 0) c.readBy = readBy; + } +} + /** * Postgres: a view reading a column blocks `ALTER … ALTER COLUMN TYPE`, a drop and a rename * of it, so those force the view to be dropped-before / recreated-after. A new default or a diff --git a/server/typescript/packages/migrate-ts/src/diff/status.ts b/server/typescript/packages/migrate-ts/src/diff/status.ts index 672bb42b17..a777fc390f 100644 --- a/server/typescript/packages/migrate-ts/src/diff/status.ts +++ b/server/typescript/packages/migrate-ts/src/diff/status.ts @@ -55,8 +55,18 @@ function blockFor( recreatedViews: ReadonlySet, ): Block | null { switch (c.kind) { - case "drop-column": - return gate(allow, "dropColumn", "destructive: drop-column not allowed (pass allow.dropColumn)"); + case "drop-column": { + const blocked = gate(allow, "dropColumn", "destructive: drop-column not allowed (pass allow.dropColumn)"); + if (blocked !== null) return blocked; + const readBy = c.readBy ?? []; + if (readBy.length > 0) { + return gate(allow, "dropColumnReadByView", + `drop-column ${c.table}.${c.column} is still read by ${readBy.length} view(s) MetaObjects does not own ` + + `(${readBy.join(", ")}). It never rewrites them, so the drop fails at apply. ` + + `Change the view(s) first, or pass allow.dropColumnReadByView`); + } + return null; + } case "drop-table": return gate(allow, "dropTable", "destructive: drop-table not allowed (pass allow.dropTable)"); case "drop-index": diff --git a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts index afeeb6811e..9689dafbf0 100644 --- a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts +++ b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts @@ -430,6 +430,33 @@ export function renderCreateView(v: ViewDescriptor): string { return `CREATE VIEW ${quote(v.name)} AS\n${v.sql};`; } +/** + * Re-add a dropped column from the descriptor the diff kept (`restore`). The data is not + * restored. SQLite refuses `ADD COLUMN … NOT NULL` with no default, so such a column comes + * back nullable rather than leaving the rollback unable to run. + */ +function renderDropColumnDown(c: Extract): string { + if (c.restore === undefined) { + return `-- WARNING: down migration cannot restore data\n-- TODO: re-add dropped column "${c.column}" manually with original type/nullable/default`; + } + const { default: dflt, identity, ...rest } = c.restore; + const nonConstant = dflt?.kind === "expr" || (dflt === undefined && identity === "uuid"); + const literal = dflt?.kind === "literal" ? dflt : undefined; + const loosen = !c.restore.nullable && literal === undefined; + const column: ColumnDescriptor = { + ...rest, + nullable: c.restore.nullable || loosen, + ...(literal !== undefined ? { default: literal } : {}), + ...(identity === "increment" ? { identity } : {}), + }; + return [ + `ALTER TABLE ${quote(c.table)} ADD COLUMN ${renderColumnInline(column)};`, + "-- NOTE: column data is not restored by this down migration.", + ...(nonConstant ? [`-- NOTE: ${quote(c.column)} had a non-constant default; SQLite cannot add a column with one to a populated table, so the default is omitted.`] : []), + ...(loosen ? [`-- NOTE: ${quote(c.column)} was NOT NULL with no default; SQLite cannot add it that way, so it returns nullable.`] : []), + ].join("\n"); +} + function renderDownNative(c: Change): string { switch (c.kind) { case "create-table": return `DROP TABLE ${quote(c.table.name)};`; @@ -439,7 +466,7 @@ function renderDownNative(c: Change): string { return `ALTER TABLE ${quote(c.to)} RENAME TO ${quote(c.from)};`; } case "add-column": return `ALTER TABLE ${quote(c.table)} DROP COLUMN ${quote(c.column.name)};`; - case "drop-column": return `-- WARNING: down migration cannot restore data\n-- TODO: re-add dropped column "${c.column}" manually`; + case "drop-column": return renderDropColumnDown(c); case "rename-column": { assertNoCarriedRenames(c); return `ALTER TABLE ${quote(c.table)} RENAME COLUMN ${quote(c.to)} TO ${quote(c.from)};`; diff --git a/server/typescript/packages/migrate-ts/src/types.ts b/server/typescript/packages/migrate-ts/src/types.ts index b08fb361db..a7527d5ce8 100644 --- a/server/typescript/packages/migrate-ts/src/types.ts +++ b/server/typescript/packages/migrate-ts/src/types.ts @@ -252,7 +252,15 @@ export type Change = status: ChangeStatus; } | { kind: "add-column"; table: string; schema?: string; column: ColumnDescriptor; status: ChangeStatus } - | { kind: "drop-column"; table: string; schema?: string; column: string; restore?: ColumnDescriptor; status: ChangeStatus } + | { + kind: "drop-column"; table: string; schema?: string; column: string; restore?: ColumnDescriptor; status: ChangeStatus; + /** + * Live views this tool does not own (declared `@unmanaged`, or outside the scoped + * schemas) whose recorded body names the dropped column. The drop fails at apply + * while they stand, so it is blocked pending `allow.dropColumnReadByView`. + */ + readBy?: readonly string[]; + } | { kind: "rename-column"; table: string; schema?: string; from: string; to: string; /** @@ -471,6 +479,14 @@ export interface AllowOptions { * dependents snapshot rather than silently cascading. */ dropViewCascade?: boolean; + /** + * Gates dropping a column that a live view this tool does NOT own still reads (a view + * declared `@unmanaged`, or one outside the scoped schemas). The tool never rewrites + * such a view, so the drop fails at apply on Postgres (`cannot drop column … other + * objects depend on it`) and on SQLite (`error in view … after drop column`). Granting + * this lets the plan through, for when the view is dealt with first or in the same release. + */ + dropColumnReadByView?: boolean; /** * Gates overwriting an existing view that carries NO MetaObjects fingerprint — * i.e. taking ownership of it. It is either hand-written or predates diff --git a/server/typescript/packages/migrate-ts/test/drop-column-unowned-view.test.ts b/server/typescript/packages/migrate-ts/test/drop-column-unowned-view.test.ts new file mode 100644 index 0000000000..8c76c483ee --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/drop-column-unowned-view.test.ts @@ -0,0 +1,138 @@ +/** + * A view this tool does not own is never rewritten, so it strands a column drop at apply. + * The plan must refuse and name the view; a view that does not read the column, or has no + * recorded body, must not block. The SQLite down must re-add the dropped column. + */ +import { describe, test, expect } from "bun:test"; +import { Database } from "bun:sqlite"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import type { MetaData } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../src/expected-schema.js"; +import { diff } from "../src/diff/index.js"; +import { emit } from "../src/emit/index.js"; +import type { SchemaSnapshot, ViewDescriptor } from "../src/types.js"; + +async function load(fields: string): Promise { + return (await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ + "metadata.root": { children: [{ + "object.entity": { name: "Account", children: [ + { "field.long": { name: "id" } }, + { "field.string": { name: "name" } }, + ...JSON.parse(fields), + { "source.rdb": { name: "src", "@table": "accounts" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + ] }, + }] }, + }))])).root; +} + +const NICKNAME = '[{"field.string":{"name":"nickname"}}]'; + +function withViews(s: SchemaSnapshot, views: ViewDescriptor[]): SchemaSnapshot { + return { ...s, views }; +} + +for (const dialect of ["postgres", "sqlite"] as const) { + describe(`drop-column under a view the tool does not own (${dialect})`, () => { + async function plan(views: ViewDescriptor[], unmanagedNames: string[], allow = {}) { + const prior = withViews(buildExpectedSchema(await load(NICKNAME), { dialect }), views); + const next = buildExpectedSchema(await load("[]"), { dialect }); + return diff({ expected: next, actual: prior, dialect, allow: { dropColumn: true, ...allow }, unmanagedNames }); + } + const schema = dialect === "postgres" ? "public" : undefined; + const view = (sql: string | undefined): ViewDescriptor => ({ + name: "v_hand", ...(schema !== undefined ? { schema } : {}), ...(sql !== undefined ? { sql } : {}), + }); + const id = "public.v_hand"; // viewIdentity defaults an absent schema to "public" + + test("an @unmanaged view that reads the column blocks the drop and is named", async () => { + const r = await plan([view("SELECT id, nickname FROM accounts")], [id]); + expect(r.blocked.length).toBe(1); + const status = r.blocked[0]!.status; + expect(status).toMatchObject({ state: "blocked", blockedBy: "dropColumnReadByView" }); + expect((status as { blockedReason: string }).blockedReason).toContain("v_hand"); + expect((status as { blockedReason: string }).blockedReason).toContain("accounts.nickname"); + }); + + test("allow.dropColumnReadByView lifts the block", async () => { + const r = await plan([view("SELECT id, nickname FROM accounts")], [id], { dropColumnReadByView: true }); + expect(r.blocked).toEqual([]); + }); + + test("an @unmanaged view that does not read the column does not block", async () => { + const r = await plan([view("SELECT id, name FROM accounts")], [id]); + expect(r.blocked).toEqual([]); + }); + + test("a hand-made view (declared by no metadata) that reads the column blocks the drop while its drop-view is blocked", async () => { + const r = await plan([view("SELECT id, nickname FROM accounts")], []); + const dropColumn = r.changes.find((c) => c.kind === "drop-column")!; + expect(dropColumn.status).toMatchObject({ state: "blocked", blockedBy: "dropColumnReadByView" }); + expect((dropColumn.status as { blockedReason: string }).blockedReason).toContain("v_hand"); + }); + + test("a hand-made view whose drop-view is allowed is dropped around the change, so it does not block the drop", async () => { + const r = await plan([view("SELECT id, nickname FROM accounts")], [], { dropView: true }); + expect(r.blocked).toEqual([]); + }); + + test("a view with no recorded body does not block", async () => { + const r = await plan([view(undefined)], [id]); + expect(r.blocked).toEqual([]); + }); + }); +} + +describe("sqlite down of drop-column", () => { + test("re-adds the column with its type and says the data is not restored", async () => { + const prior = buildExpectedSchema(await load(NICKNAME), { dialect: "sqlite" }); + const next = buildExpectedSchema(await load("[]"), { dialect: "sqlite" }); + const r = await diff({ expected: next, actual: prior, dialect: "sqlite", allow: { dropColumn: true } }); + const { up, down } = emit(r.changes, { dialect: "sqlite" }); + expect(up).toContain('DROP COLUMN "nickname"'); + expect(down).toContain('ALTER TABLE "accounts" ADD COLUMN "nickname"'); + expect(down).toMatch(/column data is not restored/i); + expect(down).not.toMatch(/TODO/); + }); + + test("D1 renders the same down", async () => { + const prior = buildExpectedSchema(await load(NICKNAME), { dialect: "d1" }); + const next = buildExpectedSchema(await load("[]"), { dialect: "d1" }); + const r = await diff({ expected: next, actual: prior, dialect: "d1", allow: { dropColumn: true } }); + const { down } = emit(r.changes, { dialect: "d1", expectedSchema: next, actualSchema: prior }); + expect(down).toContain('ALTER TABLE "accounts" ADD COLUMN "nickname"'); + }); + + test("a NOT NULL column with no default returns nullable, since SQLite cannot add it otherwise", async () => { + const prior = buildExpectedSchema(await load('[{"field.string":{"name":"nickname","@required":true}}]'), { dialect: "sqlite" }); + const next = buildExpectedSchema(await load("[]"), { dialect: "sqlite" }); + const r = await diff({ expected: next, actual: prior, dialect: "sqlite", allow: { dropColumn: true } }); + const { down } = emit(r.changes, { dialect: "sqlite" }); + expect(down).toMatch(/ADD COLUMN "nickname" \w+(\(\d+\))?;/); + expect(down).not.toContain("NOT NULL;"); + expect(down).toMatch(/NOT NULL with no default/); + }); + test("rollback applies to a populated table when the dropped column had an expression or uuid default", async () => { + // Oracle: SQLite itself refuses ADD COLUMN with a non-constant default on a table holding rows. + const prior = buildExpectedSchema(await load( + '[{"field.timestamp":{"name":"createdAt","@required":true}},{"field.uuid":{"name":"token","@required":true}}]', + ), { dialect: "sqlite" }); + const createdAt = prior.tables[0]!.columns.find((c) => c.name === "created_at")!; + createdAt.default = { kind: "expr", value: "now()" }; + const token = prior.tables[0]!.columns.find((c) => c.name === "token")!; + token.identity = "uuid"; + delete token.default; + const next = buildExpectedSchema(await load("[]"), { dialect: "sqlite" }); + const r = await diff({ expected: next, actual: prior, dialect: "sqlite", allow: { dropColumn: true } }); + const { down } = emit(r.changes, { dialect: "sqlite" }); + + const db = new Database(":memory:"); + db.run('CREATE TABLE "accounts" ("id" INTEGER PRIMARY KEY, "name" TEXT)'); + db.run(`INSERT INTO "accounts" ("name") VALUES ('a')`); + expect(() => db.exec(down)).not.toThrow(); + const cols = (db.query('PRAGMA table_info("accounts")').all() as { name: string }[]).map((c) => c.name); + expect(cols).toContain("created_at"); + expect(cols).toContain("token"); + expect(down).toMatch(/non-constant default/); + }); +}); diff --git a/server/typescript/packages/sdk/src/config.ts b/server/typescript/packages/sdk/src/config.ts index c33e5397be..40d127843d 100644 --- a/server/typescript/packages/sdk/src/config.ts +++ b/server/typescript/packages/sdk/src/config.ts @@ -45,6 +45,7 @@ export const AllowTokenEnum = z.enum([ "drop-check", "drop-view", "drop-view-cascade", + "drop-column-read-by-view", "adopt-view", "nullable-to-not-null", "drop-identity-default", From 2049f5efd420204a027b474f08c4807ebaf8944d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Tue, 3 Nov 2026 23:51:00 -0500 Subject: [PATCH 03/51] fix(metadata): exempt read-only @sql views from column-name collision check (#528) * fix(metadata): exempt @sql views from the duplicate-column check in every port * no-mistakes(review): Narrow SQL-view column exemption to read-only objects; gate wording * no-mistakes(review): Refresh conformance fixture count to 426 * no-mistakes(document): Refreshed collision error-code description; other docs already current --- AGENTS.md | 2 +- CHANGELOG.md | 11 +++ docs/CONFORMANCE.md | 6 +- examples/showcase/site-payload.json | 2 +- fixtures/conformance/ERROR-CODES.json | 2 +- .../expected.json | 39 ++++++++ .../input/meta.demo.json | 16 +++ .../providers.json | 1 + .../expected-errors.json | 15 +++ .../input/meta.demo.json | 16 +++ .../providers.json | 1 + .../expected-errors.json | 15 +++ .../input/meta.demo.json | 18 ++++ .../providers.json | 1 + .../ColumnNameCollisionMessageTests.cs | 68 +++++++++++++ .../MetaObjects/Loader/ValidationPasses.cs | 20 +++- .../metaobjects/loader/ValidationPhase.java | 29 +++++- .../ColumnNameCollisionMessageTest.java | 98 +++++++++++++++++++ .../metaobjects/loader/validation_passes.py | 28 +++++- .../test_column_name_collision_message.py | 77 +++++++++++++++ .../metadata/src/loader/validation-passes.ts | 28 +++++- .../column-name-collision-message.test.ts | 26 +++++ 22 files changed, 505 insertions(+), 14 deletions(-) create mode 100644 fixtures/conformance/column-name-shared-in-sql-view-ok/expected.json create mode 100644 fixtures/conformance/column-name-shared-in-sql-view-ok/input/meta.demo.json create mode 100644 fixtures/conformance/column-name-shared-in-sql-view-ok/providers.json create mode 100644 fixtures/conformance/error-column-name-collision-derived-view/expected-errors.json create mode 100644 fixtures/conformance/error-column-name-collision-derived-view/input/meta.demo.json create mode 100644 fixtures/conformance/error-column-name-collision-derived-view/providers.json create mode 100644 fixtures/conformance/error-column-name-collision-table-with-sql-view/expected-errors.json create mode 100644 fixtures/conformance/error-column-name-collision-table-with-sql-view/input/meta.demo.json create mode 100644 fixtures/conformance/error-column-name-collision-table-with-sql-view/providers.json create mode 100644 server/csharp/MetaObjects.Conformance.Tests/ColumnNameCollisionMessageTests.cs create mode 100644 server/java/metadata/src/test/java/com/metaobjects/source/ColumnNameCollisionMessageTest.java create mode 100644 server/python/tests/unit/test_column_name_collision_message.py create mode 100644 server/typescript/packages/metadata/test/column-name-collision-message.test.ts diff --git a/AGENTS.md b/AGENTS.md index 31c4c7fa80..ee01045468 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,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/` (423 fixtures; 35 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/` (426 fixtures; 35 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 8b13247ac0..d218fd9a9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,17 @@ here.** ### Fixed +- **`ERR_COLUMN_NAME_COLLISION` no longer rejects a read-only view whose columns come from `@sql`.** + The 1.2.0 check treated every field of a sourced object as a column MetaObjects creates. For a + `source.rdb @kind: view` with an `@sql` body, the author's SQL defines the columns and the fields + only read them, so two fields on one column are legal and nothing can be written. That object is + now exempt in all four ports (TypeScript, Java, C#, Python), provided every source of the object + is read-only. A derived view (no `@sql`), which emits a select list from its fields, and an object + with a writable table source plus an `@sql` view replica are still checked. When both colliding fields already carry an + explicit `@column`, the message now says to rename one field or point one `@column` at a different + column, instead of suggesting a `@column` they already have. The error code is unchanged. New + conformance fixtures: `column-name-shared-in-sql-view-ok`, `error-column-name-collision-derived-view` and + `error-column-name-collision-table-with-sql-view`. - **`meta migrate` refuses, at plan time, to drop a column a view it does not own still reads.** With `--from-db`, a declared-`@unmanaged` view or one outside the scoped schemas whose live body names the dropped column now blocks the `drop-column`, and the message names the view and the diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index d7e9157567..16d963fd0e 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 423 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 426 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -285,7 +285,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (423) +### `fixtures/conformance/` — metamodel loader + canonical serializer (426) | Fixture prefix | Feature doc | |---|---| @@ -611,7 +611,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 423 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 426 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 6e9ec3f63d..7330d646f0 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.2" }, "counts": { - "fixtures": 423, + "fixtures": 426, "corpora": 35, "baseTypes": 17 }, diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index d2c931bbad..278b1b50f0 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -38,7 +38,7 @@ "ERR_EXTENDS_ORIGIN_MISMATCH": "FR-024 (ADR-0029 decision 7): a field declares both an entity-nested extends (shape lineage) and an origin.passthrough @from (data lineage) and they disagree — the resolved @from target is not the field's resolved extends target (nor anywhere on its extends chain). Host-agnostic (projections, entities, values). origin.aggregate is never judged (it computes something new); a top-level abstract extends target is never judged (shape-only reuse makes no lineage claim).", "ERR_PASSTHROUGH_TYPE_MISMATCH": "#185: a field carrying origin.passthrough @from: \"Entity.field\" declares a field. or array-ness that differs from its resolved source field — a passthrough forwards the value unchanged, so its type must be identical. Host-agnostic (projections, entities, values, stored-proc parameter refs). Nullability is NOT judged (a view over an outer join legitimately widens NOT NULL → nullable). Opt out of a deliberate type change with @convert: true on the origin.passthrough (an acknowledgement — it does not generate a cast); real type-converting projections are origin.expression's job (#159).", "ERR_DERIVED_FIELD_NO_READ_SOURCE": "FR-024 (spec §7): an object.entity field carrying an origin.* child is derived (read-only) and must be providable — the entity must declare at least one source with a read-only @kind (view/materializedView/storedProc/tableFunction, e.g. a @role replica view beside the table primary). Table-only or source-less entities with origin-bearing fields error on the field. Projections and object.value hosts are exempt. Until the Phase-E B4b cutover removes view-primary entities, a read-only-kind PRIMARY source also counts as providable (legacy spelling).", - "ERR_COLUMN_NAME_COLLISION": "Two fields of one stored object (a concrete object declaring a source) resolve to the same physical column name: snake_case folds `userId` and `userID` into `user_id`, or two fields share an explicit @column. Only RESOLVED physical names are compared (explicit @column honoured, inherited fields included, derived and source-less objects exempt). The message names both fields and the column.", + "ERR_COLUMN_NAME_COLLISION": "Two fields of one stored object (a concrete object declaring a source) resolve to the same physical column name: snake_case folds `userId` and `userID` into `user_id`, or two fields share an explicit @column. Only RESOLVED physical names are compared (explicit @column honoured, inherited fields included, derived and source-less objects exempt, and so is an object whose every source is read-only and at least one is a `@sql` view, since the author's SQL defines those columns). The message names both fields and the column.", "ERR_INVALID_TEMPLATE": "A template (prompt/output) declares a @payloadRef that does not resolve, or @requiredSlots that are not fields on its payload.", "ERR_INVALID_RELATIONSHIP": "FR-017: a M:N relationship's slim vocabulary is invalid — @through does not resolve to a junction declaring two identity.reference children (ADR-0042: @through resolves package-locally when bare, exactly when FQN — a bare cross-package @through no longer binds elsewhere), @sourceRefField does not match one of them, or a M:N-only attr (@through/@sourceRefField/@symmetric) is set on a non-M:N (1:N / @cardinality:one) relationship; OR a relationship's @objectRef does not resolve to any object in the loaded tree (a dangling target).", "ERR_INVALID_REFERENCE": "An identity.reference @references names an FK target object that does not resolve to any object in the loaded tree (a dangling cross-reference between metadata).", diff --git a/fixtures/conformance/column-name-shared-in-sql-view-ok/expected.json b/fixtures/conformance/column-name-shared-in-sql-view-ok/expected.json new file mode 100644 index 0000000000..388777ebf5 --- /dev/null +++ b/fixtures/conformance/column-name-shared-in-sql-view-ok/expected.json @@ -0,0 +1,39 @@ +{ + "metadata.root": { + "package": "demo", + "children": [ + { + "object.projection": { + "name": "UserView", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@sql": "SELECT u.id, u.username FROM app_user u", + "@view": "user_view" + } + }, + { + "field.long": { + "name": "id", + "@column": "id" + } + }, + { + "field.string": { + "name": "userName", + "@column": "username" + } + }, + { + "field.string": { + "name": "displayName", + "@column": "username" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/column-name-shared-in-sql-view-ok/input/meta.demo.json b/fixtures/conformance/column-name-shared-in-sql-view-ok/input/meta.demo.json new file mode 100644 index 0000000000..5314b05bf1 --- /dev/null +++ b/fixtures/conformance/column-name-shared-in-sql-view-ok/input/meta.demo.json @@ -0,0 +1,16 @@ +{ + "metadata.root": { + "package": "demo", + "children": [ + { "object.projection": { + "name": "UserView", + "children": [ + { "source.rdb": { "@kind": "view", "@view": "user_view", "@sql": "SELECT u.id, u.username FROM app_user u" } }, + { "field.long": { "name": "id", "@column": "id" } }, + { "field.string": { "name": "userName", "@column": "username" } }, + { "field.string": { "name": "displayName", "@column": "username" } } + ] + }} + ] + } +} diff --git a/fixtures/conformance/column-name-shared-in-sql-view-ok/providers.json b/fixtures/conformance/column-name-shared-in-sql-view-ok/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/column-name-shared-in-sql-view-ok/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-column-name-collision-derived-view/expected-errors.json b/fixtures/conformance/error-column-name-collision-derived-view/expected-errors.json new file mode 100644 index 0000000000..a19f7ad425 --- /dev/null +++ b/fixtures/conformance/error-column-name-collision-derived-view/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_COLUMN_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.demo.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.projection'].children[3]['field.string']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-column-name-collision-derived-view/input/meta.demo.json b/fixtures/conformance/error-column-name-collision-derived-view/input/meta.demo.json new file mode 100644 index 0000000000..50ac7e9092 --- /dev/null +++ b/fixtures/conformance/error-column-name-collision-derived-view/input/meta.demo.json @@ -0,0 +1,16 @@ +{ + "metadata.root": { + "package": "demo", + "children": [ + { "object.projection": { + "name": "UserView", + "children": [ + { "source.rdb": { "@kind": "view", "@view": "user_view" } }, + { "field.long": { "name": "id", "@column": "id" } }, + { "field.string": { "name": "userName", "@column": "username" } }, + { "field.string": { "name": "displayName", "@column": "username" } } + ] + }} + ] + } +} diff --git a/fixtures/conformance/error-column-name-collision-derived-view/providers.json b/fixtures/conformance/error-column-name-collision-derived-view/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-column-name-collision-derived-view/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/fixtures/conformance/error-column-name-collision-table-with-sql-view/expected-errors.json b/fixtures/conformance/error-column-name-collision-table-with-sql-view/expected-errors.json new file mode 100644 index 0000000000..ce96277156 --- /dev/null +++ b/fixtures/conformance/error-column-name-collision-table-with-sql-view/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_COLUMN_NAME_COLLISION", + "source": { + "format": "json", + "files": [ + "meta.demo.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[4]['field.string']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-column-name-collision-table-with-sql-view/input/meta.demo.json b/fixtures/conformance/error-column-name-collision-table-with-sql-view/input/meta.demo.json new file mode 100644 index 0000000000..1c87fd5e2a --- /dev/null +++ b/fixtures/conformance/error-column-name-collision-table-with-sql-view/input/meta.demo.json @@ -0,0 +1,18 @@ +{ + "metadata.root": { + "package": "demo", + "children": [ + { "object.entity": { + "name": "Account", + "children": [ + { "source.rdb": { "@kind": "table", "@table": "account" } }, + { "source.rdb": { "@kind": "view", "@view": "account_view", "@role": "replica", "@sql": "SELECT a.id, a.username FROM account a" } }, + { "field.long": { "name": "id", "@column": "id" } }, + { "field.string": { "name": "userName", "@column": "username" } }, + { "field.string": { "name": "displayName", "@column": "username" } }, + { "identity.primary": { "name": "id", "@fields": ["id"] } } + ] + }} + ] + } +} diff --git a/fixtures/conformance/error-column-name-collision-table-with-sql-view/providers.json b/fixtures/conformance/error-column-name-collision-table-with-sql-view/providers.json new file mode 100644 index 0000000000..aefa027b6a --- /dev/null +++ b/fixtures/conformance/error-column-name-collision-table-with-sql-view/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] diff --git a/server/csharp/MetaObjects.Conformance.Tests/ColumnNameCollisionMessageTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ColumnNameCollisionMessageTests.cs new file mode 100644 index 0000000000..cb2d329912 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/ColumnNameCollisionMessageTests.cs @@ -0,0 +1,68 @@ +// ERR_COLUMN_NAME_COLLISION advice wording and the @sql view exemption. +// +// Mirrors typescript/packages/metadata/test/column-name-collision-message.test.ts. + +using MetaObjects; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +public class ColumnNameCollisionMessageTests +{ + private static string[] CollisionMessages(string sourceChild, string fieldA, string fieldB) + { + var doc = $$""" + { "metadata.root": { "package": "demo", "children": [ + { "object.entity": { "name": "Account", "children": [ + {{sourceChild}}, + { "field.long": { "name": "id" } }, + {{fieldA}}, + {{fieldB}}, + { "identity.primary": { "name": "id", "@fields": ["id"] } } + ] } } + ] } } + """; + return MetaDataLoader.FromString(doc, MetaDataFormat.Json).Errors + .Where(e => e.Code == ErrorCode.ERR_COLUMN_NAME_COLLISION) + .Select(e => e.Message) + .ToArray(); + } + + private const string Table = """{ "source.rdb": { "@kind": "table", "@table": "account" } }"""; + + [Fact] + public void Two_explicit_columns_on_one_column_do_not_suggest_adding_a_column() + { + var msg = Assert.Single(CollisionMessages(Table, + """{ "field.string": { "name": "userName", "@column": "username" } }""", + """{ "field.string": { "name": "displayName", "@column": "username" } }""")); + Assert.Contains("point one @column at a different column", msg); + Assert.DoesNotContain("give one an explicit @column", msg); + } + + [Fact] + public void Implicit_collision_still_suggests_an_explicit_column() + { + var msg = Assert.Single(CollisionMessages(Table, + """{ "field.string": { "name": "userId" } }""", + """{ "field.string": { "name": "userID" } }""")); + Assert.Contains("give one an explicit @column", msg); + } + + [Fact] + public void Sql_view_may_share_a_column_between_fields() + { + var doc = """ + { "metadata.root": { "package": "demo", "children": [ + { "object.projection": { "name": "UserView", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v", "@sql": "SELECT id, username FROM t" } }, + { "field.long": { "name": "id", "@column": "id" } }, + { "field.string": { "name": "userName", "@column": "username" } }, + { "field.string": { "name": "displayName", "@column": "username" } } + ] } } + ] } } + """; + Assert.Empty(MetaDataLoader.FromString(doc, MetaDataFormat.Json).Errors); + } +} diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 13f06857b2..7d11a0ca44 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -4445,6 +4445,19 @@ void Walk(MetaData node) // declaring at least one source (a source-less object generates nothing); derived // fields and field.object (may flatten to several columns) are skipped. // ADR-0039: effective children, so an inherited field collides like an own one. + // Exempt: an object whose every source is read-only and at least one is a + // source.rdb @kind: view with an @sql body. The author's SQL defines that view's columns + // and the fields only READ them, so two fields on one column create no duplicate column + // and nothing can be written. A derived view (no @sql) emits a select list from its + // fields, and an object with a writable source has a real table whose columns + // MetaObjects creates; both stay checked. + private static bool ReadsThroughSqlView(MetaData obj) + { + var sources = obj.Children().OfType().ToList(); + return sources.All(s => s.IsReadOnly()) && + sources.Any(s => s.EffectiveKind == SourceConstants.SOURCE_KIND_VIEW && s.SqlBody is not null); + } + public static IReadOnlyList ValidateColumnNameCollisions(MetaData root) { var errors = new List(); @@ -4452,6 +4465,7 @@ public static IReadOnlyList ValidateColumnNameCollisions(MetaData roo { if (obj.IsAbstract) continue; if (!obj.Children().Any(c => c.Type == TYPE_SOURCE)) continue; + if (ReadsThroughSqlView(obj)) continue; var seen = new Dictionary(StringComparer.Ordinal); foreach (var field in obj.Children().OfType()) { @@ -4464,8 +4478,10 @@ public static IReadOnlyList ValidateColumnNameCollisions(MetaData roo } errors.Add(new MetaError( $"fields \"{first.Name}\" and \"{field.Name}\" on \"{obj.Name}\" both resolve to " + - $"physical column \"{column}\". Rename one field, or give one an explicit @column " + - "so the two columns differ.", + $"physical column \"{column}\". " + + (first.DbColumn is { Length: > 0 } && field.DbColumn is { Length: > 0 } + ? "Rename one field, or point one @column at a different column." + : "Rename one field, or give one an explicit @column so the two columns differ."), ErrorCode.ERR_COLUMN_NAME_COLLISION, Envelope: field.Source)); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index 1ddc61efbc..f4c4b8c615 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -5409,11 +5409,34 @@ private static void walkRetiredRequirementLinks(MetaData node) { * generates nothing); derived fields and {@code field.object} (may flatten to several * columns) are skipped. ADR-0039: resolving accessors, so an inherited field collides like * an own one.

+ * + *

Exempt: an object whose every source is read-only and at least one is a + * {@code source.rdb @kind: view} with an {@code @sql} body. The author's SQL defines that + * view's columns and the fields only READ them, so two fields on one column create no + * duplicate column and nothing can be written. A derived view (no {@code @sql}) emits a + * select list from its fields, and an object with a writable source has a real table whose + * columns MetaObjects creates; both stay checked.

*/ + private static boolean readsThroughSqlView(MetaObject obj) { + boolean sqlView = false; + for (MetaSource s : obj.getChildren(MetaSource.class, true)) { + if (!s.isReadOnly()) return false; + if (MetaSource.KIND_VIEW.equals(s.getEffectiveKind()) && s.getSqlBody() != null) sqlView = true; + } + return sqlView; + } + + private static boolean hasExplicitColumn(MetaField field) { + if (!field.hasMetaAttr(CoreDBMetaDataProvider.COLUMN, true)) return false; + String v = field.getMetaAttr(CoreDBMetaDataProvider.COLUMN, true).getValueAsString(); + return v != null && !v.isEmpty(); + } + static void validateColumnNameCollisions(MetaRoot root) { for (MetaObject obj : root.getChildren(MetaObject.class, false)) { if (isAbstract(obj)) continue; if (obj.getChildren(MetaSource.class, true).isEmpty()) continue; + if (readsThroughSqlView(obj)) continue; java.util.Map> seen = new java.util.HashMap<>(); for (MetaField field : obj.getChildren(MetaField.class, true)) { if (ObjectField.SUBTYPE_OBJECT.equals(field.getSubType()) || field.isDerived()) continue; @@ -5424,8 +5447,10 @@ static void validateColumnNameCollisions(MetaRoot root) { ErrorMessageConstants.ERR_COLUMN_NAME_COLLISION + ": fields \"" + first.getName() + "\" and \"" + field.getName() + "\" on \"" + obj.getName() + "\" both resolve to physical column \"" - + column + "\". Rename one field, or give one an explicit @column so the" - + " two columns differ.", + + column + "\". " + + (hasExplicitColumn(first) && hasExplicitColumn(field) + ? "Rename one field, or point one @column at a different column." + : "Rename one field, or give one an explicit @column so the two columns differ."), ErrorCode.ERR_COLUMN_NAME_COLLISION, field.getSource()); } } diff --git a/server/java/metadata/src/test/java/com/metaobjects/source/ColumnNameCollisionMessageTest.java b/server/java/metadata/src/test/java/com/metaobjects/source/ColumnNameCollisionMessageTest.java new file mode 100644 index 0000000000..c60512241a --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/source/ColumnNameCollisionMessageTest.java @@ -0,0 +1,98 @@ +/* + * Copyright 2003 Doug Mealing LLC dba Meta Objects + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.metaobjects.source; + +import com.metaobjects.ErrorCode; +import com.metaobjects.MetaDataException; +import com.metaobjects.loader.InMemoryStringSource; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.registry.SharedRegistryTestBase; +import org.junit.Test; + +import java.net.URI; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * ERR_COLUMN_NAME_COLLISION advice wording and the {@code @sql} view exemption. Mirrors + * {@code packages/metadata/test/column-name-collision-message.test.ts} in the TS reference port. + */ +public class ColumnNameCollisionMessageTest extends SharedRegistryTestBase { + + private static final String TABLE = "{ \"source.rdb\": { \"@kind\": \"table\", \"@table\": \"account\" } }"; + + private static String doc(String source, String fieldA, String fieldB) { + return "{ \"metadata.root\": { \"package\": \"demo\", \"children\": [" + + " { \"object.entity\": { \"name\": \"Account\", \"children\": [" + + source + "," + + " { \"field.long\": { \"name\": \"id\" } }," + + fieldA + "," + fieldB + "," + + " { \"identity.primary\": { \"name\": \"id\", \"@fields\": [\"id\"] } }" + + " ] } } ] } }"; + } + + private void load(String canonical, String id) { + MetaDataLoader loader = createTestLoader("ColumnNameCollisionMessageTest", + java.util.Collections.emptyList()); + loader.load(List.of(new InMemoryStringSource(canonical, id))); + } + + private String collisionMessage(String canonical, String id) { + try { + load(canonical, id); + } catch (MetaDataException e) { + assertTrue("expected ERR_COLUMN_NAME_COLLISION; got " + e.getMessage(), + e.getCode().filter(c -> c == ErrorCode.ERR_COLUMN_NAME_COLLISION).isPresent()); + return e.getMessage(); + } + fail("expected ERR_COLUMN_NAME_COLLISION"); + return null; + } + + @Test + public void twoExplicitColumnsOnOneColumnDoNotSuggestAddingAColumn() { + String msg = collisionMessage(doc(TABLE, + "{ \"field.string\": { \"name\": \"userName\", \"@column\": \"username\" } }", + "{ \"field.string\": { \"name\": \"displayName\", \"@column\": \"username\" } }"), "explicit.json"); + assertTrue(msg, msg.contains("point one @column at a different column")); + assertFalse(msg, msg.contains("give one an explicit @column")); + } + + @Test + public void implicitCollisionStillSuggestsAnExplicitColumn() { + String msg = collisionMessage(doc(TABLE, + "{ \"field.string\": { \"name\": \"userId\" } }", + "{ \"field.string\": { \"name\": \"userID\" } }"), "implicit.json"); + assertTrue(msg, msg.contains("give one an explicit @column")); + } + + @Test + public void sqlViewMayShareAColumnBetweenFields() { + load(""" + { "metadata.root": { "package": "demo", "children": [ + { "object.projection": { "name": "UserView", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v", "@sql": "SELECT id, username FROM t" } }, + { "field.long": { "name": "id", "@column": "id" } }, + { "field.string": { "name": "userName", "@column": "username" } }, + { "field.string": { "name": "displayName", "@column": "username" } } + ] } } + ] } } + """, "sqlview.json"); + } +} diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 34e1886d77..bb2c548cee 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -64,6 +64,7 @@ from ..meta.meta_data import MetaData from ..meta.persistence.source.meta_source import MetaSource from ..meta.persistence.source.source_constants import ( + SOURCE_KIND_VIEW, SOURCE_READ_ONLY_KINDS, SOURCE_ROLE_PRIMARY, ) @@ -4198,6 +4199,12 @@ def _validate_index_lookup_fields(root: MetaData, errors: list[MetaError]) -> No # --------------------------------------------------------------------------- +def _has_explicit_column(field: MetaData) -> bool: + from ..meta.core.field import field_constants as fc + col = field.get_meta_attr(fc.FIELD_ATTR_COLUMN) + return isinstance(col, str) and col != "" + + def _validate_column_name_collisions(root: MetaData, errors: list[MetaError]) -> None: """ERR_COLUMN_NAME_COLLISION: two fields of one stored object resolving to the SAME physical column (``userId`` + ``userID`` both snake_case to ``user_id``, or two @@ -4208,6 +4215,13 @@ def _validate_column_name_collisions(root: MetaData, errors: list[MetaError]) -> honoured. Scope: a concrete object declaring at least one source (a source-less object generates nothing); derived fields and ``field.object`` (may flatten to several columns) are skipped. ADR-0039: effective children (inherited fields count). + + Exempt: an object whose every source is read-only and at least one is a + ``source.rdb @kind: view`` with an ``@sql`` body. The author's SQL defines that view's + columns and the fields only READ them, so two fields on one column create no duplicate + column and nothing can be written. A derived view (no ``@sql``) emits a select list + from its fields, and an object with a writable source has a real table whose columns + MetaObjects creates; both stay checked. """ from ..naming import resolve_column_name from ..meta.core.field.meta_field import MetaField @@ -4216,6 +4230,12 @@ def _validate_column_name_collisions(root: MetaData, errors: list[MetaError]) -> continue if not any(c.type == TYPE_SOURCE for c in obj.children()): continue + sources = [c for c in obj.children() if isinstance(c, MetaSource)] + if all(s.is_read_only() for s in sources) and any( + s.effective_kind() == SOURCE_KIND_VIEW and s.sql_body() is not None + for s in sources + ): + continue seen: dict[str, MetaData] = {} for field in obj.children(): if not isinstance(field, MetaField) or field.sub_type == FIELD_SUBTYPE_OBJECT \ @@ -4230,8 +4250,12 @@ def _validate_column_name_collisions(root: MetaData, errors: list[MetaError]) -> code=ErrorCode.ERR_COLUMN_NAME_COLLISION, message=( f'fields "{first.name}" and "{field.name}" on "{obj.name}" both resolve ' - f'to physical column "{column}". Rename one field, or give one an ' - f"explicit @column so the two columns differ." + f'to physical column "{column}". ' + + ( + "Rename one field, or point one @column at a different column." + if _has_explicit_column(first) and _has_explicit_column(field) + else "Rename one field, or give one an explicit @column so the two columns differ." + ) ), envelope=field.source, )) diff --git a/server/python/tests/unit/test_column_name_collision_message.py b/server/python/tests/unit/test_column_name_collision_message.py new file mode 100644 index 0000000000..24245a0ce6 --- /dev/null +++ b/server/python/tests/unit/test_column_name_collision_message.py @@ -0,0 +1,77 @@ +"""ERR_COLUMN_NAME_COLLISION advice wording and the @sql view exemption. + +Mirrors ``server/typescript/packages/metadata/test/column-name-collision-message.test.ts``. +""" +from __future__ import annotations + +import json + +from metaobjects import load_string +from metaobjects.errors import ErrorCode + +TABLE = {"source.rdb": {"@kind": "table", "@table": "account"}} + + +def _collision_messages(source: dict, field_a: dict, field_b: dict) -> list[str]: + doc = { + "metadata.root": { + "package": "demo", + "children": [ + { + "object.entity": { + "name": "Account", + "children": [ + source, + {"field.long": {"name": "id"}}, + field_a, + field_b, + {"identity.primary": {"name": "id", "@fields": ["id"]}}, + ], + } + } + ], + } + } + result = load_string(json.dumps(doc)) + return [e.message for e in result.errors if e.code == ErrorCode.ERR_COLUMN_NAME_COLLISION] + + +def test_two_explicit_columns_on_one_column_do_not_suggest_adding_a_column() -> None: + (msg,) = _collision_messages( + TABLE, + {"field.string": {"name": "userName", "@column": "username"}}, + {"field.string": {"name": "displayName", "@column": "username"}}, + ) + assert "point one @column at a different column" in msg + assert "give one an explicit @column" not in msg + + +def test_implicit_collision_still_suggests_an_explicit_column() -> None: + (msg,) = _collision_messages( + TABLE, + {"field.string": {"name": "userId"}}, + {"field.string": {"name": "userID"}}, + ) + assert "give one an explicit @column" in msg + + +def test_sql_view_may_share_a_column_between_fields() -> None: + doc = { + "metadata.root": { + "package": "demo", + "children": [ + { + "object.projection": { + "name": "UserView", + "children": [ + {"source.rdb": {"@kind": "view", "@view": "v", "@sql": "SELECT id, username FROM t"}}, + {"field.long": {"name": "id", "@column": "id"}}, + {"field.string": {"name": "userName", "@column": "username"}}, + {"field.string": {"name": "displayName", "@column": "username"}}, + ], + } + } + ], + } + } + assert load_string(json.dumps(doc)).errors == [] diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 116eed45a8..3d72cc712b 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -87,7 +87,8 @@ import { FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, } from "../core/field/field-constants.js"; -import { FIELD_ATTR_DB_INDEXED, IDENTITY_ATTR_EXPR } from "../persistence/db/db-constants.js"; +import { FIELD_ATTR_COLUMN, FIELD_ATTR_DB_INDEXED, IDENTITY_ATTR_EXPR } from "../persistence/db/db-constants.js"; +import { SOURCE_KIND_VIEW } from "../persistence/source/source-constants.js"; import { IDENTITY_ATTR_FIELDS, IDENTITY_SUBTYPE_REFERENCE, @@ -2777,13 +2778,33 @@ export function validateRetiredRequirementLinks(root: MetaData): ParseError[] { // object generates nothing); derived fields (origin.*) and field.object (which may // flatten to several columns) are not columns of this table and are skipped. // ADR-0039: effective fields, so an inherited field collides like an own one. +// Exempt: an object whose every source is read-only and at least one is a +// `source.rdb @kind: view` with an `@sql` body. The author's SQL defines that view's +// columns and the fields only READ them, so two fields on one column create no +// duplicate column and nothing can be written. A derived view (no `@sql`) emits a +// select list from its fields, and an object with a writable source has a real table +// whose columns MetaObjects creates; both stay checked. // --------------------------------------------------------------------------- +function readsThroughSqlView(obj: MetaData): boolean { + const sources = obj.children().filter((c): c is MetaSource => c instanceof MetaSource); + return ( + sources.every((s) => s.isReadOnly()) && + sources.some((s) => s.effectiveKind === SOURCE_KIND_VIEW && s.sqlBody !== undefined) + ); +} + +function hasExplicitColumn(field: MetaData): boolean { + const col = field.attr(FIELD_ATTR_COLUMN); + return typeof col === "string" && col !== ""; +} + export function validateColumnNameCollisions(root: MetaData): ParseError[] { const errors: ParseError[] = []; for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT)) { if (obj.isAbstract) continue; if (!obj.children().some((c) => c.type === TYPE_SOURCE)) continue; + if (readsThroughSqlView(obj)) continue; const seen = new Map(); for (const field of obj.children()) { if (!isMetaField(field) || field.subType === FIELD_SUBTYPE_OBJECT || field.isDerived()) continue; @@ -2796,7 +2817,10 @@ export function validateColumnNameCollisions(root: MetaData): ParseError[] { errors.push( new ParseError( `fields "${first.name}" and "${field.name}" on "${obj.name}" both resolve to physical column ` + - `"${column}". Rename one field, or give one an explicit @column so the two columns differ.`, + `"${column}". ` + + (hasExplicitColumn(first) && hasExplicitColumn(field) + ? "Rename one field, or point one @column at a different column." + : "Rename one field, or give one an explicit @column so the two columns differ."), { code: "ERR_COLUMN_NAME_COLLISION", source: field.source }, ), ); diff --git a/server/typescript/packages/metadata/test/column-name-collision-message.test.ts b/server/typescript/packages/metadata/test/column-name-collision-message.test.ts new file mode 100644 index 0000000000..45ece7f8cb --- /dev/null +++ b/server/typescript/packages/metadata/test/column-name-collision-message.test.ts @@ -0,0 +1,26 @@ +import { expect, test } from "bun:test"; +import { join } from "node:path"; +import { tsAdapter } from "./conformance/adapter.js"; + +const CORPUS = join(import.meta.dir, "../../../../../fixtures/conformance"); +const PROVIDERS = ["metaobjects-core-types", "metaobjects-db"]; + +async function messages(fixture: string): Promise { + const out = await tsAdapter.loadFixture(join(CORPUS, fixture, "input"), PROVIDERS); + return (out.errors ?? []).map((e) => e.message ?? ""); +} + +test("two explicit @column on one column: advice does not suggest adding @column", async () => { + const [msg] = await messages("error-column-name-collision-derived-view"); + expect(msg).toContain("point one @column at a different column"); + expect(msg).not.toContain("give one an explicit @column"); +}); + +test("implicit collision still suggests an explicit @column", async () => { + const [msg] = await messages("error-column-name-collision"); + expect(msg).toContain("give one an explicit @column"); +}); + +test("an @sql view may share a column between fields", async () => { + expect(await messages("column-name-shared-in-sql-view-ok")).toEqual([]); +}); From 37ca9384a4cbeac9c0cfb67c4912b789e6390ca0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 4 Nov 2026 01:04:50 -0500 Subject: [PATCH 04/51] feat: enforce cross-field validators in every port's generated create models (#530) * feat: generated record models enforce cross-field validators in every port validator.comparison/requiredWhen/presentIff/atLeastOne are now enforced by the full create model (Zod refinement, Bean Validation, IValidatableObject, Pydantic model_validator), mirroring the DB CHECK semantics. PATCH models and CHECK emission are unchanged. Gated by validation-conformance cross-field cases. * no-mistakes(review): Enforce cross-field rules on TPH subtype create in TS, Java, Kotlin * no-mistakes(review): Fix C# inherited Validate, TS array skip, behavioral tests * no-mistakes(review): Fix C# decimal/double comparison and Python array skip * no-mistakes(review): Parenthesize Kotlin cross-field getter; behavioral wrap test * no-mistakes(review): Python comparison rejects unorderable timestamps as validation error * no-mistakes(review): Replace TS zod cross-field source-text tests with execution * no-mistakes(review): Skip cross-field rules on server-owned fields in JVM/C# * no-mistakes(review): Import KotlinCrossFieldRules in ejectable Kotlin generators * no-mistakes(document): Updated stale cross-field gap note in docs/1.0-readiness.md to point at the new enforcement docs. Author already updated CHANGELOG, features/entities.md, the FR-036 spec, the authoring skill, the validation-conformance README and CONFORMANCE.md. --- CHANGELOG.md | 16 ++ .../skills/metaobjects-authoring/SKILL.md | 6 +- docs/1.0-readiness.md | 28 +- docs/CONFORMANCE.md | 2 +- docs/features/entities.md | 22 ++ ...ion-enforcement-and-fr-035-release-gaps.md | 17 +- .../codegen/generators/routes.ts | 9 +- .../codegen/templates/queries-file.ts | 9 +- .../codegen/templates/zod-validators.ts | 160 ++++++++++- .../showcase/codegen/generators/routes.ts | 9 +- .../codegen/templates/queries-file.ts | 9 +- .../codegen/templates/zod-validators.ts | 160 ++++++++++- .../skills/metaobjects-authoring/SKILL.md | 6 +- .../skills/metaobjects-authoring/SKILL.md | 6 +- .../skills/metaobjects-authoring/SKILL.md | 6 +- .../skills/metaobjects-authoring/SKILL.md | 6 +- .../skills/metaobjects-authoring/SKILL.md | 6 +- fixtures/validation-conformance/README.md | 24 ++ .../cross-field-cases.json | 263 ++++++++++++++++++ .../meta.cross-field.json | 33 +++ .../CrossFieldValidationConformanceTests.cs | 125 +++++++++ .../CrossFieldValidatorGenerationTests.cs | 232 +++++++++++++++ .../Generators/EntityGenerator.cs | 256 +++++++++++++++++ server/java/codegen-kotlin/pom.xml | 1 + .../generator/kotlin/GeneratorRegistry.kt | 8 +- .../generator/kotlin/KotlinCrossFieldRules.kt | 105 +++++++ .../generator/kotlin/KotlinEntityGenerator.kt | 48 ++++ .../kotlin/KotlinSpringControllerGenerator.kt | 12 + .../kotlin/KotlinCrossFieldValidationTest.kt | 94 +++++++ .../kotlin/ValidationConformanceTest.kt | 19 +- .../spring/SpringControllerGenerator.java | 20 +- .../generator/spring/SpringDtoGenerator.java | 11 +- .../spring/SpringGeneratorSupport.java | 147 ++++++++++ .../GeneratedTphCrossFieldCompileRunTest.java | 163 +++++++++++ .../SpringCrossFieldValidationTest.java | 132 +++++++++ .../spring/ValidationConformanceTest.java | 36 ++- .../TphCrossFieldControllerRunTest.kt | 112 ++++++++ .../metaobjects/mojo/EjectSupportTest.java | 3 +- .../codegen/generators/entity_model.py | 118 ++++++++ .../codegen/test_validation_conformance.py | 111 ++++++++ .../src/templates/form-file.ts | 9 +- .../codegen-ts/src/reference/routes.ts | 9 +- .../codegen-ts/src/templates/queries-file.ts | 9 +- .../codegen-ts/src/templates/routes-file.ts | 9 +- .../src/templates/zod-validators.ts | 160 ++++++++++- .../codegen-ts/test/tph-cross-field.test.ts | 180 ++++++++++++ .../codegen-ts/test/zod-cross-field.test.ts | 129 +++++++++ .../integration-tests/src/validation-cases.ts | 8 + ...validation-conformance-cross-field.test.ts | 69 +++++ .../test-generators/src/generators/routes.ts | 9 +- .../src/templates/queries-file.ts | 9 +- .../src/templates/zod-validators.ts | 160 ++++++++++- 52 files changed, 3207 insertions(+), 103 deletions(-) create mode 100644 fixtures/validation-conformance/cross-field-cases.json create mode 100644 fixtures/validation-conformance/meta.cross-field.json create mode 100644 server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidatorGenerationTests.cs create mode 100644 server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinCrossFieldRules.kt create mode 100644 server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinCrossFieldValidationTest.kt create mode 100644 server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/GeneratedTphCrossFieldCompileRunTest.java create mode 100644 server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCrossFieldValidationTest.java create mode 100644 server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/TphCrossFieldControllerRunTest.kt create mode 100644 server/typescript/packages/codegen-ts/test/tph-cross-field.test.ts create mode 100644 server/typescript/packages/codegen-ts/test/zod-cross-field.test.ts create mode 100644 server/typescript/packages/integration-tests/test/validation-conformance-cross-field.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d218fd9a9a..2726877493 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,22 @@ here.** ## [Unreleased] +### Added + +- **Generated record models enforce the four cross-field validators in every port.** + `validator.comparison`, `validator.requiredWhen`, `validator.presentIff` and + `validator.atLeastOne` used to render only as DB `CHECK` constraints, so a store with no `CHECK` + support (a graph or document database) enforced none of them and the application had to repeat the + rules in its writer. The full create/insert model now enforces them with the language's native + mechanism: a Zod refinement on the insert schema (TypeScript), a class-level Bean Validation + constraint on the create DTO (Java, Kotlin), `IValidatableObject` (C#) and a Pydantic + `model_validator` (Python). Semantics mirror the `CHECK` derivation: null-safe, `comparison` passes + when either side is null, `@equals` is read per the gating field's subtype. PATCH and + partial-update models are unchanged (a partial body cannot see the merged row, so the database + `CHECK` remains the enforcement there), and `CHECK` emission is unchanged. A record that violates a + declared rule is now rejected at the model where it used to reach the database. Gated by + `fixtures/validation-conformance/cross-field-cases.json` in all five ports. + ### Fixed - **`ERR_COLUMN_NAME_COLLISION` no longer rejects a read-only view whose columns come from `@sql`.** diff --git a/agent-context/skills/metaobjects-authoring/SKILL.md b/agent-context/skills/metaobjects-authoring/SKILL.md index a1e709017f..008e5dae1b 100644 --- a/agent-context/skills/metaobjects-authoring/SKILL.md +++ b/agent-context/skills/metaobjects-authoring/SKILL.md @@ -426,7 +426,11 @@ behavior: Entity-scoped `validator.*` children declare invariants that reference sibling fields **by name** (the same name-reference pattern as `identity.*`). The backend derives the -enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored. +enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`, +and the generated full create/record model also enforces the rule in every port (Zod refinement, +Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a +store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them +(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there. | Subtype | Rule | Key attrs | |---|---|---| diff --git a/docs/1.0-readiness.md b/docs/1.0-readiness.md index b54be142ed..08ba4ef1d8 100644 --- a/docs/1.0-readiness.md +++ b/docs/1.0-readiness.md @@ -155,29 +155,11 @@ Status legend: ✅ done · 🔶 in progress · ⬜ not started · ❓ **[RATIFY] in all three non-TS ports; a Python runtime path dropped an inherited M:N) — assume more lurk, and lead every cross-port fix with a shared fixture. - **Known instance, measured 2026-09-06 — the four entity-scoped cross-field validators.** - `validator.comparison`, `requiredWhen`, `presentIff` and `atLeastOne` are registered - vocabulary in all five ports and are taught by the shipped `metaobjects-authoring` skill, - but their only enforcement is the database `CHECK` that TS-owned `migrate` emits (gated by - `migrate-ts/test/validator-check/cross-field.test.ts`, 7 tests). **No port's generated API - tier validates them:** Python's `entity_model.py` and C#'s `EntityGenerator.cs` dispatch - only on the four FIELD-scoped validators (`length`, `array`, `numeric`, `regex`), and the - shared `validation-conformance` corpus covers only those same four — **zero fixtures across - every behavioral corpus touch the cross-field family.** They are also four of the 13 entries - in `registry-conformance/coverage-report.json`'s `untestedSubTypes`, which is the same list - the `.base` defect hid in until `0.25.0`. - - Consequence for an adopter today: a request body violating a declared cross-field rule is - refused by the DATABASE, not by the API, in every port — a constraint violation rather than - a 400. - - **This does not block the cut**, and the reason is worth stating so it is not re-litigated: - the vocabulary is enforced (the CHECK reaches every port, because schema is TS-owned per - ADR-0015), and adding API-tier enforcement later changes no load verdict and no metadata — - it is additive, and reaches an adopter as a wrong request failing earlier and more clearly. - What must NOT happen is adding a cross-port `validation-conformance` fixture for these - before the ports implement the tier; that turns three lanes red to record a gap this bullet - already records. + **Known instance (measured 2026-09-06, resolved Unreleased).** The four entity-scoped cross-field + validators (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) were enforced only by the DB + `CHECK`. The generated record model now enforces them in every port; see + [features/entities.md](features/entities.md#cross-field-validators) and the CHANGELOG `[Unreleased]` entry. + They remain among the `untestedSubTypes` in `registry-conformance/coverage-report.json`, which tracks the registry, not the generated behavior. ## F. Adoption proof (the audit as readiness signal) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 16d963fd0e..6487032d76 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -38,7 +38,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 59 (53 query + 6 migration) | all 59; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` also on MySQL (a scenario's `engines:` key is exact) | 53 query (migrations TS-only, ADR-0015); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query (via Exposed); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query; the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query (pg8000); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | | [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 119 (31 core + 10 tph + 9 m2m + 5 jsonb + 2 write-through + 2 secret-fields + 12 projection + 37 report + 11 decimal) | ✓ (Fastify reference + generated lane); `report/` and `decimal/` also on SQLite, MySQL and D1 | ✓ (embedded HTTP + JDBC); `report/` and `decimal/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/` and `decimal/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/` and `decimal/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/` and `decimal/` also on SQLite and MySQL | | [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | -| [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | +| [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 20 cross-field cases (`cross-field-cases.json`, generated record model only) | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | | [`fixtures/registry-conformance/`](../fixtures/registry-conformance/) | 1 canonical manifest | ✓ (reference emitter) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/object-model-conformance/`](../fixtures/object-model-conformance/) | 1 shared metadata fixture (per-port scenarios) | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/codegen-conformance/`](../fixtures/codegen-conformance/) | 6 shared inputs; `shared-provided-enum` carries the enum-type decision table and `cross-package-binding` the reference-binding decision table (ADR-0059) every port answers | ✓ | ✓ | ✓ | ✓ | ✓ | diff --git a/docs/features/entities.md b/docs/features/entities.md index 74f96a2a36..5247997235 100644 --- a/docs/features/entities.md +++ b/docs/features/entities.md @@ -319,6 +319,28 @@ row = om.create("Author", {"name": "Ada", "bio": None}) found = om.find_by_id("Author", row["id"]) ``` +## Cross-field validators + +`validator.comparison`, `validator.requiredWhen`, `validator.presentIff` and `validator.atLeastOne` +are declared as children of the entity and reference sibling fields by name. They are enforced in +two places: + +- **The generated full record (create) model**, in every port, with the language's native + mechanism: a Zod refinement on the insert schema (TypeScript), a class-level Bean Validation + constraint on the create DTO (Java, Kotlin), `IValidatableObject` (C#) and a Pydantic + `model_validator` (Python). A store with no `CHECK` support, such as a graph or document + database, is therefore still covered. +- **A database `CHECK` constraint**, derived by `meta migrate`. + +The two share one set of semantics: absent or null is SQL `NULL`; `comparison` passes when either +side is null; `requiredWhen` is violated only when the gate equals `@equals` and the target is null; +`presentIff` requires the target to be present exactly when the gate equals `@equals`; `atLeastOne` +needs one non-null field. `@equals` is read per the gating field's subtype. The shared cases in +`fixtures/validation-conformance/cross-field-cases.json` gate all five ports. + +PATCH and partial-update models do **not** enforce these rules, because a partial body cannot see +the merged row. The database `CHECK` is the enforcement there. + ## Verified by The following conformance fixtures gate this feature's behavior across ports: diff --git a/docs/superpowers/specs/2026-07-14-fr-036-constraint-validation-enforcement-and-fr-035-release-gaps.md b/docs/superpowers/specs/2026-07-14-fr-036-constraint-validation-enforcement-and-fr-035-release-gaps.md index 728d593ac4..c03e51005a 100644 --- a/docs/superpowers/specs/2026-07-14-fr-036-constraint-validation-enforcement-and-fr-035-release-gaps.md +++ b/docs/superpowers/specs/2026-07-14-fr-036-constraint-validation-enforcement-and-fr-035-release-gaps.md @@ -50,10 +50,21 @@ has no empty-string case):** (no anchors) accepts `"xxABCyy"` on TS/Python, rejects on Java/Kotlin/C#. Ruling 2 pins **full-match**. **Field-scoped vs entity-scoped split is correct and load-bearing:** cross-field validators -(`comparison`, `presentIff`, `requiredWhen`, `atLeastOne`) render ONLY as TS-owned DB CHECK +(`comparison`, `presentIff`, `requiredWhen`, `atLeastOne`) were rendered ONLY as TS-owned DB CHECK constraints (`migrate-ts/src/expected-schema.ts`), never as jakarta/Zod — so they evaluate the MERGED -row after UPDATE and hold under PATCH with zero handler work. Do NOT add cross-field validation to any -port's handler. Per-field only. +row after UPDATE and hold under PATCH with zero handler work. PATCH and partial-update handlers still +add nothing: a partial body cannot see the merged row, so the DB CHECK stays the enforcement there. + +> **Amended (Unreleased) — record models now enforce cross-field rules.** The original reading above +> ("DB CHECK only") left a store with no CHECK constraints (a graph or document database, say) with +> no enforcement of these four validators at all. Every port's generated **full record model** — the +> create/insert shape — now also enforces them, in the language's native idiom: a Zod refinement on +> the insert schema (TS), a class-level Bean Validation constraint on the create DTO (Java, Kotlin), +> `IValidatableObject` on the create model (C#) and a Pydantic `model_validator(mode="after")` +> (Python). The semantics mirror the DB CHECK derivation exactly (null-safe; `comparison` passes when +> either side is null; `@equals` rendered per the gating field's subtype) and are gated by the shared +> `fixtures/validation-conformance/cross-field-cases.json` cases in all five port runners. PATCH and +> partial-update models are deliberately unchanged, and DB CHECK emission is unchanged. --- diff --git a/examples/advanced-modeling/codegen/generators/routes.ts b/examples/advanced-modeling/codegen/generators/routes.ts index 56a79d85b6..08d409771c 100644 --- a/examples/advanced-modeling/codegen/generators/routes.ts +++ b/examples/advanced-modeling/codegen/generators/routes.ts @@ -94,6 +94,7 @@ import { } from "@metaobjectsdev/codegen-ts/engine"; import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js"; import { isTphDiscriminatorBase, tphPlan } from "../templates/tph-discriminator.js"; +import { hasInsertRefinements } from "../templates/zod-validators.js"; // --- composition (OWNED) — assembles one .routes.ts. Change this to change the output. --- // Dispatch: a TPH discriminator base → polymorphic list/get + a per-subtype CRUD set; a @@ -621,7 +622,11 @@ function renderTphRoutes( const subFileSpec = entityModuleSpecifier( ctx.selfTarget, ctx.entityModuleTarget, effectivePackage(sub), sub.name, ctx.extStyle, ); - const subInsertSym = imp(`${sub.name}InsertSchema@${subFileSpec}`); + // A subtype with cross-field rules has a refined InsertSchema, which Zod will not + // `.omit()`; its codegen exports the discriminator-less refined body instead. + const subInsertBody = hasInsertRefinements(sub) + ? code`${imp(`${sub.name}InsertBodySchema@${subFileSpec}`)}` + : code`${imp(`${sub.name}InsertSchema@${subFileSpec}`)}.omit({ ${discField}: true })`; // FR-036 Program B: the per-subtype UPDATE must carry the FR-035 present-key // tristate (a non-@required subtype column accepts an explicit null → clears; // a @required column's explicit null is rejected). The subtype's own @@ -640,7 +645,7 @@ function renderTphRoutes( path: ${baseConstSym}.$path + ${JSON.stringify(`/${segment}`)}, db: ${dbSym}, table: ${tableSym}, - insertSchema: ${subInsertSym}.omit({ ${discField}: true }), + insertSchema: ${subInsertBody}, updateSchema: ${subUpdateSym}, filterAllowlist: ${subFilterSym}, sortAllowlist: ${subSortSym}, diff --git a/examples/advanced-modeling/codegen/templates/queries-file.ts b/examples/advanced-modeling/codegen/templates/queries-file.ts index e9e3c386d9..d7362d6181 100644 --- a/examples/advanced-modeling/codegen/templates/queries-file.ts +++ b/examples/advanced-modeling/codegen/templates/queries-file.ts @@ -28,7 +28,7 @@ import { isTphDiscriminatorBase, tphConcreteSubtypes } from "./tph-discriminator import { isProjection, isWriteThrough } from "@metaobjectsdev/codegen-ts/engine"; import { isReport } from "@metaobjectsdev/codegen-ts/engine"; import { hasItemRoute } from "@metaobjectsdev/codegen-ts/engine"; -import { hasAutoSetFields } from "./zod-validators.js"; +import { hasAutoSetFields, hasInsertRefinements } from "./zod-validators.js"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; /** @@ -372,6 +372,9 @@ export async function list${pluralize(baseName)}(db: Db, opts?: { limit?: number // the schema (schemaInputType), so a subtype module from an owned entity generator // that predates the `Create` alias still satisfies it. const subCreateSym = schemaInputType(subInsertSym); + // A refined (cross-field) InsertSchema has no `.partial()`; the partial update reads + // the unrefined shape, as an unrefined subtype's does. + const subPartialSym = hasInsertRefinements(sub) ? imp(`${sub.name}InsertBaseSchema@${subFileSpec}`) : subInsertSym; subtypeSections.push(code` export async function list${pluralize(sub.name)}(db: Db, opts?: { limit?: number; offset?: number }): Promise<${subTypeSym}[]> { @@ -395,7 +398,7 @@ ${supportsReturning(ctx.dialect) ? code`export async function create${sub.name}( } export async function update${sub.name}ById(db: Db, ${pkField}: ${pkType}, data: Partial<${subCreateSym}>): Promise<${subTypeSym} | null> { - const validated = ${subInsertSym}.partial().parse(data) as Record; + const validated = ${subPartialSym}.partial().parse(data) as Record; // The discriminator is immutable — a ${sub.name} can never become another subtype. const { [${JSON.stringify(discField)}]: _disc, ...safe } = validated; const [row] = await db.update(${tableSym}).set(safe) @@ -417,7 +420,7 @@ export async function create${sub.name}(db: Db, data: ${subCreateSym}): Promise< } export async function update${sub.name}ById(db: Db, ${pkField}: ${pkType}, data: Partial<${subCreateSym}>): Promise<${subTypeSym} | null> { - const validated = ${subInsertSym}.partial().parse(data) as Record; + const validated = ${subPartialSym}.partial().parse(data) as Record; // The discriminator is immutable — a ${sub.name} can never become another subtype. const { [${JSON.stringify(discField)}]: _disc, ...safe } = validated; if (Object.keys(safe).length > 0) { diff --git a/examples/advanced-modeling/codegen/templates/zod-validators.ts b/examples/advanced-modeling/codegen/templates/zod-validators.ts index ea4945feae..661966d8ea 100644 --- a/examples/advanced-modeling/codegen/templates/zod-validators.ts +++ b/examples/advanced-modeling/codegen/templates/zod-validators.ts @@ -28,6 +28,10 @@ import { FIELD_ATTR_DB_COLUMN_TYPE, DB_COLUMN_TYPE_JSONB, AUTO_SET_ON_CREATE, AUTO_SET_ON_UPDATE, VALIDATOR_ATTR_MAX, VALIDATOR_ATTR_MIN, VALIDATOR_ATTR_PATTERN, + VALIDATOR_SUBTYPE_COMPARISON, VALIDATOR_SUBTYPE_REQUIRED_WHEN, + VALIDATOR_SUBTYPE_PRESENT_IFF, VALIDATOR_SUBTYPE_AT_LEAST_ONE, + VALIDATOR_ATTR_LEFT, VALIDATOR_ATTR_OP, VALIDATOR_ATTR_RIGHT, + VALIDATOR_ATTR_FIELD, VALIDATOR_ATTR_WHEN, VALIDATOR_ATTR_EQUALS, VALIDATOR_ATTR_FIELDS, GENERATION_INCREMENT, GENERATION_UUID, OBJECT_ATTR_DISCRIMINATOR, OBJECT_ATTR_DISCRIMINATOR_VALUE, OBJECT_SUBTYPE_VALUE, @@ -256,6 +260,135 @@ function isInsertRequiredPk(field: MetaField, assignedPk: Set): boolean return field.attr(FIELD_ATTR_DEFAULT) === undefined; } +// ── Entity-scoped cross-field validators on the full (insert) record ────────── +// validator.comparison / requiredWhen / presentIff / atLeastOne are enforced on the +// INSERT-shaped schemas only, as one `.superRefine`. A PATCH body cannot see the merged +// row, so the Update schema is deliberately left alone (the DB CHECK stays the guard +// there). Semantics mirror the migrate-ts CHECK derivation: absent / null / undefined is +// SQL NULL, "" is NOT null; a comparison with a NULL side passes; requiredWhen is violated +// only when the gate EQUALS the literal and the target is null; presentIff requires +// (target != null) === (gate equals literal), a null gate being "not equal". + +const CROSS_FIELD_OPS: Record = { + gt: ">", gte: ">=", lt: "<", lte: "<=", ne: "!==", eq: "===", +}; + +const NUMERIC_SUBTYPES: ReadonlySet = new Set([ + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, +]); + +/** Names of the fields the INSERT-shaped schemas carry (same skip rules as the emitters). */ +function insertSchemaFieldNameSet(obj: MetaObject): Set { + const autoGen = autoGenPkFieldNames(obj); + const out = new Set(); + for (const f of obj.fields()) { + if (autoGen.has(f.name)) continue; + if (isReadOnlyMutability(f) || f.isDerived()) continue; + out.add(f.name); + } + return out; +} + +/** The @equals literal as a TS expression, typed by the gating field's subtype. */ +function crossFieldLiteral(raw: unknown, when: MetaField): { lit: string; numeric: boolean } { + const s = String(raw); + if (when.subType === FIELD_SUBTYPE_BOOLEAN) { + return { lit: s === "true" || s === "1" || s === "TRUE" ? "true" : "false", numeric: false }; + } + if (NUMERIC_SUBTYPES.has(when.subType) && /^-?\d+(\.\d+)?$/.test(s)) return { lit: s, numeric: true }; + return { lit: JSON.stringify(s), numeric: false }; +} + +/** Does this object declare at least one cross-field validator that will be enforced + * on its insert schema? Exported so the route, query and form emitters can tell a refined + * schema (which Zod will not `.omit()` or `.partial()`) from a plain object; a refined TPH + * subtype also exports `InsertBaseSchema` (unrefined) and `InsertBodySchema` + * (refined, pinned discriminator omitted). */ +export function hasInsertRefinements(obj: MetaObject): boolean { + return crossFieldRefinementBody(obj).length > 0; +} + +function crossFieldRefinementBody(obj: MetaObject): string[] { + const inSchema = insertSchemaFieldNameSet(obj); + const byName = new Map(obj.fields().map((f) => [f.name, f] as const)); + // A reference must name a field that exists AND is in the insert schema; otherwise skip + // the validator (migrate skips on a missing field; a readOnly/derived/auto-PK field is + // never in the body, so enforcing on it would reject every create). + const ref = (name: unknown): MetaField | undefined => { + if (typeof name !== "string" || !inSchema.has(name)) return undefined; + return byName.get(name); + }; + // A TPH subtype's discriminator is pinned to one literal, so the rule reads that literal: + // the same refinement then holds whether or not the body carries the discriminator. + const pin = tphDiscriminatorPin(obj); + const acc = (f: MetaField) => pin !== undefined && f.name === pin.fieldName + ? JSON.stringify(pin.value) + : `row[${JSON.stringify(f.name)}]`; + const issue = (path: string, msg: string) => + `ctx.addIssue({ code: "custom", path: [${path}], message: ${JSON.stringify(msg)} });`; + const blocks: string[] = []; + // ADR-0039: entity.validators() is the resolving accessor (never ownValidators). + for (const v of obj.validators()) { + switch (v.subType) { + case VALIDATOR_SUBTYPE_COMPARISON: { + const left = ref(v.attr(VALIDATOR_ATTR_LEFT)); + const right = ref(v.attr(VALIDATOR_ATTR_RIGHT)); + const opName = String(v.attr(VALIDATOR_ATTR_OP)); + const op = CROSS_FIELD_OPS[opName]; + if (!left || !right || !op || left.resolvedIsArray() || right.resolvedIsArray()) break; + const numeric = NUMERIC_SUBTYPES.has(left.subType); + const c = numeric + ? "Number(l) - Number(r)" + : "l instanceof Date && r instanceof Date ? l.getTime() - r.getTime() : String(l) < String(r) ? -1 : String(l) > String(r) ? 1 : 0"; + blocks.push( + ` {\n const l: unknown = ${acc(left)};\n const r: unknown = ${acc(right)};\n` + + ` if (l != null && r != null) {\n const c = ${c};\n` + + ` if (!(c ${op} 0)) ${issue(JSON.stringify(left.name), `${left.name} must be ${opName} ${right.name}`)}\n }\n }`, + ); + break; + } + case VALIDATOR_SUBTYPE_REQUIRED_WHEN: + case VALIDATOR_SUBTYPE_PRESENT_IFF: { + const target = ref(v.attr(VALIDATOR_ATTR_FIELD)); + const when = ref(v.attr(VALIDATOR_ATTR_WHEN)); + if (!target || !when || when.resolvedIsArray()) break; + const { lit, numeric } = crossFieldLiteral(v.attr(VALIDATOR_ATTR_EQUALS), when); + const gate = numeric ? `g != null && Number(g) === ${lit}` : `g === ${lit}`; + const path = JSON.stringify(target.name); + const decl = ` const g: unknown = ${acc(when)};\n const t: unknown = ${acc(target)};\n const open = ${gate};\n`; + if (v.subType === VALIDATOR_SUBTYPE_REQUIRED_WHEN) { + blocks.push(` {\n${decl} if (open && t == null) ${issue(path, `${target.name} is required when ${when.name} is ${String(v.attr(VALIDATOR_ATTR_EQUALS))}`)}\n }`); + } else { + blocks.push(` {\n${decl} if ((t != null) !== open) ${issue(path, `${target.name} must be present if and only if ${when.name} is ${String(v.attr(VALIDATOR_ATTR_EQUALS))}`)}\n }`); + } + break; + } + case VALIDATOR_SUBTYPE_AT_LEAST_ONE: { + const raw = v.attr(VALIDATOR_ATTR_FIELDS); + const names = Array.isArray(raw) ? raw : (typeof raw === "string" ? [raw] : []); + const refs = names.map(ref); + if (refs.length === 0 || refs.some((r) => r === undefined)) break; + const fields = refs as MetaField[]; + const anyPresent = fields.map((f) => `${acc(f)} != null`).join(" || "); + blocks.push(` if (!(${anyPresent})) ${issue(JSON.stringify(fields[0]!.name), `at least one of ${fields.map((f) => f.name).join(", ")} is required`)}`); + break; + } + default: + break; + } + } + return blocks; +} + +/** `.superRefine(...)` suffix for an insert-shaped schema, or "" when the object has no + * enforceable cross-field validator (output is then byte-identical to before). */ +function insertRefinementSuffix(obj: MetaObject): string { + const blocks = crossFieldRefinementBody(obj); + if (blocks.length === 0) return ""; + return `.superRefine((row, ctx) => {\n${blocks.join("\n")}\n})`; +} + /** * Emit ONLY the `InsertSchema`. Used by the value-object file emitter * for metaobjects with no writable source.rdb — those have no PATCH/update @@ -322,7 +455,7 @@ export function renderInsertSchemaOnly(obj: MetaObject, ctx?: RenderContext): Co return code` ${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({ ${joinCode(insertFieldLines, { on: ",\n" })} -}); +})${insertRefinementSuffix(obj)}; `; } @@ -535,6 +668,25 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code const docs = renderDocsFor(obj); const docsPrefix = docs ? `${docs}\n` : ""; + // A Zod object carrying refinements cannot be `.omit()`ed or `.partial()`ed, and a TPH + // subtype's route and form omit the pinned discriminator while its update query takes a + // partial. So when both apply, the unrefined shape is exported as `InsertBaseSchema` + // and refined twice: as `InsertSchema` and, discriminator omitted, as + // `InsertBodySchema`. + const refineSuffix = insertRefinementSuffix(obj); + const insertDecl = refineSuffix !== "" && tphPin !== undefined + ? code`export const ${objName}InsertBaseSchema = ${z}.object({ +${joinCode(insertFieldLines, { on: ",\n" })} +}); + +${docsPrefix}export const ${insertSchemaName} = ${objName}InsertBaseSchema${refineSuffix}; + +/** ${insertSchemaName} without the pinned \`${tphPin.fieldName}\` — the body a per-subtype route accepts. */ +export const ${objName}InsertBodySchema = ${objName}InsertBaseSchema.omit({ ${tphPin.fieldName}: true })${refineSuffix};` + : code`${docsPrefix}export const ${insertSchemaName} = ${z}.object({ +${joinCode(insertFieldLines, { on: ",\n" })} +})${refineSuffix};`; + // #203 — emit the preserving insert-shape only for @autoSet entities (nothing to // preserve otherwise). Backs `insertPreserving` (import/restore/replication). const preservingBlock = emitPreserving @@ -545,16 +697,14 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code * (no create-time now() stamp) so the caller's original values are preserved. */ export const ${preservingSchemaName} = ${z}.object({ ${joinCode(preservingFieldLines, { on: ",\n" })} -}); +})${insertRefinementSuffix(obj)}; /** Typed input of \`insertPreserving${objName}\` — ${preservingSchemaName}'s pre-transform shape. */ export type ${objName}CreatePreserving = ${z}.input;` : code``; return code` -${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({ -${joinCode(insertFieldLines, { on: ",\n" })} -}); +${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${insertDecl} ${docsPrefix}export const ${updateSchemaName} = ${z}.object({ ${joinCode(updateFieldLines, { on: ",\n" })} diff --git a/examples/showcase/codegen/generators/routes.ts b/examples/showcase/codegen/generators/routes.ts index 56a79d85b6..08d409771c 100644 --- a/examples/showcase/codegen/generators/routes.ts +++ b/examples/showcase/codegen/generators/routes.ts @@ -94,6 +94,7 @@ import { } from "@metaobjectsdev/codegen-ts/engine"; import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js"; import { isTphDiscriminatorBase, tphPlan } from "../templates/tph-discriminator.js"; +import { hasInsertRefinements } from "../templates/zod-validators.js"; // --- composition (OWNED) — assembles one .routes.ts. Change this to change the output. --- // Dispatch: a TPH discriminator base → polymorphic list/get + a per-subtype CRUD set; a @@ -621,7 +622,11 @@ function renderTphRoutes( const subFileSpec = entityModuleSpecifier( ctx.selfTarget, ctx.entityModuleTarget, effectivePackage(sub), sub.name, ctx.extStyle, ); - const subInsertSym = imp(`${sub.name}InsertSchema@${subFileSpec}`); + // A subtype with cross-field rules has a refined InsertSchema, which Zod will not + // `.omit()`; its codegen exports the discriminator-less refined body instead. + const subInsertBody = hasInsertRefinements(sub) + ? code`${imp(`${sub.name}InsertBodySchema@${subFileSpec}`)}` + : code`${imp(`${sub.name}InsertSchema@${subFileSpec}`)}.omit({ ${discField}: true })`; // FR-036 Program B: the per-subtype UPDATE must carry the FR-035 present-key // tristate (a non-@required subtype column accepts an explicit null → clears; // a @required column's explicit null is rejected). The subtype's own @@ -640,7 +645,7 @@ function renderTphRoutes( path: ${baseConstSym}.$path + ${JSON.stringify(`/${segment}`)}, db: ${dbSym}, table: ${tableSym}, - insertSchema: ${subInsertSym}.omit({ ${discField}: true }), + insertSchema: ${subInsertBody}, updateSchema: ${subUpdateSym}, filterAllowlist: ${subFilterSym}, sortAllowlist: ${subSortSym}, diff --git a/examples/showcase/codegen/templates/queries-file.ts b/examples/showcase/codegen/templates/queries-file.ts index e9e3c386d9..d7362d6181 100644 --- a/examples/showcase/codegen/templates/queries-file.ts +++ b/examples/showcase/codegen/templates/queries-file.ts @@ -28,7 +28,7 @@ import { isTphDiscriminatorBase, tphConcreteSubtypes } from "./tph-discriminator import { isProjection, isWriteThrough } from "@metaobjectsdev/codegen-ts/engine"; import { isReport } from "@metaobjectsdev/codegen-ts/engine"; import { hasItemRoute } from "@metaobjectsdev/codegen-ts/engine"; -import { hasAutoSetFields } from "./zod-validators.js"; +import { hasAutoSetFields, hasInsertRefinements } from "./zod-validators.js"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; /** @@ -372,6 +372,9 @@ export async function list${pluralize(baseName)}(db: Db, opts?: { limit?: number // the schema (schemaInputType), so a subtype module from an owned entity generator // that predates the `Create` alias still satisfies it. const subCreateSym = schemaInputType(subInsertSym); + // A refined (cross-field) InsertSchema has no `.partial()`; the partial update reads + // the unrefined shape, as an unrefined subtype's does. + const subPartialSym = hasInsertRefinements(sub) ? imp(`${sub.name}InsertBaseSchema@${subFileSpec}`) : subInsertSym; subtypeSections.push(code` export async function list${pluralize(sub.name)}(db: Db, opts?: { limit?: number; offset?: number }): Promise<${subTypeSym}[]> { @@ -395,7 +398,7 @@ ${supportsReturning(ctx.dialect) ? code`export async function create${sub.name}( } export async function update${sub.name}ById(db: Db, ${pkField}: ${pkType}, data: Partial<${subCreateSym}>): Promise<${subTypeSym} | null> { - const validated = ${subInsertSym}.partial().parse(data) as Record; + const validated = ${subPartialSym}.partial().parse(data) as Record; // The discriminator is immutable — a ${sub.name} can never become another subtype. const { [${JSON.stringify(discField)}]: _disc, ...safe } = validated; const [row] = await db.update(${tableSym}).set(safe) @@ -417,7 +420,7 @@ export async function create${sub.name}(db: Db, data: ${subCreateSym}): Promise< } export async function update${sub.name}ById(db: Db, ${pkField}: ${pkType}, data: Partial<${subCreateSym}>): Promise<${subTypeSym} | null> { - const validated = ${subInsertSym}.partial().parse(data) as Record; + const validated = ${subPartialSym}.partial().parse(data) as Record; // The discriminator is immutable — a ${sub.name} can never become another subtype. const { [${JSON.stringify(discField)}]: _disc, ...safe } = validated; if (Object.keys(safe).length > 0) { diff --git a/examples/showcase/codegen/templates/zod-validators.ts b/examples/showcase/codegen/templates/zod-validators.ts index ea4945feae..661966d8ea 100644 --- a/examples/showcase/codegen/templates/zod-validators.ts +++ b/examples/showcase/codegen/templates/zod-validators.ts @@ -28,6 +28,10 @@ import { FIELD_ATTR_DB_COLUMN_TYPE, DB_COLUMN_TYPE_JSONB, AUTO_SET_ON_CREATE, AUTO_SET_ON_UPDATE, VALIDATOR_ATTR_MAX, VALIDATOR_ATTR_MIN, VALIDATOR_ATTR_PATTERN, + VALIDATOR_SUBTYPE_COMPARISON, VALIDATOR_SUBTYPE_REQUIRED_WHEN, + VALIDATOR_SUBTYPE_PRESENT_IFF, VALIDATOR_SUBTYPE_AT_LEAST_ONE, + VALIDATOR_ATTR_LEFT, VALIDATOR_ATTR_OP, VALIDATOR_ATTR_RIGHT, + VALIDATOR_ATTR_FIELD, VALIDATOR_ATTR_WHEN, VALIDATOR_ATTR_EQUALS, VALIDATOR_ATTR_FIELDS, GENERATION_INCREMENT, GENERATION_UUID, OBJECT_ATTR_DISCRIMINATOR, OBJECT_ATTR_DISCRIMINATOR_VALUE, OBJECT_SUBTYPE_VALUE, @@ -256,6 +260,135 @@ function isInsertRequiredPk(field: MetaField, assignedPk: Set): boolean return field.attr(FIELD_ATTR_DEFAULT) === undefined; } +// ── Entity-scoped cross-field validators on the full (insert) record ────────── +// validator.comparison / requiredWhen / presentIff / atLeastOne are enforced on the +// INSERT-shaped schemas only, as one `.superRefine`. A PATCH body cannot see the merged +// row, so the Update schema is deliberately left alone (the DB CHECK stays the guard +// there). Semantics mirror the migrate-ts CHECK derivation: absent / null / undefined is +// SQL NULL, "" is NOT null; a comparison with a NULL side passes; requiredWhen is violated +// only when the gate EQUALS the literal and the target is null; presentIff requires +// (target != null) === (gate equals literal), a null gate being "not equal". + +const CROSS_FIELD_OPS: Record = { + gt: ">", gte: ">=", lt: "<", lte: "<=", ne: "!==", eq: "===", +}; + +const NUMERIC_SUBTYPES: ReadonlySet = new Set([ + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, +]); + +/** Names of the fields the INSERT-shaped schemas carry (same skip rules as the emitters). */ +function insertSchemaFieldNameSet(obj: MetaObject): Set { + const autoGen = autoGenPkFieldNames(obj); + const out = new Set(); + for (const f of obj.fields()) { + if (autoGen.has(f.name)) continue; + if (isReadOnlyMutability(f) || f.isDerived()) continue; + out.add(f.name); + } + return out; +} + +/** The @equals literal as a TS expression, typed by the gating field's subtype. */ +function crossFieldLiteral(raw: unknown, when: MetaField): { lit: string; numeric: boolean } { + const s = String(raw); + if (when.subType === FIELD_SUBTYPE_BOOLEAN) { + return { lit: s === "true" || s === "1" || s === "TRUE" ? "true" : "false", numeric: false }; + } + if (NUMERIC_SUBTYPES.has(when.subType) && /^-?\d+(\.\d+)?$/.test(s)) return { lit: s, numeric: true }; + return { lit: JSON.stringify(s), numeric: false }; +} + +/** Does this object declare at least one cross-field validator that will be enforced + * on its insert schema? Exported so the route, query and form emitters can tell a refined + * schema (which Zod will not `.omit()` or `.partial()`) from a plain object; a refined TPH + * subtype also exports `InsertBaseSchema` (unrefined) and `InsertBodySchema` + * (refined, pinned discriminator omitted). */ +export function hasInsertRefinements(obj: MetaObject): boolean { + return crossFieldRefinementBody(obj).length > 0; +} + +function crossFieldRefinementBody(obj: MetaObject): string[] { + const inSchema = insertSchemaFieldNameSet(obj); + const byName = new Map(obj.fields().map((f) => [f.name, f] as const)); + // A reference must name a field that exists AND is in the insert schema; otherwise skip + // the validator (migrate skips on a missing field; a readOnly/derived/auto-PK field is + // never in the body, so enforcing on it would reject every create). + const ref = (name: unknown): MetaField | undefined => { + if (typeof name !== "string" || !inSchema.has(name)) return undefined; + return byName.get(name); + }; + // A TPH subtype's discriminator is pinned to one literal, so the rule reads that literal: + // the same refinement then holds whether or not the body carries the discriminator. + const pin = tphDiscriminatorPin(obj); + const acc = (f: MetaField) => pin !== undefined && f.name === pin.fieldName + ? JSON.stringify(pin.value) + : `row[${JSON.stringify(f.name)}]`; + const issue = (path: string, msg: string) => + `ctx.addIssue({ code: "custom", path: [${path}], message: ${JSON.stringify(msg)} });`; + const blocks: string[] = []; + // ADR-0039: entity.validators() is the resolving accessor (never ownValidators). + for (const v of obj.validators()) { + switch (v.subType) { + case VALIDATOR_SUBTYPE_COMPARISON: { + const left = ref(v.attr(VALIDATOR_ATTR_LEFT)); + const right = ref(v.attr(VALIDATOR_ATTR_RIGHT)); + const opName = String(v.attr(VALIDATOR_ATTR_OP)); + const op = CROSS_FIELD_OPS[opName]; + if (!left || !right || !op || left.resolvedIsArray() || right.resolvedIsArray()) break; + const numeric = NUMERIC_SUBTYPES.has(left.subType); + const c = numeric + ? "Number(l) - Number(r)" + : "l instanceof Date && r instanceof Date ? l.getTime() - r.getTime() : String(l) < String(r) ? -1 : String(l) > String(r) ? 1 : 0"; + blocks.push( + ` {\n const l: unknown = ${acc(left)};\n const r: unknown = ${acc(right)};\n` + + ` if (l != null && r != null) {\n const c = ${c};\n` + + ` if (!(c ${op} 0)) ${issue(JSON.stringify(left.name), `${left.name} must be ${opName} ${right.name}`)}\n }\n }`, + ); + break; + } + case VALIDATOR_SUBTYPE_REQUIRED_WHEN: + case VALIDATOR_SUBTYPE_PRESENT_IFF: { + const target = ref(v.attr(VALIDATOR_ATTR_FIELD)); + const when = ref(v.attr(VALIDATOR_ATTR_WHEN)); + if (!target || !when || when.resolvedIsArray()) break; + const { lit, numeric } = crossFieldLiteral(v.attr(VALIDATOR_ATTR_EQUALS), when); + const gate = numeric ? `g != null && Number(g) === ${lit}` : `g === ${lit}`; + const path = JSON.stringify(target.name); + const decl = ` const g: unknown = ${acc(when)};\n const t: unknown = ${acc(target)};\n const open = ${gate};\n`; + if (v.subType === VALIDATOR_SUBTYPE_REQUIRED_WHEN) { + blocks.push(` {\n${decl} if (open && t == null) ${issue(path, `${target.name} is required when ${when.name} is ${String(v.attr(VALIDATOR_ATTR_EQUALS))}`)}\n }`); + } else { + blocks.push(` {\n${decl} if ((t != null) !== open) ${issue(path, `${target.name} must be present if and only if ${when.name} is ${String(v.attr(VALIDATOR_ATTR_EQUALS))}`)}\n }`); + } + break; + } + case VALIDATOR_SUBTYPE_AT_LEAST_ONE: { + const raw = v.attr(VALIDATOR_ATTR_FIELDS); + const names = Array.isArray(raw) ? raw : (typeof raw === "string" ? [raw] : []); + const refs = names.map(ref); + if (refs.length === 0 || refs.some((r) => r === undefined)) break; + const fields = refs as MetaField[]; + const anyPresent = fields.map((f) => `${acc(f)} != null`).join(" || "); + blocks.push(` if (!(${anyPresent})) ${issue(JSON.stringify(fields[0]!.name), `at least one of ${fields.map((f) => f.name).join(", ")} is required`)}`); + break; + } + default: + break; + } + } + return blocks; +} + +/** `.superRefine(...)` suffix for an insert-shaped schema, or "" when the object has no + * enforceable cross-field validator (output is then byte-identical to before). */ +function insertRefinementSuffix(obj: MetaObject): string { + const blocks = crossFieldRefinementBody(obj); + if (blocks.length === 0) return ""; + return `.superRefine((row, ctx) => {\n${blocks.join("\n")}\n})`; +} + /** * Emit ONLY the `InsertSchema`. Used by the value-object file emitter * for metaobjects with no writable source.rdb — those have no PATCH/update @@ -322,7 +455,7 @@ export function renderInsertSchemaOnly(obj: MetaObject, ctx?: RenderContext): Co return code` ${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({ ${joinCode(insertFieldLines, { on: ",\n" })} -}); +})${insertRefinementSuffix(obj)}; `; } @@ -535,6 +668,25 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code const docs = renderDocsFor(obj); const docsPrefix = docs ? `${docs}\n` : ""; + // A Zod object carrying refinements cannot be `.omit()`ed or `.partial()`ed, and a TPH + // subtype's route and form omit the pinned discriminator while its update query takes a + // partial. So when both apply, the unrefined shape is exported as `InsertBaseSchema` + // and refined twice: as `InsertSchema` and, discriminator omitted, as + // `InsertBodySchema`. + const refineSuffix = insertRefinementSuffix(obj); + const insertDecl = refineSuffix !== "" && tphPin !== undefined + ? code`export const ${objName}InsertBaseSchema = ${z}.object({ +${joinCode(insertFieldLines, { on: ",\n" })} +}); + +${docsPrefix}export const ${insertSchemaName} = ${objName}InsertBaseSchema${refineSuffix}; + +/** ${insertSchemaName} without the pinned \`${tphPin.fieldName}\` — the body a per-subtype route accepts. */ +export const ${objName}InsertBodySchema = ${objName}InsertBaseSchema.omit({ ${tphPin.fieldName}: true })${refineSuffix};` + : code`${docsPrefix}export const ${insertSchemaName} = ${z}.object({ +${joinCode(insertFieldLines, { on: ",\n" })} +})${refineSuffix};`; + // #203 — emit the preserving insert-shape only for @autoSet entities (nothing to // preserve otherwise). Backs `insertPreserving` (import/restore/replication). const preservingBlock = emitPreserving @@ -545,16 +697,14 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code * (no create-time now() stamp) so the caller's original values are preserved. */ export const ${preservingSchemaName} = ${z}.object({ ${joinCode(preservingFieldLines, { on: ",\n" })} -}); +})${insertRefinementSuffix(obj)}; /** Typed input of \`insertPreserving${objName}\` — ${preservingSchemaName}'s pre-transform shape. */ export type ${objName}CreatePreserving = ${z}.input;` : code``; return code` -${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({ -${joinCode(insertFieldLines, { on: ",\n" })} -}); +${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${insertDecl} ${docsPrefix}export const ${updateSchemaName} = ${z}.object({ ${joinCode(updateFieldLines, { on: ",\n" })} diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index a1e709017f..008e5dae1b 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -426,7 +426,11 @@ behavior: Entity-scoped `validator.*` children declare invariants that reference sibling fields **by name** (the same name-reference pattern as `identity.*`). The backend derives the -enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored. +enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`, +and the generated full create/record model also enforces the rule in every port (Zod refinement, +Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a +store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them +(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there. | Subtype | Rule | Key attrs | |---|---|---| diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md index a1e709017f..008e5dae1b 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -426,7 +426,11 @@ behavior: Entity-scoped `validator.*` children declare invariants that reference sibling fields **by name** (the same name-reference pattern as `identity.*`). The backend derives the -enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored. +enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`, +and the generated full create/record model also enforces the rule in every port (Zod refinement, +Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a +store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them +(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there. | Subtype | Rule | Key attrs | |---|---|---| diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md index a1e709017f..008e5dae1b 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -426,7 +426,11 @@ behavior: Entity-scoped `validator.*` children declare invariants that reference sibling fields **by name** (the same name-reference pattern as `identity.*`). The backend derives the -enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored. +enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`, +and the generated full create/record model also enforces the rule in every port (Zod refinement, +Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a +store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them +(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there. | Subtype | Rule | Key attrs | |---|---|---| diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index a1e709017f..008e5dae1b 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -426,7 +426,11 @@ behavior: Entity-scoped `validator.*` children declare invariants that reference sibling fields **by name** (the same name-reference pattern as `identity.*`). The backend derives the -enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored. +enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`, +and the generated full create/record model also enforces the rule in every port (Zod refinement, +Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a +store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them +(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there. | Subtype | Rule | Key attrs | |---|---|---| diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md index a1e709017f..008e5dae1b 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -426,7 +426,11 @@ behavior: Entity-scoped `validator.*` children declare invariants that reference sibling fields **by name** (the same name-reference pattern as `identity.*`). The backend derives the -enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored. +enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`, +and the generated full create/record model also enforces the rule in every port (Zod refinement, +Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a +store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them +(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there. | Subtype | Rule | Key attrs | |---|---|---| diff --git a/fixtures/validation-conformance/README.md b/fixtures/validation-conformance/README.md index 0bb31d696b..b6fc8ca33e 100644 --- a/fixtures/validation-conformance/README.md +++ b/fixtures/validation-conformance/README.md @@ -111,6 +111,30 @@ FR-036 pin cases (the two semantic pins + the length-precedence pin): absent `note` is still rejected. No port may apply the Pin 1 floor (min 1) when an author has explicitly said `@min: 0`. +## Cross-field validators — `meta.cross-field.json` + `cross-field-cases.json` + +A second, separate pair of files pins the four entity-scoped cross-field validators +(`validator.comparison`, `validator.requiredWhen`, `validator.presentIff`, +`validator.atLeastOne`) on the generated **full record (create) model**. They are separate files +so the run-time runners, which read `cases.json`, are unaffected. The entity is `Event`; every field +is optional, so absence is expressible in every port. + +The semantics mirror the DB `CHECK` derivation in `migrate-ts/src/expected-schema.ts`, with an absent +or null value standing for SQL `NULL` (and `""` NOT null): + +- `comparison` (`startsAt lte endsAt`): passes when either side is null. +- `requiredWhen`: violated only when the gating field equals `@equals` and the target is null; a null + gate is unconstrained. Both a string gate (`kind = BIRTH`) and a boolean gate (`flag = true`). +- `presentIff`: the target is present exactly when the gate equals `@equals`; a null gate counts as + not equal, so the target must be absent. +- `atLeastOne` (`email`, `phone`): at least one is non-null. +- A rule naming a field the create body never carries (`reviewedBy`, `@mutability: readOnly`; likewise a + derived field or a store-generated key) is skipped, so `review = DONE` without a reviewer is valid. + +Each case violates at most one validator (single-violation design). PATCH and partial-update models +are NOT covered here by design: they do not enforce cross-field rules, and the DB `CHECK` stays the +enforcement for them. + ## `field.uri` / `field.inet` strict contract (#234, ADR-0037 — Contract A) `Account` carries two OPTIONAL fields — `website` (`field.uri`) and `sourceIp` diff --git a/fixtures/validation-conformance/cross-field-cases.json b/fixtures/validation-conformance/cross-field-cases.json new file mode 100644 index 0000000000..57949d652f --- /dev/null +++ b/fixtures/validation-conformance/cross-field-cases.json @@ -0,0 +1,263 @@ +{ + "cases": [ + { + "name": "cross-valid-baseline", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "email": "a@b.c" + }, + "expectValid": true + }, + { + "name": "comparison-violated", + "entity": "Event", + "payload": { + "startsAt": 5, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "email": "a@b.c" + }, + "expectValid": false + }, + { + "name": "comparison-equal-boundary", + "entity": "Event", + "payload": { + "startsAt": 2, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "email": "a@b.c" + }, + "expectValid": true + }, + { + "name": "comparison-null-right-passes", + "entity": "Event", + "payload": { + "startsAt": 1, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "email": "a@b.c" + }, + "expectValid": true + }, + { + "name": "comparison-null-left-passes", + "entity": "Event", + "payload": { + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "email": "a@b.c" + }, + "expectValid": true + }, + { + "name": "required-when-violated", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "state": "OPEN", + "email": "a@b.c" + }, + "expectValid": false + }, + { + "name": "required-when-other-value-unconstrained", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "DEATH", + "state": "OPEN", + "email": "a@b.c" + }, + "expectValid": true + }, + { + "name": "required-when-gate-null-unconstrained", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "state": "OPEN", + "email": "a@b.c" + }, + "expectValid": true + }, + { + "name": "required-when-boolean-violated", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "email": "a@b.c", + "flag": true + }, + "expectValid": false + }, + { + "name": "required-when-boolean-satisfied", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "email": "a@b.c", + "flag": true, + "flagNote": "why" + }, + "expectValid": true + }, + { + "name": "required-when-boolean-false-unconstrained", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "email": "a@b.c", + "flag": false + }, + "expectValid": true + }, + { + "name": "present-iff-missing-target", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "CLOSED", + "email": "a@b.c" + }, + "expectValid": false + }, + { + "name": "present-iff-forbidden-target", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "email": "a@b.c", + "closedNote": "stray" + }, + "expectValid": false + }, + { + "name": "present-iff-satisfied", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "CLOSED", + "email": "a@b.c", + "closedNote": "done" + }, + "expectValid": true + }, + { + "name": "present-iff-gate-null-forbids-target", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "email": "a@b.c", + "closedNote": "stray" + }, + "expectValid": false + }, + { + "name": "present-iff-both-absent", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "email": "a@b.c" + }, + "expectValid": true + }, + { + "name": "at-least-one-violated", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN" + }, + "expectValid": false + }, + { + "name": "at-least-one-second-field", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "phone": "555" + }, + "expectValid": true + }, + { + "name": "at-least-one-both", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "BIRTH", + "subject": "p1", + "state": "OPEN", + "email": "a@b.c", + "phone": "555" + }, + "expectValid": true + }, + { + "name": "rule-on-read-only-field-skipped", + "entity": "Event", + "payload": { + "startsAt": 1, + "endsAt": 2, + "kind": "OTHER", + "state": "OPEN", + "email": "a@b.c", + "review": "DONE" + }, + "expectValid": true + } + ] +} diff --git a/fixtures/validation-conformance/meta.cross-field.json b/fixtures/validation-conformance/meta.cross-field.json new file mode 100644 index 0000000000..c2e4b65c98 --- /dev/null +++ b/fixtures/validation-conformance/meta.cross-field.json @@ -0,0 +1,33 @@ +{ + "metadata.root": { + "package": "acme::events", + "children": [ + { "object.entity": { + "name": "Event", + "children": [ + { "source.rdb": { "@table": "events" } }, + { "field.long": { "name": "id" } }, + { "field.int": { "name": "startsAt" } }, + { "field.int": { "name": "endsAt" } }, + { "field.string": { "name": "kind" } }, + { "field.string": { "name": "subject" } }, + { "field.string": { "name": "state" } }, + { "field.string": { "name": "closedNote" } }, + { "field.boolean": { "name": "flag" } }, + { "field.string": { "name": "flagNote" } }, + { "field.string": { "name": "email" } }, + { "field.string": { "name": "phone" } }, + { "field.string": { "name": "review" } }, + { "field.string": { "name": "reviewedBy", "@mutability": "readOnly" } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, + { "validator.comparison": { "name": "startsBeforeEnds", "@left": "startsAt", "@op": "lte", "@right": "endsAt" } }, + { "validator.requiredWhen": { "name": "birthNeedsSubject", "@field": "subject", "@when": "kind", "@equals": "BIRTH" } }, + { "validator.requiredWhen": { "name": "flaggedNeedsNote", "@field": "flagNote", "@when": "flag", "@equals": "true" } }, + { "validator.presentIff": { "name": "closedIffNote", "@field": "closedNote", "@when": "state", "@equals": "CLOSED" } }, + { "validator.atLeastOne": { "name": "reachable", "@fields": ["email", "phone"] } }, + { "validator.requiredWhen": { "name": "reviewNeedsReviewer", "@field": "reviewedBy", "@when": "review", "@equals": "DONE" } } + ] + }} + ] + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs new file mode 100644 index 0000000000..72f15b02a6 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs @@ -0,0 +1,125 @@ +using System.ComponentModel.DataAnnotations; +using System.Reflection; +using System.Text.Json; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +/// +/// Cross-field validator gate (C# port). Runs the shared +/// fixtures/validation-conformance/cross-field-cases.json corpus through the GENERATED +/// Event record (compiled in-memory with Roslyn) exactly the way +/// does: bind the payload, then +/// +/// with validateAllProperties: true, which invokes once the +/// property-level attributes pass. +/// +public sealed class CrossFieldValidationConformanceTests +{ + private static string CorpusDir() + { + string root = AppContext.BaseDirectory; + while (!Directory.Exists(Path.Combine(root, "fixtures", "validation-conformance"))) + { + string? parent = Directory.GetParent(root)?.FullName; + if (parent is null || parent == root) + throw new InvalidOperationException("fixtures/validation-conformance not found"); + root = parent; + } + return Path.Combine(root, "fixtures", "validation-conformance"); + } + + private static JsonElement[] AllCases() + { + using JsonDocument doc = JsonDocument.Parse( + File.ReadAllText(Path.Combine(CorpusDir(), "cross-field-cases.json"))); + return doc.RootElement.GetProperty("cases").EnumerateArray().Select(c => c.Clone()).ToArray(); + } + + public static IEnumerable Cases() => + AllCases().Select(c => new object[] { c.GetProperty("name").GetString()! }); + + [Fact] + public void Discovers_all_cross_field_cases() => Assert.Equal(20, AllCases().Length); + + [Theory] + [MemberData(nameof(Cases))] + public void Generated_record_cross_field_validation_matches_expected_verdict(string caseName) + { + JsonElement theCase = AllCases().Single(c => c.GetProperty("name").GetString() == caseName); + string entityName = theCase.TryGetProperty("entity", out JsonElement e) ? e.GetString()! : "Event"; + Type type = Generated.Asm.GetType($"Acme.Events.Generated.{entityName}")!; + bool expectValid = theCase.GetProperty("expectValid").GetBoolean(); + + bool valid; + var results = new List(); + try + { + object? instance = JsonSerializer.Deserialize(theCase.GetProperty("payload").GetRawText(), type, + new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + valid = instance is not null && Validator.TryValidateObject( + instance, new ValidationContext(instance), results, validateAllProperties: true); + } + catch (JsonException) + { + valid = false; + } + + Assert.True(valid == expectValid, + $"case '{caseName}': expected valid={expectValid} but got valid={valid}; " + + $"errors=[{string.Join("; ", results.Select(r => r.ErrorMessage))}]"); + } + + [Fact] + public void Violation_names_the_target_members() + { + Type type = Generated.Asm.GetType("Acme.Events.Generated.Event")!; + Assert.True(typeof(IValidatableObject).IsAssignableFrom(type)); + object inst = JsonSerializer.Deserialize( + "{\"startsAt\":5,\"endsAt\":2,\"kind\":\"BIRTH\",\"state\":\"OPEN\",\"email\":\"a@b.c\"}", type, + new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; + var results = new List(); + Assert.False(Validator.TryValidateObject(inst, new ValidationContext(inst), results, true)); + var members = results.SelectMany(r => r.MemberNames).ToHashSet(); + Assert.Contains("StartsAt", members); + Assert.Contains("EndsAt", members); + Assert.Contains("Subject", members); // BIRTH without a subject + } + + private static class Generated + { + internal static readonly Assembly Asm = Compile(); + + private static Assembly Compile() + { + var loadResult = new MetaDataLoader().Load( + [new FileSource(Path.Combine(CorpusDir(), "meta.cross-field.json"))]); + Assert.Empty(loadResult.Errors); + var ctx = new GenContext + { + Entities = loadResult.Root.Objects(), + Root = loadResult.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Events.Generated" }, + }; + var trees = new EntityGenerator().Generate(ctx) + .Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12))) + .ToArray(); + var refs = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator).Where(p => p.Length > 0) + .Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList(); + var comp = CSharpCompilation.Create("crossfield_" + Guid.NewGuid().ToString("N"), trees, refs, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + using var ms = new MemoryStream(); + var emit = comp.Emit(ms); + var errors = emit.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => $"{d.Id}: {d.GetMessage()}").ToList(); + Assert.True(errors.Count == 0, "generated cross-field record should compile, got: " + string.Join("; ", errors)); + return Assembly.Load(ms.ToArray()); + } + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidatorGenerationTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidatorGenerationTests.cs new file mode 100644 index 0000000000..1bf6703669 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidatorGenerationTests.cs @@ -0,0 +1,232 @@ +using System.ComponentModel.DataAnnotations; +using System.Reflection; +using System.Text.Json; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +/// +/// Generator-level tests for entity-scoped cross-field validators on the full record model: each +/// compiles the generated classes with Roslyn and runs . +/// Oracle: the validators' declared meaning (FR-036's CHECK semantics), e.g. lo lt hi +/// rejects 2 >= 1. The shared corpus gates the full verdict table; these cover inheritance and +/// the skipped-validator cases the corpus does not. +/// +public class CrossFieldValidatorGenerationTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Event", "children": [ + { "source.rdb": { "@table": "events" } }, + { "field.long": { "name": "id" } }, + { "field.int": { "name": "lo" } }, + { "field.int": { "name": "hi" } }, + { "field.string": { "name": "email" } }, + { "field.string": { "name": "phone" } }, + { "identity.primary": { "@fields": "id" } }, + { "validator.comparison": { "name": "c", "@left": "lo", "@op": "lt", "@right": "hi" } }, + { "validator.atLeastOne": { "name": "r", "@fields": ["email", "phone"] } }, + { "validator.requiredWhen": { "name": "ghost", "@field": "email", "@when": "missing", "@equals": "x" } } + ]}} + ]}} + """; + + private const string Plain = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Widget", "children": [ + { "source.rdb": { "@table": "widgets" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "name" } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + private const string Inherited = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Parent", "children": [ + { "source.rdb": { "@table": "parents" } }, + { "field.long": { "name": "id" } }, + { "field.int": { "name": "a" } }, + { "field.int": { "name": "b" } }, + { "identity.primary": { "@fields": "id" } }, + { "validator.comparison": { "name": "ab", "@left": "a", "@op": "lte", "@right": "b" } } + ]}}, + { "object.entity": { "name": "Child", "extends": "Parent", "children": [ + { "source.rdb": { "@table": "children" } }, + { "field.int": { "name": "c" } }, + { "field.int": { "name": "d" } }, + { "validator.comparison": { "name": "cd", "@left": "c", "@op": "lte", "@right": "d" } } + ]}} + ]}} + """; + + // The parent's only cross-field validator compares an int with a string, which no port emits, + // so the parent class has nothing to evaluate; the child still declares a rule of its own. + private const string SkippedParent = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Parent", "children": [ + { "source.rdb": { "@table": "parents" } }, + { "field.long": { "name": "id" } }, + { "field.int": { "name": "a" } }, + { "field.string": { "name": "b" } }, + { "identity.primary": { "@fields": "id" } }, + { "validator.comparison": { "name": "ab", "@left": "a", "@op": "lt", "@right": "b" } } + ]}}, + { "object.entity": { "name": "Child", "extends": "Parent", "children": [ + { "source.rdb": { "@table": "children" } }, + { "field.string": { "name": "kind" } }, + { "field.string": { "name": "note" } }, + { "validator.requiredWhen": { "name": "kn", "@field": "note", "@when": "kind", "@equals": "X" } } + ]}} + ]}} + """; + + // TPH: the abstract intermediate level is not emitted (EmitAbstractShapes off), so its rule + // must still be evaluated by the concrete subtype that extends the emitted base. + private const string TphAbstractMid = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Animal", "@discriminator": "type", "children": [ + { "source.rdb": { "@table": "animals" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "type" } }, + { "field.int": { "name": "lo" } }, + { "field.int": { "name": "hi" } }, + { "identity.primary": { "@fields": "id" } }, + { "validator.comparison": { "name": "lohi", "@left": "lo", "@op": "lte", "@right": "hi" } } + ]}}, + { "object.entity": { "name": "Mammal", "extends": "Animal", "abstract": true, "children": [ + { "field.string": { "name": "kind" } }, + { "field.string": { "name": "fur" } }, + { "validator.requiredWhen": { "name": "furry", "@field": "fur", "@when": "kind", "@equals": "FURRY" } } + ]}}, + { "object.entity": { "name": "Dog", "extends": "Mammal", "@discriminatorValue": "Dog", "children": [ + { "field.string": { "name": "bark" } } + ]}} + ]}} + """; + + // A decimal compared with a double: C# has no implicit conversion between the two. + private const string MixedNumeric = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Quote", "children": [ + { "source.rdb": { "@table": "quotes" } }, + { "field.long": { "name": "id" } }, + { "field.decimal": { "name": "price", "@precision": 10, "@scale": 2 } }, + { "field.double": { "name": "cap" } }, + { "identity.primary": { "@fields": "id" } }, + { "validator.comparison": { "name": "underCap", "@left": "price", "@op": "lte", "@right": "cap" } } + ]}} + ]}} + """; + + private static GenContext Ctx(string model) + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "xf.json")]); + Assert.Empty(r.Errors); + return new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme" }, + }; + } + + private static Assembly Compile(EntityGenerator generator, string model) + { + var trees = generator.Generate(Ctx(model)).Select(f => CSharpSyntaxTree.ParseText(f.Content)).ToArray(); + var refs = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator).Where(p => p.Length > 0) + .Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList(); + var comp = CSharpCompilation.Create("xfi_" + Guid.NewGuid().ToString("N"), trees, refs, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + using var ms = new MemoryStream(); + var emit = comp.Emit(ms); + Assert.True(emit.Success, string.Join("; ", emit.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error))); + return Assembly.Load(ms.ToArray()); + } + + private static List Validate(Assembly asm, string type, string json) + { + object inst = JsonSerializer.Deserialize(json, asm.GetType($"Acme.{type}")!, + new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; + var results = new List(); + Validator.TryValidateObject(inst, new ValidationContext(inst), results, true); + return results; + } + + [Fact] + public void Each_resolvable_rule_is_enforced_and_a_rule_on_a_missing_field_is_skipped() + { + var asm = Compile(new EntityGenerator(), Model); + Assert.Empty(Validate(asm, "Event", "{\"lo\":1,\"hi\":2,\"email\":\"e\"}")); + Assert.Single(Validate(asm, "Event", "{\"lo\":2,\"hi\":1,\"email\":\"e\"}")); + Assert.Single(Validate(asm, "Event", "{\"lo\":1,\"hi\":2}")); + } + + [Fact] + public void A_decimal_compared_with_a_double_compiles_and_is_enforced() + { + var asm = Compile(new EntityGenerator(), MixedNumeric); + Assert.Single(Validate(asm, "Quote", "{\"price\":5.5,\"cap\":3}")); + Assert.Empty(Validate(asm, "Quote", "{\"price\":2.5,\"cap\":3}")); + } + + [Fact] + public void Entity_without_cross_field_validators_is_not_validatable() + { + var asm = Compile(new EntityGenerator(), Plain); + Assert.False(typeof(IValidatableObject).IsAssignableFrom(asm.GetType("Acme.Widget")!)); + } + + [Fact] + public void Derived_entity_runs_the_inherited_rule_and_its_own() + { + var asm = Compile(new BasedEntityGenerator(), Inherited); + Assert.Equal(2, Validate(asm, "Child", "{\"a\":3,\"b\":1,\"c\":1,\"d\":0}").Count); + } + + [Fact] + public void Without_an_emitted_base_class_a_validator_on_an_unemitted_member_is_skipped() + { + // The stock mapped declaration names no C# base, so Child carries only its own fields; + // the inherited rule references members it does not have and is skipped. + var asm = Compile(new EntityGenerator(), Inherited); + Assert.Single(Validate(asm, "Child", "{\"a\":3,\"b\":1,\"c\":1,\"d\":0}")); + } + + [Fact] + public void Derived_entity_compiles_when_every_base_rule_is_skipped() + { + var asm = Compile(new BasedEntityGenerator(), SkippedParent); + Assert.Single(Validate(asm, "Child", "{\"kind\":\"X\"}")); + Assert.Empty(Validate(asm, "Child", "{\"kind\":\"X\",\"note\":\"n\"}")); + } + + [Fact] + public void Tph_subtype_runs_the_rule_of_an_unemitted_abstract_level() + { + var asm = Compile(new EntityGenerator(), TphAbstractMid); + Assert.Single(Validate(asm, "Dog", "{\"lo\":1,\"hi\":2,\"kind\":\"FURRY\"}")); + Assert.Single(Validate(asm, "Dog", "{\"lo\":3,\"hi\":2,\"kind\":\"FURRY\",\"fur\":\"f\"}")); + Assert.Empty(Validate(asm, "Dog", "{\"lo\":1,\"hi\":2,\"kind\":\"FURRY\",\"fur\":\"f\"}")); + } + + // Emits the metadata `extends` chain as a C# base, the shape an adopter override produces. + private sealed class BasedEntityGenerator : EntityGenerator + { + protected override void EmitClassDeclarationLine( + System.Text.StringBuilder sb, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx) + { + if (kind == ClassDeclarationKind.MappedEntity && DirectMappedParent(entity, ctx.Config) is { } p) + sb.AppendLine($"public class {className} : {CSharpNaming.Pascal(p.Name)}"); + else + base.EmitClassDeclarationLine(sb, entity, className, kind, ctx); + } + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index 810c3c78e7..64c88f88d9 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -293,6 +293,19 @@ private EmittedFile EmitMappedClassImpl( sb.AppendLine(); EmitClassHeader(sb, entity, className, isProjection, pkFields, ctx); + // Cross-field validators run on the full create record only (never a read-only view). + // The C# base chain is real only when the declaration line actually names a base; fields + // the class skips as "inherited" are otherwise absent as properties, so a validator that + // references one is skipped rather than emitted against a member that does not exist. + var mappedBase = DirectMappedParent(entity, ctx.Config); + var declaresBase = mappedBase is not null && LastLineHasBase(sb); + var validatingBase = declaresBase && !InstanceArtifacts.IsAbstract(mappedBase!) + && HasEffectiveCrossField(mappedBase!) ? mappedBase : null; + var absent = mappedBase is not null && !declaresBase + ? new HashSet(mappedBase.Fields().Select(f => f.Name), StringComparer.Ordinal) + : null; + var validateMethod = isProjection ? null : CrossFieldValidateMethod(entity, validatingBase, absent); + if (validateMethod is not null && validatingBase is null) AppendValidatableInterface(sb); sb.AppendLine("{"); // Nested enum declarations (before the class properties, as C# enum members @@ -368,6 +381,11 @@ private EmittedFile EmitMappedClassImpl( } sb.Append(string.Join("\n", members)); sb.AppendLine(); + if (validateMethod is not null) + { + sb.AppendLine(); + sb.Append(validateMethod); + } EmitClassBodyTrailer(sb, entity, ctx); sb.AppendLine("}"); return new EmittedFile($"{className}.g.cs", sb.ToString()); @@ -556,6 +574,10 @@ protected virtual EmittedFile EmitTphSubtypeClass(MetaObject entity, GenContext XmlDocBuilder.AppendTo(sb, entity); EmitClassDeclarationLine(sb, entity, className, ClassDeclarationKind.TphSubtype, ctx); + var tphAncestor = EmittedTphAncestor(entity, ctx); + var validatingBase = HasEffectiveCrossField(tphAncestor) ? tphAncestor : null; + var validateMethod = CrossFieldValidateMethod(entity, validatingBase); + if (validateMethod is not null && validatingBase is null) AppendValidatableInterface(sb); sb.AppendLine("{"); // Subtype-only enum declarations (an enum field declared on the subtype, not the base). @@ -598,6 +620,11 @@ protected virtual EmittedFile EmitTphSubtypeClass(MetaObject entity, GenContext } sb.Append(string.Join("\n", members)); sb.AppendLine(); + if (validateMethod is not null) + { + sb.AppendLine(); + sb.Append(validateMethod); + } EmitClassBodyTrailer(sb, entity, ctx); sb.AppendLine("}"); return new EmittedFile($"{className}.g.cs", sb.ToString()); @@ -973,6 +1000,235 @@ private static string EnumPropertyTypeName(MetaObject owner, MetaField field, Ge return new EmittedFile("Enums.g.cs", sb.ToString()); } + // ------------------------------------------------------------------------- + // Entity-scoped cross-field validators (validator.comparison / requiredWhen / + // presentIff / atLeastOne) -> IValidatableObject.Validate on the FULL record model, + // the class the generated create handler runs through Validator.TryValidateObject. + // Semantics mirror the schema-side CHECK derivation (migrate-ts crossFieldCheck): + // null = SQL NULL, "" is NOT null; a comparison with a null side passes; a null gate + // is unconstrained for requiredWhen and counts as "not equal" for presentIff. + // A validator naming a missing / array / non-scalar field is skipped silently. + // + // NOT emitted onto partial/PATCH handling: the update handler validates per property + // (TryValidateProperty), never TryValidateObject, so IValidatableObject does not run + // there; a partial body cannot see the merged row, and the DB CHECK stays the + // enforcement. Nuance: Validator.TryValidateObject runs IValidatableObject.Validate + // ONLY when every property-level attribute passed, so a body with a property-level + // violation reports that one first and the cross-field rules on a later pass. + // ------------------------------------------------------------------------- + + private static bool IsCrossFieldValidator(MetaValidator v) => + v.SubType is VALIDATOR_SUBTYPE_COMPARISON or VALIDATOR_SUBTYPE_REQUIRED_WHEN + or VALIDATOR_SUBTYPE_PRESENT_IFF or VALIDATOR_SUBTYPE_AT_LEAST_ONE; + + private enum CrossKind { Other, Numeric, Temporal, Str, Bool, Enum } + + private static CrossKind KindOf(MetaField f) => f.SubType switch + { + FIELD_SUBTYPE_INT or FIELD_SUBTYPE_LONG or FIELD_SUBTYPE_DOUBLE or FIELD_SUBTYPE_FLOAT + or FIELD_SUBTYPE_DECIMAL or FIELD_SUBTYPE_CURRENCY => CrossKind.Numeric, + FIELD_SUBTYPE_DATE or FIELD_SUBTYPE_TIME or FIELD_SUBTYPE_TIMESTAMP => CrossKind.Temporal, + FIELD_SUBTYPE_STRING => CrossKind.Str, + FIELD_SUBTYPE_BOOLEAN => CrossKind.Bool, + FIELD_SUBTYPE_ENUM => CrossKind.Enum, + _ => CrossKind.Other, + }; + + private static string CsLiteral(string s) => + "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "\\r").Replace("\n", "\\n") + "\""; + + // The cross-field validators THIS class must evaluate: its effective set, minus the ones the + // emitted base class's Validate already evaluates. Subtracting the base's effective set (not + // reading own validators) keeps a validator declared on an un-emitted intermediate level. + private static List CrossFieldValidatorsFor(MetaObject entity, MetaObject? validatingBase) + { + var inherited = validatingBase is null + ? new HashSet(ReferenceEqualityComparer.Instance) + : new HashSet(validatingBase.Validators(), ReferenceEqualityComparer.Instance); + return entity.Validators().Where(v => IsCrossFieldValidator(v) && !inherited.Contains(v)).ToList(); + } + + // A class whose effective validators include a cross-field one always declares or inherits + // Validate (CrossFieldValidateMethod emits it even when every rule is skipped), so a subclass + // may override it on exactly this test. + private static bool HasEffectiveCrossField(MetaObject entity) => + entity.Validators().Any(IsCrossFieldValidator); + + private static bool LastLineHasBase(StringBuilder sb) + { + var len = sb.Length; + while (len > 0 && (sb[len - 1] == '\n' || sb[len - 1] == '\r')) len--; + var start = len; + while (start > 0 && sb[start - 1] != '\n') start--; + return sb.ToString(start, len - start).Contains(" : ", StringComparison.Ordinal); + } + + // Appends `, IValidatableObject` (or ` : IValidatableObject`) to the just-written class + // declaration line. Works on the builder so an overridden declaration seam still applies. + private static void AppendValidatableInterface(StringBuilder sb) + { + var len = sb.Length; + while (len > 0 && (sb[len - 1] == '\n' || sb[len - 1] == '\r')) len--; + var lineStart = len; + while (lineStart > 0 && sb[lineStart - 1] != '\n') lineStart--; + var line = sb.ToString(lineStart, len - lineStart); + sb.Length = len; + sb.AppendLine(line.Contains(" : ", StringComparison.Ordinal) ? ", IValidatableObject" : " : IValidatableObject"); + } + + // Returns the emitted Validate method (4-space class-body indent), or null when nothing to emit. + private string? CrossFieldValidateMethod( + MetaObject entity, MetaObject? validatingBase, ISet? absentProps = null) + { + var validators = CrossFieldValidatorsFor(entity, validatingBase); + if (validators.Count == 0) return null; + var baseHasValidate = validatingBase is not null; + var generatedKey = entity.PrimaryIdentity() is MetaPrimaryIdentity + { + Generation: MetaObjects.Core.Identity.IdentityConstants.GENERATION_INCREMENT + or MetaObjects.Core.Identity.IdentityConstants.GENERATION_UUID, + } pk + ? new HashSet(pk.Fields, StringComparer.Ordinal) + : new HashSet(StringComparer.Ordinal); + + MetaField? Scalar(object? name) + { + if (name is not string n || n.Length == 0) return null; + // ADR-0039: resolving Fields() — a referenced field may be inherited. + var f = entity.Fields().FirstOrDefault(x => x.Name == n); + if (f is null || f.ResolvedIsArray()) return null; + if (f.IsReadOnlyMutability || f.IsDerived() || generatedKey.Contains(f.Name)) return null; + if (absentProps is not null && absentProps.Contains(f.Name)) return null; // not a property of this class + return CSharpNaming.ScalarFor(f.SubType) is not null || f.SubType == FIELD_SUBTYPE_ENUM ? f : null; + } + + string Gate(MetaField when, string raw) + { + var p = PropertyName(when); + switch (KindOf(when)) + { + case CrossKind.Bool: + var truthy = raw is "true" or "1" or "TRUE"; + return $"({p} == {(truthy ? "true" : "false")})"; + case CrossKind.Numeric: + if (!System.Text.RegularExpressions.Regex.IsMatch(raw, @"^-?\d+(\.\d+)?$")) return "false"; + var isInt = when.SubType is FIELD_SUBTYPE_INT or FIELD_SUBTYPE_LONG; + if (isInt && raw.Contains('.')) return "false"; + var suffix = when.SubType switch + { + FIELD_SUBTYPE_DECIMAL or FIELD_SUBTYPE_CURRENCY => "m", + FIELD_SUBTYPE_DOUBLE => "d", + FIELD_SUBTYPE_FLOAT => "f", + _ => "", + }; + return $"({p} == {raw}{suffix})"; + case CrossKind.Str: + return $"({p} == {CsLiteral(raw)})"; + default: + return $"(((object?){p})?.ToString() == {CsLiteral(raw)})"; + } + } + + var body = new StringBuilder(); + var i = 0; + foreach (var v in validators) + { + i++; + switch (v.SubType) + { + case VALIDATOR_SUBTYPE_COMPARISON: + { + var l = Scalar(v.Attr(VALIDATOR_ATTR_LEFT)); + var r = Scalar(v.Attr(VALIDATOR_ATTR_RIGHT)); + var op = v.Attr(VALIDATOR_ATTR_OP) as string; + if (l is null || r is null || op is null) break; + var lk = KindOf(l); var rk = KindOf(r); + var ordering = op is "gt" or "gte" or "lt" or "lte"; + var csOp = op switch { "gt" => ">", "gte" => ">=", "lt" => "<", "lte" => "<=", "ne" => "!=", "eq" => "==", _ => null }; + if (csOp is null) break; + string cond; + var a = $"__l{i}"; var b = $"__r{i}"; + if (lk == CrossKind.Str && rk == CrossKind.Str) + cond = $"string.CompareOrdinal({a}, {b}) {csOp} 0"; + else if (lk == CrossKind.Numeric && rk == CrossKind.Numeric) + { + var ls = CSharpNaming.ScalarForField(l); var rs = CSharpNaming.ScalarForField(r); + var la = ls != "decimal" && rs == "decimal" ? $"(decimal){a}" : a; + var rb = rs != "decimal" && ls == "decimal" ? $"(decimal){b}" : b; + cond = $"{la} {csOp} {rb}"; + } + else if (lk == CrossKind.Temporal && rk == CrossKind.Temporal + && CSharpNaming.ScalarForField(l) == CSharpNaming.ScalarForField(r)) + cond = $"{a} {csOp} {b}"; + else if (!ordering && lk == rk && lk != CrossKind.Other) + cond = op == "eq" ? $"Equals({a}, {b})" : $"!Equals({a}, {b})"; + else break; + var lp = PropertyName(l); var rp = PropertyName(r); + body.AppendLine($" if ({lp} is {{ }} {a} && {rp} is {{ }} {b} && !({cond}))"); + body.AppendLine($" yield return new ValidationResult({CsLiteral($"{lp} must be {op} {rp}.")}, new[] {{ nameof({lp}), nameof({rp}) }});"); + break; + } + case VALIDATOR_SUBTYPE_REQUIRED_WHEN: + case VALIDATOR_SUBTYPE_PRESENT_IFF: + { + var target = Scalar(v.Attr(VALIDATOR_ATTR_FIELD)); + var when = Scalar(v.Attr(VALIDATOR_ATTR_WHEN)); + if (target is null || when is null) break; + var raw = Convert.ToString(v.Attr(VALIDATOR_ATTR_EQUALS), System.Globalization.CultureInfo.InvariantCulture) ?? ""; + var gate = Gate(when, raw); + var tp = PropertyName(target); var wp = PropertyName(when); + if (v.SubType == VALIDATOR_SUBTYPE_REQUIRED_WHEN) + { + body.AppendLine($" if ({gate} && {tp} is null)"); + body.AppendLine($" yield return new ValidationResult({CsLiteral($"{tp} is required when {wp} is {raw}.")}, new[] {{ nameof({tp}) }});"); + } + else + { + body.AppendLine($" if (({tp} is not null) != {gate})"); + body.AppendLine($" yield return new ValidationResult({CsLiteral($"{tp} must be present if and only if {wp} is {raw}.")}, new[] {{ nameof({tp}) }});"); + } + break; + } + case VALIDATOR_SUBTYPE_AT_LEAST_ONE: + { + var raw = v.Attr(VALIDATOR_ATTR_FIELDS); + var names = raw switch + { + string one => new List { one }, + System.Collections.IEnumerable many => many.Cast().ToList(), + _ => new List(), + }; + var fs = names.Select(Scalar).ToList(); + if (fs.Count == 0 || fs.Any(f => f is null)) break; + var props = fs.Select(f => PropertyName(f!)).ToList(); + body.AppendLine($" if ({string.Join(" && ", props.Select(p => $"{p} is null"))})"); + body.AppendLine($" yield return new ValidationResult({CsLiteral($"At least one of {string.Join(", ", props)} is required.")}, new[] {{ {string.Join(", ", props.Select(p => $"nameof({p})"))} }});"); + break; + } + } + } + if (body.Length == 0) + { + if (baseHasValidate) return null; + body.AppendLine(" yield break;"); + } + + var sb = new StringBuilder(); + sb.AppendLine(" /// Entity-scoped cross-field validators (comparison / requiredWhen / presentIff / atLeastOne). Create-time only; the database CHECK is the enforcement on partial updates."); + sb.AppendLine(baseHasValidate + ? " public override IEnumerable Validate(ValidationContext validationContext)" + : " public virtual IEnumerable Validate(ValidationContext validationContext)"); + sb.AppendLine(" {"); + if (baseHasValidate) + { + sb.AppendLine(" foreach (var __inherited in base.Validate(validationContext))"); + sb.AppendLine(" yield return __inherited;"); + } + sb.Append(body); + sb.AppendLine(" }"); + return sb.ToString(); + } + // Extension hook — invoked once per emitted property, AFTER the framework // attributes ([Key]/[Column]/[Required]/[MaxLength]/validators) and immediately // BEFORE the `public { get; ... }` line. The default body is empty diff --git a/server/java/codegen-kotlin/pom.xml b/server/java/codegen-kotlin/pom.xml index 5a5fe50e6a..723a221397 100644 --- a/server/java/codegen-kotlin/pom.xml +++ b/server/java/codegen-kotlin/pom.xml @@ -251,6 +251,7 @@ KotlinDecimalWireEmitter.kt KotlinExtractSchemaEmitter.kt KotlinOutputFormatSpecEmitter.kt + KotlinCrossFieldRules.kt +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `dotnet meta verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (same id, same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/agent-context/skills/metaobjects-authoring/references/java-providers.md b/agent-context/skills/metaobjects-authoring/references/java-providers.md new file mode 100644 index 0000000000..8b7b598054 --- /dev/null +++ b/agent-context/skills/metaobjects-authoring/references/java-providers.md @@ -0,0 +1,93 @@ +# Your own vocabulary in Java — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its Java tools load the metadata. + +A provider is a public class implementing `com.metaobjects.registry.MetaDataTypeProvider`, with +a public no-arg constructor: a provider id, the provider ids it depends on (the JVM ids: +`field-types` registers the field types, `layout-types` the layouts), and a `registerTypes` +body that calls `registerType` (a new subtype, backed by its own node class) and `extendType` +(attributes on an existing one). This one registers `layout.picker` and adds `@searchable` and +`@valueLabels` to `field.string`: + +```java +package com.acme.vocab; + +import com.metaobjects.attr.BooleanAttribute; +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.field.StringField; +import com.metaobjects.layout.MetaLayout; +import com.metaobjects.registry.MetaDataRegistry; +import com.metaobjects.registry.MetaDataTypeProvider; + +public final class AcmeVocabulary implements MetaDataTypeProvider { + /** The node class behind layout.picker. */ + public static final class PickerLayout extends MetaLayout { + public PickerLayout(String name) { super("picker", name); } + } + + @Override public String getProviderId() { return "acme-vocabulary"; } + @Override public String[] getDependencies() { return new String[] {"field-types", "layout-types"}; } + + @Override public void registerTypes(MetaDataRegistry registry) { + // A new subtype, with its own attribute (an own attribute may be required). + registry.registerType(PickerLayout.class, def -> { + def.type("layout").subType("picker").inheritsFrom("layout", "base"); + def.optionalAttributeWithConstraints("displayField").ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + // Attributes on a type another provider owns: always optional. + registry.extendType(StringField.class, def -> { + def.optionalAttributeWithConstraints("searchable").ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + def.optionalAttributeWithConstraints("valueLabels").ofType(StringAttribute.SUBTYPE_STRING).asArray(); + }); + } +} +``` + +Wire it once, in the `metaobjects-maven-plugin` configuration. The class must be on the +plugin's classpath: put the provider in its own module and add that module as a project +dependency or under the plugin's ``. A provider in the same module is not +compiled yet when `generate` runs at `generate-sources`. + +```xml + + com.metaobjects + metaobjects-maven-plugin + + + com.acme.vocab.AcmeVocabulary + + + + com.acmeacme-vocabulary1.0 + + +``` + +`metaobjects:generate` (with its docs generators), `metaobjects:verify`, `metaobjects:fmt` and +`metaobjects:editor` all compose the metamodel providers plus these. Listing a class in +`META-INF/services` does NOT add it to the loader: the strict loader composes a fixed +metamodel set plus the providers you name, so a jar on the classpath cannot change the +vocabulary by accident. + +In a Spring Boot app, declare the provider as a bean and the auto-configured loader composes +it: `@Bean MetaDataTypeProvider acmeVocabulary() { return new AcmeVocabulary(); }`. Code that +loads the model itself passes it on the options: + +```java +MetaDataLoader.fromUris("app", uris, + LoaderOptions.create(false, false, true).setProviders(List.of(new AcmeVocabulary()))); +``` + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `metaobjects:verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (the same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/agent-context/skills/metaobjects-authoring/references/kotlin-providers.md b/agent-context/skills/metaobjects-authoring/references/kotlin-providers.md new file mode 100644 index 0000000000..09d6c6c4a4 --- /dev/null +++ b/agent-context/skills/metaobjects-authoring/references/kotlin-providers.md @@ -0,0 +1,77 @@ +# Your own vocabulary in Kotlin — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its Kotlin tools load the +> metadata. + +Kotlin runs on the JVM registry, so a provider is a class implementing +`com.metaobjects.registry.MetaDataTypeProvider`, written in Kotlin: a provider id, the JVM +provider ids it depends on (`field-types`, `layout-types`), and a `registerTypes` body that +calls `registerType` (a new subtype, backed by its own node class) and `extendType` +(attributes on an existing one). This one registers `layout.picker` and adds `@searchable` and +`@valueLabels` to `field.string`: + +```kotlin +package com.acme.vocab + +import com.metaobjects.field.StringField +import com.metaobjects.layout.MetaLayout +import com.metaobjects.registry.MetaDataRegistry +import com.metaobjects.registry.MetaDataTypeProvider + +/** The node class behind layout.picker. */ +class PickerLayout(name: String) : MetaLayout("picker", name) + +class AcmeVocabulary : MetaDataTypeProvider { + override fun getProviderId() = "acme-vocabulary" + override fun getDependencies() = arrayOf("field-types", "layout-types") + + override fun registerTypes(registry: MetaDataRegistry) { + // A new subtype, with its own attribute (an own attribute may be required). + registry.registerType(PickerLayout::class.java) { def -> + def.type("layout").subType("picker").inheritsFrom("layout", "base") + def.optionalAttributeWithConstraints("displayField").ofType("string").asSingle() + } + // Attributes on a type another provider owns: always optional. + registry.extendType(StringField::class.java) { def -> + def.optionalAttributeWithConstraints("searchable").ofType("boolean").asSingle() + def.optionalAttributeWithConstraints("valueLabels").ofType("string").asArray() + } + } +} +``` + +Wire it once. Kotlin generators run through `metaobjects:generate`, so the build lists it in +the `metaobjects-maven-plugin` configuration, with the provider's module on the plugin's +classpath (a project dependency or the plugin's ``; a provider in the same +module is not compiled yet at `generate-sources`): + +```xml + + + com.acme.vocab.AcmeVocabulary + + +``` + +`generate`, `verify`, `fmt` and `editor` then all load it. `META-INF/services` does not add a +provider to the loader. In a Spring Boot app, a `MetaDataTypeProvider` bean is composed into +the auto-configured loader. Code that loads the model through the `metadata-ktx` facade passes +it directly: + +```kotlin +val result = loadUris("app", uris, LoaderOptions.create(false, false, true), providers = listOf(AcmeVocabulary())) +``` + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `metaobjects:verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (the same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/agent-context/skills/metaobjects-authoring/references/python-providers.md b/agent-context/skills/metaobjects-authoring/references/python-providers.md new file mode 100644 index 0000000000..2e0a55db54 --- /dev/null +++ b/agent-context/skills/metaobjects-authoring/references/python-providers.md @@ -0,0 +1,69 @@ +# Your own vocabulary in Python — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its Python tools load the +> metadata. + +A provider is a `metaobjects.provider.Provider`: an id, the provider ids it depends on, the +`TypeDefinition`s it adds (a new subtype), and an `on_register` hook that `extend`s existing +types. This one registers `layout.picker` and adds `@searchable` and `@valueLabels` to +`field.string`: + +```python +# acme_vocab.py (beside metaobjects.config.yaml) +from metaobjects.meta.presentation.layout.meta_layout import MetaLayout +from metaobjects.provider import Provider +from metaobjects.registry import AttrSchema, ChildRule, TypeDefinition +from metaobjects.shared.base_types import TYPE_ATTR + +provider = Provider("acme-vocabulary", dependencies=("metaobjects-core-types",)) + +# A new subtype, with its own attribute (an own attribute may be required). +provider.add(TypeDefinition( + type="layout", sub_type="picker", factory=MetaLayout, + attrs=[AttrSchema("displayField", "string", required=False)], + child_rules=[ChildRule(TYPE_ATTR, "*")], +)) + +# Attributes on a type another provider owns: always optional. +provider.on_register(lambda registry: registry.extend( + "field", "string", + attributes=[ + AttrSchema("searchable", "boolean", required=False), + AttrSchema("valueLabels", "string", required=False, is_array=True), + ], +)) +``` + +Wire it once, in `metaobjects.config.yaml`, as `module:symbol`. The module resolves relative +to the config's directory, so no `PYTHONPATH` is needed: + +```yaml +metadata: metaobjects +providers: ["acme_vocab:provider"] +``` + +`metaobjects gen` (with its docs generators), every `metaobjects verify` mode and +`metaobjects fmt` read that list; `--provider module:symbol` adds to it for one run. Code that +loads the model itself passes the full list, core first, because `providers=` is exactly the +set composed: + +```python +from metaobjects.core_types import core_providers +from metaobjects.loader.meta_data_loader import MetaDataLoader + +result = MetaDataLoader.from_directory("metaobjects", providers=[*core_providers, provider], strict=True) +``` + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `metaobjects verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (same id, same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/agent-context/skills/metaobjects-authoring/references/typescript-providers.md b/agent-context/skills/metaobjects-authoring/references/typescript-providers.md new file mode 100644 index 0000000000..5db6706b4f --- /dev/null +++ b/agent-context/skills/metaobjects-authoring/references/typescript-providers.md @@ -0,0 +1,74 @@ +# Your own vocabulary in TypeScript — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its TypeScript tools load the +> metadata. + +A provider is an object implementing `MetaDataTypeProvider`: an `id`, the provider ids it +depends on, and a `registerTypes(registry)` body that calls `register` (a new subtype) and +`extend` (attributes on an existing one). This one registers `layout.picker` and adds +`@searchable` and `@valueLabels` to `field.string`: + +```ts +// codegen/vocabulary.ts +import { TypeId, MetaLayout, type MetaDataTypeProvider } from "@metaobjectsdev/metadata"; +import { + TYPE_FIELD, TYPE_LAYOUT, FIELD_SUBTYPE_STRING, + ATTR_SUBTYPE_STRING, ATTR_SUBTYPE_BOOLEAN, +} from "@metaobjectsdev/metadata/constants"; + +export const vocabulary: MetaDataTypeProvider = { + id: "acme-vocabulary", + dependencies: ["metaobjects-core-types"], + registerTypes(registry) { + // A new subtype, with its own attribute (an own attribute may be required). + registry.register({ + typeId: new TypeId(TYPE_LAYOUT, "picker"), + description: "A picker over the owning object.", + factory: (typeId, name) => new MetaLayout(typeId, name), + childRules: [], + attributes: [ + { name: "displayField", valueType: ATTR_SUBTYPE_STRING, required: false, description: "Field shown per choice." }, + ], + }); + // Attributes on a type another provider owns: always optional. + registry.extend(TYPE_FIELD, FIELD_SUBTYPE_STRING, { + attributes: [ + { name: "searchable", valueType: ATTR_SUBTYPE_BOOLEAN, required: false, description: "Offer in search." }, + { name: "valueLabels", valueType: ATTR_SUBTYPE_STRING, isArray: true, required: false, description: "Display labels." }, + ], + }); + }, +}; +``` + +Wire it once, in `metaobjects.config.ts`: + +```ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { vocabulary } from "./codegen/vocabulary"; + +export default defineConfig({ + generators: [/* ... */], + providers: [vocabulary], +}); +``` + +Every `meta` command that loads metadata reads that list: `gen` (with the docs generators and +the docs site), `verify`, `migrate`, `fmt`, `types`, `export`, `deps`, `upgrade`. `meta types +picker` then lists the new subtype. A config that fails to load is reported as its own error, +never as an unknown subtype. Code that loads the model itself passes the same provider: +`loadMemory(root, { providers: [vocabulary] })`. + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `meta verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (same `id`, same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/agent-context/skills/metaobjects-codegen/SKILL.md b/agent-context/skills/metaobjects-codegen/SKILL.md index a030b08545..36123e0d8f 100644 --- a/agent-context/skills/metaobjects-codegen/SKILL.md +++ b/agent-context/skills/metaobjects-codegen/SKILL.md @@ -430,6 +430,11 @@ template hack. See the decision procedure in the **`metaobjects-authoring`** ski array column type) and a native UUID is `field.uuid` (not a string + `@dbColumnType`). When you register custom vocabulary for a custom generator, the same ADR-0037 procedure decides whether it's a subtype, a `@kind` variant, or an attribute. +The vocabulary itself is a provider class, listed once in the port's project +configuration so `gen`, `verify --codegen` and the docs generators all load it (the +**`metaobjects-authoring`** skill, "Your own vocabulary", has the per-language example). +A generator then reads the custom attribute like any other: through the resolving +accessor on the node, never by re-parsing the file. ## Per-target output diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 6487032d76..0addaf83d3 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 426 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 428 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -285,7 +285,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (426) +### `fixtures/conformance/` — metamodel loader + canonical serializer (428) | Fixture prefix | Feature doc | |---|---| @@ -309,6 +309,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. | `projection-*`, `error-projection-*`, `field-readonly-on-view-projection` | [features/source-kinds.md](features/source-kinds.md) (projections + the object taxonomy, ADR-0028) | | `requirement-*`, `error-unknown-attr-requirement` | [features/requirements.md](features/requirements.md) (vocabulary only — the gate has its own corpus, `requirement-check-conformance/`; see "Split coverage" above) | | `reporting-*`, `error-dimension-*`, `error-measure-*`, `error-ratio-*`, `error-segment-*`, `error-report-*`, `error-relative-date-*` | [features/reporting.md](features/reporting.md) (the `dimension` / `measure` / `segment` / `object.report` vocabulary and its load-time rules; design in the [FR-044 spec](superpowers/specs/2026-10-02-fr-044-core-reporting-design.md)) | +| `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) | | `smoke-empty-metadata` | [features/entities.md](features/entities.md) | ### `fixtures/yaml-conformance/` (16) @@ -611,7 +612,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 426 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 428 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/extending-with-providers.md b/docs/features/extending-with-providers.md index 8fb3f3208e..be13b96183 100644 --- a/docs/features/extending-with-providers.md +++ b/docs/features/extending-with-providers.md @@ -11,6 +11,8 @@ This page covers: - The provider contract (what a provider declares) - How to register a new subtype or extend an existing one +- How to wire a project's own provider into each port (TypeScript, Python, C#, Java, + Kotlin), with a worked example per language, and which commands load it - The cross-port semantic rules (explicit providers bypass ambient discovery) - Stable error codes for composition failures @@ -176,52 +178,294 @@ provider. This is conformance-gated across all five ports (the ## Wiring providers into the loader -Each port has its own loader entry point. The contract is identical: -**provide an explicit list of providers, and the loader composes them in -dependency order, skipping any ambient discovery.** +A provider is code, so it lives in the language of the tools that load the metadata, and it +is wired in that port's own config. Each port then loads it at **every** entry point that +reads metadata, not only codegen. The contract is the same everywhere: + +> **The loader composes the core vocabulary plus exactly the providers you name, in +> dependency order.** Nothing is discovered from the classpath, the bundler's import order or +> an installed package. The same provider list and the same metadata give the same registry. + +**Every port whose tools load the metadata needs its own copy of the provider.** A provider +registered only in TypeScript is invisible to the Java build, the Python CLI or the C# tool, +and they refuse the same file with `ERR_UNKNOWN_SUBTYPE` / `ERR_UNKNOWN_ATTR`. Give each copy +the same `id` and the same vocabulary; the shared conformance fixtures +`provider-custom-vocabulary-success` and `provider-custom-vocabulary-missing-provider-fails` +hold every port to that. + +The examples below all add the same vocabulary: a new `layout.picker` subtype with its own +`@displayField` attribute, and two optional attributes on the core `field.string`, +`@searchable` (boolean) and `@valueLabels` (string array). The metadata then uses it like +core vocabulary: + + +```json +{ "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Contact", "children": [ + { "field.string": { "name": "name", "@searchable": true } }, + { "field.string": { "name": "status", "@valueLabels": ["Active", "On hold"] } }, + { "layout.picker": { "name": "contactPicker", "@displayField": "name" } } + ]}} +]}} +``` + +The agent-context skill carries the same example per language +(`agent-context/skills/metaobjects-authoring/references/-providers.md`). + +### TypeScript ```ts -// TypeScript -import { loadMemory } from "@metaobjectsdev/sdk"; -import { exampleToolcallProvider } from "./codegen/providers"; +// codegen/vocabulary.ts +import { TypeId, MetaLayout, type MetaDataTypeProvider } from "@metaobjectsdev/metadata"; +import { + TYPE_FIELD, TYPE_LAYOUT, FIELD_SUBTYPE_STRING, + ATTR_SUBTYPE_STRING, ATTR_SUBTYPE_BOOLEAN, +} from "@metaobjectsdev/metadata/constants"; -const root = await loadMemory("./", { - providers: [exampleToolcallProvider], // composed AFTER core providers -}); +export const vocabulary: MetaDataTypeProvider = { + id: "acme-vocabulary", + dependencies: ["metaobjects-core-types"], + registerTypes(registry) { + registry.register({ + typeId: new TypeId(TYPE_LAYOUT, "picker"), + description: "A picker over the owning object.", + factory: (typeId, name) => new MetaLayout(typeId, name), + childRules: [], + attributes: [ + { name: "displayField", valueType: ATTR_SUBTYPE_STRING, required: false, description: "Field shown per choice." }, + ], + }); + registry.extend(TYPE_FIELD, FIELD_SUBTYPE_STRING, { + attributes: [ + { name: "searchable", valueType: ATTR_SUBTYPE_BOOLEAN, required: false, description: "Offer in search." }, + { name: "valueLabels", valueType: ATTR_SUBTYPE_STRING, isArray: true, required: false, description: "Display labels." }, + ], + }); + }, +}; ``` -```csharp -// C# -var loader = MetaDataLoader.FromDirectory("./metadata", registry); -// where `registry` is built via Provider.ComposeRegistry(providers) +Wire it in `metaobjects.config.ts`: + +```ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { vocabulary } from "./codegen/vocabulary"; + +export default defineConfig({ generators: [/* ... */], providers: [vocabulary] }); ``` +**Loaded by:** `meta gen` (including the docs generators and the docs site), `meta verify` +(every mode), `meta migrate`, `meta fmt`, `meta types`, `meta export`, `meta deps`, +`meta upgrade` and `meta prompt-snapshot`. A config that fails to load is reported as its own +error, never misreported as an unknown subtype. Programmatic loads pass the list: +`loadMemory(root, { providers: [vocabulary] })` composes the default core set plus yours; +`replaceDefaults: true` composes yours alone (rare). + +### Python + ```python -# Python -loader = MetaDataLoader.from_directory("./metadata", providers=[example_toolcall_provider]) +# acme_vocab.py (beside metaobjects.config.yaml) +from metaobjects.meta.presentation.layout.meta_layout import MetaLayout +from metaobjects.provider import Provider +from metaobjects.registry import AttrSchema, ChildRule, TypeDefinition +from metaobjects.shared.base_types import TYPE_ATTR + +provider = Provider("acme-vocabulary", dependencies=("metaobjects-core-types",)) +provider.add(TypeDefinition( + type="layout", sub_type="picker", factory=MetaLayout, + attrs=[AttrSchema("displayField", "string", required=False)], + child_rules=[ChildRule(TYPE_ATTR, "*")], +)) +provider.on_register(lambda registry: registry.extend( + "field", "string", + attributes=[ + AttrSchema("searchable", "boolean", required=False), + AttrSchema("valueLabels", "string", required=False, is_array=True), + ], +)) ``` +Wire it in `metaobjects.config.yaml` as `module:symbol`; the module resolves relative to the +config's directory: + +```yaml +metadata: metaobjects +providers: ["acme_vocab:provider"] +``` + +**Loaded by:** `metaobjects gen` (including the docs generators), every `metaobjects verify` +mode and `metaobjects fmt`. `--provider module:symbol` adds to the configured list for one +run. Programmatic loads pass the full set, core first, because `providers=` is exactly what +is composed: +`MetaDataLoader.from_directory("metaobjects", providers=[*core_providers, provider], strict=True)` +(`core_providers` from `metaobjects.core_types`). + +### C# + +```csharp +// vocabulary/AcmeVocabularyProvider.cs, in a class library referencing the MetaObjects +// package at the version your `dotnet meta` tool runs. +using MetaObjects; +using MetaObjects.Meta; +using MetaObjects.Shared; + +namespace Acme.Vocabulary; + +public sealed class AcmeVocabularyProvider : IMetaDataTypeProvider +{ + public string Id => "acme-vocabulary"; + public IReadOnlyList Dependencies => ["metaobjects-core-types"]; + + public void RegisterTypes(TypeRegistry registry) + { + registry.Register(new TypeDefinition( + typeId: new TypeId("layout", "picker"), + description: "A picker over the owning object.", + childRules: [new ChildRule(BaseTypes.TYPE_ATTR, Structural.CHILD_RULE_WILDCARD, Structural.CHILD_RULE_WILDCARD)], + factory: (typeId, name) => new MetaLayout(typeId, name), + attributes: [new AttrSchema("displayField", "string", Required: false)])); + + registry.Extend("field", "string", attributes: + [ + new AttrSchema("searchable", "boolean", Required: false), + new AttrSchema("valueLabels", "string", Required: false, IsArray: true), + ]); + } +} +``` + +Wire it in `.metaobjects/config.json`. `assembly` is the built dll, relative to the directory +holding `.metaobjects/`; `type` is the provider's full type name, and the class needs a public +parameterless constructor: + +```json +{ + "schema_version": 1, + "csharp": { + "providers": [ + { "assembly": "vocabulary/bin/Debug/net8.0/Acme.Vocabulary.dll", "type": "Acme.Vocabulary.AcmeVocabularyProvider" } + ] + } +} +``` + +**Loaded by:** `dotnet meta gen` and `verify --codegen` (through the project's `codegen/` +runner), `dotnet meta verify` (templates, requirements, field lint) and `dotnet meta fmt`. +Build the vocabulary first; a missing dll, a missing type or a type that is not a provider is +refused with an error naming `csharp.providers`. If the `codegen/` project also references +the vocabulary project, the already-loaded assembly is reused. Programmatic loads compose the +registry themselves, and `ComposeRegistry` takes exactly the set given: +`Provider.ComposeRegistry([.. CoreTypes.LibraryProviders, new AcmeVocabularyProvider()])`, +then `MetaDataLoader.FromDirectory(dir, registry, strict: true)`. + +### Java + ```java -// Java — SPI auto-discovery is the default; META-INF/services lists every provider -// (no API call required). When a consumer genuinely needs extra vocabulary -// composed with the full metamodel provider set — so its metadata still -// strict-loads against the spec contract instead of getting the weaker -// classpath-SPI registry — the sanctioned seam is: -loader.setTypeRegistry(RegistryManifest.composeMetamodelRegistry(List.of(myProvider))); -// Calling MetaDataRegistry.compose(...) directly does NOT run spec scoping — -// use composeMetamodelRegistry(extras), not a raw compose() call. +package com.acme.vocab; + +import com.metaobjects.attr.BooleanAttribute; +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.field.StringField; +import com.metaobjects.layout.MetaLayout; +import com.metaobjects.registry.MetaDataRegistry; +import com.metaobjects.registry.MetaDataTypeProvider; + +public final class AcmeVocabulary implements MetaDataTypeProvider { + /** The node class behind layout.picker. */ + public static final class PickerLayout extends MetaLayout { + public PickerLayout(String name) { super("picker", name); } + } + + @Override public String getProviderId() { return "acme-vocabulary"; } + @Override public String[] getDependencies() { return new String[] {"field-types", "layout-types"}; } + + @Override public void registerTypes(MetaDataRegistry registry) { + registry.registerType(PickerLayout.class, def -> { + def.type("layout").subType("picker").inheritsFrom("layout", "base"); + def.optionalAttributeWithConstraints("displayField").ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + registry.extendType(StringField.class, def -> { + def.optionalAttributeWithConstraints("searchable").ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + def.optionalAttributeWithConstraints("valueLabels").ofType(StringAttribute.SUBTYPE_STRING).asArray(); + }); + } +} ``` -The semantic rule is identical across ports: +The JVM provider ids differ from the other ports': depend on `field-types` and +`layout-types` (the providers that register those types), not `metaobjects-core-types`. + +Wire it in the `metaobjects-maven-plugin` configuration. The class must be on the plugin's +classpath, so put it in its own module and add that module as a project dependency or under +the plugin's ``; a provider in the same module is not compiled yet when +`generate` runs at `generate-sources`. + +```xml + + com.metaobjects + metaobjects-maven-plugin + + + com.acme.vocab.AcmeVocabulary + + + + com.acmeacme-vocabulary1.0 + + +``` -> **Explicit `providers` declarations bypass any ambient discovery.** The -> set you pass is exactly the set the loader composes. This guarantees -> determinism — same providers list + same metadata → same registry, no -> classpath order surprises, no bundler import-order surprises. +**Loaded by:** `metaobjects:generate` (including the docs generators), `metaobjects:verify`, +`metaobjects:fmt` and `metaobjects:editor` (`-Dmeta.providers=...` on the command line works +too). A Spring Boot app declares the provider as a bean, and the auto-configured loader +composes every `MetaDataTypeProvider` bean: +`@Bean MetaDataTypeProvider acmeVocabulary() { return new AcmeVocabulary(); }`. +Programmatic loads pass it on the options: +`LoaderOptions.create(false, false, true).setProviders(List.of(new AcmeVocabulary()))`. +The loader composes the full metamodel set plus these +(`RegistryManifest.composeLoaderRegistry(extras)`). + +**Listing a class in `META-INF/services` does not add it to the loader.** The strict loader +composes a fixed metamodel set plus the providers you name, so a jar on the classpath cannot +change the vocabulary by accident. + +### Kotlin + +Kotlin runs on the JVM registry, so the provider is the same interface written in Kotlin, and +it is wired the same way: the Maven plugin's `` list (Kotlin generators run +through `metaobjects:generate`), a Spring bean, or `providers = listOf(...)` on the +`metadata-ktx` loader: + +```kotlin +class PickerLayout(name: String) : MetaLayout("picker", name) + +class AcmeVocabulary : MetaDataTypeProvider { + override fun getProviderId() = "acme-vocabulary" + override fun getDependencies() = arrayOf("field-types", "layout-types") + + override fun registerTypes(registry: MetaDataRegistry) { + registry.registerType(PickerLayout::class.java) { def -> + def.type("layout").subType("picker").inheritsFrom("layout", "base") + def.optionalAttributeWithConstraints("displayField").ofType("string").asSingle() + } + registry.extendType(StringField::class.java) { def -> + def.optionalAttributeWithConstraints("searchable").ofType("boolean").asSingle() + def.optionalAttributeWithConstraints("valueLabels").ofType("string").asArray() + } + } +} -Every port's loader defaults to `[...coreProviders, ...callerProviders]` when the -caller supplies `providers`. Pass `{ replaceDefaults: true }` (TS) or the per-port -equivalent to skip the defaults entirely — rare, but supported. +val result = loadUris("app", uris, LoaderOptions.create(false, false, true), providers = listOf(AcmeVocabulary())) +``` + +### Without the provider + +The same file, loaded strictly without the provider, fails with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on each of `@searchable` and `@valueLabels`, in that +order, in every port. A lax load accepts the unknown attributes but still refuses the unknown +subtype. + +### The TypeScript forge provider **`forgeTypesProvider` is TypeScript-only, and is no longer in any default composition.** It was listed here as part of the default composition for "the TS / C# / @@ -249,7 +493,8 @@ Composition surfaces these codes consistently across all ports (see | Code | When | Conformance fixture | |---|---|---| | `ERR_UNKNOWN_TYPE` | YAML/JSON references a `type` not registered by any provider — including a BARE wrapper key naming an unregistered type, which is an unknown type and not a missing subType | `error-unknown-bare-child-type` | -| `ERR_UNKNOWN_SUBTYPE` | `type` is known but `subType` is not | `provider-extension-missing-provider-fails` | +| `ERR_UNKNOWN_SUBTYPE` | `type` is known but `subType` is not | `provider-extension-missing-provider-fails`, `provider-custom-vocabulary-missing-provider-fails` | +| `ERR_UNKNOWN_ATTR` | A strict load meets an attribute no provider declared on that `(type, subType)` | `provider-custom-vocabulary-missing-provider-fails` | | `ERR_CHILD_NOT_OBJECT` | A `children` entry's body is not an object, so there is no node to read — checked AFTER the wrapper key resolves | `error-child-not-object` | | `ERR_PROVIDER_DUPLICATE_ID` | Two provider objects report the same `id` | `provider-extension-duplicate-id` | | `ERR_PROVIDER_MISSING_DEPENDENCY` | Provider declares dep on an unregistered id | `provider-extension-missing-dependency` | @@ -257,9 +502,13 @@ Composition surfaces these codes consistently across all ports (see | `ERR_PROVIDER_ATTR_CONFLICT` | Two providers declare the same attr on the same `(type, subType)` | (covered by negative tests in core) | Each conformance fixture's `providers.json: string[]` lists the provider ids to -compose for that test — the same wire format consumers use at runtime. The -fixtures are run in every port (TS / C# / Python today; Java SPI version -forthcoming), so any future port automatically inherits the contract. +compose for that test — the same wire format consumers use at runtime. Each +port's conformance adapter maps those ids to its own provider objects, and the +fixtures run in every port (TypeScript, C#, Java, Kotlin, Python), so any future +port inherits the contract. `provider-custom-vocabulary-success` loads a +project-defined subtype plus attributes on a core type with the provider; +`provider-custom-vocabulary-missing-provider-fails` refuses the same file +without it. ## When to write a provider vs. inline metadata @@ -384,15 +633,14 @@ overlay semantics, common patterns). core vocabulary.** Example: `source.rdb` is a persistence-paradigm split — there will eventually be `source.kv`, `source.graph`, etc., and they all need first-class subtype identity for cross-port codegen routing. -- **You need load-time error detection when the provider is missing.** The - loader treats undeclared `@-attrs` as **open policy** — they're silently - accepted, no error or warning (`attr-schema-validate.ts:15`). Only the - *subtype* itself is validated against the registry. So if your concept's - correctness depends on the provider being loaded (e.g., a custom generator - must run when the metadata is present), subtype registration is the only - mechanism that catches "consumer forgot to wire the provider" at load - time via `ERR_UNKNOWN_SUBTYPE`. With pure attr-extension, missing - providers silently no-op. +- **You need load-time error detection even in a lax load.** A strict load + (the default for every tool) refuses an undeclared `@-attr` with + `ERR_UNKNOWN_ATTR`, so a missing provider is caught either way. A lax load + (`--lax`, `strict: false`) accepts undeclared attrs and refuses only an + unknown *subtype*. So if your concept's correctness depends on the provider + being loaded even where a project loads laxly, subtype registration is the + mechanism that still catches "consumer forgot to wire the provider", via + `ERR_UNKNOWN_SUBTYPE`. If the only argument for a new subtype is "the name reads nicer," add an attr instead. A subtype is a permanent commitment in every port's registry; @@ -419,13 +667,13 @@ configuration rich. ## Cross-port parity status -| Port | API | Status | -|---|---|---| -| TypeScript | `loadMemory(repoRoot, { providers })` + `defineConfig({ providers })` | Shipped | -| C# | `Provider.ComposeRegistry(providers)` → `MetaDataLoader.FromDirectory(dir, registry)` | Shipped | -| Python | `MetaDataLoader.from_directory(dir, providers=...)` | Shipped | -| Java | SPI via `META-INF/services/com.metaobjects.registry.MetaDataTypeProvider` | Shipped (SPI auto-discovery; programmatic `compose()` factory is a follow-up) | -| Kotlin | Inherits Java SPI through `metadata-ktx` | Shipped | +| Port | Project config | Programmatic | Status | +|---|---|---|---| +| TypeScript | `defineConfig({ providers })` in `metaobjects.config.ts` | `loadMemory(root, { providers })` | Shipped | +| Python | `providers: ["module:symbol"]` in `metaobjects.config.yaml`, plus `--provider` | `MetaDataLoader.from_directory(dir, providers=[*core_providers, ...])` | Shipped | +| C# | `csharp.providers: [{ assembly, type }]` in `.metaobjects/config.json` | `Provider.ComposeRegistry(...)` → `MetaDataLoader.FromDirectory(dir, registry)` | Shipped | +| Java | Maven plugin ``; Spring `MetaDataTypeProvider` beans | `LoaderOptions.setProviders(...)` | Shipped | +| Kotlin | Maven plugin ``; Spring beans | `metadata-ktx` `loadUris(..., providers = listOf(...))` | Shipped | All five ports compose providers in **dependency order** (Kahn's algorithm) and emit the same stable error codes when composition fails. @@ -466,10 +714,10 @@ root-level), so you do **not** hand-walk the tree in a `validate` hook. ## See also - [`../recipes/extending-metaobjects-with-providers.md`](../recipes/extending-metaobjects-with-providers.md) — hands-on walkthrough -- [`../ports/typescript.md`](../ports/typescript.md), [`../ports/csharp.md`](../ports/csharp.md), [`../ports/python.md`](../ports/python.md), [`../ports/java.md`](../ports/java.md) — per-port quickstarts +- [`../ports/typescript.md`](../ports/typescript.md), [`../ports/csharp.md`](../ports/csharp.md), [`../ports/python.md`](../ports/python.md), [`../ports/java.md`](../ports/java.md), [`../ports/kotlin.md`](../ports/kotlin.md) — per-port quickstarts - [`templates-and-payloads.md`](templates-and-payloads.md) — the core `template.prompt` + `template.output` subtypes that a custom `template.toolcall` slots alongside - [`source-kinds.md`](source-kinds.md) — the `source.rdb` example of `extend`-style provider use (adds `@table`, `@kind`, `@role`, `@schema` to a core subtype) -- [`../../fixtures/conformance/`](../../fixtures/conformance/) — `provider-extension-*` fixtures +- [`../../fixtures/conformance/`](../../fixtures/conformance/) — `provider-extension-*` and `provider-custom-vocabulary-*` fixtures - [`../../fixtures/conformance/ERROR-CODES.json`](../../fixtures/conformance/ERROR-CODES.json) — stable error code dictionary diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 3d40f8f739..8edc20fae2 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -906,13 +906,13 @@ provider class** in each language: a JSON file could express the declarative sur | Port | How the CLI / build tool loads your provider | |---|---| -| **TypeScript** | `metaobjects.config.ts` → `providers: [myProvider]`. Threaded into `meta gen` (the docs site included), `meta verify`, **and** the offline `meta migrate` paths (baseline + generate). | +| **TypeScript** | `metaobjects.config.ts` → `providers: [myProvider]`. Every command that loads metadata reads it: `meta gen` (the docs site included), `verify`, `export`, `deps`, `fmt`, `types`, `upgrade` and the offline `migrate` paths. | | **Python** | `metaobjects gen \| verify --provider module:symbol` (repeatable). The symbol resolves to a `Provider` (or a list, or a zero-arg factory returning one) and is composed **on top of** the core providers — parity with TS `config.providers`. E.g. `metaobjects gen --provider myapp.providers:view_provider`. A declarative `metaobjects.config.yaml` `providers:` list is also supported (resolved config-relative, no `PYTHONPATH=` — mirroring TS's config-file providers); see [`cli.md`](cli.md). | -| **Java / Kotlin** | Put your compiled `MetaDataTypeProvider` on the **project classpath** with a `META-INF/services/com.metaobjects.registry.MetaDataTypeProvider` entry. `metaobjects-maven-plugin` builds the loader with the project classloader, so **Java ServiceLoader auto-discovers it** — no plugin config needed. | -| **C#** | The loader accepts providers like every port; a first-class `dotnet meta` consumer-provider hook is tracked for a future release ([#158](https://github.com/metaobjectsdev/metaobjects/issues/158)). Today, extend the metamodel from an app that constructs the loader directly. | +| **Java / Kotlin** | Name the class in the `metaobjects-maven-plugin` `` list (or `-Dmeta.providers`), or declare it as a Spring `MetaDataTypeProvider` bean. Nothing is discovered from the classpath: a `META-INF/services` entry does not add the provider to the loader. See [`extending-with-providers.md`](extending-with-providers.md#java). | +| **C#** | Name the built assembly and type under `csharp.providers: [{ assembly, type }]` in `.metaobjects/config.json`; `dotnet meta gen`, `verify`, `fmt` load it. See [`extending-with-providers.md`](extending-with-providers.md#c). | This split follows each ecosystem's norms — interpreted ports (TS / Python) name or -import the provider module; compiled ports (JVM) discover it on the build classpath — +import the provider module; compiled ports (JVM, C#) name the provider class in their build config — the same "idiomatic per port" principle as generator ownership ([Per port](#per-port)). ## Removed at 1.0, restored in 1.1 diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 01a0b3687e..02f28069b3 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -120,27 +120,40 @@ does and does not do is in ### Custom providers (optional) -If your app needs a metamodel subtype the core doesn't ship, declare an -`IMetaDataTypeProvider` and compose it into the registry before loading: +When the project needs a subtype or an attribute the core does not ship, write a public class +implementing `IMetaDataTypeProvider` (with a public parameterless constructor) in its own +class library, and list the built assembly in `.metaobjects/config.json`: -```csharp -using MetaObjects; -using MetaObjects.Loader; +```json +{ + "schema_version": 1, + "csharp": { + "providers": [ + { "assembly": "vocabulary/bin/Debug/net8.0/Acme.Vocabulary.dll", "type": "Acme.Vocabulary.AcmeVocabularyProvider" } + ] + } +} +``` -var registry = Provider.ComposeRegistry(new IMetaDataTypeProvider[] { - CoreTypes.CoreTypesProvider, - yourProvider, // adds your custom subtype/attrs -}); +`assembly` is relative to the directory holding `.metaobjects/`. Build the vocabulary first; +a missing dll, a missing type or a type that is not a provider is refused with an error +naming `csharp.providers`. `dotnet meta gen` and `verify --codegen` (through the `codegen/` +runner), `dotnet meta verify` and `dotnet meta fmt` then all compose the core providers plus +these. An application that loads the model itself composes the registry, and +`ComposeRegistry` takes exactly the set it is given: -var loader = MetaDataLoader.FromDirectory("./metaobjects", registry); +```csharp +var registry = Provider.ComposeRegistry([.. CoreTypes.LibraryProviders, new AcmeVocabularyProvider()]); +var load = MetaDataLoader.FromDirectory("./metaobjects", registry, strict: true); ``` -The provider object has the same four-member contract (`Id`, `Dependencies`, -`Description`, `RegisterTypes(registry)`) as TS / Python. Composition errors -surface `ERR_PROVIDER_DUPLICATE_ID`, `ERR_PROVIDER_MISSING_DEPENDENCY`, -`ERR_PROVIDER_DEPENDENCY_CYCLE` — codes match the cross-port contract. See -[`../features/extending-with-providers.md`](../features/extending-with-providers.md) -for the full reference and +The provider object has the same contract (`Id`, `Dependencies`, `RegisterTypes(registry)` +calling `Register` and `Extend`) as the other ports. Composition errors surface +`ERR_PROVIDER_DUPLICATE_ID`, `ERR_PROVIDER_MISSING_DEPENDENCY` and +`ERR_PROVIDER_DEPENDENCY_CYCLE`. If another port's tools load the same metadata, that port needs its own copy of the +provider (same id, same vocabulary); a provider registered in one language is invisible to +the others. See [`../features/extending-with-providers.md`](../features/extending-with-providers.md) for the full reference with a worked +`AcmeVocabularyProvider`, and [`../recipes/extending-metaobjects-with-providers.md`](../recipes/extending-metaobjects-with-providers.md) for a worked example. diff --git a/docs/ports/java.md b/docs/ports/java.md index 6e594802b9..05c15aef69 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -209,50 +209,61 @@ auto-load of the snapshot and `verify` drift for dependencies are separate, late ### Custom providers (optional) -Java uses **SPI auto-discovery** for type providers — drop your provider -class on the classpath, list its FQCN in -`META-INF/services/com.metaobjects.registry.MetaDataTypeProvider`, and -`MetaDataRegistry.getInstance()` will compose it in dependency order -alongside the core providers: +When the project needs a subtype or an attribute the core does not ship, write a class +implementing `com.metaobjects.registry.MetaDataTypeProvider` (public, with a public no-arg +constructor) and name it explicitly. The loader composes the full metamodel provider set plus +exactly the providers you name; **listing a class in `META-INF/services` does not add it to +the loader**, so a jar on the classpath cannot change the vocabulary by accident. ```java -// src/main/java/com/example/providers/ExampleToolcallProvider.java -package com.example.providers; +package com.acme.vocab; -import com.metaobjects.registry.MetaDataTypeProvider; -import com.metaobjects.registry.MetaDataRegistry; - -public class ExampleToolcallProvider implements MetaDataTypeProvider { - @Override public String getProviderId() { return "example-template-toolcall"; } - @Override public String[] getDependencies() { return new String[] { "core-types" }; } +public final class AcmeVocabulary implements MetaDataTypeProvider { + public static final class PickerLayout extends MetaLayout { + public PickerLayout(String name) { super("picker", name); } + } + @Override public String getProviderId() { return "acme-vocabulary"; } + // JVM provider ids: field-types and layout-types register those types. + @Override public String[] getDependencies() { return new String[] {"field-types", "layout-types"}; } @Override public void registerTypes(MetaDataRegistry registry) { - // registry.register(...) — see the cross-port contract + registry.registerType(PickerLayout.class, def -> { // a new subtype: layout.picker + def.type("layout").subType("picker").inheritsFrom("layout", "base"); + def.optionalAttributeWithConstraints("displayField").ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + registry.extendType(StringField.class, def -> { // optional attrs on field.string + def.optionalAttributeWithConstraints("searchable").ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + def.optionalAttributeWithConstraints("valueLabels").ofType(StringAttribute.SUBTYPE_STRING).asArray(); + }); } } ``` -``` -# src/main/resources/META-INF/services/com.metaobjects.registry.MetaDataTypeProvider -com.example.providers.ExampleToolcallProvider +Wire it in the plugin configuration, with the provider's module on the plugin's classpath (a +project dependency or the plugin's ``; a provider in the same module is not yet +compiled at `generate-sources`): + +```xml + + + com.acme.vocab.AcmeVocabulary + + ``` -The provider contract is structurally identical to TS / C# / Python (id + -dependencies + description + `registerTypes` body); the loader composes -all providers via Kahn's algorithm and emits the same stable error codes -on failure (`ERR_PROVIDER_DUPLICATE_ID`, `_MISSING_DEPENDENCY`, -`_DEPENDENCY_CYCLE`). - -For callers who want to bypass SPI auto-discovery — or compose extra -consumer vocabulary on top of the full metamodel provider set so it still -strict-loads against the spec contract (no `--lax` fallback) — the -sanctioned seam is -`RegistryManifest.composeMetamodelRegistry(extraProviders)`, which composes -the core metamodel providers plus `extraProviders` and runs the full -spec-description + provenance-safe attr-scoping pipeline (hand the result -to `loader.setTypeRegistry(...)`). Raw `MetaDataRegistry.compose(...)` -composes only the explicit list, skips spec scoping, and is for -internal/test partial sets. The cross-port contract lives in -[`../features/extending-with-providers.md`](../features/extending-with-providers.md). +`metaobjects:generate` (with its docs generators), `metaobjects:verify`, `metaobjects:fmt` and +`metaobjects:editor` all load it. A Spring Boot app declares the provider as a +`MetaDataTypeProvider` bean and the auto-configured loader composes it. Code that loads the +model itself passes it on the options: +`LoaderOptions.create(false, false, true).setProviders(List.of(new AcmeVocabulary()))`, which +composes through `RegistryManifest.composeLoaderRegistry(extras)`. Raw +`MetaDataRegistry.compose(...)` composes only the explicit list, skips spec scoping, and is +for internal and test partial sets. + +Composition fails with the same stable codes as every other port (`ERR_PROVIDER_DUPLICATE_ID`, +`ERR_PROVIDER_MISSING_DEPENDENCY`, `ERR_PROVIDER_DEPENDENCY_CYCLE`). If another port's tools load the same metadata, that port needs its own copy of the +provider (same id, same vocabulary); a provider registered in one language is invisible to +the others. Full contract and +the other languages' versions: [`../features/extending-with-providers.md`](../features/extending-with-providers.md). ## Generate diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index 108505e5c4..6f9def8b25 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -339,15 +339,36 @@ The data dict itself: [`codegen-data-shapes.md`](../features/codegen-data-shapes ### Custom providers (optional) -Kotlin inherits Java's SPI-based provider discovery directly — write a -`MetaDataTypeProvider` implementation (or its Kotlin DSL equivalent in -`metadata-ktx`), drop the FQCN into -`META-INF/services/com.metaobjects.registry.MetaDataTypeProvider`, and the -loader picks it up alongside the core providers. See the Java port's -[Custom providers section](java.md#custom-providers-optional) for the -mechanism; the -[`../features/extending-with-providers.md`](../features/extending-with-providers.md) -reference covers the cross-port contract. +Kotlin runs on the JVM registry, so a provider is a `MetaDataTypeProvider` written in Kotlin +and is wired exactly as in Java: the plugin's `FQCN` +list (Kotlin generators run through `metaobjects:generate`, so `generate`, `verify`, `fmt` +and `editor` all load it), a `MetaDataTypeProvider` bean in a Spring Boot app, or the +`metadata-ktx` loader's `providers` parameter: + +```kotlin +class PickerLayout(name: String) : MetaLayout("picker", name) + +class AcmeVocabulary : MetaDataTypeProvider { + override fun getProviderId() = "acme-vocabulary" + override fun getDependencies() = arrayOf("field-types", "layout-types") + override fun registerTypes(registry: MetaDataRegistry) { + registry.registerType(PickerLayout::class.java) { def -> + def.type("layout").subType("picker").inheritsFrom("layout", "base") + def.optionalAttributeWithConstraints("displayField").ofType("string").asSingle() + } + registry.extendType(StringField::class.java) { def -> + def.optionalAttributeWithConstraints("searchable").ofType("boolean").asSingle() + def.optionalAttributeWithConstraints("valueLabels").ofType("string").asArray() + } + } +} + +val result = loadUris("app", uris, LoaderOptions.create(false, false, true), providers = listOf(AcmeVocabulary())) +``` + +`META-INF/services` does not add a provider to the loader. See the Java port's +[Custom providers section](java.md#custom-providers-optional) for the plugin wiring, and +[`../features/extending-with-providers.md`](../features/extending-with-providers.md) for the cross-port contract. ### Exposed 1.x output (`exposedApi`) diff --git a/docs/ports/python.md b/docs/ports/python.md index e592bd61d8..ff6fdeb94b 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -99,23 +99,35 @@ metadata: ### Custom providers (optional) -If your app needs a metamodel subtype the core doesn't ship, declare a -`Provider` and pass it through `from_directory`: +When the project needs a subtype or an attribute the core does not ship, declare a +`metaobjects.provider.Provider` in a module beside `metaobjects.config.yaml` and list it as +`module:symbol`: + +```yaml +metadata: metaobjects +providers: ["acme_vocab:provider"] +``` + +The module resolves relative to the config's directory. `metaobjects gen` (with its docs +generators), every `metaobjects verify` mode and `metaobjects fmt` load that list, and +`--provider module:symbol` adds to it for one run. Code that loads the model itself passes the +full set, core first, because `providers=` is exactly what is composed: ```python -from metaobjects.provider import Provider -from metaobjects import MetaDataLoader -from .providers import your_provider +from metaobjects.core_types import core_providers +from metaobjects.loader.meta_data_loader import MetaDataLoader +from acme_vocab import provider -result = MetaDataLoader.from_directory("./metaobjects", providers=[your_provider]) +result = MetaDataLoader.from_directory("./metaobjects", providers=[*core_providers, provider], strict=True) ``` -The provider object has the same four-member contract (`id`, `dependencies`, -`description`, `register_types(registry)`) as TS / C#. Composition errors -surface `ERR_PROVIDER_DUPLICATE_ID`, `ERR_PROVIDER_MISSING_DEPENDENCY`, -`ERR_PROVIDER_DEPENDENCY_CYCLE` — codes match the cross-port contract. See -[`../features/extending-with-providers.md`](../features/extending-with-providers.md) -for the full reference and +The provider has the same contract (an id, its dependencies, `TypeDefinition`s added with +`add`, and an `on_register` hook that `extend`s existing types) as the other ports. +Composition errors surface `ERR_PROVIDER_DUPLICATE_ID`, `ERR_PROVIDER_MISSING_DEPENDENCY` and +`ERR_PROVIDER_DEPENDENCY_CYCLE`. If another port's tools load the same metadata, that port needs its own copy of the +provider (same id, same vocabulary); a provider registered in one language is invisible to +the others. See [`../features/extending-with-providers.md`](../features/extending-with-providers.md) for the full reference with a worked +provider, and [`../recipes/extending-metaobjects-with-providers.md`](../recipes/extending-metaobjects-with-providers.md) for a worked example. diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index c274d65c52..d762566dc2 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -260,9 +260,12 @@ export default defineConfig({ }); ``` -The CLI threads the list into every `meta gen` / `meta verify` / `meta -migrate` / `meta prompt-snapshot` invocation. At the SDK level the same -list is accepted directly: +Every `meta` command that loads metadata reads the list: `gen` (with the docs +generators and the docs site), `verify`, `migrate`, `fmt`, `types`, `export`, +`deps`, `upgrade` and `prompt-snapshot`. A config that fails to load is reported +as its own error, never as an unknown subtype. If another port's tools load the +same metadata, that port needs its own copy of the provider. At the SDK level +the same list is accepted directly: ```ts import { loadMemory } from "@metaobjectsdev/sdk"; diff --git a/docs/recipes/extending-metaobjects-with-providers.md b/docs/recipes/extending-metaobjects-with-providers.md index 643faaa44d..a2a555b60e 100644 --- a/docs/recipes/extending-metaobjects-with-providers.md +++ b/docs/recipes/extending-metaobjects-with-providers.md @@ -2,8 +2,8 @@ This recipe walks through adding a new metamodel subtype to a downstream project — using the same `example-template-toolcall` example the conformance -fixtures use, so the example here matches a real test that runs in TS, C#, -and Python. +fixtures use, so the example here matches a real test that runs in every +port. For the conceptual reference (what a provider is, the error codes, the cross-port semantic rule), see @@ -202,18 +202,11 @@ That's the value: **the metamodel becomes self-checking**. The toolcall declarations and the provider that gives them meaning live in the same project, and any divergence is caught at the load boundary, not at runtime. -## C# / Python equivalents +## The other languages -The C# and Python ports use the same provider contract — the only difference -is the API surface for loader composition. See the per-port quickstarts: - -- [`../ports/csharp.md`](../ports/csharp.md) -- [`../ports/python.md`](../ports/python.md) - -The provider object itself is structurally identical across languages -(id + dependencies + description + a body that calls `registry.register` or -`registry.extend`). A C# port of `exampleProvider` reads exactly like the TS -version with C# spelling. +Every port takes a provider the same way in principle, wired in its own config. The per-language +wiring, with a worked example for each, is in +[`../features/extending-with-providers.md`](../features/extending-with-providers.md#wiring-providers-into-the-loader). ## When NOT to write a provider @@ -237,4 +230,4 @@ metadata files, requires its own validation, and benefits from custom codegen. - [`../../fixtures/conformance/provider-extension-new-subtype-success/`](../../fixtures/conformance/provider-extension-new-subtype-success/) — the matching conformance fixture - The conformance fixture at [`../../fixtures/conformance/provider-extension-new-subtype-success/`](../../fixtures/conformance/provider-extension-new-subtype-success/) — - a runnable proof of this exact pattern across TS / C# / Python + a runnable proof of this exact pattern in every port diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 7330d646f0..0dc75bd7a6 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.2" }, "counts": { - "fixtures": 426, + "fixtures": 428, "corpora": 35, "baseTypes": 17 }, diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index 008e5dae1b..a1a3fe6c0b 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -455,6 +455,12 @@ Several variants of one thing sharing **one table**: the base `object.entity` de `@discriminatorValue`. Codegen emits per-subtype routes with the discriminator injected and immutable. Supported in all five ports; the worked example is in `references/inheritance-tph.md`. +## Your own vocabulary — a provider class, in every language + +A subtype or attribute the core does not ship (a `layout.picker`, `@searchable` on fields) is registered by a **provider class** in the project's own language — never a side file, never a loosened `strict`. Decide the shape first (`references/choosing-a-shape.md`, which also has the register/extend rules). List the provider once in the port's project configuration and every command that loads metadata — gen and its docs generators, verify, fmt — composes it. Where each port lists it, plus a worked example: `references/typescript-providers.md`, `references/python-providers.md`, `references/csharp-providers.md`, `references/java-providers.md`, `references/kotlin-providers.md` (only this stack's are installed). + +**Every port whose tools load the metadata needs its own copy**: a TypeScript-only provider leaves the Java, Python or C# side, and its docs build, failing with `ERR_UNKNOWN_SUBTYPE` / `ERR_UNKNOWN_ATTR`. + ## Requirements — capability ledger (opt-in) **This capability exists whether or not the project uses it yet.** `requirement.functional` and `requirement.architectural` are registered metadata types, declared in the metadata directory beside the entities they describe and loaded by the same loader — no side file, no bespoke parser. They record *why* each part of the model exists, so a field with no reason to exist becomes visible as one. diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md index 7ae89655d9..ee3b6858a5 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md @@ -162,6 +162,17 @@ or behavior is a **subtype**, and structural variants *within* such a subtype ar (including any `@kind` value-set) carry `allowedValues` in the gate (ADR-0036). ADR-0037 is the authority. +**What a provider does.** It names an `id` and the provider ids it depends on, then does one +or both of two things. It **registers** a new `(type, subType)` with its own attributes, which +may be required, and a node class (reuse the type's existing one unless the node has new +behaviour). It **extends** an existing `(type, subType)` with attributes, which must be +optional: a required one is `ERR_EXTEND_REQUIRED_ATTR` (ADR-0050), because removing your +provider must never weaken a type someone else owns. A new type allowed at the document root +also needs `extend` on `metadata.root` to admit it, or it fails with `ERR_CHILD_NOT_ALLOWED`. +An attribute no provider declares is `ERR_UNKNOWN_ATTR` under a strict load, and a subtype +nobody registered is `ERR_UNKNOWN_SUBTYPE`; that refusal is what keeps a typo from loading. +The per-language example and wiring is in the skill's `references/-providers.md`. + **Converge before inventing.** Search the shipped vocabulary first (`meta types `) and check the roadmap — if core already models (or plans) the concept, model yours in a fold-in-friendly shape. The type names `api`, `operation`, `surface`, and diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/java-providers.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/java-providers.md new file mode 100644 index 0000000000..8b7b598054 --- /dev/null +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/java-providers.md @@ -0,0 +1,93 @@ +# Your own vocabulary in Java — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its Java tools load the metadata. + +A provider is a public class implementing `com.metaobjects.registry.MetaDataTypeProvider`, with +a public no-arg constructor: a provider id, the provider ids it depends on (the JVM ids: +`field-types` registers the field types, `layout-types` the layouts), and a `registerTypes` +body that calls `registerType` (a new subtype, backed by its own node class) and `extendType` +(attributes on an existing one). This one registers `layout.picker` and adds `@searchable` and +`@valueLabels` to `field.string`: + +```java +package com.acme.vocab; + +import com.metaobjects.attr.BooleanAttribute; +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.field.StringField; +import com.metaobjects.layout.MetaLayout; +import com.metaobjects.registry.MetaDataRegistry; +import com.metaobjects.registry.MetaDataTypeProvider; + +public final class AcmeVocabulary implements MetaDataTypeProvider { + /** The node class behind layout.picker. */ + public static final class PickerLayout extends MetaLayout { + public PickerLayout(String name) { super("picker", name); } + } + + @Override public String getProviderId() { return "acme-vocabulary"; } + @Override public String[] getDependencies() { return new String[] {"field-types", "layout-types"}; } + + @Override public void registerTypes(MetaDataRegistry registry) { + // A new subtype, with its own attribute (an own attribute may be required). + registry.registerType(PickerLayout.class, def -> { + def.type("layout").subType("picker").inheritsFrom("layout", "base"); + def.optionalAttributeWithConstraints("displayField").ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + // Attributes on a type another provider owns: always optional. + registry.extendType(StringField.class, def -> { + def.optionalAttributeWithConstraints("searchable").ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + def.optionalAttributeWithConstraints("valueLabels").ofType(StringAttribute.SUBTYPE_STRING).asArray(); + }); + } +} +``` + +Wire it once, in the `metaobjects-maven-plugin` configuration. The class must be on the +plugin's classpath: put the provider in its own module and add that module as a project +dependency or under the plugin's ``. A provider in the same module is not +compiled yet when `generate` runs at `generate-sources`. + +```xml + + com.metaobjects + metaobjects-maven-plugin + + + com.acme.vocab.AcmeVocabulary + + + + com.acmeacme-vocabulary1.0 + + +``` + +`metaobjects:generate` (with its docs generators), `metaobjects:verify`, `metaobjects:fmt` and +`metaobjects:editor` all compose the metamodel providers plus these. Listing a class in +`META-INF/services` does NOT add it to the loader: the strict loader composes a fixed +metamodel set plus the providers you name, so a jar on the classpath cannot change the +vocabulary by accident. + +In a Spring Boot app, declare the provider as a bean and the auto-configured loader composes +it: `@Bean MetaDataTypeProvider acmeVocabulary() { return new AcmeVocabulary(); }`. Code that +loads the model itself passes it on the options: + +```java +MetaDataLoader.fromUris("app", uris, + LoaderOptions.create(false, false, true).setProviders(List.of(new AcmeVocabulary()))); +``` + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `metaobjects:verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (the same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/kotlin-providers.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/kotlin-providers.md new file mode 100644 index 0000000000..09d6c6c4a4 --- /dev/null +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/kotlin-providers.md @@ -0,0 +1,77 @@ +# Your own vocabulary in Kotlin — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its Kotlin tools load the +> metadata. + +Kotlin runs on the JVM registry, so a provider is a class implementing +`com.metaobjects.registry.MetaDataTypeProvider`, written in Kotlin: a provider id, the JVM +provider ids it depends on (`field-types`, `layout-types`), and a `registerTypes` body that +calls `registerType` (a new subtype, backed by its own node class) and `extendType` +(attributes on an existing one). This one registers `layout.picker` and adds `@searchable` and +`@valueLabels` to `field.string`: + +```kotlin +package com.acme.vocab + +import com.metaobjects.field.StringField +import com.metaobjects.layout.MetaLayout +import com.metaobjects.registry.MetaDataRegistry +import com.metaobjects.registry.MetaDataTypeProvider + +/** The node class behind layout.picker. */ +class PickerLayout(name: String) : MetaLayout("picker", name) + +class AcmeVocabulary : MetaDataTypeProvider { + override fun getProviderId() = "acme-vocabulary" + override fun getDependencies() = arrayOf("field-types", "layout-types") + + override fun registerTypes(registry: MetaDataRegistry) { + // A new subtype, with its own attribute (an own attribute may be required). + registry.registerType(PickerLayout::class.java) { def -> + def.type("layout").subType("picker").inheritsFrom("layout", "base") + def.optionalAttributeWithConstraints("displayField").ofType("string").asSingle() + } + // Attributes on a type another provider owns: always optional. + registry.extendType(StringField::class.java) { def -> + def.optionalAttributeWithConstraints("searchable").ofType("boolean").asSingle() + def.optionalAttributeWithConstraints("valueLabels").ofType("string").asArray() + } + } +} +``` + +Wire it once. Kotlin generators run through `metaobjects:generate`, so the build lists it in +the `metaobjects-maven-plugin` configuration, with the provider's module on the plugin's +classpath (a project dependency or the plugin's ``; a provider in the same +module is not compiled yet at `generate-sources`): + +```xml + + + com.acme.vocab.AcmeVocabulary + + +``` + +`generate`, `verify`, `fmt` and `editor` then all load it. `META-INF/services` does not add a +provider to the loader. In a Spring Boot app, a `MetaDataTypeProvider` bean is composed into +the auto-configured loader. Code that loads the model through the `metadata-ktx` facade passes +it directly: + +```kotlin +val result = loadUris("app", uris, LoaderOptions.create(false, false, true), providers = listOf(AcmeVocabulary())) +``` + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `metaobjects:verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (the same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md index a030b08545..36123e0d8f 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -430,6 +430,11 @@ template hack. See the decision procedure in the **`metaobjects-authoring`** ski array column type) and a native UUID is `field.uuid` (not a string + `@dbColumnType`). When you register custom vocabulary for a custom generator, the same ADR-0037 procedure decides whether it's a subtype, a `@kind` variant, or an attribute. +The vocabulary itself is a provider class, listed once in the port's project +configuration so `gen`, `verify --codegen` and the docs generators all load it (the +**`metaobjects-authoring`** skill, "Your own vocabulary", has the per-language example). +A generator then reads the custom attribute like any other: through the resolving +accessor on the node, never by re-parsing the file. ## Per-target output diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md index 008e5dae1b..a1a3fe6c0b 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -455,6 +455,12 @@ Several variants of one thing sharing **one table**: the base `object.entity` de `@discriminatorValue`. Codegen emits per-subtype routes with the discriminator injected and immutable. Supported in all five ports; the worked example is in `references/inheritance-tph.md`. +## Your own vocabulary — a provider class, in every language + +A subtype or attribute the core does not ship (a `layout.picker`, `@searchable` on fields) is registered by a **provider class** in the project's own language — never a side file, never a loosened `strict`. Decide the shape first (`references/choosing-a-shape.md`, which also has the register/extend rules). List the provider once in the port's project configuration and every command that loads metadata — gen and its docs generators, verify, fmt — composes it. Where each port lists it, plus a worked example: `references/typescript-providers.md`, `references/python-providers.md`, `references/csharp-providers.md`, `references/java-providers.md`, `references/kotlin-providers.md` (only this stack's are installed). + +**Every port whose tools load the metadata needs its own copy**: a TypeScript-only provider leaves the Java, Python or C# side, and its docs build, failing with `ERR_UNKNOWN_SUBTYPE` / `ERR_UNKNOWN_ATTR`. + ## Requirements — capability ledger (opt-in) **This capability exists whether or not the project uses it yet.** `requirement.functional` and `requirement.architectural` are registered metadata types, declared in the metadata directory beside the entities they describe and loaded by the same loader — no side file, no bespoke parser. They record *why* each part of the model exists, so a field with no reason to exist becomes visible as one. diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md index 7ae89655d9..ee3b6858a5 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md @@ -162,6 +162,17 @@ or behavior is a **subtype**, and structural variants *within* such a subtype ar (including any `@kind` value-set) carry `allowedValues` in the gate (ADR-0036). ADR-0037 is the authority. +**What a provider does.** It names an `id` and the provider ids it depends on, then does one +or both of two things. It **registers** a new `(type, subType)` with its own attributes, which +may be required, and a node class (reuse the type's existing one unless the node has new +behaviour). It **extends** an existing `(type, subType)` with attributes, which must be +optional: a required one is `ERR_EXTEND_REQUIRED_ATTR` (ADR-0050), because removing your +provider must never weaken a type someone else owns. A new type allowed at the document root +also needs `extend` on `metadata.root` to admit it, or it fails with `ERR_CHILD_NOT_ALLOWED`. +An attribute no provider declares is `ERR_UNKNOWN_ATTR` under a strict load, and a subtype +nobody registered is `ERR_UNKNOWN_SUBTYPE`; that refusal is what keeps a typo from loading. +The per-language example and wiring is in the skill's `references/-providers.md`. + **Converge before inventing.** Search the shipped vocabulary first (`meta types `) and check the roadmap — if core already models (or plans) the concept, model yours in a fold-in-friendly shape. The type names `api`, `operation`, `surface`, and diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/java-providers.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/java-providers.md new file mode 100644 index 0000000000..8b7b598054 --- /dev/null +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/java-providers.md @@ -0,0 +1,93 @@ +# Your own vocabulary in Java — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its Java tools load the metadata. + +A provider is a public class implementing `com.metaobjects.registry.MetaDataTypeProvider`, with +a public no-arg constructor: a provider id, the provider ids it depends on (the JVM ids: +`field-types` registers the field types, `layout-types` the layouts), and a `registerTypes` +body that calls `registerType` (a new subtype, backed by its own node class) and `extendType` +(attributes on an existing one). This one registers `layout.picker` and adds `@searchable` and +`@valueLabels` to `field.string`: + +```java +package com.acme.vocab; + +import com.metaobjects.attr.BooleanAttribute; +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.field.StringField; +import com.metaobjects.layout.MetaLayout; +import com.metaobjects.registry.MetaDataRegistry; +import com.metaobjects.registry.MetaDataTypeProvider; + +public final class AcmeVocabulary implements MetaDataTypeProvider { + /** The node class behind layout.picker. */ + public static final class PickerLayout extends MetaLayout { + public PickerLayout(String name) { super("picker", name); } + } + + @Override public String getProviderId() { return "acme-vocabulary"; } + @Override public String[] getDependencies() { return new String[] {"field-types", "layout-types"}; } + + @Override public void registerTypes(MetaDataRegistry registry) { + // A new subtype, with its own attribute (an own attribute may be required). + registry.registerType(PickerLayout.class, def -> { + def.type("layout").subType("picker").inheritsFrom("layout", "base"); + def.optionalAttributeWithConstraints("displayField").ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + // Attributes on a type another provider owns: always optional. + registry.extendType(StringField.class, def -> { + def.optionalAttributeWithConstraints("searchable").ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + def.optionalAttributeWithConstraints("valueLabels").ofType(StringAttribute.SUBTYPE_STRING).asArray(); + }); + } +} +``` + +Wire it once, in the `metaobjects-maven-plugin` configuration. The class must be on the +plugin's classpath: put the provider in its own module and add that module as a project +dependency or under the plugin's ``. A provider in the same module is not +compiled yet when `generate` runs at `generate-sources`. + +```xml + + com.metaobjects + metaobjects-maven-plugin + + + com.acme.vocab.AcmeVocabulary + + + + com.acmeacme-vocabulary1.0 + + +``` + +`metaobjects:generate` (with its docs generators), `metaobjects:verify`, `metaobjects:fmt` and +`metaobjects:editor` all compose the metamodel providers plus these. Listing a class in +`META-INF/services` does NOT add it to the loader: the strict loader composes a fixed +metamodel set plus the providers you name, so a jar on the classpath cannot change the +vocabulary by accident. + +In a Spring Boot app, declare the provider as a bean and the auto-configured loader composes +it: `@Bean MetaDataTypeProvider acmeVocabulary() { return new AcmeVocabulary(); }`. Code that +loads the model itself passes it on the options: + +```java +MetaDataLoader.fromUris("app", uris, + LoaderOptions.create(false, false, true).setProviders(List.of(new AcmeVocabulary()))); +``` + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `metaobjects:verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (the same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md index a030b08545..36123e0d8f 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -430,6 +430,11 @@ template hack. See the decision procedure in the **`metaobjects-authoring`** ski array column type) and a native UUID is `field.uuid` (not a string + `@dbColumnType`). When you register custom vocabulary for a custom generator, the same ADR-0037 procedure decides whether it's a subtype, a `@kind` variant, or an attribute. +The vocabulary itself is a provider class, listed once in the port's project +configuration so `gen`, `verify --codegen` and the docs generators all load it (the +**`metaobjects-authoring`** skill, "Your own vocabulary", has the per-language example). +A generator then reads the custom attribute like any other: through the resolving +accessor on the node, never by re-parsing the file. ## Per-target output diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md index 008e5dae1b..a1a3fe6c0b 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -455,6 +455,12 @@ Several variants of one thing sharing **one table**: the base `object.entity` de `@discriminatorValue`. Codegen emits per-subtype routes with the discriminator injected and immutable. Supported in all five ports; the worked example is in `references/inheritance-tph.md`. +## Your own vocabulary — a provider class, in every language + +A subtype or attribute the core does not ship (a `layout.picker`, `@searchable` on fields) is registered by a **provider class** in the project's own language — never a side file, never a loosened `strict`. Decide the shape first (`references/choosing-a-shape.md`, which also has the register/extend rules). List the provider once in the port's project configuration and every command that loads metadata — gen and its docs generators, verify, fmt — composes it. Where each port lists it, plus a worked example: `references/typescript-providers.md`, `references/python-providers.md`, `references/csharp-providers.md`, `references/java-providers.md`, `references/kotlin-providers.md` (only this stack's are installed). + +**Every port whose tools load the metadata needs its own copy**: a TypeScript-only provider leaves the Java, Python or C# side, and its docs build, failing with `ERR_UNKNOWN_SUBTYPE` / `ERR_UNKNOWN_ATTR`. + ## Requirements — capability ledger (opt-in) **This capability exists whether or not the project uses it yet.** `requirement.functional` and `requirement.architectural` are registered metadata types, declared in the metadata directory beside the entities they describe and loaded by the same loader — no side file, no bespoke parser. They record *why* each part of the model exists, so a field with no reason to exist becomes visible as one. diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md index 7ae89655d9..ee3b6858a5 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md @@ -162,6 +162,17 @@ or behavior is a **subtype**, and structural variants *within* such a subtype ar (including any `@kind` value-set) carry `allowedValues` in the gate (ADR-0036). ADR-0037 is the authority. +**What a provider does.** It names an `id` and the provider ids it depends on, then does one +or both of two things. It **registers** a new `(type, subType)` with its own attributes, which +may be required, and a node class (reuse the type's existing one unless the node has new +behaviour). It **extends** an existing `(type, subType)` with attributes, which must be +optional: a required one is `ERR_EXTEND_REQUIRED_ATTR` (ADR-0050), because removing your +provider must never weaken a type someone else owns. A new type allowed at the document root +also needs `extend` on `metadata.root` to admit it, or it fails with `ERR_CHILD_NOT_ALLOWED`. +An attribute no provider declares is `ERR_UNKNOWN_ATTR` under a strict load, and a subtype +nobody registered is `ERR_UNKNOWN_SUBTYPE`; that refusal is what keeps a typo from loading. +The per-language example and wiring is in the skill's `references/-providers.md`. + **Converge before inventing.** Search the shipped vocabulary first (`meta types `) and check the roadmap — if core already models (or plans) the concept, model yours in a fold-in-friendly shape. The type names `api`, `operation`, `surface`, and diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/python-providers.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/python-providers.md new file mode 100644 index 0000000000..2e0a55db54 --- /dev/null +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/python-providers.md @@ -0,0 +1,69 @@ +# Your own vocabulary in Python — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its Python tools load the +> metadata. + +A provider is a `metaobjects.provider.Provider`: an id, the provider ids it depends on, the +`TypeDefinition`s it adds (a new subtype), and an `on_register` hook that `extend`s existing +types. This one registers `layout.picker` and adds `@searchable` and `@valueLabels` to +`field.string`: + +```python +# acme_vocab.py (beside metaobjects.config.yaml) +from metaobjects.meta.presentation.layout.meta_layout import MetaLayout +from metaobjects.provider import Provider +from metaobjects.registry import AttrSchema, ChildRule, TypeDefinition +from metaobjects.shared.base_types import TYPE_ATTR + +provider = Provider("acme-vocabulary", dependencies=("metaobjects-core-types",)) + +# A new subtype, with its own attribute (an own attribute may be required). +provider.add(TypeDefinition( + type="layout", sub_type="picker", factory=MetaLayout, + attrs=[AttrSchema("displayField", "string", required=False)], + child_rules=[ChildRule(TYPE_ATTR, "*")], +)) + +# Attributes on a type another provider owns: always optional. +provider.on_register(lambda registry: registry.extend( + "field", "string", + attributes=[ + AttrSchema("searchable", "boolean", required=False), + AttrSchema("valueLabels", "string", required=False, is_array=True), + ], +)) +``` + +Wire it once, in `metaobjects.config.yaml`, as `module:symbol`. The module resolves relative +to the config's directory, so no `PYTHONPATH` is needed: + +```yaml +metadata: metaobjects +providers: ["acme_vocab:provider"] +``` + +`metaobjects gen` (with its docs generators), every `metaobjects verify` mode and +`metaobjects fmt` read that list; `--provider module:symbol` adds to it for one run. Code that +loads the model itself passes the full list, core first, because `providers=` is exactly the +set composed: + +```python +from metaobjects.core_types import core_providers +from metaobjects.loader.meta_data_loader import MetaDataLoader + +result = MetaDataLoader.from_directory("metaobjects", providers=[*core_providers, provider], strict=True) +``` + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `metaobjects verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (same id, same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md index a030b08545..36123e0d8f 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -430,6 +430,11 @@ template hack. See the decision procedure in the **`metaobjects-authoring`** ski array column type) and a native UUID is `field.uuid` (not a string + `@dbColumnType`). When you register custom vocabulary for a custom generator, the same ADR-0037 procedure decides whether it's a subtype, a `@kind` variant, or an attribute. +The vocabulary itself is a provider class, listed once in the port's project +configuration so `gen`, `verify --codegen` and the docs generators all load it (the +**`metaobjects-authoring`** skill, "Your own vocabulary", has the per-language example). +A generator then reads the custom attribute like any other: through the resolving +accessor on the node, never by re-parsing the file. ## Per-target output diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index 008e5dae1b..a1a3fe6c0b 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -455,6 +455,12 @@ Several variants of one thing sharing **one table**: the base `object.entity` de `@discriminatorValue`. Codegen emits per-subtype routes with the discriminator injected and immutable. Supported in all five ports; the worked example is in `references/inheritance-tph.md`. +## Your own vocabulary — a provider class, in every language + +A subtype or attribute the core does not ship (a `layout.picker`, `@searchable` on fields) is registered by a **provider class** in the project's own language — never a side file, never a loosened `strict`. Decide the shape first (`references/choosing-a-shape.md`, which also has the register/extend rules). List the provider once in the port's project configuration and every command that loads metadata — gen and its docs generators, verify, fmt — composes it. Where each port lists it, plus a worked example: `references/typescript-providers.md`, `references/python-providers.md`, `references/csharp-providers.md`, `references/java-providers.md`, `references/kotlin-providers.md` (only this stack's are installed). + +**Every port whose tools load the metadata needs its own copy**: a TypeScript-only provider leaves the Java, Python or C# side, and its docs build, failing with `ERR_UNKNOWN_SUBTYPE` / `ERR_UNKNOWN_ATTR`. + ## Requirements — capability ledger (opt-in) **This capability exists whether or not the project uses it yet.** `requirement.functional` and `requirement.architectural` are registered metadata types, declared in the metadata directory beside the entities they describe and loaded by the same loader — no side file, no bespoke parser. They record *why* each part of the model exists, so a field with no reason to exist becomes visible as one. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md index 7ae89655d9..ee3b6858a5 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md @@ -162,6 +162,17 @@ or behavior is a **subtype**, and structural variants *within* such a subtype ar (including any `@kind` value-set) carry `allowedValues` in the gate (ADR-0036). ADR-0037 is the authority. +**What a provider does.** It names an `id` and the provider ids it depends on, then does one +or both of two things. It **registers** a new `(type, subType)` with its own attributes, which +may be required, and a node class (reuse the type's existing one unless the node has new +behaviour). It **extends** an existing `(type, subType)` with attributes, which must be +optional: a required one is `ERR_EXTEND_REQUIRED_ATTR` (ADR-0050), because removing your +provider must never weaken a type someone else owns. A new type allowed at the document root +also needs `extend` on `metadata.root` to admit it, or it fails with `ERR_CHILD_NOT_ALLOWED`. +An attribute no provider declares is `ERR_UNKNOWN_ATTR` under a strict load, and a subtype +nobody registered is `ERR_UNKNOWN_SUBTYPE`; that refusal is what keeps a typo from loading. +The per-language example and wiring is in the skill's `references/-providers.md`. + **Converge before inventing.** Search the shipped vocabulary first (`meta types `) and check the roadmap — if core already models (or plans) the concept, model yours in a fold-in-friendly shape. The type names `api`, `operation`, `surface`, and diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/typescript-providers.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/typescript-providers.md new file mode 100644 index 0000000000..5db6706b4f --- /dev/null +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/typescript-providers.md @@ -0,0 +1,74 @@ +# Your own vocabulary in TypeScript — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its TypeScript tools load the +> metadata. + +A provider is an object implementing `MetaDataTypeProvider`: an `id`, the provider ids it +depends on, and a `registerTypes(registry)` body that calls `register` (a new subtype) and +`extend` (attributes on an existing one). This one registers `layout.picker` and adds +`@searchable` and `@valueLabels` to `field.string`: + +```ts +// codegen/vocabulary.ts +import { TypeId, MetaLayout, type MetaDataTypeProvider } from "@metaobjectsdev/metadata"; +import { + TYPE_FIELD, TYPE_LAYOUT, FIELD_SUBTYPE_STRING, + ATTR_SUBTYPE_STRING, ATTR_SUBTYPE_BOOLEAN, +} from "@metaobjectsdev/metadata/constants"; + +export const vocabulary: MetaDataTypeProvider = { + id: "acme-vocabulary", + dependencies: ["metaobjects-core-types"], + registerTypes(registry) { + // A new subtype, with its own attribute (an own attribute may be required). + registry.register({ + typeId: new TypeId(TYPE_LAYOUT, "picker"), + description: "A picker over the owning object.", + factory: (typeId, name) => new MetaLayout(typeId, name), + childRules: [], + attributes: [ + { name: "displayField", valueType: ATTR_SUBTYPE_STRING, required: false, description: "Field shown per choice." }, + ], + }); + // Attributes on a type another provider owns: always optional. + registry.extend(TYPE_FIELD, FIELD_SUBTYPE_STRING, { + attributes: [ + { name: "searchable", valueType: ATTR_SUBTYPE_BOOLEAN, required: false, description: "Offer in search." }, + { name: "valueLabels", valueType: ATTR_SUBTYPE_STRING, isArray: true, required: false, description: "Display labels." }, + ], + }); + }, +}; +``` + +Wire it once, in `metaobjects.config.ts`: + +```ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { vocabulary } from "./codegen/vocabulary"; + +export default defineConfig({ + generators: [/* ... */], + providers: [vocabulary], +}); +``` + +Every `meta` command that loads metadata reads that list: `gen` (with the docs generators and +the docs site), `verify`, `migrate`, `fmt`, `types`, `export`, `deps`, `upgrade`. `meta types +picker` then lists the new subtype. A config that fails to load is reported as its own error, +never as an unknown subtype. Code that loads the model itself passes the same provider: +`loadMemory(root, { providers: [vocabulary] })`. + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `meta verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (same `id`, same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md index a030b08545..36123e0d8f 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -430,6 +430,11 @@ template hack. See the decision procedure in the **`metaobjects-authoring`** ski array column type) and a native UUID is `field.uuid` (not a string + `@dbColumnType`). When you register custom vocabulary for a custom generator, the same ADR-0037 procedure decides whether it's a subtype, a `@kind` variant, or an attribute. +The vocabulary itself is a provider class, listed once in the port's project +configuration so `gen`, `verify --codegen` and the docs generators all load it (the +**`metaobjects-authoring`** skill, "Your own vocabulary", has the per-language example). +A generator then reads the custom attribute like any other: through the resolving +accessor on the node, never by re-parsing the file. ## Per-target output diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md index 008e5dae1b..a1a3fe6c0b 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -455,6 +455,12 @@ Several variants of one thing sharing **one table**: the base `object.entity` de `@discriminatorValue`. Codegen emits per-subtype routes with the discriminator injected and immutable. Supported in all five ports; the worked example is in `references/inheritance-tph.md`. +## Your own vocabulary — a provider class, in every language + +A subtype or attribute the core does not ship (a `layout.picker`, `@searchable` on fields) is registered by a **provider class** in the project's own language — never a side file, never a loosened `strict`. Decide the shape first (`references/choosing-a-shape.md`, which also has the register/extend rules). List the provider once in the port's project configuration and every command that loads metadata — gen and its docs generators, verify, fmt — composes it. Where each port lists it, plus a worked example: `references/typescript-providers.md`, `references/python-providers.md`, `references/csharp-providers.md`, `references/java-providers.md`, `references/kotlin-providers.md` (only this stack's are installed). + +**Every port whose tools load the metadata needs its own copy**: a TypeScript-only provider leaves the Java, Python or C# side, and its docs build, failing with `ERR_UNKNOWN_SUBTYPE` / `ERR_UNKNOWN_ATTR`. + ## Requirements — capability ledger (opt-in) **This capability exists whether or not the project uses it yet.** `requirement.functional` and `requirement.architectural` are registered metadata types, declared in the metadata directory beside the entities they describe and loaded by the same loader — no side file, no bespoke parser. They record *why* each part of the model exists, so a field with no reason to exist becomes visible as one. diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md index 7ae89655d9..ee3b6858a5 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md @@ -162,6 +162,17 @@ or behavior is a **subtype**, and structural variants *within* such a subtype ar (including any `@kind` value-set) carry `allowedValues` in the gate (ADR-0036). ADR-0037 is the authority. +**What a provider does.** It names an `id` and the provider ids it depends on, then does one +or both of two things. It **registers** a new `(type, subType)` with its own attributes, which +may be required, and a node class (reuse the type's existing one unless the node has new +behaviour). It **extends** an existing `(type, subType)` with attributes, which must be +optional: a required one is `ERR_EXTEND_REQUIRED_ATTR` (ADR-0050), because removing your +provider must never weaken a type someone else owns. A new type allowed at the document root +also needs `extend` on `metadata.root` to admit it, or it fails with `ERR_CHILD_NOT_ALLOWED`. +An attribute no provider declares is `ERR_UNKNOWN_ATTR` under a strict load, and a subtype +nobody registered is `ERR_UNKNOWN_SUBTYPE`; that refusal is what keeps a typo from loading. +The per-language example and wiring is in the skill's `references/-providers.md`. + **Converge before inventing.** Search the shipped vocabulary first (`meta types `) and check the roadmap — if core already models (or plans) the concept, model yours in a fold-in-friendly shape. The type names `api`, `operation`, `surface`, and diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/typescript-providers.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/typescript-providers.md new file mode 100644 index 0000000000..5db6706b4f --- /dev/null +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/typescript-providers.md @@ -0,0 +1,74 @@ +# Your own vocabulary in TypeScript — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its TypeScript tools load the +> metadata. + +A provider is an object implementing `MetaDataTypeProvider`: an `id`, the provider ids it +depends on, and a `registerTypes(registry)` body that calls `register` (a new subtype) and +`extend` (attributes on an existing one). This one registers `layout.picker` and adds +`@searchable` and `@valueLabels` to `field.string`: + +```ts +// codegen/vocabulary.ts +import { TypeId, MetaLayout, type MetaDataTypeProvider } from "@metaobjectsdev/metadata"; +import { + TYPE_FIELD, TYPE_LAYOUT, FIELD_SUBTYPE_STRING, + ATTR_SUBTYPE_STRING, ATTR_SUBTYPE_BOOLEAN, +} from "@metaobjectsdev/metadata/constants"; + +export const vocabulary: MetaDataTypeProvider = { + id: "acme-vocabulary", + dependencies: ["metaobjects-core-types"], + registerTypes(registry) { + // A new subtype, with its own attribute (an own attribute may be required). + registry.register({ + typeId: new TypeId(TYPE_LAYOUT, "picker"), + description: "A picker over the owning object.", + factory: (typeId, name) => new MetaLayout(typeId, name), + childRules: [], + attributes: [ + { name: "displayField", valueType: ATTR_SUBTYPE_STRING, required: false, description: "Field shown per choice." }, + ], + }); + // Attributes on a type another provider owns: always optional. + registry.extend(TYPE_FIELD, FIELD_SUBTYPE_STRING, { + attributes: [ + { name: "searchable", valueType: ATTR_SUBTYPE_BOOLEAN, required: false, description: "Offer in search." }, + { name: "valueLabels", valueType: ATTR_SUBTYPE_STRING, isArray: true, required: false, description: "Display labels." }, + ], + }); + }, +}; +``` + +Wire it once, in `metaobjects.config.ts`: + +```ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { vocabulary } from "./codegen/vocabulary"; + +export default defineConfig({ + generators: [/* ... */], + providers: [vocabulary], +}); +``` + +Every `meta` command that loads metadata reads that list: `gen` (with the docs generators and +the docs site), `verify`, `migrate`, `fmt`, `types`, `export`, `deps`, `upgrade`. `meta types +picker` then lists the new subtype. A config that fails to load is reported as its own error, +never as an unknown subtype. Code that loads the model itself passes the same provider: +`loadMemory(root, { providers: [vocabulary] })`. + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `meta verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (same `id`, same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/SKILL.md index a030b08545..36123e0d8f 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -430,6 +430,11 @@ template hack. See the decision procedure in the **`metaobjects-authoring`** ski array column type) and a native UUID is `field.uuid` (not a string + `@dbColumnType`). When you register custom vocabulary for a custom generator, the same ADR-0037 procedure decides whether it's a subtype, a `@kind` variant, or an attribute. +The vocabulary itself is a provider class, listed once in the port's project +configuration so `gen`, `verify --codegen` and the docs generators all load it (the +**`metaobjects-authoring`** skill, "Your own vocabulary", has the per-language example). +A generator then reads the custom attribute like any other: through the resolving +accessor on the node, never by re-parsing the file. ## Per-target output diff --git a/fixtures/conformance/provider-custom-vocabulary-missing-provider-fails/expected-errors.json b/fixtures/conformance/provider-custom-vocabulary-missing-provider-fails/expected-errors.json new file mode 100644 index 0000000000..2b95372049 --- /dev/null +++ b/fixtures/conformance/provider-custom-vocabulary-missing-provider-fails/expected-errors.json @@ -0,0 +1,29 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_SUBTYPE", + "source": { + "format": "json", + "files": ["meta.contacts.json"], + "jsonPath": "$['metadata.root'].children[0]['object.value'].children[2]['layout.picker']" + } + }, + { + "code": "ERR_UNKNOWN_ATTR", + "source": { + "format": "json", + "files": ["meta.contacts.json"], + "jsonPath": "$['metadata.root'].children[0]['object.value'].children[0]['field.string']" + } + }, + { + "code": "ERR_UNKNOWN_ATTR", + "source": { + "format": "json", + "files": ["meta.contacts.json"], + "jsonPath": "$['metadata.root'].children[0]['object.value'].children[1]['field.string']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/provider-custom-vocabulary-missing-provider-fails/input/meta.contacts.json b/fixtures/conformance/provider-custom-vocabulary-missing-provider-fails/input/meta.contacts.json new file mode 100644 index 0000000000..6f7d926d7b --- /dev/null +++ b/fixtures/conformance/provider-custom-vocabulary-missing-provider-fails/input/meta.contacts.json @@ -0,0 +1,17 @@ +{ + "metadata.root": { + "package": "examples", + "children": [ + { + "object.value": { + "name": "Contact", + "children": [ + { "field.string": { "name": "name", "@searchable": true } }, + { "field.string": { "name": "status", "@valueLabels": ["Active", "On hold"] } }, + { "layout.picker": { "name": "contactPicker", "@displayField": "name" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/provider-custom-vocabulary-missing-provider-fails/providers.json b/fixtures/conformance/provider-custom-vocabulary-missing-provider-fails/providers.json new file mode 100644 index 0000000000..8ec88fc091 --- /dev/null +++ b/fixtures/conformance/provider-custom-vocabulary-missing-provider-fails/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types"] diff --git a/fixtures/conformance/provider-custom-vocabulary-success/expected.json b/fixtures/conformance/provider-custom-vocabulary-success/expected.json new file mode 100644 index 0000000000..f568bfab16 --- /dev/null +++ b/fixtures/conformance/provider-custom-vocabulary-success/expected.json @@ -0,0 +1,35 @@ +{ + "metadata.root": { + "package": "examples", + "children": [ + { + "object.value": { + "name": "Contact", + "children": [ + { + "field.string": { + "name": "name", + "@searchable": true + } + }, + { + "field.string": { + "name": "status", + "@valueLabels": [ + "Active", + "On hold" + ] + } + }, + { + "layout.picker": { + "name": "contactPicker", + "@displayField": "name" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/provider-custom-vocabulary-success/input/meta.contacts.json b/fixtures/conformance/provider-custom-vocabulary-success/input/meta.contacts.json new file mode 100644 index 0000000000..6f7d926d7b --- /dev/null +++ b/fixtures/conformance/provider-custom-vocabulary-success/input/meta.contacts.json @@ -0,0 +1,17 @@ +{ + "metadata.root": { + "package": "examples", + "children": [ + { + "object.value": { + "name": "Contact", + "children": [ + { "field.string": { "name": "name", "@searchable": true } }, + { "field.string": { "name": "status", "@valueLabels": ["Active", "On hold"] } }, + { "layout.picker": { "name": "contactPicker", "@displayField": "name" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/provider-custom-vocabulary-success/providers.json b/fixtures/conformance/provider-custom-vocabulary-success/providers.json new file mode 100644 index 0000000000..971d8c590a --- /dev/null +++ b/fixtures/conformance/provider-custom-vocabulary-success/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "example-custom-vocabulary"] diff --git a/server/csharp/MetaObjects.Cli.Tests/CsharpProvidersTests.cs b/server/csharp/MetaObjects.Cli.Tests/CsharpProvidersTests.cs new file mode 100644 index 0000000000..78a5e03956 --- /dev/null +++ b/server/csharp/MetaObjects.Cli.Tests/CsharpProvidersTests.cs @@ -0,0 +1,237 @@ +using MetaObjects.Cli; +using MetaObjects.Config; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Cli.Tests; + +/// +/// `csharp.providers` in .metaobjects/config.json: a project's own IMetaDataTypeProvider, loaded by +/// path, composes into EVERY metadata-loading entry point (gen/verify/fmt/field-lint), strictly. +/// The test provider lives in MetaObjects.TestVocabulary (built, not referenced, by this project). +/// +public sealed class CsharpProvidersTests : IDisposable +{ + private readonly string _tmp = Path.Combine(Path.GetTempPath(), "meta-providers-" + Guid.NewGuid().ToString("N")); + private string MetaDir => Path.Combine(_tmp, "metaobjects"); + + private const string Metadata = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Contact", "children": [ + { "field.string": { "name": "name", "@searchable": true } }, + { "layout.picker": { "name": "contactPicker", "@displayField": "name" } } + ]}} + ]}} + """; + + public CsharpProvidersTests() + { + Directory.CreateDirectory(MetaDir); + File.WriteAllText(Path.Combine(MetaDir, "meta.acme.json"), Metadata); + } + + public void Dispose() { try { Directory.Delete(_tmp, recursive: true); } catch { } } + + /// Path of the built test vocabulary dll (sibling project's output). + internal static string VocabularyDll + { + get + { + // /MetaObjects.Cli.Tests/bin//net8.0/ -> /MetaObjects.TestVocabulary/bin//net8.0/ + var baseDir = new DirectoryInfo(AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar)); + var tfm = baseDir.Name; var cfg = baseDir.Parent!.Name; + var root = baseDir.Parent!.Parent!.Parent!.Parent!.FullName; + return Path.Combine(root, "MetaObjects.TestVocabulary", "bin", cfg, tfm, "MetaObjects.TestVocabulary.dll"); + } + } + + private void WriteConfig(string csharpBlock) + { + Directory.CreateDirectory(Path.Combine(_tmp, ".metaobjects")); + File.WriteAllText(Path.Combine(_tmp, ".metaobjects", "config.json"), + "{ \"schema_version\": 1, \"csharp\": " + csharpBlock + " }"); + } + + private static string Esc(string s) => s.Replace("\\", "\\\\"); + + private void WriteProviderConfig(string type = "MetaObjects.TestVocabulary.TestVocabularyProvider", string? assembly = null) => + WriteConfig("{ \"providers\": [ { \"assembly\": \"" + Esc(assembly ?? VocabularyDll) + "\", \"type\": \"" + type + "\" } ] }"); + + private ResolvedMetadata Resolve() => MetadataLocation.Resolve(null, _tmp); + + // -- loading --------------------------------------------------------------------------- + + [Fact] + public void Listed_provider_loads_the_custom_vocabulary_strictly() + { + WriteProviderConfig(); + var load = Resolve().Load(strict: true); + Assert.Empty(load.Errors); + } + + [Fact] + public void Without_the_provider_the_same_metadata_fails_strict() + { + WriteConfig("{ \"outDir\": \"gen\" }"); + var codes = Resolve().Load(strict: true).Errors.Select(e => e.Code).ToList(); + Assert.Contains(ErrorCode.ERR_UNKNOWN_SUBTYPE, codes); + Assert.Contains(ErrorCode.ERR_UNKNOWN_ATTR, codes); + } + + [Fact] + public void The_assembly_path_is_resolved_against_the_directory_holding_dot_metaobjects() + { + var rel = Path.GetRelativePath(_tmp, VocabularyDll); + WriteProviderConfig(assembly: rel); + Assert.Empty(Resolve().Load(strict: true).Errors); + } + + [Fact] + public void An_explicit_metadata_dir_reads_the_providers_of_the_project_holding_it() + { + WriteProviderConfig(); + var other = Path.Combine(Path.GetTempPath(), "meta-providers-cwd-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(other); + try { Assert.Empty(MetadataLocation.Resolve(MetaDir, other).Load(strict: true).Errors); } + finally { Directory.Delete(other, recursive: true); } + } + + [Fact] + public void Registry_composes_with_FromDirectory_for_a_programmatic_host() + { + WriteProviderConfig(); + var registry = Resolve().Registry(); + Assert.Empty(MetaDataLoader.FromDirectory(MetaDir, registry, strict: true).Errors); + } + + // -- every entry point ----------------------------------------------------------------- + + [Fact] + public void Verify_templates_gate_uses_the_providers() + { + WriteProviderConfig(); + var providers = Resolve().Providers; + var tpl = Path.Combine(_tmp, "templates"); Directory.CreateDirectory(tpl); + + var with = VerifyCommand.RunSubverbs(new VerifyCommand.Options + { MetadataDir = MetaDir, TemplatesRoot = tpl, Templates = true, Providers = providers }); + Assert.Empty(with.Templates!.LoadErrors); + + var without = VerifyCommand.RunSubverbs(new VerifyCommand.Options + { MetadataDir = MetaDir, TemplatesRoot = tpl, Templates = true }); + Assert.Contains(ErrorCode.ERR_UNKNOWN_SUBTYPE.ToString(), without.Templates!.LoadErrors); + + Assert.Empty(VerifyCommand.Run(MetaDir, tpl, providers: providers).LoadErrors); + Assert.Contains(ErrorCode.ERR_UNKNOWN_SUBTYPE.ToString(), VerifyCommand.Run(MetaDir, tpl).LoadErrors); + } + + [Fact] + public void Verify_requirement_gate_loads_with_the_providers() + { + WriteProviderConfig(); + var opts = new VerifyCommand.Options { MetadataDir = MetaDir, Providers = Resolve().Providers }; + var output = new StringWriter(); + Assert.Equal(0, VerifyCommand.RunRequirementGate(opts, false, output, false)); + Assert.DoesNotContain("load error", output.ToString()); + + var bare = new StringWriter(); + Assert.Equal(1, VerifyCommand.RunRequirementGate(new VerifyCommand.Options { MetadataDir = MetaDir }, false, bare, false)); + Assert.Contains("ERR_UNKNOWN_SUBTYPE", bare.ToString()); + } + + [Fact] + public void Verify_codegen_gate_loads_with_the_providers() + { + WriteProviderConfig(); + var opts = new VerifyCommand.Options + { + MetadataDir = MetaDir, OutDir = Path.Combine(_tmp, "generated"), Codegen = true, Providers = Resolve().Providers, + }; + var r = VerifyCommand.RunSubverbs(opts); + Assert.False(r.LoadFailureReported); + + var bare = VerifyCommand.RunSubverbs(new VerifyCommand.Options + { MetadataDir = MetaDir, OutDir = Path.Combine(_tmp, "generated"), Codegen = true }); + Assert.True(bare.LoadFailureReported); + } + + [Fact] + public void Fmt_loads_and_formats_with_the_providers() + { + WriteProviderConfig(); + var result = FmtCommand.Run(Resolve(), check: true, strict: true); + Assert.Null(result.Fatal); + + File.Delete(Path.Combine(_tmp, ".metaobjects", "config.json")); + var bare = FmtCommand.Run(Resolve(), check: true, strict: true); + Assert.NotNull(bare.Fatal); + Assert.Contains("picker", bare.Fatal!); + } + + [Fact] + public void Field_lint_loads_with_the_providers() + { + WriteProviderConfig(); + // A repeated field name: the advisory scan only gets to report it if the model LOADS. + File.WriteAllText(Path.Combine(MetaDir, "meta.acme.json"), """ + { "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Contact", "children": [ + { "field.string": { "name": "name", "@searchable": true } }, + { "field.string": { "name": "name" } }, + { "layout.picker": { "name": "contactPicker" } } + ]}} + ]}} + """); + var resolved = Resolve(); + var with = new StringWriter(); + FieldLint.RunAdvisory(resolved.Directory, resolved.Files, resolved.Libraries, with, resolved.Imports, resolved.Providers); + Assert.Contains("authoring warning", with.ToString()); + + var without = new StringWriter(); + FieldLint.RunAdvisory(resolved.Directory, resolved.Files, resolved.Libraries, without, resolved.Imports); + Assert.Equal("", without.ToString()); + } + + // -- config errors --------------------------------------------------------------------- + + private MetaModelException Refusal() + => Assert.Throws(() => Resolve()); + + [Fact] + public void Missing_assembly_says_build_it_first_and_names_the_key() + { + WriteProviderConfig(assembly: "vocabulary/bin/Debug/net8.0/Nope.dll"); + var ex = Refusal(); + Assert.Equal(ErrorCode.ERR_BAD_ATTR_VALUE, ex.Code); + Assert.Contains("csharp.providers", ex.Message); + Assert.Contains("Nope.dll", ex.Message); + Assert.Contains("Build the vocabulary project first", ex.Message); + } + + [Theory] + [InlineData("Acme.Missing.Provider", "was not found")] + [InlineData("MetaObjects.TestVocabulary.NotAProvider", "IMetaDataTypeProvider")] + [InlineData("MetaObjects.TestVocabulary.NeedsArgsProvider", "parameterless constructor")] + public void Bad_type_is_refused_with_an_actionable_message(string type, string fragment) + { + WriteProviderConfig(type); + var ex = Refusal(); + Assert.Equal(ErrorCode.ERR_BAD_ATTR_VALUE, ex.Code); + Assert.Contains("csharp.providers", ex.Message); + Assert.Contains(fragment, ex.Message); + } + + [Theory] + [InlineData("{ \"providers\": \"x\" }", "must be an array")] + [InlineData("{ \"providers\": [ \"x\" ] }", "must be an object")] + [InlineData("{ \"providers\": [ { \"assembly\": \"a.dll\" } ] }", "needs both")] + [InlineData("{ \"providers\": [ { \"assembly\": \"a.dll\", \"type\": \"T\", \"extra\": 1 } ] }", "unknown key \"extra\"")] + [InlineData("{ \"providers\": [ { \"assembly\": \"\", \"type\": \"T\" } ] }", "non-empty string")] + public void Malformed_provider_entries_are_refused(string block, string fragment) + { + WriteConfig(block); + var ex = Refusal(); + Assert.Equal(ErrorCode.ERR_BAD_ATTR_VALUE, ex.Code); + Assert.Contains(fragment, ex.Message); + } +} diff --git a/server/csharp/MetaObjects.Cli.Tests/MetaObjects.Cli.Tests.csproj b/server/csharp/MetaObjects.Cli.Tests/MetaObjects.Cli.Tests.csproj index 0662e71d11..a20f0e2e7c 100644 --- a/server/csharp/MetaObjects.Cli.Tests/MetaObjects.Cli.Tests.csproj +++ b/server/csharp/MetaObjects.Cli.Tests/MetaObjects.Cli.Tests.csproj @@ -12,5 +12,7 @@ + + diff --git a/server/csharp/MetaObjects.Cli/FieldLint.cs b/server/csharp/MetaObjects.Cli/FieldLint.cs index a07aa27e8e..72cf1128c4 100644 --- a/server/csharp/MetaObjects.Cli/FieldLint.cs +++ b/server/csharp/MetaObjects.Cli/FieldLint.cs @@ -208,13 +208,14 @@ public static List LintDuplicateFields(IEnumerable files) /// public static void RunAdvisory( string metadataDir, IReadOnlyList? metadataFiles, IReadOnlyList? libraries, TextWriter stderr, - MetaObjects.Config.ImportScope? imports = null) + MetaObjects.Config.ImportScope? imports = null, + IReadOnlyList? providers = null) { List findings; try { var load = new MetaObjects.Config.ResolvedMetadata( - metadataDir, metadataFiles, libraries ?? [], MetaObjects.Meta.PhysicalNaming.Default, null, null, imports).Load(); + metadataDir, metadataFiles, libraries ?? [], MetaObjects.Meta.PhysicalNaming.Default, null, null, imports, null, providers).Load(); if (load.Errors.Count > 0) return; var files = metadataFiles ?? new DirectorySource(metadataDir).Expand().Select(f => f.FilePath).ToList(); findings = [.. LintReferenceFields(load.Root), .. LintDuplicateFields(files)]; diff --git a/server/csharp/MetaObjects.Cli/FmtCommand.cs b/server/csharp/MetaObjects.Cli/FmtCommand.cs index d080c78432..0536cb1cc7 100644 --- a/server/csharp/MetaObjects.Cli/FmtCommand.cs +++ b/server/csharp/MetaObjects.Cli/FmtCommand.cs @@ -178,7 +178,7 @@ public static RunResult Run(ResolvedMetadata resolved, bool check, IReadOnlyList targets = allFiles; } - var registry = new MetaDataLoader().Registry; + var registry = resolved.Registry(); List BuildSources(string? overridePath = null, string? overrideText = null) { diff --git a/server/csharp/MetaObjects.Cli/Program.cs b/server/csharp/MetaObjects.Cli/Program.cs index 236ddd5f3c..a1a5c8fc25 100644 --- a/server/csharp/MetaObjects.Cli/Program.cs +++ b/server/csharp/MetaObjects.Cli/Program.cs @@ -526,6 +526,7 @@ static int RunVerify(string[] rest) // ResolveMetadataDirOrExit). Libraries = resolvedMeta.Libraries, Imports = resolvedMeta.Imports, + Providers = resolvedMeta.Providers, // ADR-0058 — same source as Libraries; the --codegen gate's regen reads it from // the loaded root rather than a flag (see VerifyCommand.RunCodegenDrift). Naming = resolvedMeta.Naming, @@ -607,7 +608,7 @@ static int RunVerify(string[] rest) // field name declared twice in one children list. Both load clean on every port. Runs // on every `verify`, whichever gates were selected; warnings ONLY, never the exit code. if (!noFieldLint && Environment.GetEnvironmentVariable(FieldLint.EnvOptOut) != "1") - FieldLint.RunAdvisory(resolvedMeta.Directory, resolvedMeta.Files, resolvedMeta.Libraries, Console.Error, resolvedMeta.Imports); + FieldLint.RunAdvisory(resolvedMeta.Directory, resolvedMeta.Files, resolvedMeta.Libraries, Console.Error, resolvedMeta.Imports, resolvedMeta.Providers); // The handed-off codegen gate already printed its own verdict (inherited console); // fold its exit code into the aggregate the same way every other subverb does — max, diff --git a/server/csharp/MetaObjects.Cli/VerifyCommand.cs b/server/csharp/MetaObjects.Cli/VerifyCommand.cs index bc85d1e049..ce820159e1 100644 --- a/server/csharp/MetaObjects.Cli/VerifyCommand.cs +++ b/server/csharp/MetaObjects.Cli/VerifyCommand.cs @@ -104,6 +104,8 @@ public sealed record Options /// was imported so the --codegen gate regenerates exactly what gen wrote. Null: none. /// public MetaObjects.Config.ImportScope? Imports { get; init; } + /// csharp.providers, instantiated; composed with the core providers on every load. Null: core only. + public IReadOnlyList? Providers { get; init; } /// /// ADR-0058 — the project's physical-naming rules, read from the SAME /// .metaobjects/config.json as (Program.cs's @@ -264,7 +266,7 @@ private static LoadResult LoadMetadata(Options opts) // The same load `gen` runs (ResolvedMetadata.Load): libraries, then the dependency snapshots, then the // project's own files; ADR-0058 naming and the wire format set on the root; the imports recorded on it. return new MetaObjects.Config.ResolvedMetadata( - opts.MetadataDir, opts.MetadataFiles, opts.Libraries, opts.Naming, opts.Wire, null, opts.Imports) + opts.MetadataDir, opts.MetadataFiles, opts.Libraries, opts.Naming, opts.Wire, null, opts.Imports, null, opts.Providers) .Load(opts.Strict); } @@ -466,8 +468,10 @@ private static void AddIfPresent(List refs, object? attr) if (attr is string s && s.Length > 0) refs.Add(s); } - public static Outcome Run(string metadataDir, string templatesRoot, bool strict = true) - => Run(MetaDataLoader.FromDirectory(metadataDir, strict: strict), templatesRoot); + public static Outcome Run( + string metadataDir, string templatesRoot, bool strict = true, IReadOnlyList? providers = null) + => Run(MetaDataLoader.FromDirectory( + metadataDir, Provider.ComposeRegistry(MetaObjects.Config.ProviderLoader.Compose(providers)), strict: strict), templatesRoot); /// /// Same as the metadataDir overload above, but starting from an diff --git a/server/csharp/MetaObjects.Codegen.Tests/CsharpProvidersCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CsharpProvidersCodegenTests.cs new file mode 100644 index 0000000000..e199914b3a --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/CsharpProvidersCodegenTests.cs @@ -0,0 +1,88 @@ +// `csharp.providers` through CodegenCli.Run — the entry an owned codegen/Program.cs calls, and the +// one `dotnet meta gen` / `verify --codegen` hand off to. The vocabulary is loaded strictly. + +using MetaObjects.Codegen; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +[Collection("Console")] +public class CsharpProvidersCodegenTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "mo-providers-" + Guid.NewGuid().ToString("N")); + private string Meta => Path.Combine(_root, "metaobjects"); + private string Out => Path.Combine(_root, "gen"); + + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Contact", "children": [ + { "field.string": { "name": "name", "@searchable": true } }, + { "layout.picker": { "name": "contactPicker", "@displayField": "name" } } + ]}} + ]}} + """; + + private sealed class OneFile : IGenerator + { + public string Name => "one-file"; + public IEnumerable Generate(GenContext ctx) => [new EmittedFile("ok.txt", "ok\n")]; + } + + public CsharpProvidersCodegenTests() + { + Directory.CreateDirectory(Meta); + File.WriteAllText(Path.Combine(Meta, "meta.acme.json"), Model); + } + + public void Dispose() { try { Directory.Delete(_root, recursive: true); } catch { } } + + private static string VocabularyDll + { + get + { + var baseDir = new DirectoryInfo(AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar)); + var root = baseDir.Parent!.Parent!.Parent!.Parent!.FullName; + return Path.Combine(root, "MetaObjects.TestVocabulary", "bin", baseDir.Parent!.Name, baseDir.Name, "MetaObjects.TestVocabulary.dll"); + } + } + + private void WriteConfig(bool withProviders) + { + Directory.CreateDirectory(Path.Combine(_root, ".metaobjects")); + var providers = withProviders + ? ", \"providers\": [ { \"assembly\": \"" + VocabularyDll.Replace("\\", "\\\\") + + "\", \"type\": \"MetaObjects.TestVocabulary.TestVocabularyProvider\" } ]" + : ""; + File.WriteAllText(Path.Combine(_root, ".metaobjects", "config.json"), + "{ \"schema_version\": 1, \"csharp\": { \"namespace\": \"Acme\"" + providers + " } }"); + } + + private static int Quiet(Func run) + { + var (o, e) = (Console.Out, Console.Error); + Console.SetOut(TextWriter.Null); Console.SetError(TextWriter.Null); + try { return run(); } finally { Console.SetOut(o); Console.SetError(e); } + } + + [Fact] + public void Gen_and_verify_codegen_load_the_custom_vocabulary_when_listed() + { + WriteConfig(withProviders: true); + Assert.Equal(0, Quiet(() => CodegenCli.Run(["gen", Meta, "--out", Out], [new OneFile()]))); + Assert.True(File.Exists(Path.Combine(Out, "ok.txt"))); + Assert.Equal(0, Quiet(() => CodegenCli.Run(["verify", "--codegen", Meta, "--out", Out], [new OneFile()]))); + } + + [Fact] + public void Gen_fails_on_the_custom_vocabulary_without_the_provider() + { + WriteConfig(withProviders: false); + var err = new StringWriter(); + var prev = Console.Error; + Console.SetError(err); + try { Assert.NotEqual(0, CodegenCli.Run(["gen", Meta, "--out", Out], [new OneFile()])); } + finally { Console.SetError(prev); } + Assert.Contains("ERR_UNKNOWN_SUBTYPE", err.ToString()); + Assert.False(File.Exists(Path.Combine(Out, "ok.txt"))); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj b/server/csharp/MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj index 60ca76cb1d..dc8ea823c6 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj +++ b/server/csharp/MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj @@ -17,6 +17,8 @@ + + diff --git a/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs b/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs index cb278e8da0..a35cd1d072 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs @@ -55,6 +55,35 @@ public void RegisterTypes(TypeRegistry registry) } } +// Test-only — a project's own vocabulary: layout.picker + field.string attrs. Mirrors the TS +// reference (`exampleCustomVocabularyProvider`) and the shape a `csharp.providers` entry supplies. +internal sealed class ExampleCustomVocabularyProvider : IMetaDataTypeProvider +{ + public string Id => "example-custom-vocabulary"; + public IReadOnlyList Dependencies => new[] { "metaobjects-core-types" }; + + public void RegisterTypes(TypeRegistry registry) + { + registry.Register(new TypeDefinition( + typeId: new TypeId("layout", "picker"), + description: "A picker that chooses one row of the owning object — test-only.", + childRules: new List + { + new ChildRule(BaseTypes.TYPE_ATTR, Structural.CHILD_RULE_WILDCARD, Structural.CHILD_RULE_WILDCARD), + }, + factory: (typeId, name) => new MetaLayout(typeId, name), + attributes: new List + { + new AttrSchema("displayField", "string", Required: false, Description: "Field shown for each choice."), + })); + registry.Extend("field", "string", attributes: new List + { + new AttrSchema("searchable", "boolean", Required: false, Description: "Offer this field in search."), + new AttrSchema("valueLabels", "string", Required: false, Description: "Display labels for the field's values.", IsArray: true), + }); + } +} + internal sealed class NoopTestProvider(string id, params string[] deps) : IMetaDataTypeProvider { public string Id { get; } = id; @@ -140,6 +169,7 @@ public static class ConformanceAdapter ["metaobjects-template"] = MetaObjects.Template.PromptMetaDataProvider.Instance, // Test-only — provider-extension-* fixtures. ["example-template-briefing"] = new ExampleTemplateBriefingProvider(), + ["example-custom-vocabulary"] = new ExampleCustomVocabularyProvider(), ["cycle-a"] = new NoopTestProvider("cycle-a", "cycle-b"), ["cycle-b"] = new NoopTestProvider("cycle-b", "cycle-a"), ["depends-on-missing"] = new NoopTestProvider("depends-on-missing", "does-not-exist"), diff --git a/server/csharp/MetaObjects.TestVocabulary/MetaObjects.TestVocabulary.csproj b/server/csharp/MetaObjects.TestVocabulary/MetaObjects.TestVocabulary.csproj new file mode 100644 index 0000000000..11d8d65c62 --- /dev/null +++ b/server/csharp/MetaObjects.TestVocabulary/MetaObjects.TestVocabulary.csproj @@ -0,0 +1,12 @@ + + + + net8.0 + enable + enable + false + + + + + diff --git a/server/csharp/MetaObjects.TestVocabulary/TestVocabularyProvider.cs b/server/csharp/MetaObjects.TestVocabulary/TestVocabularyProvider.cs new file mode 100644 index 0000000000..aef72e23d7 --- /dev/null +++ b/server/csharp/MetaObjects.TestVocabulary/TestVocabularyProvider.cs @@ -0,0 +1,34 @@ +using MetaObjects.Meta; +using MetaObjects.Shared; + +namespace MetaObjects.TestVocabulary; + +/// Registers layout.picker and extends field.string with @searchable. +public sealed class TestVocabularyProvider : IMetaDataTypeProvider +{ + public string Id => "test-vocabulary"; + public IReadOnlyList Dependencies => ["metaobjects-core-types"]; + + public void RegisterTypes(TypeRegistry registry) + { + registry.Register(new TypeDefinition( + typeId: new TypeId("layout", "picker"), + description: "A picker that chooses one row of the owning object.", + childRules: [new ChildRule(BaseTypes.TYPE_ATTR, Structural.CHILD_RULE_WILDCARD, Structural.CHILD_RULE_WILDCARD)], + factory: (typeId, name) => new MetaLayout(typeId, name), + attributes: [new AttrSchema("displayField", "string", Required: false, Description: "Field shown for each choice.")])); + registry.Extend("field", "string", + attributes: [new AttrSchema("searchable", "boolean", Required: false, Description: "Offer this field in search.")]); + } +} + +/// No public parameterless constructor: refused by the loader. +public sealed class NeedsArgsProvider(string x) : IMetaDataTypeProvider +{ + public string Id => x; + public IReadOnlyList Dependencies => []; + public void RegisterTypes(TypeRegistry registry) { } +} + +/// Not a provider at all. +public sealed class NotAProvider { } diff --git a/server/csharp/MetaObjects.sln b/server/csharp/MetaObjects.sln index b364116d81..1cf5e3c4a3 100644 --- a/server/csharp/MetaObjects.sln +++ b/server/csharp/MetaObjects.sln @@ -19,6 +19,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MetaObjects.Cli", "MetaObje EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MetaObjects.Cli.Tests", "MetaObjects.Cli.Tests\MetaObjects.Cli.Tests.csproj", "{5B55ECEC-72F4-4344-8629-69C0C79893F6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MetaObjects.TestVocabulary", "MetaObjects.TestVocabulary\MetaObjects.TestVocabulary.csproj", "{07E0DCA5-F951-44CA-9660-3C30E7EBA30B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -60,5 +62,9 @@ Global {5B55ECEC-72F4-4344-8629-69C0C79893F6}.Debug|Any CPU.Build.0 = Debug|Any CPU {5B55ECEC-72F4-4344-8629-69C0C79893F6}.Release|Any CPU.ActiveCfg = Release|Any CPU {5B55ECEC-72F4-4344-8629-69C0C79893F6}.Release|Any CPU.Build.0 = Release|Any CPU + {07E0DCA5-F951-44CA-9660-3C30E7EBA30B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {07E0DCA5-F951-44CA-9660-3C30E7EBA30B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {07E0DCA5-F951-44CA-9660-3C30E7EBA30B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {07E0DCA5-F951-44CA-9660-3C30E7EBA30B}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/server/csharp/MetaObjects/Config/MetadataLocation.cs b/server/csharp/MetaObjects/Config/MetadataLocation.cs index a86dcbe822..cbc250800e 100644 --- a/server/csharp/MetaObjects/Config/MetadataLocation.cs +++ b/server/csharp/MetaObjects/Config/MetadataLocation.cs @@ -34,6 +34,10 @@ namespace MetaObjects.Config; /// The generated-code directory the project declared (csharp.outDir in the same /// file), absolute; null when it declared none. An explicit --out takes precedence. /// +/// +/// csharp.providers, already instantiated (null/empty: the core vocabulary only). Every +/// loader entry point composes its registry from these via . +/// /// /// FR-023 — the project's resolved metadata dependencies, read from the same file at EVERY rung of /// the ladder (the explicit directory included). Their committed snapshots load FIRST, ahead of @@ -42,8 +46,13 @@ namespace MetaObjects.Config; /// public sealed record ResolvedMetadata( string Directory, IReadOnlyList? Files, IReadOnlyList Libraries, PhysicalNaming Naming, - WireFormat? Wire = null, string? OutDir = null, ImportScope? Imports = null, string? Namespace = null) + WireFormat? Wire = null, string? OutDir = null, ImportScope? Imports = null, string? Namespace = null, + IReadOnlyList? Providers = null) { + /// The registry this metadata loads against: the core providers plus the project's + /// csharp.providers. Hosts that load by hand can pass it to MetaDataLoader.FromDirectory. + public TypeRegistry Registry() => Provider.ComposeRegistry(ProviderLoader.Compose(Providers)); + /// Load this metadata, with the project's libraries, and set the loaded /// root's from (ADR-0058) and its /// from . @@ -52,9 +61,9 @@ public LoadResult Load(bool strict = false) var leading = Imports?.Sources(); var result = Files is { } files ? MetaDataLoader.FromUris( - files.Select(f => new Uri(f)).ToList(), MetaDataLoader.DefaultRegistry(), Libraries, leading, strict) + files.Select(f => new Uri(f)).ToList(), Registry(), Libraries, leading, strict) : MetaDataLoader.FromDirectory( - Directory, MetaDataLoader.DefaultRegistry(), Libraries, leading, strict: strict); + Directory, Registry(), Libraries, leading, strict: strict); result.Root.PhysicalNaming = Naming; result.Root.WireFormat = Wire ?? WireFormat.Default; if (Imports is null) return result; @@ -73,6 +82,10 @@ public sealed class MetadataLocationException(string message) : Exception(messag public static class MetadataLocation { + /// csharp.providers from , instantiated; null when none are declared. + internal static IReadOnlyList? LoadProviders(NeutralConfig? cfg) => + cfg is { Providers.Count: > 0 } ? ProviderLoader.Load(cfg.Providers) : null; + /// /// The project a metadata directory belongs to: its PARENT, the directory holding /// metaobjects/ and .metaobjects/. @@ -117,7 +130,7 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd) // No config found means no project to read a lock from: nothing is imported. var explicitImports = explicitCfg is null ? ImportScope.None : ImportScope.Resolve(explicitCfg.ConfigDir, explicitCfg); return new ResolvedMetadata( - metadataDir, null, explicitLibs, explicitNaming, explicitCfg?.Wire, explicitCfg?.OutDir, explicitImports, explicitCfg?.Namespace); + metadataDir, null, explicitLibs, explicitNaming, explicitCfg?.Wire, explicitCfg?.OutDir, explicitImports, explicitCfg?.Namespace, LoadProviders(explicitCfg)); } var cfg = NeutralConfig.Read(cwd); @@ -132,7 +145,7 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd) // No declared sources: resolve the DEFAULT directory through the same ladder // the shared conformance corpus gates (ERR_COLLECTION_NOT_FOUND when absent). var defaultFiles = SourceResolver.ResolveCollection(cwd); - return new ResolvedMetadata(Path.Combine(cwd, NeutralConfig.DefaultMetadataDir), defaultFiles, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace); + return new ResolvedMetadata(Path.Combine(cwd, NeutralConfig.DefaultMetadataDir), defaultFiles, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, LoadProviders(cfg)); } if (specs.Count > 1) @@ -162,6 +175,6 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd) "\"sources\" at the file's containing directory."); } - return new ResolvedMetadata(resolved, files, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace); + return new ResolvedMetadata(resolved, files, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, LoadProviders(cfg)); } } diff --git a/server/csharp/MetaObjects/Config/NeutralConfig.cs b/server/csharp/MetaObjects/Config/NeutralConfig.cs index 4ec962d0e3..4b2eb8c078 100644 --- a/server/csharp/MetaObjects/Config/NeutralConfig.cs +++ b/server/csharp/MetaObjects/Config/NeutralConfig.cs @@ -98,9 +98,14 @@ public sealed class NeutralConfig /// emits such a type stops and asks for one. public string? Namespace { get; } + /// `csharp.providers` — the project's own metamodel providers (assembly path resolved against + /// the directory holding `.metaobjects/`, plus a type name). Empty when absent. Instantiated by + /// , not here, so reading a config never loads code. + public IReadOnlyList Providers { get; } + private NeutralConfig( IReadOnlyList> sources, IReadOnlyList libraries, - PhysicalNaming naming, WireFormat wire, (string? OutDir, string? Namespace) csharp, + PhysicalNaming naming, WireFormat wire, (string? OutDir, string? Namespace, IReadOnlyList Providers) csharp, IReadOnlyList dependencies, IReadOnlyList scopeInclude, IReadOnlyList? migrateScope, string configDir) { @@ -110,6 +115,7 @@ private NeutralConfig( ConfigDir = configDir; OutDir = csharp.OutDir; Namespace = csharp.Namespace; + Providers = csharp.Providers; Sources = sources; Libraries = libraries; Naming = naming; @@ -311,19 +317,26 @@ private static IReadOnlyList ReadDependencies(JsonElement root, /// `dotnet meta verify` diffs, and `namespace`, the namespace both generate under. The other /// ports ignore the block, as they ignore any key they do not own. An unknown key, a /// non-string or empty value, or a non-object block is refused, the same rule as `naming`. - private static (string? OutDir, string? Namespace) ReadCSharp(JsonElement root, string path, string configDir) + private static (string? OutDir, string? Namespace, IReadOnlyList Providers) ReadCSharp( + JsonElement root, string path, string configDir) { - if (!root.TryGetProperty("csharp", out var block)) return (null, null); + if (!root.TryGetProperty("csharp", out var block)) return (null, null, []); if (block.ValueKind != JsonValueKind.Object) throw new MetaModelException($"{path}: \"csharp\" must be an object", ErrorCode.ERR_BAD_ATTR_VALUE); string? outDir = null, ns = null; + IReadOnlyList providers = []; foreach (var p in block.EnumerateObject()) { - if (p.Name is not ("outDir" or "namespace")) + if (p.Name is not ("outDir" or "namespace" or "providers")) throw new MetaModelException( - $"{path}: \"csharp\" has an unknown key \"{p.Name}\" (expected \"outDir\" and/or \"namespace\")", + $"{path}: \"csharp\" has an unknown key \"{p.Name}\" (expected \"outDir\", \"namespace\" and/or \"providers\")", ErrorCode.ERR_BAD_ATTR_VALUE); + if (p.Name == "providers") + { + providers = ReadProviders(p.Value, path, configDir); + continue; + } if (p.Value.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(p.Value.GetString())) throw new MetaModelException( $"{path}: \"csharp.{p.Name}\" must be a non-empty string", ErrorCode.ERR_BAD_ATTR_VALUE); @@ -332,7 +345,41 @@ private static (string? OutDir, string? Namespace) ReadCSharp(JsonElement root, else ns = p.Value.GetString()!; } - return (outDir, ns); + return (outDir, ns, providers); + } + + /// `csharp.providers`: an array of `{ "assembly", "type" }` objects. Both keys are required + /// non-empty strings; any other key is refused, like the rest of the `csharp` block. + private static IReadOnlyList ReadProviders(JsonElement value, string path, string configDir) + { + if (value.ValueKind != JsonValueKind.Array) + throw new MetaModelException( + $"{path}: \"csharp.providers\" must be an array of {{ \"assembly\", \"type\" }} objects", ErrorCode.ERR_BAD_ATTR_VALUE); + var specs = new List(); + var i = 0; + foreach (var entry in value.EnumerateArray()) + { + var at = $"csharp.providers[{i++}]"; + if (entry.ValueKind != JsonValueKind.Object) + throw new MetaModelException($"{path}: \"{at}\" must be an object", ErrorCode.ERR_BAD_ATTR_VALUE); + string? asm = null, type = null; + foreach (var f in entry.EnumerateObject()) + { + if (f.Name is not ("assembly" or "type")) + throw new MetaModelException( + $"{path}: \"{at}\" has an unknown key \"{f.Name}\" (expected \"assembly\" and \"type\")", + ErrorCode.ERR_BAD_ATTR_VALUE); + if (f.Value.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(f.Value.GetString())) + throw new MetaModelException( + $"{path}: \"{at}.{f.Name}\" must be a non-empty string", ErrorCode.ERR_BAD_ATTR_VALUE); + if (f.Name == "assembly") asm = f.Value.GetString()!; else type = f.Value.GetString()!; + } + if (asm is null || type is null) + throw new MetaModelException( + $"{path}: \"{at}\" needs both \"assembly\" and \"type\"", ErrorCode.ERR_BAD_ATTR_VALUE); + specs.Add(new ProviderSpec(Path.GetFullPath(asm, Path.GetFullPath(configDir)), type, path)); + } + return specs; } /// The `wire` block (ADR-0019 Amendment 2): an unknown key, an unknown value, or a diff --git a/server/csharp/MetaObjects/Config/ProviderLoader.cs b/server/csharp/MetaObjects/Config/ProviderLoader.cs new file mode 100644 index 0000000000..b735638057 --- /dev/null +++ b/server/csharp/MetaObjects/Config/ProviderLoader.cs @@ -0,0 +1,99 @@ +// `csharp.providers` — loads project-supplied IMetaDataTypeProvider classes for the dev tools. +// +// This is dev-tool PLUGIN loading (`dotnet meta`, an ejected codegen/ runner), the C# counterpart +// of Python's `module:symbol` config providers. It is NOT runtime type binding: ADR-0001 forbids +// reflection for binding metadata to native types in GENERATED code, and nothing here touches that. + +using System.Reflection; +using System.Runtime.Loader; + +namespace MetaObjects.Config; + +/// One csharp.providers entry: an assembly path (absolute) and a full type name. +public sealed record ProviderSpec(string AssemblyPath, string TypeName, string ConfigPath); + +public static class ProviderLoader +{ + /// The providers a metadata load composes: the core library set, then the project's own. + public static IReadOnlyList Compose(IReadOnlyList? extra) + => extra is { Count: > 0 } ? [.. CoreTypes.LibraryProviders, .. extra] : CoreTypes.LibraryProviders; + + /// Instantiate every spec. Throws (ERR_BAD_ATTR_VALUE) naming the config key. + public static IReadOnlyList Load(IReadOnlyList specs) + { + var result = new List(specs.Count); + foreach (var spec in specs) result.Add(LoadOne(spec)); + return result; + } + + private static MetaModelException Refuse(ProviderSpec s, string why) => + new($"{s.ConfigPath}: \"csharp.providers\" entry (assembly \"{s.AssemblyPath}\", type \"{s.TypeName}\"): {why}", + ErrorCode.ERR_BAD_ATTR_VALUE); + + private static IMetaDataTypeProvider LoadOne(ProviderSpec spec) + { + if (!File.Exists(spec.AssemblyPath)) + throw Refuse(spec, $"the assembly file does not exist at {spec.AssemblyPath}. Build the vocabulary project first " + + "(for example `dotnet build `), then re-run."); + + Type? type; + try + { + type = LoadAssembly(spec).GetType(spec.TypeName, throwOnError: false); + } + catch (Exception ex) when (ex is BadImageFormatException or FileLoadException or ReflectionTypeLoadException) + { + throw Refuse(spec, $"the assembly could not be loaded ({ex.GetType().Name}: {ex.Message}). " + + "Point it at a managed .NET assembly built for this runtime."); + } + if (type is null) + throw Refuse(spec, $"type \"{spec.TypeName}\" was not found in the assembly (use the full, namespace-qualified name)."); + if (!typeof(IMetaDataTypeProvider).IsAssignableFrom(type) || type.IsAbstract || type.IsInterface) + throw Refuse(spec, $"type \"{spec.TypeName}\" is not a concrete class implementing IMetaDataTypeProvider."); + if (type.GetConstructor(Type.EmptyTypes) is null) + throw Refuse(spec, $"type \"{spec.TypeName}\" has no public parameterless constructor."); + try + { + return (IMetaDataTypeProvider)Activator.CreateInstance(type)!; + } + catch (TargetInvocationException ex) + { + throw Refuse(spec, $"its constructor threw {ex.InnerException?.GetType().Name}: {ex.InnerException?.Message}"); + } + } + + private static readonly HashSet HookedPaths = new(StringComparer.Ordinal); + private static readonly object Gate = new(); + + private static Assembly LoadAssembly(ProviderSpec spec) + { + var name = AssemblyName.GetAssemblyName(spec.AssemblyPath); + // Reuse an assembly of the same simple name already in the process (the codegen project may + // reference the vocabulary project directly), so type identity is not split. + var loaded = AppDomain.CurrentDomain.GetAssemblies() + .FirstOrDefault(a => string.Equals(a.GetName().Name, name.Name, StringComparison.Ordinal)); + if (loaded is not null) return loaded; + + var resolver = new AssemblyDependencyResolver(spec.AssemblyPath); + var dir = Path.GetDirectoryName(spec.AssemblyPath)!; + lock (Gate) + { + if (HookedPaths.Add(spec.AssemblyPath)) + { + AssemblyLoadContext.Default.Resolving += (ctx, requested) => + { + // MetaObjects itself is already bound in the default context; the Default context + // only raises Resolving for assemblies it could not find, so this never shadows it. + var path = resolver.ResolveAssemblyToPath(requested); + if (path is null) + { + var sibling = Path.Combine(dir, requested.Name + ".dll"); + if (File.Exists(sibling)) path = sibling; + } + return path is null ? null : ctx.LoadFromAssemblyPath(path); + }; + } + } + return AssemblyLoadContext.Default.LoadFromAssemblyPath(spec.AssemblyPath); + } +} diff --git a/server/java/README.md b/server/java/README.md index 4bef7748f1..c9f270b60e 100644 --- a/server/java/README.md +++ b/server/java/README.md @@ -121,7 +121,7 @@ A single directory may freely mix `.json` and `.yaml` files — the loader disco ## Provider-based registration -Java's `MetaDataTypeProvider` (`ServiceLoader`-discovered) is the implementation of the type-provider model adopted across every language port. New types, subtypes, and attributes are contributed by a provider — never by editing central registry files. Type-binding to native classes is resolved through `ObjectClassRegistry` at load time, not via reflection, so the registration stays AOT/native-image friendly (see [ADR-0001](../../spec/decisions/ADR-0001-cross-language-type-binding.md)). +Java's `MetaDataTypeProvider` is the implementation of the type-provider model adopted across every language port. New types, subtypes, and attributes are contributed by a provider — never by editing central registry files. A project names its providers explicitly (Maven plugin ``, or Spring beans); see [extending-with-providers](../../docs/features/extending-with-providers.md). Type-binding to native classes is resolved through `ObjectClassRegistry` at load time, not via reflection, so the registration stays AOT/native-image friendly (see [ADR-0001](../../spec/decisions/ADR-0001-cross-language-type-binding.md)). ## Build + test diff --git a/server/java/core-spring/src/main/java/com/metaobjects/spring/MetaDataLoaderConfiguration.java b/server/java/core-spring/src/main/java/com/metaobjects/spring/MetaDataLoaderConfiguration.java index 2038115fdb..7dc3989457 100644 --- a/server/java/core-spring/src/main/java/com/metaobjects/spring/MetaDataLoaderConfiguration.java +++ b/server/java/core-spring/src/main/java/com/metaobjects/spring/MetaDataLoaderConfiguration.java @@ -5,6 +5,9 @@ import com.metaobjects.loader.LoaderOptions; import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.registry.MetaDataTypeProvider; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; @@ -42,6 +45,10 @@ * physical-naming-config: "classpath:.metaobjects/config.json" * } * + *

Project vocabulary: declare each {@link MetaDataTypeProvider} as a bean + * ({@code @Bean MetaDataTypeProvider contactVocabulary() { return new ContactVocabulary(); }}) + * and the application loader composes it.

+ * *

Or use @Bean methods directly:

*
{@code
  * @Configuration
@@ -82,6 +89,14 @@ public class MetaDataLoaderConfiguration {
      */
     private String physicalNamingConfig;
 
+    /**
+     * A project's own vocabulary: every {@link MetaDataTypeProvider} bean in the context, in
+     * {@code @Order} order, is composed after the metamodel set into the application loader's
+     * registry (sealed and strict, like the default). Null when this class is built by hand.
+     */
+    @Autowired(required = false)
+    private ObjectProvider typeProviders;
+
     /**
      * Creates MetaDataLoader from application properties.
      *
@@ -111,6 +126,9 @@ public MetaDataLoader applicationMetaDataLoader() throws Exception {
         // Preserve the pre-unification strict=true default (the no-options
         // fromUris overload routes through createManual which uses strict=false).
         LoaderOptions opts = LoaderOptions.create(false, false, true);
+        if (typeProviders != null) {
+            opts.setProviders(typeProviders.orderedStream().toList());
+        }
         // ADR-0058: the naming is resolved BEFORE the load call so the loader's own
         // "no config found" WARN fires only when neither this property, the default
         // classpath:.metaobjects/config.json, nor the file: walk found a project config.
diff --git a/server/java/core-spring/src/test/java/com/metaobjects/spring/MetaDataLoaderProvidersTest.java b/server/java/core-spring/src/test/java/com/metaobjects/spring/MetaDataLoaderProvidersTest.java
new file mode 100644
index 0000000000..b6eef28dea
--- /dev/null
+++ b/server/java/core-spring/src/test/java/com/metaobjects/spring/MetaDataLoaderProvidersTest.java
@@ -0,0 +1,65 @@
+package com.metaobjects.spring;
+
+import com.metaobjects.attr.BooleanAttribute;
+import com.metaobjects.attr.StringAttribute;
+import com.metaobjects.field.StringField;
+import com.metaobjects.layout.MetaLayout;
+import com.metaobjects.loader.MetaDataLoader;
+import com.metaobjects.registry.MetaDataRegistry;
+import com.metaobjects.registry.MetaDataTypeProvider;
+import org.junit.Test;
+import org.springframework.boot.autoconfigure.AutoConfigurations;
+import org.springframework.boot.test.context.runner.ApplicationContextRunner;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * A {@link MetaDataTypeProvider} bean in the context is composed into the application
+ * loader's registry, so metadata using the project's own vocabulary loads strict and clean.
+ */
+public class MetaDataLoaderProvidersTest {
+
+    public static final class PickerLayout extends MetaLayout {
+        public PickerLayout(String name) { super("picker", name); }
+    }
+
+    static MetaDataTypeProvider contactVocabulary() {
+        return new MetaDataTypeProvider() {
+            @Override public String getProviderId() { return "spring-test-contact-vocabulary"; }
+            @Override public String[] getDependencies() { return new String[]{"field-types", "layout-types"}; }
+            @Override public void registerTypes(MetaDataRegistry registry) {
+                registry.registerType(PickerLayout.class, def -> {
+                    def.type("layout").subType("picker").inheritsFrom("layout", "base");
+                    def.optionalAttributeWithConstraints("displayField")
+                       .ofType(StringAttribute.SUBTYPE_STRING).asSingle();
+                });
+                registry.extendType(StringField.class, def ->
+                    def.optionalAttributeWithConstraints("searchable")
+                       .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle());
+            }
+        };
+    }
+
+    private final ApplicationContextRunner runner = new ApplicationContextRunner()
+        .withConfiguration(AutoConfigurations.of(MetaDataAutoConfiguration.class))
+        .withPropertyValues("metaobjects.metadata-sources=classpath:metadata/test-custom-vocabulary.json");
+
+    @Test
+    public void aProviderBeanIsComposedIntoTheApplicationLoader() {
+        runner.withBean(MetaDataTypeProvider.class, MetaDataLoaderProvidersTest::contactVocabulary)
+            .run(ctx -> {
+                MetaDataLoader loader = ctx.getBean(MetaDataLoader.class);
+                assertThat(loader.getErrors()).isEmpty();
+                assertThat(loader.getTypeRegistry().getTypeDefinition("layout", "picker")).isNotNull();
+            });
+    }
+
+    @Test
+    public void withoutTheProviderBeanTheVocabularyIsRefused() {
+        runner.run(ctx -> {
+            MetaDataLoader loader = ctx.getBean(MetaDataLoader.class);
+            assertThat(loader.getErrors()).extracting(e -> e.getCode().get().name())
+                .containsExactly("ERR_UNKNOWN_SUBTYPE", "ERR_UNKNOWN_ATTR");
+        });
+    }
+}
diff --git a/server/java/core-spring/src/test/resources/metadata/test-custom-vocabulary.json b/server/java/core-spring/src/test/resources/metadata/test-custom-vocabulary.json
new file mode 100644
index 0000000000..62bbe85046
--- /dev/null
+++ b/server/java/core-spring/src/test/resources/metadata/test-custom-vocabulary.json
@@ -0,0 +1,11 @@
+{
+  "metadata.root": {
+    "package": "acme::contacts",
+    "children": [
+      { "object.value": { "name": "Contact", "children": [
+        { "field.string": { "name": "name", "@searchable": true } },
+        { "layout.picker": { "name": "contactPicker", "@displayField": "name" } }
+      ] } }
+    ]
+  }
+}
diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java
index 7551d86102..f1df2868a6 100644
--- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java
+++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java
@@ -336,6 +336,61 @@ public void setLoader(LoaderParam loaderConfig) {
         this.loaderConfig = loaderConfig;
     }
 
+    /**
+     * A project's own metamodel vocabulary: fully-qualified names of
+     * {@link com.metaobjects.registry.MetaDataTypeProvider} classes (public, no-arg constructor)
+     * composed after the metamodel set for every goal that loads metadata
+     * ({@code generate}, {@code verify}, {@code fmt}, {@code editor}). Explicit list only — no
+     * classpath scan, so a library jar's own SPI providers never leak into the measured vocabulary.
+     * The classes are loaded through the project class loader: they must be in a dependency module
+     * or in the plugin's own {@code }; a provider in the module being built is not
+     * compiled yet at {@code generate-sources}.
+     */
+    @Parameter(property = "meta.providers")
+    public List providers;
+
+    private List resolvedProviders;
+
+    /** Instantiate {@link #providers} (once per execution) through {@code projectClassLoader}. */
+    protected List resolveProviders(ClassLoader projectClassLoader)
+            throws MojoExecutionException {
+        if (resolvedProviders != null) return resolvedProviders;
+        List out = new ArrayList<>();
+        if (providers != null) {
+            for (String raw : providers) {
+                String className = raw == null ? "" : raw.trim();
+                if (className.isEmpty()) {
+                    throw new MojoExecutionException(" contains an empty class name");
+                }
+                Class c;
+                try {
+                    c = Class.forName(className, true, projectClassLoader);
+                } catch (ClassNotFoundException | LinkageError ex) {
+                    throw new MojoExecutionException(" class [" + className + "] was not found. "
+                        + "A provider must be on the plugin's classpath: in a dependency module of this project "
+                        + "or in the plugin's . A provider in the same module is not compiled yet "
+                        + "at generate-sources, so it cannot be used here.", ex);
+                }
+                if (!com.metaobjects.registry.MetaDataTypeProvider.class.isAssignableFrom(c)) {
+                    throw new MojoExecutionException(" class [" + className + "] does not implement "
+                        + com.metaobjects.registry.MetaDataTypeProvider.class.getName());
+                }
+                try {
+                    out.add((com.metaobjects.registry.MetaDataTypeProvider)
+                        c.getConstructor().newInstance());
+                } catch (NoSuchMethodException ex) {
+                    throw new MojoExecutionException(" class [" + className
+                        + "] needs a public no-argument constructor", ex);
+                } catch (ReflectiveOperationException ex) {
+                    throw new MojoExecutionException(" class [" + className
+                        + "] could not be instantiated: " + ex, ex);
+                }
+            }
+        }
+        resolvedProviders = List.copyOf(out);
+        return resolvedProviders;
+    }
+
     @Parameter
     public Map globals;
     public Map getGlobals() {
@@ -426,6 +481,7 @@ public void execute() throws MojoExecutionException, MojoFailureException
         warnIfAgentContextStale();
 
         ClassLoader projectClassLoader = createProjectClassLoader();
+        resolveProviders(projectClassLoader);
 
         MetaDataLoader loader = createLoader(projectClassLoader);
 
@@ -607,6 +663,14 @@ protected void warnIfAgentContextStale() {
 
     protected MetaDataLoader createLoader(ClassLoader projectClassLoader) {
 
+        // Normally primed by the goal's execute() (which reports a bad  entry as a
+        // MojoExecutionException); a direct caller that skipped that gets the same message unchecked.
+        List extraProviders;
+        try {
+            extraProviders = resolveProviders(projectClassLoader);
+        } catch (MojoExecutionException e) {
+            throw new MetaDataException(e.getMessage(), e);
+        }
         LoaderConfigurable configurable = null;
         String loaderClass = loaderConfig.getClassname();
         String loaderName = loaderConfig.getName();
@@ -625,6 +689,12 @@ protected MetaDataLoader createLoader(ClassLoader projectClassLoader) {
                     MetaDataLoader.SUBTYPE_MANUAL, loaderName);
         }
 
+        // The project's own vocabulary (): the loader composes its registry from the
+        // metamodel set plus these, sealed and strict like the default.
+        if (!extraProviders.isEmpty()) {
+            configurable.getLoader().getLoaderOptions().setProviders(extraProviders);
+        }
+
         // Configure the loader using the new pattern
         String sourceDir = null;
         File srcDir = getSourceDir();
diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataFmtMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataFmtMojo.java
index a346341ffe..ef95c0bcb9 100644
--- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataFmtMojo.java
+++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataFmtMojo.java
@@ -64,6 +64,7 @@ public void execute() throws MojoExecutionException, MojoFailureException {
         warnIfAgentContextStale();
 
         ClassLoader projectClassLoader = createProjectClassLoader();
+        resolveProviders(projectClassLoader); // a bad  entry fails here, before any load
         // ONE real directory walk — to learn the resolved file list via the full
         // //.metaobjects/config.json ladder, and to
         // fail fast (via createLoader's own failOnLoaderErrors) if the project
@@ -77,6 +78,8 @@ public void execute() throws MojoExecutionException, MojoFailureException {
         List targets = resolveTargets(allFiles);
 
         boolean strict = !isLax();
+        // Every fresh reload in the safety check carries the same  as the baseline.
+        List extraProviders = resolveProviders(projectClassLoader);
         String loaderName = getLoader().getName();
         List libraries = getLoader().getLibraries();
         List librarySources =
@@ -97,7 +100,7 @@ public void execute() throws MojoExecutionException, MojoFailureException {
                 // .load(List) requires init() to have run first, but takes the actual
                 // source list as a separate call — see FmtSupport.buildSources.
                 MetaDataLoader fresh = new MetaDataLoader(
-                    LoaderOptions.create(false, false, strict), MetaDataLoader.SUBTYPE_MANUAL,
+                    LoaderOptions.create(false, false, strict).setProviders(extraProviders), MetaDataLoader.SUBTYPE_MANUAL,
                     loaderName);
                 fresh.init();
                 return fresh;
@@ -110,7 +113,7 @@ public void execute() throws MojoExecutionException, MojoFailureException {
                 // a loader name may not — that is a SEPARATE identifier, the `sourceId`
                 // CanonicalJsonParser takes, for provenance only).
                 MetaDataLoader standalone = new MetaDataLoader(
-                    LoaderOptions.create(false, false, strict), MetaDataLoader.SUBTYPE_MANUAL,
+                    LoaderOptions.create(false, false, strict).setProviders(extraProviders), MetaDataLoader.SUBTYPE_MANUAL,
                     loaderNameForFile);
                 standalone.init();
                 return standalone;
diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java
index c5f7dc14fa..964a29a5cb 100644
--- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java
+++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java
@@ -341,6 +341,7 @@ private void verifyTemplates() throws MojoExecutionException, MojoFailureExcepti
         }
 
         ClassLoader projectClassLoader = createProjectClassLoader();
+        resolveProviders(projectClassLoader);
         MetaDataLoader loader = createLoader(projectClassLoader);
         runFieldLintAdvisory(loader);
         int requirementErrors = runRequirementGate(loader);
@@ -376,6 +377,7 @@ private void verifyTemplates() throws MojoExecutionException, MojoFailureExcepti
 
     private void verifyCodegen() throws MojoExecutionException, MojoFailureException {
         ClassLoader projectClassLoader = createProjectClassLoader();
+        resolveProviders(projectClassLoader);
         MetaDataLoader loader = createLoader(projectClassLoader);
         runFieldLintAdvisory(loader);
         int requirementErrors = runRequirementGate(loader);
diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MojoProvidersTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MojoProvidersTest.java
new file mode 100644
index 0000000000..8a1d4df313
--- /dev/null
+++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MojoProvidersTest.java
@@ -0,0 +1,169 @@
+package com.metaobjects.mojo;
+
+import com.metaobjects.attr.BooleanAttribute;
+import com.metaobjects.attr.StringAttribute;
+import com.metaobjects.field.StringField;
+import com.metaobjects.generator.kotlin.KotlinEntityGenerator;
+import com.metaobjects.layout.MetaLayout;
+import com.metaobjects.registry.MetaDataRegistry;
+import com.metaobjects.registry.MetaDataTypeProvider;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * The {@code } parameter reaches every goal that loads metadata: a project's own
+ * vocabulary loads under generate, verify and fmt, and is refused (strict) without it.
+ */
+public class MojoProvidersTest {
+
+    public static final class PickerLayout extends MetaLayout {
+        public PickerLayout(String name) { super("picker", name); }
+    }
+
+    /** Public, no-arg: what {@code } instantiates. */
+    public static final class ContactVocabulary implements MetaDataTypeProvider {
+        @Override public String getProviderId() { return "mojo-test-contact-vocabulary"; }
+        @Override public String[] getDependencies() { return new String[]{"field-types", "layout-types"}; }
+        @Override public void registerTypes(MetaDataRegistry registry) {
+            registry.registerType(PickerLayout.class, def -> {
+                def.type("layout").subType("picker").inheritsFrom("layout", "base");
+                def.optionalAttributeWithConstraints("displayField")
+                   .ofType(StringAttribute.SUBTYPE_STRING).asSingle();
+            });
+            registry.extendType(StringField.class, def ->
+                def.optionalAttributeWithConstraints("searchable")
+                   .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle());
+        }
+    }
+
+    public static final class NoPublicCtor implements MetaDataTypeProvider {
+        public NoPublicCtor(String ignored) { }
+        @Override public String getProviderId() { return "x"; }
+        @Override public void registerTypes(MetaDataRegistry registry) { }
+    }
+
+    private static final String PROVIDER = ContactVocabulary.class.getName();
+
+    private static final String CONTACTS =
+        "{\n  \"metadata.root\": {\n    \"package\": \"examples\",\n    \"children\": [\n"
+        + "      {\n        \"object.value\": {\n          \"name\": \"Contact\",\n"
+        + "          \"children\": [\n"
+        + "            {\n              \"field.string\": {\n                \"name\": \"name\",\n"
+        + "                \"@searchable\": true\n              }\n            },\n"
+        + "            {\n              \"layout.picker\": {\n                \"name\": \"contactPicker\",\n"
+        + "                \"@displayField\": \"name\"\n              }\n            }\n"
+        + "          ]\n        }\n      }\n    ]\n  }\n}\n";
+
+    private Path dir;
+    private Path out;
+
+    @Before
+    public void setUp() throws Exception {
+        dir = Files.createTempDirectory("mojo-providers-meta");
+        out = Files.createTempDirectory("mojo-providers-out");
+        Files.writeString(dir.resolve("meta.contacts.json"), CONTACTS, StandardCharsets.UTF_8);
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        for (Path root : List.of(dir, out)) {
+            try (var walk = Files.walk(root)) {
+                walk.sorted(java.util.Comparator.reverseOrder()).forEach(p -> {
+                    try { Files.delete(p); } catch (Exception ignored) { }
+                });
+            }
+        }
+    }
+
+    private void configure(AbstractMetaDataMojo mojo, String... providerClasses) {
+        mojo.setLoader(LoaderParam.builder("providers-test")
+            .withClassname("com.metaobjects.loader.MetaDataLoader")
+            .withSourceDir(dir.toString())
+            .build());
+        mojo.setGenerators(new ArrayList<>(List.of(GeneratorParam.builder(KotlinEntityGenerator.class.getName())
+            .withArg("outputDir", out.toString()).build())));
+        mojo.setGlobals(Collections.emptyMap());
+        mojo.providers = providerClasses.length == 0 ? null : List.of(providerClasses);
+    }
+
+    @Test
+    public void generateRefusesTheVocabularyWithoutProviders() {
+        MetaDataGeneratorMojo gen = new MetaDataGeneratorMojo();
+        configure(gen);
+        Exception e = assertThrows(Exception.class, gen::execute);
+        assertTrue(String.valueOf(e.getMessage()), e.getMessage().contains("strict provenance (2 error(s))"));
+    }
+
+    @Test
+    public void generateLoadsTheVocabularyWithProviders() throws Exception {
+        MetaDataGeneratorMojo gen = new MetaDataGeneratorMojo();
+        configure(gen, PROVIDER);
+        gen.execute();
+    }
+
+    @Test
+    public void verifyLoadsTheVocabularyWithProviders() throws Exception {
+        MetaDataGeneratorMojo gen = new MetaDataGeneratorMojo();
+        configure(gen, PROVIDER);
+        gen.execute();
+
+        MetaDataVerifyMojo verify = new MetaDataVerifyMojo();
+        configure(verify, PROVIDER);
+        verify.execute();
+
+        MetaDataVerifyMojo without = new MetaDataVerifyMojo();
+        configure(without);
+        assertThrows(Exception.class, without::execute);
+    }
+
+    @Test
+    public void fmtLoadsTheVocabularyWithProvidersInEveryReload() throws Exception {
+        MetaDataFmtMojo fmt = new MetaDataFmtMojo();
+        configure(fmt, PROVIDER);
+        fmt.execute();
+        assertEquals(CONTACTS, Files.readString(dir.resolve("meta.contacts.json"), StandardCharsets.UTF_8));
+
+        MetaDataFmtMojo without = new MetaDataFmtMojo();
+        configure(without);
+        assertThrows(Exception.class, without::execute);
+    }
+
+    @Test
+    public void aMissingClassNamesTheClasspathRule() {
+        MetaDataGeneratorMojo gen = new MetaDataGeneratorMojo();
+        configure(gen, "com.example.DoesNotExist");
+        MojoExecutionException e = assertThrows(MojoExecutionException.class, gen::execute);
+        assertTrue(e.getMessage(), e.getMessage().contains("com.example.DoesNotExist"));
+        assertTrue(e.getMessage(), e.getMessage().contains("plugin's classpath"));
+        assertTrue(e.getMessage(), e.getMessage().contains("not compiled yet at generate-sources"));
+    }
+
+    @Test
+    public void aNonProviderClassIsRefused() {
+        MetaDataGeneratorMojo gen = new MetaDataGeneratorMojo();
+        configure(gen, String.class.getName());
+        MojoExecutionException e = assertThrows(MojoExecutionException.class, gen::execute);
+        assertTrue(e.getMessage(), e.getMessage().contains("does not implement"));
+    }
+
+    @Test
+    public void aProviderWithoutAPublicNoArgConstructorIsRefused() {
+        MetaDataGeneratorMojo gen = new MetaDataGeneratorMojo();
+        configure(gen, NoPublicCtor.class.getName());
+        MojoExecutionException e = assertThrows(MojoExecutionException.class, gen::execute);
+        assertTrue(e.getMessage(), e.getMessage().contains("public no-argument constructor"));
+    }
+}
diff --git a/server/java/metadata-ktx/src/main/kotlin/com/metaobjects/metadata/ktx/Loader.kt b/server/java/metadata-ktx/src/main/kotlin/com/metaobjects/metadata/ktx/Loader.kt
index b2516ce973..90de803f4b 100644
--- a/server/java/metadata-ktx/src/main/kotlin/com/metaobjects/metadata/ktx/Loader.kt
+++ b/server/java/metadata-ktx/src/main/kotlin/com/metaobjects/metadata/ktx/Loader.kt
@@ -4,6 +4,7 @@ import com.metaobjects.loader.DirectorySource
 import com.metaobjects.loader.LoaderOptions
 import com.metaobjects.loader.MetaDataLoader
 import com.metaobjects.loader.MetaDataSource.MetaDataFormat
+import com.metaobjects.registry.MetaDataTypeProvider
 import java.net.URI
 import java.nio.file.Path
 
@@ -13,26 +14,42 @@ import java.nio.file.Path
  * [MetaDataLoader] static factory.
  */
 
-/** Load metadata from a filesystem directory; pass [DirectorySource.Options] to tune expansion. */
+/**
+ * The options a `providers` argument rides on. Empty [providers] returns [opts] untouched (so the
+ * default load is byte-identical); otherwise the providers are set on [opts], or on the
+ * `createManual` defaults (lax, quiet, unregistered) when [opts] is null.
+ */
+private fun withProviders(opts: LoaderOptions?, providers: List): LoaderOptions? =
+    if (providers.isEmpty()) opts
+    else (opts ?: LoaderOptions.create(false, false, false)).setProviders(providers)
+
+/**
+ * Load metadata from a filesystem directory; pass [DirectorySource.Options] to tune expansion and
+ * [providers] to add a project's own vocabulary (composed after the metamodel set into a sealed registry; the
+ * directory load itself stays lax, as it is without providers).
+ */
 fun loadDirectory(
     name: String,
     directory: Path,
     opts: DirectorySource.Options = DirectorySource.Options(),
-): MetaDataLoader = MetaDataLoader.fromDirectory(name, directory, opts)
+    providers: List = emptyList(),
+): MetaDataLoader = MetaDataLoader.fromDirectory(name, directory, opts, null, providers)
 
-/** Load metadata from a list of URIs; pass [LoaderOptions] to tune (e.g. `strict=true`). */
+/** Load metadata from a list of URIs; pass [LoaderOptions] to tune (e.g. `strict=true`) and [providers] for a project's own vocabulary. */
 fun loadUris(
     name: String,
     uris: List,
     opts: LoaderOptions? = null,
-): MetaDataLoader = MetaDataLoader.fromUris(name, uris, opts)
+    providers: List = emptyList(),
+): MetaDataLoader = MetaDataLoader.fromUris(name, uris, withProviders(opts, providers))
 
-/** Load metadata from classpath resource paths; pass [LoaderOptions] to tune. */
+/** Load metadata from classpath resource paths; pass [LoaderOptions] to tune and [providers] for a project's own vocabulary. */
 fun loadResources(
     name: String,
     resources: List,
     opts: LoaderOptions? = null,
-): MetaDataLoader = MetaDataLoader.fromResources(name, resources, opts)
+    providers: List = emptyList(),
+): MetaDataLoader = MetaDataLoader.fromResources(name, resources, withProviders(opts, providers))
 
 /**
  * Load metadata from a single inline string (defaults to JSON); pass [LoaderOptions] to
@@ -48,4 +65,5 @@ fun loadString(
     content: String,
     format: MetaDataFormat = MetaDataFormat.JSON,
     opts: LoaderOptions? = null,
-): MetaDataLoader = MetaDataLoader.fromString(name, content, format, opts)
+    providers: List = emptyList(),
+): MetaDataLoader = MetaDataLoader.fromString(name, content, format, withProviders(opts, providers))
diff --git a/server/java/metadata-ktx/src/test/kotlin/com/metaobjects/metadata/ktx/ProviderVocabularyTest.kt b/server/java/metadata-ktx/src/test/kotlin/com/metaobjects/metadata/ktx/ProviderVocabularyTest.kt
new file mode 100644
index 0000000000..b969889078
--- /dev/null
+++ b/server/java/metadata-ktx/src/test/kotlin/com/metaobjects/metadata/ktx/ProviderVocabularyTest.kt
@@ -0,0 +1,93 @@
+package com.metaobjects.metadata.ktx
+
+import com.metaobjects.field.StringField
+import com.metaobjects.io.json.CanonicalJsonSerializer
+import com.metaobjects.layout.MetaLayout
+import com.metaobjects.loader.LoaderOptions
+import com.metaobjects.registry.MetaDataRegistry
+import com.metaobjects.registry.MetaDataTypeProvider
+import com.metaobjects.source.JsonSource
+import java.nio.charset.StandardCharsets
+import java.nio.file.Files
+import java.nio.file.Path
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+
+/**
+ * A project's own vocabulary, written in Kotlin and passed to the metadata-ktx loader as
+ * `providers = listOf(...)`. Runs the two shared `provider-custom-vocabulary-*` conformance
+ * fixtures: loaded with the provider the input matches `expected.json`; loaded without it the
+ * strict load refuses it with the expected codes, in order, at the expected JSON paths.
+ */
+class ProviderVocabularyTest {
+
+    /** The project's own layout subtype. */
+    class PickerLayout(name: String) : MetaLayout("picker", name)
+
+    /** `layout.picker` + `field.string` gains `@searchable` / `@valueLabels`. */
+    class ContactVocabulary : MetaDataTypeProvider {
+        override fun getProviderId() = "example-custom-vocabulary"
+
+        // The Java port's real provider ids; the cross-port alias "metaobjects-core-types" is
+        // not a Java provider id.
+        override fun getDependencies() = arrayOf("field-types", "layout-types")
+
+        override fun registerTypes(registry: MetaDataRegistry) {
+            registry.registerType(PickerLayout::class.java) { def ->
+                def.type("layout").subType("picker").inheritsFrom("layout", "base")
+                def.optionalAttributeWithConstraints("displayField").ofType("string").asSingle()
+            }
+            registry.extendType(StringField::class.java) { def ->
+                def.optionalAttributeWithConstraints("searchable").ofType("boolean").asSingle()
+                def.optionalAttributeWithConstraints("valueLabels").ofType("string").asArray()
+            }
+        }
+    }
+
+    private fun fixtures(): Path {
+        var p: Path? = Path.of(System.getProperty("user.dir")).toAbsolutePath()
+        while (p != null && !Files.exists(p.resolve("fixtures/conformance"))) p = p.parent
+        assertTrue(p != null, "could not locate fixtures/conformance from user.dir")
+        return p!!.resolve("fixtures/conformance")
+    }
+
+    private fun read(p: Path) = String(Files.readAllBytes(p), StandardCharsets.UTF_8)
+
+    private val strict = { LoaderOptions.create(false, false, true) }
+
+    @Test fun `success fixture loads with providers and matches the canonical output`() {
+        val dir = fixtures().resolve("provider-custom-vocabulary-success")
+        val loader = loadString(
+            "examples", read(dir.resolve("input/meta.contacts.json")),
+            opts = strict(), providers = listOf(ContactVocabulary()),
+        )
+        assertTrue(loader.errors.isEmpty(), "unexpected errors: ${loader.errors}")
+        assertEquals(
+            read(dir.resolve("expected.json")).trim(),
+            CanonicalJsonSerializer.canonicalSerialize(loader.root).trim(),
+        )
+    }
+
+    @Test fun `missing-provider fixture is refused with the expected codes in order`() {
+        val dir = fixtures().resolve("provider-custom-vocabulary-missing-provider-fails")
+        val loader = loadString("examples", read(dir.resolve("input/meta.contacts.json")), opts = strict())
+        val got = loader.errors.map {
+            it.code.get().name to (it.envelope.get() as JsonSource).jsonPath()
+        }
+        val base = "\$['metadata.root'].children[0]['object.value'].children"
+        assertEquals(
+            listOf(
+                "ERR_UNKNOWN_SUBTYPE" to "$base[2]['layout.picker']",
+                "ERR_UNKNOWN_ATTR" to "$base[0]['field.string']",
+                "ERR_UNKNOWN_ATTR" to "$base[1]['field.string']",
+            ),
+            got,
+        )
+    }
+
+    @Test fun `no providers leaves the default registry in place`() {
+        val loader = loadString("x", """{ "metadata.root": { "package": "acme", "children": [] } }""")
+        assertTrue(loader.typeRegistry.isSealed)
+    }
+}
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderOptions.java b/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderOptions.java
index e4759bd999..74ce2192e3 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderOptions.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderOptions.java
@@ -1,5 +1,10 @@
 package com.metaobjects.loader;
 
+import com.metaobjects.registry.MetaDataTypeProvider;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
 import java.util.Objects;
 
 
@@ -13,6 +18,9 @@ public class LoaderOptions {
     private boolean verbose = true;
     private boolean strict = true;
 
+    /** Extra vocabulary providers composed into the loader's registry; empty = the shared default. */
+    private List providers = List.of();
+
     public LoaderOptions() {}
 
     public static LoaderOptions create(boolean shouldRegister, boolean verbose, boolean strict ) {
@@ -53,6 +61,22 @@ public boolean isStrict() {
         return strict;
     }
 
+    /**
+     * A project's own vocabulary: the loader composes
+     * {@link com.metaobjects.registry.RegistryManifest#composeLoaderRegistry(Collection)} with these
+     * providers appended after the metamodel set, instead of using the shared default registry.
+     * Empty (the default) leaves loading byte-identical to a loader given no providers.
+     */
+    public LoaderOptions setProviders(Collection providers) {
+        this.providers = providers == null ? List.of() : List.copyOf(new ArrayList<>(providers));
+        return this;
+    }
+
+    /** The extra providers (never null, unmodifiable). */
+    public List getProviders() {
+        return providers;
+    }
+
     ///////////////////////////////////////////////////////////////////////////
     // Misc Functions
 
@@ -63,7 +87,8 @@ public boolean equals(Object o) {
         LoaderOptions that = (LoaderOptions) o;
         return shouldRegister == that.shouldRegister &&
                 verbose == that.verbose &&
-                strict == that.strict;
+                strict == that.strict &&
+                providers.equals(that.providers);
     }
 
     @Override
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java b/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java
index 28b6c0326b..f09473d809 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java
@@ -175,6 +175,7 @@ public class MetaDataLoader implements LoaderConfigurable {
     // this list AFTER catching the load's (final) thrown MetaDataException and
     // merges the two into a single per-fixture error set.
     private final List errors = new ArrayList<>();
+    private final List deferredAttrErrors = new ArrayList<>();
 
     // FR5c — envelope-shaped warnings accumulator (cross-port parallel channel).
     //
@@ -717,7 +718,21 @@ public static MetaDataLoader fromDirectory(String name, Path directory, Director
      */
     public static MetaDataLoader fromDirectory(String name, Path directory,
                                                DirectorySource.Options opts, List libraries) {
-        MetaDataLoader loader = createManual(false, name);
+        return fromDirectory(name, directory, opts, libraries, List.of());
+    }
+
+    /**
+     * {@link #fromDirectory(String, Path, DirectorySource.Options, List)} with a project's own
+     * vocabulary: {@code providers} are composed after the metamodel set (see
+     * {@link LoaderOptions#setProviders}). Empty is byte-identical to the overload without it.
+     *
+     * @param providers extra {@link com.metaobjects.registry.MetaDataTypeProvider}s; null or empty adds none
+     */
+    public static MetaDataLoader fromDirectory(String name, Path directory,
+                                               DirectorySource.Options opts, List libraries,
+                                               List providers) {
+        MetaDataLoader loader = new MetaDataLoader(
+            LoaderOptions.create(false, false, false).setProviders(providers), SUBTYPE_MANUAL, name);
         try {
             loader.init();
             List sources = new ArrayList<>(
@@ -1036,6 +1051,23 @@ public void addError(MetaDataException error) {
         errors.add(error);
     }
 
+    /**
+     * Record an {@code ERR_UNKNOWN_ATTR} found while parsing, to be appended to {@link #getErrors()}
+     * once every source of this batch has been parsed. The cross-port contract orders structural
+     * errors (unknown type / subtype, ...) ahead of attribute-schema errors, because the TypeScript
+     * reference checks attributes in a pass after the tree is built; recording this one inline would
+     * interleave it in document order (see {@code provider-custom-vocabulary-missing-provider-fails}).
+     */
+    public void addDeferredAttrError(MetaDataException error) {
+        if (error == null) return;
+        deferredAttrErrors.add(error);
+    }
+
+    private void flushDeferredAttrErrors() {
+        errors.addAll(deferredAttrErrors);
+        deferredAttrErrors.clear();
+    }
+
     /**
      * Clear accumulated errors. Called at the start of {@link #load(List)} so
      * a fresh batch does not see stale errors from a prior load on the same
@@ -1043,6 +1075,7 @@ public void addError(MetaDataException error) {
      */
     void clearErrors() {
         errors.clear();
+        deferredAttrErrors.clear();
     }
 
     /**
@@ -1158,11 +1191,24 @@ public MetaDataRegistry getTypeRegistry() {
             // ai*/json*/object.managed tooling vocabulary). Downstream apps that
             // need extra vocabulary use setTypeRegistry(compose(...)) — their own
             // unsealed registry.
-            typeRegistry = com.metaobjects.registry.RegistryManifest.defaultLoaderRegistry();
+            typeRegistry = resolveDefaultTypeRegistry();
         }
         return typeRegistry;
     }
 
+    /**
+     * The registry this loader uses when none was set explicitly: the shared sealed default, or —
+     * when {@link LoaderOptions#getProviders()} is non-empty — a sealed registry composed from the
+     * metamodel set plus those providers (the sanctioned project-vocabulary path).
+     */
+    private com.metaobjects.registry.MetaDataRegistry resolveDefaultTypeRegistry() {
+        List extra =
+            loaderOptions == null ? List.of() : loaderOptions.getProviders();
+        return extra.isEmpty()
+            ? com.metaobjects.registry.RegistryManifest.defaultLoaderRegistry()
+            : com.metaobjects.registry.RegistryManifest.composeLoaderRegistry(extra);
+    }
+
     public MetaDataLoader setTypeRegistry(MetaDataRegistry typeRegistry) {
         this.typeRegistry = typeRegistry;
         return this;
@@ -1441,7 +1487,7 @@ protected void initDefaultRegistries() {
         if (typeRegistry == null) {
             // ADR-0023 Decision 2 — default to the sealed defined-provider-set
             // registry (see getTypeRegistry()), not the polluted SPI singleton.
-            typeRegistry = com.metaobjects.registry.RegistryManifest.defaultLoaderRegistry();
+            typeRegistry = resolveDefaultTypeRegistry();
             log.debug("Initialized default (sealed metamodel) MetaDataRegistry for loader: {}", getName());
         }
 
@@ -1796,6 +1842,7 @@ public MetaDataLoader load(List sources) {
             }
         } finally {
             deferringOverlays = false;
+            flushDeferredAttrErrors();
         }
 
         // ADR-0055 — apply every queued overlay now, before super resolution.
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java
index e4fc2442cc..93873239a9 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java
@@ -1364,7 +1364,7 @@ private void processAttributes(MetaData md, JsonObject body) {
             if (isStrictLoad()
                     && !isDeclaredAttribute(md, attrName)
                     && !isExemptPropertiesAttr(entry.getValue())) {
-                getLoader().addError(new MetaDataException(
+                getLoader().addDeferredAttrError(new MetaDataException(
                     "Unknown attribute '" + JSON_ATTR_PREFIX + attrName + "' on "
                         + md.getType() + "." + md.getSubType() + " '" + md.getName()
                         + "' in file [" + getFilename() + "] — not declared by any "
diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java b/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java
index 596e86fd55..9c97e70d21 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java
@@ -207,13 +207,7 @@ public static MetaDataRegistry defaultLoaderRegistry() {
             synchronized (DEFAULT_LOCK) {
                 r = defaultLoaderRegistry;
                 if (r == null) {
-                    r = composeMetamodelRegistry();
-                    // The core constraint set is normally lazy-loaded on first
-                    // getAllValidationConstraints() read — which, post-seal, would
-                    // happen DURING a load and trip the seal guard. Force it now,
-                    // while still unsealed, so the sealed registry is fully built.
-                    r.getAllValidationConstraints();
-                    r.seal();
+                    r = composeLoaderRegistry(List.of());
                     defaultLoaderRegistry = r;
                 }
             }
@@ -221,6 +215,32 @@ public static MetaDataRegistry defaultLoaderRegistry() {
         return r;
     }
 
+    /**
+     * The sanctioned way to give a loader a project's own vocabulary: compose the
+     * metamodel provider set PLUS {@code extra} (a project's {@link MetaDataTypeProvider}s),
+     * run the strict spec-description pipeline, and SEAL the result — exactly what
+     * {@link #defaultLoaderRegistry()} does for zero extras, so a project that adds
+     * vocabulary is held to the same strict provenance (ADR-0023) as one that does not.
+     * Every {@code MetaDataLoader} entry point that accepts providers
+     * ({@code LoaderOptions.setProviders}, the {@code from*} factories, the Maven
+     * plugin's {@code }, the Spring auto-configuration, the Kotlin facade)
+     * routes through here. Unlike {@code defaultLoaderRegistry()} the result is a NEW
+     * registry on every call.
+     *
+     * @param extra additional providers composed after the metamodel provider set
+     * @return a new, sealed registry
+     */
+    public static MetaDataRegistry composeLoaderRegistry(Collection extra) {
+        MetaDataRegistry r = composeMetamodelRegistry(extra);
+        // The core constraint set is normally lazy-loaded on first
+        // getAllValidationConstraints() read — which, post-seal, would
+        // happen DURING a load and trip the seal guard. Force it now,
+        // while still unsealed, so the sealed registry is fully built.
+        r.getAllValidationConstraints();
+        r.seal();
+        return r;
+    }
+
     private static volatile MetaDataRegistry defaultLoaderRegistry;
     private static final Object DEFAULT_LOCK = new Object();
 
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 f067080630..ac113346be 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
@@ -362,6 +362,11 @@ static void runConformanceChecks(FixtureDiscovery.Fixture fix,
         String loaderName = detectLoaderName(inputFiles);
 
         LoaderOptions opts = LoaderOptions.create(false, false, true);
+        // A fixture naming the project-vocabulary provider loads through the SANCTIONED path:
+        // LoaderOptions.setProviders -> RegistryManifest.composeLoaderRegistry (sealed, strict).
+        if (fix.hasProvidersJson && fix.requiredProviders.contains("example-custom-vocabulary")) {
+            opts.setProviders(List.of(ConformanceTestProviders.EXAMPLE_CUSTOM_VOCABULARY));
+        }
         MetaDataLoader loader = new MetaDataLoader(opts, MetaDataLoader.SUBTYPE_MANUAL, loaderName);
         // A fixture that requires the test-only example-template-briefing provider
         // gets its OWN registry (core + briefing) via setTypeRegistry — no global
diff --git a/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTestProviders.java b/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTestProviders.java
index 27cfb3f36f..3e6f25f3b2 100644
--- a/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTestProviders.java
+++ b/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTestProviders.java
@@ -17,7 +17,10 @@
  */
 package com.metaobjects.conformance;
 
+import com.metaobjects.attr.BooleanAttribute;
 import com.metaobjects.attr.StringAttribute;
+import com.metaobjects.field.StringField;
+import com.metaobjects.layout.MetaLayout;
 import com.metaobjects.registry.MetaDataRegistry;
 import com.metaobjects.registry.MetaDataTypeProvider;
 import com.metaobjects.template.MetaTemplate;
@@ -66,6 +69,41 @@ public static void registerTypes(MetaDataRegistry registry) {
         @Override public String getDescription() { return "Test-only: registers a fictional template.briefing subtype."; }
     };
 
+    /** Test-only `layout.picker` node — a MetaLayout subclass, as a project's own node class would be. */
+    public static final class PickerLayout extends MetaLayout {
+        public PickerLayout(String name) {
+            super("picker", name);
+        }
+    }
+
+    /**
+     * A project's own vocabulary (provider-custom-vocabulary-* fixtures): registers
+     * {@code layout.picker} (+ optional {@code @displayField}) and extends
+     * {@code field.string} with optional {@code @searchable} (boolean) and
+     * {@code @valueLabels} (string array). Mirrors the TypeScript reference
+     * {@code exampleCustomVocabularyProvider}.
+     */
+    public static final MetaDataTypeProvider EXAMPLE_CUSTOM_VOCABULARY = new MetaDataTypeProvider() {
+        @Override public String getProviderId() { return "example-custom-vocabulary"; }
+        @Override public String[] getDependencies() { return new String[]{"field-types", "layout-types"}; }
+        @Override public void registerTypes(MetaDataRegistry registry) {
+            registry.registerType(PickerLayout.class, def -> {
+                def.type("layout").subType("picker")
+                   .description("A picker that chooses one row of the owning object — test-only.")
+                   .inheritsFrom("layout", "base");
+                def.optionalAttributeWithConstraints("displayField")
+                   .ofType(StringAttribute.SUBTYPE_STRING).asSingle();
+            });
+            registry.extendType(StringField.class, def -> {
+                def.optionalAttributeWithConstraints("searchable")
+                   .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle();
+                def.optionalAttributeWithConstraints("valueLabels")
+                   .ofType(StringAttribute.SUBTYPE_STRING).asArray();
+            });
+        }
+        @Override public String getDescription() { return "Test-only: a project's own layout.picker + field.string attrs."; }
+    };
+
     public static final MetaDataTypeProvider CYCLE_A = noop("cycle-a", "cycle-b");
     public static final MetaDataTypeProvider CYCLE_B = noop("cycle-b", "cycle-a");
     public static final MetaDataTypeProvider DEPENDS_ON_MISSING = noop("depends-on-missing", "does-not-exist");
@@ -82,6 +120,7 @@ public static void registerTypes(MetaDataRegistry registry) {
      */
     public static final Map TEST_PROVIDERS = Map.of(
         "example-template-briefing", EXAMPLE_TEMPLATE_BRIEFING,
+        "example-custom-vocabulary", EXAMPLE_CUSTOM_VOCABULARY,
         "cycle-a", CYCLE_A,
         "cycle-b", CYCLE_B,
         "depends-on-missing", DEPENDS_ON_MISSING,
diff --git a/server/java/metadata/src/test/java/com/metaobjects/conformance/YamlTwinConformanceTest.java b/server/java/metadata/src/test/java/com/metaobjects/conformance/YamlTwinConformanceTest.java
index b713282ab6..01b25e613d 100644
--- a/server/java/metadata/src/test/java/com/metaobjects/conformance/YamlTwinConformanceTest.java
+++ b/server/java/metadata/src/test/java/com/metaobjects/conformance/YamlTwinConformanceTest.java
@@ -158,6 +158,9 @@ private static final class Outcome {
     private static Outcome load(FixtureDiscovery.Fixture f, List files, List texts,
                                 String loaderName, MetaDataSource.MetaDataFormat format) {
         LoaderOptions opts = LoaderOptions.create(false, false, true);
+        if (f.hasProvidersJson && f.requiredProviders.contains("example-custom-vocabulary")) {
+            opts.setProviders(List.of(ConformanceTestProviders.EXAMPLE_CUSTOM_VOCABULARY));
+        }
         MetaDataLoader loader = new MetaDataLoader(opts, MetaDataLoader.SUBTYPE_MANUAL, loaderName);
         if (f.hasProvidersJson && f.requiredProviders.contains("example-template-briefing")) {
             com.metaobjects.registry.MetaDataRegistry reg =
diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/LoaderProvidersTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/LoaderProvidersTest.java
new file mode 100644
index 0000000000..4b46d9e045
--- /dev/null
+++ b/server/java/metadata/src/test/java/com/metaobjects/loader/LoaderProvidersTest.java
@@ -0,0 +1,97 @@
+package com.metaobjects.loader;
+
+import com.metaobjects.MetaDataException;
+import com.metaobjects.attr.BooleanAttribute;
+import com.metaobjects.attr.StringAttribute;
+import com.metaobjects.field.StringField;
+import com.metaobjects.layout.MetaLayout;
+import com.metaobjects.registry.MetaDataRegistry;
+import com.metaobjects.registry.MetaDataTypeProvider;
+import com.metaobjects.registry.RegistryManifest;
+import org.junit.Test;
+
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+import static org.junit.Assert.*;
+
+/** A project's own vocabulary reaches the loader through every {@code from*} factory. */
+public class LoaderProvidersTest {
+
+    /** A project's own layout subtype. */
+    public static final class PickerLayout extends MetaLayout {
+        public PickerLayout(String name) { super("picker", name); }
+    }
+
+    static final MetaDataTypeProvider PROVIDER = new MetaDataTypeProvider() {
+        @Override public String getProviderId() { return "loader-providers-test"; }
+        @Override public String[] getDependencies() { return new String[]{"field-types", "layout-types"}; }
+        @Override public void registerTypes(MetaDataRegistry registry) {
+            registry.registerType(PickerLayout.class, def -> {
+                def.type("layout").subType("picker").inheritsFrom("layout", "base");
+                def.optionalAttributeWithConstraints("displayField")
+                   .ofType(StringAttribute.SUBTYPE_STRING).asSingle();
+            });
+            registry.extendType(StringField.class, def ->
+                def.optionalAttributeWithConstraints("searchable")
+                   .ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle());
+        }
+    };
+
+    static final String JSON = """
+        {"metadata.root": {"package": "p", "children": [
+          {"object.value": {"name": "Contact", "children": [
+            {"field.string": {"name": "name", "@searchable": true}},
+            {"layout.picker": {"name": "pick", "@displayField": "name"}}
+          ]}}
+        ]}}
+        """;
+
+    private static LoaderOptions strict() { return LoaderOptions.create(false, false, true); }
+
+    @Test public void fromStringComposesProviders() {
+        MetaDataLoader loader = MetaDataLoader.fromString("p", JSON,
+            MetaDataSource.MetaDataFormat.JSON, strict().setProviders(List.of(PROVIDER)));
+        assertTrue(loader.getErrors().isEmpty());
+        assertTrue(loader.getTypeRegistry().isSealed());
+        assertNotSame(RegistryManifest.defaultLoaderRegistry(), loader.getTypeRegistry());
+    }
+
+    @Test public void withoutProvidersTheStrictLoadRefusesAndDefaultRegistryIsShared() {
+        MetaDataLoader loader = MetaDataLoader.createManual(false, "p");
+        loader.getLoaderOptions().setStrict(true);
+        assertSame(RegistryManifest.defaultLoaderRegistry(), loader.getTypeRegistry());
+        MetaDataLoader refused = MetaDataLoader.fromString("p", JSON,
+            MetaDataSource.MetaDataFormat.JSON, strict());
+        assertEquals(List.of("ERR_UNKNOWN_SUBTYPE", "ERR_UNKNOWN_ATTR"),
+            refused.getErrors().stream().map(e -> e.getCode().get().name()).toList());
+    }
+
+    @Test public void fromDirectoryAndFromUrisAndFromResourcesAcceptProviders() throws Exception {
+        Path dir = Files.createTempDirectory("providers-test");
+        Path f = dir.resolve("meta.contacts.json");
+        Files.writeString(f, JSON);
+        MetaDataLoader d = MetaDataLoader.fromDirectory("p", dir,
+            new DirectorySource.Options(), null, List.of(PROVIDER));
+        assertTrue(d.getTypeRegistry().hasType("layout"));
+        assertNotNull(d.getTypeRegistry().getTypeDefinition("layout", "picker"));
+
+        MetaDataLoader u = MetaDataLoader.fromUris("p", List.of(URI.create(f.toUri().toString())),
+            strict().setProviders(List.of(PROVIDER)));
+        assertNotNull(u.getTypeRegistry().getTypeDefinition("layout", "picker"));
+    }
+
+    @Test public void composeLoaderRegistryIsFreshAndSealedEachCall() {
+        MetaDataRegistry a = RegistryManifest.composeLoaderRegistry(List.of(PROVIDER));
+        MetaDataRegistry b = RegistryManifest.composeLoaderRegistry(List.of(PROVIDER));
+        assertNotSame(a, b);
+        assertTrue(a.isSealed());
+    }
+
+    @Test public void defaultOptionsEqualityIgnoresNothingNew() {
+        assertEquals(LoaderOptions.create(false, false, true), LoaderOptions.create(false, false, true));
+        assertNotEquals(strict(), strict().setProviders(List.of(PROVIDER)));
+    }
+}
diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py
index 06817f3b69..d04d23e195 100644
--- a/server/python/src/metaobjects/cli.py
+++ b/server/python/src/metaobjects/cli.py
@@ -1178,8 +1178,9 @@ def _cmd_fmt(args: argparse.Namespace) -> int:
 
     Mirrors the TS reference surface exactly: no ``metadata_dir`` positional —
     files come from the neutral ``.metaobjects/config.json`` ladder
-    (:func:`resolve_metadata_location`, rungs 3-4; this command does not read
-    this port's own ``metaobjects.config.yaml`` rung 2, matching the scope the
+    (:func:`resolve_metadata_location`, rungs 3-4; this command reads only the
+    ``providers`` of this port's own ``metaobjects.config.yaml`` (never its rung 2
+    ``metadata`` location), matching the scope the
     C# and Java ports also keep for `fmt`), optionally narrowed by explicit
     file arguments.
     """
@@ -1191,6 +1192,20 @@ def _cmd_fmt(args: argparse.Namespace) -> int:
     providers_extra, providers_ok = _providers_from_args(args)
     if not providers_ok:
         return 1
+    # The project's own `providers:` (metaobjects.config.yaml) reach fmt too, merged with
+    # --provider. Only the providers are read from the config: the metadata location stays
+    # on the neutral ladder (see the docstring).
+    config_path = _find_config(args)
+    if config_path is not None:
+        try:
+            fmt_config = load_project_config(config_path)
+        except ConfigError as exc:
+            print(f"error: {exc}", file=sys.stderr)
+            return 1
+        config_providers, config_providers_ok = _config_providers(fmt_config)
+        if not config_providers_ok:
+            return 1
+        providers_extra = [*config_providers, *providers_extra]
     providers = [*core_providers, *providers_extra]
     registry = compose_registry(providers)
 
@@ -2587,11 +2602,17 @@ def unread(*lines: str) -> "_VerifyModel | None":
             config = load_project_config(config_path) if config_path is not None else None
             libraries: "list[str] | None" = None
             if config is not None:
-                providers, provider_errors = _resolve_config_providers(config)
-                if provider_errors:
+                # Merge, never overwrite: the project's providers AND --provider both apply.
+                flag_provider_errors = provider_errors
+                config_providers, config_provider_errors = _resolve_config_providers(config)
+                if config_provider_errors:
                     return unread(
-                        "error: invalid provider in config:", *(f"  {m}" for m in provider_errors)
+                        "error: invalid provider in config:",
+                        *(f"  {m}" for m in config_provider_errors),
                     )
+                if flag_provider_errors:
+                    return unread("error: invalid --provider:", *(f"  {m}" for m in flag_provider_errors))
+                providers = [*config_providers, *providers]
                 libraries = config.libraries
                 start = project_root_for(config.metadata_dir())
             else:
@@ -3117,7 +3138,14 @@ def _build_parser() -> argparse.ArgumentParser:
         action="append",
         default=None,
         metavar="MODULE:SYMBOL",
-        help="consumer-registered Provider(s), repeatable (module:symbol)",
+        help="consumer-registered Provider(s), repeatable (module:symbol); merged with the "
+        "`providers:` of metaobjects.config.yaml",
+    )
+    fmt_p.add_argument(
+        "--config",
+        default=None,
+        help="path to the metaobjects.config.yaml whose `providers:` apply "
+        "(default: ./metaobjects.config.yaml in cwd)",
     )
     fmt_p.set_defaults(func=_cmd_fmt)
 
diff --git a/server/python/src/metaobjects/loader/meta_data_loader.py b/server/python/src/metaobjects/loader/meta_data_loader.py
index 4589a04003..10aac86085 100644
--- a/server/python/src/metaobjects/loader/meta_data_loader.py
+++ b/server/python/src/metaobjects/loader/meta_data_loader.py
@@ -106,6 +106,9 @@ def get_envelope_warnings(self) -> list[LoaderWarning]:
         return list(self.envelope_warnings)
 
 
+_NODE_SKIPPING_CODES = frozenset({ErrorCode.ERR_UNKNOWN_SUBTYPE, ErrorCode.ERR_UNKNOWN_TYPE})
+
+
 class MetaDataLoader:
     """Source-polymorphic metadata loader.
 
@@ -152,7 +155,12 @@ def load(self, sources: list[MetaDataSource]) -> LoadResult:
             # Today these only arrive from merge sites (see merge_roots);
             # the channel is exposed here for future parser-emitted ones.
             result.envelope_warnings.extend(parsed.envelope_warnings)
-            if not parsed.errors:
+            if not parsed.errors or all(
+                e.code in _NODE_SKIPPING_CODES for e in parsed.errors
+            ):
+                # An unknown type/subtype drops only that node; the rest of the tree is
+                # intact, so keep it and let the validation passes report what else is
+                # wrong in the same load (cross-port: the TS loader does the same).
                 roots.append(parsed.root)
 
         if roots:
diff --git a/server/python/tests/codegen/test_cli_config_providers.py b/server/python/tests/codegen/test_cli_config_providers.py
new file mode 100644
index 0000000000..260314a4cf
--- /dev/null
+++ b/server/python/tests/codegen/test_cli_config_providers.py
@@ -0,0 +1,160 @@
+"""A project's custom providers reach every metadata-loading CLI entry point.
+
+``providers: ["module:symbol"]`` in ``metaobjects.config.yaml`` and ``--provider
+module:symbol`` are two spellings of the same thing and must MERGE wherever the CLI loads
+metadata: ``gen``, ``verify`` (codegen, templates, the requirement gate and field lint)
+and ``fmt``.
+"""
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+from metaobjects.cli import main
+
+# The project's own vocabulary: a new layout.picker subtype + two attrs on field.string.
+VOCAB_MODULE = '''
+from metaobjects.meta.presentation.layout.meta_layout import MetaLayout
+from metaobjects.provider import Provider
+from metaobjects.registry import AttrSchema, ChildRule, TypeDefinition
+from metaobjects.shared.base_types import TYPE_ATTR
+
+vocab = Provider("acme-vocabulary", dependencies=("metaobjects-core-types",))
+vocab.add(TypeDefinition(
+    type="layout", sub_type="picker", factory=MetaLayout,
+    attrs=[AttrSchema("displayField", "string", required=False)],
+    child_rules=[ChildRule(TYPE_ATTR, "*")],
+))
+vocab.on_register(lambda registry: registry.extend(
+    "field", "string",
+    attributes=[
+        AttrSchema("searchable", "boolean", required=False),
+        AttrSchema("valueLabels", "string", required=False, is_array=True),
+    ],
+))
+'''
+
+# A second, independent provider, supplied on the command line.
+FLAG_MODULE = '''
+from metaobjects.meta.meta_data import MetaData
+from metaobjects.provider import Provider
+from metaobjects.registry import TypeDefinition
+
+flag_provider = Provider("acme-flag", ("metaobjects-core-types",))
+flag_provider.add(TypeDefinition(
+    type="validator", sub_type="geocheck",
+    factory=lambda t, s, n: MetaData(t, s, n), description="A custom validator",
+))
+'''
+
+CUSTOM_META = {
+    "metadata.root": {
+        "package": "acme",
+        "children": [
+            {
+                "object.value": {
+                    "name": "Contact",
+                    "children": [
+                        {"field.string": {"name": "name", "@searchable": True}},
+                        {"layout.picker": {"name": "contactPicker", "@displayField": "name"}},
+                    ],
+                }
+            }
+        ],
+    }
+}
+
+
+@pytest.fixture
+def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+    meta = tmp_path / "metaobjects"
+    meta.mkdir()
+    (meta / "meta.contacts.json").write_text(json.dumps(CUSTOM_META), encoding="utf-8")
+    (tmp_path / "acme_vocab_mod.py").write_text(VOCAB_MODULE, encoding="utf-8")
+    (tmp_path / "acme_flag_mod.py").write_text(FLAG_MODULE, encoding="utf-8")
+    (tmp_path / "metaobjects.config.yaml").write_text(
+        'metadata: metaobjects\nproviders: ["acme_vocab_mod:vocab"]\n'
+        "targets:\n  app:\n    outDir: gen\n    generators: []\n",
+        encoding="utf-8",
+    )
+    monkeypatch.chdir(tmp_path)
+    saved = list(sys.path)
+    sys.path.insert(0, str(tmp_path))  # for the --provider (flag) module
+    yield tmp_path
+    sys.path[:] = saved
+    for name in ("acme_vocab_mod", "acme_flag_mod"):
+        sys.modules.pop(name, None)
+
+
+_SHARED_FIXTURE = (
+    Path(__file__).resolve().parents[4] / "fixtures" / "conformance" / "provider-custom-vocabulary-success"
+)
+
+
+def _with_geocheck(meta: dict) -> dict:
+    meta = json.loads(json.dumps(meta))
+    meta["metadata.root"]["children"][0]["object.value"]["children"][0]["field.string"][
+        "children"
+    ] = [{"validator.geocheck": {"name": "chk"}}]
+    return meta
+
+
+def _use_shared_fixture(project: Path) -> Path:
+    path = project / "metaobjects" / "meta.contacts.json"
+    meta = json.loads((_SHARED_FIXTURE / "input" / "meta.contacts.json").read_text(encoding="utf-8"))
+    path.write_text(json.dumps(meta), encoding="utf-8")  # compact, not canonical
+    return path
+
+
+def test_fmt_honors_config_providers(project: Path) -> None:
+    path = _use_shared_fixture(project)
+    assert main(["fmt", "--check"]) == 1
+    assert main(["fmt"]) == 0
+    assert main(["fmt", "--check"]) == 0
+    assert json.loads(path.read_text(encoding="utf-8")) == json.loads(
+        (_SHARED_FIXTURE / "expected.json").read_text(encoding="utf-8")
+    )
+
+
+def test_fmt_rewrites_a_file_using_the_config_vocabulary(project: Path) -> None:
+    path = _use_shared_fixture(project)
+    assert main(["fmt"]) == 0
+    expected = (_SHARED_FIXTURE / "expected.json").read_text(encoding="utf-8")
+    assert path.read_text(encoding="utf-8").rstrip("\n") == expected.rstrip("\n")
+
+
+def test_fmt_without_config_providers_still_refuses_the_vocabulary(project: Path, capsys) -> None:
+    path = _use_shared_fixture(project)
+    before = path.read_text(encoding="utf-8")
+    (project / "metaobjects.config.yaml").unlink()
+    assert main(["fmt"]) == 1
+    captured = capsys.readouterr()
+    assert "ERR_UNKNOWN_SUBTYPE" in captured.out + captured.err
+    assert path.read_text(encoding="utf-8") == before
+
+
+def test_fmt_merges_config_and_flag_providers(project: Path) -> None:
+    path = project / "metaobjects" / "meta.contacts.json"
+    path.write_text(json.dumps(_with_geocheck(CUSTOM_META)), encoding="utf-8")
+    assert main(["fmt"]) == 1
+    assert main(["fmt", "--provider", "acme_flag_mod:flag_provider"]) == 0
+    assert json.loads(path.read_text(encoding="utf-8")) == _with_geocheck(CUSTOM_META)
+
+
+def test_verify_keeps_config_and_flag_providers(project: Path) -> None:
+    """Metadata needing BOTH the config provider's vocabulary and the flag provider's
+    validator loads clean through every verify gate (requirement gate + field lint)."""
+    (project / "metaobjects" / "meta.contacts.json").write_text(
+        json.dumps(_with_geocheck(CUSTOM_META)), encoding="utf-8"
+    )
+    assert main(["verify", "--provider", "acme_flag_mod:flag_provider"]) == 0
+
+
+def test_verify_without_the_flag_provider_fails_on_its_validator(project: Path) -> None:
+    (project / "metaobjects" / "meta.contacts.json").write_text(
+        json.dumps(_with_geocheck(CUSTOM_META)), encoding="utf-8"
+    )
+    assert main(["verify"]) != 0
diff --git a/server/python/tests/conformance/conformance_adapter.py b/server/python/tests/conformance/conformance_adapter.py
index f49f406da2..5ab97f2e02 100644
--- a/server/python/tests/conformance/conformance_adapter.py
+++ b/server/python/tests/conformance/conformance_adapter.py
@@ -65,6 +65,42 @@ def _example_template_briefing_provider() -> Provider:
     return p
 
 
+def _example_custom_vocabulary_provider() -> Provider:
+    """Test-only: a project's own vocabulary (layout.picker + field.string attrs).
+
+    Mirrors the TS adapter's ``exampleCustomVocabularyProvider``: registers a new
+    ``layout.picker`` subtype (one optional ``displayField``) and extends
+    ``field.string`` with an optional boolean ``searchable`` and an optional
+    string-array ``valueLabels``. The ``provider-custom-vocabulary-*`` fixtures load
+    clean with it and are refused without it.
+    """
+    from metaobjects.meta.presentation.layout.meta_layout import MetaLayout
+
+    p = Provider("example-custom-vocabulary", dependencies=("metaobjects-core-types",))
+    p.add(
+        TypeDefinition(
+            type="layout",
+            sub_type="picker",
+            factory=MetaLayout,
+            attrs=[AttrSchema("displayField", "string", required=False)],
+            child_rules=[ChildRule(TYPE_ATTR, "*")],
+        )
+    )
+
+    def _extend(registry) -> None:
+        registry.extend(
+            "field",
+            "string",
+            attributes=[
+                AttrSchema("searchable", "boolean", required=False),
+                AttrSchema("valueLabels", "string", required=False, is_array=True),
+            ],
+        )
+
+    p.on_register(_extend)
+    return p
+
+
 def _noop_provider(provider_id: str, *deps: str) -> Provider:
     return Provider(provider_id, dependencies=tuple(deps))
 
@@ -96,6 +132,7 @@ def _noop_provider(provider_id: str, *deps: str) -> Provider:
     "metaobjects-template": prompt_provider,
     # Test-only — provider-extension-* fixtures.
     "example-template-briefing": _example_template_briefing_provider(),
+    "example-custom-vocabulary": _example_custom_vocabulary_provider(),
     "cycle-a": _noop_provider("cycle-a", "cycle-b"),
     "cycle-b": _noop_provider("cycle-b", "cycle-a"),
     "depends-on-missing": _noop_provider("depends-on-missing", "does-not-exist"),
diff --git a/server/typescript/packages/cli/src/commands/export.ts b/server/typescript/packages/cli/src/commands/export.ts
index fc9f1c3a34..7db145be2f 100644
--- a/server/typescript/packages/cli/src/commands/export.ts
+++ b/server/typescript/packages/cli/src/commands/export.ts
@@ -3,8 +3,9 @@ import { writeFile } from "node:fs/promises";
 import { parseExportArgs } from "../lib/args.js";
 import { log } from "../lib/log.js";
 import { FileSource } from "@metaobjectsdev/metadata/core";
-import { TypeRegistry, registerCoreTypes, MetaDataLoader, canonicalSerialize } from "@metaobjectsdev/metadata";
-import { registerForgeTypes, resolveCollection } from "@metaobjectsdev/sdk";
+import { composeRegistry, MetaDataLoader, canonicalSerialize } from "@metaobjectsdev/metadata";
+import { defaultLoadMemoryProviders, forgeTypesProvider, resolveCollection } from "@metaobjectsdev/sdk";
+import { loadProjectProviders } from "../lib/load-metaobjects-config.js";
 import { collectionLoadOptions } from "../lib/collection-load-options.js";
 import { describeError } from "../lib/error-text.js";
 
@@ -19,12 +20,6 @@ export async function exportCommand(args: string[], cwd: string): Promise !base.some((b) => b.id === p.id))]);
+
   // `loadAndExportJson` only accepts a scanned directory (`MetaDataLoader.fromDirectory`);
   // `resolveCollection` already resolved the file SET (declared `sources`, or the
   // `metaobjects/` default), so load that list directly via the same loader +
diff --git a/server/typescript/packages/cli/src/commands/prompt-snapshot.ts b/server/typescript/packages/cli/src/commands/prompt-snapshot.ts
index 230ae5ec5d..5578068869 100644
--- a/server/typescript/packages/cli/src/commands/prompt-snapshot.ts
+++ b/server/typescript/packages/cli/src/commands/prompt-snapshot.ts
@@ -61,17 +61,21 @@ export async function promptSnapshotCommand(args: string[], cwd: string): Promis
   // or invalid, fall back to defaults — the loader still works for any
   // metadata that only uses core+forge subtypes.
   let configLoadOptions: ReturnType = {};
-  try {
-    // `metaobjects.config.ts` gets its own nearest-ancestor walk, not `projectRoot`:
-    // it answers a different question from `.metaobjects/config.json` (design §4.6)
-    // and in a Maven- or pip-rooted monorepo the two legitimately sit in different
-    // directories, so reading it from the collection's would silently drop this
-    // package's providers (#326). Same path whenever the two files sit together.
-    configLoadOptions = loadMemoryOptionsFrom(
-      await loadMetaobjectsConfig(resolveGenConfigDir(cwd, projectRoot)),
-    );
-  } catch {
-    configLoadOptions = {};
+  // `metaobjects.config.ts` gets its own nearest-ancestor walk, not `projectRoot`:
+  // it answers a different question from `.metaobjects/config.json` (design §4.6)
+  // and in a Maven- or pip-rooted monorepo the two legitimately sit in different
+  // directories, so reading it from the collection's would silently drop this
+  // package's providers (#326). Same path whenever the two files sit together.
+  const genConfigDir = resolveGenConfigDir(cwd, projectRoot);
+  if (existsSync(join(genConfigDir, "metaobjects.config.ts"))) {
+    try {
+      configLoadOptions = loadMemoryOptionsFrom(await loadMetaobjectsConfig(genConfigDir));
+    } catch (err) {
+      // A config that exists but fails to load is reported as itself, not as the
+      // unknown-subtype error its providers would have prevented.
+      log.error(`metaobjects.config.ts failed to load: ${describeError(err)}`);
+      return 1;
+    }
   }
 
   let root;
diff --git a/server/typescript/packages/cli/src/commands/types.ts b/server/typescript/packages/cli/src/commands/types.ts
index 36f4a16648..8378583e3b 100644
--- a/server/typescript/packages/cli/src/commands/types.ts
+++ b/server/typescript/packages/cli/src/commands/types.ts
@@ -20,7 +20,8 @@
 // The `--json` flag this once advertised in its own --help, twice, is not coming back: the
 // CLI rejects a bare `--json` before a command ever sees its args (index.ts, `formatAlias`),
 // on purpose — one global spelling for all three formats.
-import { composeRegistry, buildVocabularyCatalog } from "@metaobjectsdev/metadata";
+import { composeRegistry, buildVocabularyCatalog, type MetaDataTypeProvider } from "@metaobjectsdev/metadata";
+import { loadProjectProviders } from "../lib/load-metaobjects-config.js";
 import { defaultLoadMemoryProviders } from "@metaobjectsdev/sdk";
 import { log } from "../lib/log.js";
 import { emitStructured, type OutputFormat } from "../lib/format.js";
@@ -257,7 +258,18 @@ export async function typesCommand(args: string[], fmt: OutputFormat = "text"):
   // once in this list, and printing it as registered vocabulary was part of how a TS-only
   // registration read as cross-port: `meta types forge --all` listed 20 attrs no other port
   // has. One composition, one door.
-  const registry = composeRegistry([...defaultLoadMemoryProviders], { validate: true });
+  // Plus the project's own providers when a `metaobjects.config.ts` governs this directory,
+  // so project vocabulary (`layout.picker`, extended attrs) is listed. No config: unchanged.
+  let projectProviders: readonly MetaDataTypeProvider[] = [];
+  try {
+    projectProviders = await loadProjectProviders(process.cwd(), process.cwd());
+  } catch (err) {
+    const msg = `metaobjects.config.ts failed to load: ${describeError(err)}`;
+    log.error(msg);
+    emitStructured({ error: msg, hint: "fix the config, or run outside the project for the built-in vocabulary" }, fmt);
+    return 1;
+  }
+  const registry = composeRegistry([...defaultLoadMemoryProviders, ...projectProviders], { validate: true });
   const catalog = buildVocabularyCatalog(registry);
 
   // Flatten the catalog into searchable entries.
diff --git a/server/typescript/packages/cli/src/commands/upgrade.ts b/server/typescript/packages/cli/src/commands/upgrade.ts
index 4e1bcbf95f..01e2a2b3b0 100644
--- a/server/typescript/packages/cli/src/commands/upgrade.ts
+++ b/server/typescript/packages/cli/src/commands/upgrade.ts
@@ -27,7 +27,9 @@ import {
   coreProviders,
   SUBTYPE_BASE,
   retirementSuggestions,
+  type MetaDataTypeProvider,
 } from "@metaobjectsdev/metadata";
+import { loadProjectProviders } from "../lib/load-metaobjects-config.js";
 import { log } from "../lib/log.js";
 import { describeError } from "../lib/error-text.js";
 import { unknownFlagMessage } from "../lib/strict-args.js";
@@ -124,7 +126,18 @@ export async function upgradeCommand(args: string[], cwd: string): Promise id.type))]
diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts
index 991aebeaea..4ed889e740 100644
--- a/server/typescript/packages/cli/src/commands/verify.ts
+++ b/server/typescript/packages/cli/src/commands/verify.ts
@@ -309,6 +309,16 @@ export async function verifyCommand(
     forgeConfig = undefined;
     configLoadError = e;
   }
+  // A config that EXISTS but fails to load must be reported as itself in EVERY mode: continuing
+  // without its providers turns a config error into a misleading ERR_UNKNOWN_SUBTYPE on the
+  // custom vocabulary those providers register.
+  if (forgeConfig === undefined && existsSync(join(genConfigDir, "metaobjects.config.ts"))) {
+    log.error(
+      "meta verify: metaobjects.config.ts exists but failed to load: " +
+        (configLoadError instanceof Error ? configLoadError.message : String(configLoadError)),
+    );
+    return 2;
+  }
   // Both of the gen config's contributions to the load, together — see
   // `loadMemoryOptionsFrom`. Threading `providers` and forgetting `libraries` is how
   // a shipped library became unloadable through the CLI (#333).
@@ -319,13 +329,7 @@ export async function verifyCommand(
   // keeps a passing bare verify; the note says what was skipped and why.
   if (!flags.anyExplicit) {
     if (forgeConfig !== undefined) runCodegen = true;
-    else if (existsSync(join(genConfigDir, "metaobjects.config.ts"))) {
-      log.error(
-        "meta verify: metaobjects.config.ts exists but failed to load, so the codegen gate cannot run: " +
-          (configLoadError instanceof Error ? configLoadError.message : String(configLoadError)),
-      );
-      return 2;
-    } else say("meta verify — codegen gate skipped: no metaobjects.config.ts found, so there is no generated output to diff against");
+    else say("meta verify — codegen gate skipped: no metaobjects.config.ts found, so there is no generated output to diff against");
   }
 
   // ADR-0023 strict-by-default (#96): verify loads strict unless --lax is passed,
diff --git a/server/typescript/packages/cli/src/lib/dependency-load.ts b/server/typescript/packages/cli/src/lib/dependency-load.ts
index 3cdf2488fc..26ec4ef22a 100644
--- a/server/typescript/packages/cli/src/lib/dependency-load.ts
+++ b/server/typescript/packages/cli/src/lib/dependency-load.ts
@@ -35,6 +35,7 @@ import {
   type ResolvedDependency,
 } from "@metaobjectsdev/sdk";
 import { collectionLoadOptions } from "./collection-load-options.js";
+import { loadProjectProviders } from "./load-metaobjects-config.js";
 
 /** `resolveCollection`'s code for "no `sources` declared and no default directory". */
 const ERR_COLLECTION_NOT_FOUND = "ERR_COLLECTION_NOT_FOUND";
@@ -130,7 +131,14 @@ export async function proveDependencySetLoads(configDir: string): Promise 0 ? { providers } : {}) };
   try {
     await loadMemory(collection.configDir, loadOptions);
     return { scope: "full" };
diff --git a/server/typescript/packages/cli/src/lib/fmt-engine.ts b/server/typescript/packages/cli/src/lib/fmt-engine.ts
index 48d6ed6862..0a165bd5ce 100644
--- a/server/typescript/packages/cli/src/lib/fmt-engine.ts
+++ b/server/typescript/packages/cli/src/lib/fmt-engine.ts
@@ -25,7 +25,7 @@ import {
 } from "@metaobjectsdev/metadata";
 import { FileSource } from "@metaobjectsdev/metadata/core";
 import { resolveCollection, defaultLoadMemoryProviders, type Collection } from "@metaobjectsdev/sdk";
-import { loadMetaobjectsConfig, loadMemoryOptionsFrom } from "./load-metaobjects-config.js";
+import { loadProjectProviders } from "./load-metaobjects-config.js";
 
 export type FmtFileStatus =
   | "formatted"
@@ -57,18 +57,6 @@ export interface FmtRunOptions {
   readonly files?: readonly string[];
 }
 
-async function projectProviders(collection: Collection): Promise {
-  try {
-    const cfg = await loadMetaobjectsConfig(collection.configDir);
-    return loadMemoryOptionsFrom(cfg).providers ?? [];
-  } catch {
-    // No metaobjects.config.ts (common for a non-TS-server project running
-    // `meta fmt` just for schema-neutral formatting) — format against the
-    // core vocabulary only, exactly like a project with no custom providers.
-    return [];
-  }
-}
-
 export async function runFmt(opts: FmtRunOptions): Promise {
   let collection: Collection;
   try {
@@ -77,7 +65,14 @@ export async function runFmt(opts: FmtRunOptions): Promise {
     return { files: [], fatal: err instanceof Error ? err.message : String(err) };
   }
 
-  const providers = await projectProviders(collection);
+  // Nearest-ancestor config (like every other command); a config that exists but fails
+  // to load is fatal rather than silently "no providers".
+  let providers: readonly MetaDataTypeProvider[];
+  try {
+    providers = await loadProjectProviders(opts.projectRoot, collection.configDir);
+  } catch (err) {
+    return { files: [], fatal: `metaobjects.config.ts failed to load: ${err instanceof Error ? err.message : String(err)}` };
+  }
   const registry = composeRegistry([...defaultLoadMemoryProviders, ...providers]);
 
   let targets: readonly string[];
diff --git a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts
index 848b1e4c30..606dc55fc7 100644
--- a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts
+++ b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts
@@ -309,6 +309,23 @@ export async function resolveGenCollection(
   }
 }
 
+/**
+ * The custom providers a project's `metaobjects.config.ts` contributes, for a command run
+ * from `startDir` (`fallback` = the collection's directory, as for `resolveGenConfigDir`).
+ *
+ * Absent config: `[]` (core vocabulary only). A config that EXISTS but fails to load
+ * THROWS, so the caller reports the real error instead of a downstream
+ * `ERR_UNKNOWN_SUBTYPE` that the config's own providers would have prevented.
+ */
+export async function loadProjectProviders(
+  startDir: string,
+  fallback: string,
+): Promise {
+  const dir = resolveGenConfigDir(startDir, fallback);
+  if (!existsSync(join(dir, CONFIG_FILE))) return [];
+  return loadMemoryOptionsFrom(await loadMetaobjectsConfig(dir)).providers ?? [];
+}
+
 /**
  * A `metaobjects.config.ts` that still sets column naming (ADR-0058). Its own class because
  * the commands that tolerate a missing or broken config (`meta migrate` falls back to
diff --git a/server/typescript/packages/cli/test/config-providers-everywhere.test.ts b/server/typescript/packages/cli/test/config-providers-everywhere.test.ts
new file mode 100644
index 0000000000..2901644e86
--- /dev/null
+++ b/server/typescript/packages/cli/test/config-providers-everywhere.test.ts
@@ -0,0 +1,203 @@
+import { describe, test, expect, afterAll, spyOn } from "bun:test";
+import { mkdtemp, rm, mkdir, writeFile, readFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { exportCommand } from "../src/commands/export.js";
+import { typesCommand } from "../src/commands/types.js";
+import { verifyCommand } from "../src/commands/verify.js";
+import { runFmt } from "../src/lib/fmt-engine.js";
+import { proveDependencySetLoads } from "../src/lib/dependency-load.js";
+
+// A project's own `metaobjects.config.ts` providers must reach EVERY command that loads
+// metadata, not just gen/migrate. The vocabulary mirrors the shared conformance fixture
+// `provider-custom-vocabulary-success`: a new subtype (`layout.picker @displayField`) and
+// two attrs added to `field.string` (`@searchable`, `@valueLabels`).
+
+const dirs: string[] = [];
+afterAll(async () => {
+  for (const d of dirs) await rm(d, { recursive: true, force: true });
+});
+
+const PROVIDER_SRC = [
+  `import { TypeId, MetaLayout } from "@metaobjectsdev/metadata";`,
+  `import { TYPE_FIELD, TYPE_LAYOUT, FIELD_SUBTYPE_STRING, ATTR_SUBTYPE_STRING, ATTR_SUBTYPE_BOOLEAN } from "@metaobjectsdev/metadata/constants";`,
+  `const vocab = {`,
+  `  id: "test-custom-vocabulary",`,
+  `  dependencies: ["metaobjects-core-types"],`,
+  `  registerTypes(registry) {`,
+  `    registry.register({`,
+  `      typeId: new TypeId(TYPE_LAYOUT, "picker"),`,
+  `      description: "A picker over the owning object.",`,
+  `      factory: (typeId, name) => new MetaLayout(typeId, name),`,
+  `      childRules: [],`,
+  `      attributes: [{ name: "displayField", valueType: ATTR_SUBTYPE_STRING, required: false, description: "Field shown per choice." }],`,
+  `    });`,
+  `    registry.extend(TYPE_FIELD, FIELD_SUBTYPE_STRING, {`,
+  `      attributes: [`,
+  `        { name: "searchable", valueType: ATTR_SUBTYPE_BOOLEAN, required: false, description: "Offer in search." },`,
+  `        { name: "valueLabels", valueType: ATTR_SUBTYPE_STRING, isArray: true, required: false, description: "Display labels." },`,
+  `      ],`,
+  `    });`,
+  `  },`,
+  `};`,
+].join("\n");
+
+const GOOD_CONFIG = [
+  `import { defineConfig } from "@metaobjectsdev/codegen-ts";`,
+  PROVIDER_SRC,
+  `export default defineConfig({ outDir: "out", dialect: "postgres", generators: [], providers: [vocab] });`,
+].join("\n");
+
+const BROKEN_CONFIG = `export default (() => { throw new Error("boom-from-config"); })();\n`;
+
+const META = JSON.stringify({
+  "metadata.root": {
+    package: "examples",
+    children: [
+      {
+        "object.value": {
+          name: "Contact",
+          children: [
+            { "field.string": { name: "name", "@searchable": true } },
+            { "field.string": { name: "status", "@valueLabels": ["Active", "On hold"] } },
+            { "layout.picker": { name: "contactPicker", "@displayField": "name" } },
+          ],
+        },
+      },
+    ],
+  },
+});
+
+async function project(config: string | undefined): Promise {
+  const root = await mkdtemp(join(tmpdir(), "mts-cfgprov-"));
+  dirs.push(root);
+  await mkdir(join(root, "metaobjects"), { recursive: true });
+  await writeFile(join(root, "metaobjects", "meta.app.json"), META, "utf8");
+  if (config !== undefined) await writeFile(join(root, "metaobjects.config.ts"), config, "utf8");
+  return root;
+}
+
+async function captured(fn: () => Promise): Promise<{ result: T; err: string; out: string }> {
+  const errs: string[] = [];
+  const outs: string[] = [];
+  const e = spyOn(console, "error").mockImplementation((...a: unknown[]) => { errs.push(a.map(String).join(" ")); });
+  const l = spyOn(console, "log").mockImplementation((...a: unknown[]) => { outs.push(a.map(String).join(" ")); });
+  try {
+    return { result: await fn(), err: errs.join("\n"), out: outs.join("\n") };
+  } finally {
+    e.mockRestore();
+    l.mockRestore();
+  }
+}
+
+describe("config providers reach every metadata-loading command", () => {
+  test("export loads custom vocabulary; without the provider it is refused", async () => {
+    const root = await project(GOOD_CONFIG);
+    const out = join(root, "export.json");
+    const { result } = await captured(() => exportCommand(["--out", out], root));
+    expect(result).toBe(0);
+    expect(await readFile(out, "utf8")).toContain("layout.picker");
+
+    const bare = await project(undefined);
+    const { result: bareCode } = await captured(() => exportCommand(["--out", join(bare, "x.json")], bare));
+    expect(bareCode).toBe(1);
+  });
+
+  test("export accepts a config that opts into forge vocabulary itself", async () => {
+    const config = [
+      `import { defineConfig } from "@metaobjectsdev/codegen-ts";`,
+      `import { forgeTypesProvider } from ${JSON.stringify(join(import.meta.dir, "..", "..", "sdk", "src", "index.ts"))};`,
+      PROVIDER_SRC,
+      `export default defineConfig({ outDir: "out", dialect: "postgres", generators: [], providers: [forgeTypesProvider, vocab] });`,
+    ].join("\n");
+    const root = await project(config);
+    const out = join(root, "export.json");
+    const { result, err } = await captured(() => exportCommand(["--out", out], root));
+    expect(err).not.toContain("ERR_PROVIDER_DUPLICATE_ID");
+    expect(result).toBe(0);
+    expect(await readFile(out, "utf8")).toContain("layout.picker");
+  });
+
+  test("export surfaces a broken config as itself", async () => {
+    const root = await project(BROKEN_CONFIG);
+    const { result, err } = await captured(() => exportCommand([], root));
+    expect(result).toBe(1);
+    expect(err).toContain("boom-from-config");
+  });
+
+  test("meta deps proof loads the full set with the provider (not 'port-only vocabulary')", async () => {
+    const root = await project(GOOD_CONFIG);
+    expect((await proveDependencySetLoads(root)).scope).toBe("full");
+  });
+
+  test("meta fmt finds the config in an ancestor of the collection and in-place", async () => {
+    const root = await project(GOOD_CONFIG);
+    const r = await runFmt({ projectRoot: root, check: true });
+    expect(r.fatal).toBeUndefined();
+    expect(r.files.every((f) => f.status !== "error")).toBe(true);
+  });
+
+  test("meta fmt run from a sub-project reads that sub-project's config, not the collection's", async () => {
+    // The collection (.metaobjects/config.json + metadata) sits at the repo root; the
+    // TypeScript config sits in a package below it. Reading the config from the
+    // collection's directory (the old behaviour) never saw it.
+    const root = await project(undefined);
+    await mkdir(join(root, ".git"), { recursive: true });
+    await mkdir(join(root, ".metaobjects"), { recursive: true });
+    await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1 }), "utf8");
+    const app = join(root, "app");
+    await mkdir(app, { recursive: true });
+    await writeFile(join(app, "metaobjects.config.ts"), GOOD_CONFIG, "utf8");
+    const r = await runFmt({ projectRoot: app, check: true });
+    expect(r.fatal).toBeUndefined();
+    expect(r.files.length).toBeGreaterThan(0);
+    expect(r.files.every((f) => f.status !== "error")).toBe(true);
+  });
+
+  test("meta fmt reports a broken config instead of dropping providers", async () => {
+    const root = await project(BROKEN_CONFIG);
+    const r = await runFmt({ projectRoot: root, check: true });
+    expect(r.fatal).toContain("boom-from-config");
+  });
+
+  test("meta types lists project vocabulary when a config is present", async () => {
+    const root = await project(GOOD_CONFIG);
+    const prev = process.cwd();
+    process.chdir(root);
+    try {
+      const { result, out } = await captured(() => typesCommand(["layout.picker"]));
+      expect(result).toBe(0);
+      expect(out).toContain("layout.picker");
+      const attrs = await captured(() => typesCommand(["searchable"]));
+      expect(attrs.out).toContain("searchable");
+    } finally {
+      process.chdir(prev);
+    }
+  });
+
+  test("meta types is unchanged with no config", async () => {
+    const root = await project(undefined);
+    const prev = process.cwd();
+    process.chdir(root);
+    try {
+      const { out } = await captured(() => typesCommand(["layout.picker"]));
+      expect(out).not.toContain("layout.picker  ");
+      expect(out.toLowerCase()).toContain("no vocabulary matches");
+    } finally {
+      process.chdir(prev);
+    }
+  });
+
+  test("strict verify passes custom vocabulary with the provider and surfaces a broken config", async () => {
+    const root = await project(GOOD_CONFIG);
+    const ok = await captured(() => verifyCommand(["--templates"], root));
+    expect(ok.err).not.toContain("ERR_UNKNOWN");
+    expect(ok.result).toBe(0);
+
+    const broken = await project(BROKEN_CONFIG);
+    const bad = await captured(() => verifyCommand(["--templates"], broken));
+    expect(bad.result).toBe(2);
+    expect(bad.err).toContain("boom-from-config");
+    expect(bad.err).not.toContain("ERR_UNKNOWN_SUBTYPE");
+  });
+});
diff --git a/server/typescript/packages/metadata/test/conformance/adapter.ts b/server/typescript/packages/metadata/test/conformance/adapter.ts
index b5f1bdc4a8..77991fbe4e 100644
--- a/server/typescript/packages/metadata/test/conformance/adapter.ts
+++ b/server/typescript/packages/metadata/test/conformance/adapter.ts
@@ -26,9 +26,11 @@ import { canonicalSerialize, canonicalSerializeEffective } from "../../src/seria
 import { ParseError } from "../../src/errors.js";
 import { TypeId } from "../../src/registry.js";
 import { MetaTemplate } from "../../src/template/meta-template.js";
-import { TYPE_TEMPLATE, TYPE_ATTR } from "../../src/shared/base-types.js";
+import { TYPE_TEMPLATE, TYPE_ATTR, TYPE_FIELD, TYPE_LAYOUT } from "../../src/shared/base-types.js";
 import { CHILD_RULE_WILDCARD } from "../../src/shared/structural.js";
-import { ATTR_SUBTYPE_STRING } from "../../src/core/attr/attr-constants.js";
+import { ATTR_SUBTYPE_BOOLEAN, ATTR_SUBTYPE_STRING } from "../../src/core/attr/attr-constants.js";
+import { MetaLayout } from "../../src/presentation/layout/meta-layout.js";
+import { FIELD_SUBTYPE_STRING } from "../../src/core/field/field-constants.js";
 import { navigate } from "./navigator.js";
 import { binding } from "./binding.js";
 
@@ -76,6 +78,37 @@ const exampleTemplateBriefingProvider: MetaDataTypeProvider = {
   },
 };
 
+/**
+ * The project-vocabulary case (provider-custom-vocabulary-* fixtures): a
+ * downstream project's own provider that REGISTERS one new subtype
+ * (`layout.picker`, carrying its own `@displayField`) and EXTENDS an existing
+ * type (`field.string`) with two optional attrs (`@searchable`,
+ * `@valueLabels`). Every port carries the same provider, written in its own
+ * language, so the same metadata loads clean with it and is refused without it.
+ */
+const exampleCustomVocabularyProvider: MetaDataTypeProvider = {
+  id: "example-custom-vocabulary",
+  dependencies: ["metaobjects-core-types"],
+  description: "Test-only — a project's own vocabulary: layout.picker + field.string attrs.",
+  registerTypes(registry) {
+    registry.register({
+      typeId: new TypeId(TYPE_LAYOUT, "picker"),
+      description: "A picker that chooses one row of the owning object — test-only.",
+      factory: (typeId, name) => new MetaLayout(typeId, name),
+      childRules: [],
+      attributes: [
+        { name: "displayField", valueType: ATTR_SUBTYPE_STRING, required: false, description: "Field shown for each choice." },
+      ],
+    });
+    registry.extend(TYPE_FIELD, FIELD_SUBTYPE_STRING, {
+      attributes: [
+        { name: "searchable", valueType: ATTR_SUBTYPE_BOOLEAN, required: false, description: "Offer this field in search." },
+        { name: "valueLabels", valueType: ATTR_SUBTYPE_STRING, isArray: true, required: false, description: "Display labels for the field's values." },
+      ],
+    });
+  },
+};
+
 /** Two providers that name each other as a dependency — surfaces ERR_PROVIDER_DEPENDENCY_CYCLE. */
 const cycleAProvider: MetaDataTypeProvider = {
   id: "cycle-a",
@@ -126,6 +159,7 @@ export const PROVIDERS: Readonly> = {
   [uiProvider.id]: uiProvider,               // "metaobjects-ui" (filter/sort field markers)
   // Test-only — provider-extension-* fixtures.
   "example-template-briefing": exampleTemplateBriefingProvider,
+  "example-custom-vocabulary": exampleCustomVocabularyProvider,
   "cycle-a": cycleAProvider,
   "cycle-b": cycleBProvider,
   "depends-on-missing": dependsOnMissingProvider,
diff --git a/server/typescript/packages/sdk/src/config.ts b/server/typescript/packages/sdk/src/config.ts
index 40d127843d..ae2e385592 100644
--- a/server/typescript/packages/sdk/src/config.ts
+++ b/server/typescript/packages/sdk/src/config.ts
@@ -239,6 +239,16 @@ export const ConfigSchema = z.object({
   csharp: z.strictObject({
     outDir: z.string().min(1).optional(),
     namespace: z.string().min(1).optional(),
+    /**
+     * The project's own metadata providers: each names a BUILT .NET assembly (a path relative
+     * to the directory holding `.metaobjects/`) and the provider's full type name. Only the C#
+     * port reads this; the TypeScript port validates it so the shared file loads, and takes
+     * its providers from `defineConfig({ providers })` in `metaobjects.config.ts` instead.
+     */
+    providers: z.array(z.strictObject({
+      assembly: z.string().min(1),
+      type: z.string().min(1),
+    })).optional(),
   }).optional(),
 }).strict();
 
diff --git a/server/typescript/packages/sdk/test/config.test.ts b/server/typescript/packages/sdk/test/config.test.ts
index 2464517e85..0d964d4531 100644
--- a/server/typescript/packages/sdk/test/config.test.ts
+++ b/server/typescript/packages/sdk/test/config.test.ts
@@ -284,3 +284,19 @@ describe("csharp.outDir (the C# port's generated-code directory)", () => {
     expect(ConfigSchema.safeParse({ schema_version: 1, csharp: { outDir: "" } }).success).toBe(false);
   });
 });
+
+describe("csharp.providers (read by the C# port only)", () => {
+  test("a config carrying provider assemblies validates", () => {
+    const ok = ConfigSchema.safeParse({
+      schema_version: 1,
+      csharp: { providers: [{ assembly: "bin/Debug/net8.0/Acme.Vocabulary.dll", type: "Acme.Vocabulary.AcmeProvider" }] },
+    });
+    expect(ok.success).toBe(true);
+  });
+  test("rejects an empty field, a missing field, and an unknown key", () => {
+    const bad = (p: unknown) => ConfigSchema.safeParse({ schema_version: 1, csharp: { providers: p } }).success;
+    expect(bad([{ assembly: "", type: "A.B" }])).toBe(false);
+    expect(bad([{ assembly: "a.dll" }])).toBe(false);
+    expect(bad([{ assembly: "a.dll", type: "A.B", extra: 1 }])).toBe(false);
+  });
+});

From b7a031a9c38c5b373bb1b6c9f1a6b2f3e952f10f Mon Sep 17 00:00:00 2001
From: Doug Mealing 
Date: Wed, 4 Nov 2026 08:24:06 -0500
Subject: [PATCH 06/51] fix: cross-field comparison rule across ports and C#
 concrete-parent properties (#531)

* fix(csharp-codegen): an extending entity carries its parent's properties; fix test timing flakes

A C# entity that extends another skipped the inherited fields but its class
declaration never named the base, so the parent's properties appeared nowhere.
A concrete parent is flattened onto the child (each concrete entity owns a table
with all its columns; class inheritance between mapped entities would be an EF
TPH/TPT hierarchy). An emitted abstract shape is named as the base.

Flakes fixed at the cause: DependencyCliTests changed the process-wide cwd outside
the serial collection, racing GenCommandTests; codegen-ts compile tests run under
a 30s timeout set in one helper instead of bun's 5s default.

* fix(codegen): skip cross-kind cross-field comparisons in every port; executed Patch check; TPH form rule test

A validator.comparison between fields of different kinds (e.g. date vs timestamp) is now
skipped in Java, Kotlin, TypeScript and Python as C# already did, instead of a 500
(ClassCastException), a string compare, or a TypeError. Adds the shared
comparison-across-kinds-is-skipped conformance case, replaces the Java Patch source-text
comparison with an executed check, and adds a TPH subtype form test for a cross-field rule.

* fix(codegen): eq/ne between same-subtype uuid, uri and inet fields stays enforced; review fixes

Code review of the cross-kind skip found that equality on identifier-like fields was dropped
along with ordering. Restores it in every port, adds shared uuid cases, corrects stale C#
comments, and documents the EmitClassDeclarationLine seam change.

* chore: simplify pass; sync owned template copies; C# date eq no longer rejects across kinds

* no-mistakes(review): Per-file compile timeout; @localTime temporals skip cross-field comparison

* no-mistakes(review): Apply compile timeout to tph-cross-field test

* no-mistakes(review): Skip C# eq/ne across differing CLR types

* no-mistakes(document): Updated entities.md cross-field section for kind-based comparison rule; one follow-up left.

* no-mistakes(document): Document comparison kind rule in authoring skill

* fix(codegen-kotlin): cross-field rules no longer depend on KotlinTypeMapper

An ejected copy of KotlinCrossFieldRules compiles standalone, so it cannot
reference KotlinTypeMapper. Decide the native shape from @localTime and
@lenient directly.
---
 CHANGELOG.md                                  |  40 +++++++
 .../skills/metaobjects-authoring/SKILL.md     |   2 +-
 .../metaobjects-codegen/references/csharp.md  |   4 +-
 docs/features/entities.md                     |   7 ++
 .../codegen/templates/zod-validators.ts       |  28 ++++-
 .../codegen/templates/zod-validators.ts       |  28 ++++-
 .../skills/metaobjects-authoring/SKILL.md     |   2 +-
 .../skills/metaobjects-authoring/SKILL.md     |   2 +-
 .../skills/metaobjects-authoring/SKILL.md     |   2 +-
 .../skills/metaobjects-authoring/SKILL.md     |   2 +-
 .../skills/metaobjects-authoring/SKILL.md     |   2 +-
 fixtures/validation-conformance/README.md     |  14 ++-
 .../cross-field-cases.json                    |  60 ++++++++++
 .../meta.cross-field.json                     |   9 ++
 .../DependencyCliTests.cs                     |   6 +
 .../CrossFieldValidationConformanceTests.cs   |   2 +-
 .../CrossFieldValidatorGenerationTests.cs     |  97 +++++++++++------
 .../EntityExtendsParentTests.cs               | 103 ++++++++++++++++++
 .../Generators/EntityGenerator.cs             |  72 ++++++------
 .../generator/kotlin/KotlinCrossFieldRules.kt |  58 +++++++++-
 .../kotlin/ValidationConformanceTest.kt       |   2 +-
 server/java/codegen-spring/pom.xml            |   9 ++
 .../spring/SpringGeneratorSupport.java        |  44 +++++++-
 .../SpringCrossFieldValidationTest.java       |  22 +++-
 .../spring/ValidationConformanceTest.java     |   2 +-
 .../codegen/generators/entity_model.py        |  36 +++++-
 .../codegen-ts-react/test/tph-form.test.ts    |  24 +++-
 .../src/templates/zod-validators.ts           |  28 ++++-
 .../test/array-default-compile.test.ts        |   5 +-
 .../test/assigned-pk-insert-compile.test.ts   |   5 +-
 .../test/codegen-compile-conformance.test.ts  |   5 +-
 .../codegen-ts/test/compile-timeout.ts        |  21 ++++
 .../test/db-schema-generic-compile.test.ts    |   5 +-
 ...ct-optional-property-types-compile.test.ts |   5 +-
 .../codegen-ts/test/extractor-codegen.test.ts |   5 +-
 .../test/filter-type-enum-compile.test.ts     |   5 +-
 .../codegen-ts/test/fr004-verify-demo.test.ts |   5 +-
 .../golden/api-docs-relative-imports.test.ts  |   5 +-
 .../extractor-render-payload-imports.test.ts  |   5 +-
 .../test/jsonb-vo-read-typed-compile.test.ts  |   5 +-
 .../test/names-extends-chain.test.ts          |   5 +-
 .../test/names-reference-compile.test.ts      |   5 +-
 .../test/nodenext-safe-imports.test.ts        |   5 +-
 .../test/owned-composition-imports.test.ts    |   5 +-
 .../test/owned-generator-skew-compile.test.ts |   5 +-
 .../test/projection/compile.test.ts           |   5 +-
 .../int-enum-replica-view-no-dup.test.ts      |   5 +-
 .../projection/int-enum-view-compile.test.ts  |   5 +-
 .../issue-214-read-half-compile.test.ts       |   5 +-
 .../test/reference-binding-compile.test.ts    |   5 +-
 .../test/reference-byte-identical.test.ts     |   5 +-
 .../test/sourceless-entity-surface.test.ts    |   5 +-
 .../test/templates/names-consumption.test.ts  |   5 +-
 .../codegen-ts/test/tph-cross-field.test.ts   |   5 +-
 .../test/tph-read-schema-default.test.ts      |   5 +-
 .../test/tph-reference-target.test.ts         |   5 +-
 .../test/typed-create-compile.test.ts         |   5 +-
 .../verbatim-module-syntax-compile.test.ts    |   5 +-
 .../src/templates/zod-validators.ts           |  28 ++++-
 59 files changed, 761 insertions(+), 140 deletions(-)
 create mode 100644 server/csharp/MetaObjects.Codegen.Tests/EntityExtendsParentTests.cs
 create mode 100644 server/typescript/packages/codegen-ts/test/compile-timeout.ts

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 579ec52514..9d09f79179 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -48,6 +48,46 @@ here.**
   column, instead of suggesting a `@column` they already have. The error code is unchanged. New
   conformance fixtures: `column-name-shared-in-sql-view-ok`, `error-column-name-collision-derived-view` and
   `error-column-name-collision-table-with-sql-view`.
+- **C# codegen: an entity that extends another no longer loses the parent's properties.** The member
+  loop skipped every inherited field but the class declaration never named the base, so the fields
+  appeared nowhere. A child of a **concrete** parent now declares the parent's properties itself and
+  names no base: each concrete entity owns a table with all its columns (what `meta migrate` creates
+  and the other ports' models carry), and `class Child : Parent` between two mapped entities is an EF
+  inheritance hierarchy (one shared table, or a child table holding only its own columns). A child of
+  an **abstract** parent with `EmitAbstractShapes` on now emits `class Child : Base`, as the
+  generator always meant to, and declares only its own members. Regenerating changes those two shapes
+  of C# output only. An adopter override of `EmitClassDeclarationLine` that names a concrete parent as
+  the base now gets that parent's properties twice; drop the base from the override.
+- **Test flakes fixed at their cause.** `GenCommandTests.Gen_writes_the_hash_manifest_beside_the_metadata_not_in_cwd`
+  (C# Cli) failed about one run in five because `DependencyCliTests` runs `gen` in process, which
+  changes the process-wide working directory, without joining the serial collection every other
+  such class is in; the two classes ran in parallel and one read the other's directory as the cwd.
+  The codegen-ts tests that type-check generated output with the real TypeScript compiler (28 files,
+  the slowest case measured at 3.3s against bun's 5s default) now run under a 30s timeout whose value
+  lives in one place, `test/compile-timeout.ts`. Each of those files calls `setDefaultTimeout` with
+  it, because bun applies that call only to the file that makes it, so the timeout holds in a plain
+  `bun test` as well as in CI, and a loaded machine no longer reports a timeout for correct code.
+- **A cross-field `validator.comparison` between fields of different kinds is skipped in every
+  port, never rejected and never a 500.** Comparing a `field.date` with a `field.timestamp` (or any
+  two strings or temporals of different subtype) has no ordering. Java and Kotlin cast both sides
+  to `Comparable` inside the class-level validity check, so the cast threw `ClassCastException` and
+  a create answered 500 instead of 400; TypeScript compared the two as strings and Python raised a
+  `TypeError` that surfaced as an invalid body. All five ports now follow one rule: numerics compare
+  with each other, strings and temporals only with their own subtype and `@localTime` flag (a
+  `field.timestamp` is an instant and a `@localTime` one a wall clock, which is a different native
+  type in every port), boolean and enum fields test
+  `eq` / `ne` only (also on two `uuid`, `uri` or `inet` fields), and any other pair emits no rule, so an
+  ordering test on two booleans or two enums is no longer enforced by the generated validators (C# never
+  did). The database `CHECK` still covers the pair where the database can compare it. New shared cases
+  `comparison-across-kinds-is-skipped`, `comparison-instant-vs-local-timestamp-is-skipped`,
+  `uuid-ne-rejects-equal-ids` and `uuid-ne-accepts-different-ids`
+  in `fixtures/validation-conformance/`, run by every port.
+- **Test coverage for cross-field validators.** A subtype form on a TPH hierarchy that declares a
+  cross-field rule now has a test proving the generated form binds the refined body schema (the rule
+  itself was enforced by the cross-field build). The Java check that a Patch is not held to cross-field
+  validators now runs the generated classes (the violating body is rejected by the Dto and accepted
+  by the Patch) instead of comparing generated source text.
+
 - **`meta migrate` refuses, at plan time, to drop a column a view it does not own still reads.**
   With `--from-db`, a declared-`@unmanaged` view or one outside the scoped schemas whose live body
   names the dropped column now blocks the `drop-column`, and the message names the view and the
diff --git a/agent-context/skills/metaobjects-authoring/SKILL.md b/agent-context/skills/metaobjects-authoring/SKILL.md
index a1a3fe6c0b..01fb198e0d 100644
--- a/agent-context/skills/metaobjects-authoring/SKILL.md
+++ b/agent-context/skills/metaobjects-authoring/SKILL.md
@@ -434,7 +434,7 @@ store with no `CHECK` support is still covered. PATCH and partial-update models
 
 | Subtype | Rule | Key attrs |
 |---|---|---|
-| `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
+| `validator.comparison` | two fields stand in a relational order (`@left @op @right`). Numerics compare with each other; strings and temporals only with the same subtype and `@localTime`; boolean, enum, uuid, uri and inet only `eq`/`ne`. Any other pair is skipped, never rejected. | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
 | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` |
 | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` |
 | `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` |
diff --git a/agent-context/skills/metaobjects-codegen/references/csharp.md b/agent-context/skills/metaobjects-codegen/references/csharp.md
index e2a5371bb5..d86cf4cea2 100644
--- a/agent-context/skills/metaobjects-codegen/references/csharp.md
+++ b/agent-context/skills/metaobjects-codegen/references/csharp.md
@@ -307,7 +307,9 @@ plus finer hooks — `EmitClassHeader` / `EmitClassDeclarationLine` (class decla
 `partial`, marker interfaces), `EmitPropertyAttributes` (per-property C# attributes),
 `EmitFileUsings` (extra usings), `EmitClassBodyTrailer` (extra members). Subclass a
 generator and override only the seam you need rather than forking. `@default` on a
-scalar emits a literal initializer; an `object.value`'s default storage is jsonb.
+scalar emits a literal initializer; an override of `EmitClassDeclarationLine` must not name a
+concrete parent as the C# base (the child already declares the parent's properties, so a base would
+redeclare them; only an emitted abstract shape is a base); an `object.value`'s default storage is jsonb.
 
 **Shared + externally-provided enums (FR-019).** A package-level abstract
 `field.enum` (`abstract: true`, `@values`) extended by concrete entity fields is
diff --git a/docs/features/entities.md b/docs/features/entities.md
index 5247997235..d0f0d2f728 100644
--- a/docs/features/entities.md
+++ b/docs/features/entities.md
@@ -338,6 +338,13 @@ side is null; `requiredWhen` is violated only when the gate equals `@equals` and
 needs one non-null field. `@equals` is read per the gating field's subtype. The shared cases in
 `fixtures/validation-conformance/cross-field-cases.json` gate all five ports.
 
+One difference: a `comparison` orders only fields of the same kind. Numerics compare with each other;
+strings and temporals compare only with their own subtype and `@localTime` flag. `eq` and `ne` also
+apply to two booleans, enums, `uuid`, `uri` or `inet` fields, and ordering on a boolean or enum is not
+enforced. Any other pair is skipped in the generated model, never rejected, but the DB `CHECK` still
+covers it where the database can compare the two columns. The full rule is in
+`fixtures/validation-conformance/README.md`.
+
 PATCH and partial-update models do **not** enforce these rules, because a partial body cannot see
 the merged row. The database `CHECK` is the enforcement there.
 
diff --git a/examples/advanced-modeling/codegen/templates/zod-validators.ts b/examples/advanced-modeling/codegen/templates/zod-validators.ts
index 661966d8ea..917a215da5 100644
--- a/examples/advanced-modeling/codegen/templates/zod-validators.ts
+++ b/examples/advanced-modeling/codegen/templates/zod-validators.ts
@@ -16,8 +16,7 @@ import {
   FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_CURRENCY,
   FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DECIMAL, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT,
   FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP,
-  FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_UUID,
-  FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
+  FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
   VALIDATOR_SUBTYPE_REQUIRED, VALIDATOR_SUBTYPE_LENGTH, VALIDATOR_SUBTYPE_REGEX,
   VALIDATOR_SUBTYPE_NUMERIC, VALIDATOR_SUBTYPE_ARRAY,
   IDENTITY_ATTR_FIELDS, IDENTITY_ATTR_GENERATION,
@@ -278,6 +277,30 @@ const NUMERIC_SUBTYPES: ReadonlySet = new Set([
   FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY,
 ]);
 
+const ORDERED_SUBTYPES: ReadonlySet = new Set([
+  FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP,
+]);
+
+/** Subtypes with equality but no ordering: a pair of the same one may be tested with eq / ne. */
+const EQUALITY_SUBTYPES: ReadonlySet = new Set([
+  FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
+]);
+
+/** Whether a comparison between these two fields has a sound meaning, as in every port:
+ *  numerics compare with each other, strings and temporals only with their own subtype and
+ *  @localTime flag (a date against a timestamp, or an instant against a wall clock, compares
+ *  two differently shaped strings, which is meaningless),
+ *  and boolean, enum, uuid, uri and inet fields only test equality. Anything else is skipped, never rejected. */
+function crossComparable(left: MetaField, right: MetaField, opName: string): boolean {
+  const a = left.subType;
+  const b = right.subType;
+  if (NUMERIC_SUBTYPES.has(a) && NUMERIC_SUBTYPES.has(b)) return true;
+  if (a !== b) return false;
+  if ((left.attr(FIELD_ATTR_LOCAL_TIME) === true) !== (right.attr(FIELD_ATTR_LOCAL_TIME) === true)) return false;
+  if (ORDERED_SUBTYPES.has(a)) return true;
+  return (opName === "eq" || opName === "ne") && EQUALITY_SUBTYPES.has(a);
+}
+
 /** Names of the fields the INSERT-shaped schemas carry (same skip rules as the emitters). */
 function insertSchemaFieldNameSet(obj: MetaObject): Set {
   const autoGen = autoGenPkFieldNames(obj);
@@ -337,6 +360,7 @@ function crossFieldRefinementBody(obj: MetaObject): string[] {
         const opName = String(v.attr(VALIDATOR_ATTR_OP));
         const op = CROSS_FIELD_OPS[opName];
         if (!left || !right || !op || left.resolvedIsArray() || right.resolvedIsArray()) break;
+        if (!crossComparable(left, right, opName)) break;
         const numeric = NUMERIC_SUBTYPES.has(left.subType);
         const c = numeric
           ? "Number(l) - Number(r)"
diff --git a/examples/showcase/codegen/templates/zod-validators.ts b/examples/showcase/codegen/templates/zod-validators.ts
index 661966d8ea..917a215da5 100644
--- a/examples/showcase/codegen/templates/zod-validators.ts
+++ b/examples/showcase/codegen/templates/zod-validators.ts
@@ -16,8 +16,7 @@ import {
   FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_CURRENCY,
   FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DECIMAL, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT,
   FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP,
-  FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_UUID,
-  FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
+  FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
   VALIDATOR_SUBTYPE_REQUIRED, VALIDATOR_SUBTYPE_LENGTH, VALIDATOR_SUBTYPE_REGEX,
   VALIDATOR_SUBTYPE_NUMERIC, VALIDATOR_SUBTYPE_ARRAY,
   IDENTITY_ATTR_FIELDS, IDENTITY_ATTR_GENERATION,
@@ -278,6 +277,30 @@ const NUMERIC_SUBTYPES: ReadonlySet = new Set([
   FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY,
 ]);
 
+const ORDERED_SUBTYPES: ReadonlySet = new Set([
+  FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP,
+]);
+
+/** Subtypes with equality but no ordering: a pair of the same one may be tested with eq / ne. */
+const EQUALITY_SUBTYPES: ReadonlySet = new Set([
+  FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
+]);
+
+/** Whether a comparison between these two fields has a sound meaning, as in every port:
+ *  numerics compare with each other, strings and temporals only with their own subtype and
+ *  @localTime flag (a date against a timestamp, or an instant against a wall clock, compares
+ *  two differently shaped strings, which is meaningless),
+ *  and boolean, enum, uuid, uri and inet fields only test equality. Anything else is skipped, never rejected. */
+function crossComparable(left: MetaField, right: MetaField, opName: string): boolean {
+  const a = left.subType;
+  const b = right.subType;
+  if (NUMERIC_SUBTYPES.has(a) && NUMERIC_SUBTYPES.has(b)) return true;
+  if (a !== b) return false;
+  if ((left.attr(FIELD_ATTR_LOCAL_TIME) === true) !== (right.attr(FIELD_ATTR_LOCAL_TIME) === true)) return false;
+  if (ORDERED_SUBTYPES.has(a)) return true;
+  return (opName === "eq" || opName === "ne") && EQUALITY_SUBTYPES.has(a);
+}
+
 /** Names of the fields the INSERT-shaped schemas carry (same skip rules as the emitters). */
 function insertSchemaFieldNameSet(obj: MetaObject): Set {
   const autoGen = autoGenPkFieldNames(obj);
@@ -337,6 +360,7 @@ function crossFieldRefinementBody(obj: MetaObject): string[] {
         const opName = String(v.attr(VALIDATOR_ATTR_OP));
         const op = CROSS_FIELD_OPS[opName];
         if (!left || !right || !op || left.resolvedIsArray() || right.resolvedIsArray()) break;
+        if (!crossComparable(left, right, opName)) break;
         const numeric = NUMERIC_SUBTYPES.has(left.subType);
         const c = numeric
           ? "Number(l) - Number(r)"
diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
index a1a3fe6c0b..01fb198e0d 100644
--- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
+++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
@@ -434,7 +434,7 @@ store with no `CHECK` support is still covered. PATCH and partial-update models
 
 | Subtype | Rule | Key attrs |
 |---|---|---|
-| `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
+| `validator.comparison` | two fields stand in a relational order (`@left @op @right`). Numerics compare with each other; strings and temporals only with the same subtype and `@localTime`; boolean, enum, uuid, uri and inet only `eq`/`ne`. Any other pair is skipped, never rejected. | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
 | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` |
 | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` |
 | `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` |
diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md
index a1a3fe6c0b..01fb198e0d 100644
--- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md
+++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md
@@ -434,7 +434,7 @@ store with no `CHECK` support is still covered. PATCH and partial-update models
 
 | Subtype | Rule | Key attrs |
 |---|---|---|
-| `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
+| `validator.comparison` | two fields stand in a relational order (`@left @op @right`). Numerics compare with each other; strings and temporals only with the same subtype and `@localTime`; boolean, enum, uuid, uri and inet only `eq`/`ne`. Any other pair is skipped, never rejected. | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
 | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` |
 | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` |
 | `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` |
diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md
index a1a3fe6c0b..01fb198e0d 100644
--- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md
+++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md
@@ -434,7 +434,7 @@ store with no `CHECK` support is still covered. PATCH and partial-update models
 
 | Subtype | Rule | Key attrs |
 |---|---|---|
-| `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
+| `validator.comparison` | two fields stand in a relational order (`@left @op @right`). Numerics compare with each other; strings and temporals only with the same subtype and `@localTime`; boolean, enum, uuid, uri and inet only `eq`/`ne`. Any other pair is skipped, never rejected. | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
 | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` |
 | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` |
 | `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` |
diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
index a1a3fe6c0b..01fb198e0d 100644
--- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
+++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
@@ -434,7 +434,7 @@ store with no `CHECK` support is still covered. PATCH and partial-update models
 
 | Subtype | Rule | Key attrs |
 |---|---|---|
-| `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
+| `validator.comparison` | two fields stand in a relational order (`@left @op @right`). Numerics compare with each other; strings and temporals only with the same subtype and `@localTime`; boolean, enum, uuid, uri and inet only `eq`/`ne`. Any other pair is skipped, never rejected. | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
 | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` |
 | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` |
 | `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` |
diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md
index a1a3fe6c0b..01fb198e0d 100644
--- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md
+++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md
@@ -434,7 +434,7 @@ store with no `CHECK` support is still covered. PATCH and partial-update models
 
 | Subtype | Rule | Key attrs |
 |---|---|---|
-| `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
+| `validator.comparison` | two fields stand in a relational order (`@left @op @right`). Numerics compare with each other; strings and temporals only with the same subtype and `@localTime`; boolean, enum, uuid, uri and inet only `eq`/`ne`. Any other pair is skipped, never rejected. | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` |
 | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` |
 | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` |
 | `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` |
diff --git a/fixtures/validation-conformance/README.md b/fixtures/validation-conformance/README.md
index b6fc8ca33e..0382d6982d 100644
--- a/fixtures/validation-conformance/README.md
+++ b/fixtures/validation-conformance/README.md
@@ -120,9 +120,17 @@ so the run-time runners, which read `cases.json`, are unaffected. The entity is
 is optional, so absence is expressible in every port.
 
 The semantics mirror the DB `CHECK` derivation in `migrate-ts/src/expected-schema.ts`, with an absent
-or null value standing for SQL `NULL` (and `""` NOT null):
-
-- `comparison` (`startsAt lte endsAt`): passes when either side is null.
+or null value standing for SQL `NULL` (and `""` NOT null). One deliberate difference: a comparison the
+ports skip (two fields of different kinds) still gets its `CHECK`, which the database enforces if it
+can compare the two column types:
+
+- `comparison` (`startsAt lte endsAt`): passes when either side is null. Fields of different kinds
+  have no ordering and the rule is SKIPPED in every port, never an error (`eventDate lte loggedAt`, a
+  date against a timestamp, is declared on `Event` and must accept a body where the date is later). Two temporals of
+  the same subtype are still different kinds when only one carries `@localTime` (`loggedAt lte wallClock`, an
+  instant against a wall clock, is skipped the same way). Ordering applies to numerics with each other and to
+  strings and temporals of the same subtype; `eq` / `ne` also apply to two fields of the same boolean,
+  enum, uuid, uri or inet subtype (`ownerId ne approverId` rejects two equal ids).
 - `requiredWhen`: violated only when the gating field equals `@equals` and the target is null; a null
   gate is unconstrained. Both a string gate (`kind = BIRTH`) and a boolean gate (`flag = true`).
 - `presentIff`: the target is present exactly when the gate equals `@equals`; a null gate counts as
diff --git a/fixtures/validation-conformance/cross-field-cases.json b/fixtures/validation-conformance/cross-field-cases.json
index 57949d652f..dae54a0eef 100644
--- a/fixtures/validation-conformance/cross-field-cases.json
+++ b/fixtures/validation-conformance/cross-field-cases.json
@@ -258,6 +258,66 @@
         "review": "DONE"
       },
       "expectValid": true
+    },
+    {
+      "name": "comparison-across-kinds-is-skipped",
+      "entity": "Event",
+      "payload": {
+        "startsAt": 1,
+        "endsAt": 2,
+        "kind": "BIRTH",
+        "subject": "p1",
+        "state": "OPEN",
+        "email": "a@b.c",
+        "eventDate": "2030-01-02",
+        "loggedAt": "2020-01-01T00:00:00Z"
+      },
+      "expectValid": true
+    },
+    {
+      "name": "comparison-instant-vs-local-timestamp-is-skipped",
+      "entity": "Event",
+      "payload": {
+        "startsAt": 1,
+        "endsAt": 2,
+        "kind": "BIRTH",
+        "subject": "p1",
+        "state": "OPEN",
+        "email": "a@b.c",
+        "loggedAt": "2030-01-02T00:00:00Z",
+        "wallClock": "2020-01-01T00:00:00"
+      },
+      "expectValid": true
+    },
+    {
+      "name": "uuid-ne-rejects-equal-ids",
+      "entity": "Event",
+      "payload": {
+        "startsAt": 1,
+        "endsAt": 2,
+        "kind": "BIRTH",
+        "subject": "p1",
+        "state": "OPEN",
+        "email": "a@b.c",
+        "ownerId": "3f2b1c1e-8a64-4d0e-9a52-1f6c0d2b7a10",
+        "approverId": "3f2b1c1e-8a64-4d0e-9a52-1f6c0d2b7a10"
+      },
+      "expectValid": false
+    },
+    {
+      "name": "uuid-ne-accepts-different-ids",
+      "entity": "Event",
+      "payload": {
+        "startsAt": 1,
+        "endsAt": 2,
+        "kind": "BIRTH",
+        "subject": "p1",
+        "state": "OPEN",
+        "email": "a@b.c",
+        "ownerId": "3f2b1c1e-8a64-4d0e-9a52-1f6c0d2b7a10",
+        "approverId": "9b7d4e22-0c1a-4f3b-8d65-2a7e9c5f1b34"
+      },
+      "expectValid": true
     }
   ]
 }
diff --git a/fixtures/validation-conformance/meta.cross-field.json b/fixtures/validation-conformance/meta.cross-field.json
index c2e4b65c98..a47faea675 100644
--- a/fixtures/validation-conformance/meta.cross-field.json
+++ b/fixtures/validation-conformance/meta.cross-field.json
@@ -15,6 +15,11 @@
           { "field.string":     { "name": "closedNote" } },
           { "field.boolean":    { "name": "flag" } },
           { "field.string":     { "name": "flagNote" } },
+          { "field.date":       { "name": "eventDate" } },
+          { "field.timestamp":  { "name": "loggedAt" } },
+          { "field.timestamp":  { "name": "wallClock", "@localTime": true } },
+          { "field.uuid":       { "name": "ownerId" } },
+          { "field.uuid":       { "name": "approverId" } },
           { "field.string":     { "name": "email" } },
           { "field.string":     { "name": "phone" } },
           { "field.string":     { "name": "review" } },
@@ -24,6 +29,10 @@
           { "validator.requiredWhen": { "name": "birthNeedsSubject", "@field": "subject", "@when": "kind", "@equals": "BIRTH" } },
           { "validator.requiredWhen": { "name": "flaggedNeedsNote", "@field": "flagNote", "@when": "flag", "@equals": "true" } },
           { "validator.presentIff":  { "name": "closedIffNote", "@field": "closedNote", "@when": "state", "@equals": "CLOSED" } },
+          { "validator.comparison":  { "name": "ownerNotApprover", "@left": "ownerId", "@op": "ne", "@right": "approverId" } },
+          { "validator.comparison":  { "name": "dateVsTimestamp", "@left": "eventDate", "@op": "lte", "@right": "loggedAt" } },
+          { "validator.comparison":  { "name": "instantVsWallClock", "@left": "loggedAt", "@op": "lte", "@right": "wallClock" } },
+          { "validator.comparison":  { "name": "instantEqWallClock", "@left": "loggedAt", "@op": "eq", "@right": "wallClock" } },
           { "validator.atLeastOne":  { "name": "reachable", "@fields": ["email", "phone"] } },
           { "validator.requiredWhen": { "name": "reviewNeedsReviewer", "@field": "reviewedBy", "@when": "review", "@equals": "DONE" } }
         ]
diff --git a/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs b/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs
index cb98d46aff..e316c9ba31 100644
--- a/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs
+++ b/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs
@@ -5,6 +5,12 @@
 
 namespace MetaObjects.Cli.Tests;
 
+// OwnedRunner.Run changes the process-wide working directory and console for the length of a run.
+// Outside the serial collection this class ran in parallel with every other class, so
+// GenCommandTests.Gen_writes_the_hash_manifest_beside_the_metadata_not_in_cwd read THIS test's
+// temp root as "the current directory", found the manifest gen had just written there, and failed
+// about one run in five.
+[Collection(OwnedRunnerCollection.Name)]
 public sealed class DependencyCliTests : IDisposable
 {
     private readonly string _root = Path.Combine(Path.GetTempPath(), "meta-dep-cli-" + Guid.NewGuid().ToString("N"));
diff --git a/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs
index 72f15b02a6..8ec4fd1b50 100644
--- a/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs
+++ b/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs
@@ -45,7 +45,7 @@ public static IEnumerable Cases() =>
         AllCases().Select(c => new object[] { c.GetProperty("name").GetString()! });
 
     [Fact]
-    public void Discovers_all_cross_field_cases() => Assert.Equal(20, AllCases().Length);
+    public void Discovers_all_cross_field_cases() => Assert.Equal(24, AllCases().Length);
 
     [Theory]
     [MemberData(nameof(Cases))]
diff --git a/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidatorGenerationTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidatorGenerationTests.cs
index 1bf6703669..4334b76ff4 100644
--- a/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidatorGenerationTests.cs
+++ b/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidatorGenerationTests.cs
@@ -37,6 +37,23 @@ public class CrossFieldValidatorGenerationTests
     ]}}
     """;
 
+    private const string EqAcrossClrTypes = """
+    { "metadata.root": { "package": "acme", "children": [
+      { "object.entity": { "name": "Stamp", "children": [
+        { "source.rdb": { "@table": "stamps" } },
+        { "field.long": { "name": "id" } },
+        { "field.timestamp": { "name": "loggedAt" } },
+        { "field.timestamp": { "name": "wallClock", "@localTime": true } },
+        { "field.enum": { "name": "colour", "@values": ["RED", "BLUE"] } },
+        { "field.enum": { "name": "shade", "@values": ["RED", "BLUE"] } },
+        { "identity.primary": { "@fields": "id" } },
+        { "validator.comparison": { "name": "sameInstant", "@left": "loggedAt", "@op": "eq", "@right": "wallClock" } },
+        { "validator.comparison": { "name": "differentInstant", "@left": "loggedAt", "@op": "ne", "@right": "wallClock" } },
+        { "validator.comparison": { "name": "sameColour", "@left": "colour", "@op": "eq", "@right": "shade" } }
+      ]}}
+    ]}}
+    """;
+
     private const string Plain = """
     { "metadata.root": { "package": "acme", "children": [
       { "object.entity": { "name": "Widget", "children": [
@@ -112,6 +129,22 @@ public class CrossFieldValidatorGenerationTests
     ]}}
     """;
 
+    // A concrete entity extending an abstract shape that declares a rule.
+    private const string AbstractParent = """
+    { "metadata.root": { "package": "acme", "children": [
+      { "object.entity": { "name": "Base", "abstract": true, "children": [
+        { "field.int": { "name": "a" } },
+        { "field.int": { "name": "b" } },
+        { "validator.comparison": { "name": "ab", "@left": "a", "@op": "lte", "@right": "b" } }
+      ]}},
+      { "object.entity": { "name": "Item", "extends": "Base", "children": [
+        { "source.rdb": { "@table": "items" } },
+        { "field.long": { "name": "id" } },
+        { "identity.primary": { "@fields": "id" } }
+      ]}}
+    ]}}
+    """;
+
     // A decimal compared with a double: C# has no implicit conversion between the two.
     private const string MixedNumeric = """
     { "metadata.root": { "package": "acme", "children": [
@@ -126,24 +159,27 @@ public class CrossFieldValidatorGenerationTests
     ]}}
     """;
 
-    private static GenContext Ctx(string model)
+    private static GenContext Ctx(string model, bool abstractShapes = false)
     {
         var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "xf.json")]);
         Assert.Empty(r.Errors);
         return new GenContext
         {
             Entities = r.Root.Objects(), Root = r.Root,
-            Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme" },
+            Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme", EmitAbstractShapes = abstractShapes },
         };
     }
 
-    private static Assembly Compile(EntityGenerator generator, string model)
-    {
-        var trees = generator.Generate(Ctx(model)).Select(f => CSharpSyntaxTree.ParseText(f.Content)).ToArray();
-        var refs = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
+    // Built once per run: opening every trusted-platform assembly is the cost of each compile.
+    private static readonly Lazy> CompileReferences = new(() =>
+        ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
             .Split(Path.PathSeparator).Where(p => p.Length > 0)
-            .Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList();
-        var comp = CSharpCompilation.Create("xfi_" + Guid.NewGuid().ToString("N"), trees, refs,
+            .Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList());
+
+    private static Assembly Compile(EntityGenerator generator, string model, bool abstractShapes = false)
+    {
+        var trees = generator.Generate(Ctx(model, abstractShapes)).Select(f => CSharpSyntaxTree.ParseText(f.Content)).ToArray();
+        var comp = CSharpCompilation.Create("xfi_" + Guid.NewGuid().ToString("N"), trees, CompileReferences.Value,
             new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
         using var ms = new MemoryStream();
         var emit = comp.Emit(ms);
@@ -151,10 +187,11 @@ private static Assembly Compile(EntityGenerator generator, string model)
         return Assembly.Load(ms.ToArray());
     }
 
+    private static readonly JsonSerializerOptions ValidateJsonOptions = new() { PropertyNameCaseInsensitive = true };
+
     private static List Validate(Assembly asm, string type, string json)
     {
-        object inst = JsonSerializer.Deserialize(json, asm.GetType($"Acme.{type}")!,
-            new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
+        object inst = JsonSerializer.Deserialize(json, asm.GetType($"Acme.{type}")!, ValidateJsonOptions)!;
         var results = new List();
         Validator.TryValidateObject(inst, new ValidationContext(inst), results, true);
         return results;
@@ -185,25 +222,34 @@ public void Entity_without_cross_field_validators_is_not_validatable()
     }
 
     [Fact]
-    public void Derived_entity_runs_the_inherited_rule_and_its_own()
+    public void Eq_and_ne_between_fields_of_different_clr_types_are_skipped_not_rejected()
     {
-        var asm = Compile(new BasedEntityGenerator(), Inherited);
-        Assert.Equal(2, Validate(asm, "Child", "{\"a\":3,\"b\":1,\"c\":1,\"d\":0}").Count);
+        var asm = Compile(new EntityGenerator(), EqAcrossClrTypes);
+        Assert.Empty(Validate(asm, "Stamp", "{\"loggedAt\":\"2030-01-02T00:00:00Z\",\"wallClock\":\"2020-01-01T00:00:00\",\"colour\":0,\"shade\":1}"));
+        Assert.Empty(Validate(asm, "Stamp", "{\"loggedAt\":\"2020-01-01T00:00:00Z\",\"wallClock\":\"2020-01-01T00:00:00\",\"colour\":0,\"shade\":0}"));
     }
 
     [Fact]
-    public void Without_an_emitted_base_class_a_validator_on_an_unemitted_member_is_skipped()
+    public void A_child_of_a_concrete_parent_runs_the_inherited_rule_and_its_own()
     {
-        // The stock mapped declaration names no C# base, so Child carries only its own fields;
-        // the inherited rule references members it does not have and is skipped.
+        // The child is flattened (it carries the parent's properties itself), so the parent's
+        // rule has members to read and runs beside the child's own, with no special case.
         var asm = Compile(new EntityGenerator(), Inherited);
-        Assert.Single(Validate(asm, "Child", "{\"a\":3,\"b\":1,\"c\":1,\"d\":0}"));
+        Assert.Equal(2, Validate(asm, "Child", "{\"a\":3,\"b\":1,\"c\":1,\"d\":0}").Count);
     }
 
     [Fact]
-    public void Derived_entity_compiles_when_every_base_rule_is_skipped()
+    public void A_child_of_an_emitted_abstract_shape_enforces_the_rule_declared_on_the_shape()
     {
-        var asm = Compile(new BasedEntityGenerator(), SkippedParent);
+        var asm = Compile(new EntityGenerator(), AbstractParent, abstractShapes: true);
+        Assert.Single(Validate(asm, "Item", "{\"a\":3,\"b\":1}"));
+        Assert.Empty(Validate(asm, "Item", "{\"a\":1,\"b\":3}"));
+    }
+
+    [Fact]
+    public void A_child_compiles_when_every_inherited_rule_is_skipped()
+    {
+        var asm = Compile(new EntityGenerator(), SkippedParent);
         Assert.Single(Validate(asm, "Child", "{\"kind\":\"X\"}"));
         Assert.Empty(Validate(asm, "Child", "{\"kind\":\"X\",\"note\":\"n\"}"));
     }
@@ -216,17 +262,4 @@ public void Tph_subtype_runs_the_rule_of_an_unemitted_abstract_level()
         Assert.Single(Validate(asm, "Dog", "{\"lo\":3,\"hi\":2,\"kind\":\"FURRY\",\"fur\":\"f\"}"));
         Assert.Empty(Validate(asm, "Dog", "{\"lo\":1,\"hi\":2,\"kind\":\"FURRY\",\"fur\":\"f\"}"));
     }
-
-    // Emits the metadata `extends` chain as a C# base, the shape an adopter override produces.
-    private sealed class BasedEntityGenerator : EntityGenerator
-    {
-        protected override void EmitClassDeclarationLine(
-            System.Text.StringBuilder sb, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx)
-        {
-            if (kind == ClassDeclarationKind.MappedEntity && DirectMappedParent(entity, ctx.Config) is { } p)
-                sb.AppendLine($"public class {className} : {CSharpNaming.Pascal(p.Name)}");
-            else
-                base.EmitClassDeclarationLine(sb, entity, className, kind, ctx);
-        }
-    }
 }
diff --git a/server/csharp/MetaObjects.Codegen.Tests/EntityExtendsParentTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EntityExtendsParentTests.cs
new file mode 100644
index 0000000000..76c968a04e
--- /dev/null
+++ b/server/csharp/MetaObjects.Codegen.Tests/EntityExtendsParentTests.cs
@@ -0,0 +1,103 @@
+// An entity that `extends` another must carry the parent's properties.
+//
+// The member loop skips every field the C# base class supplies, so the class declaration has
+// to NAME that base — and a base is only right when it cannot become an EF inheritance
+// hierarchy. A concrete parent is a mapped entity with its own table; migrate-ts gives the
+// child a table with ALL the columns, which `class Child : Parent` (TPH or TPT) would
+// contradict, so the child is flattened. An abstract parent is an unmapped shape (emitted
+// only with EmitAbstractShapes), so inheritance is exact there.
+
+using MetaObjects.Codegen;
+using MetaObjects.Codegen.Generators;
+using MetaObjects.Loader;
+using Xunit;
+
+namespace MetaObjects.Codegen.Tests;
+
+public class EntityExtendsParentTests
+{
+    private const string ConcreteParentModel = """
+    { "metadata.root": { "package": "acme::demo", "children": [
+      { "object.entity": { "name": "Parent", "children": [
+        { "source.rdb": { "@table": "parents" } },
+        { "field.long": { "name": "id" } },
+        { "field.string": { "name": "title" } },
+        { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] } },
+      { "object.entity": { "name": "Child", "extends": "Parent", "children": [
+        { "source.rdb": { "@table": "children" } },
+        { "field.string": { "name": "extra" } } ] } }
+    ] } }
+    """;
+
+    private const string AbstractChainModel = """
+    { "metadata.root": { "package": "acme::demo", "children": [
+      { "object.entity": { "name": "Base", "abstract": true, "children": [
+        { "field.long": { "name": "id" } } ] } },
+      { "object.entity": { "name": "Audited", "abstract": true, "extends": "Base", "children": [
+        { "field.timestamp": { "name": "createdAt" } } ] } },
+      { "object.entity": { "name": "Widget", "extends": "Audited", "children": [
+        { "source.rdb": { "@table": "widgets" } },
+        { "field.string": { "name": "label" } },
+        { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] } }
+    ] } }
+    """;
+
+    private static Dictionary Generate(string model, bool abstractShapes)
+    {
+        var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "extends.json")]);
+        Assert.Empty(r.Errors);
+        var ctx = new GenContext
+        {
+            Entities = r.Root.Objects(),
+            Root = r.Root,
+            Config = new GenConfig { OutDir = "/unused", Namespace = "Acme.Generated", EmitAbstractShapes = abstractShapes },
+        };
+        return new EntityGenerator().Generate(ctx).ToDictionary(f => f.Path, f => f.Content);
+    }
+
+    [Theory]
+    [InlineData(false)]
+    [InlineData(true)]
+    public void A_child_of_a_concrete_parent_declares_the_parents_properties_and_names_no_base(bool abstractShapes)
+    {
+        var files = Generate(ConcreteParentModel, abstractShapes);
+        var child = files["Child.g.cs"];
+        // Not an EF inheritance hierarchy: Child owns its table and every column.
+        Assert.Contains("public class Child", child);
+        Assert.DoesNotContain("class Child :", child);
+        Assert.Contains("public long Id { get; set; }", child);
+        Assert.Contains(" Title { get; set; }", child);
+        Assert.Contains(" Extra { get; set; }", child);
+        Assert.Contains("[Table(\"children\")]", child);
+        // The parent is untouched.
+        Assert.DoesNotContain("Extra", files["Parent.g.cs"]);
+    }
+
+    [Fact]
+    public void An_entity_extending_an_emitted_abstract_shape_names_it_and_declares_only_its_own_members()
+    {
+        var files = Generate(AbstractChainModel, abstractShapes: true);
+        Assert.Contains("public abstract class Base", files["Base.g.cs"]);
+        Assert.DoesNotContain("class Base :", files["Base.g.cs"]);
+        var audited = files["Audited.g.cs"];
+        Assert.Contains("public abstract class Audited : Base", audited);
+        Assert.Contains("CreatedAt", audited);
+        Assert.DoesNotContain(" Id ", audited);
+        var widget = files["Widget.g.cs"];
+        Assert.Contains("public class Widget : Audited", widget);
+        Assert.Contains("Label", widget);
+        // Inherited through the base chain, not restated.
+        Assert.DoesNotContain("CreatedAt", widget);
+        Assert.DoesNotContain(" Id ", widget);
+    }
+
+    [Fact]
+    public void Without_emitted_shapes_an_abstract_parents_fields_are_flattened_onto_the_child()
+    {
+        var widget = Generate(AbstractChainModel, abstractShapes: false)["Widget.g.cs"];
+        Assert.DoesNotContain("class Widget :", widget);
+        Assert.Contains("public long Id { get; set; }", widget);
+        Assert.Contains("CreatedAt", widget);
+        Assert.Contains("Label", widget);
+    }
+}
diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs
index 64c88f88d9..4c40700d45 100644
--- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs
+++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs
@@ -294,18 +294,11 @@ private EmittedFile EmitMappedClassImpl(
 
         EmitClassHeader(sb, entity, className, isProjection, pkFields, ctx);
         // Cross-field validators run on the full create record only (never a read-only view).
-        // The C# base chain is real only when the declaration line actually names a base; fields
-        // the class skips as "inherited" are otherwise absent as properties, so a validator that
-        // references one is skipped rather than emitted against a member that does not exist.
-        var mappedBase = DirectMappedParent(entity, ctx.Config);
-        var declaresBase = mappedBase is not null && LastLineHasBase(sb);
-        var validatingBase = declaresBase && !InstanceArtifacts.IsAbstract(mappedBase!)
-            && HasEffectiveCrossField(mappedBase!) ? mappedBase : null;
-        var absent = mappedBase is not null && !declaresBase
-            ? new HashSet(mappedBase.Fields().Select(f => f.Name), StringComparer.Ordinal)
-            : null;
-        var validateMethod = isProjection ? null : CrossFieldValidateMethod(entity, validatingBase, absent);
-        if (validateMethod is not null && validatingBase is null) AppendValidatableInterface(sb);
+        // A non-TPH entity never has a validating base: its only possible base is an abstract
+        // shape, which declares no Validate, and every property it carries is present on this
+        // class (own or inherited through the base chain), so every effective rule is emitted here.
+        var validateMethod = isProjection ? null : CrossFieldValidateMethod(entity, validatingBase: null);
+        if (validateMethod is not null) AppendValidatableInterface(sb);
         sb.AppendLine("{");
 
         // Nested enum declarations (before the class properties, as C# enum members
@@ -313,9 +306,10 @@ private EmittedFile EmitMappedClassImpl(
         var enumDecls = CollectEnumDecls(entity);
 
         // Members in declared order: scalar columns + enum-typed props + (entities only) owned-type navs.
-        // When this entity extends an emitted base class (DirectMappedParent), the base carries
+        // When this entity extends an emitted abstract shape (DirectMappedParent), the shape carries
         // the inherited fields — emit ONLY this entity's own fields and let C# inheritance supply
-        // the rest (mirrors the metadata `extends` chain; the PK lives on the declaring base).
+        // the rest. A concrete parent is never a C# base (two mapped entities in one hierarchy would
+        // be an EF TPH/TPT mapping, not the one-table-per-entity model), so its fields are declared here.
         var inheritedNames = DirectMappedParent(entity, ctx.Config) is { } mp
             ? new HashSet(mp.Fields().Select(f => f.Name), StringComparer.Ordinal)
             : new HashSet(StringComparer.Ordinal);
@@ -482,7 +476,7 @@ protected virtual void EmitClassDeclarationLine(
                 // HasValue(...) fails model validation ("has a discriminator property,
                 // but does not have a discriminator value configured").
                 var classKeyword = TphPlanBuilder.IsTphDiscriminatorBase(entity, ctx.Root) ? "abstract class" : "class";
-                sb.AppendLine($"public {classKeyword} {className}");
+                sb.AppendLine($"public {classKeyword} {className}{MappedBaseClause(entity, ctx)}");
                 break;
             case ClassDeclarationKind.TphSubtype:
                 // Extend the nearest ancestor that actually GETS EMITTED as a class — the
@@ -504,7 +498,7 @@ protected virtual void EmitClassDeclarationLine(
                 sb.AppendLine($"public {tphKeyword} {className} : {baseClass}");
                 break;
             case ClassDeclarationKind.AbstractShape:
-                sb.AppendLine($"public abstract class {className}");
+                sb.AppendLine($"public abstract class {className}{MappedBaseClause(entity, ctx)}");
                 break;
             case ClassDeclarationKind.ValueObject:
                 sb.AppendLine($"public class {className}");
@@ -512,6 +506,12 @@ protected virtual void EmitClassDeclarationLine(
         }
     }
 
+    // ` : Base` when this non-TPH entity or abstract shape extends an emitted abstract shape
+    // (DirectMappedParent), else empty. The member loops skip the fields that base carries,
+    // so the declaration line MUST name it or those properties exist nowhere on the class.
+    private static string MappedBaseClause(MetaObject entity, GenContext ctx) =>
+        DirectMappedParent(entity, ctx.Config) is { } parent ? $" : {CSharpNaming.Pascal(parent.Name)}" : "";
+
     // A M:N navigation collection property on the source entity. The collection is
     // the relationship name PascalCased; its element type is the target entity.
     //
@@ -733,16 +733,23 @@ protected static MetaObject EmittedTphAncestor(MetaObject member, GenContext ctx
 
     // The directly-extended entity to emit as a C# base class for a NON-TPH entity (mapped
     // entity or abstract shape). The metadata `extends` chain becomes the C# inheritance
-    // chain: `class Physician : BaseAuditableEntity`, `abstract class BaseAuditableEntity :
-    // BaseEntity`. Returns the immediate `extends` target when it is an emitted entity — an
-    // abstract base (only when EmitAbstractShapes is on, since the base must exist as a type)
-    // or a concrete parent. Null when there is no such parent: the entity then flattens its
-    // (un-emitted) abstract ancestors' fields as before. TPH members use DirectTphParent.
+    // chain ONLY through abstract shapes: `class Physician : BaseAuditableEntity`, `abstract
+    // class BaseAuditableEntity : BaseEntity`. An abstract shape is not mapped, so EF folds
+    // its properties into each derived entity's own table — exactly what every other port
+    // and the migrate-ts schema give a child of an abstract parent.
+    //
+    // Returns null otherwise: the entity then declares every resolved field itself. That
+    // includes a CONCRETE parent. Each concrete entity owns a table carrying ALL its columns
+    // (the migrate-ts schema gives `Child` a table with the parent's columns and its own,
+    // and the other ports' child models carry both), but a C# `Child : Parent` between two
+    // MAPPED entities is an EF inheritance hierarchy — TPH (one shared table plus a
+    // discriminator) or TPT (child table holding only the child's own columns). Either
+    // contradicts that schema, so a concrete parent is flattened, never named as a base.
+    // TPH members use DirectTphParent.
     protected static MetaObject? DirectMappedParent(MetaObject entity, GenConfig config)
     {
         if (entity.SuperData is not MetaObject sup || !sup.IsEntity()) return null;
-        if (InstanceArtifacts.IsAbstract(sup)) return config.EmitAbstractShapes ? sup : null;
-        return sup;
+        return InstanceArtifacts.IsAbstract(sup) && config.EmitAbstractShapes ? sup : null;
     }
 
     // The nearest @discriminator-bearing ancestor of a TPH subtype (its TPH base).
@@ -1054,15 +1061,6 @@ private static List CrossFieldValidatorsFor(MetaObject entity, Me
     private static bool HasEffectiveCrossField(MetaObject entity) =>
         entity.Validators().Any(IsCrossFieldValidator);
 
-    private static bool LastLineHasBase(StringBuilder sb)
-    {
-        var len = sb.Length;
-        while (len > 0 && (sb[len - 1] == '\n' || sb[len - 1] == '\r')) len--;
-        var start = len;
-        while (start > 0 && sb[start - 1] != '\n') start--;
-        return sb.ToString(start, len - start).Contains(" : ", StringComparison.Ordinal);
-    }
-
     // Appends `, IValidatableObject` (or ` : IValidatableObject`) to the just-written class
     // declaration line. Works on the builder so an overridden declaration seam still applies.
     private static void AppendValidatableInterface(StringBuilder sb)
@@ -1077,8 +1075,7 @@ private static void AppendValidatableInterface(StringBuilder sb)
     }
 
     // Returns the emitted Validate method (4-space class-body indent), or null when nothing to emit.
-    private string? CrossFieldValidateMethod(
-        MetaObject entity, MetaObject? validatingBase, ISet? absentProps = null)
+    private string? CrossFieldValidateMethod(MetaObject entity, MetaObject? validatingBase)
     {
         var validators = CrossFieldValidatorsFor(entity, validatingBase);
         if (validators.Count == 0) return null;
@@ -1098,7 +1095,6 @@ private static void AppendValidatableInterface(StringBuilder sb)
             var f = entity.Fields().FirstOrDefault(x => x.Name == n);
             if (f is null || f.ResolvedIsArray()) return null;
             if (f.IsReadOnlyMutability || f.IsDerived() || generatedKey.Contains(f.Name)) return null;
-            if (absentProps is not null && absentProps.Contains(f.Name)) return null; // not a property of this class
             return CSharpNaming.ScalarFor(f.SubType) is not null || f.SubType == FIELD_SUBTYPE_ENUM ? f : null;
         }
 
@@ -1160,7 +1156,11 @@ string Gate(MetaField when, string raw)
                     else if (lk == CrossKind.Temporal && rk == CrossKind.Temporal
                              && CSharpNaming.ScalarForField(l) == CSharpNaming.ScalarForField(r))
                         cond = $"{a} {csOp} {b}";
-                    else if (!ordering && lk == rk && lk != CrossKind.Other)
+                    else if (!ordering && l.SubType == r.SubType
+                             && (lk != CrossKind.Other || l.SubType is FIELD_SUBTYPE_UUID or FIELD_SUBTYPE_URI or FIELD_SUBTYPE_INET)
+                             && CSharpNaming.ScalarForField(l) == CSharpNaming.ScalarForField(r)
+                             && (l.SubType != FIELD_SUBTYPE_ENUM
+                                 || ReferenceEquals(Fr019SharedEnum.ResolveSharedEnumDecl(l) ?? l, Fr019SharedEnum.ResolveSharedEnumDecl(r) ?? r)))
                         cond = op == "eq" ? $"Equals({a}, {b})" : $"!Equals({a}, {b})";
                     else break;
                     var lp = PropertyName(l); var rp = PropertyName(r);
diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinCrossFieldRules.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinCrossFieldRules.kt
index b205c1db7a..a3560c8a3e 100644
--- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinCrossFieldRules.kt
+++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinCrossFieldRules.kt
@@ -1,14 +1,23 @@
 package com.metaobjects.generator.kotlin
 
 import com.metaobjects.MetaData
+import com.metaobjects.database.CoreDBMetaDataProvider
 import com.metaobjects.field.BooleanField
 import com.metaobjects.field.CurrencyField
+import com.metaobjects.field.DateField
 import com.metaobjects.field.DecimalField
 import com.metaobjects.field.DoubleField
 import com.metaobjects.field.FloatField
 import com.metaobjects.field.IntegerField
 import com.metaobjects.field.LongField
+import com.metaobjects.field.EnumField
 import com.metaobjects.field.MetaField
+import com.metaobjects.field.StringField
+import com.metaobjects.field.InetField
+import com.metaobjects.field.TimeField
+import com.metaobjects.field.TimestampField
+import com.metaobjects.field.UriField
+import com.metaobjects.field.UuidField
 import com.metaobjects.`object`.MetaObject
 import com.metaobjects.validator.AtLeastOneValidator
 import com.metaobjects.validator.ComparisonValidator
@@ -27,6 +36,46 @@ object KotlinCrossFieldRules {
         f is IntegerField || f is LongField || f is DoubleField || f is FloatField ||
             f is DecimalField || f is CurrencyField
 
+    private fun isTemporalCross(f: MetaField<*>): Boolean =
+        f is DateField || f is TimeField || f is TimestampField
+
+    private fun flag(f: MetaField<*>, attr: String): Boolean =
+        f.hasMetaAttr(attr, true) &&
+            runCatching { f.getMetaAttr(attr, true).value }.getOrNull()?.toString()?.trim().toBoolean()
+
+    /**
+     * What decides the Kotlin type of a field beyond its subtype: a timestamp is an Instant unless
+     * `@localTime`, and a uri/inet is a native type unless `@lenient` (then a String). Read from the
+     * attributes rather than the type mapper so an ejected copy of this file stands alone.
+     */
+    private fun nativeShape(f: MetaField<*>): Pair =
+        Pair(f is TimestampField && flag(f, CoreDBMetaDataProvider.LOCAL_TIME), (f is UriField || f is InetField) && flag(f, UriField.ATTR_LENIENT))
+
+    /**
+     * The comparison for two fields, or null when the pair has no sound one. Mirrors the C#
+     * generator: numerics compare with each other, strings and temporals only with their own
+     * subtype and Kotlin type (a date has no ordering against a timestamp, nor an Instant against a
+     * `@localTime` LocalDateTime, and casting both to Comparable throws
+     * ClassCastException inside the validity property, turning a create into a 500), and
+     * boolean, enum, uuid, uri and inet fields only test equality. Anything else is skipped, like every other port.
+     */
+    private fun comparison(l: MetaField<*>, r: MetaField<*>, op: String, kop: String, ref: (MetaField<*>) -> String): CodeBlock? {
+        val ordering = op == "gt" || op == "gte" || op == "lt" || op == "lte"
+        val same = l.subType == r.subType
+        if (isNumericCross(l) && isNumericCross(r) && !same) {
+            return CodeBlock.of("java.math.BigDecimal(%L.toString()).compareTo(java.math.BigDecimal(%L.toString())) $kop 0", ref(l), ref(r))
+        }
+        if (!same) return null
+        val comparable = isNumericCross(l) || l is StringField || isTemporalCross(l)
+        val equatable = !ordering && (l is BooleanField || l is EnumField || l is UuidField || l is UriField || l is InetField)
+        if (!comparable && !equatable) return null
+        if (nativeShape(l) != nativeShape(r)) return null
+        if (comparable) {
+            return CodeBlock.of("(%L as Comparable).compareTo(%L) $kop 0", ref(l), ref(r))
+        }
+        return CodeBlock.of("(%L %L %L)", ref(l), if (op == "eq") "==" else "!=", ref(r))
+    }
+
     private fun crossAttr(v: MetaData, attr: String): String? =
         if (v.hasMetaAttr(attr)) v.getMetaAttr(attr).value?.toString() else null
 
@@ -63,16 +112,13 @@ object KotlinCrossFieldRules {
                 is ComparisonValidator -> {
                     val l = fields[crossAttr(v, ComparisonValidator.ATTR_LEFT)] ?: continue
                     val r = fields[crossAttr(v, ComparisonValidator.ATTR_RIGHT)] ?: continue
-                    val op = when (crossAttr(v, ComparisonValidator.ATTR_OP)) {
+                    val opName = crossAttr(v, ComparisonValidator.ATTR_OP)
+                    val op = when (opName) {
                         "gt" -> ">"; "gte" -> ">="; "lt" -> "<"; "lte" -> "<="; "ne" -> "!="; "eq" -> "=="
                         else -> continue
                     }
                     if (l.isArrayType || r.isArrayType) continue
-                    val cmp = if (isNumericCross(l) && isNumericCross(r) && l.subType != r.subType) {
-                        CodeBlock.of("java.math.BigDecimal(%L.toString()).compareTo(java.math.BigDecimal(%L.toString())) $op 0", ref(l), ref(r))
-                    } else {
-                        CodeBlock.of("(%L as Comparable).compareTo(%L) $op 0", ref(l), ref(r))
-                    }
+                    val cmp = comparison(l, r, opName!!, op, ref) ?: continue
                     CodeBlock.of("%L == null || %L == null || %L", ref(l), ref(r), cmp)
                 }
                 is RequiredWhenValidator, is PresentIffValidator -> {
diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ValidationConformanceTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ValidationConformanceTest.kt
index 1192885046..23f56987e1 100644
--- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ValidationConformanceTest.kt
+++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ValidationConformanceTest.kt
@@ -92,7 +92,7 @@ class ValidationConformanceTest {
                 "generated Account.kt failed to compile:\n${compileResult.messages}")
 
             // --- validate each corpus payload through a jakarta Validator ---
-            val mapper = ObjectMapper().registerKotlinModule()
+            val mapper = ObjectMapper().findAndRegisterModules().registerKotlinModule()
             val validator: Validator = Validation.buildDefaultValidatorFactory().validator
 
             val casesJson = String(Files.readAllBytes(corpus.resolve(casesName)), StandardCharsets.UTF_8)
diff --git a/server/java/codegen-spring/pom.xml b/server/java/codegen-spring/pom.xml
index 239418be3f..4b4949f0ee 100644
--- a/server/java/codegen-spring/pom.xml
+++ b/server/java/codegen-spring/pom.xml
@@ -107,6 +107,15 @@
             provided
         
 
+        
+        
+            com.fasterxml.jackson.datatype
+            jackson-datatype-jsr310
+            2.18.2
+            test
+        
+
         
diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringGeneratorSupport.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringGeneratorSupport.java
index de68dd814a..ab308ab864 100644
--- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringGeneratorSupport.java
+++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringGeneratorSupport.java
@@ -15,6 +15,7 @@
 import com.metaobjects.field.BooleanField;
 import com.metaobjects.field.CurrencyField;
 import com.metaobjects.field.DecimalField;
+import com.metaobjects.field.DateField;
 import com.metaobjects.field.DoubleField;
 import com.metaobjects.field.EnumField;
 import com.metaobjects.field.FloatField;
@@ -23,6 +24,11 @@
 import com.metaobjects.field.MetaField;
 import com.metaobjects.field.ObjectField;
 import com.metaobjects.field.StringField;
+import com.metaobjects.field.TimeField;
+import com.metaobjects.field.TimestampField;
+import com.metaobjects.field.InetField;
+import com.metaobjects.field.UriField;
+import com.metaobjects.field.UuidField;
 import com.metaobjects.generator.util.RestSurfaceGate;
 import com.metaobjects.identity.MetaIdentity;
 import com.metaobjects.identity.PrimaryIdentity;
@@ -652,6 +658,36 @@ private static boolean isNumericCrossField(MetaField f) {
             || f instanceof FloatField || f instanceof DecimalField || f instanceof CurrencyField;
     }
 
+    private static boolean isTemporalCrossField(MetaField f) {
+        return f instanceof DateField || f instanceof TimeField || f instanceof TimestampField;
+    }
+
+    /**
+     * The comparison expression for two fields, or null when the pair has no sound one. Mirrors the
+     * C# generator: numerics compare with each other, strings and temporals only with their own
+     * subtype and Java type (a date has no ordering against a timestamp, nor an Instant against a
+     * {@code @localTime} LocalDateTime, and casting both to Comparable would
+     * throw ClassCastException inside the constraint method, turning a create into a 500), and
+     * boolean, enum, uuid, uri and inet fields only test equality. Anything else is skipped, like every other port.
+     */
+    private static String crossComparison(MetaField l, MetaField r, String lc, String rc, String op, String jop) {
+        boolean ordering = op.equals("gt") || op.equals("gte") || op.equals("lt") || op.equals("lte");
+        boolean sameSubType = l.getSubType().equals(r.getSubType());
+        if (isNumericCrossField(l) && isNumericCrossField(r) && !sameSubType) {
+            return "new java.math.BigDecimal(String.valueOf(" + lc + ")).compareTo(new java.math.BigDecimal(String.valueOf(" + rc + "))) " + jop + " 0";
+        }
+        if (!sameSubType) return null;
+        boolean comparable = isNumericCrossField(l) || l instanceof StringField || isTemporalCrossField(l);
+        boolean equatable = !ordering && (l instanceof BooleanField || l instanceof EnumField
+                || l instanceof UuidField || l instanceof UriField || l instanceof InetField);
+        if (!comparable && !equatable) return null;
+        if (!SpringTypeMapper.javaTypeName(l).equals(SpringTypeMapper.javaTypeName(r))) return null;
+        if (comparable) {
+            return "((Comparable) (Object) " + lc + ").compareTo(" + rc + ") " + jop + " 0";
+        }
+        return (op.equals("eq") ? "" : "!") + "java.util.Objects.equals(" + lc + ", " + rc + ")";
+    }
+
     private static String crossAttr(MetaData v, String attr) {
         if (!v.hasMetaAttr(attr)) return null;
         Object raw = v.getMetaAttr(attr).getValue();
@@ -741,12 +777,8 @@ public static List> crossFieldRules(
                 if (l == null || r == null || jop == null || l.isArrayType() || r.isArrayType()) continue;
                 String lc = ref.apply(l);
                 String rc = ref.apply(r);
-                String cmp;
-                if (isNumericCrossField(l) && isNumericCrossField(r) && !l.getSubType().equals(r.getSubType())) {
-                    cmp = "new java.math.BigDecimal(String.valueOf(" + lc + ")).compareTo(new java.math.BigDecimal(String.valueOf(" + rc + "))) " + jop + " 0";
-                } else {
-                    cmp = "((Comparable) (Object) " + lc + ").compareTo(" + rc + ") " + jop + " 0";
-                }
+                String cmp = crossComparison(l, r, lc, rc, op, jop);
+                if (cmp == null) continue;
                 expr = lc + " == null || " + rc + " == null || " + cmp;
             } else if (v instanceof RequiredWhenValidator || v instanceof PresentIffValidator) {
                 MetaField t = crossField(entity, crossAttr(v, RequiredWhenValidator.ATTR_FIELD), components);
diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCrossFieldValidationTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCrossFieldValidationTest.java
index 82ef7426de..e998f0c095 100644
--- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCrossFieldValidationTest.java
+++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCrossFieldValidationTest.java
@@ -83,11 +83,22 @@ private Path gen(boolean withValidators) throws Exception {
 
     /** Violation count Bean Validation reports for {@code json} bound to the compiled {@code EvDto}. */
     private int violations(boolean withValidators, String json) throws Exception {
+        return violations(withValidators, "acme.ev.EvDto", json);
+    }
+
+    /** Violation count Bean Validation reports for {@code json} bound to the compiled {@code className}. */
+    private int violations(boolean withValidators, String className, String json) throws Exception {
         Path src = gen(withValidators);
         Path classes = tmp.newFolder().toPath();
         compile(src, classes);
         try (URLClassLoader cl = new URLClassLoader(new URL[]{ classes.toUri().toURL() }, getClass().getClassLoader())) {
-            Object dto = MAPPER.readValue(json, cl.loadClass("acme.ev.EvDto"));
+            Class cls = cl.loadClass(className);
+            // A Patch is built through its presence-tracking fromJson, never bound field by field;
+            // a Dto binds as a record.
+            Object dto = className.endsWith("Patch")
+                ? cls.getMethod("fromJson", com.fasterxml.jackson.databind.JsonNode.class, ObjectMapper.class)
+                    .invoke(null, MAPPER.readTree(json), MAPPER)
+                : MAPPER.readValue(json, cls);
             Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
             return validator.validate(dto).size();
         }
@@ -106,10 +117,11 @@ public void entityWithoutCrossFieldValidatorsAcceptsTheSameBody() throws Excepti
     }
 
     @Test
-    public void patchIsUnchangedByCrossFieldValidators() throws Exception {
-        String withV = Files.readString(gen(true).resolve("acme/ev/EvPatch.java"));
-        String without = Files.readString(gen(false).resolve("acme/ev/EvPatch.java"));
-        assertEquals("the generated PATCH body must not change", without, withV);
+    public void patchBodyIsNotHeldToCrossFieldValidators() throws Exception {
+        // Executed, not compared as text: the same violating body is rejected by the full class
+        // and accepted by the partial one, which cannot see the merged row.
+        assertEquals(1, violations(true, "acme.ev.EvDto", VIOLATES_COMPARISON));
+        assertEquals(0, violations(true, "acme.ev.EvPatch", VIOLATES_COMPARISON));
     }
 
     private static void compile(Path srcDir, Path classesDir) throws Exception {
diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ValidationConformanceTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ValidationConformanceTest.java
index a68ab1606b..1b8dfc48cb 100644
--- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ValidationConformanceTest.java
+++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ValidationConformanceTest.java
@@ -51,7 +51,7 @@ public class ValidationConformanceTest extends SharedRegistryTestBase {
     @Rule
     public TemporaryFolder tmp = new TemporaryFolder();
 
-    private static final ObjectMapper MAPPER = new ObjectMapper();
+    private static final ObjectMapper MAPPER = new ObjectMapper().findAndRegisterModules();
 
     private static Path repoRoot() {
         return Path.of(System.getProperty("user.dir")).resolve("../../..").normalize();
diff --git a/server/python/src/metaobjects/codegen/generators/entity_model.py b/server/python/src/metaobjects/codegen/generators/entity_model.py
index bd02e13b8c..92eb5bc484 100644
--- a/server/python/src/metaobjects/codegen/generators/entity_model.py
+++ b/server/python/src/metaobjects/codegen/generators/entity_model.py
@@ -32,6 +32,7 @@
     IDENTITY_ATTR_GENERATION,
 )
 from metaobjects.meta.core.validator import validator_constants as vc
+from metaobjects.meta.persistence.db import db_constants as dbc
 from metaobjects.meta.persistence.origin.origin_constants import (
     AGG_ALL,
     AGG_ANY,
@@ -463,15 +464,42 @@ def _assigned_pk_field_names(entity: MetaObject) -> set[str]:
 # (None is SQL NULL; "" is NOT null). Enforced on the Create model only: a Patch body
 # cannot see the merged row, so the DB CHECK stays the enforcement point there.
 _COMPARISON_PY_OP = {"gt": ">", "gte": ">=", "lt": "<", "lte": "<=", "ne": "!=", "eq": "=="}
+_INT_SUBTYPES = (fc.FIELD_SUBTYPE_INT, fc.FIELD_SUBTYPE_LONG)
+_FLOAT_SUBTYPES = (fc.FIELD_SUBTYPE_DOUBLE, fc.FIELD_SUBTYPE_FLOAT)
+_DECIMAL_SUBTYPES = (fc.FIELD_SUBTYPE_DECIMAL, fc.FIELD_SUBTYPE_CURRENCY)
+_NUMERIC_CROSS = _INT_SUBTYPES + _FLOAT_SUBTYPES + _DECIMAL_SUBTYPES
+_ORDERED_CROSS = (
+    fc.FIELD_SUBTYPE_STRING, fc.FIELD_SUBTYPE_DATE, fc.FIELD_SUBTYPE_TIME, fc.FIELD_SUBTYPE_TIMESTAMP,
+)
+
+
+def _comparable(left: MetaField, right: MetaField, op: str) -> bool:
+    """Whether a comparison between these two fields has a sound meaning, as in every port: numerics
+    compare with each other, strings and temporals only with their own subtype and @localTime flag (a
+    date has no ordering against a timestamp, nor an aware datetime against a naive one, and Python
+    raises TypeError on both), and boolean, enum, uuid, uri
+    and inet fields only test equality. Anything else is skipped, never rejected."""
+    a, b = left.sub_type, right.sub_type
+    if a in _NUMERIC_CROSS and b in _NUMERIC_CROSS:
+        return True
+    if a != b:
+        return False
+    if (left.get_meta_attr(dbc.FIELD_ATTR_LOCAL_TIME) is True) != (
+        right.get_meta_attr(dbc.FIELD_ATTR_LOCAL_TIME) is True
+    ):
+        return False
+    if a in _ORDERED_CROSS:
+        return True
+    return op in ("eq", "ne") and a in (
+        fc.FIELD_SUBTYPE_BOOLEAN, fc.FIELD_SUBTYPE_ENUM,
+        fc.FIELD_SUBTYPE_UUID, fc.FIELD_SUBTYPE_URI, fc.FIELD_SUBTYPE_INET,
+    )
 _CROSS_FIELD_SUBTYPES = (
     vc.VALIDATOR_SUBTYPE_COMPARISON,
     vc.VALIDATOR_SUBTYPE_REQUIRED_WHEN,
     vc.VALIDATOR_SUBTYPE_PRESENT_IFF,
     vc.VALIDATOR_SUBTYPE_AT_LEAST_ONE,
 )
-_INT_SUBTYPES = (fc.FIELD_SUBTYPE_INT, fc.FIELD_SUBTYPE_LONG)
-_FLOAT_SUBTYPES = (fc.FIELD_SUBTYPE_DOUBLE, fc.FIELD_SUBTYPE_FLOAT)
-_DECIMAL_SUBTYPES = (fc.FIELD_SUBTYPE_DECIMAL, fc.FIELD_SUBTYPE_CURRENCY)
 _NUMERIC_LITERAL = re.compile(r"^-?\d+(\.\d+)?$")
 
 
@@ -516,6 +544,8 @@ def attr(name: str, node: MetaData = v) -> object:
                 continue
             if field_is_array(by_name[str(left)]) or field_is_array(by_name[str(right)]):
                 continue
+            if not _comparable(by_name[str(left)], by_name[str(right)], str(attr(vc.VALIDATOR_ATTR_OP))):
+                continue
             checks.append(
                 f"        if self.{left} is not None and self.{right} is not None:\n"
                 f"            try:\n"
diff --git a/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts b/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts
index e1f8cf0f8c..a11e10655f 100644
--- a/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts
+++ b/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts
@@ -16,7 +16,7 @@ import { formFile } from "../src/form-file.js";
 import { renderFormFile } from "../src/templates/form-file.js";
 import { makeRenderContext, buildPkMap, buildRelationMap } from "@metaobjectsdev/codegen-ts";
 
-async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: MetaObject }> {
+async function loadTph(withRule = false): Promise<{ root: MetaRoot; base: MetaObject; bridge: MetaObject }> {
   const loader = new MetaDataLoader();
   const { root, errors } = await loader.load([
     new InMemoryStringSource(
@@ -41,7 +41,15 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me
                 name: "BridgeAuth",
                 extends: "Auth",
                 "@discriminatorValue": "Bridge",
-                children: [{ "field.int": { name: "quantity", "@required": true } }],
+                children: [
+                  { "field.int": { name: "quantity", "@required": true } },
+                  ...(withRule
+                    ? [
+                        { "field.int": { name: "minQty" } },
+                        { "validator.comparison": { name: "qtyOrder", "@left": "minQty", "@op": "lte", "@right": "quantity" } },
+                      ]
+                    : []),
+                ],
               },
             },
             {
@@ -96,4 +104,16 @@ describe("FR-017 Tier 3 — TPH React forms", () => {
     expect(out).toContain("BridgeAuth.quantity");
     expect(out).not.toContain("BridgeAuth.type.name");
   });
+
+  // A refined Zod schema has no `.omit()`, so the form must bind the schema codegen exports
+  // for exactly this case (refined, discriminator already omitted), never the unrefined base
+  // (which would drop the cross-field rule from the form) and never `.omit()` on the refined one.
+  // The schema's behaviour is executed in codegen-ts `tph-cross-field.test.ts`.
+  test("a subtype form with a cross-field rule binds the refined body schema", async () => {
+    const { root, bridge } = await loadTph(true);
+    const out = renderFormFile(bridge, ctxFor(root));
+    expect(out).toContain("BridgeAuthInsertBodySchema");
+    expect(out).not.toContain("BridgeAuthInsertBaseSchema");
+    expect(out).not.toContain("BridgeAuthInsertSchema.omit");
+  });
 });
diff --git a/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts b/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts
index c4b93717c9..3cb10e53e9 100644
--- a/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts
+++ b/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts
@@ -16,8 +16,7 @@ import {
   FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_CURRENCY,
   FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DECIMAL, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT,
   FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP,
-  FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_UUID,
-  FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
+  FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
   VALIDATOR_SUBTYPE_REQUIRED, VALIDATOR_SUBTYPE_LENGTH, VALIDATOR_SUBTYPE_REGEX,
   VALIDATOR_SUBTYPE_NUMERIC, VALIDATOR_SUBTYPE_ARRAY,
   IDENTITY_ATTR_FIELDS, IDENTITY_ATTR_GENERATION,
@@ -278,6 +277,30 @@ const NUMERIC_SUBTYPES: ReadonlySet = new Set([
   FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY,
 ]);
 
+const ORDERED_SUBTYPES: ReadonlySet = new Set([
+  FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP,
+]);
+
+/** Subtypes with equality but no ordering: a pair of the same one may be tested with eq / ne. */
+const EQUALITY_SUBTYPES: ReadonlySet = new Set([
+  FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
+]);
+
+/** Whether a comparison between these two fields has a sound meaning, as in every port:
+ *  numerics compare with each other, strings and temporals only with their own subtype and
+ *  @localTime flag (a date against a timestamp, or an instant against a wall clock, compares
+ *  two differently shaped strings, which is meaningless),
+ *  and boolean, enum, uuid, uri and inet fields only test equality. Anything else is skipped, never rejected. */
+function crossComparable(left: MetaField, right: MetaField, opName: string): boolean {
+  const a = left.subType;
+  const b = right.subType;
+  if (NUMERIC_SUBTYPES.has(a) && NUMERIC_SUBTYPES.has(b)) return true;
+  if (a !== b) return false;
+  if ((left.attr(FIELD_ATTR_LOCAL_TIME) === true) !== (right.attr(FIELD_ATTR_LOCAL_TIME) === true)) return false;
+  if (ORDERED_SUBTYPES.has(a)) return true;
+  return (opName === "eq" || opName === "ne") && EQUALITY_SUBTYPES.has(a);
+}
+
 /** Names of the fields the INSERT-shaped schemas carry (same skip rules as the emitters). */
 function insertSchemaFieldNameSet(obj: MetaObject): Set {
   const autoGen = autoGenPkFieldNames(obj);
@@ -337,6 +360,7 @@ function crossFieldRefinementBody(obj: MetaObject): string[] {
         const opName = String(v.attr(VALIDATOR_ATTR_OP));
         const op = CROSS_FIELD_OPS[opName];
         if (!left || !right || !op || left.resolvedIsArray() || right.resolvedIsArray()) break;
+        if (!crossComparable(left, right, opName)) break;
         const numeric = NUMERIC_SUBTYPES.has(left.subType);
         const c = numeric
           ? "Number(l) - Number(r)"
diff --git a/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts b/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts
index 02c4fdef6a..17ae3d42d7 100644
--- a/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts
@@ -13,7 +13,8 @@
 // loader rejects a JSON-array default), which is exactly why the fix lives in
 // codegen-ts and can't be pushed into metadata.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -25,6 +26,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import type { GenContext } from "../src/generator.js";
 import type { Dialect } from "../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 async function loadRoot() {
   const json = JSON.stringify({
     "metadata.root": {
diff --git a/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts b/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts
index 02af8efea2..a0ea791134 100644
--- a/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts
@@ -18,7 +18,8 @@
 // This compiles entity + queries TOGETHER with the real TS compiler — the bug is
 // a mismatch BETWEEN those two files, so a single-file gate cannot see it.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -31,6 +32,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import type { GenContext } from "../src/generator.js";
 import type { Dialect } from "../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 /** @param pkField the PK field node; @param identity the identity.primary node. */
 async function loadRoot(pkField: unknown, identity: unknown) {
   const json = JSON.stringify({
diff --git a/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts b/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts
index 53c0ebfbe2..688521fdad 100644
--- a/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts
+++ b/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts
@@ -29,7 +29,8 @@
 // The peer lanes are the same test in each port. If one port drops out, that port keeps
 // precisely the bug class this exists to catch — so a skip here is never "just this lane".
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join, resolve, dirname } from "node:path";
 import { fileURLToPath, pathToFileURL } from "node:url";
@@ -49,6 +50,8 @@ import { buildPkMap } from "../src/pk-resolver.js";
 import { buildRelationMap } from "../src/relation-resolver.js";
 import type { GenContext } from "../src/generator.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 // test → codegen-ts → packages → typescript → server → repo root
 const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..", "..");
 const CORPUS = resolve(
diff --git a/server/typescript/packages/codegen-ts/test/compile-timeout.ts b/server/typescript/packages/codegen-ts/test/compile-timeout.ts
new file mode 100644
index 0000000000..0b7047ff1d
--- /dev/null
+++ b/server/typescript/packages/codegen-ts/test/compile-timeout.ts
@@ -0,0 +1,21 @@
+// Per-test timeout for every test file that type-checks generated output with the real
+// TypeScript compiler (`ts.createProgram`) or otherwise re-runs the whole generator suite.
+//
+// Why a timeout at all: bun's default is 5s. A compile test parses lib.d.ts, drizzle-orm and
+// zod's declarations on every call, and that costs 0.5-3.3s on an idle machine (the slowest,
+// codegen-compile-conformance, measured 2.7-3.3s per case; the full codegen-ts run measured
+// 2.5 min for 3,293 tests). That is under 2x headroom against the default, so a loaded
+// machine (a parallel lane, a gate run, another agent) pushes a correct test past 5s and it
+// reports a timeout that says nothing about the code.
+//
+// 30s is ~9x the slowest measured case: loose enough that load cannot trip it, tight enough
+// that a compile which really hangs still fails in half a minute.
+//
+// Usage: each file calls `setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS)` at its top level. It
+// cannot be a side effect of importing this module: bun evaluates a module once per process,
+// and `setDefaultTimeout` applies only to the file that calls it, so a side-effect import
+// raises the timeout for the first importing file alone. Bun resets the default for each
+// file, so files that do not call it keep the 5s hang detection.
+
+/** Per-test timeout for type-checking tests: ~9x the slowest measured case. */
+export const COMPILE_TEST_TIMEOUT_MS = 30_000;
diff --git a/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts b/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts
index b568b79639..bbcd9aee59 100644
--- a/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts
@@ -32,7 +32,8 @@
 // The `schema` passed here is the generated entity module itself (`import * as schema`),
 // which is what an adopter actually does with generated Drizzle tables.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -45,6 +46,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import type { GenContext } from "../src/generator.js";
 import type { Dialect } from "../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 async function loadRoot() {
   const json = JSON.stringify({
     "metadata.root": {
diff --git a/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts b/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts
index eda718d743..4d4100f29d 100644
--- a/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts
@@ -14,7 +14,8 @@
 // each kind (scalar, enum, array, nested value object), plus a jsonb column typed by an
 // all-optional value object.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -30,6 +31,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import type { GenContext } from "../src/generator.js";
 import type { Dialect } from "../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const MODEL = {
   "metadata.root": {
     package: "tracker",
diff --git a/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts b/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts
index 9328dbde6e..3fc58a160c 100644
--- a/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts
+++ b/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts
@@ -10,7 +10,8 @@
 // render the payload + output + extractor sources to a temp dir, dynamically import() the
 // emitted extractor module under bun, and CALL the generated functions.
 
-import { describe, test, expect, afterAll } from "bun:test";
+import { describe, test, expect, afterAll, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -23,6 +24,8 @@ import { buildPkMap } from "../src/pk-resolver.js";
 import { buildRelationMap } from "../src/relation-resolver.js";
 import type { GenContext } from "../src/generator.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 // Emit the REAL per-VO entity modules (`.ts` exporting `interface ` +
 // its enum union-aliases) the same way `meta gen` does, so the generated
 // extractor's `from "./.js"` payload imports RESOLVE against the modules
diff --git a/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts b/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts
index 7fbf133e65..4f5af92488 100644
--- a/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts
@@ -12,7 +12,8 @@
 // `@ts-expect-error` below must be USED (an unused one is TS2578), and the positive
 // assignments must type-check.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -23,6 +24,8 @@ import { buildPkMap } from "../src/pk-resolver.js";
 import { buildRelationMap } from "../src/relation-resolver.js";
 import type { GenContext } from "../src/generator.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const MODEL = {
   "metadata.root": {
     package: "tracker",
diff --git a/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts b/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts
index 164cf6c9cb..f19643acd1 100644
--- a/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts
+++ b/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts
@@ -14,7 +14,8 @@
 // (a) uses the TS compiler API (not `bun test`'s type system, and not a spawned
 // `bun run typecheck`) so it is hermetic + immune to workspace self-link noise.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
 import { tmpdir } from "node:os";
 import { join } from "node:path";
@@ -28,6 +29,8 @@ import { buildPkMap } from "../src/pk-resolver.js";
 import { buildRelationMap } from "../src/relation-resolver.js";
 import type { GenContext } from "../src/generator.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 // The AuthorBrief projection over the trainerWebsite test entities (Plan #3 T3/T4).
 const model = [
   { "object.value": { name: "PostBrief", children: [{ "field.string": { name: "title", "@required": true } }] } },
diff --git a/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts b/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts
index 9b0c02b336..0b651a4a61 100644
--- a/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts
+++ b/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts
@@ -21,7 +21,8 @@
 //   (`ctx.config.includeHonoRoutes`, aggregated by the runner from a
 //   `routesFileHono` generator's `emitsHonoRoutes` marker).
 
-import { describe, test, expect, afterAll } from "bun:test";
+import { describe, test, expect, afterAll, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js";
 import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
 import { tmpdir } from "node:os";
 import { join, dirname } from "node:path";
@@ -41,6 +42,8 @@ import { buildRelationMap } from "../../src/relation-resolver.js";
 import { runGen, defineConfig } from "../../src/index.js";
 import type { Generator, GenContext, EmittedFile } from "../../src/generator.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const provider = frameworkTemplatesProvider;
 
 // A simple CRUD entity (PK `id`, one required string field) — enough to exercise
diff --git a/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts b/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts
index b88f82d2d2..cc37b17e95 100644
--- a/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts
+++ b/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts
@@ -15,7 +15,8 @@
 // files AGAINST the REAL generated entity modules — NO hand-written payloads.ts.
 // The payload import must RESOLVE (no TS2307) and the payload type must be found.
 
-import { describe, test, expect, afterAll } from "bun:test";
+import { describe, test, expect, afterAll, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js";
 import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
 import { tmpdir } from "node:os";
 import { join, dirname } from "node:path";
@@ -31,6 +32,8 @@ import { buildRelationMap } from "../../src/relation-resolver.js";
 import type { GenContext, EmittedFile } from "../../src/generator.js";
 import type { Provider } from "@metaobjectsdev/render";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 // A nested payload graph that exercises the multi-VO import grouping:
 //   Order (root) -> Customer (single nested), Line (array-of-objects),
 //   plus an inline enum `priority` (union alias OWNED BY Order's module).
diff --git a/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts b/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts
index 5a57bb213d..ecb2b1f003 100644
--- a/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts
@@ -8,7 +8,8 @@
 // on both. Proven the only way that counts: a caller module reading nested members through
 // the generated finder, compiled against the generated tree with the real TS compiler.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -21,6 +22,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import type { EmittedFile, GenContext } from "../src/generator.js";
 import type { Dialect } from "../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const MODEL = {
   "metadata.root": {
     package: "rentals",
diff --git a/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts b/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts
index 9285c0ac80..109a544397 100644
--- a/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts
+++ b/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts
@@ -11,7 +11,8 @@
 // physical name must be ABSENT from the child's artifact. A positive-only assertion would
 // pass just as well for a generator that emitted both the spread AND the restated literal,
 // which is the outcome this change exists to prevent.
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, rmSync, readdirSync, readFileSync, statSync } from "node:fs";
 import { tmpdir } from "node:os";
 import { join, relative } from "node:path";
@@ -21,6 +22,8 @@ import { runGen, defineConfig } from "../src/index.js";
 import { namesFile } from "../src/generators/index.js";
 import { entityFile } from "../src/generators/entity-file.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const MODEL = {
   "metadata.root": {
     package: "acme",
diff --git a/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts b/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts
index 2edd302589..87c73b2e77 100644
--- a/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts
@@ -22,7 +22,8 @@
 // splitting them into separate fixtures is how a defect BETWEEN two emissions survives —
 // the assigned-PK bug lived exactly there, between the entity file and the queries file.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -36,6 +37,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import type { GenContext } from "../src/generator.js";
 import type { Dialect } from "../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 // Physical names deliberately unlike anything derivable, so a reading of the emitted
 // output can tell a reference from a re-derivation at a glance.
 const MODEL = {
diff --git a/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts b/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts
index 3d552eb161..81f69eca31 100644
--- a/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts
+++ b/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts
@@ -14,7 +14,8 @@
 // unresolved `../db` stub or an uninstalled optional `fastify` peer) are ignored;
 // only the extension errors this fix targets are asserted.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, rmSync, readdirSync, readFileSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -26,6 +27,8 @@ import { queriesFile } from "../src/generators/queries-file.js";
 import { routesFile } from "../src/generators/routes-file.js";
 import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const META = JSON.stringify({
   "metadata.root": {
     package: "acme::blog",
diff --git a/server/typescript/packages/codegen-ts/test/owned-composition-imports.test.ts b/server/typescript/packages/codegen-ts/test/owned-composition-imports.test.ts
index b9b74ec8d1..22152aa45a 100644
--- a/server/typescript/packages/codegen-ts/test/owned-composition-imports.test.ts
+++ b/server/typescript/packages/codegen-ts/test/owned-composition-imports.test.ts
@@ -1,8 +1,11 @@
-import { describe, expect, test } from "bun:test";
+import { describe, expect, test, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { readFileSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 /**
  * A composition an adopter OWNS may only call what the package exports.
  *
diff --git a/server/typescript/packages/codegen-ts/test/owned-generator-skew-compile.test.ts b/server/typescript/packages/codegen-ts/test/owned-generator-skew-compile.test.ts
index 516a81d527..73d850c2be 100644
--- a/server/typescript/packages/codegen-ts/test/owned-generator-skew-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/owned-generator-skew-compile.test.ts
@@ -13,7 +13,8 @@
 // Each mix of old/current entity and queries generators is generated and compiled with the
 // real TypeScript compiler.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, rmSync, readdirSync } from "node:fs";
 import { join, resolve } from "node:path";
 import ts from "typescript";
@@ -26,6 +27,8 @@ import { queriesFile as currentQueries } from "../src/reference/queries.js";
 import { entityFile as ownedEntity108 } from "./fixtures/owned-1.0.8/entity.js";
 import { queriesFile as ownedQueries108 } from "./fixtures/owned-1.0.8/queries.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const FIXTURES = ["autoset-timestamps.json", "extends-chain.json", "two-entities-fk.json", "cross-package-vo.json"];
 
 const MIXES: Array<{ label: string; generators: () => Generator[] }> = [
diff --git a/server/typescript/packages/codegen-ts/test/projection/compile.test.ts b/server/typescript/packages/codegen-ts/test/projection/compile.test.ts
index 534c40ca85..a1ee9330c7 100644
--- a/server/typescript/packages/codegen-ts/test/projection/compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/projection/compile.test.ts
@@ -7,7 +7,8 @@
 // DbContextCompileTests). Any read-only/writable inconsistency that produces
 // non-compiling output fails here, not just the one we already knew about.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -19,6 +20,8 @@ import { buildPkMap } from "../../src/pk-resolver.js";
 import { buildRelationMap } from "../../src/relation-resolver.js";
 import type { GenContext } from "../../src/generator.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 async function loadProjectionRoot() {
   const json = JSON.stringify({
     "metadata.root": {
diff --git a/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts b/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts
index e96a901c60..923d3c8f93 100644
--- a/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts
+++ b/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts
@@ -5,7 +5,8 @@
 // codec must be declared exactly once in that file. Declaring it on both sides is a
 // duplicate-identifier compile error, i.e. the same class of bug as emitting none.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -16,6 +17,8 @@ import { buildPkMap } from "../../src/pk-resolver.js";
 import { buildRelationMap } from "../../src/relation-resolver.js";
 import type { GenContext } from "../../src/generator.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 async function loadRoot() {
   const json = JSON.stringify({
     "metadata.root": {
diff --git a/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts b/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts
index 20eb413ae9..7f42bbc592 100644
--- a/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts
@@ -16,7 +16,8 @@
 // The read-view host, where the table and the view share one module and must not both
 // declare the codec, is covered by `int-enum-replica-view-no-dup.test.ts`.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -27,6 +28,8 @@ import { buildPkMap } from "../../src/pk-resolver.js";
 import { buildRelationMap } from "../../src/relation-resolver.js";
 import type { GenContext } from "../../src/generator.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const STATUS = {
   "@values": ["DRAFT", "BOOKED", "DELIVERED", "CANCELLED"],
   "@intValueMap": { DRAFT: 0, BOOKED: 10, DELIVERED: 30, CANCELLED: 90 },
diff --git a/server/typescript/packages/codegen-ts/test/projection/issue-214-read-half-compile.test.ts b/server/typescript/packages/codegen-ts/test/projection/issue-214-read-half-compile.test.ts
index 7fec7c2a64..d8eca4090e 100644
--- a/server/typescript/packages/codegen-ts/test/projection/issue-214-read-half-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/projection/issue-214-read-half-compile.test.ts
@@ -7,7 +7,8 @@
 // asserts the structure AND compiles the real generated output with tsc — the read
 // type + query code must type-check (`typeof view.$inferSelect`, the re-read, etc.).
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -22,6 +23,8 @@ import { queriesFile as refQueriesFile } from "../../src/reference/queries.js";
 import type { GenContext } from "../../src/generator.js";
 import type { Dialect } from "../../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 // Customer + a write-through Order (replica view v_order_with_customer, derived
 // customerName from Customer.name via the customer join).
 const META = JSON.stringify({
diff --git a/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts b/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts
index 88af9e562d..fd8b2e071e 100644
--- a/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts
@@ -12,7 +12,8 @@
 //   - a reference onto an ABSTRACT level of a TPH hierarchy imported a table const from a
 //     module that has none: the rows live in the discriminator base's table.
 
-import { describe, expect, test } from "bun:test";
+import { describe, expect, test, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -27,6 +28,8 @@ import { buildPkMap } from "../src/pk-resolver.js";
 import { buildRelationMap } from "../src/relation-resolver.js";
 import type { EmittedFile, GenContext } from "../src/generator.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const pk = { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } };
 
 const MODEL = {
diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts
index 32f99156a7..e33a1922c8 100644
--- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts
+++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts
@@ -2,7 +2,8 @@
 // produce BYTE-IDENTICAL output to the built-in generators they were relocated from.
 // The reference generators import only "@metaobjectsdev/codegen-ts" (the public engine);
 // if this passes, a consumer can copy them out and own them with no behavior change.
-import { describe, test, expect, beforeEach, afterEach } from "bun:test";
+import { describe, test, expect, beforeEach, afterEach, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { existsSync, mkdirSync, mkdtempSync, rmSync, readdirSync, readFileSync, cpSync, writeFileSync } from "node:fs";
 import { tmpdir } from "node:os";
 import { join, resolve } from "node:path";
@@ -80,6 +81,8 @@ import type { RequirementTestArgs, RequirementTestsOpts } from "../src/index.js"
 import { MetaDataLoader, InMemoryStringSource, isMetaSource, isReadOnlySource, type MetaObject } from "@metaobjectsdev/metadata";
 import { FileSource } from "@metaobjectsdev/metadata/core";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const FIXTURE_DIR = resolve(import.meta.dir, "fixtures");
 // test → codegen-ts → packages → typescript → server → repo root
 const REPO_FIXTURES = resolve(import.meta.dir, "..", "..", "..", "..", "..", "fixtures");
diff --git a/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts b/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts
index 87885cbf6a..8468dbac8d 100644
--- a/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts
+++ b/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts
@@ -18,7 +18,8 @@
 // The test compiles the output, plus a small hand-written repository that uses it the way a
 // document-store adopter would, with the real TypeScript compiler.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -30,6 +31,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import { isSourcelessEntity } from "../src/index.js";
 import type { GenContext } from "../src/generator.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const MODEL = {
   "metadata.root": {
     package: "shop",
diff --git a/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts b/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts
index b141107640..1daddff266 100644
--- a/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts
+++ b/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts
@@ -10,7 +10,8 @@
 // Both arms run through `runGen`, not through a hand-built RenderContext, so the whole
 // chain is under test: namesFile()'s `emitsNames` marker → the runner's aggregation →
 // ResolvedGenConfig.includeNames + RenderContext.includeNames → the template.
-import { describe, test, expect, beforeEach, afterEach } from "bun:test";
+import { describe, test, expect, beforeEach, afterEach, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js";
 import { existsSync, mkdtempSync, rmSync, readFileSync } from "node:fs";
 import { tmpdir } from "node:os";
 import { join, resolve } from "node:path";
@@ -23,6 +24,8 @@ import { entityFile } from "../../src/generators/entity-file.js";
 import { queriesFile } from "../../src/generators/queries-file.js";
 import type { ExtStyle } from "../../src/render-context.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const FIXTURE = resolve(import.meta.dir, "../fixtures/trainer-website-shape.json");
 
 const loader = new MetaDataLoader();
diff --git a/server/typescript/packages/codegen-ts/test/tph-cross-field.test.ts b/server/typescript/packages/codegen-ts/test/tph-cross-field.test.ts
index ef262f2004..c04a8a8146 100644
--- a/server/typescript/packages/codegen-ts/test/tph-cross-field.test.ts
+++ b/server/typescript/packages/codegen-ts/test/tph-cross-field.test.ts
@@ -11,7 +11,7 @@
 // kind = BIRTH) rejects a BIRTH row without a note and accepts every other row; a rule gated
 // on the discriminator reads the subtype's pinned value, so it holds on a body that omits it.
 
-import { describe, test, expect, afterEach } from "bun:test";
+import { describe, test, expect, afterEach, setDefaultTimeout } from "bun:test";
 import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs";
 import { join, dirname } from "node:path";
 import { pathToFileURL } from "node:url";
@@ -25,6 +25,9 @@ import { makeRenderContext } from "../src/render-context.js";
 import { buildPkMap } from "../src/pk-resolver.js";
 import { buildRelationMap } from "../src/relation-resolver.js";
 import type { EmittedFile, GenContext } from "../src/generator.js";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
+
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
 
 const MODEL = {
   "metadata.root": {
diff --git a/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts b/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts
index 5b77635c8e..0b4aed9155 100644
--- a/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts
+++ b/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts
@@ -15,7 +15,8 @@
 // base-declared and a subtype-declared field — the defect is not specific to the level
 // the field is declared at — and by compiling the tree, which is the symptom adopters saw.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs";
 import { join, dirname } from "node:path";
 import { pathToFileURL } from "node:url";
@@ -32,6 +33,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import type { EmittedFile, GenContext } from "../src/generator.js";
 import type { Dialect } from "../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const MODEL = {
   "metadata.root": {
     package: "demo",
diff --git a/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts b/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts
index e7aad98168..1ad356f36e 100644
--- a/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts
+++ b/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts
@@ -16,7 +16,8 @@
 // The model is TS-local on purpose, and mirrors migrate-ts's
 // `expected-schema-tph.test.ts`, which asserts the same FKs from the DDL side.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs";
 import { join, dirname } from "node:path";
 import ts from "typescript";
@@ -32,6 +33,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import type { EmittedFile, GenContext } from "../src/generator.js";
 import type { Dialect } from "../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const MODEL = {
   "metadata.root": {
     package: "demo",
diff --git a/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts b/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts
index 91c5947a0b..a997b0a855 100644
--- a/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts
@@ -10,7 +10,8 @@
 // module compiled against the generated tree with the real TS compiler — a correct call is
 // clean, a misspelt or missing field is an error at the call site.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -23,6 +24,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import type { EmittedFile, GenContext } from "../src/generator.js";
 import type { Dialect } from "../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 const MODEL = {
   "metadata.root": {
     package: "brew",
diff --git a/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts b/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts
index c738e0f94d..cac127ae11 100644
--- a/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts
+++ b/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts
@@ -14,7 +14,8 @@
 // by string-match. The entity carries a self-referential FK so the AnyPgColumn
 // annotation is actually emitted.
 
-import { describe, test, expect } from "bun:test";
+import { describe, test, expect, setDefaultTimeout } from "bun:test";
+import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js";
 import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
 import { join } from "node:path";
 import ts from "typescript";
@@ -26,6 +27,8 @@ import { buildRelationMap } from "../src/relation-resolver.js";
 import type { GenContext } from "../src/generator.js";
 import type { Dialect } from "../src/metaobjects-config.js";
 
+setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS);
+
 async function loadRoot() {
   const json = JSON.stringify({
     "metadata.root": {
diff --git a/server/typescript/packages/test-generators/src/templates/zod-validators.ts b/server/typescript/packages/test-generators/src/templates/zod-validators.ts
index 661966d8ea..917a215da5 100644
--- a/server/typescript/packages/test-generators/src/templates/zod-validators.ts
+++ b/server/typescript/packages/test-generators/src/templates/zod-validators.ts
@@ -16,8 +16,7 @@ import {
   FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_CURRENCY,
   FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DECIMAL, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT,
   FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP,
-  FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_UUID,
-  FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
+  FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
   VALIDATOR_SUBTYPE_REQUIRED, VALIDATOR_SUBTYPE_LENGTH, VALIDATOR_SUBTYPE_REGEX,
   VALIDATOR_SUBTYPE_NUMERIC, VALIDATOR_SUBTYPE_ARRAY,
   IDENTITY_ATTR_FIELDS, IDENTITY_ATTR_GENERATION,
@@ -278,6 +277,30 @@ const NUMERIC_SUBTYPES: ReadonlySet = new Set([
   FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY,
 ]);
 
+const ORDERED_SUBTYPES: ReadonlySet = new Set([
+  FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP,
+]);
+
+/** Subtypes with equality but no ordering: a pair of the same one may be tested with eq / ne. */
+const EQUALITY_SUBTYPES: ReadonlySet = new Set([
+  FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET,
+]);
+
+/** Whether a comparison between these two fields has a sound meaning, as in every port:
+ *  numerics compare with each other, strings and temporals only with their own subtype and
+ *  @localTime flag (a date against a timestamp, or an instant against a wall clock, compares
+ *  two differently shaped strings, which is meaningless),
+ *  and boolean, enum, uuid, uri and inet fields only test equality. Anything else is skipped, never rejected. */
+function crossComparable(left: MetaField, right: MetaField, opName: string): boolean {
+  const a = left.subType;
+  const b = right.subType;
+  if (NUMERIC_SUBTYPES.has(a) && NUMERIC_SUBTYPES.has(b)) return true;
+  if (a !== b) return false;
+  if ((left.attr(FIELD_ATTR_LOCAL_TIME) === true) !== (right.attr(FIELD_ATTR_LOCAL_TIME) === true)) return false;
+  if (ORDERED_SUBTYPES.has(a)) return true;
+  return (opName === "eq" || opName === "ne") && EQUALITY_SUBTYPES.has(a);
+}
+
 /** Names of the fields the INSERT-shaped schemas carry (same skip rules as the emitters). */
 function insertSchemaFieldNameSet(obj: MetaObject): Set {
   const autoGen = autoGenPkFieldNames(obj);
@@ -337,6 +360,7 @@ function crossFieldRefinementBody(obj: MetaObject): string[] {
         const opName = String(v.attr(VALIDATOR_ATTR_OP));
         const op = CROSS_FIELD_OPS[opName];
         if (!left || !right || !op || left.resolvedIsArray() || right.resolvedIsArray()) break;
+        if (!crossComparable(left, right, opName)) break;
         const numeric = NUMERIC_SUBTYPES.has(left.subType);
         const c = numeric
           ? "Number(l) - Number(r)"

From d2fa0f7d25e52a34db6fcba7a334809569d6a619 Mon Sep 17 00:00:00 2001
From: Doug Mealing 
Date: Wed, 4 Nov 2026 10:11:15 -0500
Subject: [PATCH 07/51] Add the data layer for a model explorer: explorer.json
 and its three inputs (#532)

* feat(explorer): the explorer.json data spine (P0)

The data a model explorer reads, built from port-neutral inputs only:

- `meta export --effective` writes the effective canonical JSON: every member and
  attribute a node inherits through `extends` is materialized on it.
- `meta verify --format json` carries `requirementLedger`, one row per requirement:
  digest, each @implementedBy link with the node the gate resolved it to, the
  findings against its path, and a clean/warn/error verdict from the gate.
- `meta gen` records the node a per-entity file was rendered from on its
  `.hashes.json` entry ({ hash, generatedBy, sourceNode }); `perEntity` stamps
  `EmittedFile.sourceNode`. Not named `generator`, which on the JVM is an
  ownership claim the orphan sweep acts on; JVM owner fields are preserved.
- `@metaobjectsdev/docs-site` exports `buildExplorer` / `serializeExplorer`:
  nodes, typed edges, ledger, generated files per node, derived slices
  (package, requirement subtree, prompt). Deterministic bytes.

Gated by the new fixtures/explorer-conformance/ corpus (expected.json checked
byte for byte; the committed inputs re-derived from the CLI). No metamodel
vocabulary change; metamodelVersion does not move.

* no-mistakes(review): Fix explorer id collisions and per-node ledger diagnostic matching

* no-mistakes(review): Keep diagnostic requirement node in WeakMap side table

* no-mistakes(review): apply reviewer inline fixes

* no-mistakes(review): Resolve ::Name refs in explorer builder; compact seed
---
 AGENTS.md                                     |   2 +-
 CHANGELOG.md                                  |  18 +
 docs/CONFORMANCE.md                           |  23 +-
 docs/README.md                                |   2 +
 docs/features/cli.md                          |   1 +
 docs/features/explorer-data.md                | 228 +++++
 docs/features/own-your-codegen.md             |   5 +
 docs/features/requirements.md                 |   5 +-
 examples/showcase/site-payload.json           |   2 +-
 fixtures/explorer-conformance/README.md       |  49 +
 .../explorer-conformance/shop/effective.json  | 348 +++++++
 .../explorer-conformance/shop/expected.json   | 936 ++++++++++++++++++
 .../explorer-conformance/shop/hashes.json     |  18 +
 .../shop/project/.metaobjects/config.json     |   4 +
 .../shop/project/metaobjects/meta.shop.json   | 186 ++++
 .../project/prompts/shop/order-note.mustache  |   1 +
 .../explorer-conformance/shop/verify.json     | 259 +++++
 .../packages/cli/src/commands/export.ts       |   7 +-
 .../packages/cli/src/commands/verify.ts       |  13 +
 server/typescript/packages/cli/src/index.ts   |   3 +
 .../typescript/packages/cli/src/lib/args.ts   |   4 +
 .../packages/cli/src/lib/requirement-check.ts |  28 +-
 .../cli/src/lib/requirement-ledger.ts         | 152 +++
 .../packages/cli/src/lib/requirement-lint.ts  |  29 +-
 .../cli/test/explorer-fixture.test.ts         | 149 +++
 .../cli/test/unit/args-export.test.ts         |  10 +-
 .../cli/test/unit/requirement-ledger.test.ts  |  67 ++
 .../packages/codegen-ts/src/generator.ts      |  17 +-
 .../packages/codegen-ts/src/index.ts          |   3 +-
 .../codegen-ts/src/overwrite-policy.ts        |  70 +-
 .../packages/codegen-ts/src/runner.ts         |  26 +-
 .../test/generated-provenance.test.ts         |  88 ++
 .../packages/docs-site/src/explorer/build.ts  | 404 ++++++++
 .../packages/docs-site/src/explorer/types.ts  | 121 +++
 .../packages/docs-site/src/index.ts           |  15 +
 .../docs-site/test/explorer-build.test.ts     | 125 +++
 36 files changed, 3376 insertions(+), 42 deletions(-)
 create mode 100644 docs/features/explorer-data.md
 create mode 100644 fixtures/explorer-conformance/README.md
 create mode 100644 fixtures/explorer-conformance/shop/effective.json
 create mode 100644 fixtures/explorer-conformance/shop/expected.json
 create mode 100644 fixtures/explorer-conformance/shop/hashes.json
 create mode 100644 fixtures/explorer-conformance/shop/project/.metaobjects/config.json
 create mode 100644 fixtures/explorer-conformance/shop/project/metaobjects/meta.shop.json
 create mode 100644 fixtures/explorer-conformance/shop/project/prompts/shop/order-note.mustache
 create mode 100644 fixtures/explorer-conformance/shop/verify.json
 create mode 100644 server/typescript/packages/cli/src/lib/requirement-ledger.ts
 create mode 100644 server/typescript/packages/cli/test/explorer-fixture.test.ts
 create mode 100644 server/typescript/packages/cli/test/unit/requirement-ledger.test.ts
 create mode 100644 server/typescript/packages/codegen-ts/test/generated-provenance.test.ts
 create mode 100644 server/typescript/packages/docs-site/src/explorer/build.ts
 create mode 100644 server/typescript/packages/docs-site/src/explorer/types.ts
 create mode 100644 server/typescript/packages/docs-site/test/explorer-build.test.ts

diff --git a/AGENTS.md b/AGENTS.md
index 254c95dc24..aad82fd874 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -71,7 +71,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/` (428 fixtures; 35 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/` (428 fixtures; 36 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 9d09f79179..42ce430fcf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -112,6 +112,24 @@ here.**
   and the `wire` setting, and a project on any port runs them through the Node `meta` CLI. They are
   reference helpers: opt-in, listed by `meta gen --list`, ejectable and gated by `verify --codegen`
   (ADR-0034 Amendment 10). Protobuf is not built. See `docs/features/contract-emitters.md`.
+- **The data spine for a model explorer.** These changes are data only. No screen reads the new
+  data yet.
+  - `meta export --effective` writes the effective canonical JSON. Every field, child and attribute
+    a node inherits through `extends` is written onto that node.
+  - `meta verify --format json` adds `requirementLedger`, one row per requirement. A row carries its
+    digest, each `@implementedBy` link with the node the gate resolved it to, the findings against
+    it, and a `clean`, `warn` or `error` verdict. Text output is unchanged.
+  - `meta gen` records, in `.hashes.json`, the node each per-entity file was rendered from:
+    `{ "hash", "generatedBy", "sourceNode" }`. `EmittedFile.sourceNode` lets an owned generator set
+    it, and `perEntity` sets it automatically. A file rendered from the whole model keeps the plain
+    hash entry. The field is not called `generator`, because on the JVM that word claims ownership.
+  - `@metaobjectsdev/docs-site` exports `buildExplorer` and `serializeExplorer`. Together they build a
+    deterministic `explorer.json` from those three inputs. The file holds nodes, typed edges, the
+    requirement ledger, the generated files for each node, and derived slices for each package,
+    requirement subtree and prompt.
+
+  Gated by the new `fixtures/explorer-conformance/` corpus. See `docs/features/explorer-data.md`.
+  No metamodel vocabulary changes, and `metamodelVersion` does not move.
 - **A recipe for checking an API change against the last release.** Emit the document at the last tag
   and at `HEAD`, then run oasdiff. See `docs/recipes/check-api-against-last-release.md`.
 - **A `pydantic` extra on the Python package.** `pip install "metaobjects[pydantic]"` installs
diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md
index 0addaf83d3..f7200848bc 100644
--- a/docs/CONFORMANCE.md
+++ b/docs/CONFORMANCE.md
@@ -1,6 +1,6 @@
 # Conformance coverage
 
-The MetaObjects standard ships **35 shared conformance corpora** under
+The MetaObjects standard ships **36 shared conformance corpora** under
 [`fixtures/`](../fixtures/). Every port runs every corpus that is *applicable to
 it* and asserts the same expected behaviour against the same fixtures. **This page
 is the inverse index**: fixture → feature doc + per-port pass status, and it is the
@@ -61,6 +61,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor
 | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (FR-044 — reporting vocabulary: what is lowered, what stays inert) | 1 model pair (`reporting/with` vs `reporting/without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ |
 | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — |
 | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 19 cases (14 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — |
+| [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — |
 
 A ✓ means the port runs the corpus green; an explicit `n / m` is used where a port
 carries a ledgered divergence. The two ledgered YAML fixtures are documented
@@ -610,12 +611,28 @@ message. The case list, with the rule each pins, is the
 (`server/typescript/packages/integration-tests/cube-live/cube-model.live.ts`) loads the same
 files into a real Cube.
 
+### `fixtures/explorer-conformance/` (1 case)
+
+The `shop` case → [features/explorer-data.md](features/explorer-data.md). Its `project/` is a
+small model with inheritance, a value object, a reference, a prompt with a payload and a reply,
+and a five-level requirement tree that has a resolved member claim, a dangling planned claim and a
+live requirement nothing implements. `effective.json` and `verify.json` are what
+`meta export --effective` and `meta verify --format json` write for it, `hashes.json` is a
+hand-written manifest with node provenance, and `expected.json` is the explorer document built
+from the three, compared byte for byte.
+
+**One port runs it:** TypeScript, in
+`server/typescript/packages/docs-site/test/explorer-build.test.ts` (the builder) and
+`server/typescript/packages/cli/test/explorer-fixture.test.ts` (the two committed inputs are
+what the CLI writes today). The builder reads no loader, so a port that writes the same effective
+JSON and verify payload feeds it unchanged.
+
 ## Orphaned fixtures (tested but not yet documented)
 
 The fixtures in the nine corpora mapped above (metamodel 428 + yaml 16 + verify 45
 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 +
-dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the
-`cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining
+dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance`, the
+`cube-model` corpus and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining
 corpora in the totals table gate tooling contracts (registry manifests, provider
 composition, agent context, docs emit) rather than user-facing metamodel behaviour,
 so they have no feature-doc row.
diff --git a/docs/README.md b/docs/README.md
index 181636b8dc..b710209043 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -47,6 +47,7 @@ docs/
 │   ├── reporting.md                 # dimensions, measures, segments, reports: vocabulary and load rules (FR-044)
 │   ├── contract-emitters.md         # the contract-schema and openapi generators: JSON Schema and OpenAPI for the REST contract (FR-022)
 │   ├── cube-export.md               # the cube-model generator: reporting vocabulary as Cube data-model files (FR-044)
+│   ├── explorer-data.md             # explorer.json and its inputs: export --effective, the verify ledger rows, manifest provenance
 │   └── own-your-codegen.md          # scaffold-and-own generator ownership (ADR-0034)
 └── ports/                       # one file per language/framework port
     ├── typescript.md
@@ -78,6 +79,7 @@ this tree is documentation, not the source of truth.
 | Keep Prisma as the ORM, with `schema.prisma` generated from the model and gated by `verify` (TypeScript) | [`recipes/prisma.md`](recipes/prisma.md) |
 | Publish the API as JSON Schema or OpenAPI, and check a change against the last release | [`features/contract-emitters.md`](features/contract-emitters.md), [`recipes/check-api-against-last-release.md`](recipes/check-api-against-last-release.md) |
 | Export the reporting vocabulary to Cube (`cube-model`: cubes, joins, rollups; the `cube` lane that checks it against a real Cube) | [`features/cube-export.md`](features/cube-export.md) |
+| Build the data a model explorer reads (`explorer.json` from `meta export --effective`, `meta verify --format json` and the generated-file manifest) | [`features/explorer-data.md`](features/explorer-data.md) |
 | Wire prompt construction (FR-004) | [`features/templates-and-payloads.md`](features/templates-and-payloads.md) |
 | Share a metadata shape across multiple instances (abstracts, `extends:`) | [`features/abstracts-and-inheritance.md`](features/abstracts-and-inheritance.md) |
 | Add a custom metamodel subtype or attribute to a downstream project | [`features/extending-with-providers.md`](features/extending-with-providers.md) + [`recipes/extending-metaobjects-with-providers.md`](recipes/extending-metaobjects-with-providers.md) |
diff --git a/docs/features/cli.md b/docs/features/cli.md
index b098c2c501..0e6d1de713 100644
--- a/docs/features/cli.md
+++ b/docs/features/cli.md
@@ -32,6 +32,7 @@ command surface splits in two:
 | **Codegen drift** (`verify --codegen`) | **Node `meta`** | `meta verify --codegen` | TS reference (ADR-0021 D2) — regen-to-temp + diff committed output |
 | **Template/prompt drift** (`verify --templates`) | **Node `meta`** | `meta verify --templates` | TS reference (ADR-0021 D2) — `{{field}}`↔payload; part of the bare-`verify` default |
 | **Vocabulary upgrade** (`upgrade`) | **Node `meta`** | `meta upgrade [--to ] [--apply]` | **any backend** — rewrites RETIRED metadata vocabulary (`@violation` → `@counterexample`, `@readOnly` → `@mutability`, dropping `@verifiedBy`) and resolves ATTRIBUTE CONTRADICTIONS (`@fields` beside `@expr` on an index key). Node-only because it edits the metadata documents themselves, which every port shares; a non-TS project runs `npx meta upgrade` against its own `metaobjects/`. **Canonical JSON and YAML alike.** Previews by default. Retirements needing a human decision are refused and the run exits non-zero, so CI cannot record a partial migration as finished |
+| **Model export** (`export`) | **Node `meta`** | `meta export [--effective] [--out ]` | the loaded model, overlays merged, as one canonical JSON document. `--effective` also writes every inherited field, child and attribute onto the node that inherits it, which is the input the [explorer builder](explorer-data.md) reads. The output is for reading: loading an effective document back would declare each inherited member twice |
 | **Vocabulary search** (`types`) | **Node `meta`** | `meta types [query]` | **any backend** — apropos/`kubectl explain` over the live metamodel registry (names + descriptions + when-to-use); the vocabulary is cross-port identical (registry-conformance) |
 | **Dependency sync** (`deps`) | **Node `meta`** | `meta deps sync \| check \| list` | **any backend** — resolves a declared metadata dependency (`path`, or an installed `npm` / `python` package) into a committed snapshot + lock (FR-023), so `sync`/`check`/`list` themselves stay Node-only regardless of your server language. TypeScript, Python and Java then LOAD that snapshot at every rung of their own source ladder (Kotlin loads through Java's loader and Maven plugin); C# loads the snapshot through `dotnet meta` (Phase 2 S6). On a project whose own metadata Node `meta` cannot read (a Maven `src/main/resources/metadata` directory, a C# metadata directory, or another port's vocabulary), `sync` and `check` prove the locked dependencies load together and say that the port's own `verify` is the full check. See [`metadata-dependencies.md`](metadata-dependencies.md) |
 | **Canonical format** (`fmt`) | every port | `meta fmt` / `dotnet meta fmt` / `mvn metaobjects:fmt` / `metaobjects fmt` | (#304) ships in **every** port — the canonical serializer already exists in all five, so formatting is local, not Node-only. `--check` lists non-canonical files and exits non-zero without changing anything. Formats each file STANDALONE — own-mode, declared-here layer only (ADR-0039); an `extends` onto another file's base is preserved as-is, never resolved or erred on; a file declaring `overlay: true` anywhere — whether or not a same-file base exists — is reported as skipped rather than merged (merging would drop the overlay marker, a structural change fmt never makes). A YAML file is always skipped — no canonical YAML emitter exists (ADR-0006). Before writing, every port reloads the whole project with the candidate swapped in and refuses the write unless the reloaded model's canonical form is byte-identical to the untouched baseline — fmt never changes meaning. See [Fixture corpus](#meta-fmt--canonical-formatting-304) below and `fixtures/fmt-conformance/README.md` |
diff --git a/docs/features/explorer-data.md b/docs/features/explorer-data.md
new file mode 100644
index 0000000000..fd55f77fa0
--- /dev/null
+++ b/docs/features/explorer-data.md
@@ -0,0 +1,228 @@
+# Explorer data: `explorer.json` and the three inputs it reads
+
+A model explorer shows one project so a reader can see what it does and how it was designed:
+the objects and how they connect, the prompts and what they send and get back, the requirement
+tree and whether each claim holds, and which generated files each node produced. All of that
+is read from one data file, `explorer.json`. This page documents that file and the three
+inputs it is built from.
+
+This is the data layer only. No screen reads it yet.
+
+## The inputs are port-neutral
+
+The builder (`buildExplorer` in `@metaobjectsdev/docs-site`) never loads metadata itself. It
+reads three documents:
+
+| Input | Produced by | What it contributes |
+| --- | --- | --- |
+| Effective canonical JSON | `meta export --effective` | nodes, inheritance, every model edge |
+| The verify payload | `meta verify --format json` | the requirement ledger, and the `implementedBy` / `supersededBy` edges |
+| The generated-file manifest | `.metaobjects/.gen-state/.hashes.json`, written by `meta gen` | which generated files each node produced |
+
+Only the first is required. Without the verify payload there is no `ledger` and no requirement
+claim edge; without the manifest there is no `generated` section.
+
+Because the builder reads no loader and no provider, it does not depend on which port wrote
+its inputs. Every port has a canonical serializer and writes the same manifest file.
+
+### `meta export --effective`
+
+```
+meta export --effective [--out ]
+```
+
+`meta export` writes the loaded model as one canonical JSON document, with overlays merged.
+By default each node holds only what it declares. With `--effective`, every field, child and
+attribute a node inherits through `extends` is written onto that node as well. An entity that
+extends `BaseEntity` then lists `id` and `createdAt` itself, and `extends` is still written,
+as the canonical fully-qualified name. Reference attributes (`@references`, `@objectRef`,
+`@payloadRef`, `@responseRef`) are written in their canonical form in both modes.
+
+The effective document is for reading, not for loading back. A loader reading it would see
+each inherited member twice, once on the base and once on the subtype.
+
+### `meta verify --format json`: `requirementLedger`
+
+When the model declares a requirement, the structured verify payload carries one
+`requirementLedger` row per `requirement.*` node, in document order, beside `requirementCounts`.
+The text output is unchanged. Each row states what the gate decided for that entry, so a reader
+does not have to infer "checked and clean" from a path that no diagnostic mentions.
+
+```json
+{
+  "path": "Shop.Checkout.Orders.Recorded.Quotable",
+  "package": "acme::shop",
+  "qualifiedPath": "acme::shop::Shop.Checkout.Orders.Recorded.Quotable",
+  "subType": "functional",
+  "level": 5,
+  "status": "live",
+  "digest": "<64 hex characters>",
+  "implementedBy": [
+    { "ref": "Order.reference", "resolves": true, "target": "acme::shop::Order.reference" }
+  ],
+  "diagnostics": [],
+  "verdict": "clean"
+}
+```
+
+| Field | Meaning |
+| --- | --- |
+| `path` | The dotted child-name address every diagnostic prints. |
+| `package` | The requirement's effective package, `""` when it has none. |
+| `qualifiedPath` | `::`. It is also the prefix of each generated requirement test's id, ` []`. |
+| `level`, `status`, `disposition` | As declared, and absent when not declared. |
+| `digest` | The same SHA-256 over the claim that each generated requirement test carries ([requirements.md](requirements.md)). |
+| `implementedBy` | Each link as written (`ref`), whether it resolves, and the node it resolves to (`target`): the object's resolution key, followed by `.` for a member. The gate's own resolver produces these values. |
+| `supersededBy` | The same, for `@supersededBy`; its `target` is the replacement's `qualifiedPath`. |
+| `diagnostics` | Every finding reported against this requirement, as `{ code, severity, source }`. `source` is `gate` when the finding can fail the build and `lint` when it cannot. |
+| `verdict` | From gate findings only: `error`, `warn`, or `clean`. |
+
+A finding that is not about a single requirement, such as an entity nobody claims, appears
+in `requirements.rows` and in no ledger row. The structured payload is TypeScript-only, as
+the rest of `--format json` is.
+
+### Node provenance in `.hashes.json`
+
+Each generated file now records the metadata node it was rendered from. A generator built with
+`perEntity` sets this automatically. An `EmittedFile` can also name its node directly with
+`sourceNode`, which is a node resolution key such as `acme::shop::Order`. `meta gen` then
+writes that file's manifest entry in object form:
+
+```json
+{
+  "src/generated/acme/shop/Order.ts": {
+    "hash": "",
+    "generatedBy": "entity",
+    "sourceNode": "acme::shop::Order"
+  },
+  "src/generated/index.ts": ""
+}
+```
+
+A file rendered from the whole model or a whole package keeps the plain `"": ""`
+form, so a project that writes only such files has an unchanged manifest. Every port's
+manifest reader takes `hash` from either form.
+
+The provenance field is named `generatedBy`, not `generator`. In a Java or Kotlin module's
+manifest, `generator` means that generator owns the file (ADR-0060), and the orphan sweep acts
+on that ownership. TypeScript does not make that claim. TypeScript is the only port that writes
+provenance today, and the JVM rewrites its manifest without these fields.
+
+## The `explorer.json` shape
+
+```ts
+interface ExplorerJson {
+  format: "metaobjects-explorer/1";
+  nodes: ExplorerNode[];
+  edges: ExplorerEdge[];
+  ledger?: ExplorerLedger;        // absent without a verify payload with requirements
+  generated?: ExplorerGenerated[]; // absent without a manifest
+  slices: ExplorerSlice[];
+}
+```
+
+The types are exported from `@metaobjectsdev/docs-site`. The `format` value changes when a field
+changes meaning or is removed. Adding a field does not change it.
+
+### `nodes`
+
+The output has one node for each top-level node (object, prompt, requirement) and one for
+each node nested inside one (field, identity, source, view, index, nested requirement).
+
+| Field | Meaning |
+| --- | --- |
+| `id` | A top-level node's id is `::`. A nested node's id is its parent's id followed by `.`, for example `acme::shop::Order.total`. A nested requirement's id equals its ledger row's `qualifiedPath`. A nested node with no name gets `#` in place of `.`. When siblings of different types share a name, the first one in the effective JSON keeps `.`, because that is the node a dotted `@implementedBy` reference such as `Order.id` resolves to. Each later one adds its type, for example `acme::shop::AuditEntry.id[identity.primary]`. |
+| `type`, `subType`, `name`, `package` | As in the model. `package` is the package of the top-level ancestor. |
+| `parent` | The id of the node it is nested in. A top-level node has no `parent`. |
+| `extends`, `abstract`, `isArray` | As in the effective JSON. |
+| `inheritedFrom` | Set on a member that came from a super. It holds the id of the object the member is declared on, meaning the topmost ancestor that has a member with the same type, name and body. A member redeclared with a different body belongs to the node itself. |
+| `attrs` | Every `@` attribute, without the `@`, with keys sorted. |
+
+Two nodes that would still share an id are an error: two top-level nodes with one name in one package, or two siblings with the same type and name. The builder throws and names the id.
+
+### `edges`
+
+Each edge is typed. An edge is emitted only when both its ends are nodes in the file.
+
+| `kind` | From → to | Source |
+| --- | --- | --- |
+| `extends` | node → its super | `extends` |
+| `references` | object → referenced object, `via` the `identity.reference` | `@references` |
+| `objectRef` | object → value or entity, `via` the `field.object` | `@objectRef` on a field |
+| `association` | object → target, `via` the `relationship.*` | `@objectRef` on a relationship |
+| `payload` | prompt → payload object | `@payloadRef` |
+| `reply` | prompt → reply object | `@responseRef` |
+| `contains` | requirement → nested requirement | nesting |
+| `implementedBy` | requirement → object or member | a ledger row's resolved `target` |
+| `supersededBy` | requirement → replacing requirement | a ledger row's resolved `target` |
+
+An `implementedBy` edge exists only when the verify payload resolved that link. The builder
+never matches names itself. A planned requirement that names a node that does not exist yet
+has a ledger row whose link is `"resolves": false`, and it has no edge.
+
+### `ledger`
+
+`counts` is `requirementCounts`, copied as is. `rows` holds the `requirementLedger` rows, each
+with a `node` id added. `diagnostics` is `requirements.rows`, copied as is: every gate and lint
+finding, including those about something other than a single requirement.
+
+### `generated`
+
+The manifest entries that carry `sourceNode`, grouped by node: `{ node, files: [{ path,
+generatedBy }] }`, sorted by node and then by path. A plain entry has no node and is left out.
+
+### `slices`
+
+Slices are named node sets that a view can open on. They are all derived from the model, so
+none needs to be written by hand:
+
+- `package:`: the top-level nodes of one package.
+- `requirement:`: one for every requirement that has nested requirements. It holds the
+  subtree, every node the subtree claims, and the object that owns each claimed member.
+- `prompt:`: one for every prompt. It holds the prompt, its payload and its reply.
+
+The design report also proposes slices saved by hand. Those belong in tool configuration,
+never in metadata, and are not built yet.
+
+### Determinism
+
+The same three inputs always produce the same bytes. Nodes are sorted by id. Edges are sorted
+by kind, then `from`, then `to`, then `via`, with duplicates removed. Slices are sorted by id,
+and ledger rows stay in the verify payload's order. `serializeExplorer` writes JSON indented
+two spaces, with one trailing newline. That makes the file safe to commit and diff.
+
+## Building it
+
+```ts
+import { readFileSync, writeFileSync } from "node:fs";
+import { buildExplorer, serializeExplorer } from "@metaobjectsdev/docs-site";
+
+const read = (f: string) => JSON.parse(readFileSync(f, "utf8"));
+writeFileSync("explorer.json", serializeExplorer(buildExplorer({
+  model: read("effective.json"),                        // meta export --effective --out effective.json
+  verify: read("verify.json"),                          // meta verify --format json > verify.json
+  manifest: read(".metaobjects/.gen-state/.hashes.json"),
+})));
+```
+
+A `verify` or `manifest` that is missing or malformed leaves its section out. A `model` that is
+not canonical metadata JSON makes the builder throw.
+
+## Not built yet
+
+- **`usage`**: which hand-written modules import a generated module. The design marks it
+  optional, and nothing builds it yet.
+- **Routes per node** in `generated`: the manifest records files, not the routes inside them.
+- **Provenance from the JVM, Python and C# generators.** Their manifests have no `sourceNode`
+  yet, so for those ports `generated` is empty.
+
+## Verified by
+
+- [`fixtures/explorer-conformance/shop/`](../../fixtures/explorer-conformance/shop/): a small
+  model with inheritance, a prompt, and a five-level requirement tree. Its `expected.json` is
+  checked byte for byte. `server/typescript/packages/cli/test/explorer-fixture.test.ts` checks
+  that the CLI still writes the committed `effective.json` and `verify.json`, and checks the
+  `requirementLedger` rows.
+- `server/typescript/packages/codegen-ts/test/generated-provenance.test.ts`: covers how
+  `perEntity` stamps each file, the object and plain manifest forms, and that JVM owner fields
+  are preserved.
diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md
index 8edc20fae2..0371bd297c 100644
--- a/docs/features/own-your-codegen.md
+++ b/docs/features/own-your-codegen.md
@@ -511,6 +511,11 @@ overwritten; an edited one is refused by name (`keep`, th
 replaced (`overwrite`). There is **no three-way merge**
 (TypeScript-only). **Commit the manifest.**
 
+A TypeScript entry can also carry the node the file was rendered from,
+`{ "hash", "generatedBy", "sourceNode" }`. That is provenance, not ownership, which is why it
+does not use the JVM's `generator` field. Every reader takes `hash` from either form. See
+[explorer-data.md](explorer-data.md#node-provenance-in-hashesjson).
+
 The `GENERATED` token in the header still matters at one moment: a file at a generated path
 that the manifest has no record of. A file that carries the token is taken as generated
 output (**adopted**: written fresh and recorded); one that does not is refused, whatever
diff --git a/docs/features/requirements.md b/docs/features/requirements.md
index 721c2ed79e..c7b7db9d34 100644
--- a/docs/features/requirements.md
+++ b/docs/features/requirements.md
@@ -397,7 +397,10 @@ A status with no entry is left out. When coverage is not measured the line ends
 counts the recorded gaps with no `@disposition`, when there are any. Then come the
 diagnostics, and when any is an error, `  error(s).` and a non-zero exit.
 TypeScript caps the warnings it prints at `--limit` (20 by default); the other ports print
-every one. The structured `--format json|toon` payload is TypeScript-only.
+every one. The structured `--format json|toon` payload is TypeScript-only. It carries one
+`requirementLedger` row per requirement: its digest, each `@implementedBy` link with the node
+it resolved to, the findings against it and a `clean` / `warn` / `error` verdict. See
+[explorer-data.md](explorer-data.md#meta-verify---format-json-requirementledger).
 
 **Metadata that does not load** is not a model with no requirement: `verify` fails on it in
 every port. The load errors are printed once. Where the drift gate that ran loaded the model,
diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json
index 0dc75bd7a6..7a98e03d80 100644
--- a/examples/showcase/site-payload.json
+++ b/examples/showcase/site-payload.json
@@ -8,7 +8,7 @@
   },
   "counts": {
     "fixtures": 428,
-    "corpora": 35,
+    "corpora": 36,
     "baseTypes": 17
   },
   "snippets": {
diff --git a/fixtures/explorer-conformance/README.md b/fixtures/explorer-conformance/README.md
new file mode 100644
index 0000000000..2dc475a8e7
--- /dev/null
+++ b/fixtures/explorer-conformance/README.md
@@ -0,0 +1,49 @@
+# explorer-conformance
+
+The `explorer.json` data spine: three port-neutral inputs in, one explorer document out,
+compared byte for byte. The shape is documented in
+[docs/features/explorer-data.md](../../docs/features/explorer-data.md).
+
+## `shop/`
+
+| File | What it is | How it is produced |
+| --- | --- | --- |
+| `project/` | A small project: an abstract `BaseEntity` two entities extend, a value object held by a `field.object`, an `identity.reference`, an index, an entity no requirement claims, a `template.prompt` with a payload and a reply, and a requirement tree five levels deep. | Hand-written. |
+| `effective.json` | The effective canonical JSON. | `meta export --effective` from `project/`. |
+| `verify.json` | The verify payload, with one `requirementLedger` row per requirement. | `meta verify --format json` from `project/`. |
+| `hashes.json` | A generated-file manifest: three entries carry node provenance, one is a plain hash. | Hand-written (the project wires no generators). |
+| `expected.json` | The explorer document. | `buildExplorer` over the three files above. |
+
+What the requirement tree exercises:
+
+- `Shop.Checkout.Orders.Recorded` claims two objects, and its child `Quotable` claims a member
+  (`Order.reference`), so the slice for `Recorded` also holds `Order`, the member's owner.
+- `Shop.Checkout.Orders.Refunded` is `planned` and names `Refund`, which does not exist: the
+  ledger row says the link does not resolve, and no edge is drawn.
+- `Shop.Checkout.Shipping` is `live` and nothing under it implements anything: its row's verdict
+  is `warn` (`WARN_REQUIREMENT_NOTHING_IMPLEMENTS`).
+- `AuditEntry` is claimed by nothing, which the gate reports with no requirement path; it lands
+  in `ledger.diagnostics` and in no row.
+- `AuditEntry` names its field and its primary identity both `id`. The field comes first and
+  keeps the id `acme::shop::AuditEntry.id`; the identity is `acme::shop::AuditEntry.id[identity.primary]`.
+
+## Regenerating
+
+From the repository root, after a deliberate change to either command's output or to the builder:
+
+```
+( cd fixtures/explorer-conformance/shop/project && \
+  bun ../../../../server/typescript/packages/cli/bin/meta.ts export --effective --out ../effective.json && \
+  bun ../../../../server/typescript/packages/cli/bin/meta.ts verify --format json > ../verify.json )
+```
+
+Then rebuild `expected.json` with `buildExplorer` and `serializeExplorer` from
+`@metaobjectsdev/docs-site`, and review the diff: every changed line is a change to what an
+explorer shows.
+
+## Who runs it
+
+- `server/typescript/packages/docs-site/test/explorer-build.test.ts`: the builder reproduces
+  `expected.json` from the committed inputs.
+- `server/typescript/packages/cli/test/explorer-fixture.test.ts`: the CLI still writes
+  `effective.json` and `verify.json` exactly, and the fresh inputs still build `expected.json`.
diff --git a/fixtures/explorer-conformance/shop/effective.json b/fixtures/explorer-conformance/shop/effective.json
new file mode 100644
index 0000000000..2b3a0fb71e
--- /dev/null
+++ b/fixtures/explorer-conformance/shop/effective.json
@@ -0,0 +1,348 @@
+{
+  "metadata.root": {
+    "package": "acme::shop",
+    "children": [
+      {
+        "object.entity": {
+          "name": "BaseEntity",
+          "abstract": true,
+          "children": [
+            {
+              "field.uuid": {
+                "name": "id"
+              }
+            },
+            {
+              "field.timestamp": {
+                "name": "createdAt"
+              }
+            },
+            {
+              "identity.primary": {
+                "name": "pk",
+                "@fields": [
+                  "id"
+                ]
+              }
+            }
+          ]
+        }
+      },
+      {
+        "object.value": {
+          "name": "Address",
+          "children": [
+            {
+              "field.string": {
+                "name": "street"
+              }
+            },
+            {
+              "field.string": {
+                "name": "city"
+              }
+            }
+          ]
+        }
+      },
+      {
+        "object.entity": {
+          "name": "Customer",
+          "extends": "acme::shop::BaseEntity",
+          "children": [
+            {
+              "field.uuid": {
+                "name": "id"
+              }
+            },
+            {
+              "field.timestamp": {
+                "name": "createdAt"
+              }
+            },
+            {
+              "identity.primary": {
+                "name": "pk",
+                "@fields": [
+                  "id"
+                ]
+              }
+            },
+            {
+              "field.string": {
+                "name": "name",
+                "@required": true
+              }
+            },
+            {
+              "field.string": {
+                "name": "email"
+              }
+            },
+            {
+              "field.object": {
+                "name": "shippingAddress",
+                "@objectRef": "acme::shop::Address"
+              }
+            },
+            {
+              "source.rdb": {
+                "name": "db",
+                "@table": "customers"
+              }
+            }
+          ]
+        }
+      },
+      {
+        "object.entity": {
+          "name": "Order",
+          "extends": "acme::shop::BaseEntity",
+          "children": [
+            {
+              "field.uuid": {
+                "name": "id"
+              }
+            },
+            {
+              "field.timestamp": {
+                "name": "createdAt"
+              }
+            },
+            {
+              "identity.primary": {
+                "name": "pk",
+                "@fields": [
+                  "id"
+                ]
+              }
+            },
+            {
+              "field.uuid": {
+                "name": "customerId"
+              }
+            },
+            {
+              "field.string": {
+                "name": "reference"
+              }
+            },
+            {
+              "field.decimal": {
+                "name": "total"
+              }
+            },
+            {
+              "field.enum": {
+                "name": "state",
+                "@values": [
+                  "OPEN",
+                  "PAID",
+                  "SHIPPED"
+                ]
+              }
+            },
+            {
+              "identity.reference": {
+                "name": "customerRef",
+                "@fields": [
+                  "customerId"
+                ],
+                "@references": "acme::shop::Customer"
+              }
+            },
+            {
+              "index.lookup": {
+                "name": "orderByCustomerId",
+                "@fields": [
+                  "customerId"
+                ]
+              }
+            },
+            {
+              "source.rdb": {
+                "name": "db",
+                "@table": "orders"
+              }
+            }
+          ]
+        }
+      },
+      {
+        "object.entity": {
+          "name": "AuditEntry",
+          "children": [
+            {
+              "field.uuid": {
+                "name": "id"
+              }
+            },
+            {
+              "identity.primary": {
+                "name": "id",
+                "@fields": [
+                  "id"
+                ]
+              }
+            },
+            {
+              "field.string": {
+                "name": "message"
+              }
+            },
+            {
+              "source.rdb": {
+                "name": "db",
+                "@table": "audit_entries"
+              }
+            }
+          ]
+        }
+      },
+      {
+        "object.value": {
+          "name": "OrderNoteRequest",
+          "children": [
+            {
+              "field.string": {
+                "name": "reference",
+                "@required": true
+              }
+            }
+          ]
+        }
+      },
+      {
+        "object.value": {
+          "name": "OrderNote",
+          "children": [
+            {
+              "field.string": {
+                "name": "text",
+                "@required": true
+              }
+            }
+          ]
+        }
+      },
+      {
+        "template.prompt": {
+          "name": "OrderNotePrompt",
+          "@format": "text",
+          "@payloadRef": "acme::shop::OrderNoteRequest",
+          "@responseFormat": "json",
+          "@responseRef": "acme::shop::OrderNote",
+          "@textRef": "shop/order-note"
+        }
+      },
+      {
+        "requirement.architectural": {
+          "name": "Addressable",
+          "@counterexample": "A row nobody can point at.",
+          "@implementedBy": [
+            "BaseEntity"
+          ],
+          "@statement": "Every stored row has a stable id.",
+          "@status": "live"
+        }
+      },
+      {
+        "requirement.functional": {
+          "name": "Shop",
+          "@counterexample": "A customer who cannot place an order.",
+          "@level": 1,
+          "@statement": "A customer can buy from the shop.",
+          "@status": "live",
+          "children": [
+            {
+              "requirement.functional": {
+                "name": "Checkout",
+                "@counterexample": "An order taken outside checkout.",
+                "@disposition": "deferred",
+                "@level": 2,
+                "@statement": "Orders are taken at checkout.",
+                "@status": "partial",
+                "@trackedBy": [
+                  "https://example.invalid/issues/1"
+                ],
+                "children": [
+                  {
+                    "requirement.functional": {
+                      "name": "Orders",
+                      "@counterexample": "A placed order that is lost.",
+                      "@level": 3,
+                      "@statement": "Every placed order is kept.",
+                      "@status": "live",
+                      "children": [
+                        {
+                          "requirement.functional": {
+                            "name": "Recorded",
+                            "@counterexample": "A placed order has no row.",
+                            "@implementedBy": [
+                              "Order",
+                              "Customer"
+                            ],
+                            "@level": 4,
+                            "@statement": "An order is recorded when it is placed.",
+                            "@status": "live",
+                            "children": [
+                              {
+                                "requirement.functional": {
+                                  "name": "Quotable",
+                                  "@counterexample": "An order nobody can quote back.",
+                                  "@implementedBy": [
+                                    "Order.reference"
+                                  ],
+                                  "@level": 5,
+                                  "@statement": "An order carries a reference the customer can quote.",
+                                  "@status": "live"
+                                }
+                              }
+                            ]
+                          }
+                        },
+                        {
+                          "requirement.functional": {
+                            "name": "Noted",
+                            "@counterexample": "An order with no note.",
+                            "@implementedBy": [
+                              "OrderNotePrompt"
+                            ],
+                            "@level": 4,
+                            "@statement": "A placed order gets a short note for the customer.",
+                            "@status": "live"
+                          }
+                        },
+                        {
+                          "requirement.functional": {
+                            "name": "Refunded",
+                            "@counterexample": "A paid order that cannot be refunded.",
+                            "@implementedBy": [
+                              "Refund"
+                            ],
+                            "@level": 4,
+                            "@statement": "A paid order can be refunded.",
+                            "@status": "planned"
+                          }
+                        }
+                      ]
+                    }
+                  },
+                  {
+                    "requirement.functional": {
+                      "name": "Shipping",
+                      "@counterexample": "A paid order that never ships.",
+                      "@level": 3,
+                      "@statement": "A paid order is shipped.",
+                      "@status": "live"
+                    }
+                  }
+                ]
+              }
+            }
+          ]
+        }
+      }
+    ]
+  }
+}
diff --git a/fixtures/explorer-conformance/shop/expected.json b/fixtures/explorer-conformance/shop/expected.json
new file mode 100644
index 0000000000..d28845d4f2
--- /dev/null
+++ b/fixtures/explorer-conformance/shop/expected.json
@@ -0,0 +1,936 @@
+{
+  "format": "metaobjects-explorer/1",
+  "nodes": [
+    {
+      "id": "acme::shop::Address",
+      "type": "object",
+      "subType": "value",
+      "name": "Address",
+      "package": "acme::shop",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::Address.city",
+      "type": "field",
+      "subType": "string",
+      "name": "city",
+      "package": "acme::shop",
+      "parent": "acme::shop::Address",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::Address.street",
+      "type": "field",
+      "subType": "string",
+      "name": "street",
+      "package": "acme::shop",
+      "parent": "acme::shop::Address",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::Addressable",
+      "type": "requirement",
+      "subType": "architectural",
+      "name": "Addressable",
+      "package": "acme::shop",
+      "attrs": {
+        "counterexample": "A row nobody can point at.",
+        "implementedBy": [
+          "BaseEntity"
+        ],
+        "statement": "Every stored row has a stable id.",
+        "status": "live"
+      }
+    },
+    {
+      "id": "acme::shop::AuditEntry",
+      "type": "object",
+      "subType": "entity",
+      "name": "AuditEntry",
+      "package": "acme::shop",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::AuditEntry.db",
+      "type": "source",
+      "subType": "rdb",
+      "name": "db",
+      "package": "acme::shop",
+      "parent": "acme::shop::AuditEntry",
+      "attrs": {
+        "table": "audit_entries"
+      }
+    },
+    {
+      "id": "acme::shop::AuditEntry.id",
+      "type": "field",
+      "subType": "uuid",
+      "name": "id",
+      "package": "acme::shop",
+      "parent": "acme::shop::AuditEntry",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::AuditEntry.id[identity.primary]",
+      "type": "identity",
+      "subType": "primary",
+      "name": "id",
+      "package": "acme::shop",
+      "parent": "acme::shop::AuditEntry",
+      "attrs": {
+        "fields": [
+          "id"
+        ]
+      }
+    },
+    {
+      "id": "acme::shop::AuditEntry.message",
+      "type": "field",
+      "subType": "string",
+      "name": "message",
+      "package": "acme::shop",
+      "parent": "acme::shop::AuditEntry",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::BaseEntity",
+      "type": "object",
+      "subType": "entity",
+      "name": "BaseEntity",
+      "package": "acme::shop",
+      "abstract": true,
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::BaseEntity.createdAt",
+      "type": "field",
+      "subType": "timestamp",
+      "name": "createdAt",
+      "package": "acme::shop",
+      "parent": "acme::shop::BaseEntity",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::BaseEntity.id",
+      "type": "field",
+      "subType": "uuid",
+      "name": "id",
+      "package": "acme::shop",
+      "parent": "acme::shop::BaseEntity",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::BaseEntity.pk",
+      "type": "identity",
+      "subType": "primary",
+      "name": "pk",
+      "package": "acme::shop",
+      "parent": "acme::shop::BaseEntity",
+      "attrs": {
+        "fields": [
+          "id"
+        ]
+      }
+    },
+    {
+      "id": "acme::shop::Customer",
+      "type": "object",
+      "subType": "entity",
+      "name": "Customer",
+      "package": "acme::shop",
+      "extends": "acme::shop::BaseEntity",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::Customer.createdAt",
+      "type": "field",
+      "subType": "timestamp",
+      "name": "createdAt",
+      "package": "acme::shop",
+      "parent": "acme::shop::Customer",
+      "attrs": {},
+      "inheritedFrom": "acme::shop::BaseEntity"
+    },
+    {
+      "id": "acme::shop::Customer.db",
+      "type": "source",
+      "subType": "rdb",
+      "name": "db",
+      "package": "acme::shop",
+      "parent": "acme::shop::Customer",
+      "attrs": {
+        "table": "customers"
+      }
+    },
+    {
+      "id": "acme::shop::Customer.email",
+      "type": "field",
+      "subType": "string",
+      "name": "email",
+      "package": "acme::shop",
+      "parent": "acme::shop::Customer",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::Customer.id",
+      "type": "field",
+      "subType": "uuid",
+      "name": "id",
+      "package": "acme::shop",
+      "parent": "acme::shop::Customer",
+      "attrs": {},
+      "inheritedFrom": "acme::shop::BaseEntity"
+    },
+    {
+      "id": "acme::shop::Customer.name",
+      "type": "field",
+      "subType": "string",
+      "name": "name",
+      "package": "acme::shop",
+      "parent": "acme::shop::Customer",
+      "attrs": {
+        "required": true
+      }
+    },
+    {
+      "id": "acme::shop::Customer.pk",
+      "type": "identity",
+      "subType": "primary",
+      "name": "pk",
+      "package": "acme::shop",
+      "parent": "acme::shop::Customer",
+      "attrs": {
+        "fields": [
+          "id"
+        ]
+      },
+      "inheritedFrom": "acme::shop::BaseEntity"
+    },
+    {
+      "id": "acme::shop::Customer.shippingAddress",
+      "type": "field",
+      "subType": "object",
+      "name": "shippingAddress",
+      "package": "acme::shop",
+      "parent": "acme::shop::Customer",
+      "attrs": {
+        "objectRef": "acme::shop::Address"
+      }
+    },
+    {
+      "id": "acme::shop::Order",
+      "type": "object",
+      "subType": "entity",
+      "name": "Order",
+      "package": "acme::shop",
+      "extends": "acme::shop::BaseEntity",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::Order.createdAt",
+      "type": "field",
+      "subType": "timestamp",
+      "name": "createdAt",
+      "package": "acme::shop",
+      "parent": "acme::shop::Order",
+      "attrs": {},
+      "inheritedFrom": "acme::shop::BaseEntity"
+    },
+    {
+      "id": "acme::shop::Order.customerId",
+      "type": "field",
+      "subType": "uuid",
+      "name": "customerId",
+      "package": "acme::shop",
+      "parent": "acme::shop::Order",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::Order.customerRef",
+      "type": "identity",
+      "subType": "reference",
+      "name": "customerRef",
+      "package": "acme::shop",
+      "parent": "acme::shop::Order",
+      "attrs": {
+        "fields": [
+          "customerId"
+        ],
+        "references": "acme::shop::Customer"
+      }
+    },
+    {
+      "id": "acme::shop::Order.db",
+      "type": "source",
+      "subType": "rdb",
+      "name": "db",
+      "package": "acme::shop",
+      "parent": "acme::shop::Order",
+      "attrs": {
+        "table": "orders"
+      }
+    },
+    {
+      "id": "acme::shop::Order.id",
+      "type": "field",
+      "subType": "uuid",
+      "name": "id",
+      "package": "acme::shop",
+      "parent": "acme::shop::Order",
+      "attrs": {},
+      "inheritedFrom": "acme::shop::BaseEntity"
+    },
+    {
+      "id": "acme::shop::Order.orderByCustomerId",
+      "type": "index",
+      "subType": "lookup",
+      "name": "orderByCustomerId",
+      "package": "acme::shop",
+      "parent": "acme::shop::Order",
+      "attrs": {
+        "fields": [
+          "customerId"
+        ]
+      }
+    },
+    {
+      "id": "acme::shop::Order.pk",
+      "type": "identity",
+      "subType": "primary",
+      "name": "pk",
+      "package": "acme::shop",
+      "parent": "acme::shop::Order",
+      "attrs": {
+        "fields": [
+          "id"
+        ]
+      },
+      "inheritedFrom": "acme::shop::BaseEntity"
+    },
+    {
+      "id": "acme::shop::Order.reference",
+      "type": "field",
+      "subType": "string",
+      "name": "reference",
+      "package": "acme::shop",
+      "parent": "acme::shop::Order",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::Order.state",
+      "type": "field",
+      "subType": "enum",
+      "name": "state",
+      "package": "acme::shop",
+      "parent": "acme::shop::Order",
+      "attrs": {
+        "values": [
+          "OPEN",
+          "PAID",
+          "SHIPPED"
+        ]
+      }
+    },
+    {
+      "id": "acme::shop::Order.total",
+      "type": "field",
+      "subType": "decimal",
+      "name": "total",
+      "package": "acme::shop",
+      "parent": "acme::shop::Order",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::OrderNote",
+      "type": "object",
+      "subType": "value",
+      "name": "OrderNote",
+      "package": "acme::shop",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::OrderNote.text",
+      "type": "field",
+      "subType": "string",
+      "name": "text",
+      "package": "acme::shop",
+      "parent": "acme::shop::OrderNote",
+      "attrs": {
+        "required": true
+      }
+    },
+    {
+      "id": "acme::shop::OrderNotePrompt",
+      "type": "template",
+      "subType": "prompt",
+      "name": "OrderNotePrompt",
+      "package": "acme::shop",
+      "attrs": {
+        "format": "text",
+        "payloadRef": "acme::shop::OrderNoteRequest",
+        "responseFormat": "json",
+        "responseRef": "acme::shop::OrderNote",
+        "textRef": "shop/order-note"
+      }
+    },
+    {
+      "id": "acme::shop::OrderNoteRequest",
+      "type": "object",
+      "subType": "value",
+      "name": "OrderNoteRequest",
+      "package": "acme::shop",
+      "attrs": {}
+    },
+    {
+      "id": "acme::shop::OrderNoteRequest.reference",
+      "type": "field",
+      "subType": "string",
+      "name": "reference",
+      "package": "acme::shop",
+      "parent": "acme::shop::OrderNoteRequest",
+      "attrs": {
+        "required": true
+      }
+    },
+    {
+      "id": "acme::shop::Shop",
+      "type": "requirement",
+      "subType": "functional",
+      "name": "Shop",
+      "package": "acme::shop",
+      "attrs": {
+        "counterexample": "A customer who cannot place an order.",
+        "level": 1,
+        "statement": "A customer can buy from the shop.",
+        "status": "live"
+      }
+    },
+    {
+      "id": "acme::shop::Shop.Checkout",
+      "type": "requirement",
+      "subType": "functional",
+      "name": "Checkout",
+      "package": "acme::shop",
+      "parent": "acme::shop::Shop",
+      "attrs": {
+        "counterexample": "An order taken outside checkout.",
+        "disposition": "deferred",
+        "level": 2,
+        "statement": "Orders are taken at checkout.",
+        "status": "partial",
+        "trackedBy": [
+          "https://example.invalid/issues/1"
+        ]
+      }
+    },
+    {
+      "id": "acme::shop::Shop.Checkout.Orders",
+      "type": "requirement",
+      "subType": "functional",
+      "name": "Orders",
+      "package": "acme::shop",
+      "parent": "acme::shop::Shop.Checkout",
+      "attrs": {
+        "counterexample": "A placed order that is lost.",
+        "level": 3,
+        "statement": "Every placed order is kept.",
+        "status": "live"
+      }
+    },
+    {
+      "id": "acme::shop::Shop.Checkout.Orders.Noted",
+      "type": "requirement",
+      "subType": "functional",
+      "name": "Noted",
+      "package": "acme::shop",
+      "parent": "acme::shop::Shop.Checkout.Orders",
+      "attrs": {
+        "counterexample": "An order with no note.",
+        "implementedBy": [
+          "OrderNotePrompt"
+        ],
+        "level": 4,
+        "statement": "A placed order gets a short note for the customer.",
+        "status": "live"
+      }
+    },
+    {
+      "id": "acme::shop::Shop.Checkout.Orders.Recorded",
+      "type": "requirement",
+      "subType": "functional",
+      "name": "Recorded",
+      "package": "acme::shop",
+      "parent": "acme::shop::Shop.Checkout.Orders",
+      "attrs": {
+        "counterexample": "A placed order has no row.",
+        "implementedBy": [
+          "Order",
+          "Customer"
+        ],
+        "level": 4,
+        "statement": "An order is recorded when it is placed.",
+        "status": "live"
+      }
+    },
+    {
+      "id": "acme::shop::Shop.Checkout.Orders.Recorded.Quotable",
+      "type": "requirement",
+      "subType": "functional",
+      "name": "Quotable",
+      "package": "acme::shop",
+      "parent": "acme::shop::Shop.Checkout.Orders.Recorded",
+      "attrs": {
+        "counterexample": "An order nobody can quote back.",
+        "implementedBy": [
+          "Order.reference"
+        ],
+        "level": 5,
+        "statement": "An order carries a reference the customer can quote.",
+        "status": "live"
+      }
+    },
+    {
+      "id": "acme::shop::Shop.Checkout.Orders.Refunded",
+      "type": "requirement",
+      "subType": "functional",
+      "name": "Refunded",
+      "package": "acme::shop",
+      "parent": "acme::shop::Shop.Checkout.Orders",
+      "attrs": {
+        "counterexample": "A paid order that cannot be refunded.",
+        "implementedBy": [
+          "Refund"
+        ],
+        "level": 4,
+        "statement": "A paid order can be refunded.",
+        "status": "planned"
+      }
+    },
+    {
+      "id": "acme::shop::Shop.Checkout.Shipping",
+      "type": "requirement",
+      "subType": "functional",
+      "name": "Shipping",
+      "package": "acme::shop",
+      "parent": "acme::shop::Shop.Checkout",
+      "attrs": {
+        "counterexample": "A paid order that never ships.",
+        "level": 3,
+        "statement": "A paid order is shipped.",
+        "status": "live"
+      }
+    }
+  ],
+  "edges": [
+    {
+      "kind": "contains",
+      "from": "acme::shop::Shop",
+      "to": "acme::shop::Shop.Checkout"
+    },
+    {
+      "kind": "contains",
+      "from": "acme::shop::Shop.Checkout",
+      "to": "acme::shop::Shop.Checkout.Orders"
+    },
+    {
+      "kind": "contains",
+      "from": "acme::shop::Shop.Checkout",
+      "to": "acme::shop::Shop.Checkout.Shipping"
+    },
+    {
+      "kind": "contains",
+      "from": "acme::shop::Shop.Checkout.Orders",
+      "to": "acme::shop::Shop.Checkout.Orders.Noted"
+    },
+    {
+      "kind": "contains",
+      "from": "acme::shop::Shop.Checkout.Orders",
+      "to": "acme::shop::Shop.Checkout.Orders.Recorded"
+    },
+    {
+      "kind": "contains",
+      "from": "acme::shop::Shop.Checkout.Orders",
+      "to": "acme::shop::Shop.Checkout.Orders.Refunded"
+    },
+    {
+      "kind": "contains",
+      "from": "acme::shop::Shop.Checkout.Orders.Recorded",
+      "to": "acme::shop::Shop.Checkout.Orders.Recorded.Quotable"
+    },
+    {
+      "kind": "extends",
+      "from": "acme::shop::Customer",
+      "to": "acme::shop::BaseEntity"
+    },
+    {
+      "kind": "extends",
+      "from": "acme::shop::Order",
+      "to": "acme::shop::BaseEntity"
+    },
+    {
+      "kind": "implementedBy",
+      "from": "acme::shop::Addressable",
+      "to": "acme::shop::BaseEntity"
+    },
+    {
+      "kind": "implementedBy",
+      "from": "acme::shop::Shop.Checkout.Orders.Noted",
+      "to": "acme::shop::OrderNotePrompt"
+    },
+    {
+      "kind": "implementedBy",
+      "from": "acme::shop::Shop.Checkout.Orders.Recorded",
+      "to": "acme::shop::Customer"
+    },
+    {
+      "kind": "implementedBy",
+      "from": "acme::shop::Shop.Checkout.Orders.Recorded",
+      "to": "acme::shop::Order"
+    },
+    {
+      "kind": "implementedBy",
+      "from": "acme::shop::Shop.Checkout.Orders.Recorded.Quotable",
+      "to": "acme::shop::Order.reference"
+    },
+    {
+      "kind": "objectRef",
+      "from": "acme::shop::Customer",
+      "to": "acme::shop::Address",
+      "via": "acme::shop::Customer.shippingAddress"
+    },
+    {
+      "kind": "payload",
+      "from": "acme::shop::OrderNotePrompt",
+      "to": "acme::shop::OrderNoteRequest"
+    },
+    {
+      "kind": "references",
+      "from": "acme::shop::Order",
+      "to": "acme::shop::Customer",
+      "via": "acme::shop::Order.customerRef"
+    },
+    {
+      "kind": "reply",
+      "from": "acme::shop::OrderNotePrompt",
+      "to": "acme::shop::OrderNote"
+    }
+  ],
+  "ledger": {
+    "counts": {
+      "total": 9,
+      "functional": 8,
+      "architectural": 1,
+      "byStatus": [
+        {
+          "status": "planned",
+          "count": 1
+        },
+        {
+          "status": "live",
+          "count": 7
+        },
+        {
+          "status": "partial",
+          "count": 1
+        }
+      ],
+      "undecided": 1,
+      "entitiesClaimed": 2,
+      "entitiesTotal": 3,
+      "metadataFiles": 1
+    },
+    "rows": [
+      {
+        "node": "acme::shop::Addressable",
+        "path": "Addressable",
+        "package": "acme::shop",
+        "qualifiedPath": "acme::shop::Addressable",
+        "subType": "architectural",
+        "status": "live",
+        "digest": "c22897fd7559820a2a7a69bae54353900122be23f3d0058e9ec2b6195ae840e1",
+        "implementedBy": [
+          {
+            "ref": "BaseEntity",
+            "resolves": true,
+            "target": "acme::shop::BaseEntity"
+          }
+        ],
+        "diagnostics": [],
+        "verdict": "clean"
+      },
+      {
+        "node": "acme::shop::Shop",
+        "path": "Shop",
+        "package": "acme::shop",
+        "qualifiedPath": "acme::shop::Shop",
+        "subType": "functional",
+        "level": 1,
+        "status": "live",
+        "digest": "edc8a9b8159eb03a08d020427683253d6d1471032e0cf48115956362fc121653",
+        "implementedBy": [],
+        "diagnostics": [],
+        "verdict": "clean"
+      },
+      {
+        "node": "acme::shop::Shop.Checkout",
+        "path": "Shop.Checkout",
+        "package": "acme::shop",
+        "qualifiedPath": "acme::shop::Shop.Checkout",
+        "subType": "functional",
+        "level": 2,
+        "status": "partial",
+        "disposition": "deferred",
+        "digest": "111b8c39a19c717933fdd529af808540a27c0592406d0a792c524960ac775a2d",
+        "implementedBy": [],
+        "diagnostics": [],
+        "verdict": "clean"
+      },
+      {
+        "node": "acme::shop::Shop.Checkout.Orders",
+        "path": "Shop.Checkout.Orders",
+        "package": "acme::shop",
+        "qualifiedPath": "acme::shop::Shop.Checkout.Orders",
+        "subType": "functional",
+        "level": 3,
+        "status": "live",
+        "digest": "e84c69fda54cb9f04f3949af069c2c5d56027e008be3198a08c4ee4fbcad8be6",
+        "implementedBy": [],
+        "diagnostics": [],
+        "verdict": "clean"
+      },
+      {
+        "node": "acme::shop::Shop.Checkout.Orders.Recorded",
+        "path": "Shop.Checkout.Orders.Recorded",
+        "package": "acme::shop",
+        "qualifiedPath": "acme::shop::Shop.Checkout.Orders.Recorded",
+        "subType": "functional",
+        "level": 4,
+        "status": "live",
+        "digest": "6feebe1e415dda976cc6843c4546c1541b25e8ee44b85316811bfdb177f77635",
+        "implementedBy": [
+          {
+            "ref": "Order",
+            "resolves": true,
+            "target": "acme::shop::Order"
+          },
+          {
+            "ref": "Customer",
+            "resolves": true,
+            "target": "acme::shop::Customer"
+          }
+        ],
+        "diagnostics": [],
+        "verdict": "clean"
+      },
+      {
+        "node": "acme::shop::Shop.Checkout.Orders.Recorded.Quotable",
+        "path": "Shop.Checkout.Orders.Recorded.Quotable",
+        "package": "acme::shop",
+        "qualifiedPath": "acme::shop::Shop.Checkout.Orders.Recorded.Quotable",
+        "subType": "functional",
+        "level": 5,
+        "status": "live",
+        "digest": "b5d7fb7a9657bfda7b30e2629617bf5c56e4337ef7a06abfe55715613ecdda63",
+        "implementedBy": [
+          {
+            "ref": "Order.reference",
+            "resolves": true,
+            "target": "acme::shop::Order.reference"
+          }
+        ],
+        "diagnostics": [],
+        "verdict": "clean"
+      },
+      {
+        "node": "acme::shop::Shop.Checkout.Orders.Noted",
+        "path": "Shop.Checkout.Orders.Noted",
+        "package": "acme::shop",
+        "qualifiedPath": "acme::shop::Shop.Checkout.Orders.Noted",
+        "subType": "functional",
+        "level": 4,
+        "status": "live",
+        "digest": "45ed514b57928304f2d8b7c69e4cc3e5196cd8131ea57bc5ececc8056f52b995",
+        "implementedBy": [
+          {
+            "ref": "OrderNotePrompt",
+            "resolves": true,
+            "target": "acme::shop::OrderNotePrompt"
+          }
+        ],
+        "diagnostics": [],
+        "verdict": "clean"
+      },
+      {
+        "node": "acme::shop::Shop.Checkout.Orders.Refunded",
+        "path": "Shop.Checkout.Orders.Refunded",
+        "package": "acme::shop",
+        "qualifiedPath": "acme::shop::Shop.Checkout.Orders.Refunded",
+        "subType": "functional",
+        "level": 4,
+        "status": "planned",
+        "digest": "dcaacae2ee305ce97e804148559dfe32c13dc69083ff736f09cab1b60a8d7a74",
+        "implementedBy": [
+          {
+            "ref": "Refund",
+            "resolves": false
+          }
+        ],
+        "diagnostics": [],
+        "verdict": "clean"
+      },
+      {
+        "node": "acme::shop::Shop.Checkout.Shipping",
+        "path": "Shop.Checkout.Shipping",
+        "package": "acme::shop",
+        "qualifiedPath": "acme::shop::Shop.Checkout.Shipping",
+        "subType": "functional",
+        "level": 3,
+        "status": "live",
+        "digest": "d7d26a3dd5661647327cec62f969b61c74346e1df1e954de4d8392705bdecf31",
+        "implementedBy": [],
+        "diagnostics": [
+          {
+            "code": "WARN_REQUIREMENT_NOTHING_IMPLEMENTS",
+            "severity": "warn",
+            "source": "gate"
+          }
+        ],
+        "verdict": "warn"
+      }
+    ],
+    "diagnostics": [
+      {
+        "code": "WARN_REQUIREMENT_NOTHING_IMPLEMENTS",
+        "path": "Shop.Checkout.Shipping",
+        "severity": "warn",
+        "source": "gate",
+        "message": "is 'live' but neither it nor anything nested under it names an implementing node. A functional requirement's check is existence — a subtree that claims nothing is a capability nobody built."
+      },
+      {
+        "code": "WARN_REQUIREMENT_OBJECT_UNCLAIMED",
+        "path": "",
+        "severity": "warn",
+        "source": "gate",
+        "message": "no requirement claims 'acme::shop::AuditEntry'. Add it to an L4 requirement's 'implementedBy'."
+      }
+    ]
+  },
+  "generated": [
+    {
+      "node": "acme::shop::Customer",
+      "files": [
+        {
+          "path": "src/generated/acme/shop/Customer.ts",
+          "generatedBy": "entity"
+        }
+      ]
+    },
+    {
+      "node": "acme::shop::Order",
+      "files": [
+        {
+          "path": "src/generated/acme/shop/Order.queries.ts",
+          "generatedBy": "queries"
+        },
+        {
+          "path": "src/generated/acme/shop/Order.ts",
+          "generatedBy": "entity"
+        }
+      ]
+    }
+  ],
+  "slices": [
+    {
+      "id": "package:acme::shop",
+      "kind": "package",
+      "anchor": "acme::shop",
+      "nodes": [
+        "acme::shop::Address",
+        "acme::shop::Addressable",
+        "acme::shop::AuditEntry",
+        "acme::shop::BaseEntity",
+        "acme::shop::Customer",
+        "acme::shop::Order",
+        "acme::shop::OrderNote",
+        "acme::shop::OrderNotePrompt",
+        "acme::shop::OrderNoteRequest",
+        "acme::shop::Shop"
+      ]
+    },
+    {
+      "id": "prompt:acme::shop::OrderNotePrompt",
+      "kind": "prompt",
+      "anchor": "acme::shop::OrderNotePrompt",
+      "nodes": [
+        "acme::shop::OrderNote",
+        "acme::shop::OrderNotePrompt",
+        "acme::shop::OrderNoteRequest"
+      ]
+    },
+    {
+      "id": "requirement:acme::shop::Shop",
+      "kind": "requirement",
+      "anchor": "acme::shop::Shop",
+      "nodes": [
+        "acme::shop::Customer",
+        "acme::shop::Order",
+        "acme::shop::Order.reference",
+        "acme::shop::OrderNotePrompt",
+        "acme::shop::Shop",
+        "acme::shop::Shop.Checkout",
+        "acme::shop::Shop.Checkout.Orders",
+        "acme::shop::Shop.Checkout.Orders.Noted",
+        "acme::shop::Shop.Checkout.Orders.Recorded",
+        "acme::shop::Shop.Checkout.Orders.Recorded.Quotable",
+        "acme::shop::Shop.Checkout.Orders.Refunded",
+        "acme::shop::Shop.Checkout.Shipping"
+      ]
+    },
+    {
+      "id": "requirement:acme::shop::Shop.Checkout",
+      "kind": "requirement",
+      "anchor": "acme::shop::Shop.Checkout",
+      "nodes": [
+        "acme::shop::Customer",
+        "acme::shop::Order",
+        "acme::shop::Order.reference",
+        "acme::shop::OrderNotePrompt",
+        "acme::shop::Shop.Checkout",
+        "acme::shop::Shop.Checkout.Orders",
+        "acme::shop::Shop.Checkout.Orders.Noted",
+        "acme::shop::Shop.Checkout.Orders.Recorded",
+        "acme::shop::Shop.Checkout.Orders.Recorded.Quotable",
+        "acme::shop::Shop.Checkout.Orders.Refunded",
+        "acme::shop::Shop.Checkout.Shipping"
+      ]
+    },
+    {
+      "id": "requirement:acme::shop::Shop.Checkout.Orders",
+      "kind": "requirement",
+      "anchor": "acme::shop::Shop.Checkout.Orders",
+      "nodes": [
+        "acme::shop::Customer",
+        "acme::shop::Order",
+        "acme::shop::Order.reference",
+        "acme::shop::OrderNotePrompt",
+        "acme::shop::Shop.Checkout.Orders",
+        "acme::shop::Shop.Checkout.Orders.Noted",
+        "acme::shop::Shop.Checkout.Orders.Recorded",
+        "acme::shop::Shop.Checkout.Orders.Recorded.Quotable",
+        "acme::shop::Shop.Checkout.Orders.Refunded"
+      ]
+    },
+    {
+      "id": "requirement:acme::shop::Shop.Checkout.Orders.Recorded",
+      "kind": "requirement",
+      "anchor": "acme::shop::Shop.Checkout.Orders.Recorded",
+      "nodes": [
+        "acme::shop::Customer",
+        "acme::shop::Order",
+        "acme::shop::Order.reference",
+        "acme::shop::Shop.Checkout.Orders.Recorded",
+        "acme::shop::Shop.Checkout.Orders.Recorded.Quotable"
+      ]
+    }
+  ]
+}
diff --git a/fixtures/explorer-conformance/shop/hashes.json b/fixtures/explorer-conformance/shop/hashes.json
new file mode 100644
index 0000000000..a07fb4fffb
--- /dev/null
+++ b/fixtures/explorer-conformance/shop/hashes.json
@@ -0,0 +1,18 @@
+{
+  "src/generated/acme/shop/Customer.ts": {
+    "hash": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
+    "generatedBy": "entity",
+    "sourceNode": "acme::shop::Customer"
+  },
+  "src/generated/acme/shop/Order.queries.ts": {
+    "hash": "sha256:2222222222222222222222222222222222222222222222222222222222222222",
+    "generatedBy": "queries",
+    "sourceNode": "acme::shop::Order"
+  },
+  "src/generated/acme/shop/Order.ts": {
+    "hash": "sha256:3333333333333333333333333333333333333333333333333333333333333333",
+    "generatedBy": "entity",
+    "sourceNode": "acme::shop::Order"
+  },
+  "src/generated/index.ts": "sha256:4444444444444444444444444444444444444444444444444444444444444444"
+}
diff --git a/fixtures/explorer-conformance/shop/project/.metaobjects/config.json b/fixtures/explorer-conformance/shop/project/.metaobjects/config.json
new file mode 100644
index 0000000000..dea4b1e4ab
--- /dev/null
+++ b/fixtures/explorer-conformance/shop/project/.metaobjects/config.json
@@ -0,0 +1,4 @@
+{
+  "schema_version": 1,
+  "sources": []
+}
diff --git a/fixtures/explorer-conformance/shop/project/metaobjects/meta.shop.json b/fixtures/explorer-conformance/shop/project/metaobjects/meta.shop.json
new file mode 100644
index 0000000000..ce876bc67c
--- /dev/null
+++ b/fixtures/explorer-conformance/shop/project/metaobjects/meta.shop.json
@@ -0,0 +1,186 @@
+{
+  "metadata.root": {
+    "package": "acme::shop",
+    "children": [
+      {
+        "object.entity": {
+          "name": "BaseEntity",
+          "abstract": true,
+          "children": [
+            { "field.uuid": { "name": "id" } },
+            { "field.timestamp": { "name": "createdAt" } },
+            { "identity.primary": { "name": "pk", "@fields": ["id"] } }
+          ]
+        }
+      },
+      {
+        "object.value": {
+          "name": "Address",
+          "children": [
+            { "field.string": { "name": "street" } },
+            { "field.string": { "name": "city" } }
+          ]
+        }
+      },
+      {
+        "object.entity": {
+          "name": "Customer",
+          "extends": "BaseEntity",
+          "children": [
+            { "field.string": { "name": "name", "@required": true } },
+            { "field.string": { "name": "email" } },
+            { "field.object": { "name": "shippingAddress", "@objectRef": "Address" } },
+            { "source.rdb": { "name": "db", "@table": "customers" } }
+          ]
+        }
+      },
+      {
+        "object.entity": {
+          "name": "Order",
+          "extends": "BaseEntity",
+          "children": [
+            { "field.uuid": { "name": "customerId" } },
+            { "field.string": { "name": "reference" } },
+            { "field.decimal": { "name": "total" } },
+            { "field.enum": { "name": "state", "@values": ["OPEN", "PAID", "SHIPPED"] } },
+            { "identity.reference": { "name": "customerRef", "@fields": ["customerId"], "@references": "Customer" } },
+            { "index.lookup": { "name": "orderByCustomerId", "@fields": ["customerId"] } },
+            { "source.rdb": { "name": "db", "@table": "orders" } }
+          ]
+        }
+      },
+      {
+        "object.entity": {
+          "name": "AuditEntry",
+          "children": [
+            { "field.uuid": { "name": "id" } },
+            { "identity.primary": { "name": "id", "@fields": ["id"] } },
+            { "field.string": { "name": "message" } },
+            { "source.rdb": { "name": "db", "@table": "audit_entries" } }
+          ]
+        }
+      },
+      {
+        "object.value": {
+          "name": "OrderNoteRequest",
+          "children": [
+            { "field.string": { "name": "reference", "@required": true } }
+          ]
+        }
+      },
+      {
+        "object.value": {
+          "name": "OrderNote",
+          "children": [
+            { "field.string": { "name": "text", "@required": true } }
+          ]
+        }
+      },
+      {
+        "template.prompt": {
+          "name": "OrderNotePrompt",
+          "@payloadRef": "OrderNoteRequest",
+          "@responseRef": "OrderNote",
+          "@textRef": "shop/order-note",
+          "@format": "text",
+          "@responseFormat": "json"
+        }
+      },
+      {
+        "requirement.architectural": {
+          "name": "Addressable",
+          "@status": "live",
+          "@statement": "Every stored row has a stable id.",
+          "@counterexample": "A row nobody can point at.",
+          "@implementedBy": ["BaseEntity"]
+        }
+      },
+      {
+        "requirement.functional": {
+          "name": "Shop",
+          "@level": 1,
+          "@status": "live",
+          "@statement": "A customer can buy from the shop.",
+          "@counterexample": "A customer who cannot place an order.",
+          "children": [
+            {
+              "requirement.functional": {
+                "name": "Checkout",
+                "@level": 2,
+                "@status": "partial",
+                "@disposition": "deferred",
+                "@trackedBy": ["https://example.invalid/issues/1"],
+                "@statement": "Orders are taken at checkout.",
+                "@counterexample": "An order taken outside checkout.",
+                "children": [
+                  {
+                    "requirement.functional": {
+                      "name": "Orders",
+                      "@level": 3,
+                      "@status": "live",
+                      "@statement": "Every placed order is kept.",
+                      "@counterexample": "A placed order that is lost.",
+                      "children": [
+                        {
+                          "requirement.functional": {
+                            "name": "Recorded",
+                            "@level": 4,
+                            "@status": "live",
+                            "@statement": "An order is recorded when it is placed.",
+                            "@counterexample": "A placed order has no row.",
+                            "@implementedBy": ["Order", "Customer"],
+                            "children": [
+                              {
+                                "requirement.functional": {
+                                  "name": "Quotable",
+                                  "@level": 5,
+                                  "@status": "live",
+                                  "@statement": "An order carries a reference the customer can quote.",
+                                  "@counterexample": "An order nobody can quote back.",
+                                  "@implementedBy": ["Order.reference"]
+                                }
+                              }
+                            ]
+                          }
+                        },
+                        {
+                          "requirement.functional": {
+                            "name": "Noted",
+                            "@level": 4,
+                            "@status": "live",
+                            "@statement": "A placed order gets a short note for the customer.",
+                            "@counterexample": "An order with no note.",
+                            "@implementedBy": ["OrderNotePrompt"]
+                          }
+                        },
+                        {
+                          "requirement.functional": {
+                            "name": "Refunded",
+                            "@level": 4,
+                            "@status": "planned",
+                            "@statement": "A paid order can be refunded.",
+                            "@counterexample": "A paid order that cannot be refunded.",
+                            "@implementedBy": ["Refund"]
+                          }
+                        }
+                      ]
+                    }
+                  },
+                  {
+                    "requirement.functional": {
+                      "name": "Shipping",
+                      "@level": 3,
+                      "@status": "live",
+                      "@statement": "A paid order is shipped.",
+                      "@counterexample": "A paid order that never ships."
+                    }
+                  }
+                ]
+              }
+            }
+          ]
+        }
+      }
+    ]
+  }
+}
diff --git a/fixtures/explorer-conformance/shop/project/prompts/shop/order-note.mustache b/fixtures/explorer-conformance/shop/project/prompts/shop/order-note.mustache
new file mode 100644
index 0000000000..62faf4546d
--- /dev/null
+++ b/fixtures/explorer-conformance/shop/project/prompts/shop/order-note.mustache
@@ -0,0 +1 @@
+Write a short note for order {{reference}}.
diff --git a/fixtures/explorer-conformance/shop/verify.json b/fixtures/explorer-conformance/shop/verify.json
new file mode 100644
index 0000000000..54702a591e
--- /dev/null
+++ b/fixtures/explorer-conformance/shop/verify.json
@@ -0,0 +1,259 @@
+{
+  "verify": [
+    {
+      "gate": "templates",
+      "ran": true,
+      "ok": true
+    },
+    {
+      "gate": "schema",
+      "ran": false,
+      "ok": true
+    },
+    {
+      "gate": "codegen",
+      "ran": false,
+      "ok": true
+    },
+    {
+      "gate": "deps",
+      "ran": false,
+      "ok": true
+    },
+    {
+      "gate": "requirements",
+      "ran": true,
+      "ok": true
+    },
+    {
+      "gate": "replay",
+      "ran": false,
+      "ok": true
+    }
+  ],
+  "exitCode": 0,
+  "summary": "2 gate(s) ran, all clean; 2 requirement diagnostic(s)",
+  "help": [],
+  "antiPatterns": {
+    "status": "ran",
+    "total": 0,
+    "rows": []
+  },
+  "requirements": {
+    "status": "ran",
+    "total": 2,
+    "rows": [
+      {
+        "code": "WARN_REQUIREMENT_NOTHING_IMPLEMENTS",
+        "path": "Shop.Checkout.Shipping",
+        "severity": "warn",
+        "source": "gate",
+        "message": "is 'live' but neither it nor anything nested under it names an implementing node. A functional requirement's check is existence — a subtree that claims nothing is a capability nobody built."
+      },
+      {
+        "code": "WARN_REQUIREMENT_OBJECT_UNCLAIMED",
+        "path": "",
+        "severity": "warn",
+        "source": "gate",
+        "message": "no requirement claims 'acme::shop::AuditEntry'. Add it to an L4 requirement's 'implementedBy'."
+      }
+    ]
+  },
+  "overlays": {
+    "status": "ran",
+    "total": 0,
+    "rows": []
+  },
+  "names": {
+    "status": "ran",
+    "total": 0,
+    "rows": []
+  },
+  "deprecations": {
+    "status": "ran",
+    "total": 0,
+    "rows": []
+  },
+  "fields": {
+    "status": "ran",
+    "total": 0,
+    "rows": []
+  },
+  "requirementCounts": {
+    "total": 9,
+    "functional": 8,
+    "architectural": 1,
+    "byStatus": [
+      {
+        "status": "planned",
+        "count": 1
+      },
+      {
+        "status": "live",
+        "count": 7
+      },
+      {
+        "status": "partial",
+        "count": 1
+      }
+    ],
+    "undecided": 1,
+    "entitiesClaimed": 2,
+    "entitiesTotal": 3,
+    "metadataFiles": 1
+  },
+  "requirementLedger": [
+    {
+      "path": "Addressable",
+      "package": "acme::shop",
+      "qualifiedPath": "acme::shop::Addressable",
+      "subType": "architectural",
+      "status": "live",
+      "digest": "c22897fd7559820a2a7a69bae54353900122be23f3d0058e9ec2b6195ae840e1",
+      "implementedBy": [
+        {
+          "ref": "BaseEntity",
+          "resolves": true,
+          "target": "acme::shop::BaseEntity"
+        }
+      ],
+      "diagnostics": [],
+      "verdict": "clean"
+    },
+    {
+      "path": "Shop",
+      "package": "acme::shop",
+      "qualifiedPath": "acme::shop::Shop",
+      "subType": "functional",
+      "level": 1,
+      "status": "live",
+      "digest": "edc8a9b8159eb03a08d020427683253d6d1471032e0cf48115956362fc121653",
+      "implementedBy": [],
+      "diagnostics": [],
+      "verdict": "clean"
+    },
+    {
+      "path": "Shop.Checkout",
+      "package": "acme::shop",
+      "qualifiedPath": "acme::shop::Shop.Checkout",
+      "subType": "functional",
+      "level": 2,
+      "status": "partial",
+      "disposition": "deferred",
+      "digest": "111b8c39a19c717933fdd529af808540a27c0592406d0a792c524960ac775a2d",
+      "implementedBy": [],
+      "diagnostics": [],
+      "verdict": "clean"
+    },
+    {
+      "path": "Shop.Checkout.Orders",
+      "package": "acme::shop",
+      "qualifiedPath": "acme::shop::Shop.Checkout.Orders",
+      "subType": "functional",
+      "level": 3,
+      "status": "live",
+      "digest": "e84c69fda54cb9f04f3949af069c2c5d56027e008be3198a08c4ee4fbcad8be6",
+      "implementedBy": [],
+      "diagnostics": [],
+      "verdict": "clean"
+    },
+    {
+      "path": "Shop.Checkout.Orders.Recorded",
+      "package": "acme::shop",
+      "qualifiedPath": "acme::shop::Shop.Checkout.Orders.Recorded",
+      "subType": "functional",
+      "level": 4,
+      "status": "live",
+      "digest": "6feebe1e415dda976cc6843c4546c1541b25e8ee44b85316811bfdb177f77635",
+      "implementedBy": [
+        {
+          "ref": "Order",
+          "resolves": true,
+          "target": "acme::shop::Order"
+        },
+        {
+          "ref": "Customer",
+          "resolves": true,
+          "target": "acme::shop::Customer"
+        }
+      ],
+      "diagnostics": [],
+      "verdict": "clean"
+    },
+    {
+      "path": "Shop.Checkout.Orders.Recorded.Quotable",
+      "package": "acme::shop",
+      "qualifiedPath": "acme::shop::Shop.Checkout.Orders.Recorded.Quotable",
+      "subType": "functional",
+      "level": 5,
+      "status": "live",
+      "digest": "b5d7fb7a9657bfda7b30e2629617bf5c56e4337ef7a06abfe55715613ecdda63",
+      "implementedBy": [
+        {
+          "ref": "Order.reference",
+          "resolves": true,
+          "target": "acme::shop::Order.reference"
+        }
+      ],
+      "diagnostics": [],
+      "verdict": "clean"
+    },
+    {
+      "path": "Shop.Checkout.Orders.Noted",
+      "package": "acme::shop",
+      "qualifiedPath": "acme::shop::Shop.Checkout.Orders.Noted",
+      "subType": "functional",
+      "level": 4,
+      "status": "live",
+      "digest": "45ed514b57928304f2d8b7c69e4cc3e5196cd8131ea57bc5ececc8056f52b995",
+      "implementedBy": [
+        {
+          "ref": "OrderNotePrompt",
+          "resolves": true,
+          "target": "acme::shop::OrderNotePrompt"
+        }
+      ],
+      "diagnostics": [],
+      "verdict": "clean"
+    },
+    {
+      "path": "Shop.Checkout.Orders.Refunded",
+      "package": "acme::shop",
+      "qualifiedPath": "acme::shop::Shop.Checkout.Orders.Refunded",
+      "subType": "functional",
+      "level": 4,
+      "status": "planned",
+      "digest": "dcaacae2ee305ce97e804148559dfe32c13dc69083ff736f09cab1b60a8d7a74",
+      "implementedBy": [
+        {
+          "ref": "Refund",
+          "resolves": false
+        }
+      ],
+      "diagnostics": [],
+      "verdict": "clean"
+    },
+    {
+      "path": "Shop.Checkout.Shipping",
+      "package": "acme::shop",
+      "qualifiedPath": "acme::shop::Shop.Checkout.Shipping",
+      "subType": "functional",
+      "level": 3,
+      "status": "live",
+      "digest": "d7d26a3dd5661647327cec62f969b61c74346e1df1e954de4d8392705bdecf31",
+      "implementedBy": [],
+      "diagnostics": [
+        {
+          "code": "WARN_REQUIREMENT_NOTHING_IMPLEMENTS",
+          "severity": "warn",
+          "source": "gate"
+        }
+      ],
+      "verdict": "warn"
+    }
+  ],
+  "notRepresented": [
+    "per-gate drift detail for every gate but schema (which template variable drifted, which generated file differs, which migration failed to replay) — printed as text on stderr; this payload carries each gate's pass/fail verdict, and the schema gate's differences in schemaDrift",
+    "the loader's own warnings and the agent-context/manifest advisories — printed as text on stderr"
+  ]
+}
diff --git a/server/typescript/packages/cli/src/commands/export.ts b/server/typescript/packages/cli/src/commands/export.ts
index 7db145be2f..4b6aa66d63 100644
--- a/server/typescript/packages/cli/src/commands/export.ts
+++ b/server/typescript/packages/cli/src/commands/export.ts
@@ -3,7 +3,7 @@ import { writeFile } from "node:fs/promises";
 import { parseExportArgs } from "../lib/args.js";
 import { log } from "../lib/log.js";
 import { FileSource } from "@metaobjectsdev/metadata/core";
-import { composeRegistry, MetaDataLoader, canonicalSerialize } from "@metaobjectsdev/metadata";
+import { composeRegistry, MetaDataLoader, canonicalSerialize, canonicalSerializeEffective } from "@metaobjectsdev/metadata";
 import { defaultLoadMemoryProviders, forgeTypesProvider, resolveCollection } from "@metaobjectsdev/sdk";
 import { loadProjectProviders } from "../lib/load-metaobjects-config.js";
 import { collectionLoadOptions } from "../lib/collection-load-options.js";
@@ -67,7 +67,10 @@ export async function exportCommand(args: string[], cwd: string): Promise w.message),
   };
diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts
index 4ed889e740..4eac6c7432 100644
--- a/server/typescript/packages/cli/src/commands/verify.ts
+++ b/server/typescript/packages/cli/src/commands/verify.ts
@@ -11,6 +11,7 @@ import { existsSync } from "node:fs";
 import { join, relative, resolve as resolvePath } from "node:path";
 import { parseVerifyArgs, type MigrateFlags } from "../lib/args.js";
 import { log } from "../lib/log.js";
+import { requirementLedgerRows, type RequirementLedgerRow } from "../lib/requirement-ledger.js";
 import { emitStructured, type OutputFormat } from "../lib/format.js";
 import {
   antiPatternRows, missingBaseUrlRows, removedPropRows, ranSection, skippedSection, warnCapped,
@@ -432,6 +433,10 @@ export async function verifyCommand(
   // then omits the block rather than reporting zeroes that would read as an empty
   // ledger instead of no ledger.
   let requirementCounts: RequirementCounts | undefined;
+  // One row per requirement: its claim digest, each link as resolved, and the codes
+  // reported against its path. Undefined exactly when `requirementCounts` is — same
+  // opt-in-by-declaration rule.
+  let requirementLedger: RequirementLedgerRow[] | undefined;
 
   // Whether the schema gate is selected. `runSchemaVerify` makes this decision
   // internally (it is selected by --db or --dialect d1, not by a subverb flag);
@@ -526,6 +531,7 @@ export async function verifyCommand(
         exitCode,
         requirements: requirementSection,
         requirementCounts,
+        requirementLedger,
         antiPatterns: antiPatternSection,
         overlays: overlaySection,
         names: nameSection,
@@ -866,6 +872,11 @@ export async function verifyCommand(
       ...diags.map((d) => toDiagnosticRow(d, "gate")),
       ...lint.map((d) => toDiagnosticRow(d, "lint")),
     ]);
+    // The same findings per ENTRY, beside what each entry declares — so a reader learns an
+    // entry was checked and found clean from a row saying so, not from its path's absence.
+    if (s !== undefined && structured) {
+      requirementLedger = requirementLedgerRows(root, scan, diags, lint);
+    }
 
     if (errors.length > 0) {
       log.error(`meta verify — requirements: ${errors.length} error(s).`);
@@ -2081,6 +2092,7 @@ function buildVerifyPayload(input: {
   exitCode: number;
   requirements: AdvisorySection;
   requirementCounts: RequirementCounts | undefined;
+  requirementLedger?: RequirementLedgerRow[] | undefined;
   antiPatterns: AdvisorySection;
   overlays: AdvisorySection;
   names: AdvisorySection;
@@ -2186,6 +2198,7 @@ function buildVerifyPayload(input: {
     deprecations: input.deprecations,
     fields: input.fields,
     ...(input.requirementCounts !== undefined ? { requirementCounts: input.requirementCounts } : {}),
+    ...(input.requirementLedger !== undefined ? { requirementLedger: input.requirementLedger } : {}),
     ...(input.schemaDrift !== undefined ? { schemaDrift: input.schemaDrift } : {}),
     // The honest boundary. Everything named here is REACHABLE — it is printed as
     // text on stderr — but it is not in this document, and a reader must not have
diff --git a/server/typescript/packages/cli/src/index.ts b/server/typescript/packages/cli/src/index.ts
index d63cc68585..e501e8bdcf 100644
--- a/server/typescript/packages/cli/src/index.ts
+++ b/server/typescript/packages/cli/src/index.ts
@@ -453,6 +453,9 @@ USAGE:
 
 FLAGS:
   --out           Write output to a file (default: stdout)
+  --effective           Write the effective tree: every inherited field, child and
+                        attribute materialized on the node that inherits it (overlays
+                        are merged either way). The input the explorer builder reads.
   --help, -h            Print this help
 `,
   fmt: `meta fmt — rewrite metadata files into canonical form
diff --git a/server/typescript/packages/cli/src/lib/args.ts b/server/typescript/packages/cli/src/lib/args.ts
index 7155271048..5e1452f585 100644
--- a/server/typescript/packages/cli/src/lib/args.ts
+++ b/server/typescript/packages/cli/src/lib/args.ts
@@ -199,11 +199,14 @@ function parseGeneratorNames(raw: string): string[] {
 
 export interface ExportFlags {
   out: string | undefined;
+  /** Emit the EFFECTIVE tree: inherited members and attributes materialized, overlays merged. */
+  effective: boolean;
 }
 
 /** The flag table `parseExportArgs` parses. Exported so the help text can be gated against it. */
 export const EXPORT_OPTIONS = {
   out: { type: "string" },
+  effective: { type: "boolean", default: false },
 } as const;
 
 export function parseExportArgs(argv: string[]): ExportFlags {
@@ -215,6 +218,7 @@ export function parseExportArgs(argv: string[]): ExportFlags {
   });
   return {
     out: values.out,
+    effective: values.effective,
   };
 }
 
diff --git a/server/typescript/packages/cli/src/lib/requirement-check.ts b/server/typescript/packages/cli/src/lib/requirement-check.ts
index 117e379ec5..afcff955b9 100644
--- a/server/typescript/packages/cli/src/lib/requirement-check.ts
+++ b/server/typescript/packages/cli/src/lib/requirement-check.ts
@@ -63,6 +63,11 @@ export interface Diagnostic {
   message: string;
 }
 
+/** The requirement node a gate or lint diagnostic is about. Two packages may each declare a
+ *  requirement at the same path, so the path alone cannot tell their findings apart. Kept
+ *  beside the diagnostic, not on it, so a diagnostic's shape is only its four fields. */
+export const diagnosticRequirement = new WeakMap();
+
 export const ERR_REQUIREMENT_LINK_ABOVE_FLOOR = "ERR_REQUIREMENT_LINK_ABOVE_FLOOR";
 export const ERR_REQUIREMENT_DANGLING_REF = "ERR_REQUIREMENT_DANGLING_REF";
 export const ERR_REQUIREMENT_BAD_LEVEL = "ERR_REQUIREMENT_BAD_LEVEL";
@@ -426,6 +431,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
   if (addressed.length === 0) return out; // opt-in by declaration — no requirements, nothing to say
 
   for (const { node: req, path: reqPath } of addressed) {
+    const report = (d: Diagnostic): void => { diagnosticRequirement.set(d, req); out.push(d); };
     const architectural = req.subType === REQUIREMENT_SUBTYPE_ARCHITECTURAL;
     const level = req.level();
     const refs = req.implementedBy();
@@ -443,7 +449,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
     if (!architectural || levelled) {
       if (!levelled || !Number.isInteger(level)
           || level < REQUIREMENT_MIN_LEVEL || level > REQUIREMENT_MAX_LEVEL) {
-        out.push({
+        report({
           severity: "error", code: ERR_REQUIREMENT_BAD_LEVEL, path: reqPath,
           message: `level must be an integer ${REQUIREMENT_MIN_LEVEL}-${REQUIREMENT_MAX_LEVEL} (got ${String(level)}). ` +
             `L1 solution, L2 segment (app/library), L3 service, L4 object, L5 member.` +
@@ -455,7 +461,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
       if (parent !== undefined && parent.type === TYPE_REQUIREMENT) {
         const pl = (parent as MetaRequirement).level();
         if (pl !== undefined && level !== undefined && level <= pl) {
-          out.push({
+          report({
             severity: "error", code: ERR_REQUIREMENT_LEVEL_NESTING, path: reqPath,
             message: `nested under "${parent.name}" (level ${pl}) but declares level ${level}. ` +
               `Nesting is the hierarchy — a child sits strictly below its parent.`,
@@ -466,7 +472,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
 
     // -- the link boundary ----------------------------------------------------
     if (refs.length > 0 && !req.mayReferenceModel()) {
-      out.push({
+      report({
         severity: "error", code: ERR_REQUIREMENT_LINK_ABOVE_FLOOR, path: reqPath,
         message: `'implementedBy' is legal at L${REQUIREMENT_LINK_FLOOR_LEVEL} (object) and ` +
           `L${REQUIREMENT_MAX_LEVEL} (member) only. L1-L3 are organisational and never reference ` +
@@ -495,7 +501,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
       // existing one — unlike the level checks above, which `@level` already
       // promised.
       if (!architectural && level === REQUIREMENT_LINK_FLOOR_LEVEL && !isObjectRef) {
-        out.push({
+        report({
           severity: "error", code: ERR_REQUIREMENT_L4_NOT_OBJECT, path: reqPath,
           message: `L${REQUIREMENT_LINK_FLOOR_LEVEL} references an object; '${ref}' names a member. ` +
             `Move it to a nested L${REQUIREMENT_LEVEL_MEMBER} child, or reference the object itself.`,
@@ -503,7 +509,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
         continue;
       }
       if (!architectural && level === REQUIREMENT_LEVEL_MEMBER && isObjectRef) {
-        out.push({
+        report({
           severity: "error", code: ERR_REQUIREMENT_L5_NOT_MEMBER, path: reqPath,
           message: `L${REQUIREMENT_LEVEL_MEMBER} references a member (field, view or identity); ` +
             `'${ref}' names an object. Move it to its L${REQUIREMENT_LINK_FLOOR_LEVEL} parent.`,
@@ -521,7 +527,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
           // resolved and only the member is gone, it listed that same object back and said
           // to qualify it: name the member instead.
           const hint = node === undefined ? didYouMeanHint(root, owner) : missingMemberHint(node, path);
-          out.push({
+          report({
             severity: "error", code: ERR_REQUIREMENT_DANGLING_REF, path: reqPath,
             message: `'${ref}' does not resolve in the loaded model (status '${String(req.status())}' — ` +
               `the model moved and the requirement is stale).` + hint,
@@ -547,7 +553,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
     if (superseded !== undefined) {
       const referrerPkg = effectiveRequirementPackage(req);
       if (resolveRequirementRef(addressed, superseded, referrerPkg) === undefined) {
-        out.push({
+        report({
           severity: "error", code: ERR_REQUIREMENT_DANGLING_REF, path: reqPath,
           message: `@supersededBy '${superseded}' does not name a requirement in the loaded ` +
             `ledger. It must name the requirement that REPLACED this one — if nothing did, ` +
@@ -577,7 +583,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
     // all": true for a flat policy (the original form), false for L1-L3 of a
     // levelled one, true again at the link floor.
     if (architectural && live && refs.length === 0 && req.mayReferenceModel()) {
-      out.push({
+      report({
         severity: "error", code: ERR_REQUIREMENT_ARCH_NO_IMPLEMENTERS, path: reqPath,
         message: `architectural requirement is '${String(status)}' but nothing implements it. ` +
           `Its check is universality — a claim set of zero means the policy is declared and unapplied.`,
@@ -587,7 +593,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
     // -- disposition: the decision, not the state -----------------------------
     const disposition = req.disposition();
     if (disposition !== undefined && !req.hasOutstandingWork()) {
-      out.push({
+      report({
         severity: "warn", code: WARN_REQUIREMENT_DISPOSITION_NOT_APPLICABLE, path: reqPath,
         message: `carries @disposition '${disposition}' but its status is '${String(status)}', which has no ` +
           `outstanding work to decide about. A disposition is meaningful on 'planned' and 'partial' only — ` +
@@ -608,7 +614,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
     // keeps its `WARN_` name on purpose: it identifies the finding, and one finding
     // under two codes would split every suppression and corpus case that keys on it.
     if (!architectural && live && !subtreeClaimsAnything(req)) {
-      out.push({
+      report({
         severity: scan.requireImplementers ? "error" : "warn",
         code: WARN_REQUIREMENT_NOTHING_IMPLEMENTS, path: reqPath,
         message: `is '${String(status)}' but neither it nor anything nested under it names an ` +
@@ -618,7 +624,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe
     }
 
     if (disposition === REQUIREMENT_DISPOSITION_DEFERRED && req.trackedBy().length === 0) {
-      out.push({
+      report({
         severity: "warn", code: WARN_REQUIREMENT_DEFERRED_UNTRACKED, path: reqPath,
         message: `is deferred but names no @trackedBy issue. Deferring without a ticket is how a known gap ` +
           `becomes an unknown one — nothing will raise it again.`,
diff --git a/server/typescript/packages/cli/src/lib/requirement-ledger.ts b/server/typescript/packages/cli/src/lib/requirement-ledger.ts
new file mode 100644
index 0000000000..9a1896f9ff
--- /dev/null
+++ b/server/typescript/packages/cli/src/lib/requirement-ledger.ts
@@ -0,0 +1,152 @@
+// `meta verify --format json` — the per-requirement ledger rows.
+//
+// The requirement gate and its counts say how the ledger fares as a WHOLE; a reader
+// (the explorer builder, an agent, a dashboard) also needs each entry's own verdict, and
+// before this it had to infer "checked and clean" from a path's absence in the
+// diagnostics. One row per `requirement.*` node states it outright: what the entry
+// declares, the digest of its claim, whether each `@implementedBy` link resolves and to
+// WHAT, and the codes the gate and the authoring lint reported against it.
+//
+// Every value here comes from the SAME scan, resolver and diagnostics the gate used on
+// this run. Nothing is re-derived: a row that disagreed with the gate beside it would be
+// a second answer to one question.
+
+import {
+  effectiveRequirementPackage,
+  resolveClaimTarget,
+  resolveMember,
+  type MetaRequirement,
+  type MetaData,
+} from "@metaobjectsdev/metadata";
+import { requirementDigest } from "@metaobjectsdev/codegen-ts";
+import {
+  diagnosticRequirement,
+  resolveRequirementRef,
+  splitMemberRef,
+  type Diagnostic,
+  type RequirementScan,
+} from "./requirement-check.js";
+
+/** One `@implementedBy` (or `@supersededBy`) link, as the gate resolved it. */
+export interface RequirementLinkRow {
+  /** The link exactly as authored. */
+  ref: string;
+  resolves: boolean;
+  /** The node it binds to — `` or `.`
+   *  for `@implementedBy`, `::` for `@supersededBy`. Absent when it does not
+   *  resolve. */
+  target?: string;
+}
+
+export interface RequirementDiagnosticRef {
+  code: string;
+  severity: string;
+  /** "gate" can fail the build; "lint" never can. */
+  source: "gate" | "lint";
+}
+
+/** One `requirement.*` node, as this run of `meta verify` judged it. */
+export interface RequirementLedgerRow {
+  /** The dotted child-name address every diagnostic prints. */
+  path: string;
+  /** The requirement's effective package, "" when it has none. */
+  package: string;
+  /** `::`, or `` with no package — the prefix of every generated
+   *  requirement test's id (` []`). */
+  qualifiedPath: string;
+  subType: string;
+  level?: number;
+  status?: string;
+  disposition?: string;
+  /** SHA-256 over the claim (subtype, level, status, statement, counterexample,
+   *  `@implementedBy`) — the digest every port's requirement tests carry. */
+  digest: string;
+  implementedBy: RequirementLinkRow[];
+  supersededBy?: RequirementLinkRow;
+  /** Every finding this run reported against this requirement, gate and lint, in report order. */
+  diagnostics: RequirementDiagnosticRef[];
+  /** From the GATE findings only: "error" when one can fail the build, "warn" when the
+   *  worst is a warning, "clean" when the gate reported nothing against this entry. */
+  verdict: "clean" | "warn" | "error";
+}
+
+function implementedByRows(root: MetaData, req: MetaRequirement): RequirementLinkRow[] {
+  // referrerPkg is the requirement's own effective package — the binding the gate uses
+  // (ADR-0042), so a row resolves exactly the links the gate resolved.
+  const referrerPkg = effectiveRequirementPackage(req);
+  return req.implementedBy().map((ref) => {
+    const { owner, path } = splitMemberRef(ref);
+    const node = resolveClaimTarget(root, owner, referrerPkg);
+    if (node === undefined) return { ref, resolves: false };
+    if (path.length > 0 && resolveMember(node, path) === undefined) return { ref, resolves: false };
+    const key = node.resolutionKey();
+    return { ref, resolves: true, target: path.length === 0 ? key : `${key}.${path.join(".")}` };
+  });
+}
+
+/**
+ * One row per requirement in the scan, in the scan's (document) order.
+ *
+ * `diags` are this run's gate diagnostics and `lint` its authoring findings. Each is matched
+ * to a row by the requirement node it names, and by path only when it names none.
+ */
+export function requirementLedgerRows(
+  root: MetaData,
+  scan: RequirementScan,
+  diags: readonly Diagnostic[],
+  lint: readonly Diagnostic[],
+): RequirementLedgerRow[] {
+  const byNode = new Map();
+  const byPath = new Map();
+  const note = (d: Diagnostic, source: "gate" | "lint"): void => {
+    const ref = { code: d.code, severity: d.severity, source };
+    const requirement = diagnosticRequirement.get(d);
+    if (requirement !== undefined) {
+      byNode.set(requirement, [...(byNode.get(requirement) ?? []), ref]);
+    } else if (d.path !== undefined) {
+      byPath.set(d.path, [...(byPath.get(d.path) ?? []), ref]);
+    }
+  };
+  for (const d of diags) note(d, "gate");
+  for (const d of lint) note(d, "lint");
+
+  return scan.addressed.map(({ node: req, path }) => {
+    const pkg = effectiveRequirementPackage(req);
+    const diagnostics = [...(byNode.get(req) ?? []), ...(byPath.get(path) ?? [])];
+    const gate = diagnostics.filter((d) => d.source === "gate");
+    const verdict = gate.some((d) => d.severity === "error")
+      ? "error"
+      : gate.length > 0 ? "warn" : "clean";
+    const level = req.level();
+    const status = req.status();
+    const disposition = req.disposition();
+    const superseded = req.supersededBy();
+    let supersededBy: RequirementLinkRow | undefined;
+    if (superseded !== undefined) {
+      const target = resolveRequirementRef(scan.addressed, superseded, pkg);
+      const hit = target === undefined ? undefined : scan.addressed.find((r) => r.node === target);
+      supersededBy = hit === undefined
+        ? { ref: superseded, resolves: false }
+        : { ref: superseded, resolves: true, target: qualify(effectiveRequirementPackage(hit.node), hit.path) };
+    }
+    return {
+      path,
+      package: pkg,
+      qualifiedPath: qualify(pkg, path),
+      subType: req.subType,
+      // `exactOptionalPropertyTypes` — an omitted key, never an explicit `undefined`.
+      ...(level !== undefined ? { level } : {}),
+      ...(status !== undefined ? { status } : {}),
+      ...(disposition !== undefined ? { disposition } : {}),
+      digest: requirementDigest(req),
+      implementedBy: implementedByRows(root, req),
+      ...(supersededBy !== undefined ? { supersededBy } : {}),
+      diagnostics,
+      verdict,
+    };
+  });
+}
+
+function qualify(pkg: string, path: string): string {
+  return pkg === "" ? path : `${pkg}::${path}`;
+}
diff --git a/server/typescript/packages/cli/src/lib/requirement-lint.ts b/server/typescript/packages/cli/src/lib/requirement-lint.ts
index cc1e324adb..7f1820e42f 100644
--- a/server/typescript/packages/cli/src/lib/requirement-lint.ts
+++ b/server/typescript/packages/cli/src/lib/requirement-lint.ts
@@ -56,7 +56,7 @@ import {
 // compares this path set against `walkRequirements()`, the generator's own walk,
 // rather than leaving the two to agree by inspection.)
 import {
-  collectAddressedRequirements, type AddressedRequirement, type Diagnostic,
+  collectAddressedRequirements, diagnosticRequirement, type AddressedRequirement, type Diagnostic,
 } from "./requirement-check.js";
 
 export const WARN_REQUIREMENT_NAME_NOT_ADDRESSABLE = "WARN_REQUIREMENT_NAME_NOT_ADDRESSABLE";
@@ -236,8 +236,10 @@ function excerpt(value: string): string {
   return JSON.stringify(flat.length > LIMIT ? `${flat.slice(0, LIMIT - 1)}…` : flat);
 }
 
-function warn(path: string, code: string, message: string): Diagnostic {
-  return { severity: "warn", code, path, message };
+function warn(at: AddressedRequirement, code: string, message: string): Diagnostic {
+  const d: Diagnostic = { severity: "warn", code, path: at.path, message };
+  diagnosticRequirement.set(d, at.node);
+  return d;
 }
 
 /**
@@ -263,7 +265,8 @@ export function lintRequirements(
 ): Diagnostic[] {
   const out: Diagnostic[] = [];
 
-  for (const { node, path } of addressed) {
+  for (const at of addressed) {
+    const { node, path } = at;
     const name = node.name;
 
     // -- the name is an address, not prose ------------------------------------
@@ -279,7 +282,7 @@ export function lintRequirements(
     if (name.trim() === "") problems.push("is blank");
     else if (name.trim() !== name) problems.push("has leading or trailing whitespace");
     if (problems.length > 0) {
-      out.push(warn(path, WARN_REQUIREMENT_NAME_NOT_ADDRESSABLE,
+      out.push(warn(at, WARN_REQUIREMENT_NAME_NOT_ADDRESSABLE,
         `name ${JSON.stringify(name)} ${problems.join(", and ")}. A requirement's name is its ` +
         `address — it is the segment of the dotted path '${path}' and the filename of its generated ` +
         `test stub — so this either collides with nesting or produces a path the stub cannot be ` +
@@ -293,11 +296,11 @@ export function lintRequirements(
     // the statement, "rename it" is the wrong instruction. The instruction is "you
     // have written the claim twice; @statement is the one that is read".
     if (statementKey !== "" && normalise(toSnakeCase(name)) === statementKey) {
-      out.push(warn(path, WARN_REQUIREMENT_NAME_RESTATES_STATEMENT,
+      out.push(warn(at, WARN_REQUIREMENT_NAME_RESTATES_STATEMENT,
         `name '${name}' says the same thing as @statement. The claim belongs in @statement, which every ` +
         `surface reads; the name is an address and is better as a short identifier.`));
     } else if (name.trim().split(/\s+/).filter((w) => w !== "").length >= PROSE_WORD_COUNT) {
-      out.push(warn(path, WARN_REQUIREMENT_NAME_READS_AS_PROSE,
+      out.push(warn(at, WARN_REQUIREMENT_NAME_READS_AS_PROSE,
         `name '${name}' reads as a sentence. The name is an address — the dotted path other entries and ` +
         `the generated stub filename are built from — so a short identifier keeps both legible. Put the ` +
         `prose in @statement.`));
@@ -310,7 +313,7 @@ export function lintRequirements(
       // OWN-ONLY: the fix is deleting or filling one declaration. See readOwnSlot.
       const value = readOwnSlot(node, slot);
       if (value !== undefined && value.trim() === "") {
-        out.push(warn(path, WARN_REQUIREMENT_PROSE_EMPTY,
+        out.push(warn(at, WARN_REQUIREMENT_PROSE_EMPTY,
           `@${slot} is declared but empty. The loader requires the attribute to be present, not to say ` +
           `anything — an empty one passes every check while recording nothing.`));
       }
@@ -329,12 +332,12 @@ export function lintRequirements(
       const description = readSlot(node, DOC_ATTR_DESCRIPTION);
       if (description !== undefined) {
         if (normalise(description) === statementKey) {
-          out.push(warn(path, WARN_REQUIREMENT_PROSE_DUPLICATED,
+          out.push(warn(at, WARN_REQUIREMENT_PROSE_DUPLICATED,
             `description repeats @statement verbatim. @statement already IS the description of what the ` +
             `requirement is; description holds the SCOPE — what the claim covers, what it deliberately ` +
             `does not, which sibling entry owns the rest. If the scope is obvious, leave it off.`));
         } else if (leadingSentenceMatches(description, statementKey)) {
-          out.push(warn(path, WARN_REQUIREMENT_PROSE_DUPLICATED,
+          out.push(warn(at, WARN_REQUIREMENT_PROSE_DUPLICATED,
             `description opens by repeating @statement verbatim, then continues. Drop the first sentence — ` +
             `it is already read from @statement, and description is only the scope that follows it.`));
         }
@@ -342,7 +345,7 @@ export function lintRequirements(
 
       const counterexample = readSlot(node, REQUIREMENT_ATTR_COUNTEREXAMPLE);
       if (counterexample !== undefined && normalise(counterexample) === statementKey) {
-        out.push(warn(path, WARN_REQUIREMENT_PROSE_DUPLICATED,
+        out.push(warn(at, WARN_REQUIREMENT_PROSE_DUPLICATED,
           `@counterexample repeats @statement verbatim. It must describe what BREAKING the claim looks ` +
           `like — the thing you could point at to falsify it — which is what makes the claim checkable.`));
       }
@@ -353,7 +356,7 @@ export function lintRequirements(
       // OWN-ONLY: the fix is deleting one attribute. See readOwnSlot.
       const value = readOwnSlot(node, slot);
       if (value === undefined || value.trim() === "") continue;
-      out.push(warn(path, WARN_REQUIREMENT_INERT_DOC_SLOT,
+      out.push(warn(at, WARN_REQUIREMENT_INERT_DOC_SLOT,
         `@${slot} says nothing here that @${REQUIREMENT_ATTR_STATEMENT} does not. A requirement's ` +
         `statement is REQUIRED and is already the one-line sentence, so a summary beside it can only ` +
         `repeat it — and no requirement surface reads it. Its content is invisible: ${excerpt(value)}. ` +
@@ -364,7 +367,7 @@ export function lintRequirements(
     // -- an id is not a label -------------------------------------------------
     const title = readOwnSlot(node, DOC_ATTR_TITLE);
     if (title !== undefined && TITLE_ID_ONLY.test(title.trim())) {
-      out.push(warn(path, WARN_REQUIREMENT_TITLE_IS_AN_ID,
+      out.push(warn(at, WARN_REQUIREMENT_TITLE_IS_AN_ID,
         `@title holds only a catalogue or ticket id: ${excerpt(title)}. A title is the entry's ` +
         `LABEL and an id is not a name, so this slot says nothing a reader can use. Put the id in ` +
         `@${REQUIREMENT_ATTR_TRACKED_BY}, which is the free-form reference slot and IS read, and ` +
diff --git a/server/typescript/packages/cli/test/explorer-fixture.test.ts b/server/typescript/packages/cli/test/explorer-fixture.test.ts
new file mode 100644
index 0000000000..d01388949b
--- /dev/null
+++ b/server/typescript/packages/cli/test/explorer-fixture.test.ts
@@ -0,0 +1,149 @@
+// The explorer data spine, end to end, over `fixtures/explorer-conformance/shop/`:
+//
+//   `meta export --effective`   → effective.json   (committed)
+//   `meta verify --format json` → verify.json      (committed; carries `requirementLedger`)
+//   buildExplorer(both + the manifest)             → expected.json (committed, byte-checked in docs-site)
+//
+// This file keeps the committed INPUTS honest: regenerating them from `project/` must give
+// the same bytes, so a change to either command's output shows up here as a fixture diff
+// rather than as an explorer that quietly reads stale data.
+import { describe, test, expect, beforeEach, afterEach, afterAll } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { buildExplorer, serializeExplorer } from "@metaobjectsdev/docs-site";
+import { run } from "../src/index.js";
+
+const FIXTURE = resolve(import.meta.dir, "../../../../../fixtures/explorer-conformance/shop");
+const PROJECT = join(FIXTURE, "project");
+const committed = (name: string): string => readFileSync(join(FIXTURE, name), "utf8");
+
+const dirs: string[] = [];
+afterAll(() => {
+  for (const d of dirs) rmSync(d, { recursive: true, force: true });
+});
+
+let out: string[];
+let origLog: typeof console.log;
+let origErr: typeof console.error;
+beforeEach(() => {
+  out = [];
+  origLog = console.log;
+  origErr = console.error;
+  console.log = (...a: unknown[]) => { out.push(a.map(String).join(" ")); };
+  console.error = () => {};
+});
+afterEach(() => {
+  console.log = origLog;
+  console.error = origErr;
+});
+
+async function exportJson(effective: boolean): Promise {
+  const dir = mkdtempSync(join(tmpdir(), "explorer-export-"));
+  dirs.push(dir);
+  const file = join(dir, "model.json");
+  const exit = await run(["export", ...(effective ? ["--effective"] : []), "--out", file, "--cwd", PROJECT]);
+  expect(exit).toBe(0);
+  return readFileSync(file, "utf8");
+}
+
+async function verifyJson(): Promise {
+  const exit = await run(["verify", "--format", "json", "--cwd", PROJECT]);
+  expect(exit).toBe(0);
+  return out.join("\n") + "\n";
+}
+
+interface LedgerRow {
+  path: string;
+  qualifiedPath: string;
+  verdict: string;
+  digest: string;
+  implementedBy: { ref: string; resolves: boolean; target?: string }[];
+  diagnostics: { code: string; severity: string; source: string }[];
+}
+
+describe("explorer fixture — the committed inputs are what the CLI writes today", () => {
+  test("`meta export --effective` reproduces effective.json", async () => {
+    expect(await exportJson(true)).toBe(committed("effective.json"));
+  });
+
+  test("`meta verify --format json` reproduces verify.json", async () => {
+    expect(await verifyJson()).toBe(committed("verify.json"));
+  });
+
+  test("the fresh inputs build the committed expected.json", async () => {
+    const model = JSON.parse(await exportJson(true));
+    out = [];
+    const verify = JSON.parse(await verifyJson());
+    const manifest = JSON.parse(committed("hashes.json"));
+    expect(serializeExplorer(buildExplorer({ model, verify, manifest }))).toBe(committed("expected.json"));
+  });
+});
+
+describe("meta export --effective", () => {
+  test("materializes inherited members; the plain export does not", async () => {
+    const own = JSON.parse(await exportJson(false));
+    const eff = JSON.parse(await exportJson(true));
+    const fieldNames = (doc: unknown, object: string): string[] => {
+      const root = (doc as { "metadata.root": { children: Record[] }>[] } })["metadata.root"];
+      const node = root.children.map((c) => Object.values(c)[0]).find((b) => b?.name === object);
+      return (node?.children ?? []).map((c) => Object.values(c)[0]?.name ?? "");
+    };
+    expect(fieldNames(own, "Customer")).not.toContain("id");
+    expect(fieldNames(eff, "Customer")).toContain("id");
+    expect(fieldNames(eff, "Customer")).toContain("createdAt");
+  });
+});
+
+describe("meta verify --format json — requirementLedger rows", () => {
+  async function rows(): Promise> {
+    const payload = JSON.parse(await verifyJson()) as { requirementLedger: LedgerRow[] };
+    return new Map(payload.requirementLedger.map((r) => [r.path, r]));
+  }
+
+  test("one row per requirement, in document order, each with a sha-256 digest", async () => {
+    const r = await rows();
+    expect([...r.keys()]).toEqual([
+      "Addressable",
+      "Shop",
+      "Shop.Checkout",
+      "Shop.Checkout.Orders",
+      "Shop.Checkout.Orders.Recorded",
+      "Shop.Checkout.Orders.Recorded.Quotable",
+      "Shop.Checkout.Orders.Noted",
+      "Shop.Checkout.Orders.Refunded",
+      "Shop.Checkout.Shipping",
+    ]);
+    for (const row of r.values()) expect(row.digest).toMatch(/^[0-9a-f]{64}$/);
+    expect(r.get("Shop.Checkout")?.qualifiedPath).toBe("acme::shop::Shop.Checkout");
+  });
+
+  test("each @implementedBy link carries the node the gate resolved it to", async () => {
+    const r = await rows();
+    expect(r.get("Shop.Checkout.Orders.Recorded")?.implementedBy).toEqual([
+      { ref: "Order", resolves: true, target: "acme::shop::Order" },
+      { ref: "Customer", resolves: true, target: "acme::shop::Customer" },
+    ]);
+    expect(r.get("Shop.Checkout.Orders.Recorded.Quotable")?.implementedBy).toEqual([
+      { ref: "Order.reference", resolves: true, target: "acme::shop::Order.reference" },
+    ]);
+    // A planned requirement may name a node that does not exist yet: the row says so.
+    expect(r.get("Shop.Checkout.Orders.Refunded")?.implementedBy).toEqual([{ ref: "Refund", resolves: false }]);
+  });
+
+  test("the verdict comes from the gate's findings against that path", async () => {
+    const r = await rows();
+    const shipping = r.get("Shop.Checkout.Shipping");
+    expect(shipping?.verdict).toBe("warn");
+    expect(shipping?.diagnostics).toEqual([
+      { code: "WARN_REQUIREMENT_NOTHING_IMPLEMENTS", severity: "warn", source: "gate" },
+    ]);
+    expect(r.get("Shop.Checkout.Orders.Recorded")?.verdict).toBe("clean");
+  });
+
+  test("text output carries no ledger rows", async () => {
+    const exit = await run(["verify", "--format", "text", "--cwd", PROJECT]);
+    expect(exit).toBe(0);
+    expect(out.join("\n")).not.toContain("requirementLedger");
+  });
+});
diff --git a/server/typescript/packages/cli/test/unit/args-export.test.ts b/server/typescript/packages/cli/test/unit/args-export.test.ts
index d5b8894642..c3ad749b2c 100644
--- a/server/typescript/packages/cli/test/unit/args-export.test.ts
+++ b/server/typescript/packages/cli/test/unit/args-export.test.ts
@@ -2,19 +2,25 @@ import { describe, test, expect } from "bun:test";
 import { parseExportArgs } from "../../src/lib/args.js";
 
 describe("parseExportArgs", () => {
-  test("default flags — out is undefined", () => {
-    expect(parseExportArgs([])).toEqual({ out: undefined });
+  test("default flags — out is undefined, effective is off", () => {
+    expect(parseExportArgs([])).toEqual({ out: undefined, effective: false });
+  });
+
+  test("--effective selects the effective tree", () => {
+    expect(parseExportArgs(["--effective"])).toEqual({ out: undefined, effective: true });
   });
 
   test("--out sets the output path", () => {
     expect(parseExportArgs(["--out", "dist/metadata.json"])).toEqual({
       out: "dist/metadata.json",
+      effective: false,
     });
   });
 
   test("--out with absolute path", () => {
     expect(parseExportArgs(["--out", "/tmp/metadata.json"])).toEqual({
       out: "/tmp/metadata.json",
+      effective: false,
     });
   });
 
diff --git a/server/typescript/packages/cli/test/unit/requirement-ledger.test.ts b/server/typescript/packages/cli/test/unit/requirement-ledger.test.ts
new file mode 100644
index 0000000000..a135dce8f9
--- /dev/null
+++ b/server/typescript/packages/cli/test/unit/requirement-ledger.test.ts
@@ -0,0 +1,67 @@
+// `requirementLedgerRows` — the per-requirement rows `meta verify --format json` carries.
+//
+// A requirement's dotted path carries no package, so two packages may each declare one at
+// the same path. Each row must hold only the findings against its own node: a finding
+// against one package's `Billing` is not a finding against the other's.
+import { describe, test, expect } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { loadMemory } from "@metaobjectsdev/sdk";
+import { checkRequirements, scanRequirements } from "../../src/lib/requirement-check.js";
+import { lintRequirements } from "../../src/lib/requirement-lint.js";
+import { requirementLedgerRows } from "../../src/lib/requirement-ledger.js";
+
+const pkg = (name: string, claim: string): string => `
+metadata:
+  package: acme::${name}
+  children:
+    - object.entity:
+        name: Invoice
+        children:
+          - source.rdb: { table: ${name}_invoices }
+          - field.uuid: { name: id }
+          - identity.primary: { name: pk, fields: [id] }
+    - requirement.functional:
+        name: Billing
+        level: 1
+        status: live
+        statement: "Invoices are issued"
+        counterexample: "A sale with no invoice"
+        children:
+          - requirement.functional:
+              name: Invoicing
+              level: 4
+              status: live
+              statement: "Each invoice is stored"
+              counterexample: "An invoice that cannot be found again"
+              implementedBy: ["${claim}"]
+`;
+
+describe("requirementLedgerRows", () => {
+  test("two packages' requirements at one path keep their own findings", async () => {
+    const dir = mkdtempSync(join(tmpdir(), "req-ledger-"));
+    try {
+      mkdirSync(join(dir, "metaobjects"));
+      writeFileSync(join(dir, "metaobjects/meta.a.yaml"), pkg("a", "acme::a::Invoice"));
+      writeFileSync(join(dir, "metaobjects/meta.b.yaml"), pkg("b", "acme::b::Receipt"));
+      const root = await loadMemory(dir, { strict: true });
+      const scan = scanRequirements(root);
+      const gate = checkRequirements(root, scan);
+      expect(gate.length).toBeGreaterThan(0);
+      for (const d of [...gate, ...lintRequirements(root, scan.addressed)]) {
+        expect(Object.keys(d).filter((k) => !["code", "message", "path", "severity"].includes(k))).toEqual([]);
+      }
+      const rows = requirementLedgerRows(root, scan, gate, lintRequirements(root, scan.addressed));
+      const verdicts = rows.map((r) => [r.qualifiedPath, r.verdict, r.diagnostics.map((d) => d.code)]);
+      expect(verdicts).toEqual([
+        ["acme::a::Billing", "clean", []],
+        ["acme::a::Billing.Invoicing", "clean", []],
+        ["acme::b::Billing", "clean", []],
+        ["acme::b::Billing.Invoicing", "error", ["ERR_REQUIREMENT_DANGLING_REF"]],
+      ]);
+    } finally {
+      rmSync(dir, { recursive: true, force: true });
+    }
+  });
+});
diff --git a/server/typescript/packages/codegen-ts/src/generator.ts b/server/typescript/packages/codegen-ts/src/generator.ts
index 93c86ad4ec..d6caa13394 100644
--- a/server/typescript/packages/codegen-ts/src/generator.ts
+++ b/server/typescript/packages/codegen-ts/src/generator.ts
@@ -17,6 +17,12 @@ export interface EmittedFile {
   content: string;
   /** Set by the runner from generator.name — generators should not set this. */
   generatedBy?: string;
+  /** The resolution key of the metadata node this file was rendered from
+   *  (`acme::shop::Order`), recorded beside the file's hash in `.gen-state/.hashes.json`.
+   *  `perEntity` sets it for you; a generator rendering one file from one node by other
+   *  means sets it itself. Leave it unset for a file rendered from the whole model or a
+   *  whole package (a barrel, a docs index). */
+  sourceNode?: string;
 }
 
 export interface GenContext {
@@ -229,8 +235,15 @@ export function perEntity(
 ): (ctx: GenContext) => Promise {
   return async (ctx) => {
     const matched = ctx.entities.filter(ctx.matches);
-    const results = await Promise.all(matched.map((e) => fn(e, ctx)));
-    return results.flatMap((r) => (Array.isArray(r) ? r : [r]));
+    const results = await Promise.all(matched.map(async (e) => {
+      const r = await fn(e, ctx);
+      // Each file names the object it was rendered from, unless the generator said
+      // otherwise — so every per-entity generator, owned copies included, records its
+      // provenance without a line of its own.
+      const key = e.resolutionKey();
+      return (Array.isArray(r) ? r : [r]).map((f) => (f.sourceNode !== undefined ? f : { ...f, sourceNode: key }));
+    }));
+    return results.flat();
   };
 }
 
diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts
index b696f9f0ec..57464372da 100644
--- a/server/typescript/packages/codegen-ts/src/index.ts
+++ b/server/typescript/packages/codegen-ts/src/index.ts
@@ -95,7 +95,8 @@ export { decideAndWrite, GitMissingError, WRITE_STATUSES } from "./overwrite-pol
 // `listGeneratedPaths` answers the sibling question — WHICH paths we have ever
 // written — which is how the gate scopes itself to its own output instead of
 // convicting every stranger's file that happens to sit in the same directory.
-export { contentHash, readGeneratedHash, listGeneratedPaths } from "./overwrite-policy.js";
+export { contentHash, readGeneratedHash, listGeneratedPaths, recordGeneratedProvenance } from "./overwrite-policy.js";
+export type { GeneratedProvenance } from "./overwrite-policy.js";
 
 export { CodegenError } from "./errors.js";
 export { GENERATED_HEADER, GENERATED_EDIT_NOTE, NAMES_FILE_SUFFIX, DEFAULT_OUT_DIR, RETIRED_CODEGEN_ATTRS, sidecarLine, type RetiredCodegenAttr } from "./constants.js";
diff --git a/server/typescript/packages/codegen-ts/src/overwrite-policy.ts b/server/typescript/packages/codegen-ts/src/overwrite-policy.ts
index a1b0d45b55..70311f1554 100644
--- a/server/typescript/packages/codegen-ts/src/overwrite-policy.ts
+++ b/server/typescript/packages/codegen-ts/src/overwrite-policy.ts
@@ -184,18 +184,80 @@ function loadHashes(genStateDir: string): HashesFile {
 }
 
 function saveHashes(genStateDir: string, hashes: HashesFile): void {
-  mkdirSync(genStateDir, { recursive: true });
   const raw = readRawManifest(genStateDir);
+  const next: Record = {};
+  for (const [key, hash] of Object.entries(hashes)) {
+    const existing = raw[key];
+    next[key] = isRecord(existing) ? { ...existing, hash } : hash;
+  }
+  writeRawManifest(genStateDir, next);
+}
+
+function writeRawManifest(genStateDir: string, entries: Record): void {
+  mkdirSync(genStateDir, { recursive: true });
   // Keys SORTED, because this file is committed. Insertion order would make the
   // diff — and any merge conflict between two people who both regenerated —
   // depend on which entity happened to generate first, which is noise nobody can
   // review.
   const sorted: Record = {};
-  for (const key of Object.keys(hashes).sort()) {
+  for (const key of Object.keys(entries).sort()) sorted[key] = entries[key];
+  writeFileSync(join(genStateDir, HASHES_FILE), JSON.stringify(sorted, null, 2) + "\n");
+}
+
+/** What produced one generated file: the generator, and the metadata node it was rendered
+ *  from when it was rendered from one. */
+export interface GeneratedProvenance {
+  generatedBy: string;
+  /** The resolution key of the node (`acme::shop::Order`). Absent for a file rendered from
+   *  the whole model or a whole package — a barrel, a docs index. */
+  sourceNode?: string;
+}
+
+/** The manifest fields provenance owns. Every other field on an entry — `hash`, and the
+ *  JVM's `generator` / `outputDir` owner (ADR-0060) — is kept as it is. */
+const PROVENANCE_FIELDS = ["generatedBy", "sourceNode"] as const;
+
+/**
+ * Record, on each recorded path's manifest entry, the node it was generated from.
+ *
+ * A path with a source node becomes `{ "hash", "generatedBy", "sourceNode" }`; one without
+ * keeps (or returns to) the plain `""` form, so a file rendered from the whole model
+ * adds nothing to the committed manifest. A path with no recorded hash is left alone — this
+ * describes what a write recorded, it never records a write.
+ *
+ * `generatedBy` is deliberately not the JVM's `generator` field: there `generator` is an
+ * OWNERSHIP claim the orphan sweep acts on, and a TypeScript name in it would read as a
+ * generator no Maven execution configures.
+ *
+ * Batched: one read and at most one write for the whole run. Nothing is written when no
+ * entry changes, so a regeneration that changes nothing leaves the file's bytes alone.
+ */
+export function recordGeneratedProvenance(
+  genStateDir: string,
+  provenance: ReadonlyMap,
+): void {
+  if (!existsSync(join(genStateDir, HASHES_FILE))) return;
+  const raw = readRawManifest(genStateDir);
+  let changed = false;
+  for (const [key, prov] of provenance) {
     const existing = raw[key];
-    sorted[key] = isRecord(existing) ? { ...existing, hash: hashes[key] } : hashes[key];
+    const hash = entryHash(existing);
+    if (hash === undefined) continue;
+    const rest: Record = {};
+    if (isRecord(existing)) {
+      for (const [k, v] of Object.entries(existing)) {
+        if (k !== "hash" && !(PROVENANCE_FIELDS as readonly string[]).includes(k)) rest[k] = v;
+      }
+    }
+    const next: unknown = prov.sourceNode !== undefined
+      ? { hash, ...rest, generatedBy: prov.generatedBy, sourceNode: prov.sourceNode }
+      : Object.keys(rest).length > 0 ? { hash, ...rest } : hash;
+    if (JSON.stringify(next) !== JSON.stringify(existing)) {
+      raw[key] = next;
+      changed = true;
+    }
   }
-  writeFileSync(join(genStateDir, HASHES_FILE), JSON.stringify(sorted, null, 2) + "\n");
+  if (changed) writeRawManifest(genStateDir, raw);
 }
 
 // ---------------------------------------------------------------------------
diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts
index 78e84b97e1..f8bc70baa9 100644
--- a/server/typescript/packages/codegen-ts/src/runner.ts
+++ b/server/typescript/packages/codegen-ts/src/runner.ts
@@ -33,6 +33,8 @@ import {
   listGeneratedPaths,
   loadEngineVersion,
   saveEngineVersion,
+  recordGeneratedProvenance,
+  type GeneratedProvenance,
   type WriteResult,
   type MergeStrategy,
   type BaselineMode,
@@ -791,7 +793,13 @@ export async function runGen(opts: RunGenOpts): Promise {
   }
 
   // 4. Run each generator with a per-target render context; collect with full path.
-  const emitted: { fullPath: string; content: string; generatedBy: string; handEdits?: HandEdits }[] = [];
+  const emitted: {
+    fullPath: string;
+    content: string;
+    generatedBy: string;
+    handEdits?: HandEdits;
+    sourceNode?: string;
+  }[] = [];
   // FR-038 §8 — generators that opted into orphan reconciliation, paired with the
   // directory their policy's relative paths are measured from. Collected here
   // because `writeOutDir` is resolved per generator inside this loop.
@@ -972,6 +980,7 @@ export async function runGen(opts: RunGenOpts): Promise {
         content: file.content,
         generatedBy: generator.name,
         ...(generator.handEdits !== undefined && { handEdits: generator.handEdits }),
+        ...(file.sourceNode !== undefined && { sourceNode: file.sourceNode }),
       });
     }
   }
@@ -1277,6 +1286,21 @@ export async function runGen(opts: RunGenOpts): Promise {
   noteUntracked();
   reportAdoptions();
 
+  // G3 — which node each recorded file came from, beside its hash. Only with a real
+  // projectRoot: without one the manifest is keyed by path hashes, not paths.
+  if (projectRoot !== undefined) {
+    const provenance = new Map();
+    for (const file of emitted) {
+      if (outsideProject(file.fullPath)) continue;
+      // The same key policyFor gives the write, so the two always name one entry.
+      provenance.set(relative(projectRoot, file.fullPath), {
+        generatedBy: file.generatedBy,
+        ...(file.sourceNode !== undefined && { sourceNode: file.sourceNode }),
+      });
+    }
+    recordGeneratedProvenance(genStateDir, provenance);
+  }
+
   // Sweep AFTER the writes: writing is the primary job, and a deletion that runs
   // first would be unrecoverable if a later write threw. Ordering cannot change
   // the decision — a path this run emitted is never an orphan either way.
diff --git a/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts b/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts
new file mode 100644
index 0000000000..e1c027716d
--- /dev/null
+++ b/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts
@@ -0,0 +1,88 @@
+// Node provenance in the generated-file manifest: `perEntity` stamps each file with the node
+// it rendered, and the runner records that on the file's `.hashes.json` entry, so a reader
+// (the explorer builder) can say which files a node produced without matching names.
+import { describe, test, expect, beforeEach, afterEach } from "bun:test";
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { MetaDataLoader } from "@metaobjectsdev/metadata";
+import { FileSource } from "@metaobjectsdev/metadata/core";
+import { runGen } from "../src/runner.js";
+import { defineConfig } from "../src/metaobjects-config.js";
+import { perEntity, perModel, type Generator } from "../src/generator.js";
+import { recordGeneratedProvenance } from "../src/overwrite-policy.js";
+
+const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json");
+
+let tmp: string;
+beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-provenance-")); });
+afterEach(() => { rmSync(tmp, { recursive: true, force: true }); });
+
+const manifest = (dir: string): Record =>
+  JSON.parse(readFileSync(join(dir, ".metaobjects", ".gen-state", ".hashes.json"), "utf8"));
+
+describe("perEntity stamps the source node", () => {
+  test("each file carries its entity's resolution key unless the generator set one", async () => {
+    const { root } = await new MetaDataLoader().load([new FileSource(FIXTURE)]);
+    const plain = perEntity((e) => ({ path: `${e.name}.ts`, content: "" }));
+    const preset = perEntity((e) => ({ path: `${e.name}.ts`, content: "", sourceNode: "kept" }));
+    const ctx = { entities: root.objects(), root, matches: () => true } as unknown as Parameters[0];
+    expect((await plain(ctx)).map((f) => f.sourceNode)).toEqual(["demo::Post"]);
+    expect((await preset(ctx)).map((f) => f.sourceNode)).toEqual(["kept"]);
+  });
+});
+
+describe("runGen records provenance in .hashes.json", () => {
+  test("a per-entity file gets { hash, generatedBy, sourceNode }; a whole-model file stays plain", async () => {
+    const { root } = await new MetaDataLoader().load([new FileSource(FIXTURE)]);
+    const entity: Generator = { name: "alpha", generate: perEntity((e) => ({ path: `${e.name}.alpha.ts`, content: "// a\n" })) };
+    const barrel: Generator = { name: "barrel", generate: perModel(() => ({ path: "index.ts", content: "// i\n" })) };
+    await runGen({
+      config: defineConfig({ outDir: join(tmp, "gen"), extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [entity, barrel] }),
+      metadata: root,
+      projectRoot: tmp,
+    });
+    const m = manifest(tmp);
+    expect(m["gen/Post.alpha.ts"]).toEqual({
+      hash: expect.any(String),
+      generatedBy: "alpha",
+      sourceNode: "demo::Post",
+    });
+    expect(typeof m["gen/index.ts"]).toBe("string");
+  });
+});
+
+describe("recordGeneratedProvenance", () => {
+  function seed(entries: Record): string {
+    const dir = join(tmp, ".gen-state");
+    mkdirSync(dir, { recursive: true });
+    writeFileSync(join(dir, ".hashes.json"), JSON.stringify(entries));
+    return dir;
+  }
+  const read = (dir: string): Record => JSON.parse(readFileSync(join(dir, ".hashes.json"), "utf8"));
+
+  test("keeps the JVM owner fields beside the provenance", () => {
+    const dir = seed({ "a.kt": { hash: "h1", generator: "kotlin-entity", outputDir: "src" } });
+    recordGeneratedProvenance(dir, new Map([["a.kt", { generatedBy: "entity", sourceNode: "x::A" }]]));
+    expect(read(dir)["a.kt"]).toEqual({ hash: "h1", generator: "kotlin-entity", outputDir: "src", generatedBy: "entity", sourceNode: "x::A" });
+  });
+
+  test("a file with no source node returns to the plain form", () => {
+    const dir = seed({ "i.ts": { hash: "h2", generatedBy: "barrel", sourceNode: "gone::X" } });
+    recordGeneratedProvenance(dir, new Map([["i.ts", { generatedBy: "barrel" }]]));
+    expect(read(dir)["i.ts"]).toBe("h2");
+  });
+
+  test("never records a path the manifest has no hash for, and writes nothing when nothing changes", () => {
+    const dir = seed({ "a.ts": "h3" });
+    const before = readFileSync(join(dir, ".hashes.json"), "utf8");
+    recordGeneratedProvenance(dir, new Map([["b.ts", { generatedBy: "g", sourceNode: "x::B" }], ["a.ts", { generatedBy: "g" }]]));
+    expect(readFileSync(join(dir, ".hashes.json"), "utf8")).toBe(before);
+  });
+
+  test("no manifest, no file", () => {
+    const dir = join(tmp, "none");
+    recordGeneratedProvenance(dir, new Map([["a.ts", { generatedBy: "g", sourceNode: "x::A" }]]));
+    expect(() => readFileSync(join(dir, ".hashes.json"))).toThrow();
+  });
+});
diff --git a/server/typescript/packages/docs-site/src/explorer/build.ts b/server/typescript/packages/docs-site/src/explorer/build.ts
new file mode 100644
index 0000000000..f7918becf0
--- /dev/null
+++ b/server/typescript/packages/docs-site/src/explorer/build.ts
@@ -0,0 +1,404 @@
+// The `explorer.json` builder — the data spine every explorer page reads.
+//
+// PORT-NEUTRAL INPUT, on purpose. It reads three documents and never the loader:
+//
+//   model     the EFFECTIVE canonical JSON (`meta export --effective`): inheritance and
+//             overlays already resolved, references already in their canonical spelling.
+//   verify    the `meta verify --format json` payload: the requirement ledger rows, each
+//             link as the gate resolved it, the counts and the findings.
+//   manifest  `.metaobjects/.gen-state/.hashes.json`: which generated file came from which
+//             node, where the port records it.
+//
+// Every port already has a canonical serializer and writes the same manifest, so a Java, C#
+// or Python project can feed this without the Node CLI knowing its providers. The builder
+// therefore resolves nothing the inputs have not resolved: an `@implementedBy` link becomes
+// an edge only because the verify row names its target, never by a name match here.
+//
+// DETERMINISTIC: the same three inputs give the same bytes (`serializeExplorer`), so the
+// file can sit under a drift gate.
+
+import {
+  ATTR_PREFIX,
+  FIELD_ATTR_OBJECT_REF,
+  IDENTITY_REFERENCE_ATTR_REFERENCES,
+  IDENTITY_SUBTYPE_REFERENCE,
+  PACKAGE_SEPARATOR,
+  CHILD_REF_SEPARATOR,
+  RELATIONSHIP_ATTR_OBJECT_REF,
+  RESERVED_KEY_ABSTRACT,
+  RESERVED_KEY_CHILDREN,
+  RESERVED_KEY_EXTENDS,
+  RESERVED_KEY_IS_ARRAY,
+  RESERVED_KEY_NAME,
+  RESERVED_KEY_PACKAGE,
+  SUBTYPE_ROOT,
+  TEMPLATE_ATTR_PAYLOAD_REF,
+  TEMPLATE_ATTR_RESPONSE_REF,
+  TYPE_FIELD,
+  TYPE_IDENTITY,
+  TYPE_METADATA,
+  TYPE_RELATIONSHIP,
+  TYPE_REQUIREMENT,
+  TYPE_SUBTYPE_SEPARATOR,
+  TYPE_TEMPLATE,
+} from "@metaobjectsdev/metadata/constants";
+import {
+  EXPLORER_FORMAT,
+  type ExplorerEdge,
+  type ExplorerEdgeKind,
+  type ExplorerGenerated,
+  type ExplorerJson,
+  type ExplorerLedger,
+  type ExplorerLedgerRow,
+  type ExplorerNode,
+  type ExplorerSlice,
+} from "./types.js";
+
+export interface ExplorerInput {
+  /** Parsed `meta export --effective` output (or any port's effective canonical JSON). */
+  model: unknown;
+  /** Parsed `meta verify --format json` output. Without it there is no ledger and no
+   *  `implementedBy` / `supersededBy` edge. */
+  verify?: unknown;
+  /** Parsed `.metaobjects/.gen-state/.hashes.json`. Without it there is no `generated`. */
+  manifest?: unknown;
+}
+
+const ROOT_KEY = `${TYPE_METADATA}${TYPE_SUBTYPE_SEPARATOR}${SUBTYPE_ROOT}`;
+
+/** Code-unit order: the same in every runtime and locale, unlike `localeCompare`. */
+const byCodeUnit = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
+
+function isRecord(v: unknown): v is Record {
+  return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+/** One `{ ".": body }` element of a `children` array. */
+interface RawChild {
+  type: string;
+  subType: string;
+  body: Record;
+}
+
+function rawChildren(body: Record): RawChild[] {
+  const list = body[RESERVED_KEY_CHILDREN];
+  if (!Array.isArray(list)) return [];
+  const out: RawChild[] = [];
+  for (const el of list) {
+    if (!isRecord(el)) continue;
+    const keys = Object.keys(el);
+    if (keys.length !== 1) continue;
+    const key = keys[0] as string;
+    const inner = el[key];
+    if (!isRecord(inner)) continue;
+    const sep = key.indexOf(TYPE_SUBTYPE_SEPARATOR);
+    out.push({
+      type: sep === -1 ? key : key.slice(0, sep),
+      subType: sep === -1 ? "" : key.slice(sep + 1),
+      body: inner,
+    });
+  }
+  return out;
+}
+
+function attrsOf(body: Record): Record {
+  const out: Record = {};
+  for (const key of Object.keys(body).sort(byCodeUnit)) {
+    if (key.startsWith(ATTR_PREFIX)) out[key.slice(ATTR_PREFIX.length)] = body[key];
+  }
+  return out;
+}
+
+function stringAttr(body: Record, name: string): string | undefined {
+  const v = body[`${ATTR_PREFIX}${name}`];
+  return typeof v === "string" && v !== "" ? v : undefined;
+}
+
+/** A node as walked, before it is written out: its id, its raw body and its top-level owner. */
+interface Walked {
+  node: ExplorerNode;
+  body: Record;
+  /** The id of the top-level node this one sits under (itself, at the top). */
+  owner: string;
+}
+
+function walkModel(model: unknown): Walked[] {
+  if (!isRecord(model) || !isRecord(model[ROOT_KEY])) {
+    throw new Error(`explorer: the model is not canonical metadata JSON — expected one "${ROOT_KEY}" object`);
+  }
+  const root = model[ROOT_KEY] as Record;
+  const rootPkg = typeof root[RESERVED_KEY_PACKAGE] === "string" ? (root[RESERVED_KEY_PACKAGE] as string) : "";
+  const out: Walked[] = [];
+  const seen = new Set();
+
+  const visit = (child: RawChild, index: number, parent: Walked | undefined): void => {
+    const name = typeof child.body[RESERVED_KEY_NAME] === "string" ? (child.body[RESERVED_KEY_NAME] as string) : "";
+    let pkg: string;
+    let id: string;
+    if (parent === undefined) {
+      const own = child.body[RESERVED_KEY_PACKAGE];
+      pkg = typeof own === "string" ? own : rootPkg;
+      id = pkg === "" ? name : `${pkg}${PACKAGE_SEPARATOR}${name}`;
+    } else {
+      pkg = parent.node.package;
+      id = name === "" ? `${parent.node.id}#${index}` : `${parent.node.id}${CHILD_REF_SEPARATOR}${name}`;
+      // The first sibling of a name keeps the plain id: it is the one a dotted reference
+      // resolves to. A later sibling of another type sharing the name is qualified by type.
+      if (name !== "" && seen.has(id)) id = `${id}[${child.type}${TYPE_SUBTYPE_SEPARATOR}${child.subType}]`;
+    }
+    if (seen.has(id)) {
+      throw new Error(`explorer: two nodes share the id "${id}" — the model names two siblings alike`);
+    }
+    seen.add(id);
+    const ext = child.body[RESERVED_KEY_EXTENDS];
+    const node: ExplorerNode = {
+      id,
+      type: child.type,
+      subType: child.subType,
+      name,
+      package: pkg,
+      ...(parent !== undefined ? { parent: parent.node.id } : {}),
+      ...(typeof ext === "string" && ext !== "" ? { extends: nodeIdOf(ext) } : {}),
+      ...(child.body[RESERVED_KEY_ABSTRACT] === true ? { abstract: true as const } : {}),
+      ...(child.body[RESERVED_KEY_IS_ARRAY] === true ? { isArray: true as const } : {}),
+      attrs: attrsOf(child.body),
+    };
+    const walked: Walked = { node, body: child.body, owner: parent === undefined ? id : parent.owner };
+    out.push(walked);
+    rawChildren(child.body).forEach((c, i) => visit(c, i, walked));
+  };
+
+  rawChildren(root).forEach((c, i) => visit(c, i, undefined));
+  return out;
+}
+
+/** A canonical reference spells a root-level target `::Name`; the node's id is `Name`. */
+function nodeIdOf(ref: string): string {
+  return ref.startsWith(PACKAGE_SEPARATOR) ? ref.slice(PACKAGE_SEPARATOR.length) : ref;
+}
+
+/**
+ * Mark the members a top-level node's effective tree inherited: a direct child whose type,
+ * name and body equal a direct child of an ancestor named through `extends`. The id recorded
+ * is the TOPMOST such ancestor — where the member is declared.
+ */
+function markInherited(walked: Walked[], byId: Map): void {
+  const childKey = (w: Walked): string => `${w.node.type}${TYPE_SUBTYPE_SEPARATOR}${w.node.subType}:${w.node.name}`;
+  const directChildren = new Map>();
+  for (const w of walked) {
+    if (w.node.parent === undefined || w.node.name === "") continue;
+    const m = directChildren.get(w.node.parent) ?? new Map();
+    m.set(childKey(w), w);
+    directChildren.set(w.node.parent, m);
+  }
+  for (const w of walked) {
+    if (w.node.parent !== undefined || w.node.extends === undefined) continue;
+    const members = directChildren.get(w.node.id);
+    if (members === undefined) continue;
+    for (const [key, member] of members) {
+      const body = JSON.stringify(member.body);
+      let declaredOn: string | undefined;
+      const visited = new Set([w.node.id]);
+      let cur = byId.get(w.node.extends);
+      while (cur !== undefined && !visited.has(cur.node.id)) {
+        visited.add(cur.node.id);
+        const same = directChildren.get(cur.node.id)?.get(key);
+        if (same === undefined || JSON.stringify(same.body) !== body) break;
+        declaredOn = cur.node.id;
+        cur = cur.node.extends === undefined ? undefined : byId.get(cur.node.extends);
+      }
+      if (declaredOn !== undefined) member.node.inheritedFrom = declaredOn;
+    }
+  }
+}
+
+function modelEdges(walked: Walked[], byId: Map): ExplorerEdge[] {
+  const edges: ExplorerEdge[] = [];
+  const add = (kind: ExplorerEdgeKind, from: string, to: string | undefined, via?: string): void => {
+    if (to === undefined) return;
+    const target = nodeIdOf(to);
+    if (!byId.has(from) || !byId.has(target)) return;
+    edges.push({ kind, from, to: target, ...(via !== undefined && via !== from ? { via } : {}) });
+  };
+  for (const w of walked) {
+    const { node, body, owner } = w;
+    if (node.extends !== undefined) add("extends", node.id, node.extends);
+    if (node.type === TYPE_IDENTITY && node.subType === IDENTITY_SUBTYPE_REFERENCE) {
+      add("references", owner, stringAttr(body, IDENTITY_REFERENCE_ATTR_REFERENCES), node.id);
+    }
+    if (node.type === TYPE_FIELD) add("objectRef", owner, stringAttr(body, FIELD_ATTR_OBJECT_REF), node.id);
+    if (node.type === TYPE_RELATIONSHIP) add("association", owner, stringAttr(body, RELATIONSHIP_ATTR_OBJECT_REF), node.id);
+    if (node.type === TYPE_TEMPLATE) {
+      add("payload", node.id, stringAttr(body, TEMPLATE_ATTR_PAYLOAD_REF));
+      add("reply", node.id, stringAttr(body, TEMPLATE_ATTR_RESPONSE_REF));
+    }
+    if (node.type === TYPE_REQUIREMENT && node.parent !== undefined && byId.get(node.parent)?.node.type === TYPE_REQUIREMENT) {
+      add("contains", node.parent, node.id);
+    }
+  }
+  return edges;
+}
+
+function asLinks(v: unknown): { ref: string; resolves: boolean; target?: string }[] {
+  if (!Array.isArray(v)) return [];
+  return v.filter(isRecord).map(asLink).filter((l): l is NonNullable => l !== undefined);
+}
+
+function asLink(v: unknown): { ref: string; resolves: boolean; target?: string } | undefined {
+  if (!isRecord(v) || typeof v.ref !== "string") return undefined;
+  return {
+    ref: v.ref,
+    resolves: v.resolves === true,
+    ...(typeof v.target === "string" ? { target: v.target } : {}),
+  };
+}
+
+function ledgerFrom(verify: unknown, byId: Map, edges: ExplorerEdge[]): ExplorerLedger | undefined {
+  if (!isRecord(verify) || !Array.isArray(verify.requirementLedger)) return undefined;
+  const rows: ExplorerLedgerRow[] = [];
+  for (const raw of verify.requirementLedger) {
+    if (!isRecord(raw) || typeof raw.qualifiedPath !== "string" || typeof raw.path !== "string") continue;
+    const node = raw.qualifiedPath;
+    const implementedBy = asLinks(raw.implementedBy);
+    const supersededBy = asLink(raw.supersededBy);
+    const diagnostics = Array.isArray(raw.diagnostics)
+      ? raw.diagnostics.filter(isRecord).map((d) => ({
+          code: String(d.code ?? ""),
+          severity: String(d.severity ?? ""),
+          source: String(d.source ?? ""),
+        }))
+      : [];
+    rows.push({
+      node,
+      path: raw.path,
+      package: typeof raw.package === "string" ? raw.package : "",
+      qualifiedPath: raw.qualifiedPath,
+      subType: typeof raw.subType === "string" ? raw.subType : "",
+      ...(typeof raw.level === "number" ? { level: raw.level } : {}),
+      ...(typeof raw.status === "string" ? { status: raw.status } : {}),
+      ...(typeof raw.disposition === "string" ? { disposition: raw.disposition } : {}),
+      digest: typeof raw.digest === "string" ? raw.digest : "",
+      implementedBy,
+      ...(supersededBy !== undefined ? { supersededBy } : {}),
+      diagnostics,
+      verdict: typeof raw.verdict === "string" ? raw.verdict : "",
+    });
+    if (byId.has(node)) {
+      for (const link of implementedBy) {
+        if (link.target !== undefined && byId.has(link.target)) edges.push({ kind: "implementedBy", from: node, to: link.target });
+      }
+      if (supersededBy?.target !== undefined && byId.has(supersededBy.target)) {
+        edges.push({ kind: "supersededBy", from: node, to: supersededBy.target });
+      }
+    }
+  }
+  const requirements = verify.requirements;
+  return {
+    counts: isRecord(verify.requirementCounts) ? verify.requirementCounts : {},
+    rows,
+    diagnostics: isRecord(requirements) && Array.isArray(requirements.rows) ? requirements.rows : [],
+  };
+}
+
+function generatedFrom(manifest: unknown): ExplorerGenerated[] | undefined {
+  if (!isRecord(manifest)) return undefined;
+  const byNode = new Map();
+  for (const [path, entry] of Object.entries(manifest)) {
+    if (!isRecord(entry) || typeof entry.sourceNode !== "string") continue;
+    const by = typeof entry.generatedBy === "string" ? entry.generatedBy : "";
+    const list = byNode.get(entry.sourceNode) ?? [];
+    list.push({ path, generatedBy: by });
+    byNode.set(entry.sourceNode, list);
+  }
+  return [...byNode.keys()].sort(byCodeUnit).map((node) => ({
+    node,
+    files: (byNode.get(node) ?? []).sort((a, b) => byCodeUnit(a.path, b.path)),
+  }));
+}
+
+function derivedSlices(walked: Walked[], byId: Map, edges: ExplorerEdge[]): ExplorerSlice[] {
+  const slices: ExplorerSlice[] = [];
+  const ownerOf = (id: string): string => byId.get(id)?.owner ?? id;
+  const sorted = (s: Set): string[] => [...s].sort(byCodeUnit);
+
+  // Per package: its top-level nodes.
+  const packages = new Map>();
+  for (const w of walked) {
+    if (w.node.parent !== undefined) continue;
+    const set = packages.get(w.node.package) ?? new Set();
+    set.add(w.node.id);
+    packages.set(w.node.package, set);
+  }
+  for (const [pkg, ids] of packages) slices.push({ id: `package:${pkg}`, kind: "package", anchor: pkg, nodes: sorted(ids) });
+
+  // Per requirement subtree, for every requirement with nested requirements: the subtree,
+  // each node it claims, and the object owning a claimed member.
+  const containsFrom = new Map();
+  const claimsFrom = new Map();
+  for (const e of edges) {
+    const target = e.kind === "contains" ? containsFrom : e.kind === "implementedBy" ? claimsFrom : undefined;
+    if (target === undefined) continue;
+    const list = target.get(e.from) ?? [];
+    list.push(e.to);
+    target.set(e.from, list);
+  }
+  for (const w of walked) {
+    if (w.node.type !== TYPE_REQUIREMENT || !containsFrom.has(w.node.id)) continue;
+    const set = new Set();
+    const stack = [w.node.id];
+    while (stack.length > 0) {
+      const id = stack.pop() as string;
+      if (set.has(id)) continue;
+      set.add(id);
+      for (const t of claimsFrom.get(id) ?? []) {
+        set.add(t);
+        set.add(ownerOf(t));
+      }
+      stack.push(...(containsFrom.get(id) ?? []));
+    }
+    slices.push({ id: `requirement:${w.node.id}`, kind: "requirement", anchor: w.node.id, nodes: sorted(set) });
+  }
+
+  // Per prompt: the prompt, its payload and its reply.
+  for (const w of walked) {
+    if (w.node.type !== TYPE_TEMPLATE || w.node.parent !== undefined) continue;
+    const set = new Set([w.node.id]);
+    for (const e of edges) if (e.from === w.node.id && (e.kind === "payload" || e.kind === "reply")) set.add(e.to);
+    slices.push({ id: `prompt:${w.node.id}`, kind: "prompt", anchor: w.node.id, nodes: sorted(set) });
+  }
+
+  return slices.sort((a, b) => byCodeUnit(a.id, b.id));
+}
+
+const edgeKey = (e: ExplorerEdge): string => `${e.kind}\u0000${e.from}\u0000${e.to}\u0000${e.via ?? ""}`;
+
+/** Build `explorer.json` from the port-neutral inputs. Throws when `model` is not canonical
+ *  metadata JSON; a missing or malformed `verify` / `manifest` only leaves its part out. */
+export function buildExplorer(input: ExplorerInput): ExplorerJson {
+  const walked = walkModel(input.model);
+  const byId = new Map(walked.map((w) => [w.node.id, w] as const));
+  markInherited(walked, byId);
+  const edges = modelEdges(walked, byId);
+  const ledger = input.verify !== undefined ? ledgerFrom(input.verify, byId, edges) : undefined;
+  const generated = input.manifest !== undefined ? generatedFrom(input.manifest) : undefined;
+
+  // One edge per (kind, from, to, via): an object can reach one target twice through two
+  // members, which is two edges, but never the same edge twice.
+  const unique = new Map();
+  for (const e of edges) unique.set(edgeKey(e), e);
+  const sortedEdges = [...unique.values()].sort((a, b) => byCodeUnit(edgeKey(a), edgeKey(b)));
+
+  return {
+    format: EXPLORER_FORMAT,
+    nodes: walked.map((w) => w.node).sort((a, b) => byCodeUnit(a.id, b.id)),
+    edges: sortedEdges,
+    ...(ledger !== undefined ? { ledger } : {}),
+    ...(generated !== undefined ? { generated } : {}),
+    slices: derivedSlices(walked, byId, sortedEdges),
+  };
+}
+
+/** The file's bytes: two-space JSON and one trailing newline. */
+export function serializeExplorer(explorer: ExplorerJson): string {
+  return JSON.stringify(explorer, null, 2) + "\n";
+}
diff --git a/server/typescript/packages/docs-site/src/explorer/types.ts b/server/typescript/packages/docs-site/src/explorer/types.ts
new file mode 100644
index 0000000000..9fc5a69ce5
--- /dev/null
+++ b/server/typescript/packages/docs-site/src/explorer/types.ts
@@ -0,0 +1,121 @@
+// The `explorer.json` shape: the one data file every explorer view reads.
+//
+// It is BUILT from port-neutral inputs only (see build.ts), so its fields hold what those
+// inputs state and nothing a loader would have to recompute.
+
+/** Bumped when a field changes meaning or is removed; adding a field does not bump it. */
+export const EXPLORER_FORMAT = "metaobjects-explorer/1";
+
+/** One metadata node: a top-level node (object, prompt, requirement, …) or any node nested
+ *  in one (field, identity, source, view, nested requirement, …). */
+export interface ExplorerNode {
+  /** `::` for a top-level node (`` with no package), then `.`
+   *  per nesting level: `acme::shop::Order`, `acme::shop::Order.total`,
+   *  `acme::shop::Shop.Checkout`. A nested node with no name gets `#` instead. */
+  id: string;
+  type: string;
+  subType: string;
+  /** "" for a nested node with no name. */
+  name: string;
+  /** The package of the node's top-level ancestor, "" when it has none. */
+  package: string;
+  /** The id of the node this one is nested in; absent on a top-level node. */
+  parent?: string;
+  /** The id `extends` names, as the effective tree spells it. */
+  extends?: string;
+  abstract?: true;
+  isArray?: true;
+  /** On a member the effective tree materialized from a super: the id of the object it is
+   *  declared on. Read as "same type, name and body as that ancestor's member", so a member
+   *  redeclared with a different body is this node's own. */
+  inheritedFrom?: string;
+  /** Every `@` attribute on the effective node, without the `@`, keys sorted. */
+  attrs: Record;
+}
+
+export const EXPLORER_EDGE_KINDS = [
+  "extends",
+  "references",
+  "association",
+  "objectRef",
+  "payload",
+  "reply",
+  "contains",
+  "implementedBy",
+  "supersededBy",
+] as const;
+export type ExplorerEdgeKind = (typeof EXPLORER_EDGE_KINDS)[number];
+
+/** A typed link between two nodes. Only links whose both ends are nodes are drawn. */
+export interface ExplorerEdge {
+  kind: ExplorerEdgeKind;
+  from: string;
+  to: string;
+  /** The member that carries the link, when it is not `from` itself: the
+   *  `identity.reference`, the `field.object`, the `relationship.*`. */
+  via?: string;
+}
+
+/** One requirement as `meta verify --format json` judged it (`requirementLedger[]`), with
+ *  the node id it has here. */
+export interface ExplorerLedgerRow {
+  node: string;
+  path: string;
+  package: string;
+  qualifiedPath: string;
+  subType: string;
+  level?: number;
+  status?: string;
+  disposition?: string;
+  digest: string;
+  implementedBy: { ref: string; resolves: boolean; target?: string }[];
+  supersededBy?: { ref: string; resolves: boolean; target?: string };
+  diagnostics: { code: string; severity: string; source: string }[];
+  verdict: string;
+}
+
+export interface ExplorerLedger {
+  /** `requirementCounts` from the verify payload, verbatim. */
+  counts: Record;
+  /** One row per requirement, in the verify payload's (document) order. */
+  rows: ExplorerLedgerRow[];
+  /** `requirements.rows` from the verify payload, verbatim: every gate and lint finding,
+   *  including the ones whose subject is not a requirement (an unclaimed entity). */
+  diagnostics: unknown[];
+}
+
+export interface ExplorerGeneratedFile {
+  /** Project-relative, as the manifest keys it. */
+  path: string;
+  generatedBy: string;
+}
+
+/** The generated files the manifest attributes to one node. */
+export interface ExplorerGenerated {
+  node: string;
+  files: ExplorerGeneratedFile[];
+}
+
+export type ExplorerSliceKind = "requirement" | "package" | "prompt";
+
+/** A named node set a view opens on, derived from the model with no authoring. */
+export interface ExplorerSlice {
+  /** `:`. */
+  id: string;
+  kind: ExplorerSliceKind;
+  /** The requirement, package or prompt the slice is derived from ("" for the root package). */
+  anchor: string;
+  /** Node ids, sorted. */
+  nodes: string[];
+}
+
+export interface ExplorerJson {
+  format: typeof EXPLORER_FORMAT;
+  nodes: ExplorerNode[];
+  edges: ExplorerEdge[];
+  /** Absent without a verify payload, or when the model declares no requirement. */
+  ledger?: ExplorerLedger;
+  /** Absent without a manifest. */
+  generated?: ExplorerGenerated[];
+  slices: ExplorerSlice[];
+}
diff --git a/server/typescript/packages/docs-site/src/index.ts b/server/typescript/packages/docs-site/src/index.ts
index 47ab07b969..6fdf286c97 100644
--- a/server/typescript/packages/docs-site/src/index.ts
+++ b/server/typescript/packages/docs-site/src/index.ts
@@ -2,3 +2,18 @@ export { generateSite, DEFAULT_ASSET_BASE } from "./site.js";
 export type { SiteOptions, SiteResult } from "./site.js";
 export { SITE_TEMPLATE_NAMES, SITE_ASSET_NAMES, readSiteFile } from "./scaffold.js";
 export type { MetaDataTypeProvider } from "@metaobjectsdev/metadata";
+export { buildExplorer, serializeExplorer } from "./explorer/build.js";
+export type { ExplorerInput } from "./explorer/build.js";
+export { EXPLORER_FORMAT, EXPLORER_EDGE_KINDS } from "./explorer/types.js";
+export type {
+  ExplorerJson,
+  ExplorerNode,
+  ExplorerEdge,
+  ExplorerEdgeKind,
+  ExplorerLedger,
+  ExplorerLedgerRow,
+  ExplorerGenerated,
+  ExplorerGeneratedFile,
+  ExplorerSlice,
+  ExplorerSliceKind,
+} from "./explorer/types.js";
diff --git a/server/typescript/packages/docs-site/test/explorer-build.test.ts b/server/typescript/packages/docs-site/test/explorer-build.test.ts
new file mode 100644
index 0000000000..00718de1eb
--- /dev/null
+++ b/server/typescript/packages/docs-site/test/explorer-build.test.ts
@@ -0,0 +1,125 @@
+// `buildExplorer` — the explorer data spine — over the committed conformance fixture
+// (`fixtures/explorer-conformance/shop/`), checked byte for byte, plus the behaviour a
+// byte check alone would not explain when it breaks.
+import { describe, test, expect } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { buildExplorer, serializeExplorer, type ExplorerJson } from "../src/index.js";
+
+const FIXTURE = resolve(import.meta.dir, "../../../../../fixtures/explorer-conformance/shop");
+const text = (name: string): string => readFileSync(join(FIXTURE, name), "utf8");
+const json = (name: string): unknown => JSON.parse(text(name));
+
+function build(parts: { verify?: boolean; manifest?: boolean } = { verify: true, manifest: true }): ExplorerJson {
+  return buildExplorer({
+    model: json("effective.json"),
+    ...(parts.verify ? { verify: json("verify.json") } : {}),
+    ...(parts.manifest ? { manifest: json("hashes.json") } : {}),
+  });
+}
+
+describe("explorer-conformance/shop", () => {
+  test("builds expected.json byte for byte", () => {
+    expect(serializeExplorer(build())).toBe(text("expected.json"));
+  });
+
+  test("object key order in the model and the manifest does not change the bytes", () => {
+    const reversed = (v: unknown): unknown =>
+      Array.isArray(v) ? v.map(reversed)
+        : typeof v === "object" && v !== null
+          ? Object.fromEntries(Object.entries(v).reverse().map(([k, x]) => [k, reversed(x)]))
+          : v;
+    const explorer = buildExplorer({
+      model: reversed(json("effective.json")),
+      verify: json("verify.json"),
+      manifest: reversed(json("hashes.json")),
+    });
+    expect(serializeExplorer(explorer)).toBe(text("expected.json"));
+  });
+});
+
+describe("buildExplorer", () => {
+  test("marks inherited members with the object that declares them", () => {
+    const nodes = new Map(build().nodes.map((n) => [n.id, n]));
+    expect(nodes.get("acme::shop::Order.id")?.inheritedFrom).toBe("acme::shop::BaseEntity");
+    expect(nodes.get("acme::shop::Order.total")?.inheritedFrom).toBeUndefined();
+    // AuditEntry declares its own `id` and does not extend BaseEntity.
+    expect(nodes.get("acme::shop::AuditEntry.id")?.inheritedFrom).toBeUndefined();
+  });
+
+  test("an implementedBy edge exists only where the verify ledger resolved the link", () => {
+    const withVerify = build().edges.filter((e) => e.kind === "implementedBy");
+    expect(withVerify).toContainEqual({ kind: "implementedBy", from: "acme::shop::Shop.Checkout.Orders.Recorded.Quotable", to: "acme::shop::Order.reference" });
+    // `Refunded` names `Refund`, which does not exist: a ledger row, no edge.
+    expect(withVerify.some((e) => e.from.endsWith("Refunded"))).toBe(false);
+    expect(build({ manifest: true }).edges.some((e) => e.kind === "implementedBy")).toBe(false);
+    expect(build({ manifest: true }).ledger).toBeUndefined();
+  });
+
+  test("generated groups the manifest's attributed files by node; plain entries are skipped", () => {
+    expect(build().generated?.map((g) => g.node)).toEqual(["acme::shop::Customer", "acme::shop::Order"]);
+    expect(build({ verify: true }).generated).toBeUndefined();
+  });
+
+  test("a requirement slice holds the subtree, its targets and the owner of a claimed member", () => {
+    const slice = build().slices.find((s) => s.id === "requirement:acme::shop::Shop.Checkout.Orders.Recorded");
+    expect(slice?.nodes).toEqual([
+      "acme::shop::Customer",
+      "acme::shop::Order",
+      "acme::shop::Order.reference",
+      "acme::shop::Shop.Checkout.Orders.Recorded",
+      "acme::shop::Shop.Checkout.Orders.Recorded.Quotable",
+    ]);
+  });
+
+  test("rejects input that is not canonical metadata JSON", () => {
+    expect(() => buildExplorer({ model: { nodes: [] } })).toThrow(/not canonical metadata JSON/);
+  });
+
+  test("a sibling sharing a member's name gets a type-qualified id; the member keeps the plain one", () => {
+    const nodes = new Map(build().nodes.map((n) => [n.id, n]));
+    expect(nodes.get("acme::shop::AuditEntry.id")?.type).toBe("field");
+    expect(nodes.get("acme::shop::AuditEntry.id[identity.primary]")?.type).toBe("identity");
+  });
+
+  test("rejects two top-level nodes sharing an id", () => {
+    const model = {
+      "metadata.root": {
+        package: "p",
+        children: [
+          { "object.entity": { name: "A" } },
+          { "object.value": { name: "A" } },
+        ],
+      },
+    };
+    expect(() => buildExplorer({ model })).toThrow(/two nodes share the id "p::A"/);
+  });
+
+  test("a root-level target spelled `::Name` still gets its edges and inheritedFrom", () => {
+    const idField = { name: "id", type: "long" };
+    const model = {
+      "metadata.root": {
+        children: [
+          { "object.entity": { name: "BaseEntity", abstract: true, children: [{ "field.long": idField }] } },
+          {
+            "object.entity": {
+              name: "Order",
+              package: "acme::shop",
+              extends: "::BaseEntity",
+              children: [
+                { "field.long": idField },
+                { "relationship.association": { name: "owner", "@objectRef": "::BaseEntity" } },
+              ],
+            },
+          },
+        ],
+      },
+    };
+    const built = buildExplorer({ model });
+    const nodes = new Map(built.nodes.map((n) => [n.id, n]));
+    expect(nodes.get("acme::shop::Order")?.extends).toBe("BaseEntity");
+    expect(nodes.get("acme::shop::Order.id")?.inheritedFrom).toBe("BaseEntity");
+    expect(built.edges).toContainEqual({ kind: "extends", from: "acme::shop::Order", to: "BaseEntity" });
+    expect(built.edges).toContainEqual({ kind: "association", from: "acme::shop::Order", to: "BaseEntity", via: "acme::shop::Order.owner" });
+  });
+});

From 32cc7ff06af70dcba7c55598dd952b770890b786 Mon Sep 17 00:00:00 2001
From: Doug Mealing 
Date: Wed, 4 Nov 2026 10:28:11 -0500
Subject: [PATCH 08/51] Refuse two providers claiming one attribute name on a
 node type (#533)

* feat(metadata): refuse two providers claiming one attribute name on a node type (#527)

The registry now records which provider registered each attribute and refuses a
second provider's claim at composition, in TypeScript, Python, C#, Java and Kotlin.

- Same (type, subType): ERR_PROVIDER_ATTR_CONFLICT, message now names the owner.
- Shared .base root or a descendant subtype: new ERR_PROVIDER_ATTR_SHADOW,
  checked in both directions so registration order does not matter.
- The same provider repeating its own name, sibling subtypes, and registration
  outside a provider's turn stay legal. A refusal leaves nothing in the registry.
- The rule is scoped to one node type so the JVM registry's metadata.base chain
  does not make Java stricter than the other ports; the shipped core has no collision.
- meta types --detail prints the registering provider; JSON carries `provider`.
- ADR-0062, extending-with-providers docs, authoring skill, CHANGELOG, and shared
  provider-composition fixtures (attr-shadow-*, attr-ownership/).

No wire-name attribute is added.

Fixes #527

* no-mistakes(review): apply reviewer inline fixes

* no-mistakes(review): Close Java extend shadow gap; refuse duplicate common attrs

* no-mistakes(review): Refuse common-vs-per-type attr collisions; Java @description single owner

* no-mistakes(review): apply reviewer inline fixes

* no-mistakes(document): Fixed three stale doc spots: Java manifest comment, provider-composition README code count, stray CHANGELOG blank line. Docs state the full ADR-0062 rule. No unresolved findings.
---
 CHANGELOG.md                                  |  23 ++
 .../references/choosing-a-shape.md            |   8 +
 docs/CONFORMANCE.md                           |   2 +-
 docs/features/extending-with-providers.md     |  29 +-
 .../references/choosing-a-shape.md            |   8 +
 .../references/choosing-a-shape.md            |   8 +
 .../references/choosing-a-shape.md            |   8 +
 .../references/choosing-a-shape.md            |   8 +
 .../references/choosing-a-shape.md            |   8 +
 fixtures/conformance/ERROR-CODES.json         |   3 +-
 .../README.md                                 |  72 ++++-
 .../attr-ownership/common-attr-owners.json    |  25 ++
 .../attr-ownership/distinct-names-load.json   |  21 ++
 .../same-provider-redeclare.json              |  20 ++
 .../attr-shadow-descendant.json               |   8 +
 .../attr-shadow-extend.json                   |   9 +
 .../attr-shadow-inherited.json                |   8 +
 .../common-attr-conflict.json                 |   8 +
 .../common-attr-per-type-after.json           |   8 +
 .../common-attr-per-type-before.json          |   8 +
 scripts/check-doc-examples.ts                 |   1 +
 .../AttrOwnershipTests.cs                     | 150 +++++++++
 .../ProviderCompositionConformanceTests.cs    | 153 +++++++++
 server/csharp/MetaObjects/Errors.cs           |   3 +
 server/csharp/MetaObjects/Registry.cs         | 124 ++++++-
 .../main/java/com/metaobjects/ErrorCode.java  |   6 +
 .../main/java/com/metaobjects/MetaData.java   |   4 +-
 .../metaobjects/identity/PrimaryIdentity.java |   2 -
 .../identity/ReferenceIdentity.java           |   3 -
 .../identity/SecondaryIdentity.java           |   2 -
 .../com/metaobjects/index/LookupIndex.java    |   5 -
 .../com/metaobjects/object/MetaObject.java    |   1 -
 .../registry/MetaDataRegistry.java            | 305 +++++++++++++++---
 .../registry/RegistryManifest.java            |  18 +-
 .../registry/TypeDefinitionBuilder.java       |  34 +-
 .../relationship/MetaRelationship.java        |   6 -
 .../ProviderCompositionConformanceTest.java   | 162 ++++++++++
 .../registry/AttrOwnershipTest.java           | 171 ++++++++++
 .../RegistryManifestConformanceTest.java      |   2 -
 server/python/src/metaobjects/errors.py       |   3 +
 server/python/src/metaobjects/registry.py     |  97 +++++-
 .../test_provider_composition_conformance.py  |  95 ++++++
 .../unit/test_registry_attr_ownership.py      | 117 +++++++
 .../packages/cli/src/commands/types.ts        |  28 +-
 .../packages/cli/test/types-command.test.ts   |  23 ++
 .../packages/metadata/src/errors.ts           |   3 +
 .../packages/metadata/src/provider.ts         |   4 +-
 .../packages/metadata/src/registry.ts         | 157 ++++++++-
 .../metadata/src/vocabulary-catalog.ts        |  27 +-
 .../provider-composition-conformance.test.ts  | 142 +++++++-
 .../test/registry-attr-ownership.test.ts      | 125 +++++++
 .../ADR-0062-provider-attribute-ownership.md  |  97 ++++++
 spec/decisions/README.md                      |   1 +
 53 files changed, 2246 insertions(+), 117 deletions(-)
 create mode 100644 fixtures/provider-composition-conformance/attr-ownership/common-attr-owners.json
 create mode 100644 fixtures/provider-composition-conformance/attr-ownership/distinct-names-load.json
 create mode 100644 fixtures/provider-composition-conformance/attr-ownership/same-provider-redeclare.json
 create mode 100644 fixtures/provider-composition-conformance/attr-shadow-descendant.json
 create mode 100644 fixtures/provider-composition-conformance/attr-shadow-extend.json
 create mode 100644 fixtures/provider-composition-conformance/attr-shadow-inherited.json
 create mode 100644 fixtures/provider-composition-conformance/common-attr-conflict.json
 create mode 100644 fixtures/provider-composition-conformance/common-attr-per-type-after.json
 create mode 100644 fixtures/provider-composition-conformance/common-attr-per-type-before.json
 create mode 100644 server/csharp/MetaObjects.Conformance.Tests/AttrOwnershipTests.cs
 create mode 100644 server/java/metadata/src/test/java/com/metaobjects/registry/AttrOwnershipTest.java
 create mode 100644 server/python/tests/unit/test_registry_attr_ownership.py
 create mode 100644 server/typescript/packages/metadata/test/registry-attr-ownership.test.ts
 create mode 100644 spec/decisions/ADR-0062-provider-attribute-ownership.md

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 42ce430fcf..9d1633e25f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,6 +26,29 @@ here.**
   declared rule is now rejected at the model where it used to reach the database. Gated by
   `fixtures/validation-conformance/cross-field-cases.json` in all five ports.
 
+- **Two providers can no longer claim one attribute name on a node type.** The registry now
+  records which provider registered each attribute and refuses a second provider's claim at
+  composition, in all five ports (TypeScript, Python, C#, Java, Kotlin). A repeat on the same
+  `(type, subType)` keeps `ERR_PROVIDER_ATTR_CONFLICT` (its message now names the owner); a name
+  another provider already holds on the shared root or a descendant subtype is the new
+  `ERR_PROVIDER_ATTR_SHADOW`. The refusal names both providers and the attribute, whichever
+  registers first, and leaves nothing in the registry. The same provider repeating its own name,
+  sibling subtypes sharing a name, and registration outside a provider all stay legal. The shipped
+  core providers have no such collision, so existing projects see no change. `meta types --detail`
+  prints the registering provider beside each attribute, and its JSON carries a `provider` field.
+  A common attribute is accepted on every node type, so it counts as a claim on every slot: a
+  second provider registering a common attribute name another provider holds, as a common
+  attribute or on any type, and a provider declaring a per-type attribute whose name another
+  provider registered as common, are both `ERR_PROVIDER_ATTR_CONFLICT`, in either order (two
+  common registrations used to be first-wins). The registry records each common attribute's
+  provider. Java's core providers no longer declare a per-type `@description` beside the
+  documentation provider's common one (same type, same meaning); `@description` is still accepted
+  on every node. This is how per-paradigm physical-name words (`@column`, `@field`) stay safe as
+  providers multiply; no wire-name attribute is added. See ADR-0062 and
+  `docs/features/extending-with-providers.md`. New conformance fixtures: `attr-shadow-inherited`,
+  `attr-shadow-descendant`, `attr-shadow-extend`, `common-attr-conflict`,
+  `common-attr-per-type-after`, `common-attr-per-type-before` and the `attr-ownership/` sub-corpus. Fixes #527.
+
 ### Fixed
 
 - **TypeScript: every `meta` command now loads the providers in `metaobjects.config.ts`.**
diff --git a/agent-context/skills/metaobjects-authoring/references/choosing-a-shape.md b/agent-context/skills/metaobjects-authoring/references/choosing-a-shape.md
index ee3b6858a5..bb4979af93 100644
--- a/agent-context/skills/metaobjects-authoring/references/choosing-a-shape.md
+++ b/agent-context/skills/metaobjects-authoring/references/choosing-a-shape.md
@@ -186,6 +186,14 @@ and address-free — the subtype names the *concept*; transport/protocol is a cl
 Declare config as the *names* of required keys (values stay in env/config) and
 generate a fail-closed check. Reference typed payloads instead of inlining shapes.
 
+**Name your attributes so they cannot collide.** Two providers may not claim one attribute
+name on a node type (ADR-0062): the registry refuses the second at composition with
+`ERR_PROVIDER_ATTR_CONFLICT` (same `(type, subType)`) or `ERR_PROVIDER_ATTR_SHADOW` (the shared
+`.base` root, or a subtype of it), naming both providers. A physical address takes your
+store's own idiomatic word (`@column` relational, `@field` document), unique on that node type;
+`meta types --detail` shows which provider holds each name. A store with no provider of its own
+uses the registered `attr.properties` bag rather than an invented attribute.
+
 **Lifecycle.** Register with explicit provider wiring — never loosen `strict` to
 free-ride ad-hoc attrs. When core later ships the concept your provider shrinks from
 `register` to `extend` (the `template.toolcall` precedent). A second independent
diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md
index f7200848bc..cf6542d422 100644
--- a/docs/CONFORMANCE.md
+++ b/docs/CONFORMANCE.md
@@ -45,7 +45,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor
 | [`fixtures/template-codegen-conformance/`](../fixtures/template-codegen-conformance/) | 3 | ✓ | ✓ | ✓ | ✓ | ✓ |
 | [`fixtures/template-output-render-conformance/`](../fixtures/template-output-render-conformance/) | 5 | ✓ | ✓ | ✓ | ✓ | ✓ |
 | [`fixtures/generator-registry-conformance/`](../fixtures/generator-registry-conformance/) | 1 canonical manifest | ✓ | ✓ | ✓ | ✓ | ✓ |
-| [`fixtures/provider-composition-conformance/`](../fixtures/provider-composition-conformance/) | 9 (5 error-shape + 4 compose-load) | ✓ | ✓ | — (JVM registry via Java) | ✓ | ✓ |
+| [`fixtures/provider-composition-conformance/`](../fixtures/provider-composition-conformance/) | 18 (11 error-shape + 4 compose-load + 3 attr-ownership) | ✓ | ✓ | — (JVM registry via Java) | ✓ | ✓ |
 | [`fixtures/source-resolution-conformance/`](../fixtures/source-resolution-conformance/) | 25 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ |
 | [`fixtures/scope-conformance/`](../fixtures/scope-conformance/) | 10 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ |
 | [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 37 cases (26 resolution + 11 check) + 14 transport cases | ✓ (reference implementation; all three arms) | ✓ (resolution arm, all 26; no check, so the 11 check cases are not run) | inherits via Java | ✓ (resolution arm, all 26; no check, so the 11 check cases are not run) | ✓ (resolution arm, all 26 identically; no check yet, so the 11 check cases are not run; the transport arm is Node-only) |
diff --git a/docs/features/extending-with-providers.md b/docs/features/extending-with-providers.md
index be13b96183..d2e1383c56 100644
--- a/docs/features/extending-with-providers.md
+++ b/docs/features/extending-with-providers.md
@@ -39,9 +39,9 @@ unregistered id throws `ERR_PROVIDER_MISSING_DEPENDENCY`; a cycle throws
 `ERR_PROVIDER_DUPLICATE_ID`. All three codes are stable across ports — see
 [`../../fixtures/conformance/ERROR-CODES.json`](../../fixtures/conformance/ERROR-CODES.json).
 
-## The two rules that govern every provider
+## The three rules that govern every provider
 
-Before the mechanics, the two rules a provider must obey. Both are machine-enforced —
+Before the mechanics, the three rules a provider must obey. All three are machine-enforced —
 you will hit an error, not a review comment.
 
 ### 1. Own vs projected attributes (ADR-0050)
@@ -80,6 +80,28 @@ So vendor or domain vocabulary enters by **registration**:
 "Declared" includes "declared by your provider" — that is what keeps strict provenance
 meaningful while still letting you extend the metamodel.
 
+### 3. One attribute name, one provider, per node type (ADR-0062)
+
+**Two providers may not claim the same attribute name on a node type.** The registry records
+which provider registered each attribute, and refuses a second provider's claim at composition:
+
+- on the same `(type, subType)` — `ERR_PROVIDER_ATTR_CONFLICT`;
+- on the shared root `(type, base)` that the subtype inherits from, or on a subtype of it —
+  `ERR_PROVIDER_ATTR_SHADOW`, whether the second provider registers the type or `extend`s it;
+- as a common attribute (accepted on every node type), or on any type when another provider
+  already registered it as a common attribute — `ERR_PROVIDER_ATTR_CONFLICT`. A common attribute
+  is on every slot, so it collides with the same name on any type, in either order.
+
+The message names both providers and the attribute. The check runs both ways, so it does not
+matter which provider registers first. The same provider repeating its own name, sibling
+subtypes using one name, and registration outside a provider's turn are all legal.
+
+This is what keeps per-paradigm physical names safe (ADR-0007, ADR-0018). Name your store's
+address in your store's own word (`@column` for a relational field, `@field` for a document
+field) and pick a word no other provider on that node type already holds. A store you have no
+provider for goes in the `attr.properties` bag, not an invented attribute. `meta types
+--detail` prints the registering provider next to each attribute, so you can see what is taken.
+
 ## What modularity does and does not mean
 
 > **MetaObjects modularity is additive and behavioural, never subtractive: every port
@@ -499,7 +521,8 @@ Composition surfaces these codes consistently across all ports (see
 | `ERR_PROVIDER_DUPLICATE_ID` | Two provider objects report the same `id` | `provider-extension-duplicate-id` |
 | `ERR_PROVIDER_MISSING_DEPENDENCY` | Provider declares dep on an unregistered id | `provider-extension-missing-dependency` |
 | `ERR_PROVIDER_DEPENDENCY_CYCLE` | Provider dependencies form a cycle | `provider-extension-dependency-cycle` |
-| `ERR_PROVIDER_ATTR_CONFLICT` | Two providers declare the same attr on the same `(type, subType)` | (covered by negative tests in core) |
+| `ERR_PROVIDER_ATTR_CONFLICT` | Two providers declare the same attr on the same `(type, subType)`, or one registers a common attr whose name the other holds as a common attr or on any type | `attr-conflict`, `common-attr-conflict`, `common-attr-per-type-after`, `common-attr-per-type-before` (provider-composition corpus) |
+| `ERR_PROVIDER_ATTR_SHADOW` | A provider declares an attr another provider already holds on the shared root or a descendant subtype of the same type | `attr-shadow-inherited`, `attr-shadow-descendant`, `attr-shadow-extend` (provider-composition corpus) |
 
 Each conformance fixture's `providers.json: string[]` lists the provider ids to
 compose for that test — the same wire format consumers use at runtime. Each
diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
index ee3b6858a5..bb4979af93 100644
--- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
+++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
@@ -186,6 +186,14 @@ and address-free — the subtype names the *concept*; transport/protocol is a cl
 Declare config as the *names* of required keys (values stay in env/config) and
 generate a fail-closed check. Reference typed payloads instead of inlining shapes.
 
+**Name your attributes so they cannot collide.** Two providers may not claim one attribute
+name on a node type (ADR-0062): the registry refuses the second at composition with
+`ERR_PROVIDER_ATTR_CONFLICT` (same `(type, subType)`) or `ERR_PROVIDER_ATTR_SHADOW` (the shared
+`.base` root, or a subtype of it), naming both providers. A physical address takes your
+store's own idiomatic word (`@column` relational, `@field` document), unique on that node type;
+`meta types --detail` shows which provider holds each name. A store with no provider of its own
+uses the registered `attr.properties` bag rather than an invented attribute.
+
 **Lifecycle.** Register with explicit provider wiring — never loosen `strict` to
 free-ride ad-hoc attrs. When core later ships the concept your provider shrinks from
 `register` to `extend` (the `template.toolcall` precedent). A second independent
diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
index ee3b6858a5..bb4979af93 100644
--- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
+++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
@@ -186,6 +186,14 @@ and address-free — the subtype names the *concept*; transport/protocol is a cl
 Declare config as the *names* of required keys (values stay in env/config) and
 generate a fail-closed check. Reference typed payloads instead of inlining shapes.
 
+**Name your attributes so they cannot collide.** Two providers may not claim one attribute
+name on a node type (ADR-0062): the registry refuses the second at composition with
+`ERR_PROVIDER_ATTR_CONFLICT` (same `(type, subType)`) or `ERR_PROVIDER_ATTR_SHADOW` (the shared
+`.base` root, or a subtype of it), naming both providers. A physical address takes your
+store's own idiomatic word (`@column` relational, `@field` document), unique on that node type;
+`meta types --detail` shows which provider holds each name. A store with no provider of its own
+uses the registered `attr.properties` bag rather than an invented attribute.
+
 **Lifecycle.** Register with explicit provider wiring — never loosen `strict` to
 free-ride ad-hoc attrs. When core later ships the concept your provider shrinks from
 `register` to `extend` (the `template.toolcall` precedent). A second independent
diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
index ee3b6858a5..bb4979af93 100644
--- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
+++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
@@ -186,6 +186,14 @@ and address-free — the subtype names the *concept*; transport/protocol is a cl
 Declare config as the *names* of required keys (values stay in env/config) and
 generate a fail-closed check. Reference typed payloads instead of inlining shapes.
 
+**Name your attributes so they cannot collide.** Two providers may not claim one attribute
+name on a node type (ADR-0062): the registry refuses the second at composition with
+`ERR_PROVIDER_ATTR_CONFLICT` (same `(type, subType)`) or `ERR_PROVIDER_ATTR_SHADOW` (the shared
+`.base` root, or a subtype of it), naming both providers. A physical address takes your
+store's own idiomatic word (`@column` relational, `@field` document), unique on that node type;
+`meta types --detail` shows which provider holds each name. A store with no provider of its own
+uses the registered `attr.properties` bag rather than an invented attribute.
+
 **Lifecycle.** Register with explicit provider wiring — never loosen `strict` to
 free-ride ad-hoc attrs. When core later ships the concept your provider shrinks from
 `register` to `extend` (the `template.toolcall` precedent). A second independent
diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
index ee3b6858a5..bb4979af93 100644
--- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
+++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
@@ -186,6 +186,14 @@ and address-free — the subtype names the *concept*; transport/protocol is a cl
 Declare config as the *names* of required keys (values stay in env/config) and
 generate a fail-closed check. Reference typed payloads instead of inlining shapes.
 
+**Name your attributes so they cannot collide.** Two providers may not claim one attribute
+name on a node type (ADR-0062): the registry refuses the second at composition with
+`ERR_PROVIDER_ATTR_CONFLICT` (same `(type, subType)`) or `ERR_PROVIDER_ATTR_SHADOW` (the shared
+`.base` root, or a subtype of it), naming both providers. A physical address takes your
+store's own idiomatic word (`@column` relational, `@field` document), unique on that node type;
+`meta types --detail` shows which provider holds each name. A store with no provider of its own
+uses the registered `attr.properties` bag rather than an invented attribute.
+
 **Lifecycle.** Register with explicit provider wiring — never loosen `strict` to
 free-ride ad-hoc attrs. When core later ships the concept your provider shrinks from
 `register` to `extend` (the `template.toolcall` precedent). A second independent
diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
index ee3b6858a5..bb4979af93 100644
--- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
+++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md
@@ -186,6 +186,14 @@ and address-free — the subtype names the *concept*; transport/protocol is a cl
 Declare config as the *names* of required keys (values stay in env/config) and
 generate a fail-closed check. Reference typed payloads instead of inlining shapes.
 
+**Name your attributes so they cannot collide.** Two providers may not claim one attribute
+name on a node type (ADR-0062): the registry refuses the second at composition with
+`ERR_PROVIDER_ATTR_CONFLICT` (same `(type, subType)`) or `ERR_PROVIDER_ATTR_SHADOW` (the shared
+`.base` root, or a subtype of it), naming both providers. A physical address takes your
+store's own idiomatic word (`@column` relational, `@field` document), unique on that node type;
+`meta types --detail` shows which provider holds each name. A store with no provider of its own
+uses the registered `attr.properties` bag rather than an invented attribute.
+
 **Lifecycle.** Register with explicit provider wiring — never loosen `strict` to
 free-ride ad-hoc attrs. When core later ships the concept your provider shrinks from
 `register` to `extend` (the `template.toolcall` precedent). A second independent
diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json
index 278b1b50f0..25ae559688 100644
--- a/fixtures/conformance/ERROR-CODES.json
+++ b/fixtures/conformance/ERROR-CODES.json
@@ -27,7 +27,8 @@
     "ERR_PROVIDER_DEPENDENCY_CYCLE": "Provider composition has a dependency cycle.",
     "ERR_PROVIDER_DUPLICATE_ID": "Two providers in a composition share the same id.",
     "ERR_PROVIDER_MISSING_DEPENDENCY": "A provider declares a dependency id with no matching provider.",
-    "ERR_PROVIDER_ATTR_CONFLICT": "A provider extend redefines an attr another provider already declared.",
+    "ERR_PROVIDER_ATTR_CONFLICT": "A provider extend redefines an attr another provider already declared, or a provider registers a common attr whose name another provider holds as a common attr or on any type, or the reverse (ADR-0062).",
+    "ERR_PROVIDER_ATTR_SHADOW": "A provider declares an attribute name on a type that another provider already declares on a related slot: the type it inherits from (.base), or a subtype that inherits from it (ADR-0062). Two providers may not claim one attribute name on a node type; the second needs its own idiomatic name. The same provider re-declaring its own attribute stays legal.",
     "ERR_EXTEND_REQUIRED_ATTR": "A provider tried to project a REQUIRED attribute onto a type it does not own (via extends). Projection is optional-only: a required attr registered this way disappears silently whenever that provider is composed out, taking its validation rule with it. Declare it with the type instead (ADR-0050).",
     "ERR_SUBTYPE_RULE_VIOLATION": "A node violates a subtype composition rule (e.g. a value object with an identity or a source — FR-024 value purity; a projection extending a non-projection — FR-024/ADR-0028).",
     "ERR_OVERLAY_NO_TARGET": "An overlay node has no existing target to merge into.",
diff --git a/fixtures/provider-composition-conformance/README.md b/fixtures/provider-composition-conformance/README.md
index 8ba95d0a90..8d44e8a12b 100644
--- a/fixtures/provider-composition-conformance/README.md
+++ b/fixtures/provider-composition-conformance/README.md
@@ -1,6 +1,6 @@
 # provider-composition conformance
 
-Five registry/provider error codes are Tier-1 cross-port invariants that the
+Six registry/provider error codes are Tier-1 cross-port invariants that the
 existing `fixtures/conformance/error-*` corpus **cannot** reach: that corpus is
 metadata-input → error, but these codes are triggered by *how providers are
 composed and sealed*, not by any metadata document. This small corpus gates them
@@ -11,7 +11,8 @@ cross-port.
 | `ERR_PROVIDER_DUPLICATE_ID` | Two providers in a composition report the same `id`. |
 | `ERR_PROVIDER_MISSING_DEPENDENCY` | A provider declares a dependency id absent from the set. |
 | `ERR_PROVIDER_DEPENDENCY_CYCLE` | Providers form a dependency cycle (topo-sort cannot proceed). |
-| `ERR_PROVIDER_ATTR_CONFLICT` | A provider `extend`s a type, redefining an attr another provider already declared. |
+| `ERR_PROVIDER_ATTR_CONFLICT` | A provider `extend`s a type, redefining an attr another provider already declared; or a common attr and another provider's common or per-type attr share a name, in either order (ADR-0062). |
+| `ERR_PROVIDER_ATTR_SHADOW` | A provider declares an attr name that another provider already declares on the type it inherits from (`.base`), or on a subtype that inherits from it, whether it registers or `extend`s the type (ADR-0062). |
 | `ERR_REGISTRY_SEALED` | A registration is attempted against a registry sealed after bootstrap (ADR-0023). |
 
 ## Corpus shape
@@ -112,6 +113,73 @@ Composing `["attr-conflict-base", "attr-conflict-clash"]` → `ERR_PROVIDER_ATTR
   sealed registry this must throw `ERR_REGISTRY_SEALED`. This provider is **only**
   used via a manifest's `sealThenRegister` — never composed directly.
 
+### Attribute-ownership providers (ADR-0062)
+
+All six register on the `template` type's shared root (`template.base`) and one fresh
+subtype `template.shadowprobe`; each attr is a single optional string. They compose on
+their own (no `composeWithCore`), so each registers the root it needs.
+
+| id | dependencies | registers |
+|----|--------------|-----------|
+| `shadow-base` | none | `template.base` with attr `shadowAttr`. |
+| `shadow-sub-clash` | `shadow-base` | `template.shadowprobe` with attr `shadowAttr` (the name `shadow-base` owns on the root). |
+| `shadow-sub-owner` | none | `template.shadowprobe` with attr `reverseAttr`. |
+| `shadow-base-late` | `shadow-sub-owner` | `template.base` with attr `reverseAttr` (the name `shadow-sub-owner` owns on the subtype). |
+| `shadow-sub-distinct` | `shadow-base` | `template.shadowprobe` with attr `distinctAttr`. |
+| `shadow-self` | none | `template.base` with attr `selfAttr`, then `template.shadowprobe` with the SAME attr `selfAttr`. |
+| `shadow-sub-extend-clash` | `shadow-sub-distinct` | `extend`s `template.shadowprobe` with attr `shadowAttr` (the name `shadow-base` owns on the root, which the subtype only inherits). |
+
+Composing `["shadow-base", "shadow-sub-clash"]` and `["shadow-sub-owner", "shadow-base-late"]`
+→ `ERR_PROVIDER_ATTR_SHADOW` (the two directions: the verdict must not depend on which
+provider registered first). Composing `["shadow-base", "shadow-sub-distinct", "shadow-sub-extend-clash"]`
+→ `ERR_PROVIDER_ATTR_SHADOW` too: `extend` is held to the same rule as `register`. Two providers
+claiming one name on the SAME type is the existing `attr-conflict` scenario
+(`ERR_PROVIDER_ATTR_CONFLICT`).
+
+The common-attr providers each register one optional string common attr:
+
+| id | dependencies | registers |
+|----|--------------|-----------|
+| `common-owner` | none | common attr `commonAttr`. |
+| `common-clash` | `common-owner` | common attr `commonAttr` (the name `common-owner` owns). |
+| `common-self` | none | common attr `selfCommonAttr`, then `template.shadowprobe` with attr `selfCommonAttr`, then the SAME common attr again. |
+| `common-sub-clash` | `common-owner` | `template.shadowprobe` with attr `commonAttr` (the name `common-owner` owns as common). |
+| `common-sub-owner` | none | `template.shadowprobe` with attr `lateCommonAttr`. |
+| `common-late` | `common-sub-owner` | common attr `lateCommonAttr` (the name `common-sub-owner` owns per-type). |
+
+Composing `["common-owner", "common-clash"]`, `["common-owner", "common-sub-clash"]` and
+`["common-sub-owner", "common-late"]` → `ERR_PROVIDER_ATTR_CONFLICT`. A common attr is on every
+node type, so it collides with another provider's common attr and, in both orders, with another
+provider's per-type attr of the same name.
+
+## The `attr-ownership/` subdir (ADR-0062)
+
+Positive scenarios: composition succeeds and the registry reports which provider owns each
+attribute. Own subdirectory for the same backward-compat reason as `compose-load/` (the flat
+runners list the parent non-recursively and require `expectedError`). Shape:
+
+```jsonc
+{
+  "description": "...",
+  "providers": ["shadow-base", "shadow-sub-distinct"],   // composed in listed order; must succeed
+  "expectOwners": [                                      // OPTIONAL — the port's per-slot attr-owner lookup
+    { "type": "template", "subType": "base", "attr": "shadowAttr", "owner": "shadow-base" }
+  ],
+  "expectCommonOwners": [                                // OPTIONAL — the port's common-attr owner lookup
+    { "attr": "commonAttr", "owner": "common-owner" }
+  ]
+}
+```
+
+A manifest carries at least one of `expectOwners` / `expectCommonOwners`.
+
+`expectOwners` asks for the provider that registered `attr` on exactly `(type, subType)` — an
+inherited attr is asked of the slot that declares it. `distinct-names-load.json` proves distinct
+names load; `same-provider-redeclare.json` proves one provider re-declaring its own name on a type
+and on the type it inherits from stays legal; `common-attr-owners.json` proves distinct common attr
+names from two providers load, one provider declaring its own common attr name per-type and
+re-registering the common attr stays legal, and each port reports the same owners.
+
 ## Notes
 
 - `ERR_REGISTRY_SEALED` is a **five-port** invariant here. It was previously exercised
diff --git a/fixtures/provider-composition-conformance/attr-ownership/common-attr-owners.json b/fixtures/provider-composition-conformance/attr-ownership/common-attr-owners.json
new file mode 100644
index 0000000000..285e042179
--- /dev/null
+++ b/fixtures/provider-composition-conformance/attr-ownership/common-attr-owners.json
@@ -0,0 +1,25 @@
+{
+  "description": "Two providers registering DISTINCT common attr names compose cleanly, one provider declaring its own common attr name per-type and re-registering it as a common attr stays legal, and the registry records which provider owns each common attr and each per-type attr.",
+  "providers": [
+    "common-owner",
+    "common-self"
+  ],
+  "expectOwners": [
+    {
+      "type": "template",
+      "subType": "shadowprobe",
+      "attr": "selfCommonAttr",
+      "owner": "common-self"
+    }
+  ],
+  "expectCommonOwners": [
+    {
+      "attr": "commonAttr",
+      "owner": "common-owner"
+    },
+    {
+      "attr": "selfCommonAttr",
+      "owner": "common-self"
+    }
+  ]
+}
diff --git a/fixtures/provider-composition-conformance/attr-ownership/distinct-names-load.json b/fixtures/provider-composition-conformance/attr-ownership/distinct-names-load.json
new file mode 100644
index 0000000000..0fa2c8271d
--- /dev/null
+++ b/fixtures/provider-composition-conformance/attr-ownership/distinct-names-load.json
@@ -0,0 +1,21 @@
+{
+  "description": "Two providers declaring DISTINCT attr names on a type and the type it inherits from compose cleanly, and the registry records which provider owns each attribute.",
+  "providers": [
+    "shadow-base",
+    "shadow-sub-distinct"
+  ],
+  "expectOwners": [
+    {
+      "type": "template",
+      "subType": "base",
+      "attr": "shadowAttr",
+      "owner": "shadow-base"
+    },
+    {
+      "type": "template",
+      "subType": "shadowprobe",
+      "attr": "distinctAttr",
+      "owner": "shadow-sub-distinct"
+    }
+  ]
+}
diff --git a/fixtures/provider-composition-conformance/attr-ownership/same-provider-redeclare.json b/fixtures/provider-composition-conformance/attr-ownership/same-provider-redeclare.json
new file mode 100644
index 0000000000..a8b5d9fc07
--- /dev/null
+++ b/fixtures/provider-composition-conformance/attr-ownership/same-provider-redeclare.json
@@ -0,0 +1,20 @@
+{
+  "description": "One provider declaring the same attr name on a type and on the type it inherits from stays legal; the registry records that provider as owner of both.",
+  "providers": [
+    "shadow-self"
+  ],
+  "expectOwners": [
+    {
+      "type": "template",
+      "subType": "base",
+      "attr": "selfAttr",
+      "owner": "shadow-self"
+    },
+    {
+      "type": "template",
+      "subType": "shadowprobe",
+      "attr": "selfAttr",
+      "owner": "shadow-self"
+    }
+  ]
+}
diff --git a/fixtures/provider-composition-conformance/attr-shadow-descendant.json b/fixtures/provider-composition-conformance/attr-shadow-descendant.json
new file mode 100644
index 0000000000..8e932880c4
--- /dev/null
+++ b/fixtures/provider-composition-conformance/attr-shadow-descendant.json
@@ -0,0 +1,8 @@
+{
+  "description": "A provider declares an attr on the shared root (.base) after another provider declared that name on a subtype that inherits from it (the verdict must not depend on registration order).",
+  "providers": [
+    "shadow-sub-owner",
+    "shadow-base-late"
+  ],
+  "expectedError": "ERR_PROVIDER_ATTR_SHADOW"
+}
diff --git a/fixtures/provider-composition-conformance/attr-shadow-extend.json b/fixtures/provider-composition-conformance/attr-shadow-extend.json
new file mode 100644
index 0000000000..4db73a32ee
--- /dev/null
+++ b/fixtures/provider-composition-conformance/attr-shadow-extend.json
@@ -0,0 +1,9 @@
+{
+  "description": "A provider extends a subtype with an attr name that another provider already declares on the subtype's shared root (.base). The subtype only inherits the name, so the extend is a shadow, not a same-slot redefinition.",
+  "providers": [
+    "shadow-base",
+    "shadow-sub-distinct",
+    "shadow-sub-extend-clash"
+  ],
+  "expectedError": "ERR_PROVIDER_ATTR_SHADOW"
+}
diff --git a/fixtures/provider-composition-conformance/attr-shadow-inherited.json b/fixtures/provider-composition-conformance/attr-shadow-inherited.json
new file mode 100644
index 0000000000..1d959ba527
--- /dev/null
+++ b/fixtures/provider-composition-conformance/attr-shadow-inherited.json
@@ -0,0 +1,8 @@
+{
+  "description": "A provider declares an attr on a subtype whose shared root (.base) another provider already declares with that name.",
+  "providers": [
+    "shadow-base",
+    "shadow-sub-clash"
+  ],
+  "expectedError": "ERR_PROVIDER_ATTR_SHADOW"
+}
diff --git a/fixtures/provider-composition-conformance/common-attr-conflict.json b/fixtures/provider-composition-conformance/common-attr-conflict.json
new file mode 100644
index 0000000000..40d0af620a
--- /dev/null
+++ b/fixtures/provider-composition-conformance/common-attr-conflict.json
@@ -0,0 +1,8 @@
+{
+  "description": "A provider registers a common attr whose name another provider already registers as a common attr.",
+  "providers": [
+    "common-owner",
+    "common-clash"
+  ],
+  "expectedError": "ERR_PROVIDER_ATTR_CONFLICT"
+}
diff --git a/fixtures/provider-composition-conformance/common-attr-per-type-after.json b/fixtures/provider-composition-conformance/common-attr-per-type-after.json
new file mode 100644
index 0000000000..3473184de8
--- /dev/null
+++ b/fixtures/provider-composition-conformance/common-attr-per-type-after.json
@@ -0,0 +1,8 @@
+{
+  "description": "A provider declares a per-type attr whose name another provider already registers as a common attr (accepted on every node type).",
+  "providers": [
+    "common-owner",
+    "common-sub-clash"
+  ],
+  "expectedError": "ERR_PROVIDER_ATTR_CONFLICT"
+}
diff --git a/fixtures/provider-composition-conformance/common-attr-per-type-before.json b/fixtures/provider-composition-conformance/common-attr-per-type-before.json
new file mode 100644
index 0000000000..d7971f5395
--- /dev/null
+++ b/fixtures/provider-composition-conformance/common-attr-per-type-before.json
@@ -0,0 +1,8 @@
+{
+  "description": "A provider registers a common attr (accepted on every node type) whose name another provider already declares per-type. The reverse order of common-attr-per-type-after; the verdict must not depend on which provider registers first.",
+  "providers": [
+    "common-sub-owner",
+    "common-late"
+  ],
+  "expectedError": "ERR_PROVIDER_ATTR_CONFLICT"
+}
diff --git a/scripts/check-doc-examples.ts b/scripts/check-doc-examples.ts
index 37ad016a7d..97ea0ee1a6 100644
--- a/scripts/check-doc-examples.ts
+++ b/scripts/check-doc-examples.ts
@@ -229,6 +229,7 @@ const FRAGMENT_CODES = new Set([
   // Environment-shaped: about the registry/provider wiring, never about the example.
   "ERR_REGISTRY_SEALED",
   "ERR_PROVIDER_ATTR_CONFLICT",
+  "ERR_PROVIDER_ATTR_SHADOW",
   "ERR_PROVIDER_DEPENDENCY_CYCLE",
   "ERR_PROVIDER_DUPLICATE_ID",
   "ERR_PROVIDER_MISSING_DEPENDENCY",
diff --git a/server/csharp/MetaObjects.Conformance.Tests/AttrOwnershipTests.cs b/server/csharp/MetaObjects.Conformance.Tests/AttrOwnershipTests.cs
new file mode 100644
index 0000000000..84f8cf9a78
--- /dev/null
+++ b/server/csharp/MetaObjects.Conformance.Tests/AttrOwnershipTests.cs
@@ -0,0 +1,150 @@
+// ADR-0062 — the registry records which provider registered each attribute and refuses a
+// second provider's claim on the same name. The cross-port scenarios live in
+// fixtures/provider-composition-conformance/; this file pins what the shared corpus cannot
+// (message text, no-trace-on-refusal, unowned registrations, the shipped core).
+
+using MetaObjects;
+using MetaObjects.Meta;
+using Xunit;
+
+namespace MetaObjects.Conformance.Tests;
+
+public sealed class AttrOwnershipTests
+{
+    private sealed class Probe : IMetaDataTypeProvider
+    {
+        private readonly Action _register;
+
+        public Probe(string id, Action register, params string[] dependencies)
+        {
+            Id = id;
+            Dependencies = dependencies;
+            _register = register;
+        }
+
+        public string Id { get; }
+        public IReadOnlyList Dependencies { get; }
+        public void RegisterTypes(TypeRegistry registry) => _register(registry);
+    }
+
+    private static TypeDefinition Def(string subType, params string[] names) =>
+        new(
+            typeId: new TypeId("template", subType),
+            description: "test",
+            childRules: new List(),
+            factory: (typeId, name) => new MetaTemplate(typeId, name),
+            attributes: names.Select(n => new AttrSchema(n, "string", Required: false, Description: n)).ToList());
+
+    [Fact]
+    public void ShadowingRegistrationNamesBothProvidersAndTheAttribute()
+    {
+        var ex = Assert.Throws(() => Provider.ComposeRegistry(new IMetaDataTypeProvider[]
+        {
+            new Probe("owner-a", r => r.Register(Def("base", "physicalName"))),
+            new Probe("owner-b", r => r.Register(Def("probe", "physicalName")), "owner-a"),
+        }));
+        Assert.Equal(ErrorCode.ERR_PROVIDER_ATTR_SHADOW, ex.Code);
+        Assert.Contains("owner-a", ex.Message);
+        Assert.Contains("owner-b", ex.Message);
+        Assert.Contains("physicalName", ex.Message);
+    }
+
+    [Fact]
+    public void ExtendOntoTheSharedRootCollidesWithASubtypeName()
+    {
+        var ex = Assert.Throws(() => Provider.ComposeRegistry(new IMetaDataTypeProvider[]
+        {
+            new Probe("owner-a", r =>
+            {
+                r.Register(Def("base", "other"));
+                r.Register(Def("probe", "physicalName"));
+            }),
+            new Probe("owner-b", r => r.Extend("template", "base",
+                attributes: new List { new("physicalName", "string", Required: false, Description: "x") }), "owner-a"),
+        }));
+        Assert.Equal(ErrorCode.ERR_PROVIDER_ATTR_SHADOW, ex.Code);
+    }
+
+    [Fact]
+    public void SameSlotExtendByAnotherProviderKeepsAttrConflictAndNamesTheOwner()
+    {
+        var ex = Assert.Throws(() => Provider.ComposeRegistry(new IMetaDataTypeProvider[]
+        {
+            new Probe("owner-a", r => r.Register(Def("probe", "physicalName"))),
+            new Probe("owner-b", r => r.Extend("template", "probe",
+                attributes: new List { new("physicalName", "string", Required: false, Description: "x") }), "owner-a"),
+        }));
+        Assert.Equal(ErrorCode.ERR_PROVIDER_ATTR_CONFLICT, ex.Code);
+        Assert.Contains("owner-a", ex.Message);
+        Assert.Contains("owner-b", ex.Message);
+    }
+
+    [Fact]
+    public void SiblingSubtypesMayUseOneName()
+    {
+        var registry = Provider.ComposeRegistry(new IMetaDataTypeProvider[]
+        {
+            new Probe("owner-a", r => r.Register(Def("probe-a", "physicalName"))),
+            new Probe("owner-b", r => r.Register(Def("probe-b", "physicalName")), "owner-a"),
+        });
+        Assert.Equal("owner-a", registry.AttrOrigin("template", "probe-a", "physicalName"));
+        Assert.Equal("owner-b", registry.AttrOrigin("template", "probe-b", "physicalName"));
+    }
+
+    [Fact]
+    public void RegistrationOutsideAProviderTurnClaimsNothingAndCollidesWithNothing()
+    {
+        var registry = Provider.ComposeRegistry(new IMetaDataTypeProvider[]
+        {
+            new Probe("owner-a", r => r.Register(Def("base", "physicalName"))),
+        });
+
+        // After compose no provider is running: this registration is unowned, so it is not
+        // refused even though owner-a holds the same name on the type's shared root.
+        registry.Register(Def("probe", "physicalName"));
+
+        Assert.Equal("owner-a", registry.AttrOrigin("template", "base", "physicalName"));
+        Assert.Equal(TypeRegistry.LibrarySentinel, registry.AttrOrigin("template", "probe", "physicalName"));
+    }
+
+    [Fact]
+    public void RefusedRegistrationLeavesNoTrace()
+    {
+        bool refused = false;
+        var registry = Provider.ComposeRegistry(new IMetaDataTypeProvider[]
+        {
+            new Probe("owner-a", r => r.Register(Def("base", "physicalName"))),
+            new Probe("owner-b", r =>
+            {
+                try
+                {
+                    r.Register(Def("probe", "physicalName"));
+                }
+                catch (MetaModelException)
+                {
+                    refused = true;
+                }
+            }, "owner-a"),
+        });
+
+        Assert.True(refused);
+        Assert.Null(registry.Find("template", "probe"));
+        Assert.Equal(TypeRegistry.LibrarySentinel, registry.AttrOrigin("template", "probe", "physicalName"));
+    }
+
+    [Fact]
+    public void ShippedCoreProvidersComposeWithNoCollisionAndEveryAttrHasAnOwner()
+    {
+        var registry = Provider.ComposeRegistry(CoreTypes.LibraryProviders);
+        var unowned = new List();
+        foreach (var id in registry.AllTypes())
+        {
+            foreach (var attr in registry.AttrsOf(id.Type, id.SubType))
+            {
+                if (registry.AttrOrigin(id.Type, id.SubType, attr.Name) == TypeRegistry.LibrarySentinel)
+                    unowned.Add($"{id}.{attr.Name}");
+            }
+        }
+        Assert.Empty(unowned);
+    }
+}
diff --git a/server/csharp/MetaObjects.Conformance.Tests/ProviderCompositionConformanceTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ProviderCompositionConformanceTests.cs
index ccd7acb7db..8debb3c513 100644
--- a/server/csharp/MetaObjects.Conformance.Tests/ProviderCompositionConformanceTests.cs
+++ b/server/csharp/MetaObjects.Conformance.Tests/ProviderCompositionConformanceTests.cs
@@ -116,6 +116,97 @@ public void RegisterTypes(TypeRegistry registry)
     }
 }
 
+/// 
+/// ADR-0062 attribute-ownership providers (see the corpus README). Each registers one string
+/// attr per listed (subtype, attr) pair on the template type: base is the shared
+/// root, shadowprobe a fresh subtype.
+/// 
+internal sealed class ShadowTestProvider : IMetaDataTypeProvider
+{
+    public const string ShadowSubType = "shadowprobe";
+
+    private readonly (string SubType, string Attr)[] _types;
+
+    public ShadowTestProvider(string id, string[] dependencies, params (string SubType, string Attr)[] types)
+    {
+        Id = id;
+        Dependencies = dependencies;
+        _types = types;
+    }
+
+    public string Id { get; }
+    public IReadOnlyList Dependencies { get; }
+
+    public void RegisterTypes(TypeRegistry registry)
+    {
+        foreach (var (subType, attr) in _types)
+        {
+            registry.Register(new TypeDefinition(
+                typeId: new TypeId("template", subType),
+                description: "Test-only — attribute-ownership probe.",
+                childRules: new List(),
+                factory: (typeId, name) => new MetaTemplate(typeId, name),
+                attributes: new List
+                {
+                    new AttrSchema(attr, "string", Required: false, Description: "Ownership probe attr."),
+                }));
+        }
+    }
+}
+
+/// ADR-0062 — extends template.shadowprobe with the name shadow-base owns on the root.
+internal sealed class ShadowSubExtendClashProvider : IMetaDataTypeProvider
+{
+    public string Id => "shadow-sub-extend-clash";
+    public IReadOnlyList Dependencies => new[] { "shadow-sub-distinct" };
+
+    public void RegisterTypes(TypeRegistry registry)
+    {
+        registry.Extend(
+            "template",
+            ShadowTestProvider.ShadowSubType,
+            attributes: new List
+            {
+                new AttrSchema("shadowAttr", "string", Required: false, Description: "Ownership probe attr."),
+            });
+    }
+}
+
+/// ADR-0062 — registers one optional string common attr; selfClaim also declares
+/// it on template.shadowprobe and then registers the common attr again.
+internal sealed class CommonAttrTestProvider : IMetaDataTypeProvider
+{
+    private readonly string _attr;
+    private readonly bool _selfClaim;
+
+    public CommonAttrTestProvider(string id, string[] dependencies, string attr, bool selfClaim = false)
+    {
+        Id = id;
+        Dependencies = dependencies;
+        _attr = attr;
+        _selfClaim = selfClaim;
+    }
+
+    public string Id { get; }
+    public IReadOnlyList Dependencies { get; }
+
+    public void RegisterTypes(TypeRegistry registry)
+    {
+        RegisterCommon(registry);
+        if (_selfClaim)
+        {
+            new ShadowTestProvider(Id, System.Array.Empty(), (ShadowTestProvider.ShadowSubType, _attr)).RegisterTypes(registry);
+            RegisterCommon(registry);
+        }
+    }
+
+    private void RegisterCommon(TypeRegistry registry) =>
+        registry.RegisterCommonAttrs(new[]
+        {
+            new AttrSchema(_attr, "string", Required: false, Description: "Ownership probe common attr."),
+        });
+}
+
 public sealed class ProviderCompositionConformanceTests
 {
     private static readonly IReadOnlyDictionary Providers =
@@ -131,6 +222,19 @@ public sealed class ProviderCompositionConformanceTests
             ["attr-conflict-clash"] = new AttrConflictClashProvider(),
             ["seal-probe"]          = new SealProbeProvider(),
             ["extend-spec-subtype"] = new ExtendSpecSubtypeProvider(),
+            ["shadow-base"]         = new ShadowTestProvider("shadow-base", System.Array.Empty(), ("base", "shadowAttr")),
+            ["shadow-sub-clash"]    = new ShadowTestProvider("shadow-sub-clash", new[] { "shadow-base" }, (ShadowTestProvider.ShadowSubType, "shadowAttr")),
+            ["shadow-sub-owner"]    = new ShadowTestProvider("shadow-sub-owner", System.Array.Empty(), (ShadowTestProvider.ShadowSubType, "reverseAttr")),
+            ["shadow-base-late"]    = new ShadowTestProvider("shadow-base-late", new[] { "shadow-sub-owner" }, ("base", "reverseAttr")),
+            ["shadow-sub-distinct"] = new ShadowTestProvider("shadow-sub-distinct", new[] { "shadow-base" }, (ShadowTestProvider.ShadowSubType, "distinctAttr")),
+            ["shadow-self"]         = new ShadowTestProvider("shadow-self", System.Array.Empty(), ("base", "selfAttr"), (ShadowTestProvider.ShadowSubType, "selfAttr")),
+            ["shadow-sub-extend-clash"] = new ShadowSubExtendClashProvider(),
+            ["common-owner"]        = new CommonAttrTestProvider("common-owner", System.Array.Empty(), "commonAttr"),
+            ["common-clash"]        = new CommonAttrTestProvider("common-clash", new[] { "common-owner" }, "commonAttr"),
+            ["common-self"]         = new CommonAttrTestProvider("common-self", System.Array.Empty(), "selfCommonAttr", selfClaim: true),
+            ["common-sub-clash"]    = new ShadowTestProvider("common-sub-clash", new[] { "common-owner" }, (ShadowTestProvider.ShadowSubType, "commonAttr")),
+            ["common-sub-owner"]    = new ShadowTestProvider("common-sub-owner", System.Array.Empty(), (ShadowTestProvider.ShadowSubType, "lateCommonAttr")),
+            ["common-late"]         = new CommonAttrTestProvider("common-late", new[] { "common-sub-owner" }, "lateCommonAttr"),
         };
 
     // Flat-corpus (error-code) manifest shape — unchanged.
@@ -285,4 +389,53 @@ public void ProviderCompositionComposeLoad(string fileName)
             Assert.Equal(expectedCodes, actualCodes);
         }
     }
+
+    // -----------------------------------------------------------------------
+    // ADR-0062 `attr-ownership/` corpus — composition succeeds and the registry names
+    // the provider that owns each attribute.
+    // -----------------------------------------------------------------------
+
+    private sealed record OwnerExpectation(string Type, string SubType, string Attr, string Owner);
+
+    private sealed record CommonOwnerExpectation(string Attr, string Owner);
+
+    private sealed record OwnershipManifest(
+        string[] Providers, OwnerExpectation[]? ExpectOwners, CommonOwnerExpectation[]? ExpectCommonOwners);
+
+    private static string OwnershipCorpusRootPath() =>
+        Path.Combine(CorpusRootPath(), "attr-ownership");
+
+    public static IEnumerable OwnershipManifestFiles()
+    {
+        foreach (var file in Directory.GetFiles(OwnershipCorpusRootPath(), "*.json").OrderBy(f => f, System.StringComparer.Ordinal))
+            yield return new object[] { Path.GetFileName(file) };
+    }
+
+    [Fact]
+    public void OwnershipCorpusIsNonEmpty()
+    {
+        Assert.NotEmpty(OwnershipManifestFiles());
+    }
+
+    [Theory]
+    [MemberData(nameof(OwnershipManifestFiles))]
+    public void ProviderCompositionAttrOwnership(string fileName)
+    {
+        var opts = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
+        var manifest = JsonSerializer.Deserialize(
+            File.ReadAllText(Path.Combine(OwnershipCorpusRootPath(), fileName)), opts)!;
+
+        var registry = Provider.ComposeRegistry(manifest.Providers.Select(Resolve).ToList());
+        OwnerExpectation[] owners = manifest.ExpectOwners ?? [];
+        CommonOwnerExpectation[] commonOwners = manifest.ExpectCommonOwners ?? [];
+        Assert.True(owners.Length + commonOwners.Length > 0);
+        foreach (var expected in owners)
+        {
+            Assert.Equal(expected.Owner, registry.AttrOrigin(expected.Type, expected.SubType, expected.Attr));
+        }
+        foreach (var expected in commonOwners)
+        {
+            Assert.Equal(expected.Owner, registry.CommonAttrOrigin(expected.Attr));
+        }
+    }
 }
diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs
index da46527c5a..b98e164351 100644
--- a/server/csharp/MetaObjects/Errors.cs
+++ b/server/csharp/MetaObjects/Errors.cs
@@ -57,6 +57,9 @@ public enum ErrorCode
     ERR_PROVIDER_DUPLICATE_ID,
     ERR_PROVIDER_MISSING_DEPENDENCY,
     ERR_PROVIDER_ATTR_CONFLICT,
+    // ADR-0062 — a provider declared an attribute name another provider already declares
+    // on the type it inherits from (or on a subtype that inherits from it).
+    ERR_PROVIDER_ATTR_SHADOW,
     // ADR-0050 — a provider tried to project a REQUIRED attribute onto a type it
     // does not own (via TypeRegistry.Extend). Projection is optional-only: a
     // required attr registered this way disappears silently whenever that
diff --git a/server/csharp/MetaObjects/Registry.cs b/server/csharp/MetaObjects/Registry.cs
index 64eee45660..accf05604f 100644
--- a/server/csharp/MetaObjects/Registry.cs
+++ b/server/csharp/MetaObjects/Registry.cs
@@ -250,6 +250,70 @@ private void StampAttrProvenance(string type, string subType, string attrName)
     public string AttrOrigin(string type, string subType, string attrName) =>
         _attrProvenance.TryGetValue((type, subType, attrName), out string? origin) ? origin : LibrarySentinel;
 
+    /// 
+    /// ADR-0062 — the provider-collision rule. Provider P may not put attribute
+    ///  on (type, subType) when a DIFFERENT provider Q already put
+    /// the same name on a related slot: the slot itself, the type it inherits from
+    /// (<type>.base) or, when this slot is the shared root, any subtype that
+    /// inherits from it; or registered it as a common attr, which every node type accepts.
+    /// Checked in both directions so the verdict does not depend on which
+    /// provider registered first. The same provider declaring a name on several related
+    /// slots stays legal, and an attr registered outside any provider's turn (no current
+    /// provider, or the library sentinel) claims nothing.
+    /// 
+    private void CheckAttrOwnership(string type, string subType, string name)
+    {
+        string? claimant = CurrentProviderId;
+        if (claimant is null) return;
+
+        string commonOwner = CommonAttrOrigin(name);
+        if (commonOwner != LibrarySentinel && commonOwner != claimant)
+        {
+            throw new MetaModelException(
+                $"Provider \"{claimant}\" declares attribute \"{name}\" on \"{type}.{subType}\", but provider " +
+                $"\"{commonOwner}\" already registers it as a common attribute, which every node type accepts; " +
+                $"provider \"{claimant}\" cannot declare it again (ADR-0062)",
+                ErrorCode.ERR_PROVIDER_ATTR_CONFLICT);
+        }
+
+        var related = new List { subType };
+        if (subType == SUBTYPE_BASE)
+        {
+            if (_subTypes.TryGetValue(type, out List? subs))
+            {
+                related.AddRange(subs.Where(sub => sub != SUBTYPE_BASE));
+            }
+        }
+        else if (_defs.ContainsKey($"{type}.{SUBTYPE_BASE}"))
+        {
+            related.Add(SUBTYPE_BASE);
+        }
+
+        foreach (string sub in related)
+        {
+            if (!_attrProvenance.TryGetValue((type, sub, name), out string? owner)
+                || owner == LibrarySentinel || owner == claimant)
+            {
+                continue;
+            }
+
+            if (sub == subType)
+            {
+                throw new MetaModelException(
+                    $"TypeRegistry.Extend: attribute \"{name}\" is already declared on \"{type}.{subType}\" " +
+                    $"by provider \"{owner}\"; provider \"{claimant}\" cannot declare it again (ADR-0062)",
+                    ErrorCode.ERR_PROVIDER_ATTR_CONFLICT);
+            }
+
+            throw new MetaModelException(
+                $"Provider \"{claimant}\" declares attribute \"{name}\" on \"{type}.{subType}\", but provider " +
+                $"\"{owner}\" already declares it on the related slot \"{type}.{sub}\". Two providers may not " +
+                "claim one attribute name on a type and the type it inherits from; give the second provider " +
+                "its own idiomatic name (ADR-0062).",
+                ErrorCode.ERR_PROVIDER_ATTR_SHADOW);
+        }
+    }
+
     private void CheckNotSealed(string operation)
     {
         if (_sealed)
@@ -297,6 +361,13 @@ 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.
+        foreach (AttrSchema attr in def.Attributes)
+        {
+            CheckAttrOwnership(def.TypeId.Type, def.TypeId.SubType, attr.Name);
+        }
+
         _defs[key] = def;
 
         // #265 — stamp provenance for every attr present at registration time (also
@@ -359,18 +430,50 @@ public void SetDefaultSubType(string type, string subType)
 
     private readonly List _commonAttrs = new();
 
+    /// ADR-0062 — common attr name -> the provider id that registered it
+    /// ( when registered outside any provider's turn).
+    private readonly Dictionary _commonAttrProvenance = new();
+
     /// 
     /// Register attrs that are accepted on every metatype. Used by providers to
-    /// declare cross-cutting attrs (e.g. documentation attrs). Repeated
-    /// registration of the same name is silently deduped (first registration
-    /// wins); conflicts with per-type attrs are detected at validation time.
+    /// declare cross-cutting attrs (e.g. documentation attrs). The same provider (or
+    /// a registration outside any provider's turn) re-registering a name is deduped; a
+    /// different provider registering a name another provider holds, as a common attr or on
+    /// any type, throws ERR_PROVIDER_ATTR_CONFLICT (ADR-0062). A name one provider
+    /// holds both ways is resolved at validation time.
     /// Throws  if any attr has
     /// ValueType == SUBTYPE_BASE.
     /// 
     public void RegisterCommonAttrs(IEnumerable attrs)
     {
         CheckNotSealed("RegisterCommonAttrs");
-        foreach (AttrSchema attr in attrs)
+        List batch = attrs.ToList();
+        // ADR-0062: checked for the whole batch first, so a refusal leaves no trace.
+        string? claimant = CurrentProviderId;
+        foreach (AttrSchema attr in batch)
+        {
+            if (claimant is null) break;
+            string owner = CommonAttrOrigin(attr.Name);
+            if (owner != LibrarySentinel && owner != claimant)
+            {
+                throw new MetaModelException(
+                    $"Provider \"{claimant}\" registers common attribute \"{attr.Name}\", but provider \"{owner}\" " +
+                    $"already registers it as a common attribute; provider \"{claimant}\" cannot declare it again (ADR-0062)",
+                    ErrorCode.ERR_PROVIDER_ATTR_CONFLICT);
+            }
+
+            foreach (var ((slotType, slotSubType, slotAttr), slotOwner) in _attrProvenance)
+            {
+                if (slotAttr != attr.Name || slotOwner == LibrarySentinel || slotOwner == claimant) continue;
+                throw new MetaModelException(
+                    $"Provider \"{claimant}\" registers common attribute \"{attr.Name}\", which every node type accepts, " +
+                    $"but provider \"{slotOwner}\" already declares it on \"{slotType}.{slotSubType}\"; provider " +
+                    $"\"{claimant}\" cannot declare it again (ADR-0062)",
+                    ErrorCode.ERR_PROVIDER_ATTR_CONFLICT);
+            }
+        }
+
+        foreach (AttrSchema attr in batch)
         {
             if (attr.ValueType == SUBTYPE_BASE)
             {
@@ -398,13 +501,20 @@ public void RegisterCommonAttrs(IEnumerable attrs)
 
             if (_commonAttrs.Any(existing => existing.Name == attr.Name))
             {
-                continue; // first-wins dedupe; per-type conflicts handled at validation time
+                continue; // same-name dedupe
             }
 
             _commonAttrs.Add(attr);
+            _commonAttrProvenance[attr.Name] = claimant ?? LibrarySentinel;
         }
     }
 
+    /// ADR-0062 — the provider id that registered common attr
+    /// , or  if unregistered or
+    /// registered outside any provider's turn.
+    public string CommonAttrOrigin(string attrName) =>
+        _commonAttrProvenance.TryGetValue(attrName, out string? origin) ? origin : LibrarySentinel;
+
     /// Returns the registered common attrs (defensive copy).
     public IReadOnlyList GetCommonAttrs() => _commonAttrs.ToList();
 
@@ -482,11 +592,15 @@ public void Extend(string type, string subType, IReadOnlyList? attri
 
             if (def.Attributes.Any(a => a.Name == attr.Name))
             {
+                // ADR-0062: name the provider that holds the slot when it is a different one.
+                CheckAttrOwnership(type, subType, attr.Name);
                 throw new MetaModelException(
                     $"TypeRegistry.Extend: attribute \"{attr.Name}\" is already declared on \"{type}.{subType}\"",
                     ErrorCode.ERR_PROVIDER_ATTR_CONFLICT);
             }
 
+            CheckAttrOwnership(type, subType, attr.Name);
+
             // ADR-0050: a REQUIRED attr may never be PROJECTED onto someone else's type.
             // Extend is how a concern provider decorates a type another provider owns, and
             // a concern can be composed out. A required attr arriving this way makes the
diff --git a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java
index 01355a0b6b..3f2433e6c5 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java
@@ -159,6 +159,12 @@ public enum ErrorCode {
     /** A provider extend redefines an attr another provider already declared. */
     ERR_PROVIDER_ATTR_CONFLICT,
 
+    /**
+     * ADR-0062: a provider declares an attribute name another provider already declares on
+     * the type it inherits from (or on a subtype that inherits from it).
+     */
+    ERR_PROVIDER_ATTR_SHADOW,
+
     /**
      * ADR-0050: a provider tried to project a REQUIRED attribute onto a type it does
      * not own (via extends). Projection is optional-only — a required attr registered
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 91866188c2..adb4ac9809 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/MetaData.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/MetaData.java
@@ -17,7 +17,6 @@
 
 import com.metaobjects.attr.BooleanAttribute;
 import com.metaobjects.attr.MetaAttribute;
-import com.metaobjects.attr.StringAttribute;
 import com.metaobjects.field.MetaField;
 // ✅ MIGRATED: MetaKey import removed - using MetaRelationship instead
 import com.metaobjects.object.MetaObject;
@@ -148,7 +147,7 @@ public class MetaData implements Cloneable, Serializable {
     public static void registerTypes(MetaDataRegistry registry) {
         try {
             // Check if MetaData base type is already registered to prevent duplicates
-            if (registry.hasConstraint("metadata.base.description.placement")) {
+            if (registry.hasConstraint("metadata.base.isAbstract.placement")) {
                 log.debug("MetaData base type already registered, skipping");
                 return;
             }
@@ -158,7 +157,6 @@ public static void registerTypes(MetaDataRegistry registry) {
                 .description("Base metadata type for inheritance hierarchy - enforces abstract requirements")
 
                 // COMMON ATTRIBUTES available to all metadata types
-                .optionalAttribute(ATTR_DESCRIPTION, StringAttribute.SUBTYPE_STRING)  // Description attribute for all metadata
                 .optionalAttribute(ATTR_IS_ABSTRACT, BooleanAttribute.SUBTYPE_BOOLEAN)  // Abstract flag for all metadata
 
                 // ROOT LEVEL can contain top-level metadata types
diff --git a/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java b/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java
index 7707736146..9ed59d7cb4 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java
@@ -7,7 +7,6 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static com.metaobjects.object.MetaObject.ATTR_DESCRIPTION;
 import static com.metaobjects.attr.StringAttribute.SUBTYPE_STRING;
 
 /**
@@ -49,7 +48,6 @@ public static void registerTypes(MetaDataRegistry registry) {
             // the dedicated validateIdentityFieldsAndGeneration pass already enforces it).
             def.requiredAttributeWithConstraints(ATTR_FIELDS).ofType(StringAttribute.SUBTYPE_STRING).asArray();
             def.optionalAttributeWithConstraints(ATTR_GENERATION).ofType(StringAttribute.SUBTYPE_STRING).withEnum(GENERATION_INCREMENT, GENERATION_UUID, GENERATION_ASSIGNED);
-            def.optionalAttributeWithConstraints(ATTR_DESCRIPTION).ofType(StringAttribute.SUBTYPE_STRING).asSingle();
 
             // ACCEPTS ANY ATTRIBUTES (for extensibility from service providers)
             // ADR-0051: NO any-attr wildcard. An undeclared attribute is ERR_UNKNOWN_ATTR in
diff --git a/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java b/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java
index b803e61750..1e8df0b0a5 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java
@@ -12,8 +12,6 @@
 import java.util.Collections;
 import java.util.List;
 
-import static com.metaobjects.object.MetaObject.ATTR_DESCRIPTION;
-
 /**
  * Reference identity — declares that this entity has fields whose value(s)
  * identify an instance of another entity.
@@ -65,7 +63,6 @@ public static void registerTypes(MetaDataRegistry registry) {
             def.reference(new com.metaobjects.validation.ReferenceDescriptor(
                 ATTR_REFERENCES, com.metaobjects.object.MetaObject.TYPE_OBJECT, null, true, "ERR_INVALID_REFERENCE"));
             def.optionalAttributeWithConstraints(ATTR_ENFORCE).ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle();
-            def.optionalAttributeWithConstraints(ATTR_DESCRIPTION).ofType(StringAttribute.SUBTYPE_STRING).asSingle();
             // RDB-physical FK constraint-name override contributed by the db provider
             // (db.json extends identity.reference). Description sourced from the embedded
             // spec/metamodel/db.json by applySpecDescriptions.
diff --git a/server/java/metadata/src/main/java/com/metaobjects/identity/SecondaryIdentity.java b/server/java/metadata/src/main/java/com/metaobjects/identity/SecondaryIdentity.java
index 4ead072b01..2874ff7045 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/identity/SecondaryIdentity.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/identity/SecondaryIdentity.java
@@ -7,7 +7,6 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static com.metaobjects.object.MetaObject.ATTR_DESCRIPTION;
 import static com.metaobjects.attr.StringAttribute.SUBTYPE_STRING;
 
 /**
@@ -61,7 +60,6 @@ public static void registerTypes(MetaDataRegistry registry) {
             // @fields XOR @expr, enforced by ValidationPhase (ERR_INVALID_INDEX),
             // because an exclusive-or is not expressible as a per-attr required flag.
             def.optionalAttributeWithConstraints(ATTR_FIELDS).ofType(StringAttribute.SUBTYPE_STRING).asArray();
-            def.optionalAttributeWithConstraints(ATTR_DESCRIPTION).ofType(StringAttribute.SUBTYPE_STRING).asSingle();
             // RDB-physical index attrs (@orders / @where / @expr / @using) are
             // contributed by CoreDBMetaDataProvider via registry.extendType, mirroring
             // the TS db provider's "extends" blocks in spec/metamodel/db.json.
diff --git a/server/java/metadata/src/main/java/com/metaobjects/index/LookupIndex.java b/server/java/metadata/src/main/java/com/metaobjects/index/LookupIndex.java
index 24dcfe8ec1..b1b20b5156 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/index/LookupIndex.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/index/LookupIndex.java
@@ -20,8 +20,6 @@
 import com.metaobjects.attr.StringAttribute;
 import com.metaobjects.registry.MetaDataRegistry;
 
-import static com.metaobjects.object.MetaObject.ATTR_DESCRIPTION;
-
 /**
  * A non-unique lookup index on one or more fields ({@code index.lookup}).
  *
@@ -63,9 +61,6 @@ public static void registerTypes(MetaDataRegistry registry) {
             def.optionalAttributeWithConstraints(ATTR_FIELDS)
                .ofType(StringAttribute.SUBTYPE_STRING).asArray();
 
-            def.optionalAttributeWithConstraints(ATTR_DESCRIPTION)
-               .ofType(StringAttribute.SUBTYPE_STRING).asSingle();
-
             // ACCEPTS ANY CHILD ATTRIBUTES (for extensibility from service providers)
             // ADR-0051: NO any-attr wildcard. An undeclared attribute is ERR_UNKNOWN_ATTR in
             // every port; extension is REGISTRATION -- a downstream provider declares its
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 d744a023ba..ac83f3d6eb 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
@@ -135,7 +135,6 @@ public static void registerTypes(MetaDataRegistry registry) {
             def.optionalAttributeWithConstraints(ATTR_IS_INTERFACE).ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle();
 
             // OBJECT-SPECIFIC ATTRIBUTES
-            def.optionalAttributeWithConstraints(ATTR_DESCRIPTION).ofType(StringAttribute.SUBTYPE_STRING).asSingle();
             def.optionalAttributeWithConstraints(ATTR_OBJECT).ofType(StringAttribute.SUBTYPE_STRING).asSingle();
             // NOTE: @objectRef is NOT registered on object.base. It is a FIELD-level
             // attr (registered on field.base — see MetaField) consumed by field.object
diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java b/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java
index 2f930b8ff3..5c70193dc1 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java
@@ -85,6 +85,9 @@ public class MetaDataRegistry {
      */
     private final Map commonAttributes = new ConcurrentHashMap<>();
 
+    /** ADR-0062 — common attr name -> the provider that registered it (or {@link #LIBRARY_PROVENANCE}). */
+    private final Map commonAttrProvenance = new ConcurrentHashMap<>();
+
     /**
      * #265 — attr-name provenance stamped during provider composition:
      * {@code (type, subType) -> (attrName -> providerId)}. Consulted by
@@ -108,6 +111,9 @@ public class MetaDataRegistry {
      */
     static final String LIBRARY_PROVENANCE = "_LIBRARY";
 
+    /** The shared-root subtype every type's concrete subtypes inherit from. */
+    private static final String SUBTYPE_BASE = "base";
+
     /**
      * #265 — the provider id currently executing its {@code registerTypes} turn
      * inside {@link #registerProviders}, or {@code null} outside that scope. Set
@@ -370,16 +376,21 @@ public MetaDataRegistry extendType(Class metaDataClass, Cons
         // ADR-0050: fails closed — checked BEFORE the commit below, so a violation
         // never reaches typeDefinitions (see checkNoProjectedRequiredAttr).
         checkNoProjectedRequiredAttr(typeIdToExtend, existing, extendedDefinition);
+        // ADR-0062: same fail-closed position — a name another provider already holds on a
+        // related slot never reaches typeDefinitions.
+        List claimed = newAttrClaims(typeIdToExtend, builder);
+        checkAttrOwnership(typeIdToExtend, extendedDefinition.getParentType(),
+                extendedDefinition.getParentSubType(), claimed);
         typeDefinitions.put(typeIdToExtend, extendedDefinition);
         // #265 — extendType() rebuilds from `existing` and writes straight into
         // typeDefinitions WITHOUT going through register(), so it must stamp
-        // provenance itself. Unlike register()'s blanket stamp, this DIFFS: only
-        // attr names newly present vs. `existing` get stamped with the current
-        // provider. Blanket-stamping here would mis-attribute every attr `existing`
-        // already carried (e.g. re-registering core's own attrs as this provider's)
-        // — and a same-name redefinition (the attr-conflict probe) must keep its
-        // PRIOR origin, not be silently reassigned to whoever redefined it.
-        stampNewAttrProvenance(typeIdToExtend, existing, extendedDefinition);
+        // provenance itself. Unlike register()'s blanket stamp, only the names this
+        // extension claims get stamped with the current provider. Blanket-stamping here
+        // would mis-attribute every attr `existing` already carried (e.g. re-registering
+        // core's own attrs as this provider's) — and a same-name redefinition (the
+        // attr-conflict probe) must keep its PRIOR origin, not be silently reassigned to
+        // whoever redefined it.
+        stampAttrProvenance(typeIdToExtend, claimed);
 
         log.debug("Extended type: {} with additional attributes/children",
                  typeIdToExtend.toQualifiedName());
@@ -506,6 +517,10 @@ void applyExtendsAttrs(String type, String subType,
                 atb.asSingle();
             }
         }
+        // ADR-0062: register() only checks names new to the slot's full requirement set, so
+        // a name this slot inherits and the directive re-declares is checked here.
+        checkAttrOwnership(typeId, existing.getParentType(), existing.getParentSubType(),
+                newAttrClaims(typeId, builder));
         register(builder.build());
     }
 
@@ -545,6 +560,26 @@ public void register(TypeDefinition definition) {
             );
         }
 
+        // 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.
+        // Only names NEW to this slot are checked: re-registering a slot a provider
+        // already owns replaces its complete definition and is not a new claim.
+        Set alreadyDeclared = new HashSet<>();
+        if (existing != null) {
+            for (ChildRequirement req : existing.getChildRequirements()) {
+                if (isNamedAttrRequirement(req)) {
+                    alreadyDeclared.add(req.getName());
+                }
+            }
+        }
+        List claimed = new ArrayList<>();
+        for (ChildRequirement req : definition.getDirectChildRequirements()) {
+            if (isNamedAttrRequirement(req) && !alreadyDeclared.contains(req.getName())) {
+                claimed.add(req.getName());
+            }
+        }
+        checkAttrOwnership(typeId, definition.getParentType(), definition.getParentSubType(), claimed);
+
         // Resolve inheritance if this type has a parent
         resolveInheritance(definition);
 
@@ -554,7 +589,7 @@ public void register(TypeDefinition definition) {
         // provider's turn). Blanket, not diffed: register() always REPLACES the
         // (type, subType)'s complete definition (unlike extendType(), which
         // rebuilds an already-registered type from `existing` — see
-        // stampNewAttrProvenance for why that path diffs instead).
+        // stampAttrProvenance for why that path stamps only claimed names).
         recordAttrProvenance(typeId, definition.getDirectChildRequirements());
         log.debug("Registered type: {} -> {} (parent: {})", typeId.toQualifiedName(),
                  definition.getImplementationClass().getSimpleName(),
@@ -821,7 +856,9 @@ public void addGlobalChildRequirement(String parentType, String parentSubType, C
      *       {@code CanonicalJsonParser.processAttributes} fires for any parent.
      * 
      *
-     * 

Idempotent: re-registering the same attr name is a no-op.

+ *

Idempotent: re-registering the same attr name is a no-op for the provider that + * registered it. A common attr is on every node type, so another provider may not claim + * its name, as a common attr or on any type (ADR-0062, {@code ERR_PROVIDER_ATTR_CONFLICT}).

* * @param name bare attribute name (no {@code @} prefix; e.g. {@code "description"}) * @param valueType attribute value subtype (e.g. {@link StringAttribute#SUBTYPE_STRING}, @@ -839,6 +876,7 @@ public void registerCommonAttribute(String name, String valueType, boolean isArr // Idempotent: skip re-registration of the same attr name (allows tests that // re-initialise the registry to not blow up on duplicate constraints). This // precedes the seal guard so a no-op re-registration never trips the seal. + checkCommonAttrOwnership(name); if (commonAttributes.containsKey(name)) { return; } @@ -846,6 +884,7 @@ public void registerCommonAttribute(String name, String valueType, boolean isArr CommonAttributeDef def = new CommonAttributeDef(name, valueType, isArray); commonAttributes.put(name, def); + commonAttrProvenance.put(name, currentProviderId != null ? currentProviderId : LIBRARY_PROVENANCE); // 1. Global ChildRequirement under the UNIVERSAL_PARENT_KEY tier — makes // acceptsChild() return true for this attr on any (parentType, parentSubType) pair. @@ -893,6 +932,15 @@ public CommonAttributeDef getCommonAttribute(String name) { return commonAttributes.get(name); } + /** + * ADR-0062 — the provider that registered common attribute {@code name}, or + * {@code null} when it is not registered or was registered outside any provider's turn. + */ + public String getCommonAttrProvider(String name) { + String providerId = commonAttrProvenance.get(name); + return LIBRARY_PROVENANCE.equals(providerId) ? null : providerId; + } + /** * Whether any common attribute is registered. * @@ -1142,7 +1190,7 @@ private static boolean isPrunableAttr(ChildRequirement req) { /** * #265 — true for a NAMED {@code attr}-typed requirement (concrete, non-wildcard - * name): the shape {@link #recordAttrProvenance}/{@link #stampNewAttrProvenance} + * name): the shape {@link #recordAttrProvenance}/{@link #stampAttrProvenance} * track provenance for, and the shape {@link #isPrunableAttr} narrows further by * spec-inclusion. False for structural placement rules and the any-attr wildcard. */ @@ -1154,13 +1202,175 @@ private static boolean isNamedAttrRequirement(ChildRequirement req) { return name != null && !"*".equals(name); // false for the any-attr wildcard } + /** + * ADR-0062 — the provider that registered {@code attrName} on exactly + * {@code (type, subType)}, or {@code null} when it is not registered there or was + * registered outside any provider's turn. An inherited attr reports its declaring slot, + * so ask {@code .base} for those. + */ + public String getAttrProvider(String type, String subType, String attrName) { + Map byName = attrProvenance.get(new MetaDataTypeId(type, subType)); + String providerId = byName != null ? byName.get(attrName) : null; + return LIBRARY_PROVENANCE.equals(providerId) ? null : providerId; + } + + /** + * ADR-0062 — the slots related to {@code typeId} for the provider-collision rule: the + * same-node-type slots it inherits from (its explicit parent chain, plus the + * {@code .base} shared root by convention) and, when {@code typeId} is a shared + * root or a parent, every registered subtype of that type that inherits from it. + * {@code parentType}/{@code parentSubType} are the definition's own parent, passed in + * because a definition being registered is not in {@link #typeDefinitions} yet. + * + *

The rule is scoped to ONE node type. The JVM registry additionally chains every + * {@code .base} to {@code metadata.base} (the attrs every node shares, owned by + * the core-types provider); no other port has that edge, and several providers re-declare + * {@code @isAbstract}/{@code @description} on their own root with the same meaning. A + * cross-type walk would make Java refuse what the other four ports accept, so the walk + * stops at the node-type boundary.

+ */ + private Set relatedSlots(MetaDataTypeId typeId, String parentType, String parentSubType) { + Set related = new LinkedHashSet<>(); + String nextType = parentType; + String nextSubType = parentSubType; + while (nextType != null && nextSubType != null) { + MetaDataTypeId parent = new MetaDataTypeId(nextType, nextSubType); + if (!parent.type().equals(typeId.type()) || parent.equals(typeId) || !related.add(parent)) { + break; + } + TypeDefinition parentDef = typeDefinitions.get(parent); + nextType = parentDef != null && parentDef.hasParent() ? parentDef.getParentType() : null; + nextSubType = parentDef != null && parentDef.hasParent() ? parentDef.getParentSubType() : null; + } + boolean isSharedRoot = SUBTYPE_BASE.equals(typeId.subType()); + if (!isSharedRoot) { + MetaDataTypeId root = new MetaDataTypeId(typeId.type(), SUBTYPE_BASE); + if (typeDefinitions.containsKey(root)) { + related.add(root); + } + } + for (Map.Entry entry : typeDefinitions.entrySet()) { + MetaDataTypeId other = entry.getKey(); + if (other.equals(typeId)) { + continue; + } + if (isSharedRoot && other.type().equals(typeId.type())) { + related.add(other); + continue; + } + TypeDefinition def = entry.getValue(); + while (def != null && def.hasParent()) { + MetaDataTypeId parent = new MetaDataTypeId(def.getParentType(), def.getParentSubType()); + if (!parent.type().equals(typeId.type())) { + break; + } + if (parent.equals(typeId)) { + related.add(other); + break; + } + def = typeDefinitions.get(parent); + } + } + return related; + } + + /** + * ADR-0062 — the provider-collision rule. Provider P may not put attribute {@code name} + * on {@code typeId} when a DIFFERENT provider Q already put the same name on a related + * slot (see {@link #relatedSlots}). Checked in both directions so the verdict does not + * depend on which provider registered first. The same provider declaring a name on + * several related slots stays legal, and an attr registered outside any provider's turn + * claims nothing. + */ + private void checkAttrOwnership(MetaDataTypeId typeId, String parentType, String parentSubType, + Collection names) { + String claimant = currentProviderId; + if (claimant == null || names.isEmpty()) { + return; + } + Set related = relatedSlots(typeId, parentType, parentSubType); + for (String name : names) { + String commonOwner = getCommonAttrProvider(name); + if (commonOwner != null && !commonOwner.equals(claimant)) { + throw new MetaDataException( + "Provider \"" + claimant + "\" declares attribute \"" + name + "\" on \"" + + typeId.toQualifiedName() + "\", but provider \"" + commonOwner + + "\" already registers it as a common attribute, which every node type accepts; provider \"" + + claimant + "\" cannot declare it again (ADR-0062).", + com.metaobjects.ErrorCode.ERR_PROVIDER_ATTR_CONFLICT); + } + for (MetaDataTypeId slot : related) { + Map byName = attrProvenance.get(slot); + String owner = byName != null ? byName.get(name) : null; + if (owner == null || LIBRARY_PROVENANCE.equals(owner) || owner.equals(claimant)) { + continue; + } + throw new MetaDataException( + "Provider \"" + claimant + "\" declares attribute \"" + name + "\" on \"" + + typeId.toQualifiedName() + "\", but provider \"" + owner + + "\" already declares it on the related slot \"" + slot.toQualifiedName() + + "\". Two providers may not claim one attribute name on a type and the type it " + + "inherits from; give the second provider its own idiomatic name (ADR-0062).", + com.metaobjects.ErrorCode.ERR_PROVIDER_ATTR_SHADOW); + } + } + } + + /** + * ADR-0062 — a common attr is on every node type, so provider P may not register common + * attr {@code name} when a DIFFERENT provider already registered that name as a common + * attr or on any type. Re-registration by the same provider, and registration outside + * any provider's turn, stay legal. + */ + private void checkCommonAttrOwnership(String name) { + String claimant = currentProviderId; + if (claimant == null) { + return; + } + String commonOwner = getCommonAttrProvider(name); + if (commonOwner != null && !commonOwner.equals(claimant)) { + throw new MetaDataException( + "Provider \"" + claimant + "\" registers common attribute \"" + name + "\", but provider \"" + + commonOwner + "\" already registers it as a common attribute; provider \"" + claimant + + "\" cannot declare it again (ADR-0062).", + com.metaobjects.ErrorCode.ERR_PROVIDER_ATTR_CONFLICT); + } + for (Map.Entry> entry : attrProvenance.entrySet()) { + String owner = entry.getValue().get(name); + if (owner == null || LIBRARY_PROVENANCE.equals(owner) || owner.equals(claimant)) { + continue; + } + throw new MetaDataException( + "Provider \"" + claimant + "\" registers common attribute \"" + name + "\", which every node " + + "type accepts, but provider \"" + owner + "\" already declares it on \"" + + entry.getKey().toQualifiedName() + "\"; provider \"" + claimant + + "\" cannot declare it again (ADR-0062).", + com.metaobjects.ErrorCode.ERR_PROVIDER_ATTR_CONFLICT); + } + } + + /** + * ADR-0062 — text appended to a same-slot {@code ERR_PROVIDER_ATTR_CONFLICT} so it names + * the provider that holds the slot. Empty when the holder is unknown or is the provider + * running now (a plain duplicate declaration, not a cross-provider claim). + */ + String describeSlotHolder(String type, String subType, String attrName) { + String owner = getAttrProvider(type, subType, attrName); + String claimant = currentProviderId; + if (owner == null || claimant == null || owner.equals(claimant)) { + return ""; + } + return " Declared by provider \"" + owner + "\"; provider \"" + claimant + + "\" cannot declare it again (ADR-0062)."; + } + /** * #265 — record provenance for every named attr requirement in {@code directRequirements} * onto {@code typeId}, stamping {@link #currentProviderId} (or {@link #LIBRARY_PROVENANCE} * outside a provider's turn). Called from {@link #register}, which always replaces the * (type, subType)'s COMPLETE definition — so a blanket stamp is correct here (contrast - * {@link #stampNewAttrProvenance}, which diffs because {@link #extendType} rebuilds from - * an already-registered definition). + * {@link #stampAttrProvenance}, which stamps only claimed names because + * {@link #extendType} rebuilds from an already-registered definition). */ private void recordAttrProvenance(MetaDataTypeId typeId, Collection directRequirements) { String providerId = currentProviderId != null ? currentProviderId : LIBRARY_PROVENANCE; @@ -1174,39 +1384,45 @@ private void recordAttrProvenance(MetaDataTypeId typeId, Collection existingNames = new HashSet<>(); - for (ChildRequirement req : existing.getChildRequirements()) { - if (isNamedAttrRequirement(req)) { - existingNames.add(req.getName()); - } - } + private void stampAttrProvenance(MetaDataTypeId typeId, Collection names) { String providerId = currentProviderId != null ? currentProviderId : LIBRARY_PROVENANCE; - for (ChildRequirement req : extended.getDirectChildRequirements()) { - if (!isNamedAttrRequirement(req) || existingNames.contains(req.getName())) { - continue; + for (String name : names) { + attrProvenance.computeIfAbsent(typeId, k -> new ConcurrentHashMap<>()).put(name, providerId); + } + } + + /** + * ADR-0062 — the attr names a builder seeded from {@code typeId}'s definition declares + * as a new claim on that slot: every declared name the slot does not already declare + * itself. That includes a name the slot only inherits, which is a claim on a related + * slot's name. A name the slot already declares is the builder's same-slot check. + */ + private List newAttrClaims(MetaDataTypeId typeId, TypeDefinitionBuilder builder) { + List claimed = new ArrayList<>(); + for (String name : builder.getDeclaredAttrNames()) { + if (!declaresAttrOn(typeId.type(), typeId.subType(), name)) { + claimed.add(name); } - attrProvenance.computeIfAbsent(typeId, k -> new ConcurrentHashMap<>()) - .put(req.getName(), providerId); } + return claimed; + } + + /** + * ADR-0062 — whether {@code (type, subType)} itself declares {@code attrName} (it was + * registered or extended onto exactly that slot), as opposed to inheriting it. + */ + boolean declaresAttrOn(String type, String subType, String attrName) { + Map byName = attrProvenance.get(new MetaDataTypeId(type, subType)); + return byName != null && byName.containsKey(attrName); } /** @@ -1222,10 +1438,9 @@ private void stampNewAttrProvenance(MetaDataTypeId typeId, TypeDefinition existi *

If the attr is genuinely required, it is OWN, not projected: declare it with the * type, in the type's own provider.

* - *

Diffs {@code extended}'s named attr requirements against {@code existing}'s (the - * same base set {@link #stampNewAttrProvenance} diffs against, for the same reason — - * {@code existing}'s FULL direct+inherited requirements, since {@code extended}'s - * direct-only set would otherwise see every previously-inherited attr as "new") and + *

Diffs {@code extended}'s named attr requirements against {@code existing}'s + * FULL direct+inherited requirements, since {@code extended}'s + * direct-only set would otherwise see every previously-inherited attr as "new", and * throws on the first newly-added attr that is required. Callers MUST invoke this * BEFORE committing {@code extended} into {@code typeDefinitions} so a violation * fails closed — the projected attr is never applied. diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java b/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java index 9c97e70d21..89c236a088 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java +++ b/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java @@ -303,11 +303,11 @@ public static List metamodelProviders() { // SP-G Phase1 Units2-3 — manifest emitter exclusions (documented, uniform // across all four ports; see fixtures/registry-conformance/README.md // "EXCLUDED" list + the SP-G divergence analysis buckets C-2/C-3/C-5/B-2): - // - structural keywords (isArray/isAbstract) + the `description` commonAttr - // are NOT per-type attrs. Java DOES register all three as ordinary - // per-type attrs (on metadata.base / field.base, inherited everywhere) — - // so this filter is what drops them from Java's emitter output. They are - // no-ops for TS/C#/Python. `description` stays in the commonAttrs block. + // - structural keywords (isArray/isAbstract) are NOT per-type attrs. Java + // DOES register them as ordinary per-type attrs (on metadata.base / + // field.base, inherited everywhere) — so this filter is what drops them + // from Java's emitter output. They are no-ops for TS/C#/Python. + // `description` lives only in the commonAttrs block (ADR-0062). // - metadata.base is Java's internal inheritance anchor — other ports // register only metadata.root (the deferred inheritsFrom anchor). // - the generic view.* controls are a TS-web-presentation facet. Java @@ -334,8 +334,6 @@ public enum ExclusionReason { NATIVE_BINDING, /** Bare structural / OO-shape keyword (isArray/isAbstract/extends/implements/isInterface). */ STRUCTURAL_KEYWORD, - /** A commonAttr ({@code description}) re-registered per-type — belongs in commonAttrs. */ - COMMON_ATTR_DUP, /** The {@code metadata.base} per-port inheritance anchor (deferred inheritsFrom facet). */ INHERITANCE_ANCHOR, /** TS-web-presentation-only facet (the generic {@code view.*} controls). */ @@ -362,8 +360,7 @@ public enum ExclusionReason { * NOT per-type attributes — Java registers them on {@code object.base} * (inherited by entity/value), so the classification is what drops them from * the emitter (no-op for TS/C#/Python). They remain REGISTERED (the loader - * must accept an authored {@code extends:}). {@code description} is carved out - * ONLY per-type — it remains in the {@code commonAttrs} block. {@code object} + * must accept an authored {@code extends:}). {@code object} * (ADR-0001 class-FQN type binding) and {@code objectAdapter} (ADR-0005 * value-access seam) are per-port binding mechanisms (same category as native * type bindings); they stay REGISTERED in Java (read by the value-access @@ -376,8 +373,7 @@ public enum ExclusionReason { com.metaobjects.object.MetaObject.ATTR_IMPLEMENTS, ExclusionReason.STRUCTURAL_KEYWORD, com.metaobjects.object.MetaObject.ATTR_IS_INTERFACE, ExclusionReason.STRUCTURAL_KEYWORD, com.metaobjects.object.MetaObject.ATTR_OBJECT, ExclusionReason.NATIVE_BINDING, - com.metaobjects.object.AbstractObjectRepresentation.ATTR_OBJECT_ADAPTER, ExclusionReason.NATIVE_BINDING, - MetaData.ATTR_DESCRIPTION, ExclusionReason.COMMON_ATTR_DUP); + com.metaobjects.object.AbstractObjectRepresentation.ATTR_OBJECT_ADAPTER, ExclusionReason.NATIVE_BINDING); /** * Classify a per-type attr: an {@link ExclusionReason} (carved out) or diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/TypeDefinitionBuilder.java b/server/java/metadata/src/main/java/com/metaobjects/registry/TypeDefinitionBuilder.java index 37c0e714f9..818b478ffd 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/registry/TypeDefinitionBuilder.java +++ b/server/java/metadata/src/main/java/com/metaobjects/registry/TypeDefinitionBuilder.java @@ -56,6 +56,10 @@ public class TypeDefinitionBuilder { private String parentType; private String parentSubType; private final Map childRequirements = new HashMap<>(); + // ADR-0062: attr names copied in by from() (the slot's own AND inherited names), and + // the attr names this builder's caller declared afterwards. + private final java.util.Set seededAttrNames = new java.util.HashSet<>(); + private final java.util.Set declaredAttrNames = new java.util.LinkedHashSet<>(); // Auto-constraint generation support private MetaDataRegistry registry; @@ -124,6 +128,8 @@ public static TypeDefinitionBuilder from(TypeDefinition existing) { if ("*".equals(keyToUse)) { // For wildcard requirements, create unique keys to avoid overwrites keyToUse = "*:" + req.getExpectedType() + ":" + req.getExpectedSubType(); + } else if ("attr".equals(req.getExpectedType())) { + builder.seededAttrNames.add(keyToUse); } builder.childRequirements.put(keyToUse, req); } @@ -440,8 +446,23 @@ private void addChildRequirement(ChildRequirement requirement) { key = "*:" + requirement.getExpectedType() + ":" + requirement.getExpectedSubType(); } + boolean namedAttr = "attr".equals(requirement.getExpectedType()) && !"*".equals(requirement.getName()); + if (namedAttr) { + declaredAttrNames.add(key); + } ChildRequirement existing = childRequirements.get(key); - if (existing != null && !existing.equals(requirement)) { + // ADR-0062: a name this slot only INHERITS is not a same-slot redefinition. The + // registry's ownership check (extendType / applyExtendsAttrs) decides whether + // declaring it here is legal, so the declaration replaces the inherited copy. + boolean inheritedOrigin = existing != null && namedAttr && registry != null + && seededAttrNames.contains(key) && !registry.declaresAttrOn(type, subType, key); + // ADR-0062: an IDENTICAL re-declaration is idempotent for the provider that owns the + // slot's attr, but another provider repeating it is still a second claim on the name. + boolean foreignRepeat = existing != null && existing.equals(requirement) + && namedAttr + && registry != null + && !registry.describeSlotHolder(type, subType, requirement.getName()).isEmpty(); + if (existing != null && !inheritedOrigin && (foreignRepeat || !existing.equals(requirement))) { // A colliding ATTR child requirement is a provider redefining an attr // another provider already declared on this type — the cross-port // ERR_PROVIDER_ATTR_CONFLICT invariant (mirrors the TS/Python/C# @@ -452,7 +473,8 @@ private void addChildRequirement(ChildRequirement requirement) { throw new com.metaobjects.MetaDataException( "Attribute '" + requirement.getName() + "' is already declared on this type " + "(a provider redefined an attr another provider already declared). " - + "Existing: " + existing + ", New: " + requirement, + + "Existing: " + existing + ", New: " + requirement + + (registry != null ? registry.describeSlotHolder(type, subType, requirement.getName()) : ""), com.metaobjects.ErrorCode.ERR_PROVIDER_ATTR_CONFLICT); } throw new IllegalArgumentException( @@ -495,6 +517,14 @@ public TypeDefinition build() { return td; } + /** + * ADR-0062 — the named attr names declared on this builder after it was created, in + * declaration order (excludes the requirements {@link #from} copied in). + */ + java.util.Set getDeclaredAttrNames() { + return java.util.Collections.unmodifiableSet(declaredAttrNames); + } + /** * Get the current type being built (for debugging) * diff --git a/server/java/metadata/src/main/java/com/metaobjects/relationship/MetaRelationship.java b/server/java/metadata/src/main/java/com/metaobjects/relationship/MetaRelationship.java index 8f8363173b..d17082f134 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/relationship/MetaRelationship.java +++ b/server/java/metadata/src/main/java/com/metaobjects/relationship/MetaRelationship.java @@ -8,8 +8,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static com.metaobjects.object.MetaObject.ATTR_DESCRIPTION; - /** * Abstract base relationship metadata for expressing object relationships. * Provides simplified model-driven relationship patterns optimized for AI generation. @@ -144,10 +142,6 @@ public static void registerTypes(MetaDataRegistry registry) { .ofType(BooleanAttribute.SUBTYPE_BOOLEAN) .asSingle(); - def.optionalAttributeWithConstraints(ATTR_DESCRIPTION) - .ofType(StringAttribute.SUBTYPE_STRING) - .asSingle(); - // @onDelete / @onUpdate — enum-constrained; withEnum also marks as single def.optionalAttributeWithConstraints(ATTR_ON_DELETE) .ofType(StringAttribute.SUBTYPE_STRING) diff --git a/server/java/metadata/src/test/java/com/metaobjects/conformance/ProviderCompositionConformanceTest.java b/server/java/metadata/src/test/java/com/metaobjects/conformance/ProviderCompositionConformanceTest.java index f5d2619491..e2278dd23a 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/conformance/ProviderCompositionConformanceTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/conformance/ProviderCompositionConformanceTest.java @@ -15,6 +15,7 @@ */ package com.metaobjects.conformance; +import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.metaobjects.ErrorCode; @@ -47,12 +48,14 @@ import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** @@ -108,6 +111,16 @@ static final class SealProbeTemplate extends MetaTemplate { SealProbeTemplate(String name) { super("sealprobe", name); } } + // ADR-0062 attribute-ownership probes: the shared root template.base and the fresh + // subtype template.shadowprobe (see the corpus README). + static final class ShadowRootTemplate extends MetaTemplate { + ShadowRootTemplate(String name) { super(TemplateConstants.SUBTYPE_BASE, name); } + } + + static final class ShadowProbeTemplate extends MetaTemplate { + ShadowProbeTemplate(String name) { super("shadowprobe", name); } + } + // ------------------------------------------------------------------ // Canonical named-provider set (test-only; identical id/deps/behavior // cross-port). The no-op cycle/duplicate/missing providers are reused from @@ -173,6 +186,77 @@ static final class SealProbeTemplate extends MetaTemplate { @Override public String getDescription() { return "Test-only — #265 compose-load probe: extends view.currency with @decimals."; } }; + /** Registers the shared root {@code template.base} with one optional string attr. */ + private static void registerShadowRoot(MetaDataRegistry registry, String attr) { + registry.registerType(ShadowRootTemplate.class, def -> { + def.type(TemplateConstants.TYPE_TEMPLATE).subType(TemplateConstants.SUBTYPE_BASE) + .description("Test-only — attribute-ownership probe root."); + def.optionalAttributeWithConstraints(attr) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + } + + /** Registers {@code template.shadowprobe} (inheriting the root) with one optional string attr. */ + private static void registerShadowProbe(MetaDataRegistry registry, String attr) { + registry.registerType(ShadowProbeTemplate.class, def -> { + def.type(TemplateConstants.TYPE_TEMPLATE).subType("shadowprobe") + .description("Test-only — attribute-ownership probe subtype.") + .inheritsFrom(TemplateConstants.TYPE_TEMPLATE, TemplateConstants.SUBTYPE_BASE); + def.optionalAttributeWithConstraints(attr) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + } + + private static MetaDataTypeProvider shadowProvider(String id, String[] deps, Consumer body) { + return new MetaDataTypeProvider() { + @Override public String getProviderId() { return id; } + @Override public String[] getDependencies() { return deps; } + @Override public void registerTypes(MetaDataRegistry registry) { body.accept(registry); } + @Override public String getDescription() { return "Test-only ADR-0062 attribute-ownership provider: " + id; } + }; + } + + private static final MetaDataTypeProvider SHADOW_BASE = + shadowProvider("shadow-base", new String[0], r -> registerShadowRoot(r, "shadowAttr")); + private static final MetaDataTypeProvider SHADOW_SUB_CLASH = + shadowProvider("shadow-sub-clash", new String[]{"shadow-base"}, r -> registerShadowProbe(r, "shadowAttr")); + private static final MetaDataTypeProvider SHADOW_SUB_OWNER = + shadowProvider("shadow-sub-owner", new String[0], r -> registerShadowProbe(r, "reverseAttr")); + private static final MetaDataTypeProvider SHADOW_BASE_LATE = + shadowProvider("shadow-base-late", new String[]{"shadow-sub-owner"}, r -> registerShadowRoot(r, "reverseAttr")); + private static final MetaDataTypeProvider SHADOW_SUB_DISTINCT = + shadowProvider("shadow-sub-distinct", new String[]{"shadow-base"}, r -> registerShadowProbe(r, "distinctAttr")); + private static final MetaDataTypeProvider SHADOW_SELF = + shadowProvider("shadow-self", new String[0], r -> { + registerShadowRoot(r, "selfAttr"); + registerShadowProbe(r, "selfAttr"); + }); + + private static final MetaDataTypeProvider SHADOW_SUB_EXTEND_CLASH = + shadowProvider("shadow-sub-extend-clash", new String[]{"shadow-sub-distinct"}, + r -> r.extendType(ShadowProbeTemplate.class, def -> def + .optionalAttributeWithConstraints("shadowAttr") + .ofType(StringAttribute.SUBTYPE_STRING).asSingle())); + private static final MetaDataTypeProvider COMMON_OWNER = + shadowProvider("common-owner", new String[0], + r -> r.registerCommonAttribute("commonAttr", StringAttribute.SUBTYPE_STRING, false)); + private static final MetaDataTypeProvider COMMON_CLASH = + shadowProvider("common-clash", new String[]{"common-owner"}, + r -> r.registerCommonAttribute("commonAttr", StringAttribute.SUBTYPE_STRING, false)); + private static final MetaDataTypeProvider COMMON_SELF = + shadowProvider("common-self", new String[0], r -> { + r.registerCommonAttribute("selfCommonAttr", StringAttribute.SUBTYPE_STRING, false); + registerShadowProbe(r, "selfCommonAttr"); + r.registerCommonAttribute("selfCommonAttr", StringAttribute.SUBTYPE_STRING, false); + }); + private static final MetaDataTypeProvider COMMON_SUB_CLASH = + shadowProvider("common-sub-clash", new String[]{"common-owner"}, r -> registerShadowProbe(r, "commonAttr")); + private static final MetaDataTypeProvider COMMON_SUB_OWNER = + shadowProvider("common-sub-owner", new String[0], r -> registerShadowProbe(r, "lateCommonAttr")); + private static final MetaDataTypeProvider COMMON_LATE = + shadowProvider("common-late", new String[]{"common-sub-owner"}, + r -> r.registerCommonAttribute("lateCommonAttr", StringAttribute.SUBTYPE_STRING, false)); + private static MetaDataTypeProvider resolve(String id) { MetaDataTypeProvider p = ConformanceTestProviders.TEST_PROVIDERS.get(id); if (p != null) return p; @@ -181,6 +265,19 @@ private static MetaDataTypeProvider resolve(String id) { case "attr-conflict-clash": return ATTR_CONFLICT_CLASH; case "seal-probe": return SEAL_PROBE; case "extend-spec-subtype": return EXTEND_SPEC_SUBTYPE; + case "shadow-base": return SHADOW_BASE; + case "shadow-sub-clash": return SHADOW_SUB_CLASH; + case "shadow-sub-owner": return SHADOW_SUB_OWNER; + case "shadow-base-late": return SHADOW_BASE_LATE; + case "shadow-sub-distinct": return SHADOW_SUB_DISTINCT; + case "shadow-self": return SHADOW_SELF; + case "shadow-sub-extend-clash": return SHADOW_SUB_EXTEND_CLASH; + case "common-owner": return COMMON_OWNER; + case "common-clash": return COMMON_CLASH; + case "common-self": return COMMON_SELF; + case "common-sub-clash": return COMMON_SUB_CLASH; + case "common-sub-owner": return COMMON_SUB_OWNER; + case "common-late": return COMMON_LATE; default: throw new IllegalArgumentException( "Unknown named provider \"" + id + "\" in provider-composition corpus"); @@ -275,6 +372,71 @@ public void providerComposition() throws IOException { } } + // ------------------------------------------------------------------ + // ADR-0062 attr-ownership corpus — composition succeeds and the registry + // names the provider that owns each attribute. + // ------------------------------------------------------------------ + + @RunWith(Parameterized.class) + public static class AttrOwnership { + + private static Path ownershipCorpusRoot() { + return corpusRoot().resolve("attr-ownership"); + } + + @Parameters(name = "{0}") + public static Collection manifests() { + try (Stream files = Files.list(ownershipCorpusRoot())) { + List names = files + .filter(p -> p.getFileName().toString().endsWith(".json")) + .map(p -> p.getFileName().toString()) + .sorted() + .collect(Collectors.toList()); + if (names.isEmpty()) { + throw new AssertionError("provider-composition attr-ownership corpus is empty (mis-pathed root?)"); + } + List rows = new ArrayList<>(names.size()); + for (String n : names) rows.add(new Object[]{n}); + return rows; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + @Parameter(0) + public String fileName; + + @Test + public void providerCompositionAttrOwnership() throws IOException { + JsonObject manifest = JsonParser.parseString( + Files.readString(ownershipCorpusRoot().resolve(fileName))).getAsJsonObject(); + List resolved = new ArrayList<>(); + manifest.getAsJsonArray("providers").forEach(e -> resolved.add(resolve(e.getAsString()))); + + MetaDataRegistry registry = MetaDataRegistry.compose(resolved); + + JsonArray owners = manifest.has("expectOwners") ? manifest.getAsJsonArray("expectOwners") : new JsonArray(); + JsonArray commonOwners = manifest.has("expectCommonOwners") + ? manifest.getAsJsonArray("expectCommonOwners") : new JsonArray(); + assertTrue(owners.size() + commonOwners.size() > 0); + owners.forEach(el -> { + JsonObject expected = el.getAsJsonObject(); + assertEquals( + expected.get("owner").getAsString(), + registry.getAttrProvider( + expected.get("type").getAsString(), + expected.get("subType").getAsString(), + expected.get("attr").getAsString())); + }); + commonOwners.forEach(el -> { + JsonObject expected = el.getAsJsonObject(); + assertEquals( + expected.get("owner").getAsString(), + registry.getCommonAttrProvider(expected.get("attr").getAsString())); + }); + } + } + // ------------------------------------------------------------------ // #265 compose-load corpus — see the corpus README "The `compose-load/` // subdir". Own directory, own nested runner: a manifest here never carries diff --git a/server/java/metadata/src/test/java/com/metaobjects/registry/AttrOwnershipTest.java b/server/java/metadata/src/test/java/com/metaobjects/registry/AttrOwnershipTest.java new file mode 100644 index 0000000000..8823137851 --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/registry/AttrOwnershipTest.java @@ -0,0 +1,171 @@ +package com.metaobjects.registry; + +import com.metaobjects.ErrorCode; +import com.metaobjects.MetaDataException; +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.template.MetaTemplate; +import com.metaobjects.template.TemplateConstants; +import org.junit.Test; + +import java.util.List; +import java.util.function.Consumer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * ADR-0062 — the registry records which provider registered each attribute and refuses a + * second provider's claim on the same name. The cross-port scenarios live in + * {@code fixtures/provider-composition-conformance/}; this class pins what the shared corpus + * cannot (message text, same-slot extend, unowned registrations, the shipped core). + */ +public class AttrOwnershipTest { + + static final class RootTemplate extends MetaTemplate { + RootTemplate(String name) { super(TemplateConstants.SUBTYPE_BASE, name); } + } + + static final class ProbeTemplate extends MetaTemplate { + ProbeTemplate(String name) { super("probe", name); } + } + + static final class SiblingTemplate extends MetaTemplate { + SiblingTemplate(String name) { super("sibling", name); } + } + + private static void root(MetaDataRegistry r, String attr) { + r.registerType(RootTemplate.class, def -> { + def.type(TemplateConstants.TYPE_TEMPLATE).subType(TemplateConstants.SUBTYPE_BASE).description("root"); + def.optionalAttributeWithConstraints(attr).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + } + + private static void probe(MetaDataRegistry r, String attr) { + r.registerType(ProbeTemplate.class, def -> { + def.type(TemplateConstants.TYPE_TEMPLATE).subType("probe").description("probe") + .inheritsFrom(TemplateConstants.TYPE_TEMPLATE, TemplateConstants.SUBTYPE_BASE); + def.optionalAttributeWithConstraints(attr).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + } + + private static void sibling(MetaDataRegistry r, String attr) { + r.registerType(SiblingTemplate.class, def -> { + def.type(TemplateConstants.TYPE_TEMPLATE).subType("sibling").description("sibling"); + def.optionalAttributeWithConstraints(attr).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + } + + private static MetaDataTypeProvider provider(String id, String[] deps, Consumer body) { + return new MetaDataTypeProvider() { + @Override public String getProviderId() { return id; } + @Override public String[] getDependencies() { return deps; } + @Override public void registerTypes(MetaDataRegistry registry) { body.accept(registry); } + @Override public String getDescription() { return "test " + id; } + }; + } + + private static MetaDataException refusal(MetaDataTypeProvider... providers) { + try { + MetaDataRegistry.compose(List.of(providers)); + } catch (MetaDataException e) { + return e; + } + fail("expected the composition to be refused"); + return null; + } + + @Test + public void shadowingRegistrationNamesBothProvidersAndTheAttribute() { + MetaDataException e = refusal( + provider("owner-a", new String[0], r -> root(r, "physicalName")), + provider("owner-b", new String[]{"owner-a"}, r -> probe(r, "physicalName"))); + assertEquals(ErrorCode.ERR_PROVIDER_ATTR_SHADOW, e.getCode().orElseThrow()); + assertTrue(e.getMessage().contains("owner-a")); + assertTrue(e.getMessage().contains("owner-b")); + assertTrue(e.getMessage().contains("physicalName")); + } + + @Test + public void extendOntoTheSharedRootCollidesWithASubtypeName() { + MetaDataException e = refusal( + provider("owner-a", new String[0], r -> { + root(r, "other"); + probe(r, "physicalName"); + }), + provider("owner-b", new String[]{"owner-a"}, r -> + r.extendType(RootTemplate.class, def -> + def.optionalAttributeWithConstraints("physicalName") + .ofType(StringAttribute.SUBTYPE_STRING).asSingle()))); + assertEquals(ErrorCode.ERR_PROVIDER_ATTR_SHADOW, e.getCode().orElseThrow()); + } + + @Test + public void extendingASubtypeWithANameItOnlyInheritsIsAShadowEvenWhenTheSpecDiffers() { + MetaDataException e = refusal( + provider("owner-a", new String[0], r -> { + root(r, "physicalName"); + probe(r, "other"); + }), + provider("owner-b", new String[]{"owner-a"}, r -> + r.extendType(ProbeTemplate.class, def -> + def.optionalAttributeWithConstraints("physicalName") + .ofType(StringAttribute.SUBTYPE_STRING).asArray()))); + assertEquals(ErrorCode.ERR_PROVIDER_ATTR_SHADOW, e.getCode().orElseThrow()); + } + + @Test + public void ownerExtendingItsSubtypeWithAnInheritedNameIsLegalAndRecorded() { + MetaDataRegistry registry = MetaDataRegistry.compose(List.of( + provider("owner-a", new String[0], r -> { + root(r, "physicalName"); + probe(r, "other"); + r.extendType(ProbeTemplate.class, def -> + def.optionalAttributeWithConstraints("physicalName") + .ofType(StringAttribute.SUBTYPE_STRING).asSingle()); + }))); + assertEquals("owner-a", registry.getAttrProvider(TemplateConstants.TYPE_TEMPLATE, "probe", "physicalName")); + } + + @Test + public void sameSlotExtendByAnotherProviderKeepsAttrConflictAndNamesTheOwner() { + MetaDataException e = refusal( + provider("owner-a", new String[0], r -> probe(r, "physicalName")), + provider("owner-b", new String[]{"owner-a"}, r -> + r.extendType(ProbeTemplate.class, def -> + def.optionalAttributeWithConstraints("physicalName") + .ofType(StringAttribute.SUBTYPE_STRING).asSingle()))); + assertEquals(ErrorCode.ERR_PROVIDER_ATTR_CONFLICT, e.getCode().orElseThrow()); + assertTrue(e.getMessage().contains("owner-a")); + assertTrue(e.getMessage().contains("owner-b")); + } + + @Test + public void siblingSubtypesMayUseOneName() { + MetaDataRegistry registry = MetaDataRegistry.compose(List.of( + provider("owner-a", new String[0], r -> probe(r, "physicalName")), + provider("owner-b", new String[]{"owner-a"}, r -> sibling(r, "physicalName")))); + assertEquals("owner-a", registry.getAttrProvider("template", "probe", "physicalName")); + assertEquals("owner-b", registry.getAttrProvider("template", "sibling", "physicalName")); + } + + @Test + public void registrationOutsideAProviderTurnClaimsNothingAndCollidesWithNothing() { + MetaDataRegistry registry = MetaDataRegistry.compose(List.of( + provider("owner-a", new String[0], r -> root(r, "physicalName")))); + // After compose no provider is running: unowned, so not refused. + probe(registry, "physicalName"); + assertEquals("owner-a", registry.getAttrProvider("template", "base", "physicalName")); + assertNull(registry.getAttrProvider("template", "probe", "physicalName")); + } + + @Test + public void shippedCoreProvidersComposeWithNoCollisionAndNameTheirOwner() { + // Composing the shipped core is itself the audit: any cross-provider claim on a + // node type would throw ERR_PROVIDER_ATTR_SHADOW here. + MetaDataRegistry registry = RegistryManifest.composeMetamodelRegistry(List.of()); + assertNotNull(registry.getAttrProvider("metadata", "base", "isAbstract")); + } +} diff --git a/server/java/metadata/src/test/java/com/metaobjects/registry/RegistryManifestConformanceTest.java b/server/java/metadata/src/test/java/com/metaobjects/registry/RegistryManifestConformanceTest.java index c395cec386..f4622e7897 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/registry/RegistryManifestConformanceTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/registry/RegistryManifestConformanceTest.java @@ -216,8 +216,6 @@ public void carveOutsCarryTheirDeclaredReasonCategory() { RegistryManifest.classifyPerTypeAttr("object")); assertEquals(RegistryManifest.ExclusionReason.NATIVE_BINDING, RegistryManifest.classifyPerTypeAttr("objectAdapter")); - assertEquals(RegistryManifest.ExclusionReason.COMMON_ATTR_DUP, - RegistryManifest.classifyPerTypeAttr("description")); // Genuinely logical attrs are INCLUDED. assertEquals(RegistryManifest.ExclusionReason.INCLUDED, RegistryManifest.classifyPerTypeAttr("column")); diff --git a/server/python/src/metaobjects/errors.py b/server/python/src/metaobjects/errors.py index fc8a3b55e5..eac4041d32 100644 --- a/server/python/src/metaobjects/errors.py +++ b/server/python/src/metaobjects/errors.py @@ -53,6 +53,9 @@ class ErrorCode(str, Enum): ERR_PROVIDER_DUPLICATE_ID = "ERR_PROVIDER_DUPLICATE_ID" ERR_PROVIDER_MISSING_DEPENDENCY = "ERR_PROVIDER_MISSING_DEPENDENCY" ERR_PROVIDER_ATTR_CONFLICT = "ERR_PROVIDER_ATTR_CONFLICT" + # ADR-0062: a provider declared an attribute name another provider already declares + # on the type it inherits from (or on a subtype that inherits from it). + ERR_PROVIDER_ATTR_SHADOW = "ERR_PROVIDER_ATTR_SHADOW" # ADR-0050: a provider tried to PROJECT a REQUIRED attribute onto a type it does # not own (via TypeRegistry.extend). Projection is optional-only — a required # attr registered this way disappears silently whenever that provider is diff --git a/server/python/src/metaobjects/registry.py b/server/python/src/metaobjects/registry.py index 5113ca3ead..f0ccee113e 100644 --- a/server/python/src/metaobjects/registry.py +++ b/server/python/src/metaobjects/registry.py @@ -125,6 +125,9 @@ def __init__(self) -> None: # on a spec-declared subtype is never pruned by the library's strict # per-subtype allow-list — only LIBRARY-origin attrs are. self._attr_provenance: dict[tuple[str, str, str], str] = {} + # ADR-0062 -- common attr name -> the provider id that registered it + # (LIBRARY_ATTR_ORIGIN when registered outside any provider's turn). + self._common_attr_provenance: dict[str, str] = {} def seal(self) -> None: """Seal the registry: every subsequent mutating registration raises @@ -146,8 +149,60 @@ def _check_not_sealed(self, operation: str) -> None: ErrorCode.ERR_REGISTRY_SEALED, ) + def _check_attr_ownership(self, type_: str, sub_type: str, name: str) -> None: + """ADR-0062 -- the provider-collision rule. + + Provider P may not put attribute ``name`` on ``(type_, sub_type)`` when a DIFFERENT + provider Q already put the same name on a related slot: the slot itself, the type + it inherits from (``.base``) or, when this slot is the shared root, any + subtype that inherits from it; or registered it as a common attr, which every node + type accepts. Checked in both directions so the verdict does not + depend on which provider registered first. The same provider declaring a name on + several related slots stays legal, and an attr registered outside any provider's + turn (no current provider, or the library sentinel) claims nothing. + """ + claimant = self._current_provider_id + if claimant is None: + return + common_owner = self._common_attr_provenance.get(name, LIBRARY_ATTR_ORIGIN) + if common_owner not in (LIBRARY_ATTR_ORIGIN, claimant): + raise ParseError( + f'Provider "{claimant}" declares attribute "{name}" on "{type_}.{sub_type}", but ' + f'provider "{common_owner}" already registers it as a common attribute, which every ' + f'node type accepts; provider "{claimant}" cannot declare it again (ADR-0062)', + ErrorCode.ERR_PROVIDER_ATTR_CONFLICT, + ) + related = [sub_type] + if sub_type == SUBTYPE_BASE: + related += [s for (t, s) in self._defs if t == type_ and s != SUBTYPE_BASE] + elif (type_, SUBTYPE_BASE) in self._defs: + related.append(SUBTYPE_BASE) + for sub in related: + owner = self._attr_provenance.get((type_, sub, name)) + if owner is None or owner == LIBRARY_ATTR_ORIGIN or owner == claimant: + continue + if sub == sub_type: + raise ParseError( + f'TypeRegistry.extend: attribute "{name}" is already declared on ' + f'"{type_}.{sub_type}" by provider "{owner}"; provider "{claimant}" ' + "cannot declare it again (ADR-0062)", + ErrorCode.ERR_PROVIDER_ATTR_CONFLICT, + ) + raise ParseError( + f'Provider "{claimant}" declares attribute "{name}" on "{type_}.{sub_type}", ' + f'but provider "{owner}" already declares it on the related slot ' + f'"{type_}.{sub}". Two providers may not claim one attribute name on a type ' + "and the type it inherits from; give the second provider its own idiomatic " + "name (ADR-0062).", + ErrorCode.ERR_PROVIDER_ATTR_SHADOW, + ) + def register(self, definition: TypeDefinition) -> None: self._check_not_sealed(f'register("{definition.key}")') + # 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: + self._check_attr_ownership(definition.type, definition.sub_type, attr.name) # Store a per-registry COPY of the definition's mutable lists. Providers # hold their TypeDefinition objects as long-lived singletons (re-used across # every compose_registry call); a later provider's extend() does @@ -218,11 +273,37 @@ def default_sub_type_of(self, type_: str) -> str | None: return self._default_sub_types.get(type_) def register_common_attrs(self, attrs: list[AttrSchema]) -> None: - """Register attrs accepted on every metatype. First-wins dedupe by name. + """Register attrs accepted on every metatype. - Conflict with per-type attrs is detected at validation time, not here. + The same provider (or a registration outside any provider's turn) re-registering a + name is deduped; a different provider registering a name another provider holds, as + a common attr or on any type, raises ``ERR_PROVIDER_ATTR_CONFLICT`` (ADR-0062). A + name one provider holds both ways is resolved at validation time. """ self._check_not_sealed("register_common_attrs") + # ADR-0062: checked for the whole batch first, so a refusal leaves no trace. + claimant = self._current_provider_id + for attr in attrs: + if claimant is None: + break + owner = self._common_attr_provenance.get(attr.name, LIBRARY_ATTR_ORIGIN) + if owner not in (LIBRARY_ATTR_ORIGIN, claimant): + raise ParseError( + f'Provider "{claimant}" registers common attribute "{attr.name}", but ' + f'provider "{owner}" already registers it as a common attribute; provider ' + f'"{claimant}" cannot declare it again (ADR-0062)', + ErrorCode.ERR_PROVIDER_ATTR_CONFLICT, + ) + for (slot_type, slot_sub, slot_attr), slot_owner in self._attr_provenance.items(): + if slot_attr != attr.name or slot_owner in (LIBRARY_ATTR_ORIGIN, claimant): + continue + raise ParseError( + f'Provider "{claimant}" registers common attribute "{attr.name}", which every ' + f'node type accepts, but provider "{slot_owner}" already declares it on ' + f'"{slot_type}.{slot_sub}"; provider "{claimant}" cannot declare it again ' + "(ADR-0062)", + ErrorCode.ERR_PROVIDER_ATTR_CONFLICT, + ) for attr in attrs: # ADR-0050, the second door. A common attr is projected onto EVERY registered # type, so a required one is the same defect as a required extend() -- with the @@ -239,8 +320,15 @@ def register_common_attrs(self, attrs: list[AttrSchema]) -> None: ErrorCode.ERR_EXTEND_REQUIRED_ATTR, ) if any(existing.name == attr.name for existing in self._common_attrs): - continue # first registration wins + continue # dedupe same-name re-registration self._common_attrs.append(attr) + self._common_attr_provenance[attr.name] = claimant or LIBRARY_ATTR_ORIGIN + + def common_attr_origin(self, attr_name: str) -> str: + """The provider id that registered common attr ``attr_name``, or + :data:`LIBRARY_ATTR_ORIGIN` if unregistered or registered outside any provider's + turn (ADR-0062).""" + return self._common_attr_provenance.get(attr_name, LIBRARY_ATTR_ORIGIN) def get_common_attrs(self) -> list[AttrSchema]: """Return a defensive copy of the registered common attrs.""" @@ -317,11 +405,14 @@ def extend( f"which is not valid for attrs. Use None for a polymorphic/untyped attr." ) if any(existing.name == attr.name for existing in definition.attrs): + # ADR-0062: name the provider that holds the slot when it is a different one. + self._check_attr_ownership(type_, sub_type, attr.name) raise ParseError( f'TypeRegistry.extend: attribute "{attr.name}" is already declared ' f'on "{type_}.{sub_type}"', ErrorCode.ERR_PROVIDER_ATTR_CONFLICT, ) + self._check_attr_ownership(type_, sub_type, attr.name) # ADR-0050: a REQUIRED attr may never be PROJECTED onto someone else's # type. A provider may only project OPTIONAL attributes onto a type it # does not own — a required attr registered this way disappears, diff --git a/server/python/tests/conformance/test_provider_composition_conformance.py b/server/python/tests/conformance/test_provider_composition_conformance.py index 71a3d6e78b..e9530d38b1 100644 --- a/server/python/tests/conformance/test_provider_composition_conformance.py +++ b/server/python/tests/conformance/test_provider_composition_conformance.py @@ -119,8 +119,77 @@ def register_types(self, registry: TypeRegistry) -> None: # noqa: D401 ) +# ADR-0062 -- attribute-ownership providers (see the corpus README). All register on +# `template.base` and the fresh subtype `template.shadowprobe`. +_SHADOW_SUBTYPE = "shadowprobe" + + +def _template_type(sub_type: str, attr_name: str) -> TypeDefinition: + return TypeDefinition( + type="template", + sub_type=sub_type, + factory=lambda t, s, n: MetaTemplate(t, s, n), + attrs=[AttrSchema(attr_name, "string")], + child_rules=[], + ) + + +def _shadow_provider(provider_id: str, deps: tuple[str, ...], *types: tuple[str, str]) -> Provider: + p = Provider(provider_id, dependencies=deps) + for sub_type, attr_name in types: + p.add(_template_type(sub_type, attr_name)) + return p + + +class _ShadowSubExtendClashProvider(Provider): + """Extends `template.shadowprobe` with the name `shadow-base` owns on the root.""" + + def __init__(self) -> None: + super().__init__("shadow-sub-extend-clash", dependencies=("shadow-sub-distinct",)) + + def register_types(self, registry: TypeRegistry) -> None: # noqa: D401 + registry.extend("template", _SHADOW_SUBTYPE, attributes=[AttrSchema("shadowAttr", "string")]) + + +class _CommonAttrProvider(Provider): + """Registers one optional string common attr; `self_claim` also declares it on + `template.shadowprobe` and then registers the common attr again.""" + + def __init__(self, provider_id: str, deps: tuple[str, ...], attr_name: str, self_claim: bool = False) -> None: + super().__init__(provider_id, dependencies=deps) + self._attr_name = attr_name + self._self_claim = self_claim + + def register_types(self, registry: TypeRegistry) -> None: # noqa: D401 + registry.register_common_attrs([AttrSchema(self._attr_name, "string")]) + if self._self_claim: + registry.register(_template_type(_SHADOW_SUBTYPE, self._attr_name)) + registry.register_common_attrs([AttrSchema(self._attr_name, "string")]) + + def _providers() -> dict[str, Provider]: return { + "shadow-sub-extend-clash": _ShadowSubExtendClashProvider(), + "common-owner": _CommonAttrProvider("common-owner", (), "commonAttr"), + "common-clash": _CommonAttrProvider("common-clash", ("common-owner",), "commonAttr"), + "common-self": _CommonAttrProvider("common-self", (), "selfCommonAttr", self_claim=True), + "common-sub-clash": _shadow_provider("common-sub-clash", ("common-owner",), (_SHADOW_SUBTYPE, "commonAttr")), + "common-sub-owner": _shadow_provider("common-sub-owner", (), (_SHADOW_SUBTYPE, "lateCommonAttr")), + "common-late": _CommonAttrProvider("common-late", ("common-sub-owner",), "lateCommonAttr"), + "shadow-base": _shadow_provider("shadow-base", (), ("base", "shadowAttr")), + "shadow-sub-clash": _shadow_provider( + "shadow-sub-clash", ("shadow-base",), (_SHADOW_SUBTYPE, "shadowAttr") + ), + "shadow-sub-owner": _shadow_provider("shadow-sub-owner", (), (_SHADOW_SUBTYPE, "reverseAttr")), + "shadow-base-late": _shadow_provider( + "shadow-base-late", ("shadow-sub-owner",), ("base", "reverseAttr") + ), + "shadow-sub-distinct": _shadow_provider( + "shadow-sub-distinct", ("shadow-base",), (_SHADOW_SUBTYPE, "distinctAttr") + ), + "shadow-self": _shadow_provider( + "shadow-self", (), ("base", "selfAttr"), (_SHADOW_SUBTYPE, "selfAttr") + ), "duplicate-x": _noop_provider("duplicate-x"), # Same `.id` as duplicate-x — surfaces ERR_PROVIDER_DUPLICATE_ID at compose time. "duplicate-x-clone": _noop_provider("duplicate-x"), @@ -225,3 +294,29 @@ def test_provider_composition_compose_load(manifest_path: Path) -> None: actual_codes = sorted(_error_code(e) for e in result.errors) expected_codes = sorted(manifest.get("expectErrors", [])) assert actual_codes == expected_codes + + +# --------------------------------------------------------------------------- +# ADR-0062 `attr-ownership/` corpus -- composition succeeds and the registry +# names the provider that owns each attribute. +# --------------------------------------------------------------------------- + + +def _ownership_manifest_files() -> list[Path]: + return sorted((_corpus_root() / "attr-ownership").glob("*.json")) + + +def test_attr_ownership_corpus_non_empty() -> None: + assert len(_ownership_manifest_files()) > 0 + + +@pytest.mark.parametrize("manifest_path", _ownership_manifest_files(), ids=lambda p: p.name) +def test_provider_composition_attr_ownership(manifest_path: Path) -> None: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + providers = _providers() + registry = compose_registry([_resolve(providers, pid) for pid in manifest["providers"]]) + assert manifest.get("expectOwners") or manifest.get("expectCommonOwners") + for owner in manifest.get("expectOwners", []): + assert registry.attr_origin(owner["type"], owner["subType"], owner["attr"]) == owner["owner"] + for owner in manifest.get("expectCommonOwners", []): + assert registry.common_attr_origin(owner["attr"]) == owner["owner"] diff --git a/server/python/tests/unit/test_registry_attr_ownership.py b/server/python/tests/unit/test_registry_attr_ownership.py new file mode 100644 index 0000000000..7aa418c580 --- /dev/null +++ b/server/python/tests/unit/test_registry_attr_ownership.py @@ -0,0 +1,117 @@ +"""ADR-0062 -- the registry records which provider registered each attribute and refuses a +second provider's claim on the same name. The cross-port scenarios live in +fixtures/provider-composition-conformance/; this file pins what the shared corpus cannot +(message text, no-trace-on-refusal, unowned registrations, the shipped core).""" +from __future__ import annotations + +import pytest + +from metaobjects.core_types import core_providers +from metaobjects.errors import ErrorCode, ParseError +from metaobjects.meta.template.meta_template import MetaTemplate +from metaobjects.provider import Provider, compose_registry +from metaobjects.registry import LIBRARY_ATTR_ORIGIN, AttrSchema, TypeDefinition, TypeRegistry + + +def _type(sub_type: str, *names: str) -> TypeDefinition: + return TypeDefinition( + type="template", + sub_type=sub_type, + factory=lambda t, s, n: MetaTemplate(t, s, n), + attrs=[AttrSchema(n, "string") for n in names], + child_rules=[], + ) + + +def _provider(provider_id: str, *types: TypeDefinition, deps: tuple[str, ...] = ()) -> Provider: + p = Provider(provider_id, dependencies=deps) + for t in types: + p.add(t) + return p + + +def test_shadowing_registration_names_both_providers_and_the_attribute() -> None: + with pytest.raises(ParseError) as exc: + compose_registry( + [ + _provider("owner-a", _type("base", "physicalName")), + _provider("owner-b", _type("probe", "physicalName"), deps=("owner-a",)), + ] + ) + assert exc.value.code == ErrorCode.ERR_PROVIDER_ATTR_SHADOW + for needle in ("owner-a", "owner-b", "physicalName"): + assert needle in str(exc.value) + + +def test_extend_onto_the_shared_root_collides_with_a_subtype_name() -> None: + class _Extender(Provider): + def register_types(self, registry: TypeRegistry) -> None: + registry.extend("template", "base", attributes=[AttrSchema("physicalName", "string")]) + + extender = _Extender("owner-b", dependencies=("owner-a",)) + with pytest.raises(ParseError) as exc: + compose_registry( + [ + _provider("owner-a", _type("base", "other"), _type("probe", "physicalName")), + extender, + ] + ) + assert exc.value.code == ErrorCode.ERR_PROVIDER_ATTR_SHADOW + + +def test_same_slot_extend_by_another_provider_keeps_attr_conflict_and_names_the_owner() -> None: + class _Extender(Provider): + def register_types(self, registry: TypeRegistry) -> None: + registry.extend("template", "probe", attributes=[AttrSchema("physicalName", "string")]) + + with pytest.raises(ParseError) as exc: + compose_registry( + [ + _provider("owner-a", _type("probe", "physicalName")), + _Extender("owner-b", dependencies=("owner-a",)), + ] + ) + assert exc.value.code == ErrorCode.ERR_PROVIDER_ATTR_CONFLICT + assert "owner-a" in str(exc.value) and "owner-b" in str(exc.value) + + +def test_sibling_subtypes_may_use_one_name() -> None: + registry = compose_registry( + [ + _provider("owner-a", _type("probe-a", "physicalName")), + _provider("owner-b", _type("probe-b", "physicalName"), deps=("owner-a",)), + ] + ) + assert registry.attr_origin("template", "probe-a", "physicalName") == "owner-a" + assert registry.attr_origin("template", "probe-b", "physicalName") == "owner-b" + + +def test_refused_registration_leaves_no_trace() -> None: + registry = TypeRegistry() + registry._current_provider_id = "owner-a" # noqa: SLF001 + registry.register(_type("base", "physicalName")) + registry._current_provider_id = "owner-b" # noqa: SLF001 + with pytest.raises(ParseError): + registry.register(_type("probe", "physicalName")) + assert registry.find("template", "probe") is None + assert registry.attr_origin("template", "probe", "physicalName") == LIBRARY_ATTR_ORIGIN + + +def test_registration_outside_a_provider_turn_claims_nothing() -> None: + registry = TypeRegistry() + registry.register(_type("base", "physicalName")) + registry._current_provider_id = "owner-b" # noqa: SLF001 + registry.register(_type("probe", "physicalName")) + assert registry.attr_origin("template", "base", "physicalName") == LIBRARY_ATTR_ORIGIN + assert registry.attr_origin("template", "probe", "physicalName") == "owner-b" + + +def test_shipped_core_providers_compose_with_no_collision_and_every_attr_has_an_owner() -> None: + registry = compose_registry(core_providers) + unowned = [ + f"{t}.{s}.{a.name}" + for (t, s) in registry._defs # noqa: SLF001 + for a in registry.attrs_of(t, s) + if registry.attr_origin(t, s, a.name) == LIBRARY_ATTR_ORIGIN + ] + assert unowned == [] diff --git a/server/typescript/packages/cli/src/commands/types.ts b/server/typescript/packages/cli/src/commands/types.ts index 8378583e3b..8e47d88192 100644 --- a/server/typescript/packages/cli/src/commands/types.ts +++ b/server/typescript/packages/cli/src/commands/types.ts @@ -134,6 +134,8 @@ interface Entry { tsOnly: boolean; /** A type's shared root (`.base`): its attrs apply to every subtype. */ sharedRoot: boolean; + /** An attr entry: the id of the provider that registered it (ADR-0062). */ + provider: string | undefined; raw: unknown; // the catalog node } @@ -159,9 +161,10 @@ interface RawAttr { whenToUse?: string; } -function attrRecord(at: RawAttr): Record { +function attrRecord(at: RawAttr, provider?: string): Record { return { name: at.name, + ...(provider !== undefined ? { provider } : {}), valueType: at.valueType, isArray: at.isArray, required: at.required, @@ -187,12 +190,14 @@ function payloadMatch(e: Entry): Record { ...(e.whenToUse !== undefined ? { whenToUse: e.whenToUse } : {}), }; if (e.kind === "subtype") { - out.attrs = (e.raw as { attrs: RawAttr[] }).attrs.map(attrRecord); + const mt = e.raw as { attrs: RawAttr[]; attrProviders: Record }; + out.attrs = mt.attrs.map((at) => attrRecord(at, mt.attrProviders[at.name])); } else { const at = e.raw as RawAttr; out.valueType = at.valueType; out.isArray = at.isArray; out.required = at.required; + if (e.provider !== undefined) out.provider = e.provider; if (at.allowedValues !== undefined) out.allowedValues = at.allowedValues; } return out; @@ -280,13 +285,13 @@ export async function typesCommand(args: string[], fmt: OutputFormat = "text"): kind: "subtype", name: tsName, owner: tsName, type: mt.type, description: mt.description, whenToUse: mt.whenToUse, attrNames: mt.attrs.map((a) => `@${a.name}`), - common: false, tsOnly: !mt.crossPort, sharedRoot: mt.sharedRoot, raw: mt, + common: false, tsOnly: !mt.crossPort, sharedRoot: mt.sharedRoot, provider: undefined, raw: mt, }); for (const at of mt.attrs) { entries.push({ kind: "attr", name: `${tsName} @${at.name}`, owner: tsName, type: mt.type, description: at.description, whenToUse: at.whenToUse, attrNames: [], - common: false, tsOnly: !mt.crossPort, sharedRoot: false, raw: at, + common: false, tsOnly: !mt.crossPort, sharedRoot: false, provider: mt.attrProviders[at.name], raw: at, }); } } @@ -299,7 +304,7 @@ export async function typesCommand(args: string[], fmt: OutputFormat = "text"): entries.push({ kind: "attr", name: `@${at.name}`, owner: "(any node)", type: "", description: at.description, whenToUse: at.whenToUse, attrNames: [], - common: true, tsOnly: false, sharedRoot: false, raw: at, + common: true, tsOnly: false, sharedRoot: false, provider: catalog.commonAttrProviders[at.name], raw: at, }); } @@ -359,12 +364,19 @@ export async function typesCommand(args: string[], fmt: OutputFormat = "text"): log.info(" TypeScript-only: registered here, but not part of the cross-port metamodel contract."); if (e.whenToUse) log.info(` → reach for it when: ${e.whenToUse}`); if (e.kind === "subtype") { - const mt = e.raw as { attrs: { name: string; valueType: string | null; required: boolean; description: string }[] }; + const mt = e.raw as { + attrs: { name: string; valueType: string | null; required: boolean; description: string }[]; + attrProviders: Record; + }; if (mt.attrs.length) { log.info(" @attrs:"); - for (const at of mt.attrs) - log.info(` @${at.name} ${at.valueType ?? "any"}${at.required ? " REQUIRED" : ""} ${at.description}`); + for (const at of mt.attrs) { + const by = mt.attrProviders[at.name]; + log.info(` @${at.name} ${at.valueType ?? "any"}${at.required ? " REQUIRED" : ""}${by !== undefined ? ` [${by}]` : ""} ${at.description}`); + } } + } else if (e.provider !== undefined) { + log.info(` registered by provider: ${e.provider}`); } } } else { diff --git a/server/typescript/packages/cli/test/types-command.test.ts b/server/typescript/packages/cli/test/types-command.test.ts index 91acd508e5..47d7b153ad 100644 --- a/server/typescript/packages/cli/test/types-command.test.ts +++ b/server/typescript/packages/cli/test/types-command.test.ts @@ -318,3 +318,26 @@ describe("--detail prints each attr once", () => { expect(out).toContain("field.string @maxLength (attr)"); }); }); + +describe("ADR-0062 every attribute names the provider that registered it", () => { + test("--detail lists the owning provider beside each @attr", async () => { + const out = await run(["field.string", "--detail"]); + // @column is registered by the db provider onto a type the core provider owns. + expect(out).toMatch(/@column .*\[metaobjects-db\]/); + }); + + test("the JSON answer carries `provider` on each attr", async () => { + const calls: string[] = []; + const spy = spyOn(console, "log").mockImplementation((...a: unknown[]) => { + calls.push(a.map(String).join(" ")); + }); + try { + expect(await typesCommand(["field.string", "--limit", "0"], "json")).toBe(0); + } finally { + spy.mockRestore(); + } + const doc = JSON.parse(calls[0] as string) as { matches: { name: string; attrs?: { name: string; provider?: string }[] }[] }; + const subtype = doc.matches.find((m) => m.name === "field.string"); + expect(subtype?.attrs?.find((a) => a.name === "column")?.provider).toBe("metaobjects-db"); + }); +}); diff --git a/server/typescript/packages/metadata/src/errors.ts b/server/typescript/packages/metadata/src/errors.ts index 504ca1ec0d..e9616a15a8 100644 --- a/server/typescript/packages/metadata/src/errors.ts +++ b/server/typescript/packages/metadata/src/errors.ts @@ -76,6 +76,9 @@ export const ERROR_CODES = [ "ERR_PROVIDER_DUPLICATE_ID", "ERR_PROVIDER_MISSING_DEPENDENCY", "ERR_PROVIDER_ATTR_CONFLICT", + // ADR-0062 — a provider declared an attribute name another provider already declares on + // the type it inherits from (or on a subtype that inherits from it). + "ERR_PROVIDER_ATTR_SHADOW", "ERR_EXTEND_REQUIRED_ATTR", "ERR_MALFORMED_JSON", "ERR_MISSING_REQUIRED_ATTR", diff --git a/server/typescript/packages/metadata/src/provider.ts b/server/typescript/packages/metadata/src/provider.ts index 1aabdc5ee1..88f74fed53 100644 --- a/server/typescript/packages/metadata/src/provider.ts +++ b/server/typescript/packages/metadata/src/provider.ts @@ -35,7 +35,9 @@ export function composeRegistry( const ordered = topoSortProviders(providers); const registry = new TypeRegistry(); for (const provider of ordered) { - provider.registerTypes(registry); + // ADR-0062: the registry attributes every attribute registered or extended during + // this turn to the provider, and refuses another provider's claim on the same name. + registry.runAsProvider(provider.id, () => provider.registerTypes(registry)); } // FR-033 — opt-in metamodel contradiction gate. The library bootstrap (the // loader's default registry) sets validate:true so a contradictory provider set diff --git a/server/typescript/packages/metadata/src/registry.ts b/server/typescript/packages/metadata/src/registry.ts index edb12b2014..028526c966 100644 --- a/server/typescript/packages/metadata/src/registry.ts +++ b/server/typescript/packages/metadata/src/registry.ts @@ -129,6 +129,20 @@ export class TypeRegistry { /** Keyed by `"type.subType"`. */ private readonly _defs = new Map(); + /** + * ADR-0062 — the provider whose `registerTypes` turn is running, set by + * `runAsProvider` (which `composeRegistry` wraps around every provider). `undefined` + * outside a compose loop (a hand-built registry in a unit test), where nothing is + * attributed and nothing can collide. + */ + private _currentProviderId: string | undefined; + + /** ADR-0062 — `"type.subType"` -> (attr name -> id of the provider that registered it). */ + private readonly _attrOwners = new Map>(); + + /** ADR-0062 — common attr name -> id of the provider that registered it. */ + private readonly _commonAttrOwners = new Map(); + /** Per-type insertion-ordered subtype lists. */ private readonly _subTypes = new Map(); @@ -158,6 +172,93 @@ export class TypeRegistry { return this._sealed; } + /** + * Run `fn` with `providerId` recorded as the owner of every attribute registered or + * extended during the call (ADR-0062). `composeRegistry` wraps each provider's + * `registerTypes` in this; a hand-rolled composition may do the same. + */ + runAsProvider(providerId: string, fn: () => T): T { + const previous = this._currentProviderId; + this._currentProviderId = providerId; + try { + return fn(); + } finally { + this._currentProviderId = previous; + } + } + + /** + * The id of the provider that registered attribute `name` on exactly + * `(type, subType)`, or `undefined` when it is not registered there or was registered + * outside any provider's turn. Inherited attributes report the id of their declaring + * slot, so ask `.base` for those. Used by the collision rule and by `meta types`. + */ + attrOwner(type: string, subType: string, name: string): string | undefined { + return this._attrOwners.get(`${type}.${subType}`)?.get(name); + } + + private stampAttrOwner(type: string, subType: string, name: string): void { + if (this._currentProviderId === undefined) return; + 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); + } + + /** + * ADR-0062 — the provider-collision rule. Provider P may not put attribute `name` on + * `(type, subType)` when a DIFFERENT provider Q already put the same name on a related + * slot: the slot itself, a type it inherits from (`.base`), or — when this slot + * is the shared root — any subtype that inherits from it; or registered it as a common + * attribute, which every node type accepts. Checked in both directions + * so the verdict does not depend on which provider happened to register first. The + * same provider declaring a name on several related slots stays legal, and an + * attribute registered outside any provider's turn claims nothing. + */ + private checkAttrOwnership(type: string, subType: string, name: string): void { + const claimant = this._currentProviderId; + if (claimant === undefined) return; + const commonOwner = this._commonAttrOwners.get(name); + if (commonOwner !== undefined && commonOwner !== claimant) { + throw new MetaModelError( + `Provider "${claimant}" declares attribute "${name}" on "${type}.${subType}", but provider ` + + `"${commonOwner}" already registers it as a common attribute, which every node type accepts; ` + + `provider "${claimant}" cannot declare it again (ADR-0062)`, + { code: "ERR_PROVIDER_ATTR_CONFLICT" }, + ); + } + const related: string[] = []; + if (subType === SUBTYPE_BASE) { + for (const sub of this._subTypes.get(type) ?? []) { + if (sub !== SUBTYPE_BASE) related.push(sub); + } + } else if (this._defs.has(`${type}.${SUBTYPE_BASE}`)) { + related.push(SUBTYPE_BASE); + } + related.unshift(subType); + for (const sub of related) { + const owner = this._attrOwners.get(`${type}.${sub}`)?.get(name); + if (owner === undefined || owner === claimant) continue; + if (sub === subType) { + throw new MetaModelError( + `TypeRegistry.extend: attribute "${name}" is already declared on "${type}.${subType}" ` + + `by provider "${owner}"; provider "${claimant}" cannot declare it again (ADR-0062)`, + { code: "ERR_PROVIDER_ATTR_CONFLICT" }, + ); + } + throw new MetaModelError( + `Provider "${claimant}" declares attribute "${name}" on "${type}.${subType}", but provider ` + + `"${owner}" already declares it on the related slot "${type}.${sub}". Two providers ` + + `may not claim one attribute name on a type and the type it inherits from; give the ` + + `second provider its own idiomatic name (ADR-0062).`, + { code: "ERR_PROVIDER_ATTR_SHADOW" }, + ); + } + } + /** Guard at the top of every mutating registration method. */ private checkNotSealed(operation: string): void { if (this._sealed) { @@ -194,14 +295,21 @@ export class TypeRegistry { } } - this._defs.set(key, 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. const list = this._subTypes.get(def.typeId.type); + for (const attr of def.attributes) { + this.checkAttrOwnership(def.typeId.type, def.typeId.subType, attr.name); + } + this._defs.set(key, def); if (list !== undefined) { list.push(def.typeId.subType); } else { this._subTypes.set(def.typeId.type, [def.typeId.subType]); } + for (const attr of def.attributes) { + this.stampAttrOwner(def.typeId.type, def.typeId.subType, attr.name); + } } find(type: string, subType: string): TypeDefinition | undefined { @@ -239,12 +347,39 @@ export class TypeRegistry { /** * Register attrs that are accepted on every metatype. Callers (providers) use - * this to declare cross-cutting attrs (e.g. doc attrs). Repeated registration - * of the same name is silently deduped (first registration wins); conflicts with - * per-type attrs are resolved at validation time (Task 1.3). + * this to declare cross-cutting attrs (e.g. doc attrs). The same provider (or a + * registration outside any provider's turn) re-registering a name is deduped; a + * different provider registering a name another provider holds, as a common attr or + * on any type, is `ERR_PROVIDER_ATTR_CONFLICT` (ADR-0062). A name one provider holds + * both ways is resolved at validation time (Task 1.3). */ registerCommonAttrs(attrs: AttrSchema[]): void { this.checkNotSealed("registerCommonAttrs"); + // ADR-0062: a common attr is on every node type, so another provider may not register + // a common attr name a provider already holds, as a common attr or on any type. + // Checked for the whole batch first, so a refusal leaves no trace. + const claimant = this._currentProviderId; + for (const attr of attrs) { + if (claimant === undefined) break; + const owner = this._commonAttrOwners.get(attr.name); + if (owner !== undefined && owner !== claimant) { + throw new MetaModelError( + `Provider "${claimant}" registers common attribute "${attr.name}", but provider "${owner}" ` + + `already registers it as a common attribute; provider "${claimant}" cannot declare it again (ADR-0062)`, + { code: "ERR_PROVIDER_ATTR_CONFLICT" }, + ); + } + for (const [slot, owners] of this._attrOwners) { + const slotOwner = owners.get(attr.name); + if (slotOwner === undefined || slotOwner === claimant) continue; + throw new MetaModelError( + `Provider "${claimant}" registers common attribute "${attr.name}", which every node type accepts, ` + + `but provider "${slotOwner}" already declares it on "${slot}"; provider "${claimant}" cannot ` + + `declare it again (ADR-0062)`, + { code: "ERR_PROVIDER_ATTR_CONFLICT" }, + ); + } + } for (const attr of attrs) { if (attr.valueType === SUBTYPE_BASE) { throw new Error( @@ -267,12 +402,18 @@ export class TypeRegistry { ); } if (this._commonAttrs.some((existing) => existing.name === attr.name)) { - continue; // dedupe same-name re-registration; conflict-with-per-type-attr is checked at validation time + continue; // dedupe same-name re-registration } this._commonAttrs.push(attr); + if (claimant !== undefined) this._commonAttrOwners.set(attr.name, claimant); } } + /** The id of the provider that registered common attr `name`, if one was composed in. */ + commonAttrOwner(name: string): string | undefined { + return this._commonAttrOwners.get(name); + } + /** Returns the registered common attrs (attrs accepted on every metatype). * Returns a defensive copy so callers cannot mutate internal state, matching * the spread-copy pattern used by `attrsOf` and `allSubTypesOf`. */ @@ -306,11 +447,14 @@ export class TypeRegistry { ); } if (def.attributes.some((a) => a.name === attr.name)) { + // ADR-0062: name the provider that holds the slot when it is a different one. + this.checkAttrOwnership(type, subType, attr.name); throw new MetaModelError( `TypeRegistry.extend: attribute "${attr.name}" is already declared on "${type}.${subType}"`, { code: "ERR_PROVIDER_ATTR_CONFLICT" }, ); } + this.checkAttrOwnership(type, subType, attr.name); // ADR-0050: a REQUIRED attr may never be PROJECTED onto someone else's type. // `extend` is how a concern provider decorates a type another provider owns, and // a concern can be composed out. A required attr arriving this way makes the @@ -332,6 +476,7 @@ export class TypeRegistry { ); } def.attributes.push(attr); + this.stampAttrOwner(type, subType, attr.name); } for (const rule of ext.childRules ?? []) { def.childRules.push(rule); diff --git a/server/typescript/packages/metadata/src/vocabulary-catalog.ts b/server/typescript/packages/metadata/src/vocabulary-catalog.ts index 953b168265..0eaa1481e9 100644 --- a/server/typescript/packages/metadata/src/vocabulary-catalog.ts +++ b/server/typescript/packages/metadata/src/vocabulary-catalog.ts @@ -42,6 +42,12 @@ export interface VocabularyType { example?: string; whenToUse?: string; attrs: ManifestAttr[]; + /** + * `attr name -> id of the provider that registered it on exactly this (type, subType)` + * (ADR-0062). Only attrs a composed provider registered appear; an attr this slot + * inherits from `.base` is listed on the base row. + */ + attrProviders: Record; children: ManifestChild[]; parents?: string[]; /** @@ -68,10 +74,12 @@ export interface VocabularyCatalog { types: VocabularyType[]; /** Attrs accepted on EVERY node, whatever its type (`@title`, `@description`, …). */ commonAttrs: ManifestAttr[]; + /** `common attr name -> id of the provider that registered it` (ADR-0062). */ + commonAttrProviders: Record; defaultSubTypes: Record; } -function toVocabularyType(def: TypeDefinition): VocabularyType { +function toVocabularyType(def: TypeDefinition, registry: TypeRegistry): VocabularyType { const { type, subType } = def.typeId; const reason = classifyTypeSubType(type, subType); const out: VocabularyType = { @@ -89,11 +97,16 @@ function toVocabularyType(def: TypeDefinition): VocabularyType { // CROSS-PORT value during a reference-first rollout, and this answer is about what // THIS registry requires of an author right now. attrs: sortedAttrs(def.attributes.filter((a) => classifyPerTypeAttr(a.name) === INCLUDED)), + attrProviders: {}, children: sortedChildren(def.childRules), crossPort: reason === undefined, ...(reason !== undefined ? { portPrivateReason: reason } : {}), sharedRoot: subType === SUBTYPE_BASE, }; + for (const attr of out.attrs) { + const owner = registry.attrOwner(type, subType, attr.name); + if (owner !== undefined) out.attrProviders[attr.name] = owner; + } if (def.parents !== undefined && def.parents.length > 0) { out.parents = [...def.parents].sort(compareStrings); } @@ -112,7 +125,7 @@ function toVocabularyType(def: TypeDefinition): VocabularyType { export function buildVocabularyCatalog(registry: TypeRegistry): VocabularyCatalog { const types = registry .allTypes() - .map((typeId) => toVocabularyType(registry.find(typeId.type, typeId.subType) as TypeDefinition)) + .map((typeId) => toVocabularyType(registry.find(typeId.type, typeId.subType) as TypeDefinition, registry)) .sort((a, b) => compareStrings(`${a.type}.${a.subType}`, `${b.type}.${b.subType}`), ); @@ -124,10 +137,18 @@ export function buildVocabularyCatalog(registry: TypeRegistry): VocabularyCatalo if (defaultSub !== undefined) defaultSubTypes[typeName] = defaultSub; } + const commonAttrs = sortedAttrs(registry.getCommonAttrs()); + const commonAttrProviders: Record = {}; + for (const attr of commonAttrs) { + const owner = registry.commonAttrOwner(attr.name); + if (owner !== undefined) commonAttrProviders[attr.name] = owner; + } + return { metamodelVersion: METAMODEL_VERSION, types, - commonAttrs: sortedAttrs(registry.getCommonAttrs()), + commonAttrs, + commonAttrProviders, defaultSubTypes, }; } diff --git a/server/typescript/packages/metadata/test/provider-composition-conformance.test.ts b/server/typescript/packages/metadata/test/provider-composition-conformance.test.ts index 9ed1034141..a8ba5a43c9 100644 --- a/server/typescript/packages/metadata/test/provider-composition-conformance.test.ts +++ b/server/typescript/packages/metadata/test/provider-composition-conformance.test.ts @@ -17,9 +17,9 @@ import { join } from "node:path"; import { readdirSync } from "node:fs"; import type { MetaDataTypeProvider } from "../src/provider.js"; import { composeRegistry } from "../src/provider.js"; -import { TypeRegistry, TypeId } from "../src/registry.js"; +import { TypeRegistry, TypeId, type AttrSchema } from "../src/registry.js"; import { MetaTemplate } from "../src/template/meta-template.js"; -import { TYPE_TEMPLATE, TYPE_ATTR, TYPE_VIEW } from "../src/shared/base-types.js"; +import { TYPE_TEMPLATE, TYPE_ATTR, TYPE_VIEW, SUBTYPE_BASE } from "../src/shared/base-types.js"; import { CHILD_RULE_WILDCARD } from "../src/shared/structural.js"; import { ATTR_SUBTYPE_STRING, ATTR_SUBTYPE_INT } from "../src/core/attr/attr-constants.js"; import { VIEW_SUBTYPE_CURRENCY } from "../src/presentation/view/view-constants.js"; @@ -147,7 +147,114 @@ const extendSpecSubtypeProvider: MetaDataTypeProvider = { }, }; +// ADR-0062 — attribute-ownership providers (see the corpus README). All register on +// `template.base` and the fresh subtype `template.shadowprobe`. +const SHADOW_SUBTYPE = "shadowprobe"; + +function templateType(subType: string, attrName: string): Parameters[0] { + return { + typeId: new TypeId(TYPE_TEMPLATE, subType), + description: "Test-only — attribute-ownership probe.", + factory: (typeId, name) => new MetaTemplate(typeId, name), + childRules: [], + attributes: [ + { name: attrName, valueType: ATTR_SUBTYPE_STRING, required: false, description: "Ownership probe attr." }, + ], + }; +} + +const shadowBaseProvider: MetaDataTypeProvider = { + id: "shadow-base", + registerTypes: (registry) => registry.register(templateType(SUBTYPE_BASE, "shadowAttr")), +}; +const shadowSubClashProvider: MetaDataTypeProvider = { + id: "shadow-sub-clash", + dependencies: ["shadow-base"], + registerTypes: (registry) => registry.register(templateType(SHADOW_SUBTYPE, "shadowAttr")), +}; +const shadowSubOwnerProvider: MetaDataTypeProvider = { + id: "shadow-sub-owner", + registerTypes: (registry) => registry.register(templateType(SHADOW_SUBTYPE, "reverseAttr")), +}; +const shadowBaseLateProvider: MetaDataTypeProvider = { + id: "shadow-base-late", + dependencies: ["shadow-sub-owner"], + registerTypes: (registry) => registry.register(templateType(SUBTYPE_BASE, "reverseAttr")), +}; +const shadowSubDistinctProvider: MetaDataTypeProvider = { + id: "shadow-sub-distinct", + dependencies: ["shadow-base"], + registerTypes: (registry) => registry.register(templateType(SHADOW_SUBTYPE, "distinctAttr")), +}; +const shadowSelfProvider: MetaDataTypeProvider = { + id: "shadow-self", + registerTypes(registry) { + registry.register(templateType(SUBTYPE_BASE, "selfAttr")); + registry.register(templateType(SHADOW_SUBTYPE, "selfAttr")); + }, +}; + +const shadowSubExtendClashProvider: MetaDataTypeProvider = { + id: "shadow-sub-extend-clash", + dependencies: ["shadow-sub-distinct"], + registerTypes: (registry) => + registry.extend(TYPE_TEMPLATE, SHADOW_SUBTYPE, { + attributes: [ + { name: "shadowAttr", valueType: ATTR_SUBTYPE_STRING, required: false, description: "Ownership probe attr." }, + ], + }), +}; + +function commonAttr(name: string): AttrSchema { + return { name, valueType: ATTR_SUBTYPE_STRING, required: false, description: "Ownership probe common attr." }; +} + +const commonOwnerProvider: MetaDataTypeProvider = { + id: "common-owner", + registerTypes: (registry) => registry.registerCommonAttrs([commonAttr("commonAttr")]), +}; +const commonClashProvider: MetaDataTypeProvider = { + id: "common-clash", + dependencies: ["common-owner"], + registerTypes: (registry) => registry.registerCommonAttrs([commonAttr("commonAttr")]), +}; +const commonSelfProvider: MetaDataTypeProvider = { + id: "common-self", + registerTypes(registry) { + registry.registerCommonAttrs([commonAttr("selfCommonAttr")]); + registry.register(templateType(SHADOW_SUBTYPE, "selfCommonAttr")); + registry.registerCommonAttrs([commonAttr("selfCommonAttr")]); + }, +}; +const commonSubClashProvider: MetaDataTypeProvider = { + id: "common-sub-clash", + dependencies: ["common-owner"], + registerTypes: (registry) => registry.register(templateType(SHADOW_SUBTYPE, "commonAttr")), +}; +const commonSubOwnerProvider: MetaDataTypeProvider = { + id: "common-sub-owner", + registerTypes: (registry) => registry.register(templateType(SHADOW_SUBTYPE, "lateCommonAttr")), +}; +const commonLateProvider: MetaDataTypeProvider = { + id: "common-late", + dependencies: ["common-sub-owner"], + registerTypes: (registry) => registry.registerCommonAttrs([commonAttr("lateCommonAttr")]), +}; + const PROVIDERS: Readonly> = { + "shadow-sub-extend-clash": shadowSubExtendClashProvider, + "common-owner": commonOwnerProvider, + "common-clash": commonClashProvider, + "common-self": commonSelfProvider, + "common-sub-clash": commonSubClashProvider, + "common-sub-owner": commonSubOwnerProvider, + "common-late": commonLateProvider, + "shadow-base": shadowBaseProvider, + "shadow-sub-clash": shadowSubClashProvider, + "shadow-sub-owner": shadowSubOwnerProvider, + "shadow-base-late": shadowBaseLateProvider, + "shadow-sub-distinct": shadowSubDistinctProvider, + "shadow-self": shadowSelfProvider, "duplicate-x": duplicateXProvider, "duplicate-x-clone": duplicateXCloneProvider, "depends-on-missing": dependsOnMissingProvider, @@ -176,6 +283,9 @@ interface Manifest { expectAttrs?: ExpectAttrs; metadata?: unknown; expectErrors?: string[]; + // ADR-0062 attr-ownership shape — see README.md "The `attr-ownership/` subdir". + expectOwners?: { type: string; subType: string; attr: string; owner: string }[]; + expectCommonOwners?: { attr: string; owner: string }[]; } /** Pull the stable ERR_ code off a caught error, if it carries one. */ @@ -280,3 +390,31 @@ for (const file of composeLoadManifestFiles) { } }); } + +// --------------------------------------------------------------------------- +// ADR-0062 attr-ownership corpus — composition succeeds and the registry names +// the provider that owns each attribute. +// --------------------------------------------------------------------------- + +const OWNERSHIP_CORPUS = join(CORPUS, "attr-ownership"); +const ownershipFiles = readdirSync(OWNERSHIP_CORPUS) + .filter((f) => f.endsWith(".json")) + .sort(); + +test("provider-composition attr-ownership corpus is non-empty (guards against a mis-pathed OWNERSHIP_CORPUS)", () => { + expect(ownershipFiles.length).toBeGreaterThan(0); +}); + +for (const file of ownershipFiles) { + test(`provider-composition (attr-ownership): ${file}`, async () => { + const manifest: Manifest = await Bun.file(join(OWNERSHIP_CORPUS, file)).json(); + const registry = composeRegistry(manifest.providers.map(resolve)); + expect((manifest.expectOwners?.length ?? 0) + (manifest.expectCommonOwners?.length ?? 0)).toBeGreaterThan(0); + for (const { type, subType, attr, owner } of manifest.expectOwners ?? []) { + expect(registry.attrOwner(type, subType, attr)).toBe(owner); + } + for (const { attr, owner } of manifest.expectCommonOwners ?? []) { + expect(registry.commonAttrOwner(attr)).toBe(owner); + } + }); +} diff --git a/server/typescript/packages/metadata/test/registry-attr-ownership.test.ts b/server/typescript/packages/metadata/test/registry-attr-ownership.test.ts new file mode 100644 index 0000000000..80af17ebf3 --- /dev/null +++ b/server/typescript/packages/metadata/test/registry-attr-ownership.test.ts @@ -0,0 +1,125 @@ +// ADR-0062 — the registry records which provider registered each attribute and refuses a +// second provider's claim on the same name. The cross-port scenarios live in +// fixtures/provider-composition-conformance/; this file pins the TS-specific details the +// shared corpus cannot (error text, no-trace-on-refusal, unowned registrations). + +import { describe, expect, test } from "bun:test"; +import { composeRegistry, type MetaDataTypeProvider } from "../src/provider.js"; +import { TypeId, TypeRegistry, type TypeDefinition } from "../src/registry.js"; +import { MetaTemplate } from "../src/template/meta-template.js"; +import { TYPE_TEMPLATE, SUBTYPE_BASE } from "../src/shared/base-types.js"; +import { ATTR_SUBTYPE_STRING } from "../src/core/attr/attr-constants.js"; +import { coreProviders } from "../src/core-types.js"; +import { MetaModelError } from "../src/errors.js"; + +function def(subType: string, ...attrNames: string[]): TypeDefinition { + return { + typeId: new TypeId(TYPE_TEMPLATE, subType), + description: "test", + factory: (typeId, name) => new MetaTemplate(typeId, name), + childRules: [], + attributes: attrNames.map((name) => ({ + name, + valueType: ATTR_SUBTYPE_STRING, + required: false, + description: name, + })), + }; +} + +function provider( + id: string, + registerTypes: MetaDataTypeProvider["registerTypes"], + dependencies: string[] = [], +): MetaDataTypeProvider { + return { id, dependencies, registerTypes }; +} + +function codeOf(fn: () => unknown): { code: string; message: string } { + try { + fn(); + } catch (err) { + const e = err as MetaModelError; + return { code: e.code ?? "", message: e.message }; + } + throw new Error("expected the call to throw"); +} + +describe("attribute ownership (ADR-0062)", () => { + test("a shadowing registration names both providers and the attribute", () => { + const { code, message } = codeOf(() => + composeRegistry([ + provider("owner-a", (r) => r.register(def(SUBTYPE_BASE, "physicalName"))), + provider("owner-b", (r) => r.register(def("probe", "physicalName")), ["owner-a"]), + ]), + ); + expect(code).toBe("ERR_PROVIDER_ATTR_SHADOW"); + expect(message).toContain("owner-a"); + expect(message).toContain("owner-b"); + expect(message).toContain("physicalName"); + }); + + test("a same-slot extend by another provider keeps ERR_PROVIDER_ATTR_CONFLICT and names the owner", () => { + const { code, message } = codeOf(() => + composeRegistry([ + provider("owner-a", (r) => r.register(def("probe", "physicalName"))), + provider("owner-b", (r) => r.extend(TYPE_TEMPLATE, "probe", { attributes: def("probe", "physicalName").attributes }), ["owner-a"]), + ]), + ); + expect(code).toBe("ERR_PROVIDER_ATTR_CONFLICT"); + expect(message).toContain("owner-a"); + expect(message).toContain("owner-b"); + }); + + test("an extend onto the shared root collides with a subtype's name", () => { + const { code } = codeOf(() => + composeRegistry([ + provider("owner-a", (r) => { + r.register(def(SUBTYPE_BASE, "other")); + r.register(def("probe", "physicalName")); + }), + provider("owner-b", (r) => r.extend(TYPE_TEMPLATE, SUBTYPE_BASE, { attributes: def("x", "physicalName").attributes }), ["owner-a"]), + ]), + ); + expect(code).toBe("ERR_PROVIDER_ATTR_SHADOW"); + }); + + test("sibling subtypes may use one name: they are different slots", () => { + const registry = composeRegistry([ + provider("owner-a", (r) => r.register(def("probe-a", "physicalName"))), + provider("owner-b", (r) => r.register(def("probe-b", "physicalName")), ["owner-a"]), + ]); + expect(registry.attrOwner(TYPE_TEMPLATE, "probe-a", "physicalName")).toBe("owner-a"); + expect(registry.attrOwner(TYPE_TEMPLATE, "probe-b", "physicalName")).toBe("owner-b"); + }); + + test("a refused registration leaves no trace in the registry", () => { + const registry = new TypeRegistry(); + registry.runAsProvider("owner-a", () => registry.register(def(SUBTYPE_BASE, "physicalName"))); + expect(() => registry.runAsProvider("owner-b", () => registry.register(def("probe", "physicalName")))).toThrow(); + expect(registry.has(TYPE_TEMPLATE, "probe")).toBe(false); + expect(registry.allSubTypesOf(TYPE_TEMPLATE)).toEqual([SUBTYPE_BASE]); + expect(registry.attrOwner(TYPE_TEMPLATE, "probe", "physicalName")).toBeUndefined(); + }); + + test("a registration outside any provider's turn claims nothing and collides with nothing", () => { + const registry = new TypeRegistry(); + registry.register(def(SUBTYPE_BASE, "physicalName")); + registry.runAsProvider("owner-b", () => registry.register(def("probe", "physicalName"))); + expect(registry.attrOwner(TYPE_TEMPLATE, SUBTYPE_BASE, "physicalName")).toBeUndefined(); + expect(registry.attrOwner(TYPE_TEMPLATE, "probe", "physicalName")).toBe("owner-b"); + }); + + test("the shipped core providers compose with no collision and name an owner for every attribute", () => { + const registry = composeRegistry([...coreProviders], { validate: true }); + const unowned: string[] = []; + for (const id of registry.allTypes()) { + for (const attr of registry.attrsOf(id.type, id.subType)) { + if (registry.attrOwner(id.type, id.subType, attr.name) === undefined) { + unowned.push(`${id.toString()}.${attr.name}`); + } + } + } + expect(unowned).toEqual([]); + }); +}); diff --git a/spec/decisions/ADR-0062-provider-attribute-ownership.md b/spec/decisions/ADR-0062-provider-attribute-ownership.md new file mode 100644 index 0000000000..7df201d68d --- /dev/null +++ b/spec/decisions/ADR-0062-provider-attribute-ownership.md @@ -0,0 +1,97 @@ +# ADR-0062: Two providers may not claim one attribute name on a node type + +## Status + +**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. + +## Context + +ADR-0007 gave each storage paradigm its own physical-name word on the node it describes +(`@column` for a relational field, `@field` for a document field) and rejected a shared +`@locator`-style attribute, because one word cannot hold a multi-sourced field's address in two +stores at once. ADR-0018 did the same per kind (`@table`, `@view`). That scheme works only while +no two providers choose the same word. A provider is free to register or extend a type, and +the registry used to stop only the narrowest case: a second `extend` of the same +`(type, subType)` redeclaring an attribute (`ERR_PROVIDER_ATTR_CONFLICT`). It did not stop a provider +that put `@column` on `field.base` while another already had `@column` on `field.string`, or +the reverse. Both registered, the loader saw one name with two meanings, and which won depended +on registration order. Issue #527 asked where a per-provider physical name goes and what stops +a collision. + +## Decision + +1. **A per-paradigm idiomatic word, unique across providers on a node type.** Each provider + names its physical address in the word its own store uses. Two providers do not share a word + on a node type. The registry enforces it at registration, not in review. + +2. **The rule.** A provider that registers or extends `(T, S)` with attribute `A` is refused when + a different provider already registered `A` on a *related slot* of the same node type `T`: + - the same slot `(T, S)` — `ERR_PROVIDER_ATTR_CONFLICT` (unchanged code; its message now also + names the owning provider); + - an inherited slot, the shared root `(T, base)` — `ERR_PROVIDER_ATTR_SHADOW`; + - when `S` is the shared root, any registered subtype `(T, S')` — `ERR_PROVIDER_ATTR_SHADOW`. + + The check runs in both directions, so the verdict does not depend on which provider registers + first, and whether the second provider registers the slot or `extend`s it. A name a subtype + only inherits from the shared root is the root's, so declaring it on the subtype is a shadow, + not a same-slot repeat. A refusal names both providers and the attribute, and leaves nothing + behind in the registry. + + A common attribute is accepted on every node type, so it is on every slot at once. A provider + that registers common attribute `A` is refused with `ERR_PROVIDER_ATTR_CONFLICT` when a + different provider already registered `A` as a common attribute or on any `(T, S)`; and a + provider that registers or extends any `(T, S)` with `A` is refused with the same code when a + different provider already registered common attribute `A`. Both orders reach the same verdict. + +3. **What stays legal.** The same provider declaring a name on several related slots (its own + `@x` on the root and on a subtype) and re-registering its own slot. Sibling subtypes using + one name, because they are different slots and never co-resolve. Registration outside any + provider's turn (a direct `registry.register` call in a test or script) claims nothing. + +4. **Scope is one node type.** The JVM registry also chains every `.base` to + `metadata.base`, which the core-types provider owns. No other port has that edge, and several + shipped providers re-declare `@isAbstract` on their own root with the same meaning. The rule stops at the node-type boundary so all five ports reach the same + verdict, and the only shipped-provider change is the Java `@description` copy removed under Consequences. + +5. **Owner tracking.** The registry records the registering provider per `(type, subType, + attribute)`, and per common attribute. The error uses it, and `meta types` shows it + (`[]` beside each attribute with `--detail`, and a `provider` field in JSON). The + owner is not written into the expected-registry manifest, which is byte-matched across ports. + +6. **A store with no provider uses a property bag.** Vocabulary an adopter has no provider for + goes in the registered `attr.properties` bag (ADR-0023), not in an invented attribute. + +7. **No wire-name attribute is added here.** If one is added later, it follows this rule with + its own idiomatic word, and does not take a name another provider already holds. + +## Consequences + +- The shipped core providers compose with no collision in any port (audited before the check was + turned on), so existing adopters see no change. +- A third-party provider that reuses a core or sibling provider's attribute name now fails at + composition with a message that names both providers. The fix is a different idiomatic word. +- The Java port's core providers (`core-types`, `object-types`, `identity-types`, + `relationship-types` and `index-types`) used to declare a per-type `@description` beside the + documentation provider's common `@description`, each an optional single string with the same + meaning. They no longer do: the documentation provider is that name's one owner, as it already + is in the other ports, and `@description` is still accepted on every node through the common + attribute. The registry manifest's `description` carve-out for the per-type copies is gone with + them. +- The two codes split by where the clash is, not by severity: `ERR_PROVIDER_ATTR_CONFLICT` keeps + its established same-slot meaning and fixture, and `ERR_PROVIDER_ATTR_SHADOW` is the new + inherited/descendant case. +- Conformance: `fixtures/provider-composition-conformance/` carries the refusals + (`attr-shadow-inherited`, `attr-shadow-descendant`, `attr-shadow-extend`, + `common-attr-conflict`, `common-attr-per-type-after`, `common-attr-per-type-before`) and an `attr-ownership/` sub-corpus where composition succeeds and each + port reports the same owner per attribute and per common attribute. + +## Alternatives considered + +- **A generic physical-address attribute** — rejected in ADR-0007 for the same reasons. +- **Prefix every provider attribute with the provider id** — rejected in ADR-0018: it makes the + authoring surface ugly to fix a problem a registry check solves. +- **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. diff --git a/spec/decisions/README.md b/spec/decisions/README.md index 02ad241caf..6e0de22349 100644 --- a/spec/decisions/README.md +++ b/spec/decisions/README.md @@ -58,6 +58,7 @@ Write one when a decision is **cross-cutting** (affects more than one language p - [ADR-0059 — References resolve once, after the tree](ADR-0059-references-resolve-once-after-the-tree.md) — *Accepted* (sources keep references as written; one resolver per port binds them before freeze and the serializer writes them canonical; supersedes ADR-0032 §3–§4, amends ADR-0042) - [ADR-0060 — Java and Kotlin codegen decide overwrites from the committed hash manifest](ADR-0060-jvm-codegen-hash-manifest.md) — *Accepted* (the JVM plugin records each file it writes in `.metaobjects/.gen-state/.hashes.json`, refuses an edited one, and deletes an untouched orphan, owned per generator and output directory) - [ADR-0061 — A template body may use a per-port engine, chosen by its file](ADR-0061-per-port-template-engines.md) — *Accepted* (Python and TypeScript render and check Jinja bodies — `.jinja` / `.j2` / `.jinja2` — against the same payload check; the metadata never names an engine; Java, Kotlin and C# refuse Jinja with `ERR_TEMPLATE_ENGINE_UNSUPPORTED`) +- [ADR-0062 — Two providers may not claim one attribute name on a node type](ADR-0062-provider-attribute-ownership.md) — *Accepted* (the registry records which provider registered each attribute and refuses a second provider's claim on the same name on the same slot, the shared root or a descendant subtype: `ERR_PROVIDER_ATTR_CONFLICT` for the same slot, new `ERR_PROVIDER_ATTR_SHADOW` for the related slots; each provider keeps its own idiomatic physical-name word, a store without a provider uses `attr.properties`, no wire-name attribute is added) > **Index gap — ADR-0031 through ADR-0051 are on disk but not listed above.** The index stopped > being maintained after ADR-0030; the files are authoritative, this list is not. Read From dea62717b62afb32e517e56c1a28bbf11bd1c0dc Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 4 Nov 2026 17:01:27 -0500 Subject: [PATCH 09/51] feat(docs-site): add model explorer as default docs site (#534) * feat(docs-site): the model explorer site, built by docsSiteFile() docsSiteFile() now builds a model explorer by default: a main page that says what the software does (count tiles, feature and quality cards with roll-ups), a model map with slices and colour-by, a page per object, projection, report, prompt and requirement with a one-hop mini-map, the traceability matrix, a trace from a requirement to its generated files, the API index and a gaps page. Every page is drawn from explorer.json, which the generator builds in the same run from the loaded model, the requirement gate's ledger, the files the run wrote and the routes it mounts (it runs after the other generators wherever it is listed). Declared status is a filled chip with its glyph, gate verdicts are outlines, roll-ups are bars, and no colour reports a test result. Pages carry Pagefind markup, work at phone width, depend on the model alone so verify --codegen holds them, and are link-checked. meta eject docs-site copies the explorer theme beside the classic one. site: "classic" keeps the earlier site. * fix(docs-site): explorer review fixes: narrowed runs, unrecorded routes, page-path collisions, textRef guard - ctx.runOutput widens a run narrowed to some entities with the manifest, and drops records for generators no longer declared or files no longer on disk. - No routes in the run leaves explorer.json's api section out, so the site says the run recorded none instead of claiming none are mounted. - A requirement ledger that throws warns and leaves the ledger out. - An object named index gets index.node.html; the empty package's pages live under -root; writing one page twice throws. - readPromptTexts refuses an absolute or .. @textRef. - Named constants for the disposition and dataGrid attributes. * refactor(docs-site): share the scratch build and owned-theme lookup between the two sites simplify pass: one buildInScratch()/ownedSiteDirs() for the classic and explorer paths, one requirementLedger closure in verify, body templates read once per build, and the explorer's edge sort keys each edge once. Output is byte-identical. * docs(explorer-site): name the page path for an object called index and for no package * no-mistakes(review): Fix explorer anchors, out-of-tree runOutput, structured unclaimed node * no-mistakes(test): Allow structured node key on unclaimed-object ledger rows * no-mistakes(document): Docs checked against the P1 explorer change. One stale fact fixed in docs/features/explorer-data.md: the builder now takes an optional fourth input (routes), so "three inputs" no longer holds. Every other doc touched by the change (CHANGELOG, cli.md, own-your-codegen.md, requirements.md, explorer-site.md, docs-site README, the typescript-docs skill reference, docs/README.md) already matches the code. Spot-checked the classic-theme warning, the Pagefind filter markup, the `/` shortcut, the URL params, and the `node` field in requirement-payload.ts. * docs(explorer-site): say why Pagefind results resolve under a sub-path Pagefind 1.x derives its base URL from where pagefind.js loads; the explorer loads it from the site root, so result links carry the serving path. Checked by serving an indexed site from a sub-path: results link under it and load. * no-mistakes(review): Scope explorer gate findings per node, split lint, match undecided count * test(cli): type explorer fixture ledger diagnostics with message The typecheck gate failed: the local LedgerRow diagnostics type lacked message, which the verdict assertion expects. Test-only fix. * no-mistakes(document): Docs current; explorer-site.md updated for verdict, advisory and out-of-tree rules. --- CHANGELOG.md | 27 + .../references/typescript-docs.md | 2 +- docs/README.md | 2 + docs/features/cli.md | 2 +- docs/features/explorer-data.md | 39 +- docs/features/explorer-site.md | 181 ++++ docs/features/own-your-codegen.md | 19 +- docs/features/requirements.md | 2 +- .../references/typescript-docs.md | 2 +- .../references/typescript-docs.md | 2 +- .../explorer-conformance/shop/expected.json | 50 +- .../explorer-conformance/shop/verify.json | 5 +- .../packages/cli/src/commands/gen.ts | 3 + .../packages/cli/src/commands/verify.ts | 46 +- .../packages/cli/src/lib/advisory.ts | 2 +- .../packages/cli/src/lib/codegen-drift.ts | 15 +- .../packages/cli/src/lib/requirement-check.ts | 7 +- .../cli/src/lib/requirement-ledger.ts | 3 +- .../cli/src/lib/requirement-payload.ts | 107 ++ .../cli/test/explorer-fixture.test.ts | 9 +- .../cli/test/explorer-site-ledger.test.ts | 144 +++ .../cli/test/gen-docs-generators.test.ts | 27 +- .../packages/cli/test/gen-docs-site.test.ts | 26 +- .../cli/test/unit/reporting-inert.test.ts | 4 +- .../cli/test/unit/requirement-ledger.test.ts | 11 +- .../packages/codegen-ts/src/generator.ts | 30 + .../src/generators/docs-site-file.ts | 200 +++- .../packages/codegen-ts/src/index.ts | 2 +- .../codegen-ts/src/overwrite-policy.ts | 20 + .../packages/codegen-ts/src/runner.ts | 80 +- .../test/docs-site-explorer.test.ts | 105 ++ .../codegen-ts/test/run-output.test.ts | 111 ++ .../typescript/packages/docs-site/README.md | 41 +- .../packages/docs-site/assets/explorer.css | 232 +++++ .../packages/docs-site/assets/explorer.js | 315 ++++++ .../packages/docs-site/package.json | 2 +- .../packages/docs-site/src/explorer/build.ts | 24 +- .../packages/docs-site/src/explorer/html.ts | 85 ++ .../docs-site/src/explorer/index-model.ts | 343 ++++++ .../packages/docs-site/src/explorer/pages.ts | 977 ++++++++++++++++++ .../packages/docs-site/src/explorer/site.ts | 294 ++++++ .../packages/docs-site/src/explorer/types.ts | 16 +- .../packages/docs-site/src/index.ts | 5 +- .../packages/docs-site/src/link-check.ts | 4 +- .../packages/docs-site/src/scaffold.ts | 37 +- .../templates/explorer-api.html.mustache | 5 + .../templates/explorer-card.mustache | 7 + .../templates/explorer-foot.mustache | 7 + .../templates/explorer-gaps.html.mustache | 5 + .../templates/explorer-head.mustache | 19 + .../templates/explorer-map.html.mustache | 13 + .../templates/explorer-matrix.html.mustache | 5 + .../templates/explorer-model.html.mustache | 5 + .../templates/explorer-object.html.mustache | 56 + .../templates/explorer-overview.html.mustache | 25 + .../templates/explorer-package.html.mustache | 5 + .../templates/explorer-prompt.html.mustache | 27 + .../templates/explorer-prompts.html.mustache | 6 + .../explorer-requirement.html.mustache | 20 + .../explorer-requirements.html.mustache | 6 + .../templates/explorer-trace.html.mustache | 6 + .../docs-site/test/explorer-build.test.ts | 20 + .../docs-site/test/explorer-site.test.ts | 247 +++++ .../packages/docs-site/test/scaffold.test.ts | 28 +- 64 files changed, 4008 insertions(+), 164 deletions(-) create mode 100644 docs/features/explorer-site.md create mode 100644 server/typescript/packages/cli/src/lib/requirement-payload.ts create mode 100644 server/typescript/packages/cli/test/explorer-site-ledger.test.ts create mode 100644 server/typescript/packages/codegen-ts/test/docs-site-explorer.test.ts create mode 100644 server/typescript/packages/codegen-ts/test/run-output.test.ts create mode 100644 server/typescript/packages/docs-site/assets/explorer.css create mode 100644 server/typescript/packages/docs-site/assets/explorer.js create mode 100644 server/typescript/packages/docs-site/src/explorer/html.ts create mode 100644 server/typescript/packages/docs-site/src/explorer/index-model.ts create mode 100644 server/typescript/packages/docs-site/src/explorer/pages.ts create mode 100644 server/typescript/packages/docs-site/src/explorer/site.ts create mode 100644 server/typescript/packages/docs-site/templates/explorer-api.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-card.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-foot.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-gaps.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-head.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-map.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-matrix.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-model.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-object.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-overview.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-package.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-prompt.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-prompts.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-requirement.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-requirements.html.mustache create mode 100644 server/typescript/packages/docs-site/templates/explorer-trace.html.mustache create mode 100644 server/typescript/packages/docs-site/test/explorer-site.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d1633e25f..5cfebfbee3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,25 @@ here.** ### Added +- **A model explorer site, built by `docsSiteFile()`.** The docs site now shows what the + software does and how the model is designed: a main page with count tiles and the feature and + quality cards with their roll-ups, a model map with slices (package, requirement subtree, + prompt) and colour-by (kind, API, claims, capability, status), a page per object, projection, + report, prompt and requirement with a one-hop mini-map, the traceability matrix, a trace from a + requirement to the files generated from it, the API index and a gaps page. Every page is drawn + from `explorer.json`, which the generator builds in the same run from the loaded model, the + requirement gate's ledger, the files the run wrote and the routes it mounts; it runs after the + other generators wherever it is listed. Declared status is a filled chip with its glyph, gate + verdicts are outlines, roll-ups are bars, and no colour reports a test result. Pages are marked + for Pagefind, work at phone width, depend on the model alone (so `meta verify --codegen` holds + them) and are link-checked. The graphs load Cytoscape.js from `assetBase`. `meta eject + docs-site` now copies the explorer's `explorer-*.mustache` templates and `explorer.css` / + `explorer.js` beside the classic theme. `buildExplorer` takes an optional `routes` input, and + nodes carry their declaration `order`. Each `requirements.rows` entry in `meta verify + --format json` now carries `node`: the entity's resolution key on a + `WARN_REQUIREMENT_OBJECT_UNCLAIMED` row, `""` on every other row, and each finding in a + `requirementLedger` row carries its `message`. See `docs/features/explorer-site.md`. + - **Generated record models enforce the four cross-field validators in every port.** `validator.comparison`, `validator.requiredWhen`, `validator.presentIff` and `validator.atLeastOne` used to render only as DB `CHECK` constraints, so a store with no `CHECK` @@ -183,6 +202,14 @@ here.** ### Changed +- **`docsSiteFile()` builds the model explorer by default.** A project that lists + `docsSiteFile()` gets a different site under `site/` on its next `meta gen`, with new page + paths (object pages move under `model/`); `meta gen` removes the old pages it wrote, as it + does any untouched generated file it no longer emits, and `meta verify --codegen` reports + drift until it has run. Pass `docsSiteFile({ site: "classic" })` to keep the earlier + site byte for byte. A project that ejected the classic theme gets a warning and the packaged + explorer theme; run `meta eject docs-site` again to copy the explorer's files. + - **Python and Java report a missing provider's errors in the same order as the other ports.** When a file holds both an unknown subtype and unknown attributes, Python used to drop the whole file at the unknown subtype and never report the attributes; it now reports diff --git a/agent-context/skills/metaobjects-codegen/references/typescript-docs.md b/agent-context/skills/metaobjects-codegen/references/typescript-docs.md index 477959e311..ff88a88e8a 100644 --- a/agent-context/skills/metaobjects-codegen/references/typescript-docs.md +++ b/agent-context/skills/metaobjects-codegen/references/typescript-docs.md @@ -23,7 +23,7 @@ generate, docs included). Each factory is an ordinary entry in `generators`, fro | `requirementsFile()` | `requirements` | the declared `requirement.*` ledger, each entry headed by its dotted path and `title`. Writes nothing for a model with no `requirement.*` node. | | `agentDocsFile()` | `agent-docs` | `agent/schema.md`, `agent/ui.md` (only when the run also lists a client-tier generator, OR the config sets `includeUiTier: true` — the escape hatch for a docs-only config whose UI is generated by a separate config; skipping it with a UI surface in the model and `includeUiTier` unset prints an advisory naming `includeUiTier`; `includeUiTier: false` says there is no UI anywhere and skips it without one) and `agent/requirements.md` — the three `agent/` pages the always-on pointer reads before touching a tier. | | `metamodelDocsFile()` | `metamodel-docs` | the built-in vocabulary reference, under `metamodel/` (was `meta docs --metamodel`). | -| `docsSiteFile()` | `docs-site` | an HTML site under `site/` (was `meta docs --site`). Option: `prompts`. `meta eject docs-site` copies its templates and assets to `codegen/docs-site/` (was `meta docs --scaffold-site`). | +| `docsSiteFile()` | `docs-site` | an HTML site under `site/` (was `meta docs --site`): the model explorer by default (what the software does, the model map, requirement pages, matrix, trace, API, gaps), drawn from an `explorer.json` built in the same run; `site: "classic"` writes the earlier site. Options: `site`, `prompts`. `meta eject docs-site` copies its templates and assets to `codegen/docs-site/` (was `meta docs --scaffold-site`). | ```ts import { defineConfig } from "@metaobjectsdev/cli"; diff --git a/docs/README.md b/docs/README.md index b710209043..542ee95aaa 100644 --- a/docs/README.md +++ b/docs/README.md @@ -48,6 +48,7 @@ docs/ │ ├── contract-emitters.md # the contract-schema and openapi generators: JSON Schema and OpenAPI for the REST contract (FR-022) │ ├── cube-export.md # the cube-model generator: reporting vocabulary as Cube data-model files (FR-044) │ ├── explorer-data.md # explorer.json and its inputs: export --effective, the verify ledger rows, manifest provenance +│ ├── explorer-site.md # the model explorer site docsSiteFile() builds from explorer.json │ └── own-your-codegen.md # scaffold-and-own generator ownership (ADR-0034) └── ports/ # one file per language/framework port ├── typescript.md @@ -80,6 +81,7 @@ this tree is documentation, not the source of truth. | Publish the API as JSON Schema or OpenAPI, and check a change against the last release | [`features/contract-emitters.md`](features/contract-emitters.md), [`recipes/check-api-against-last-release.md`](recipes/check-api-against-last-release.md) | | Export the reporting vocabulary to Cube (`cube-model`: cubes, joins, rollups; the `cube` lane that checks it against a real Cube) | [`features/cube-export.md`](features/cube-export.md) | | Build the data a model explorer reads (`explorer.json` from `meta export --effective`, `meta verify --format json` and the generated-file manifest) | [`features/explorer-data.md`](features/explorer-data.md) | +| Build the model explorer site: what the software does, the model map, requirement pages, the matrix, trace and gaps (`docsSiteFile()`) | [`features/explorer-site.md`](features/explorer-site.md) | | Wire prompt construction (FR-004) | [`features/templates-and-payloads.md`](features/templates-and-payloads.md) | | Share a metadata shape across multiple instances (abstracts, `extends:`) | [`features/abstracts-and-inheritance.md`](features/abstracts-and-inheritance.md) | | Add a custom metamodel subtype or attribute to a downstream project | [`features/extending-with-providers.md`](features/extending-with-providers.md) + [`recipes/extending-metaobjects-with-providers.md`](recipes/extending-metaobjects-with-providers.md) | diff --git a/docs/features/cli.md b/docs/features/cli.md index 0e6d1de713..f69c343808 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -324,7 +324,7 @@ documentation never lands in the code's output directory by default. | `requirements` | `requirementsFile()` | The declared ledger, as `requirements.md` + `requirements.toon`; nothing for a model with no `requirement.*` node. | | `agent-docs` | `agentDocsFile()` | Three pages an agent reads BEFORE touching a tier (below), under `agent/`. | | `metamodel-docs` | `metamodelDocsFile()` | The reference of the BUILT-IN metamodel (every registered type, subtype and attribute), not your model, under `metamodel/`. Its rendered form is published at . | -| `docs-site` | `docsSiteFile()` | The HTML site under `site/`; `meta eject docs-site` copies its templates and assets to `codegen/docs-site/` for you to change. | +| `docs-site` | `docsSiteFile()` | The HTML site under `site/`: the model explorer by default ([explorer-site.md](explorer-site.md)), the earlier site with `site: "classic"`; `meta eject docs-site` copies its templates and assets to `codegen/docs-site/` for you to change. | ```ts targets: { docs: { outDir: "./docs/generated" } }, diff --git a/docs/features/explorer-data.md b/docs/features/explorer-data.md index fd55f77fa0..5502ac514d 100644 --- a/docs/features/explorer-data.md +++ b/docs/features/explorer-data.md @@ -1,17 +1,19 @@ -# Explorer data: `explorer.json` and the three inputs it reads +# Explorer data: `explorer.json` and the inputs it reads A model explorer shows one project so a reader can see what it does and how it was designed: the objects and how they connect, the prompts and what they send and get back, the requirement tree and whether each claim holds, and which generated files each node produced. All of that -is read from one data file, `explorer.json`. This page documents that file and the three -inputs it is built from. +is read from one data file, `explorer.json`. This page documents that file and the inputs it is +built from. -This is the data layer only. No screen reads it yet. +This page is the data layer. The site that reads it, built by `docsSiteFile()`, is +[explorer-site.md](explorer-site.md); that generator builds the file during `meta gen`, so +you only build it by hand to feed a tool of your own. ## The inputs are port-neutral The builder (`buildExplorer` in `@metaobjectsdev/docs-site`) never loads metadata itself. It -reads three documents: +reads three documents, and a fourth optional input, the REST routes (see [`api`](#api)): | Input | Produced by | What it contributes | | --- | --- | --- | @@ -74,12 +76,17 @@ does not have to infer "checked and clean" from a path that no diagnostic mentio | `digest` | The same SHA-256 over the claim that each generated requirement test carries ([requirements.md](requirements.md)). | | `implementedBy` | Each link as written (`ref`), whether it resolves, and the node it resolves to (`target`): the object's resolution key, followed by `.` for a member. The gate's own resolver produces these values. | | `supersededBy` | The same, for `@supersededBy`; its `target` is the replacement's `qualifiedPath`. | -| `diagnostics` | Every finding reported against this requirement, as `{ code, severity, source }`. `source` is `gate` when the finding can fail the build and `lint` when it cannot. | +| `diagnostics` | Every finding reported against this requirement, as `{ code, severity, source, message }`. `source` is `gate` when the finding can fail the build and `lint` when it cannot. Two packages may declare a requirement at the same `path`, so read a requirement's findings here rather than matching `requirements.rows` by path. | | `verdict` | From gate findings only: `error`, `warn`, or `clean`. | A finding that is not about a single requirement, such as an entity nobody claims, appears -in `requirements.rows` and in no ledger row. The structured payload is TypeScript-only, as -the rest of `--format json` is. +in `requirements.rows` and in no ledger row. Each `requirements.rows` entry is `{ code, path, +node, severity, source, message }`. `path` is the requirement's dotted path, or `""` when the +subject is not a requirement. `node` names that other subject: a +`WARN_REQUIREMENT_OBJECT_UNCLAIMED` row carries the entity's resolution key there (for example +`"node": "acme::shop::AuditEntry"`, the entity's id in `explorer.json`), and every other row +carries `""`. Read the subject from `path` and `node`, never from `message`, whose wording may +change. The structured payload is TypeScript-only, as the rest of `--format json` is. ### Node provenance in `.hashes.json` @@ -117,6 +124,7 @@ interface ExplorerJson { edges: ExplorerEdge[]; ledger?: ExplorerLedger; // absent without a verify payload with requirements generated?: ExplorerGenerated[]; // absent without a manifest + api?: ExplorerRoute[]; // absent without a routes input slices: ExplorerSlice[]; } ``` @@ -134,6 +142,7 @@ each node nested inside one (field, identity, source, view, index, nested requir | `id` | A top-level node's id is `::`. A nested node's id is its parent's id followed by `.`, for example `acme::shop::Order.total`. A nested requirement's id equals its ledger row's `qualifiedPath`. A nested node with no name gets `#` in place of `.`. When siblings of different types share a name, the first one in the effective JSON keeps `.`, because that is the node a dotted `@implementedBy` reference such as `Order.id` resolves to. Each later one adds its type, for example `acme::shop::AuditEntry.id[identity.primary]`. | | `type`, `subType`, `name`, `package` | As in the model. `package` is the package of the top-level ancestor. | | `parent` | The id of the node it is nested in. A top-level node has no `parent`. | +| `order` | Its position among its siblings in the effective tree, from 0: the declaration order, which the id sort does not keep. | | `extends`, `abstract`, `isArray` | As in the effective JSON. | | `inheritedFrom` | Set on a member that came from a super. It holds the id of the object the member is declared on, meaning the topmost ancestor that has a member with the same type, name and body. A member redeclared with a different body belongs to the node itself. | | `attrs` | Every `@` attribute, without the `@`, with keys sorted. | @@ -171,6 +180,11 @@ finding, including those about something other than a single requirement. The manifest entries that carry `sourceNode`, grouped by node: `{ node, files: [{ path, generatedBy }] }`, sorted by node and then by path. A plain entry has no node and is left out. +### `api` + +One row per REST route: `{ node, method, path }`, with the project's `apiPrefix` in the path, +sorted by node, then path, then method. Absent when no routes were passed. + ### `slices` Slices are named node sets that a view can open on. They are all derived from the model, so @@ -186,7 +200,7 @@ never in metadata, and are not built yet. ### Determinism -The same three inputs always produce the same bytes. Nodes are sorted by id. Edges are sorted +The same inputs always produce the same bytes. Nodes are sorted by id. Edges are sorted by kind, then `from`, then `to`, then `via`, with duplicates removed. Slices are sorted by id, and ledger rows stay in the verify payload's order. `serializeExplorer` writes JSON indented two spaces, with one trailing newline. That makes the file safe to commit and diff. @@ -205,14 +219,17 @@ writeFileSync("explorer.json", serializeExplorer(buildExplorer({ }))); ``` -A `verify` or `manifest` that is missing or malformed leaves its section out. A `model` that is +`routes` (optional) is a list of `{ node, method, path }`, one per REST route, and becomes the +`api` section; `docsSiteFile()` fills it from the routes the run mounts. The manifest records +files, not the routes inside them, so a hand build that wants routes passes them here. + +A `verify`, `manifest` or `routes` that is missing or malformed leaves its section out. A `model` that is not canonical metadata JSON makes the builder throw. ## Not built yet - **`usage`**: which hand-written modules import a generated module. The design marks it optional, and nothing builds it yet. -- **Routes per node** in `generated`: the manifest records files, not the routes inside them. - **Provenance from the JVM, Python and C# generators.** Their manifests have no `sourceNode` yet, so for those ports `generated` is empty. diff --git a/docs/features/explorer-site.md b/docs/features/explorer-site.md new file mode 100644 index 0000000000..c221b86457 --- /dev/null +++ b/docs/features/explorer-site.md @@ -0,0 +1,181 @@ +# The model explorer site + +`docsSiteFile()` builds a static site that shows one project: what the software does, how the +model is put together, and whether each requirement claim holds. Every page is drawn from one +data file, [`explorer.json`](explorer-data.md), which the generator builds during the same +`meta gen` run. A page never works a model fact out for itself. + +The explorer is the default site. The earlier site (package navigation, a page per object, the +Mermaid ER diagrams) is still there as `docsSiteFile({ site: "classic" })`. + +## Building it + +List the generator with a `docs` target in `metaobjects.config.ts`: + +```ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { docsSiteFile } from "@metaobjectsdev/codegen-ts/generators"; +import { entityFile } from "./codegen/generators/entity"; +import { routesFile } from "./codegen/generators/routes"; + +export default defineConfig({ + apiPrefix: "/api", + targets: { docs: { outDir: "./docs/generated" } }, + generators: [entityFile(), routesFile(), docsSiteFile()], +}); +``` + +`meta gen` writes the site to `docs/generated/site/`. The generator runs after every other +generator in the run, wherever it appears in the list, because it reads what they did: + +| `explorer.json` input | Where `meta gen` gets it | +|---|---| +| The effective model | The model this run loaded (the same bytes as `meta export --effective`) | +| The requirement ledger | The requirement gate, run with its defaults (the rows `meta verify --format json` prints) | +| Generated files per node | The files this run wrote, with the node each came from. Files under a target whose `outDir` lies outside the project are left out, under `meta gen` and `verify --codegen` alike | +| Routes per node | The REST routes this run's routes generator mounts; none if the run has no routes generator | + +Open `site/index.html` in a browser, or serve the directory. The pages use relative links, so +the site works from any path and from `file://`. + +### Options + +| Option | Default | What it does | +|---|---|---| +| `site` | `"explorer"` | `"classic"` builds the earlier site instead | +| `subDir` | `"site"` | The directory under the `docs` target | +| `title` | the project directory's name | The name in the header and the page titles | +| `prompts` | none | An extra directory of prompt `.mustache` sources, so the prompt pages can show the text | +| `stamp` | none | Footer text. With none, the pages depend on the model alone | +| `assetBase` | `https://cdn.jsdelivr.net/npm` | Where the graph library loads from (see "Offline use") | +| `target` | `"docs"` | The output target | + +### Search + +Every page has a search box over a built-in index of objects, fields, prompts and +requirements; press `/` to jump to it. For full-text search, run +[Pagefind](https://pagefind.app/) over the output after `meta gen`: + +```bash +npx pagefind --site docs/generated/site +``` + +The page content is marked `data-pagefind-body`, and each page carries a `section` and `kind` +filter. When the site is served over HTTP and `pagefind/pagefind.js` exists, the search box +uses it; otherwise it keeps the built-in index. Pagefind takes its base URL from where +`pagefind/pagefind.js` loads, so result links work when the site is served under a sub-path. +Pagefind's output is not generated by `meta gen`, so leave `pagefind/` out of the drift check +(or out of the repository). + +### Offline use + +The map, the mini-maps and the trace draw with [Cytoscape.js](https://js.cytoscape.org/), +loaded from `${assetBase}/cytoscape@3.30.2/dist/cytoscape.min.js`. Only those three kinds of +page load it. Opened without network access, every page still renders and the graphs show a +notice in their place. To serve the file yourself, put +`cytoscape@3.30.2/dist/cytoscape.min.js` under a path of your own and pass that path: + +```ts +docsSiteFile({ assetBase: "/vendor/npm" }) +``` + +## The screens + +| Screen | Page | What it shows | +|---|---|---| +| What it does | `index.html` | Six count tiles, the features (`requirement.functional`) as cards by level with their roll-up, and the qualities (`requirement.architectural`). A folded summary slot stays empty: this build makes no LLM call | +| Model map | `map.html` | Every top-level node and the edges between them. Open a slice (a package, a requirement subtree, a prompt), colour by kind, API, claims, capability or status, and hide or show value objects and nodes outside the slice. The URL keeps the choice (`?slice=&colour=&focus=`) | +| Object | `model//.html` | Why it exists (the requirements that claim it), its fields, inherited ones marked, relationships, indexes, a one-hop mini-map, its routes and the files generated from it. A projection shows its read model and each field's origin; a report shows where its rows come from, its dimensions and its measures | +| Prompt | `model//.html` | The payload and reply types, the template text with each variable marked, and which payload fields the text never uses | +| Features, qualities | `requirements/features.html`, `requirements/qualities.html` | The requirement tree, one card per entry | +| Requirement | `requirements//.html` | Its status, what it claims, the entries below it with their roll-up, what the gate found, its authoring advisories apart, and links to its slice of the map and its trace | +| Matrix | `matrix.html` | Requirements against stored entities and prompts. An empty column is a node nothing claims | +| Trace | `trace.html?start=` | One requirement down to the model nodes it claims and the files generated from them | +| API | `api.html` | Every route this run mounts, by node | +| Gaps | `gaps.html` | The gate's findings and coverage warnings, the authoring lint's advisories (listed apart, never as a verdict), undecided gaps as the gate counts them (a roll-up parent of outstanding work is left out), and the checks this explorer adds: planned entries with live work below, prompts nothing claims, fields named like a reference with no `identity.reference`, payload fields the text never uses | + +An object named `index` gets `index.node.html`, so it never takes its package's index page, +and a model with no package puts its pages under `model/-root/`. + +Every page works at phone width: the navigation scrolls, the tiles stack in two columns, and +wide tables scroll inside their card. + +## How status is drawn + +The colours keep four things apart, so none can be read as another: + +- **Declared status** is a filled chip with its glyph: ● live, ◐ partial, ○ planned, + ⊘ retired. It is what the author wrote in `@status`. +- **Gate verdicts** are outlines: a red ring or badge for an error or an unclaimed entity, an + amber one for a warning. They come from gate findings only. An authoring-lint advisory cannot + fail a build, so it is never coloured: it appears as a neutral line under "Authoring + advisories" on the requirement and Gaps pages. +- **Roll-ups** are stacked bars of the statuses below an entry. A parent's status is written + by hand and never rolled up, so the bar and the chip can disagree, and the Gaps page lists + where they do. +- **Test results are never coloured.** The site reads no test run, and nothing on it claims + one passed. + +## Own the theme + +```bash +meta eject docs-site +``` + +copies the templates of both sites to `codegen/docs-site/templates/` (the explorer's are the +`explorer-*.mustache` files) and their CSS and JS to `codegen/docs-site/assets/` +(`explorer.css`, `explorer.js`). Only files that are not there yet are written (`--force` +overwrites). `docsSiteFile()` renders with your copies, and a file you did not copy falls back +to the packaged one. A project that ejected the theme before the explorer existed has only the +classic files; `meta gen` warns about it, and running `meta eject docs-site` again adds the +explorer's files without touching the ones you own. + +## Drift and determinism + +The site prints no date and no build time, its graph layouts start from fixed positions, and +the same model writes the same bytes. `meta verify --codegen` therefore holds it to the model +like any other generated output. Every build also checks its own links and fails on a dangling +one. + +## As a library + +```ts +import { generateExplorerSite, readPromptTexts, type ExplorerJson } from "@metaobjectsdev/docs-site"; + +const explorer: ExplorerJson = JSON.parse(readFileSync("explorer.json", "utf8")); +generateExplorerSite({ + explorer, + outDir: "site", + title: "Shop", + texts: readPromptTexts(explorer, ["prompts"]), +}); +``` + +It takes `templatesDir`, `assetsDir`, `assetBase` and `stamp` as well, and throws on a +dangling link. Build `explorer.json` itself with `buildExplorer` +([explorer-data.md](explorer-data.md)). + +## Not built yet + +- A 3D view of the map, an LLM-written summary, a test-result overlay, a live view served by + the running application, and publishing the site. +- "Hand-written code that imports it": the site reads no import graph, so the object pages say + it was not scanned. +- Generated-file provenance from the JVM, Python and C# generators (see + [explorer-data.md](explorer-data.md)), so for those ports the generated-file lists are empty. + +## Verified by + +- `server/typescript/packages/docs-site/test/explorer-site.test.ts`: the shop fixture + (`fixtures/explorer-conformance/shop/`) and the fitness model + (`fixtures/persistence-conformance/canonical/meta.fitness.json`). Every screen is written, + links resolve, two builds match byte for byte, status chips and verdict outlines are + distinct, and projection and report pages show their read model. +- `server/typescript/packages/codegen-ts/test/docs-site-explorer.test.ts`: the generator sees + the files and routes of generators listed after it, and the ledger is asked for once. +- `server/typescript/packages/cli/test/explorer-site-ledger.test.ts`: the requirement views read + the gate's per-node ledger, so two packages sharing a path keep their own findings, an + authoring advisory is never a verdict, and the undecided card matches the gate. +- `server/typescript/packages/cli/test/gen-docs-site.test.ts` and + `gen-docs-generators.test.ts`: `meta gen` writes the site, a second run is identical, + `meta verify --codegen` is clean, and an ejected `explorer.css` wins. diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 0371bd297c..b74b1cbb1e 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -299,10 +299,12 @@ wins over the packaged one. ### The docs site: `meta eject docs-site` copies the theme -`docsSiteFile()` writes the HTML site (package navigation, search, a page per object and -package, the ER diagrams) under `site/` in the `docs` target. It loads the model from your -declared source directories, with your config's providers. To change how it looks, copy the -templates and assets into your repo: +`docsSiteFile()` writes the HTML site under `site/` in the `docs` target. By default that is +the model explorer ([explorer-site.md](explorer-site.md)), drawn from the model this run +loaded; `docsSiteFile({ site: "classic" })` writes the earlier site (package navigation, +search, a page per object and package, the ER diagrams), which loads the model from your +declared source directories with your config's providers. To change how either looks, copy +the templates and assets into your repo: ```bash meta eject docs-site @@ -314,10 +316,11 @@ That writes the Mustache templates to `codegen/docs-site/templates/` and the CSS packaged one. The site prints no date, so its pages depend on the model alone and `meta verify --codegen` can check them; `docsSiteFile({ stamp })` adds footer text. -The page chrome loads daisyUI, Tailwind's browser build, Mermaid and svg-pan-zoom from -jsDelivr, so a site opened offline renders unstyled and its diagrams do not work. -`docsSiteFile({ assetBase: "/vendor/npm" })` replaces that base; serving the five files from -it is on you. The files and how to fetch them are in the `@metaobjectsdev/docs-site` README, +The explorer loads one file from jsDelivr, Cytoscape.js, for its graphs. The classic page +chrome loads daisyUI, Tailwind's browser build, Mermaid and svg-pan-zoom from jsDelivr, so a +classic site opened offline renders unstyled and its diagrams do not work. +`docsSiteFile({ assetBase: "/vendor/npm" })` replaces that base for either site; serving the +files from it is on you. The files and how to fetch them are in the `@metaobjectsdev/docs-site` README, "Offline use". ### The ER diagram comes from `docsFile()` diff --git a/docs/features/requirements.md b/docs/features/requirements.md index c7b7db9d34..8f072f87f4 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -369,7 +369,7 @@ the summary at `info`, warnings as warnings and errors as errors. | `WARN_REQUIREMENT_DISPOSITION_NOT_APPLICABLE` | warn | `@disposition` on a status other than `planned` or `partial`. | | `WARN_REQUIREMENT_NOTHING_IMPLEMENTS` | warn | A `live` or `partial` functional requirement where neither it nor anything nested under it names a node. An error under [the strict switch](#requiring-implementers). | | `WARN_REQUIREMENT_DEFERRED_UNTRACKED` | warn | `@disposition: deferred` with no `@trackedBy`. | -| `WARN_REQUIREMENT_OBJECT_UNCLAIMED` | warn | Coverage is measured and no requirement claims a concrete entity. The line has no requirement path, because its subject is the entity. | +| `WARN_REQUIREMENT_OBJECT_UNCLAIMED` | warn | Coverage is measured and no requirement claims a concrete entity. The line has no requirement path, because its subject is the entity. Its `--format json` row names the entity in `node`. | A diagnostic prints as ` []: `. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript-docs.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript-docs.md index 477959e311..ff88a88e8a 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript-docs.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript-docs.md @@ -23,7 +23,7 @@ generate, docs included). Each factory is an ordinary entry in `generators`, fro | `requirementsFile()` | `requirements` | the declared `requirement.*` ledger, each entry headed by its dotted path and `title`. Writes nothing for a model with no `requirement.*` node. | | `agentDocsFile()` | `agent-docs` | `agent/schema.md`, `agent/ui.md` (only when the run also lists a client-tier generator, OR the config sets `includeUiTier: true` — the escape hatch for a docs-only config whose UI is generated by a separate config; skipping it with a UI surface in the model and `includeUiTier` unset prints an advisory naming `includeUiTier`; `includeUiTier: false` says there is no UI anywhere and skips it without one) and `agent/requirements.md` — the three `agent/` pages the always-on pointer reads before touching a tier. | | `metamodelDocsFile()` | `metamodel-docs` | the built-in vocabulary reference, under `metamodel/` (was `meta docs --metamodel`). | -| `docsSiteFile()` | `docs-site` | an HTML site under `site/` (was `meta docs --site`). Option: `prompts`. `meta eject docs-site` copies its templates and assets to `codegen/docs-site/` (was `meta docs --scaffold-site`). | +| `docsSiteFile()` | `docs-site` | an HTML site under `site/` (was `meta docs --site`): the model explorer by default (what the software does, the model map, requirement pages, matrix, trace, API, gaps), drawn from an `explorer.json` built in the same run; `site: "classic"` writes the earlier site. Options: `site`, `prompts`. `meta eject docs-site` copies its templates and assets to `codegen/docs-site/` (was `meta docs --scaffold-site`). | ```ts import { defineConfig } from "@metaobjectsdev/cli"; diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/typescript-docs.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/typescript-docs.md index 477959e311..ff88a88e8a 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/typescript-docs.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/typescript-docs.md @@ -23,7 +23,7 @@ generate, docs included). Each factory is an ordinary entry in `generators`, fro | `requirementsFile()` | `requirements` | the declared `requirement.*` ledger, each entry headed by its dotted path and `title`. Writes nothing for a model with no `requirement.*` node. | | `agentDocsFile()` | `agent-docs` | `agent/schema.md`, `agent/ui.md` (only when the run also lists a client-tier generator, OR the config sets `includeUiTier: true` — the escape hatch for a docs-only config whose UI is generated by a separate config; skipping it with a UI surface in the model and `includeUiTier` unset prints an advisory naming `includeUiTier`; `includeUiTier: false` says there is no UI anywhere and skips it without one) and `agent/requirements.md` — the three `agent/` pages the always-on pointer reads before touching a tier. | | `metamodelDocsFile()` | `metamodel-docs` | the built-in vocabulary reference, under `metamodel/` (was `meta docs --metamodel`). | -| `docsSiteFile()` | `docs-site` | an HTML site under `site/` (was `meta docs --site`). Option: `prompts`. `meta eject docs-site` copies its templates and assets to `codegen/docs-site/` (was `meta docs --scaffold-site`). | +| `docsSiteFile()` | `docs-site` | an HTML site under `site/` (was `meta docs --site`): the model explorer by default (what the software does, the model map, requirement pages, matrix, trace, API, gaps), drawn from an `explorer.json` built in the same run; `site: "classic"` writes the earlier site. Options: `site`, `prompts`. `meta eject docs-site` copies its templates and assets to `codegen/docs-site/` (was `meta docs --scaffold-site`). | ```ts import { defineConfig } from "@metaobjectsdev/cli"; diff --git a/fixtures/explorer-conformance/shop/expected.json b/fixtures/explorer-conformance/shop/expected.json index d28845d4f2..fc4b44dda3 100644 --- a/fixtures/explorer-conformance/shop/expected.json +++ b/fixtures/explorer-conformance/shop/expected.json @@ -7,6 +7,7 @@ "subType": "value", "name": "Address", "package": "acme::shop", + "order": 1, "attrs": {} }, { @@ -15,6 +16,7 @@ "subType": "string", "name": "city", "package": "acme::shop", + "order": 1, "parent": "acme::shop::Address", "attrs": {} }, @@ -24,6 +26,7 @@ "subType": "string", "name": "street", "package": "acme::shop", + "order": 0, "parent": "acme::shop::Address", "attrs": {} }, @@ -33,6 +36,7 @@ "subType": "architectural", "name": "Addressable", "package": "acme::shop", + "order": 8, "attrs": { "counterexample": "A row nobody can point at.", "implementedBy": [ @@ -48,6 +52,7 @@ "subType": "entity", "name": "AuditEntry", "package": "acme::shop", + "order": 4, "attrs": {} }, { @@ -56,6 +61,7 @@ "subType": "rdb", "name": "db", "package": "acme::shop", + "order": 3, "parent": "acme::shop::AuditEntry", "attrs": { "table": "audit_entries" @@ -67,6 +73,7 @@ "subType": "uuid", "name": "id", "package": "acme::shop", + "order": 0, "parent": "acme::shop::AuditEntry", "attrs": {} }, @@ -76,6 +83,7 @@ "subType": "primary", "name": "id", "package": "acme::shop", + "order": 1, "parent": "acme::shop::AuditEntry", "attrs": { "fields": [ @@ -89,6 +97,7 @@ "subType": "string", "name": "message", "package": "acme::shop", + "order": 2, "parent": "acme::shop::AuditEntry", "attrs": {} }, @@ -98,6 +107,7 @@ "subType": "entity", "name": "BaseEntity", "package": "acme::shop", + "order": 0, "abstract": true, "attrs": {} }, @@ -107,6 +117,7 @@ "subType": "timestamp", "name": "createdAt", "package": "acme::shop", + "order": 1, "parent": "acme::shop::BaseEntity", "attrs": {} }, @@ -116,6 +127,7 @@ "subType": "uuid", "name": "id", "package": "acme::shop", + "order": 0, "parent": "acme::shop::BaseEntity", "attrs": {} }, @@ -125,6 +137,7 @@ "subType": "primary", "name": "pk", "package": "acme::shop", + "order": 2, "parent": "acme::shop::BaseEntity", "attrs": { "fields": [ @@ -138,6 +151,7 @@ "subType": "entity", "name": "Customer", "package": "acme::shop", + "order": 2, "extends": "acme::shop::BaseEntity", "attrs": {} }, @@ -147,6 +161,7 @@ "subType": "timestamp", "name": "createdAt", "package": "acme::shop", + "order": 1, "parent": "acme::shop::Customer", "attrs": {}, "inheritedFrom": "acme::shop::BaseEntity" @@ -157,6 +172,7 @@ "subType": "rdb", "name": "db", "package": "acme::shop", + "order": 6, "parent": "acme::shop::Customer", "attrs": { "table": "customers" @@ -168,6 +184,7 @@ "subType": "string", "name": "email", "package": "acme::shop", + "order": 4, "parent": "acme::shop::Customer", "attrs": {} }, @@ -177,6 +194,7 @@ "subType": "uuid", "name": "id", "package": "acme::shop", + "order": 0, "parent": "acme::shop::Customer", "attrs": {}, "inheritedFrom": "acme::shop::BaseEntity" @@ -187,6 +205,7 @@ "subType": "string", "name": "name", "package": "acme::shop", + "order": 3, "parent": "acme::shop::Customer", "attrs": { "required": true @@ -198,6 +217,7 @@ "subType": "primary", "name": "pk", "package": "acme::shop", + "order": 2, "parent": "acme::shop::Customer", "attrs": { "fields": [ @@ -212,6 +232,7 @@ "subType": "object", "name": "shippingAddress", "package": "acme::shop", + "order": 5, "parent": "acme::shop::Customer", "attrs": { "objectRef": "acme::shop::Address" @@ -223,6 +244,7 @@ "subType": "entity", "name": "Order", "package": "acme::shop", + "order": 3, "extends": "acme::shop::BaseEntity", "attrs": {} }, @@ -232,6 +254,7 @@ "subType": "timestamp", "name": "createdAt", "package": "acme::shop", + "order": 1, "parent": "acme::shop::Order", "attrs": {}, "inheritedFrom": "acme::shop::BaseEntity" @@ -242,6 +265,7 @@ "subType": "uuid", "name": "customerId", "package": "acme::shop", + "order": 3, "parent": "acme::shop::Order", "attrs": {} }, @@ -251,6 +275,7 @@ "subType": "reference", "name": "customerRef", "package": "acme::shop", + "order": 7, "parent": "acme::shop::Order", "attrs": { "fields": [ @@ -265,6 +290,7 @@ "subType": "rdb", "name": "db", "package": "acme::shop", + "order": 9, "parent": "acme::shop::Order", "attrs": { "table": "orders" @@ -276,6 +302,7 @@ "subType": "uuid", "name": "id", "package": "acme::shop", + "order": 0, "parent": "acme::shop::Order", "attrs": {}, "inheritedFrom": "acme::shop::BaseEntity" @@ -286,6 +313,7 @@ "subType": "lookup", "name": "orderByCustomerId", "package": "acme::shop", + "order": 8, "parent": "acme::shop::Order", "attrs": { "fields": [ @@ -299,6 +327,7 @@ "subType": "primary", "name": "pk", "package": "acme::shop", + "order": 2, "parent": "acme::shop::Order", "attrs": { "fields": [ @@ -313,6 +342,7 @@ "subType": "string", "name": "reference", "package": "acme::shop", + "order": 4, "parent": "acme::shop::Order", "attrs": {} }, @@ -322,6 +352,7 @@ "subType": "enum", "name": "state", "package": "acme::shop", + "order": 6, "parent": "acme::shop::Order", "attrs": { "values": [ @@ -337,6 +368,7 @@ "subType": "decimal", "name": "total", "package": "acme::shop", + "order": 5, "parent": "acme::shop::Order", "attrs": {} }, @@ -346,6 +378,7 @@ "subType": "value", "name": "OrderNote", "package": "acme::shop", + "order": 6, "attrs": {} }, { @@ -354,6 +387,7 @@ "subType": "string", "name": "text", "package": "acme::shop", + "order": 0, "parent": "acme::shop::OrderNote", "attrs": { "required": true @@ -365,6 +399,7 @@ "subType": "prompt", "name": "OrderNotePrompt", "package": "acme::shop", + "order": 7, "attrs": { "format": "text", "payloadRef": "acme::shop::OrderNoteRequest", @@ -379,6 +414,7 @@ "subType": "value", "name": "OrderNoteRequest", "package": "acme::shop", + "order": 5, "attrs": {} }, { @@ -387,6 +423,7 @@ "subType": "string", "name": "reference", "package": "acme::shop", + "order": 0, "parent": "acme::shop::OrderNoteRequest", "attrs": { "required": true @@ -398,6 +435,7 @@ "subType": "functional", "name": "Shop", "package": "acme::shop", + "order": 9, "attrs": { "counterexample": "A customer who cannot place an order.", "level": 1, @@ -411,6 +449,7 @@ "subType": "functional", "name": "Checkout", "package": "acme::shop", + "order": 0, "parent": "acme::shop::Shop", "attrs": { "counterexample": "An order taken outside checkout.", @@ -429,6 +468,7 @@ "subType": "functional", "name": "Orders", "package": "acme::shop", + "order": 0, "parent": "acme::shop::Shop.Checkout", "attrs": { "counterexample": "A placed order that is lost.", @@ -443,6 +483,7 @@ "subType": "functional", "name": "Noted", "package": "acme::shop", + "order": 1, "parent": "acme::shop::Shop.Checkout.Orders", "attrs": { "counterexample": "An order with no note.", @@ -460,6 +501,7 @@ "subType": "functional", "name": "Recorded", "package": "acme::shop", + "order": 0, "parent": "acme::shop::Shop.Checkout.Orders", "attrs": { "counterexample": "A placed order has no row.", @@ -478,6 +520,7 @@ "subType": "functional", "name": "Quotable", "package": "acme::shop", + "order": 0, "parent": "acme::shop::Shop.Checkout.Orders.Recorded", "attrs": { "counterexample": "An order nobody can quote back.", @@ -495,6 +538,7 @@ "subType": "functional", "name": "Refunded", "package": "acme::shop", + "order": 2, "parent": "acme::shop::Shop.Checkout.Orders", "attrs": { "counterexample": "A paid order that cannot be refunded.", @@ -512,6 +556,7 @@ "subType": "functional", "name": "Shipping", "package": "acme::shop", + "order": 1, "parent": "acme::shop::Shop.Checkout", "attrs": { "counterexample": "A paid order that never ships.", @@ -792,7 +837,8 @@ { "code": "WARN_REQUIREMENT_NOTHING_IMPLEMENTS", "severity": "warn", - "source": "gate" + "source": "gate", + "message": "is 'live' but neither it nor anything nested under it names an implementing node. A functional requirement's check is existence — a subtree that claims nothing is a capability nobody built." } ], "verdict": "warn" @@ -802,6 +848,7 @@ { "code": "WARN_REQUIREMENT_NOTHING_IMPLEMENTS", "path": "Shop.Checkout.Shipping", + "node": "", "severity": "warn", "source": "gate", "message": "is 'live' but neither it nor anything nested under it names an implementing node. A functional requirement's check is existence — a subtree that claims nothing is a capability nobody built." @@ -809,6 +856,7 @@ { "code": "WARN_REQUIREMENT_OBJECT_UNCLAIMED", "path": "", + "node": "acme::shop::AuditEntry", "severity": "warn", "source": "gate", "message": "no requirement claims 'acme::shop::AuditEntry'. Add it to an L4 requirement's 'implementedBy'." diff --git a/fixtures/explorer-conformance/shop/verify.json b/fixtures/explorer-conformance/shop/verify.json index 54702a591e..220450bdc0 100644 --- a/fixtures/explorer-conformance/shop/verify.json +++ b/fixtures/explorer-conformance/shop/verify.json @@ -46,6 +46,7 @@ { "code": "WARN_REQUIREMENT_NOTHING_IMPLEMENTS", "path": "Shop.Checkout.Shipping", + "node": "", "severity": "warn", "source": "gate", "message": "is 'live' but neither it nor anything nested under it names an implementing node. A functional requirement's check is existence — a subtree that claims nothing is a capability nobody built." @@ -53,6 +54,7 @@ { "code": "WARN_REQUIREMENT_OBJECT_UNCLAIMED", "path": "", + "node": "acme::shop::AuditEntry", "severity": "warn", "source": "gate", "message": "no requirement claims 'acme::shop::AuditEntry'. Add it to an L4 requirement's 'implementedBy'." @@ -246,7 +248,8 @@ { "code": "WARN_REQUIREMENT_NOTHING_IMPLEMENTS", "severity": "warn", - "source": "gate" + "source": "gate", + "message": "is 'live' but neither it nor anything nested under it names an implementing node. A functional requirement's check is existence — a subtree that claims nothing is a capability nobody built." } ], "verdict": "warn" diff --git a/server/typescript/packages/cli/src/commands/gen.ts b/server/typescript/packages/cli/src/commands/gen.ts index bdba49c353..6f96d480fc 100644 --- a/server/typescript/packages/cli/src/commands/gen.ts +++ b/server/typescript/packages/cli/src/commands/gen.ts @@ -34,6 +34,7 @@ import { describeError } from "../lib/error-text.js"; import { findRuntimeBoundaryCrossings, runtimeBoundaryWarnings } from "../lib/runtime-boundary-advisory.js"; import { hasLegacyDocsBlock, legacyDocsConfigMessage, NO_CONFIG_MESSAGE } from "../lib/docs-removed.js"; import { buildAgentSchemaInput } from "../lib/agent-schema.js"; +import { requirementPayload } from "../lib/requirement-payload.js"; import { existsSync } from "node:fs"; /** @@ -263,6 +264,8 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat // that is what tells the post-selection audit "this project opted into none", // which is a different statement from a programmatic caller that never said. libraries: genCollection.libraries, + // The requirement ledger the docs site's model explorer shows, built only if it asks. + requirementLedger: () => requirementPayload(metadata, genCollection), ...(cliConfig.entities.length > 0 ? { entityFilter: cliConfig.entities } : {}), }); } catch (err) { diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index 4eac6c7432..7a0c181fdd 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -12,6 +12,7 @@ import { join, relative, resolve as resolvePath } from "node:path"; import { parseVerifyArgs, type MigrateFlags } from "../lib/args.js"; import { log } from "../lib/log.js"; import { requirementLedgerRows, type RequirementLedgerRow } from "../lib/requirement-ledger.js"; +import { requirementCountsOf, requirementDiagnosticRow, requirementPayload, type RequirementCounts, type RequirementDiagnosticRow } from "../lib/requirement-payload.js"; import { emitStructured, type OutputFormat } from "../lib/format.js"; import { antiPatternRows, missingBaseUrlRows, removedPropRows, ranSection, skippedSection, warnCapped, @@ -408,7 +409,7 @@ export async function verifyCommand( // can carry them IN FULL. They were previously formatted straight to stderr and // existed nowhere else, which is why 96% of a 239-finding report was unreachable // by any flag, env var or format. - let requirementSection: AdvisorySection = + let requirementSection: AdvisorySection = skippedSection("the requirement pass did not run"); let antiPatternSection: AdvisorySection = skippedSection("the advisory anti-pattern pass did not run"); @@ -807,22 +808,7 @@ export async function verifyCommand( // reason the text line carries it: the claimed/total ratio is only ever taken // over what actually loaded, so a reader needs the denominator's provenance to // notice a spine that covers half an estate. - requirementCounts = { - total: s.total, - functional: s.functional, - architectural: s.architectural, - byStatus: order - .filter((k) => (s.byStatus[k] ?? 0) > 0) - .map((k) => ({ status: k, count: s.byStatus[k] ?? 0 })), - undecided: s.undecided, - // Absent when coverage was not measured (FR-043 §5.4), never zeroed: a reader - // cannot tell `0/0 claimed` from "not measured", and the two mean opposite - // things. - ...(s.entitiesTotal === undefined - ? {} - : { entitiesClaimed: s.entitiesClaimed ?? 0, entitiesTotal: s.entitiesTotal }), - metadataFiles: collection.files.length, - }; + requirementCounts = requirementCountsOf(s, collection.files.length); } const errors = diags.filter((d) => d.severity === "error"); @@ -868,9 +854,9 @@ export async function verifyCommand( // Everything this pass found, uncapped, for the structured payload — gate // diagnostics and lint findings in one list, each row saying which it is, so a // reader can tell what can fail a build from what never can. - requirementSection = ranSection([ - ...diags.map((d) => toDiagnosticRow(d, "gate")), - ...lint.map((d) => toDiagnosticRow(d, "lint")), + requirementSection = ranSection([ + ...diags.map((d) => requirementDiagnosticRow(d, "gate")), + ...lint.map((d) => requirementDiagnosticRow(d, "lint")), ]); // The same findings per ENTRY, beside what each entry declares — so a reader learns an // entry was checked and found clean from a row saying so, not from its path's absence. @@ -1704,6 +1690,8 @@ export async function verifyCommand( return 2; } const config = forgeConfig; + // The explorer's requirement ledger, built only if the docs site asks for it. + const requirementLedger = () => requirementPayload(codegenRoot, genCollection); let result; try { result = await computeCodegenDrift(config, codegenRoot, genConfigDir, genCollection.inScope, genCollection.ownFiles, { @@ -1713,6 +1701,7 @@ export async function verifyCommand( config.dialect, (m) => log.warn(`verify --codegen: [agent-docs] ${m}`), ), + requirementLedger, }); } catch (err) { log.error(`verify --codegen: regeneration failed: ${describeError(err)}`); @@ -1735,6 +1724,7 @@ export async function verifyCommand( genCollection.ownFiles, { sourceRoots: sourceRootsOf(genCollection), agentSchema: () => buildAgentSchemaInput(codegenRoot, config.dialect, () => {}), + requirementLedger, }); return probe.error === undefined && probe.clean; } finally { @@ -1942,20 +1932,6 @@ function toSchemaDriftRow(c: Change): SchemaDriftRow { // structured output (--format toon|json) // --------------------------------------------------------------------------- -/** The ledger counts `meta verify` prints on every run, machine-readable. */ -interface RequirementCounts { - total: number; - functional: number; - architectural: number; - byStatus: { status: string; count: number }[]; - undecided: number; - /** Absent when coverage was not measured — FR-043 §5.4. */ - entitiesClaimed?: number; - entitiesTotal?: number; - /** How many metadata files the two entity counts were taken over. */ - metadataFiles: number; -} - /** One gate's verdict. `ran: false` is NOT a pass — it is "not selected". */ interface VerifyGateRow { gate: string; @@ -2090,7 +2066,7 @@ function toDiagnosticRow(d: Diagnostic, source: "gate" | "lint"): AdvisoryDiagno function buildVerifyPayload(input: { gates: VerifyGateRow[]; exitCode: number; - requirements: AdvisorySection; + requirements: AdvisorySection; requirementCounts: RequirementCounts | undefined; requirementLedger?: RequirementLedgerRow[] | undefined; antiPatterns: AdvisorySection; diff --git a/server/typescript/packages/cli/src/lib/advisory.ts b/server/typescript/packages/cli/src/lib/advisory.ts index bc8397d4d1..bb97eb871c 100644 --- a/server/typescript/packages/cli/src/lib/advisory.ts +++ b/server/typescript/packages/cli/src/lib/advisory.ts @@ -76,7 +76,7 @@ export interface AdvisoryFindingRow { export interface AdvisoryDiagnosticRow { code: string; /** The dotted child-name path, or "" for a diagnostic whose subject is not a - * requirement (object coverage names the entity in its message instead). */ + * requirement (a requirement row names an unclaimed entity in `node` instead). */ path: string; severity: string; /** "gate" — can fail the build; "lint" — advisory authoring warning, never can. */ diff --git a/server/typescript/packages/cli/src/lib/codegen-drift.ts b/server/typescript/packages/cli/src/lib/codegen-drift.ts index 334e02f512..259d53825e 100644 --- a/server/typescript/packages/cli/src/lib/codegen-drift.ts +++ b/server/typescript/packages/cli/src/lib/codegen-drift.ts @@ -187,7 +187,7 @@ export async function computeCodegenDrift( projectRoot: string, scope?: (fqn: string) => boolean, sourceFiles?: readonly string[], - run?: Pick, + run?: Pick, ): Promise { const root = isAbsolute(projectRoot) ? projectRoot : resolve(projectRoot); @@ -218,16 +218,19 @@ export async function computeCodegenDrift( // relative import paths in generated content come out identical. const tempRoot = mkdtempSync(join(tmpdir(), "meta-verify-codegen-")); try { + const untrackedOutDirs: string[] = []; const tempFor = (committed: string): string => { const rel = relative(root, committed); // If a committed outDir lives outside the project root, fall back to a // flattened, collision-safe slot under the temp root. (Relative-import // fidelity for out-of-tree targets isn't guaranteed, but the diff is // still meaningful per-file.) - const safeRel = rel.startsWith("..") || isAbsolute(rel) - ? committed.replace(/[^A-Za-z0-9]+/g, "_") - : rel; - return join(tempRoot, safeRel); + if (rel.startsWith("..") || isAbsolute(rel)) { + const slot = join(tempRoot, committed.replace(/[^A-Za-z0-9]+/g, "_")); + untrackedOutDirs.push(slot); + return slot; + } + return join(tempRoot, rel); }; // Remap the config so runGen writes into the temp mirror instead of the @@ -274,10 +277,12 @@ export async function computeCodegenDrift( // owned generator may read anything. `projectRoot` stays the temp tree, which the // owned route and entity generators compute their adapter import against. inputRoot: root, + untrackedOutDirs, ...(scope !== undefined ? { scope } : {}), ...(sourceFiles !== undefined ? { sourceFiles } : {}), ...(run?.sourceRoots !== undefined ? { sourceRoots: run.sourceRoots } : {}), ...(run?.agentSchema !== undefined ? { agentSchema: run.agentSchema } : {}), + ...(run?.requirementLedger !== undefined ? { requirementLedger: run.requirementLedger } : {}), }); // Where gen discards hand edits instead of keeping them (handEdits: "overwrite"). diff --git a/server/typescript/packages/cli/src/lib/requirement-check.ts b/server/typescript/packages/cli/src/lib/requirement-check.ts index afcff955b9..afcae8c987 100644 --- a/server/typescript/packages/cli/src/lib/requirement-check.ts +++ b/server/typescript/packages/cli/src/lib/requirement-check.ts @@ -58,8 +58,11 @@ export interface Diagnostic { * path. Two branches of a ledger may reuse a NAME, so a bare name does not * locate the node, and a diagnostic you cannot locate is one you cannot act on. * Absent on a diagnostic whose subject is not a requirement (object coverage - * names the entity in its message instead). */ + * names the entity in `node` instead). */ path?: string; + /** The entity a diagnostic is about when its subject is not a requirement (object + * coverage): its fully-qualified name, `::`. */ + node?: string; message: string; } @@ -659,7 +662,7 @@ export function checkRequirements(root: MetaData, scan: RequirementScan = scanRe const key = ent.resolutionKey(); if (!claimedObjects.has(key)) { out.push({ - severity: OBJECT_COVERAGE_SEVERITY, code: WARN_REQUIREMENT_OBJECT_UNCLAIMED, + severity: OBJECT_COVERAGE_SEVERITY, code: WARN_REQUIREMENT_OBJECT_UNCLAIMED, node: key, message: `no requirement claims '${key}'. Add it to an L${REQUIREMENT_LINK_FLOOR_LEVEL} requirement's 'implementedBy'.`, }); } diff --git a/server/typescript/packages/cli/src/lib/requirement-ledger.ts b/server/typescript/packages/cli/src/lib/requirement-ledger.ts index 9a1896f9ff..f9b916af71 100644 --- a/server/typescript/packages/cli/src/lib/requirement-ledger.ts +++ b/server/typescript/packages/cli/src/lib/requirement-ledger.ts @@ -43,6 +43,7 @@ export interface RequirementDiagnosticRef { severity: string; /** "gate" can fail the build; "lint" never can. */ source: "gate" | "lint"; + message: string; } /** One `requirement.*` node, as this run of `meta verify` judged it. */ @@ -99,7 +100,7 @@ export function requirementLedgerRows( const byNode = new Map(); const byPath = new Map(); const note = (d: Diagnostic, source: "gate" | "lint"): void => { - const ref = { code: d.code, severity: d.severity, source }; + const ref = { code: d.code, severity: d.severity, source, message: d.message }; const requirement = diagnosticRequirement.get(d); if (requirement !== undefined) { byNode.set(requirement, [...(byNode.get(requirement) ?? []), ref]); diff --git a/server/typescript/packages/cli/src/lib/requirement-payload.ts b/server/typescript/packages/cli/src/lib/requirement-payload.ts new file mode 100644 index 0000000000..f410ff7cea --- /dev/null +++ b/server/typescript/packages/cli/src/lib/requirement-payload.ts @@ -0,0 +1,107 @@ +// The requirement ledger as `meta verify --format json` states it, for the docs site's model +// explorer (`docsSiteFile()`), which runs inside `meta gen` and `meta verify --codegen`. +// +// codegen-ts cannot run the requirement gate (it lives here, in the CLI), so the two commands +// compute this and hand it to the run as `RunGenOpts.requirementLedger`. It is the same scan, +// gate, lint and ledger rows `meta verify` uses, with the gate's defaults: no +// `--require-implementers`, the authoring lint on. Fixed defaults rather than the caller's +// flags, so the generated site depends on the model alone and `verify --codegen` can hold it. + +import type { MetaData } from "@metaobjectsdev/metadata"; +import { REQUIREMENT_STATUSES } from "@metaobjectsdev/metadata"; +import type { AdvisoryDiagnosticRow } from "./advisory.js"; +import { + checkRequirements, + scanRequirements, + summariseRequirements, + type Diagnostic, + type RequirementSummary, +} from "./requirement-check.js"; +import { lintRequirements } from "./requirement-lint.js"; +import { requirementLedgerRows, type RequirementLedgerRow } from "./requirement-ledger.js"; + +/** The ledger counts `meta verify` prints on every run, machine-readable. */ +export interface RequirementCounts { + total: number; + functional: number; + architectural: number; + byStatus: { status: string; count: number }[]; + undecided: number; + /** Absent when coverage was not measured — FR-043 §5.4. */ + entitiesClaimed?: number; + entitiesTotal?: number; + /** How many metadata files the two entity counts were taken over. */ + metadataFiles: number; +} + +/** The counts as the structured payload carries them. */ +export function requirementCountsOf(s: RequirementSummary, metadataFiles: number): RequirementCounts { + const order = [...REQUIREMENT_STATUSES]; + return { + total: s.total, + functional: s.functional, + architectural: s.architectural, + byStatus: order + .filter((k) => (s.byStatus[k] ?? 0) > 0) + .map((k) => ({ status: k, count: s.byStatus[k] ?? 0 })), + undecided: s.undecided, + // Absent when coverage was not measured (FR-043 §5.4), never zeroed: a reader cannot tell + // `0/0 claimed` from "not measured", and the two mean opposite things. + ...(s.entitiesTotal === undefined + ? {} + : { entitiesClaimed: s.entitiesClaimed ?? 0, entitiesTotal: s.entitiesTotal }), + metadataFiles, + }; +} + +/** One requirement finding as the structured payload carries it. */ +export interface RequirementDiagnosticRow extends AdvisoryDiagnosticRow { + /** The fully-qualified name of the entity the finding is about when its subject is not a + * requirement (`WARN_REQUIREMENT_OBJECT_UNCLAIMED`), or "". */ + node: string; +} + +/** One finding as the structured payload carries it. */ +export function requirementDiagnosticRow(d: Diagnostic, source: "gate" | "lint"): RequirementDiagnosticRow { + return { + code: d.code, + // "" rather than omitted: a tabular encoder (TOON) needs every row to carry the same keys. + path: d.path ?? "", + node: d.node ?? "", + severity: d.severity, + source, + message: d.message, + }; +} + +/** The part of `meta verify --format json` the explorer builder reads. */ +export interface RequirementPayload { + requirementLedger: RequirementLedgerRow[]; + requirementCounts: RequirementCounts; + requirements: { rows: RequirementDiagnosticRow[] }; +} + +/** + * The requirement ledger of a loaded model, or undefined when it declares no requirement. + * `coverable` and `metadataFiles` are the collection's (`inCoverage`, `files.length`). + */ +export function requirementPayload( + root: MetaData, + collection: { inCoverage: (fqn: string) => boolean; files: readonly string[] }, +): RequirementPayload | undefined { + const scan = scanRequirements(root, { coverable: collection.inCoverage, requireImplementers: false }); + const s = summariseRequirements(root, scan); + if (s === undefined) return undefined; + const diags = [...checkRequirements(root, scan)]; + const lint = lintRequirements(root, scan.addressed); + return { + requirementLedger: requirementLedgerRows(root, scan, diags, lint), + requirementCounts: requirementCountsOf(s, collection.files.length), + requirements: { + rows: [ + ...diags.map((d) => requirementDiagnosticRow(d, "gate")), + ...lint.map((d) => requirementDiagnosticRow(d, "lint")), + ], + }, + }; +} diff --git a/server/typescript/packages/cli/test/explorer-fixture.test.ts b/server/typescript/packages/cli/test/explorer-fixture.test.ts index d01388949b..08debae401 100644 --- a/server/typescript/packages/cli/test/explorer-fixture.test.ts +++ b/server/typescript/packages/cli/test/explorer-fixture.test.ts @@ -59,7 +59,7 @@ interface LedgerRow { verdict: string; digest: string; implementedBy: { ref: string; resolves: boolean; target?: string }[]; - diagnostics: { code: string; severity: string; source: string }[]; + diagnostics: { code: string; severity: string; source: string; message: string }[]; } describe("explorer fixture — the committed inputs are what the CLI writes today", () => { @@ -136,7 +136,12 @@ describe("meta verify --format json — requirementLedger rows", () => { const shipping = r.get("Shop.Checkout.Shipping"); expect(shipping?.verdict).toBe("warn"); expect(shipping?.diagnostics).toEqual([ - { code: "WARN_REQUIREMENT_NOTHING_IMPLEMENTS", severity: "warn", source: "gate" }, + { + code: "WARN_REQUIREMENT_NOTHING_IMPLEMENTS", + severity: "warn", + source: "gate", + message: expect.stringContaining("is 'live' but neither it nor anything nested under it names an implementing node"), + }, ]); expect(r.get("Shop.Checkout.Orders.Recorded")?.verdict).toBe("clean"); }); diff --git a/server/typescript/packages/cli/test/explorer-site-ledger.test.ts b/server/typescript/packages/cli/test/explorer-site-ledger.test.ts new file mode 100644 index 0000000000..4bc3e27e4f --- /dev/null +++ b/server/typescript/packages/cli/test/explorer-site-ledger.test.ts @@ -0,0 +1,144 @@ +// The explorer site's requirement views, driven by the ledger the gate itself computes +// (`requirementPayload`) over small real models. The oracle is the gate: each assertion +// names a fact `meta verify` states, and checks the page says the same. +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { canonicalSerializeEffective } from "@metaobjectsdev/metadata"; +import { loadMemory } from "@metaobjectsdev/sdk"; +import { buildExplorer, generateExplorerSite } from "@metaobjectsdev/docs-site"; +import { requirementPayload } from "../src/lib/requirement-payload.js"; +import { ERR_REQUIREMENT_DANGLING_REF, WARN_REQUIREMENT_NOTHING_IMPLEMENTS } from "../src/lib/requirement-check.js"; +import { WARN_REQUIREMENT_TITLE_IS_AN_ID } from "../src/lib/requirement-lint.js"; + +const dirs: string[] = []; +afterAll(() => { + for (const d of dirs) rmSync(d, { recursive: true, force: true }); +}); + +/** Loads `files`, runs the gate, builds the explorer site, and returns a page reader plus the + * gate's own counts. */ +async function site(files: Record): Promise<{ page: (p: string) => string; undecided: unknown }> { + const dir = mkdtempSync(join(tmpdir(), "explorer-ledger-")); + dirs.push(dir); + mkdirSync(join(dir, "metaobjects")); + for (const [name, body] of Object.entries(files)) writeFileSync(join(dir, "metaobjects", name), body); + const root = await loadMemory(dir, { strict: true }); + const verify = requirementPayload(root, { inCoverage: () => true, files: Object.keys(files) }); + if (verify === undefined) throw new Error("the model declares requirements"); + const explorer = buildExplorer({ model: JSON.parse(canonicalSerializeEffective(root)) as unknown, verify }); + const out = join(dir, "site"); + generateExplorerSite({ explorer, outDir: out, title: "Ledger" }); + return { page: (p) => readFileSync(join(out, p), "utf8"), undecided: verify.requirementCounts.undecided }; +} + +/** The body of the Gaps card titled `title`. */ +function gapsCard(gaps: string, title: string): string { + const card = gaps.split('

').find((c) => c.startsWith(`

${title} `)); + if (card === undefined) throw new Error(`no "${title}" card`); + return card; +} + +/** The row of a requirement page's proof table that reports `what`. */ +function proofRow(html: string, what: string): string { + const row = html.split("").find((r) => r.startsWith(`${what}`)); + if (row === undefined) throw new Error(`no "${what}" proof row`); + return row; +} + +/** The `class` attribute values on a page that mark a gate verdict (`v-*`). */ +function verdictClasses(html: string): string[] { + return [...html.matchAll(/class="([^"]*)"/g)].flatMap((m) => (m[1] ?? "").split(" ")).filter((c) => c.startsWith("v-")); +} + +const billing = (name: string, claim: string): string => ` +metadata: + package: acme::${name} + children: + - object.entity: + name: Invoice + children: + - source.rdb: { table: ${name}_invoices } + - field.uuid: { name: id } + - identity.primary: { name: pk, fields: [id] } + - requirement.functional: + name: Billing + level: 1 + status: live + statement: "Invoices are issued" + counterexample: "A sale with no invoice" + children: + - requirement.functional: + name: Invoicing + level: 4 + status: live + statement: "Each invoice is stored" + counterexample: "An invoice that cannot be found again" + implementedBy: ["${claim}"] +`; + +const checkout = ` +metadata: + package: acme::shop + children: + - requirement.functional: + name: Checkout + level: 1 + status: partial + statement: "Customers can check out" + counterexample: "A cart that cannot be paid" + children: + - requirement.functional: + name: Refunds + level: 2 + status: planned + statement: "Orders can be refunded" + counterexample: "A refund nobody can issue" + - requirement.functional: + name: Notes + level: 1 + status: planned + title: "REQ-12" + statement: "Orders carry notes" + counterexample: "A note that is lost" +`; + +describe("explorer requirement views follow the gate's ledger", () => { + test("two packages' requirements at one path each show only their own findings", async () => { + const s = await site({ "meta.a.yaml": billing("a", "acme::a::Invoice"), "meta.b.yaml": billing("b", "acme::b::Receipt") }); + const a = s.page("requirements/acme/a/Billing.Invoicing.html"); + const b = s.page("requirements/acme/b/Billing.Invoicing.html"); + expect(proofRow(a, "Gate findings")).not.toContain(ERR_REQUIREMENT_DANGLING_REF); + expect(verdictClasses(a)).toEqual([]); + expect(proofRow(b, "Gate findings")).toContain(ERR_REQUIREMENT_DANGLING_REF); + const gate = gapsCard(s.page("gaps.html"), "Gate findings"); + const dangling = gate.split("").find((r) => r.includes(ERR_REQUIREMENT_DANGLING_REF)); + expect(dangling).toContain('href="requirements/acme/b/Billing.Invoicing.html"'); + expect(gate).not.toContain('href="requirements/acme/a/Billing.Invoicing.html"'); + }); + + test("an authoring advisory is listed as one and never drawn as a gate verdict", async () => { + const s = await site({ "meta.shop.yaml": checkout }); + const notes = s.page("requirements/acme/shop/Notes.html"); + expect(verdictClasses(notes)).toEqual([]); + expect(proofRow(notes, "Authoring advisories")).toContain(WARN_REQUIREMENT_TITLE_IS_AN_ID); + expect(proofRow(notes, "Gate findings")).not.toContain(WARN_REQUIREMENT_TITLE_IS_AN_ID); + const gaps = s.page("gaps.html"); + expect(gapsCard(gaps, "Gate findings")).not.toContain(WARN_REQUIREMENT_TITLE_IS_AN_ID); + expect(gapsCard(gaps, "Gate findings")).toContain(WARN_REQUIREMENT_NOTHING_IMPLEMENTS); + const lint = gapsCard(gaps, "Authoring advisories"); + expect(lint).toContain(WARN_REQUIREMENT_TITLE_IS_AN_ID); + expect(verdictClasses(lint)).toEqual([]); + }); + + test("the undecided card matches the gate: a partial parent over a planned child is not owed", async () => { + const s = await site({ "meta.shop.yaml": checkout }); + expect(s.undecided).toBe(2); + const card = gapsCard(s.page("gaps.html"), "Undecided gaps"); + expect(card).toContain('2'); + expect(card).toContain('href="requirements/acme/shop/Checkout.Refunds.html"'); + expect(card).toContain('href="requirements/acme/shop/Notes.html"'); + expect(card).not.toContain('href="requirements/acme/shop/Checkout.html"'); + }); +}); diff --git a/server/typescript/packages/cli/test/gen-docs-generators.test.ts b/server/typescript/packages/cli/test/gen-docs-generators.test.ts index 2e775d2b7c..0305f0a94d 100644 --- a/server/typescript/packages/cli/test/gen-docs-generators.test.ts +++ b/server/typescript/packages/cli/test/gen-docs-generators.test.ts @@ -244,22 +244,39 @@ describe("meta gen writes the documentation the list declares", () => { }); test("the docs site lands under site/, and an ejected theme is what it renders with", async () => { - const root = project({ config: base(`[docsSiteFile()]`) }); + const root = project({ config: base(`["entity", docsSiteFile()]`) }); expect(await run(["gen", "--cwd", root])).toBe(0); const site = join(root, "docs", "generated", "site"); - expect(existsSync(join(site, "index.html"))).toBe(true); + // The explorer is the default site: its main page, the data every page reads, a page per object. + const index = readFileSync(join(site, "index.html"), "utf8"); + expect(index).toContain('content="metaobjects docs-site explorer"'); // No date in the footer: the pages depend on the model alone. - expect(readFileSync(join(site, "index.html"), "utf8")).toContain("generated · metadata-docs"); + expect(index).toContain("by the metaobjects docs-site generator. Static"); + expect(existsSync(join(site, "model", "app", "Talk.html"))).toBe(true); + // It runs after the entity generator, so the files that run wrote are traced to their node. + const explorer = JSON.parse(readFileSync(join(site, "explorer.json"), "utf8")) as { generated?: { node: string; files: { path: string }[] }[] }; + expect(explorer.generated?.find((g) => g.node === "app::Talk")?.files.map((f) => f.path)).toEqual( + expect.arrayContaining([expect.stringContaining("Talk.ts")]), + ); expect(await run(["eject", "docs-site", "--cwd", root])).toBe(0); - const css = join(root, "codegen", "docs-site", "assets", "site.css"); + const css = join(root, "codegen", "docs-site", "assets", "explorer.css"); expect(existsSync(css)).toBe(true); writeFileSync(css, "/* owned theme */\n", "utf8"); // A re-run keeps the edit. expect(await run(["eject", "docs-site", "--cwd", root])).toBe(0); expect(readFileSync(css, "utf8")).toBe("/* owned theme */\n"); expect(await run(["gen", "--cwd", root])).toBe(0); - expect(readFileSync(join(site, "assets", "site.css"), "utf8")).toBe("/* owned theme */\n"); + expect(readFileSync(join(site, "assets", "explorer.css"), "utf8")).toBe("/* owned theme */\n"); + }); + + test("site: \"classic\" builds the site that shipped before the explorer", async () => { + const root = project({ config: base(`[docsSiteFile({ site: "classic" })]`) }); + expect(await run(["gen", "--cwd", root])).toBe(0); + const site = join(root, "docs", "generated", "site"); + expect(readFileSync(join(site, "index.html"), "utf8")).toContain("generated · metadata-docs"); + expect(existsSync(join(site, "assets", "site.css"))).toBe(true); + expect(existsSync(join(site, "explorer.json"))).toBe(false); }); }); diff --git a/server/typescript/packages/cli/test/gen-docs-site.test.ts b/server/typescript/packages/cli/test/gen-docs-site.test.ts index ee722f1a0c..5f1efe4385 100644 --- a/server/typescript/packages/cli/test/gen-docs-site.test.ts +++ b/server/typescript/packages/cli/test/gen-docs-site.test.ts @@ -1,7 +1,8 @@ // The docs site as a generator (`docsSiteFile()`, ADR-0034 Amendment 9; `meta docs --site` -// until 1.1.0). The site loads the model with a loader of its own, over whole source -// directories, so what `meta gen` hands it is what these cases hold to: the project's own -// providers, every declared source directory, and output that depends on the model alone. +// until 1.1.0). The default site, the model explorer, reads the model `meta gen` loaded; the +// classic site loads it again with a loader of its own, over whole source directories. Either +// way these cases hold it to the project's own providers, every declared source directory, and +// output that depends on the model alone. import { describe, test, expect, afterEach } from "bun:test"; import { mkdtemp, rm, mkdir, writeFile, readFile } from "node:fs/promises"; import { existsSync } from "node:fs"; @@ -102,13 +103,24 @@ describe("meta gen with docsSiteFile()", () => { test("threads the config's providers into the site's own loader, so a custom subtype renders", async () => { const root = await project(CUSTOM_META, config("providers: [geoProvider],", GEO_PROVIDER)); expect(await run(["gen", "--cwd", root])).toBe(0); - expect(existsSync(join(root, "docs-out", "site", "acme", "geo", "Place.html"))).toBe(true); + const page = join(root, "docs-out", "site", "model", "acme", "geo", "Place.html"); + expect(existsSync(page)).toBe(true); + expect(await readFile(page, "utf8")).toContain("geopoint"); }); - test("docsSiteFile({ assetBase }) points the page chrome at that base instead of jsDelivr", async () => { + test("docsSiteFile({ assetBase }) points the explorer's graph library at that base instead of jsDelivr", async () => { const cfg = config("").replace("docsSiteFile()", `docsSiteFile({ assetBase: "/vendor/npm" })`); const root = await project(META, cfg); expect(await run(["gen", "--cwd", root])).toBe(0); + const html = await readFile(join(root, "docs-out", "site", "map.html"), "utf8"); + expect(html).not.toContain("cdn.jsdelivr.net"); + expect(html).toContain(''); + }); + + test("docsSiteFile({ site: \"classic\", assetBase }) points the classic chrome at that base", async () => { + const cfg = config("").replace("docsSiteFile()", `docsSiteFile({ site: "classic", assetBase: "/vendor/npm" })`); + const root = await project(META, cfg); + expect(await run(["gen", "--cwd", root])).toBe(0); const html = await readFile(join(root, "docs-out", "site", "index.html"), "utf8"); expect(html).not.toContain("cdn.jsdelivr.net"); expect(html).toContain(''); @@ -132,8 +144,8 @@ describe("meta gen with docsSiteFile()", () => { expect(await run(["gen", "--cwd", root])).toBe(0); const site = join(root, "docs-out", "site"); for (const [pkg, model] of [["site", "Welcome"], ["shared", "SharedThing"]] as const) { - expect(existsSync(join(site, "acme", pkg, `${model}.html`))).toBe(true); - expect(await readFile(join(site, "acme", pkg, "index.html"), "utf8")).toContain(model); + expect(existsSync(join(site, "model", "acme", pkg, `${model}.html`))).toBe(true); + expect(await readFile(join(site, "model", "acme", pkg, "index.html"), "utf8")).toContain(model); } }); diff --git a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts index 0294324565..25d13f73b0 100644 --- a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts @@ -503,7 +503,9 @@ export default defineConfig({ docsFile({ target: "out" }), requirementsFile({ target: "out" }), requirementsFile({ target: "out--requirements" }), - docsSiteFile({ target: "out--site" }), + // The classic site, whose pages this diff is stated against; the explorer's report + // pages are covered in docs-site's explorer-site.test.ts. + docsSiteFile({ target: "out--site", site: "classic" }), ], }); `, diff --git a/server/typescript/packages/cli/test/unit/requirement-ledger.test.ts b/server/typescript/packages/cli/test/unit/requirement-ledger.test.ts index a135dce8f9..9e83e568d5 100644 --- a/server/typescript/packages/cli/test/unit/requirement-ledger.test.ts +++ b/server/typescript/packages/cli/test/unit/requirement-ledger.test.ts @@ -8,7 +8,11 @@ import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { loadMemory } from "@metaobjectsdev/sdk"; -import { checkRequirements, scanRequirements } from "../../src/lib/requirement-check.js"; +import { + checkRequirements, + scanRequirements, + WARN_REQUIREMENT_OBJECT_UNCLAIMED, +} from "../../src/lib/requirement-check.js"; import { lintRequirements } from "../../src/lib/requirement-lint.js"; import { requirementLedgerRows } from "../../src/lib/requirement-ledger.js"; @@ -50,7 +54,10 @@ describe("requirementLedgerRows", () => { const gate = checkRequirements(root, scan); expect(gate.length).toBeGreaterThan(0); for (const d of [...gate, ...lintRequirements(root, scan.addressed)]) { - expect(Object.keys(d).filter((k) => !["code", "message", "path", "severity"].includes(k))).toEqual([]); + // Only the object-coverage row names a structured `node` (the unclaimed entity). + const allowed = ["code", "message", "path", "severity"]; + if (d.code === WARN_REQUIREMENT_OBJECT_UNCLAIMED) allowed.push("node"); + expect(Object.keys(d).filter((k) => !allowed.includes(k))).toEqual([]); } const rows = requirementLedgerRows(root, scan, gate, lintRequirements(root, scan.addressed)); const verdicts = rows.map((r) => [r.qualifiedPath, r.verdict, r.diagnostics.map((d) => d.code)]); diff --git a/server/typescript/packages/codegen-ts/src/generator.ts b/server/typescript/packages/codegen-ts/src/generator.ts index d6caa13394..1cf0c7754d 100644 --- a/server/typescript/packages/codegen-ts/src/generator.ts +++ b/server/typescript/packages/codegen-ts/src/generator.ts @@ -127,9 +127,35 @@ export interface GenContext { * call, where a docs generator's own options decide. See docs-run.ts. */ docs?: DocsRunFacts; + /** + * The files this run generated, for a generator marked `readsRunOutput` (the docs site's + * model explorer, which lists what was generated from each node). The runner runs such a + * generator after every other one, so the list is complete. Paths are project-relative, + * as `.gen-state/.hashes.json` keys them. A run narrowed with `--generators` adds the + * files the committed manifest records for the generators it did not run, so a narrowed + * run lists what a full run lists. Absent for a generator without the marker. + */ + runOutput?: () => readonly RunOutputFile[]; + /** + * The requirement ledger as `meta verify --format json` states it (`requirementLedger`, + * `requirementCounts`, `requirements.rows`), computed by the caller that owns the + * requirement gate (`meta gen`, `meta verify --codegen`), which codegen-ts cannot import. + * Called at most once per run, and only when a generator asks. Absent when the caller + * supplied none; returns undefined when the model declares no requirement. + */ + requirementLedger?: () => unknown; warn: (msg: string) => void; } +/** One file of the run, as `GenContext.runOutput` lists it. */ +export interface RunOutputFile { + /** Project-relative path, `/`-separated. */ + path: string; + generatedBy: string; + /** The node the file was rendered from (`EmittedFile.sourceNode`), when it was. */ + sourceNode?: string; +} + export interface Generator { /** kebab-case identifier; surfaces in diagnostics + drift logs. */ name: string; @@ -190,6 +216,10 @@ export interface Generator { * pages in the same target link to them (`ctx.docs.apiSurfaces`). Like `emitsModelDocs`, * a cross-link fact only. */ emitsApiDocs?: { readonly subDir: string }; + /** Marks a generator that reads the files the rest of the run generated + * (`ctx.runOutput`). The runner runs every marked generator after every unmarked one, + * in declared order, so the list it reads is complete. */ + readsRunOutput?: boolean; /** §A6 — marks the generator that emits the Names artifact. The runner * aggregates this across the suite into ResolvedGenConfig.includeNames, which the * entity generator reads to decide whether it may reference those constants. diff --git a/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts b/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts index 213ce576bf..271cbc0a9c 100644 --- a/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts @@ -7,24 +7,53 @@ // docs-site` copies both into `codegen/docs-site/`, and this generator reads them from there // when they exist (Amendment 8, ruling 3, as Amendment 9 restates it). // -// The site loads the model with its own loader, from whole source DIRECTORIES (one page group -// each), so it reads the collection's source roots off the context rather than the loaded -// root every other generator walks. +// Two sites, chosen by `site`: +// +// explorer (the default) the model explorer: what the software does (the requirement +// tree), the model map, a page per object, prompt, requirement and route, the +// coverage matrix, the trace and the gaps. Every page reads one document, +// `explorer.json`, which this generator builds from the effective model, the +// requirement ledger the caller computed (`ctx.requirementLedger`), the files this +// run wrote (`ctx.runOutput`) and the routes the run mounts. It runs after every +// other generator, so the files it lists are this run's. +// classic the site before the explorer: a page per package and per object with ER +// diagrams. It loads the model with its own loader, from whole source DIRECTORIES +// (one page group each), so it reads the collection's source roots off the context. import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { basename, join, resolve } from "node:path"; import { existsSync } from "node:fs"; -import { generateSite } from "@metaobjectsdev/docs-site"; -import type { EmittedFile, Generator, GeneratorFactory } from "../generator.js"; +import { canonicalSerializeEffective } from "@metaobjectsdev/metadata"; +import { + buildExplorer, + generateExplorerSite, + generateSite, + readPromptTexts, + type ExplorerRoute, +} from "@metaobjectsdev/docs-site"; +import type { EmittedFile, GenContext, Generator, GeneratorFactory } from "../generator.js"; import { DOCS_TARGET_NAME } from "../docs-run.js"; +import { buildApiModelForRun } from "./api-model.js"; /** The site lands here, under the target. */ const DEFAULT_SITE_DIR = "site"; /** Where `meta eject docs-site` writes the site's templates and assets, under the project. */ export const OWNED_DOCS_SITE_DIR = "codegen/docs-site"; +/** The two sites `docsSiteFile()` builds. */ +export const DOCS_SITE_EXPLORER = "explorer"; +export const DOCS_SITE_CLASSIC = "classic"; +export type DocsSiteKind = typeof DOCS_SITE_EXPLORER | typeof DOCS_SITE_CLASSIC; + +/** The file every explorer theme template set carries, so an owned set can be told apart from + * an owned classic one. */ +const EXPLORER_MARKER_TEMPLATE = "explorer-head.mustache"; + export interface DocsSiteFileOpts { + /** Which site: `explorer` (default), the model explorer, or `classic`, the per-package site + * with ER diagrams that shipped before it. */ + site?: DocsSiteKind; /** A directory holding prompt `.mustache` sources outside `metaobjects/` and `templates/`, * relative to the project, so the site can show prompt TEXT. */ prompts?: string; @@ -36,10 +65,11 @@ export interface DocsSiteFileOpts { * depend on the model alone and `meta verify --codegen` can hold them to it. A date here * makes every day's run differ from the last. */ stamp?: string; - /** Where the pages load their third-party CSS and JS from (daisyUI, Tailwind's browser build, - * Mermaid, svg-pan-zoom). Default `https://cdn.jsdelivr.net/npm`, which needs network access - * to render; set it to your own mirror, or to a path you serve the five files from. Give an - * absolute URL or a root-relative path. See `@metaobjectsdev/docs-site` for the files. */ + /** Where the pages load their third-party CSS and JS from: the explorer loads Cytoscape for + * its graphs, the classic site daisyUI, Tailwind's browser build, Mermaid and svg-pan-zoom. + * Default `https://cdn.jsdelivr.net/npm`, which needs network access to draw them; set it to + * your own mirror, or to a path you serve the files from. Give an absolute URL or a + * root-relative path. See `@metaobjectsdev/docs-site` for the files. */ assetBase?: string; /** Named output target. Default `"docs"`, which `targets` must declare. */ target?: string; @@ -48,11 +78,15 @@ export interface DocsSiteFileOpts { export const docsSiteFile = function docsSiteFile(opts?: DocsSiteFileOpts): Generator { const dir = (opts?.subDir ?? DEFAULT_SITE_DIR).replace(/\/$/, ""); const prefix = dir === "" ? "" : `${dir}/`; + const kind = opts?.site ?? DOCS_SITE_EXPLORER; return { name: "docs-site", target: opts?.target ?? DOCS_TARGET_NAME, + // The explorer lists the files the run generated, so it runs after the rest. + ...(kind === DOCS_SITE_EXPLORER && { readsRunOutput: true }), async generate(ctx) { const project = ctx.inputRoot ?? ctx.projectRoot ?? process.cwd(); + if (kind === DOCS_SITE_EXPLORER) return explorerSite(ctx, project, prefix, opts); if (ctx.sourceRoots === undefined || ctx.sourceRoots.length === 0) { throw new Error( "docs-site: the run named no metadata source directories (ctx.sourceRoots), which the " + @@ -60,54 +94,124 @@ export const docsSiteFile = function docsSiteFile(opts?: DocsSiteFileOpts): Gene "`sourceRoots`.", ); } - // Prompt `.mustache` sources are searched beside the model: the project's `templates/` - // and the `prompts` directory when given. Deduplicated by path: one directory named twice - // would be loaded twice. - const sourceDirs = [...ctx.sourceRoots]; - const seen = new Set(sourceDirs.map((d) => resolve(d))); - const prompts = opts?.prompts === undefined ? undefined : resolve(project, opts.prompts); - if (prompts !== undefined && !existsSync(prompts)) { - ctx.warn(`docs-site: the prompts directory does not exist: ${prompts}`); - } - for (const d of [join(project, "templates"), ...(prompts !== undefined ? [prompts] : [])]) { - const abs = resolve(d); - if (existsSync(abs) && !seen.has(abs)) { - sourceDirs.push(abs); - seen.add(abs); - } - } - const ownedTemplates = join(project, OWNED_DOCS_SITE_DIR, "templates"); - const ownedAssets = join(project, OWNED_DOCS_SITE_DIR, "assets"); - // The builder writes to a directory (its link check reads the pages back), so the site - // is built in a scratch directory and returned as files for the runner to write. - const scratch = mkdtempSync(join(tmpdir(), "meta-docs-site-")); - try { + const sourceDirs = promptSourceDirs(ctx, project, opts, ctx.sourceRoots); + const owned = ownedSiteDirs(project); + return buildInScratch(prefix, async (outDir) => { const result = await generateSite({ sourceDirs, - outDir: scratch, + outDir, title: opts?.title ?? (basename(project) || "Metadata"), stamp: opts?.stamp ?? "", commit: "", core: { n: 15 }, ...(opts?.assetBase !== undefined ? { assetBase: opts.assetBase } : {}), ...(ctx.providers !== undefined ? { extraProviders: ctx.providers } : {}), - ...(existsSync(ownedTemplates) ? { templatesDir: ownedTemplates } : {}), - ...(existsSync(ownedAssets) ? { assetsDir: ownedAssets } : {}), + ...owned, }); - const written = [ - ...result.pages, - "assets/site.css", - "assets/site.js", - "assets/search-index.json", - ]; - const files: EmittedFile[] = written.map((path) => ({ - path: `${prefix}${path}`, - content: readFileSync(join(scratch, path), "utf8"), - })); - return files; - } finally { - rmSync(scratch, { recursive: true, force: true }); - } + return [...result.pages, "assets/site.css", "assets/site.js", "assets/search-index.json"]; + }); }, }; } as GeneratorFactory; + +/** Prompt `.mustache` sources are searched beside the model: the source roots, the project's + * `templates/` and the `prompts` directory when given. Deduplicated by path: one directory + * named twice would be loaded twice. */ +function promptSourceDirs(ctx: GenContext, project: string, opts: DocsSiteFileOpts | undefined, roots: readonly string[]): string[] { + const dirs = [...roots]; + const seen = new Set(dirs.map((d) => resolve(d))); + const prompts = opts?.prompts === undefined ? undefined : resolve(project, opts.prompts); + if (prompts !== undefined && !existsSync(prompts)) { + ctx.warn(`docs-site: the prompts directory does not exist: ${prompts}`); + } + for (const d of [join(project, "templates"), ...(prompts !== undefined ? [prompts] : [])]) { + const abs = resolve(d); + if (existsSync(abs) && !seen.has(abs)) { + dirs.push(abs); + seen.add(abs); + } + } + return dirs; +} + +/** The owned site directories `meta eject docs-site` wrote, only those that exist. */ +function ownedSiteDirs(project: string): { templatesDir?: string; assetsDir?: string } { + const templatesDir = join(project, OWNED_DOCS_SITE_DIR, "templates"); + const assetsDir = join(project, OWNED_DOCS_SITE_DIR, "assets"); + return { + ...(existsSync(templatesDir) && { templatesDir }), + ...(existsSync(assetsDir) && { assetsDir }), + }; +} + +/** The builder writes to a directory (its link check reads the pages back), so a site is built + * in a scratch directory and returned as files for the runner to write. `build` returns the + * page paths it wrote, relative to that directory. */ +async function buildInScratch(prefix: string, build: (outDir: string) => string[] | Promise): Promise { + const scratch = mkdtempSync(join(tmpdir(), "meta-docs-site-")); + try { + const paths = await build(scratch); + return paths.map((path) => ({ path: `${prefix}${path}`, content: readFileSync(join(scratch, path), "utf8") })); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +} + +/** The routes the run mounts, as the api reference states them (`METHOD /path` per symbol). */ +function runRoutes(ctx: GenContext): ExplorerRoute[] { + const routes: ExplorerRoute[] = []; + for (const unit of buildApiModelForRun(ctx).units) { + const node = unit.package !== undefined && unit.package !== "" ? `${unit.package}::${unit.node}` : unit.node; + for (const sym of unit.symbols) { + if (sym.kind !== "rest") continue; + const space = sym.name.indexOf(" "); + if (space < 0) continue; + routes.push({ node, method: sym.name.slice(0, space), path: sym.name.slice(space + 1) }); + } + } + return routes; +} + +async function explorerSite(ctx: GenContext, project: string, prefix: string, opts: DocsSiteFileOpts | undefined): Promise { + // The manifest's shape (path → generatedBy, sourceNode), from the files this run wrote: a + // fresh clone builds the same site as the machine that last generated. + const manifest: Record = {}; + for (const f of ctx.runOutput?.() ?? []) { + manifest[f.path] = { generatedBy: f.generatedBy, ...(f.sourceNode !== undefined && { sourceNode: f.sourceNode }) }; + } + // The ledger is the requirement gate's; a gate that throws leaves the section out (as a + // missing verify input does) rather than failing the whole run in the docs step. + let ledger: unknown; + try { + ledger = ctx.requirementLedger?.(); + } catch (err) { + ctx.warn(`docs-site: the requirement ledger could not be built, so the site shows none: ${err instanceof Error ? err.message : String(err)}`); + } + // No route at all means this run recorded none (no routes generator, or REST off), which the + // site says as such; an empty list would claim the run mounted nothing. + const routes = runRoutes(ctx); + const explorer = buildExplorer({ + model: JSON.parse(canonicalSerializeEffective(ctx.loadedRoot)) as unknown, + ...(ledger !== undefined && { verify: ledger }), + manifest, + ...(routes.length > 0 && { routes }), + }); + const texts = readPromptTexts(explorer, promptSourceDirs(ctx, project, opts, ctx.sourceRoots ?? [])); + const owned = ownedSiteDirs(project); + if (owned.templatesDir !== undefined && !existsSync(join(owned.templatesDir, EXPLORER_MARKER_TEMPLATE))) { + ctx.warn( + `docs-site: ${OWNED_DOCS_SITE_DIR}/templates holds the classic site's theme, which the explorer ` + + "does not read; it uses its bundled templates. Re-run `meta eject docs-site` to own the " + + "explorer's theme, or pass `site: \"classic\"`.", + ); + } + return buildInScratch(prefix, (outDir) => generateExplorerSite({ + explorer, + outDir, + title: opts?.title ?? (basename(project) || "Metadata"), + stamp: opts?.stamp ?? "", + texts, + ...(opts?.assetBase !== undefined ? { assetBase: opts.assetBase } : {}), + ...owned, + }).files); +} diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index 57464372da..27ad6f8d5b 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -6,7 +6,7 @@ export { runGen, declaredGeneratorNames, stableGeneratorName, undeclaredGeneratorsMessage } from "./runner.js"; export type { RunGenOpts, RunGenResult } from "./runner.js"; -export type { Generator, GenContext, EmittedFile, GeneratorFactory } from "./generator.js"; +export type { Generator, GenContext, EmittedFile, GeneratorFactory, RunOutputFile } from "./generator.js"; export { perEntity, perPackage, perModel, oncePerRun } from "./generator.js"; // The one aggregation of the UI-tier markers, Hono routes and the routes' `expose` option: // the run's own answers to "does this run emit a UI tier?" and "which verbs are mounted?". diff --git a/server/typescript/packages/codegen-ts/src/overwrite-policy.ts b/server/typescript/packages/codegen-ts/src/overwrite-policy.ts index 70311f1554..74d9d5dd04 100644 --- a/server/typescript/packages/codegen-ts/src/overwrite-policy.ts +++ b/server/typescript/packages/codegen-ts/src/overwrite-policy.ts @@ -260,6 +260,26 @@ export function recordGeneratedProvenance( if (changed) writeRawManifest(genStateDir, raw); } +/** + * Every recorded path that carries provenance, as `recordGeneratedProvenance` wrote it: the + * generator, and the source node when there is one. A plain `""` entry carries no + * generator and is left out. Sorted by path. + */ +export function listGeneratedProvenance( + genStateDir: string, +): { path: string; generatedBy: string; sourceNode?: string }[] { + const out: { path: string; generatedBy: string; sourceNode?: string }[] = []; + for (const [path, entry] of Object.entries(readRawManifest(genStateDir))) { + if (!isRecord(entry) || typeof entry.generatedBy !== "string") continue; + out.push({ + path, + generatedBy: entry.generatedBy, + ...(typeof entry.sourceNode === "string" && { sourceNode: entry.sourceNode }), + }); + } + return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); +} + // --------------------------------------------------------------------------- // FR-038 §8 — readers for orphan reconciliation. // diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index f8bc70baa9..19dae55244 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -1,4 +1,4 @@ -import { join, relative, resolve, isAbsolute, dirname } from "node:path"; +import { join, relative, resolve, isAbsolute, dirname, sep } from "node:path"; import { warnMissingPromptGenerators } from "./prompt-generator-gate.js"; import { runEmitsEntityModule, runEmitsHonoRoutes, runEmitsQueries, runEmitsRestRoutes, runEmitsUiTier, runRoutesExpose, warnUnmarkedRoutesGenerators, warnUnmarkedUiGenerators } from "./ui-tier-gate.js"; import { warnRetiredCodegenAttrs } from "./retired-codegen-attrs.js"; @@ -16,7 +16,7 @@ import { assertNoCollectionNameCollisions } from "./naming/collection-name-colli import { isAbstract } from "./instance-artifacts.js"; import { dbEmittingObjects, missingDialectMessage } from "./db-emitting.js"; import { generatableObjects, hasAnyRdbSource } from "./source-detect.js"; -import type { Generator, GenContext, EmittedFile } from "./generator.js"; +import type { Generator, GenContext, EmittedFile, RunOutputFile } from "./generator.js"; import type { MetaobjectsGenConfig } from "./metaobjects-config.js"; import { normalizeConfig, assertCodegenDialect, DEFAULT_TARGET_NAME } from "./metaobjects-config.js"; import type { ResolvedTarget } from "./import-path.js"; @@ -34,6 +34,7 @@ import { loadEngineVersion, saveEngineVersion, recordGeneratedProvenance, + listGeneratedProvenance, type GeneratedProvenance, type WriteResult, type MergeStrategy, @@ -190,6 +191,21 @@ export interface RunGenOpts { * `GenContext.libraries`. */ libraries?: readonly string[]; + /** + * The requirement ledger as `meta verify --format json` states it, threaded onto + * `GenContext.requirementLedger` for the docs site's model explorer. codegen-ts cannot + * compute it (the requirement gate is the CLI's), so the caller that can supplies it; the + * runner calls it at most once, and only when a generator asks. Absent: the explorer + * shows no ledger. + */ + requirementLedger?: () => unknown; + /** + * Directories inside `projectRoot` that stand in for output directories OUTSIDE the real + * project. `meta verify --codegen` regenerates into a temp tree and moves an out-of-tree + * target into a slot under it; a file written there is treated as outside the project, as + * `meta gen` treats the real one: written, never recorded, and absent from `ctx.runOutput`. + */ + untrackedOutDirs?: readonly string[]; } export interface RunGenResult { @@ -358,10 +374,12 @@ export async function runGen(opts: RunGenOpts): Promise { // a watch loop, a test) would otherwise find the first run's snapshot and three-way merge, // which is exactly the record-keeping an untracked file does not have. const untrackedGenStateDir = join(tmpdir(), `meta-gen-untracked-${process.pid}-${randomUUID()}`); + const untrackedOutDirs = opts.untrackedOutDirs ?? []; const outsideProject = (fullPath: string): boolean => { if (projectRoot === undefined) return false; const rel = relative(projectRoot, fullPath); - return rel.startsWith("..") || isAbsolute(rel); + if (rel.startsWith("..") || isAbsolute(rel)) return true; + return untrackedOutDirs.some((dir) => isNestedIn(fullPath, dir)); }; let untrackedCount = 0; const policyFor = (fullPath: string, handEdits?: HandEdits): DecideAndWriteOpts => { @@ -791,6 +809,10 @@ export async function runGen(opts: RunGenOpts): Promise { if (unknown.length > 0) throw new Error(undeclaredGeneratorsMessage(unknown, declared)); selected = config.generators.filter((_, i) => wanted.has(declared[i]!)); } + // A generator that reads the run's output runs after every one that writes it, each group in + // declared order, so the list it reads is complete. + selected = [...selected.filter((g) => g.readsRunOutput !== true), ...selected.filter((g) => g.readsRunOutput === true)]; + const requirementLedger = opts.requirementLedger !== undefined ? once(opts.requirementLedger) : undefined; // 4. Run each generator with a per-target render context; collect with full path. const emitted: { @@ -820,6 +842,43 @@ export async function runGen(opts: RunGenOpts): Promise { // Generators that ran and produced no file. See the note at the `files.length === 0` // check below. A Set because a generator may run once per target. const emptyGenerators = new Set(); + // `ctx.runOutput`: what this run has generated so far, keyed as the manifest keys it. A run + // narrowed with `--generators` or to some entities adds what the committed manifest records + // for the rest — the declared generators it did not run, and the objects it did not render — + // so a narrowed run reads what a full run reads. A record for a generator no longer declared, + // or for a file no longer on disk, is stale and stays out. + const entityNarrowed = opts.entityFilter !== undefined && opts.entityFilter.length > 0; + const runOutputFiles = (): RunOutputFile[] => { + const out = new Map(); + const keyOf = (fullPath: string): string | undefined => { + if (projectRoot === undefined) return fullPath.split(sep).join("/"); + if (outsideProject(fullPath)) return undefined; + return relative(projectRoot, fullPath).split(sep).join("/"); + }; + if (opts.generatorNames !== undefined || entityNarrowed) { + const ranNames = new Set(selected.map((g) => g.name)); + const declaredNames = new Set(config.generators.map((g) => g.name)); + const renderedNodes = new Set(safeEntities.map((e) => e.resolutionKey())); + for (const rec of listGeneratedProvenance(genStateDir)) { + if (!declaredNames.has(rec.generatedBy)) continue; + // A generator that ran states its own output, except for the objects an entity + // filter kept it from. + if (ranNames.has(rec.generatedBy) && (!entityNarrowed || rec.sourceNode === undefined || renderedNodes.has(rec.sourceNode))) continue; + if (projectRoot !== undefined && !existsSync(join(projectRoot, rec.path))) continue; + out.set(rec.path, rec); + } + } + for (const file of emitted) { + const path = keyOf(file.fullPath); + if (path === undefined) continue; + out.set(path, { + path, + generatedBy: file.generatedBy, + ...(file.sourceNode !== undefined && { sourceNode: file.sourceNode }), + }); + } + return [...out.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + }; for (const generator of selected) { const selfTarget = targetOf(generator); @@ -909,6 +968,8 @@ export async function runGen(opts: RunGenOpts): Promise { ...(config.providers !== undefined && { providers: config.providers }), docs: docsFactsFor(selfTarget.name), ...(selectedManifests !== undefined && { libraries: selectedManifests }), + ...(generator.readsRunOutput === true && { runOutput: runOutputFiles }), + ...(requirementLedger !== undefined && { requirementLedger }), warn: (msg) => warnings.push(`[${generator.name}] ${msg}`), }; @@ -1349,3 +1410,16 @@ export function undeclaredGeneratorsMessage(unknown: readonly string[], declared "." ); } + +/** Memoize a zero-argument callback: called at most once, and only when first asked. */ +function once(fn: () => T): () => T { + let done = false; + let value: T | undefined; + return () => { + if (!done) { + value = fn(); + done = true; + } + return value as T; + }; +} diff --git a/server/typescript/packages/codegen-ts/test/docs-site-explorer.test.ts b/server/typescript/packages/codegen-ts/test/docs-site-explorer.test.ts new file mode 100644 index 0000000000..b343a604d1 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/docs-site-explorer.test.ts @@ -0,0 +1,105 @@ +// docsSiteFile() builds the model explorer by default: explorer.json from the effective model, +// the requirement ledger the caller hands the run, the files the run wrote and the routes it +// mounts. It runs after the generators declared beside it, whatever their order. +import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { MetaDataLoader, type MetaRoot } from "@metaobjectsdev/metadata"; +import { FileSource } from "@metaobjectsdev/metadata/core"; +import { runGen } from "../src/runner.js"; +import { defineConfig } from "../src/metaobjects-config.js"; +import type { Generator } from "../src/generator.js"; +import { docsSiteFile, entityFile, routesFile } from "../src/generators/index.js"; + +const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); + +interface ExplorerShape { + generated?: { node: string; files: { path: string; generatedBy: string }[] }[]; + api?: { node: string; method: string; path: string }[]; + ledger?: unknown; +} + +let tmp: string; +let root: MetaRoot; +// The run's one metadata source directory (the classic site loads whole directories). +let sources: string; +beforeEach(async () => { + tmp = mkdtempSync(join(tmpdir(), "codegen-docs-site-")); + sources = join(tmp, "metaobjects"); + mkdirSync(sources); + copyFileSync(FIXTURE, join(sources, "meta.blog.json")); + root = (await new MetaDataLoader().load([new FileSource(FIXTURE)])).root; +}); +afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); + +const config = (generators: Generator[]) => + defineConfig({ + outDir: join(tmp, "src"), + extStyle: "none", + dbImport: "../db", + dialect: "sqlite", + apiPrefix: "/api", + targets: { docs: { outDir: join(tmp, "docs") } }, + generators, + }); + +const explorerOf = (): ExplorerShape => + JSON.parse(readFileSync(join(tmp, "docs", "site", "explorer.json"), "utf8")) as ExplorerShape; + +describe("docsSiteFile() builds the model explorer", () => { + test("declared first, it still sees what the code generators wrote, and the routes they mount", async () => { + await runGen({ + config: config([docsSiteFile(), entityFile(), routesFile()]), + metadata: root, + projectRoot: tmp, + sourceRoots: [sources], + }); + expect(existsSync(join(tmp, "docs", "site", "index.html"))).toBe(true); + const ex = explorerOf(); + const post = ex.generated?.find((g) => g.node.endsWith("Post")); + expect(post?.files.map((f) => f.generatedBy)).toEqual(expect.arrayContaining(["entity-file", "routes-file"])); + expect(ex.api?.some((r) => r.node.endsWith("Post") && r.method === "GET" && r.path.startsWith("/api/"))).toBe(true); + expect(readFileSync(join(tmp, "docs", "site", "api.html"), "utf8")).toContain("/api/"); + }); + + test("without a routes generator in the run, the site says no routes were recorded, not that none are mounted", async () => { + await runGen({ config: config([entityFile(), docsSiteFile()]), metadata: root, projectRoot: tmp, sourceRoots: [sources] }); + expect(explorerOf().api).toBeUndefined(); + expect(readFileSync(join(tmp, "docs", "site", "api.html"), "utf8")).toContain("recorded no routes"); + }); + + test("a requirement ledger that throws leaves the ledger out with a warning, and the site still builds", async () => { + const result = await runGen({ + config: config([docsSiteFile()]), + metadata: root, + projectRoot: tmp, + sourceRoots: [sources], + requirementLedger: () => { throw new Error("gate exploded"); }, + }); + expect(explorerOf().ledger).toBeUndefined(); + expect(result.warnings.some((w) => w.includes("gate exploded"))).toBe(true); + }); + + test("the requirement ledger comes from the caller, asked for once", async () => { + let calls = 0; + await runGen({ + config: config([docsSiteFile()]), + metadata: root, + projectRoot: tmp, + sourceRoots: [sources], + requirementLedger: () => { + calls += 1; + return { requirementLedger: [], requirementCounts: { total: 0 }, requirements: { rows: [] } }; + }, + }); + expect(calls).toBe(1); + expect(explorerOf().ledger).toBeDefined(); + }); + + test("site: \"classic\" builds the earlier site and no explorer.json", async () => { + await runGen({ config: config([docsSiteFile({ site: "classic" })]), metadata: root, projectRoot: tmp, sourceRoots: [sources] }); + expect(existsSync(join(tmp, "docs", "site", "assets", "site.css"))).toBe(true); + expect(existsSync(join(tmp, "docs", "site", "explorer.json"))).toBe(false); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/run-output.test.ts b/server/typescript/packages/codegen-ts/test/run-output.test.ts new file mode 100644 index 0000000000..b76b1b610e --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/run-output.test.ts @@ -0,0 +1,111 @@ +// `readsRunOutput`: a generator that lists what the rest of the run generated (the docs site's +// model explorer) runs after every other generator and reads the files through `ctx.runOutput`, +// keyed as the manifest keys them. `requirementLedger` is the caller's callback, called once. +import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { mkdtempSync, rmSync, unlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { MetaDataLoader } from "@metaobjectsdev/metadata"; +import { FileSource } from "@metaobjectsdev/metadata/core"; +import { runGen } from "../src/runner.js"; +import { defineConfig } from "../src/metaobjects-config.js"; +import { perEntity, type Generator, type RunOutputFile } from "../src/generator.js"; + +const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); +const TWO = resolve(import.meta.dir, "fixtures", "two-entities-fk.json"); + +let tmp: string; +beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-run-output-")); }); +afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); + +async function load(file = FIXTURE) { + return (await new MetaDataLoader().load([new FileSource(file)])).root; +} + +function reader(seen: { files?: readonly RunOutputFile[] | undefined; ledger?: unknown[] }): Generator { + return { + name: "reader", + readsRunOutput: true, + generate(ctx) { + seen.files = ctx.runOutput?.(); + seen.ledger = [ctx.requirementLedger?.(), ctx.requirementLedger?.()]; + return [{ path: "list.txt", content: (seen.files ?? []).map((f) => f.path).join("\n") }]; + }, + }; +} + +const alpha: Generator = { name: "alpha", generate: perEntity((e) => ({ path: `${e.name}.alpha.ts`, content: "// a\n" })) }; + +describe("readsRunOutput", () => { + test("runs after a generator declared later and sees its files, project-relative", async () => { + const seen: { files?: readonly RunOutputFile[] | undefined } = {}; + let calls = 0; + await runGen({ + config: defineConfig({ outDir: join(tmp, "gen"), extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [reader(seen), alpha] }), + metadata: await load(), + projectRoot: tmp, + requirementLedger: () => { calls++; return { requirementLedger: [] }; }, + }); + expect(seen.files).toEqual([{ path: "gen/Post.alpha.ts", generatedBy: "alpha", sourceNode: "demo::Post" }]); + expect(calls).toBe(1); + }); + + test("an unmarked generator gets no runOutput", async () => { + let had: unknown = "unset"; + const plain: Generator = { name: "plain", generate(ctx) { had = ctx.runOutput; return []; } }; + await runGen({ + config: defineConfig({ outDir: join(tmp, "gen"), extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [plain] }), + metadata: await load(), + projectRoot: tmp, + }); + expect(had).toBeUndefined(); + }); + + test("a narrowed run reads the manifest for the generators it did not run", async () => { + const config = defineConfig({ outDir: join(tmp, "gen"), extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [alpha, reader({})] }); + await runGen({ config, metadata: await load(), projectRoot: tmp }); + const seen: { files?: readonly RunOutputFile[] | undefined } = {}; + const narrowed = defineConfig({ outDir: join(tmp, "gen"), extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [alpha, reader(seen)] }); + await runGen({ config: narrowed, metadata: await load(), projectRoot: tmp, generatorNames: ["reader"] }); + expect(seen.files).toEqual([{ path: "gen/Post.alpha.ts", generatedBy: "alpha", sourceNode: "demo::Post" }]); + }); + + test("a run narrowed to some entities still reads the other objects' files from the manifest", async () => { + const config = (seen: { files?: readonly RunOutputFile[] | undefined }) => + defineConfig({ outDir: join(tmp, "gen"), extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [alpha, reader(seen)] }); + await runGen({ config: config({}), metadata: await load(TWO), projectRoot: tmp }); + const seen: { files?: readonly RunOutputFile[] | undefined } = {}; + await runGen({ config: config(seen), metadata: await load(TWO), projectRoot: tmp, entityFilter: ["Post"] }); + expect(seen.files?.map((f) => f.path)).toEqual(["gen/Post.alpha.ts", "gen/User.alpha.ts"]); + }); + + test("a narrowed run leaves out records for a generator no longer declared or a file no longer on disk", async () => { + const beta: Generator = { name: "beta", generate: perEntity((e) => ({ path: `${e.name}.beta.ts`, content: "// b\n" })) }; + const base = { outDir: join(tmp, "gen"), extStyle: "none" as const, dbImport: "../db", dialect: "sqlite" as const }; + await runGen({ config: defineConfig({ ...base, generators: [alpha, beta, reader({})] }), metadata: await load(TWO), projectRoot: tmp }); + unlinkSync(join(tmp, "gen", "User.alpha.ts")); + const seen: { files?: readonly RunOutputFile[] | undefined } = {}; + await runGen({ config: defineConfig({ ...base, generators: [alpha, reader(seen)] }), metadata: await load(TWO), projectRoot: tmp, generatorNames: ["reader"] }); + expect(seen.files?.map((f) => f.path)).toEqual(["gen/Post.alpha.ts"]); + }); + + test("a stand-in for an out-of-tree outDir is left out, as the out-of-tree outDir itself is", async () => { + const webAlpha: Generator = { ...alpha, target: "web" }; + const config = (web: string, seen: { files?: readonly RunOutputFile[] | undefined }) => + defineConfig({ outDir: join(tmp, "project", "gen"), targets: { web: { outDir: web } }, extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [webAlpha, reader(seen)] }); + // `meta gen`: the web target sits outside the project. + const gen: { files?: readonly RunOutputFile[] | undefined } = {}; + await runGen({ config: config(join(tmp, "web"), gen), metadata: await load(), projectRoot: join(tmp, "project") }); + // `meta verify --codegen`: the same target, moved to a slot inside the regenerated tree. + const verify: { files?: readonly RunOutputFile[] | undefined } = {}; + const slot = join(tmp, "verify", "_web"); + await runGen({ + config: { ...config(slot, verify), outDir: join(tmp, "verify", "gen") }, + metadata: await load(), + projectRoot: join(tmp, "verify"), + untrackedOutDirs: [slot], + }); + expect(gen.files).toEqual([]); + expect(verify.files).toEqual(gen.files); + }); +}); diff --git a/server/typescript/packages/docs-site/README.md b/server/typescript/packages/docs-site/README.md index af95f2c5aa..c3938a9f7a 100644 --- a/server/typescript/packages/docs-site/README.md +++ b/server/typescript/packages/docs-site/README.md @@ -1,8 +1,14 @@ # @metaobjectsdev/docs-site -HTML documentation-site generator for metaobjects models — a browsable multi-page -site (package nav, Cmd+K search, per-object / package / prompt / output pages, and -kind-aware ER diagrams that encode object kind by shape and domain by color). +HTML documentation-site generator for metaobjects models. It builds two sites: + +- **The model explorer** (the default): what the software does, the model map with slices + and colour-by, a page per object, prompt and requirement, the traceability matrix, the + trace, the API index and the gaps, all drawn from one `explorer.json`. See + [`docs/features/explorer-site.md`](../../../../docs/features/explorer-site.md). +- **The classic site** (`site: "classic"`): package nav, Cmd+K search, per-object / package / + prompt / output pages, and kind-aware ER diagrams that encode object kind by shape and + domain by color. It is the engine behind the `docs-site` generator, `docsSiteFile()` from `@metaobjectsdev/codegen-ts/generators` (it was `meta docs --site` until 1.1.0). Output @@ -23,14 +29,20 @@ export default defineConfig({ ``` `meta gen` writes the site to `site/` under the target (`./docs/generated/site/`), beside -whatever other documentation the config lists. Options: `subDir` (default `site`), +whatever other documentation the config lists. Options: `site` (`"explorer"`, the +default, or `"classic"`), `subDir` (default `site`), `prompts` (an extra directory of prompt `.mustache` sources), `title`, `stamp` (footer text; default none, so the pages depend on the model alone and `meta verify --codegen` can check them), `assetBase` (see below) and `target`. ## Offline use: `assetBase` -The page chrome loads five third-party files from jsDelivr (`https://cdn.jsdelivr.net/npm`): +The explorer loads one third-party file, Cytoscape.js, from +`${assetBase}/cytoscape@3.30.2/dist/cytoscape.min.js`, and only on the pages that draw a graph +(the map, the object mini-maps, the trace). Without it every page still renders and the graphs +show a notice. The rest of this section is about the classic site. + +The classic page chrome loads five third-party files from jsDelivr (`https://cdn.jsdelivr.net/npm`): daisyUI's two stylesheets, Tailwind's browser build, Mermaid and svg-pan-zoom. A site opened without network access therefore renders unstyled, and the Mermaid diagrams and pan/zoom do not work. `assetBase` replaces that base in all five tags; the default is unchanged. @@ -60,6 +72,17 @@ packaged copy is what the option fills. ## Usage (as a library) +The explorer: + +```ts +import { buildExplorer, generateExplorerSite, readPromptTexts } from "@metaobjectsdev/docs-site"; + +const explorer = buildExplorer({ model, verify, manifest, routes }); +generateExplorerSite({ explorer, outDir: "docs/site", title: "My Model", texts: readPromptTexts(explorer, ["prompts"]) }); +``` + +The classic site: + ```ts import { generateSite } from "@metaobjectsdev/docs-site"; @@ -72,7 +95,7 @@ await generateSite({ }); ``` -`generateSite` throws if the generated site contains any dangling link. +Both throw if the generated site contains any dangling link. ## Own your docs-site theme @@ -83,8 +106,8 @@ repo: meta eject docs-site ``` -This writes the 9 mustache templates to `codegen/docs-site/templates/` and the CSS/JS -to `codegen/docs-site/assets/` — only files that don't already exist, so your edits are +This writes both sites' mustache templates to `codegen/docs-site/templates/` (the +explorer's are `explorer-*.mustache`) and their CSS/JS to `codegen/docs-site/assets/` — only files that don't already exist, so your edits are never clobbered (`--force` overwrites). Edit them, then regenerate: ``` @@ -95,7 +118,7 @@ meta gen file you didn't override falls back to the bundled default. The engine (`@metaobjectsdev/docs-site`) stays a versioned dependency — you own only the theme. -When calling `generateSite` directly, pass `templatesDir` / `assetsDir` to point at your +When calling `generateSite` or `generateExplorerSite` directly, pass `templatesDir` / `assetsDir` to point at your owned copies (a file of the same basename there wins over the bundled one). ## License diff --git a/server/typescript/packages/docs-site/assets/explorer.css b/server/typescript/packages/docs-site/assets/explorer.css new file mode 100644 index 0000000000..aae678b023 --- /dev/null +++ b/server/typescript/packages/docs-site/assets/explorer.css @@ -0,0 +1,232 @@ +/* The model explorer's theme. `meta eject docs-site` copies this file to + codegen/docs-site/assets/, where an edit wins over the bundled copy. + + Colour rules (design report §4.2), which the classes below keep apart: + .s- a DECLARED status: filled chip, with its glyph in the text + .v- a GATE verdict: an outline (ring), never a fill + .bar .b-* a ROLL-UP of what sits below: a separate stacked bar + No class here colours a test result. */ + +:root { + --bg: #f7f7f5; --panel: #ffffff; --ink: #1d1f23; --muted: #5f6670; --line: #e2e3e0; + --accent: #3b5bdb; --accent-soft: #e8ecfd; --accent-ink: #ffffff; + --live: #2f9e44; --live-soft: #e3f5e7; --partial: #e8890c; --partial-soft: #fdf0dc; + --planned: #4c6ef5; --planned-soft: #e9edff; --retired: #868e96; --retired-soft: #eef0f2; + --bad: #e03131; --bad-soft: #fde8e8; --warn: #e8890c; --code: #f1f2ef; + --entity: #495057; --value: #7048e8; --prompt: #0c8599; --projection: #1971c2; --report: #c2255c; + --shadow: 0 1px 2px rgba(16, 24, 40, .04), 0 1px 3px rgba(16, 24, 40, .06); + --shadow-lift: 0 4px 14px rgba(16, 24, 40, .10); + color-scheme: light; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #15171a; --panel: #1d2024; --ink: #e7e9ec; --muted: #9aa2ab; --line: #2e3238; + --accent: #8da2fb; --accent-soft: #252c47; --accent-ink: #15171a; + --live: #51cf66; --live-soft: #1e3324; --partial: #ffa94d; --partial-soft: #3a2c17; + --planned: #91a7ff; --planned-soft: #232a45; --retired: #adb5bd; --retired-soft: #2a2d31; + --bad: #ff6b6b; --bad-soft: #3a1f1f; --warn: #ffa94d; --code: #24272c; + --entity: #ced4da; --value: #b197fc; --prompt: #3bc9db; --projection: #74c0fc; --report: #f783ac; + --shadow: 0 1px 2px rgba(0, 0, 0, .3); --shadow-lift: 0 4px 14px rgba(0, 0, 0, .45); + color-scheme: dark; + } +} +:root[data-theme="dark"] { + --bg: #15171a; --panel: #1d2024; --ink: #e7e9ec; --muted: #9aa2ab; --line: #2e3238; + --accent: #8da2fb; --accent-soft: #252c47; --accent-ink: #15171a; + --live: #51cf66; --live-soft: #1e3324; --partial: #ffa94d; --partial-soft: #3a2c17; + --planned: #91a7ff; --planned-soft: #232a45; --retired: #adb5bd; --retired-soft: #2a2d31; + --bad: #ff6b6b; --bad-soft: #3a1f1f; --warn: #ffa94d; --code: #24272c; + --entity: #ced4da; --value: #b197fc; --prompt: #3bc9db; --projection: #74c0fc; --report: #f783ac; + --shadow: 0 1px 2px rgba(0, 0, 0, .3); --shadow-lift: 0 4px 14px rgba(0, 0, 0, .45); + color-scheme: dark; +} + +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; } +body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +code, .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12.5px; } +code { background: var(--code); border-radius: 4px; padding: 0 4px; } +code.digest { display: block; overflow-wrap: anywhere; font-size: 11.5px; padding: 4px 6px; } +pre code, .mono code { background: none; padding: 0; } + +/* ── Header ─────────────────────────────────────────────────────────────── */ +header.top { position: sticky; top: 0; z-index: 10; background: var(--panel); border-bottom: 1px solid var(--line); display: flex; gap: 16px; align-items: center; padding: 10px 20px; flex-wrap: wrap; } +.brand { font-weight: 700; letter-spacing: .2px; color: var(--ink); white-space: nowrap; } +.brand:hover { text-decoration: none; } +.brand small { font-weight: 400; color: var(--muted); margin-left: 6px; } +.nav { display: flex; gap: 4px; flex-wrap: wrap; } +.nav a { padding: 5px 10px; border-radius: 6px; color: var(--ink); white-space: nowrap; } +.nav a:hover { background: var(--code); text-decoration: none; } +.nav a.on { background: var(--accent-soft); color: var(--accent); font-weight: 600; } +#search { margin-left: auto; position: relative; } +#search input { width: 260px; max-width: 60vw; padding: 6px 10px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--ink); font: inherit; } +#search input:focus { outline: 2px solid var(--accent-soft); border-color: var(--accent); } +#results { position: absolute; right: 0; top: 36px; width: 420px; max-width: 90vw; max-height: 60vh; overflow: auto; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; box-shadow: var(--shadow-lift); display: none; } +#results a { display: block; padding: 7px 12px; border-bottom: 1px solid var(--line); color: var(--ink); } +#results a:hover, #results a.sel { background: var(--accent-soft); text-decoration: none; } +#results a small { color: var(--muted); display: block; } +#results .none { padding: 8px 12px; color: var(--muted); } +#theme { padding: 5px 9px; } + +/* ── Page ───────────────────────────────────────────────────────────────── */ +main { padding: 24px 20px 20px; max-width: 1400px; margin: 0 auto; } +h1 { font-size: 22px; margin: 0 0 4px; line-height: 1.3; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +h2 { font-size: 16px; margin: 26px 0 10px; } +h3 { font-size: 14px; margin: 16px 0 6px; } +h3.first { margin-top: 0; } +.h-sub { color: var(--muted); font-weight: 400; } +.sub { color: var(--muted); } +.small { font-size: 12px; } +.crumbs { color: var(--muted); font-size: 12.5px; margin-bottom: 6px; } +.meta-line { margin-top: 4px; } +.page { margin-top: 14px; } +.card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; box-shadow: var(--shadow); min-width: 0; } +.grid { display: grid; gap: 12px; } +.tiles { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); margin: 18px 0; } +a.tile { color: var(--ink); transition: box-shadow .15s, border-color .15s, transform .15s; } +a.tile:hover { text-decoration: none; border-color: var(--accent); box-shadow: var(--shadow-lift); transform: translateY(-1px); } +.tile .n { font-size: 26px; font-weight: 700; letter-spacing: -.3px; font-variant-numeric: tabular-nums; } +.tile .l { color: var(--muted); font-size: 12.5px; line-height: 1.4; } +.two { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } +.side { grid-template-columns: minmax(0, 1fr) 340px; align-items: start; } +.apis { grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); } +@media (max-width: 1000px) { .side { grid-template-columns: minmax(0, 1fr); } } +@media (max-width: 900px) { .two { grid-template-columns: minmax(0, 1fr); } } + +table { border-collapse: collapse; width: 100%; } +th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; } +th { font-size: 12px; color: var(--muted); font-weight: 600; } +tr:target td { background: var(--accent-soft); } +table.kv th { width: 120px; } +.tablewrap { overflow-x: auto; } + +/* ── Status, verdict and roll-up ────────────────────────────────────────── */ +.chip { display: inline-flex; align-items: center; gap: 4px; padding: 1px 8px; border-radius: 999px; font-size: 12px; border: 1px solid var(--line); white-space: nowrap; margin: 1px 2px 1px 0; font-weight: 500; line-height: 1.6; } +h1 .chip { font-size: 12.5px; } +.s-live { background: var(--live-soft); color: var(--live); border-color: transparent; } +.s-partial { background: var(--partial-soft); color: var(--partial); border-color: transparent; } +.s-planned { background: var(--planned-soft); color: var(--planned); border-color: transparent; } +.s-retired { background: var(--retired-soft); color: var(--retired); border-color: transparent; text-decoration: line-through; } +.v-error, .v-unclaimed { background: transparent; color: var(--bad); border: 1.5px solid var(--bad); } +.v-warn { background: transparent; color: var(--warn); border: 1.5px solid var(--warn); } +.glyph { font-size: 12px; } +.g-live { color: var(--live); } .g-partial { color: var(--partial); } .g-planned { color: var(--planned); } .g-retired { color: var(--retired); } +.lvl { display: inline-block; min-width: 24px; text-align: center; font-size: 11px; font-weight: 700; border-radius: 4px; background: var(--code); color: var(--muted); padding: 0 4px; margin-right: 6px; line-height: 18px; } +h1 .lvl { font-size: 12px; line-height: 22px; } +.bar { display: flex; height: 8px; border-radius: 4px; overflow: hidden; background: var(--code); min-width: 80px; } +.bar span { display: block; height: 100%; } +.b-live { background: var(--live); } .b-partial { background: var(--partial); } .b-planned { background: var(--planned); } .b-retired { background: var(--retired); } +.minibar { display: inline-block; width: 90px; vertical-align: middle; margin: 0 4px; } +.legend { display: flex; gap: 8px; flex-wrap: wrap; font-size: 12px; color: var(--muted); align-items: center; margin: 4px 0; } +.legend-row { margin: 10px 0; } +.pill { font-size: 11px; color: var(--muted); border: 1px solid var(--line); border-radius: 4px; padding: 0 5px; margin-left: 4px; white-space: nowrap; } +.pill.gate { color: var(--accent); border-color: var(--accent); } +a.k-entity { color: var(--accent); font-weight: 500; } +span.k-entity { color: var(--entity); } .k-value { color: var(--value); } .k-prompt, .k-template { color: var(--prompt); } +.k-projection { color: var(--projection); } .k-report { color: var(--report); } +.kdot { font-size: 10px; } +.kdot.k-entity { color: var(--entity); } .kdot.k-value { color: var(--value); } .kdot.k-prompt { color: var(--prompt); } +.k-badge { color: var(--projection); } +.vals { color: var(--muted); font-size: 11.5px; } + +/* ── S1 cards ───────────────────────────────────────────────────────────── */ +.cap { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; } +.cap .card h3 { margin-top: 0; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.capcard .statement { margin: 2px 0 0; } +.rollup { margin: 10px 0 4px; } +.rollup .sub { margin-top: 3px; } +ul { padding-left: 18px; margin: 6px 0; } +.cap li, .kids li { margin: 4px 0; } +.members { margin-top: 8px; line-height: 1.9; } +details.summary { margin-top: 6px; } +details > summary { cursor: pointer; color: var(--muted); font-size: 12px; } +.note { border-left: 3px solid var(--accent); background: var(--accent-soft); padding: 8px 12px; border-radius: 6px; font-size: 13px; margin: 8px 0; } +.note.intro { margin: 4px 0 8px; font-size: 13.5px; } + +/* ── S5 tree ────────────────────────────────────────────────────────────── */ +.tabs { display: flex; gap: 6px; margin: 12px 0; flex-wrap: wrap; } +.tabs a { padding: 5px 12px; border: 1px solid var(--line); border-radius: 6px; color: var(--ink); background: var(--panel); } +.tabs a.on { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); } +.tree { margin-top: 10px; } +.tree ul { list-style: none; padding-left: 18px; border-left: 1px dashed var(--line); margin-left: 8px; } +.tree > ul { border-left: none; padding-left: 0; margin-left: 0; } +.tree li { margin: 4px 0; } +.tree .row { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; } +.tree .stmt { color: var(--muted); font-size: 12.5px; flex-basis: 100%; margin-left: 30px; } + +/* ── Graphs ─────────────────────────────────────────────────────────────── */ +.graph { width: 100%; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; } +#cy { height: 640px; } #cymini { height: 260px; } #cytrace { height: 680px; } +.panel h3 { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.maplegend { margin-top: 8px; } +.toolbar { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin: 10px 0; } +select, button { padding: 5px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--panel); color: var(--ink); font: inherit; max-width: 100%; } +button { cursor: pointer; } +button:hover { border-color: var(--accent); } +.layout, .gen, .route { margin: 4px 0; } +.gen .pill { margin-left: 0; } + +/* ── S4 text ────────────────────────────────────────────────────────────── */ +pre { background: var(--code); padding: 10px 12px; border-radius: 8px; overflow: auto; font-size: 12px; white-space: pre-wrap; word-break: break-word; } +pre.text { max-height: 560px; } +.var { color: var(--prompt); } + +/* ── S6 proof ───────────────────────────────────────────────────────────── */ +.proof { font-size: 12.5px; } +.proof td:first-child { white-space: nowrap; font-weight: 500; } + +/* ── S7 matrix ──────────────────────────────────────────────────────────── */ +.mx { overflow: auto; max-height: 78vh; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); } +.mx table { width: auto; border-collapse: separate; border-spacing: 0; } +/* The header row is sticky as a whole: a sticky cell per column would paint over the slanted + label of the column before it. */ +.mx thead { position: sticky; top: 0; z-index: 2; background: var(--panel); } +.mx th.col { height: 150px; white-space: nowrap; vertical-align: bottom; padding: 0; } +.mx th.col.corner { position: sticky; left: 0; background: var(--panel); } +.mx th.col div { transform: rotate(-60deg); transform-origin: left bottom; width: 18px; margin-left: 12px; font-weight: 500; font-size: 11.5px; max-width: 18px; } +.mx th.col div a { display: inline-block; max-width: 150px; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom; } +.mx th.col.unc div a { color: var(--bad); } +.mx td.c { width: 20px; min-width: 20px; height: 22px; padding: 0; text-align: center; font-size: 11px; border-right: 1px solid var(--line); } +.mx td.rh { position: sticky; left: 0; background: var(--panel); z-index: 1; border-right: 1px solid var(--line); white-space: nowrap; max-width: 360px; overflow: hidden; text-overflow: ellipsis; font-size: 12px; } +.mx tr.grp td { background: var(--code); font-weight: 600; } +.mx td.c.live { background: var(--live-soft); } .mx td.c.planned { background: var(--planned-soft); } +.mx td.c.partial { background: var(--partial-soft); } .mx td.c.retired { background: var(--retired-soft); } + +/* ── S9 gaps, API ───────────────────────────────────────────────────────── */ +.gap h3 { display: flex; gap: 8px; align-items: center; margin-top: 0; flex-wrap: wrap; } +.gap .why { margin-bottom: 8px; } +.count { font-weight: 700; font-size: 12px; border-radius: 999px; padding: 0 8px; background: var(--code); } +.method { display: inline-block; min-width: 52px; text-align: center; font: 600 11px ui-monospace, SFMono-Regular, Menlo, monospace; border-radius: 4px; padding: 1px 4px; background: var(--code); color: var(--muted); } +.m-GET, .m-get { background: var(--live-soft); color: var(--live); } +.m-POST, .m-post { background: var(--planned-soft); color: var(--planned); } +.m-PUT, .m-put, .m-PATCH, .m-patch { background: var(--partial-soft); color: var(--partial); } +.m-DELETE, .m-delete { background: var(--bad-soft); color: var(--bad); } + +footer { color: var(--muted); font-size: 12px; padding: 24px 20px; text-align: center; } + +/* ── Phone ──────────────────────────────────────────────────────────────── */ +@media (max-width: 700px) { + header.top { gap: 8px 12px; padding: 10px 16px; } + .nav { order: 3; flex-basis: 100%; flex-wrap: nowrap; overflow-x: auto; margin: 0 -16px; padding: 0 16px 2px; scrollbar-width: none; } + .nav::-webkit-scrollbar { display: none; } + #search { order: 4; margin-left: 0; flex-basis: 100%; } + #search input { width: 100%; max-width: none; } + #results { left: 0; right: 0; width: auto; max-width: none; } + #theme { margin-left: auto; } + main { padding: 16px; } + h1 { font-size: 20px; } + .tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } + .tile .n { font-size: 22px; } + .cap { grid-template-columns: minmax(0, 1fr); } + .apis { grid-template-columns: minmax(0, 1fr); } + #cy { height: 440px; } #cytrace { height: 520px; } + .mx { max-height: none; } + /* A wide table scrolls inside its own box, never the page. */ + main table { display: block; max-width: 100%; overflow-x: auto; } + .mx table { display: table; max-width: none; } + .tree .stmt { margin-left: 0; } + .tree ul { padding-left: 12px; margin-left: 4px; } +} +@media print { header.top, #search, #theme, .toolbar { display: none; } .card { box-shadow: none; } } diff --git a/server/typescript/packages/docs-site/assets/explorer.js b/server/typescript/packages/docs-site/assets/explorer.js new file mode 100644 index 0000000000..680dc59d2c --- /dev/null +++ b/server/typescript/packages/docs-site/assets/explorer.js @@ -0,0 +1,315 @@ +// The model explorer's scripts: search, the theme toggle, and the three graphs (the model map, +// an object page's one-hop mini-map, the trace). They read window.MO_EXPLORER, which +// assets/explorer-data.js sets from explorer.json; nothing here derives a model fact. +// `meta eject docs-site` copies this file to codegen/docs-site/assets/. +(function () { + "use strict"; + var D = window.MO_EXPLORER || { nodes: [], edges: [], slices: {}, features: [], reqs: [], generated: {}, search: [] }; + var ROOT = document.body.getAttribute("data-root") || ""; + var $ = function (s, r) { return (r || document).querySelector(s); }; + var esc = function (s) { return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; }); }; + var css = function (v) { return getComputedStyle(document.documentElement).getPropertyValue(v).trim(); }; + var STATUS = ["live", "partial", "planned", "retired"]; + var GLYPH = { live: "●", partial: "◐", planned: "○", retired: "⊘" }; + var PAL = ["#1971c2", "#e8590c", "#2b8a3e", "#ae3ec9", "#c2255c", "#0b7285", "#5c940d", "#f08c00"]; + var byId = {}; + D.nodes.forEach(function (n) { byId[n.id] = n; }); + var reqById = {}; + D.reqs.forEach(function (r) { reqById[r.id] = r; }); + var href = function (rel) { return ROOT + rel; }; + var redraw = []; + + // ── Theme ─────────────────────────────────────────────────────────────── + var themeBtn = $("#theme"); + if (themeBtn) themeBtn.onclick = function () { + var cur = document.documentElement.getAttribute("data-theme"); + var dark = cur ? cur === "dark" : matchMedia("(prefers-color-scheme: dark)").matches; + var next = dark ? "light" : "dark"; + document.documentElement.setAttribute("data-theme", next); + try { localStorage.setItem("mo-theme", next); } catch (e) { /* private window: the toggle still works for this page */ } + redraw.forEach(function (f) { f(); }); + }; + + // ── Search ────────────────────────────────────────────────────────────── + // The built-in index ships in explorer-data.js and works from file://. When the site has been + // indexed with Pagefind (`npx pagefind --site `) and is served over http, Pagefind's + // full-text index answers instead. + var q = $("#q"), res = $("#results"), pagefind = null, pagefindTried = false, sel = -1; + function loadPagefind() { + if (pagefindTried || !/^https?:$/.test(location.protocol)) return Promise.resolve(null); + pagefindTried = true; + // Pagefind takes its base URL from where pagefind.js loads, so loading it from ROOT makes every + // result URL carry the path the site is served under (a sub-path included). + var url = new URL(ROOT + "pagefind/pagefind.js", location.href).href; + return fetch(url, { method: "HEAD" }).then(function (r) { + if (!r.ok) return null; + return import(url).then(function (m) { pagefind = m; return m; }); + }).catch(function () { return null; }); + } + function show(items) { + sel = -1; + res.innerHTML = items.length ? items.map(function (x) { return '' + esc(x.t) + "" + esc(x.s) + ""; }).join("") : '
No match
'; + res.style.display = "block"; + } + function builtIn(v) { + var words = v.split(/\s+/).filter(Boolean); + return D.search.filter(function (x) { return words.every(function (w) { return x.k.indexOf(w) >= 0; }); }) + .sort(function (a, b) { return (a.t.toLowerCase().indexOf(words[0]) === 0 ? 0 : 1) - (b.t.toLowerCase().indexOf(words[0]) === 0 ? 0 : 1); }) + .slice(0, 25).map(function (x) { return { t: x.t, s: x.s, h: href(x.h) }; }); + } + if (q && res) { + q.addEventListener("input", function () { + var v = q.value.trim().toLowerCase(); + if (!v) { res.style.display = "none"; return; } + show(builtIn(v)); + loadPagefind().then(function (pf) { + if (!pf || q.value.trim().toLowerCase() !== v) return; + pf.search(v).then(function (r) { + return Promise.all(r.results.slice(0, 12).map(function (x) { return x.data(); })); + }).then(function (rows) { + if (q.value.trim().toLowerCase() !== v || !rows.length) return; + show(rows.map(function (d) { return { t: (d.meta && d.meta.title) || d.url, s: (d.excerpt || "").replace(/<[^>]+>/g, ""), h: d.url }; })); + }).catch(function () { /* keep the built-in results */ }); + }); + }); + q.addEventListener("keydown", function (e) { + var links = res.querySelectorAll("a"); + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + sel = Math.max(0, Math.min(links.length - 1, sel + (e.key === "ArrowDown" ? 1 : -1))); + links.forEach(function (a, i) { a.classList.toggle("sel", i === sel); }); + } else if (e.key === "Enter" && links.length) { + location.href = links[Math.max(0, sel)].href; + } else if (e.key === "Escape") { res.style.display = "none"; q.blur(); } + }); + document.addEventListener("click", function (e) { if (!$("#search").contains(e.target)) res.style.display = "none"; }); + document.addEventListener("keydown", function (e) { + if (e.key === "/" && document.activeElement !== q && !/^(INPUT|SELECT|TEXTAREA)$/.test(document.activeElement.tagName)) { e.preventDefault(); q.focus(); } + }); + } + + if (typeof window.cytoscape !== "function") { + document.querySelectorAll(".graph").forEach(function (g) { + g.innerHTML = '
The graph library did not load (it comes from the site\'s assetBase). Every node still has its own page.
'; + }); + return; + } + + // ── Colours ───────────────────────────────────────────────────────────── + // Fill: the kind, the feature, or the DECLARED status of the claims on a node. + // Ring: a gate verdict (unclaimed). Never a test result. + function kindColour(n) { + return css({ entity: "--entity", value: "--value", prompt: "--prompt", template: "--prompt", projection: "--projection", report: "--report" }[n.kind] || "--entity"); + } + function fill(n, mode) { + if (n.abstract) return css("--retired"); + if (mode === "kind") return kindColour(n); + if (mode === "api") return n.api.length ? css("--accent") : css("--retired-soft"); + if (mode === "claims") return n.claims > 8 ? css("--live") : n.claims > 2 ? css("--partial") : n.claims > 0 ? css("--planned") : css("--retired-soft"); + if (mode === "cap") return n.feature >= 0 ? PAL[n.feature % PAL.length] : n.quality ? css("--retired") : css("--retired-soft"); + return n.status === "unclaimed" ? css("--retired-soft") : css("--" + n.status); + } + function legend(mode) { + var ring = D.hasClaims ? 'red ring: unclaimed (gate)' : ""; + if (mode === "cap") return '
' + D.features.map(function (f, i) { return '● ' + esc(f.label) + ""; }).join("") + '● qualities only○ no claim' + ring + "Fill is the feature (L1) with the most claims on the node; size is fields plus claims.
"; + if (mode === "status") return '
' + STATUS.map(function (s) { return '' + GLYPH[s] + " " + s + ""; }).join("") + '○ no claim' + ring + "Fill is the best declared status among the requirements that claim the node.
"; + if (mode === "api") return '
● mounted routes○ none
'; + if (mode === "claims") return '
● more than 8 claims● 3 to 8● 1 or 2○ none' + ring + "
"; + return '
' + ["entity", "value", "projection", "report", "prompt"].map(function (k) { return '● ' + k + ""; }).join("") + "Abstract bases are dashed and grey.
"; + } + function shape(n) { return n.kind === "prompt" || n.kind === "template" ? "diamond" : n.kind === "value" ? "round-triangle" : n.kind === "projection" || n.kind === "report" ? "round-hexagon" : n.abstract ? "round-rectangle" : "ellipse"; } + function baseStyle() { + return [ + { selector: "node", style: { "background-color": "data(col)", label: "data(label)", width: "data(size)", height: "data(size)", shape: "data(shape)", color: css("--ink"), "font-size": 10, "text-valign": "bottom", "text-margin-y": 3, "border-width": 1, "border-color": css("--line"), "text-wrap": "none" } }, + { selector: "node[dashed = 1]", style: { "border-style": "dashed", "border-width": 2, "background-opacity": 0.4 } }, + { selector: "node[ring = 1]", style: { "border-width": 3, "border-color": css("--bad") } }, + { selector: "node[faded = 1]", style: { opacity: 0.18 } }, + { selector: "edge", style: { width: 1.2, "line-color": css("--muted"), "target-arrow-color": css("--muted"), "target-arrow-shape": "triangle", "curve-style": "bezier", "arrow-scale": 0.7, opacity: 0.6 } }, + { selector: "edge[ext = 1]", style: { "line-style": "dashed", "target-arrow-shape": "triangle-tee" } }, + { selector: "edge[faded = 1]", style: { opacity: 0.08 } }, + { selector: ":selected", style: { "border-width": 3, "border-color": css("--accent") } }, + ]; + } + var bar = function (c) { + var t = STATUS.reduce(function (a, s) { return a + (c[s] || 0); }, 0); + if (!t) return '
'; + return '
' + STATUS.filter(function (s) { return c[s]; }).map(function (s) { return ''; }).join("") + "
"; + }; + var chip = function (s) { return s ? '' + (GLYPH[s] || "") + " " + esc(s) + "" : ""; }; + var nodeLink = function (id) { var n = byId[id]; return n ? '' + esc(n.name) + "" : esc(id); }; + + // ── S2: the model map ─────────────────────────────────────────────────── + // cose from a grid (not from one point) gives the same picture on every load. + var COSE = { name: "cose", animate: false, randomize: false, nodeRepulsion: 12000, nodeOverlap: 24, idealEdgeLength: 90, componentSpacing: 90, gravity: 0.6, padding: 24, nodeDimensionsIncludeLabels: true }; + function seedGrid(els) { + var nodes = els.filter(function (e) { return !e.data.source; }), cols = Math.ceil(Math.sqrt(nodes.length || 1)); + nodes.forEach(function (e, i) { e.position = { x: (i % cols) * 120, y: Math.floor(i / cols) * 100 }; }); + } + var cyEl = $("#cy"); + if (cyEl) { + var cy = null; + var params = new URLSearchParams(location.search); + var sliceSel = $("#slice"), colourSel = $("#colour"); + if (params.get("slice") && sliceSel.querySelector('option[value="' + CSS.escape(params.get("slice")) + '"]')) sliceSel.value = params.get("slice"); + if (params.get("colour") && colourSel.querySelector('option[value="' + CSS.escape(params.get("colour")) + '"]')) colourSel.value = params.get("colour"); + var focus = params.get("focus"); + var promptSet = function () { + var s = {}; + D.nodes.forEach(function (n) { if (n.kind === "prompt" || n.kind === "template") s[n.id] = 1; }); + D.edges.forEach(function (e) { if (s[e.s] && (e.k === "payload" || e.k === "reply")) s[e.t] = 1; }); + D.edges.forEach(function (e) { if (s[e.s] && byId[e.s] && byId[e.s].kind === "value" && e.k === "objectRef") s[e.t] = 1; }); + return s; + }; + var build = function (relayout) { + var slice = sliceSel.value, mode = colourSel.value, hide = $("#hideOut").checked, showExt = $("#showExt").checked; + $("#maplegend").innerHTML = legend(mode); + var inSlice = null; + if (slice === "@prompts") inSlice = promptSet(); + else if (slice && D.slices[slice]) { inSlice = {}; D.slices[slice].forEach(function (id) { inSlice[id] = 1; }); } + var showVals = $("#showValues").checked || slice === "@prompts" || (inSlice && Object.keys(inSlice).some(function (id) { return byId[id] && byId[id].kind !== "entity"; })); + var entityCount = D.nodes.filter(function (n) { return n.kind === "entity"; }).length; + if (!entityCount) showVals = true; + var nodes = D.nodes.filter(function (n) { return (n.kind === "entity" || showVals) && (!hide || !inSlice || inSlice[n.id]); }); + var ids = {}; + nodes.forEach(function (n) { ids[n.id] = 1; }); + var els = nodes.map(function (n) { + return { data: { id: n.id, label: n.name, col: fill(n, mode), size: 18 + Math.min(40, n.fields * 1.6 + n.claims * 2), shape: shape(n), faded: inSlice && !inSlice[n.id] ? 1 : 0, dashed: n.abstract, ring: n.unclaimed } }; + }); + D.edges.forEach(function (e, i) { + if (!ids[e.s] || !ids[e.t] || (!showExt && e.k === "extends")) return; + els.push({ data: { id: "e" + i, source: e.s, target: e.t, label: e.v || e.k, ext: e.k === "extends" ? 1 : 0, faded: inSlice && !(inSlice[e.s] && inSlice[e.t]) ? 1 : 0 } }); + }); + seedGrid(els); + var pan = cy && !relayout ? { pos: {} } : null; + if (pan) cy.nodes().forEach(function (n) { pan.pos[n.id()] = n.position(); }); + if (cy) cy.destroy(); + var keep = pan && els.every(function (el) { return el.data.source || pan.pos[el.data.id]; }); + cy = cytoscape({ + container: cyEl, elements: els, wheelSensitivity: 0.3, maxZoom: 1.5, style: baseStyle(), + layout: keep ? { name: "preset", positions: function (n) { return pan.pos[n.id()]; }, fit: true, padding: 20 } : COSE, + }); + cy.on("tap", "node", function (ev) { showPanel(ev.target.id()); }); + cy.on("dbltap", "node", function (ev) { var n = byId[ev.target.id()]; if (n) location.href = href(n.href); }); + var sliceReq = slice.indexOf("requirement:") === 0 ? reqById[slice.slice("requirement:".length)] : null; + if (sliceReq) $("#panel").innerHTML = slicePanel(sliceReq, D.slices[slice] || []); + if (focus && byId[focus] && cy.getElementById(focus).length) { cy.getElementById(focus).select(); showPanel(focus); focus = null; } + var u = new URL(location.href); + if (slice) u.searchParams.set("slice", slice); else u.searchParams.delete("slice"); + u.searchParams.set("colour", mode); + history.replaceState(null, "", u.search ? u.pathname + u.search : u.pathname); + }; + ["#slice", "#colour", "#hideOut", "#showValues", "#showExt"].forEach(function (s) { $(s).onchange = function () { build(false); }; }); + $("#relayout").onclick = function () { if (cy) cy.layout(Object.assign({}, COSE, { randomize: true })).run(); }; + redraw.push(function () { build(false); }); + build(true); + } + function slicePanel(r, nodes) { + return '
Slice

' + (r.level ? "L" + r.level : "—") + '' + esc(r.label) + " " + chip(r.status) + "

" + esc(r.statement) + "
" + + "

" + r.claimed + " model node" + (r.claimed === 1 ? "" : "s") + " claimed below

" + nodes.map(nodeLink).join(", ") + + "

Status below

" + bar(r.rollup); + } + function showPanel(id) { + var n = byId[id], p = $("#panel"); + if (!n || !p) return; + var claims = D.reqs.filter(function (r) { return r.targets.indexOf(id) >= 0; }); + var byTop = {}; + claims.forEach(function (r) { var t = r; while (t.parent && reqById[t.parent]) t = reqById[t.parent]; (byTop[t.id] = byTop[t.id] || []).push(r); }); + var refs = D.edges.filter(function (e) { return e.s === id || e.t === id; }).length; + var gen = (D.generated[id] || []).map(function (g) { return '' + esc(g[0]) + " " + g[1]; }).join(" · "); + p.innerHTML = '
' + esc(n.pkg) + " · " + esc(n.kind) + (n.storage ? " · " + esc(n.storage) : "") + "
" + + '

' + nodeLink(id) + (n.unclaimed ? ' unclaimed' : "") + "

" + + "

Why it exists (" + claims.length + " claim" + (claims.length === 1 ? "" : "s") + ")

" + + (claims.length ? Object.keys(byTop).map(function (t) { + return "
" + esc(reqById[t].label) + ": " + byTop[t].slice(0, 6).map(function (r) { return '' + (GLYPH[r.status] || "") + " " + esc(r.label) + ""; }).join(", ") + (byTop[t].length > 6 ? " +" + (byTop[t].length - 6) : "") + "
"; + }).join("") : 'No requirement claims this node.') + + "

Shape

" + n.fields + " field" + (n.fields === 1 ? "" : "s") + ", " + refs + " reference" + (refs === 1 ? "" : "s") + + (n.api.length ? "

API

" + n.api.map(function (a) { return "
" + esc(a) + "
"; }).join("") : "") + + "

Generated

" + (gen || 'nothing traced'); + } + + // ── S3: the one-hop mini-map ──────────────────────────────────────────── + var mini = $("#cymini"); + if (mini) { + var me = mini.getAttribute("data-node"); + var drawMini = function () { + var es = D.edges.filter(function (e) { return e.s === me || e.t === me; }); + var ids = {}; + ids[me] = 1; + es.forEach(function (e) { ids[e.s] = 1; ids[e.t] = 1; }); + var els = Object.keys(ids).filter(function (id) { return byId[id]; }).sort().map(function (id) { + var n = byId[id]; + return { data: { id: id, label: n.name, col: fill(n, D.hasClaims ? "status" : "kind"), me: id === me ? 1 : 0, ring: n.unclaimed, shape: shape(n) } }; + }).concat(es.map(function (e, i) { return { data: { id: "m" + i, source: e.s, target: e.t, label: e.v || e.k } }; })); + mini.innerHTML = ""; + var c = cytoscape({ + container: mini, elements: els, maxZoom: 1.3, + style: [ + { selector: "node", style: { "background-color": "data(col)", label: "data(label)", shape: "data(shape)", "font-size": 10, color: css("--ink"), "text-valign": "bottom", "text-margin-y": 2, width: 18, height: 18, "border-width": 1, "border-color": css("--line") } }, + { selector: "node[ring = 1]", style: { "border-width": 3, "border-color": css("--bad") } }, + { selector: "node[me = 1]", style: { width: 30, height: 30, "border-width": 3, "border-color": css("--accent") } }, + { selector: "edge", style: { width: 1, label: "data(label)", "font-size": 8, color: css("--muted"), "line-color": css("--muted"), "target-arrow-shape": "triangle", "target-arrow-color": css("--muted"), "curve-style": "bezier", "text-rotation": "autorotate", "text-background-color": css("--panel"), "text-background-opacity": 1, "text-background-padding": 2 } }, + ], + layout: { name: "concentric", concentric: function (n) { return n.data("me") ? 2 : 1; }, levelWidth: function () { return 1; }, startAngle: Math.PI, padding: 30, minNodeSpacing: 60 }, + }); + c.on("tap", "node", function (ev) { var n = byId[ev.target.id()]; if (n && n.id !== me) location.href = href(n.href); }); + }; + redraw.push(drawMini); + drawMini(); + } + + // ── S8: the trace ─────────────────────────────────────────────────────── + var tr = $("#cytrace"), tstart = $("#tstart"); + if (tr && tstart) { + var p2 = new URLSearchParams(location.search).get("start"); + if (p2 && reqById[p2]) tstart.value = p2; + var drawTrace = function () { + var r0 = reqById[tstart.value]; + if (!r0) return; + var kids = {}; + D.reqs.forEach(function (r) { if (r.parent) (kids[r.parent] = kids[r.parent] || []).push(r); }); + var reqs = [], walk = function (r) { reqs.push(r); (kids[r.id] || []).forEach(walk); }; + walk(r0); + var cols = [[], [], [], []], els = [], seen = {}; + var add = function (id, label, col, data) { if (seen[id]) return; seen[id] = 1; cols[col].push(id); data.id = id; data.label = label; els.push({ data: data }); }; + reqs.forEach(function (r) { add("r:" + r.id, (r.level ? "L" + r.level + " " : "") + r.label, r.level >= 4 ? 1 : 0, { col: r.status ? css("--" + r.status) : css("--muted"), shape: "round-rectangle", go: r.href }); }); + reqs.forEach(function (r) { if (r.parent && seen["r:" + r.parent]) els.push({ data: { id: "pe:" + r.id, source: "r:" + r.parent, target: "r:" + r.id } }); }); + reqs.forEach(function (r) { + r.targets.forEach(function (t) { + var n = byId[t]; + if (!n) return; + add("o:" + t, n.name, 2, { col: kindColour(n), shape: shape(n), go: n.href, ring: n.unclaimed }); + if (!seen["le:" + r.id + ">" + t]) { seen["le:" + r.id + ">" + t] = 1; els.push({ data: { id: "le:" + r.id + ">" + t, source: "r:" + r.id, target: "o:" + t, col: r.status ? css("--" + r.status) : css("--muted") } }); } + }); + }); + cols[2].slice().forEach(function (oid) { + var id = oid.slice(2); + var gen = D.generated[id] || []; + if (!gen.length) return; + var total = gen.reduce(function (a, g) { return a + g[1]; }, 0); + var gid = "g:" + id; + add(gid, total + " generated (" + gen.map(function (g) { return g[0]; }).join(", ") + ")", 3, { col: css("--accent"), shape: "tag", go: byId[id].href }); + els.push({ data: { id: "ge:" + gid, source: oid, target: gid } }); + }); + var pos = {}; + cols.forEach(function (c, ci) { c.forEach(function (id, i) { pos[id] = { x: ci * 260, y: (i - c.length / 2) * 26 }; }); }); + tr.innerHTML = ""; + var c = cytoscape({ + container: tr, elements: els, wheelSensitivity: 0.3, maxZoom: 1.6, + style: [ + { selector: "node", style: { "background-color": "data(col)", label: "data(label)", shape: "data(shape)", "font-size": 11, color: css("--ink"), "text-halign": "right", "text-valign": "center", "text-margin-x": 6, width: 12, height: 12 } }, + { selector: "node[ring = 1]", style: { "border-width": 2, "border-color": css("--bad") } }, + { selector: "edge", style: { width: 1, "line-color": "data(col)", opacity: 0.5, "curve-style": "unbundled-bezier" } }, + { selector: "edge[!col]", style: { "line-color": css("--muted") } }, + ], + layout: { name: "preset", positions: function (n) { return pos[n.id()]; }, fit: true, padding: 24 }, + }); + c.on("tap", "node", function (ev) { var go = ev.target.data("go"); if (go) location.href = href(go); }); + }; + tstart.onchange = function () { + var u = new URL(location.href); u.searchParams.set("start", tstart.value); history.replaceState(null, "", u.pathname + u.search); + drawTrace(); + }; + redraw.push(drawTrace); + drawTrace(); + } +})(); diff --git a/server/typescript/packages/docs-site/package.json b/server/typescript/packages/docs-site/package.json index a559b1c5e1..3c3129bb1c 100644 --- a/server/typescript/packages/docs-site/package.json +++ b/server/typescript/packages/docs-site/package.json @@ -1,7 +1,7 @@ { "name": "@metaobjectsdev/docs-site", "version": "1.2.0", - "description": "HTML documentation-site generator for metaobjects models — a browsable multi-page site (nav, search, per-object/package pages, kind-aware ER diagrams). Powers the `docs-site` generator (`docsSiteFile()`).", + "description": "HTML documentation-site generator for metaobjects models — a model explorer (what the software does, model map, requirement pages, matrix, trace, gaps) and a classic multi-page site with kind-aware ER diagrams. Powers the `docs-site` generator (`docsSiteFile()`).", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/server/typescript/packages/docs-site/src/explorer/build.ts b/server/typescript/packages/docs-site/src/explorer/build.ts index f7918becf0..344fbc4afd 100644 --- a/server/typescript/packages/docs-site/src/explorer/build.ts +++ b/server/typescript/packages/docs-site/src/explorer/build.ts @@ -51,6 +51,7 @@ import { type ExplorerLedger, type ExplorerLedgerRow, type ExplorerNode, + type ExplorerRoute, type ExplorerSlice, } from "./types.js"; @@ -62,6 +63,9 @@ export interface ExplorerInput { verify?: unknown; /** Parsed `.metaobjects/.gen-state/.hashes.json`. Without it there is no `generated`. */ manifest?: unknown; + /** The routes the project mounts: `[{ node, method, path }]`, one per route, `node` a node + * id. A route whose node is not in the model is dropped. Without it there is no `api`. */ + routes?: unknown; } const ROOT_KEY = `${TYPE_METADATA}${TYPE_SUBTYPE_SEPARATOR}${SUBTYPE_ROOT}`; @@ -157,6 +161,7 @@ function walkModel(model: unknown): Walked[] { subType: child.subType, name, package: pkg, + order: index, ...(parent !== undefined ? { parent: parent.node.id } : {}), ...(typeof ext === "string" && ext !== "" ? { extends: nodeIdOf(ext) } : {}), ...(child.body[RESERVED_KEY_ABSTRACT] === true ? { abstract: true as const } : {}), @@ -241,7 +246,7 @@ function modelEdges(walked: Walked[], byId: Map): ExplorerEdge[] function asLinks(v: unknown): { ref: string; resolves: boolean; target?: string }[] { if (!Array.isArray(v)) return []; - return v.filter(isRecord).map(asLink).filter((l): l is NonNullable => l !== undefined); + return v.map(asLink).filter((l): l is NonNullable => l !== undefined); } function asLink(v: unknown): { ref: string; resolves: boolean; target?: string } | undefined { @@ -266,6 +271,7 @@ function ledgerFrom(verify: unknown, byId: Map, edges: ExplorerE code: String(d.code ?? ""), severity: String(d.severity ?? ""), source: String(d.source ?? ""), + message: String(d.message ?? ""), })) : []; rows.push({ @@ -316,6 +322,18 @@ function generatedFrom(manifest: unknown): ExplorerGenerated[] | undefined { })); } +function routesFrom(routes: unknown, byId: Map): ExplorerRoute[] | undefined { + if (!Array.isArray(routes)) return undefined; + const seen = new Map(); + for (const r of routes) { + if (!isRecord(r) || typeof r.node !== "string" || typeof r.method !== "string" || typeof r.path !== "string") continue; + if (!byId.has(r.node)) continue; + const route: ExplorerRoute = { node: r.node, method: r.method.toUpperCase(), path: r.path }; + seen.set(`${route.node}\u0000${route.path}\u0000${route.method}`, route); + } + return [...seen.keys()].sort(byCodeUnit).map((k) => seen.get(k) as ExplorerRoute); +} + function derivedSlices(walked: Walked[], byId: Map, edges: ExplorerEdge[]): ExplorerSlice[] { const slices: ExplorerSlice[] = []; const ownerOf = (id: string): string => byId.get(id)?.owner ?? id; @@ -381,12 +399,13 @@ export function buildExplorer(input: ExplorerInput): ExplorerJson { const edges = modelEdges(walked, byId); const ledger = input.verify !== undefined ? ledgerFrom(input.verify, byId, edges) : undefined; const generated = input.manifest !== undefined ? generatedFrom(input.manifest) : undefined; + const api = input.routes !== undefined ? routesFrom(input.routes, byId) : undefined; // One edge per (kind, from, to, via): an object can reach one target twice through two // members, which is two edges, but never the same edge twice. const unique = new Map(); for (const e of edges) unique.set(edgeKey(e), e); - const sortedEdges = [...unique.values()].sort((a, b) => byCodeUnit(edgeKey(a), edgeKey(b))); + const sortedEdges = [...unique].sort(([a], [b]) => byCodeUnit(a, b)).map(([, e]) => e); return { format: EXPLORER_FORMAT, @@ -394,6 +413,7 @@ export function buildExplorer(input: ExplorerInput): ExplorerJson { edges: sortedEdges, ...(ledger !== undefined ? { ledger } : {}), ...(generated !== undefined ? { generated } : {}), + ...(api !== undefined ? { api } : {}), slices: derivedSlices(walked, byId, sortedEdges), }; } diff --git a/server/typescript/packages/docs-site/src/explorer/html.ts b/server/typescript/packages/docs-site/src/explorer/html.ts new file mode 100644 index 0000000000..278824a70a --- /dev/null +++ b/server/typescript/packages/docs-site/src/explorer/html.ts @@ -0,0 +1,85 @@ +// HTML fragments the explorer pages share: status chips, level badges, roll-up bars, links. +// +// The colour rules are design report §4.2, and every fragment here keeps them apart: +// - a requirement's DECLARED status is a filled chip plus a glyph (● ◐ ○ ⊘), so it reads +// without colour; +// - a GATE verdict (a finding on a requirement, an unclaimed entity) is an outlined badge or a +// ring, never a fill; +// - a ROLL-UP of the statuses below is a separate stacked bar, and never repaints the chip. +// Nothing here colours a test result: the build does not read one. + +import { REQUIREMENT_ATTR_DISPOSITION } from "@metaobjectsdev/metadata"; +import { STATUSES, STATUS_GLYPH, type ReqEntry, type Rollup } from "./index-model.js"; + +export function esc(s: unknown): string { + return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!); +} + +/** A declared status: a filled chip with its glyph. */ +export function statusChip(status: string): string { + if (status === "") return ""; + return `${STATUS_GLYPH[status] ?? ""} ${esc(status)}`; +} + +/** A declared status as its glyph alone, in the status colour (child lists, matrix cells). */ +export function statusGlyph(status: string): string { + if (status === "") return ""; + return `${STATUS_GLYPH[status] ?? ""}`; +} + +/** The level badge: `L3`, or `—` for a flat architectural policy. */ +export function levelBadge(r: ReqEntry): string { + return r.level !== undefined + ? `L${r.level}` + : `—`; +} + +/** The `source` a verify finding carries when it can fail the build; anything else is an + * authoring advisory, which never can. */ +export const GATE_SOURCE = "gate"; + +/** A gate verdict as an outlined badge: `error` or `warn`, with the finding codes. Authoring + * advisories never reach it. */ +export function verdictBadge(r: ReqEntry): string { + const gate = (r.row?.diagnostics ?? []).filter((d) => d.source === GATE_SOURCE); + if (gate.length === 0) return ""; + const worst = gate.some((d) => d.severity === "error") ? "error" : "warn"; + const codes = gate.map((d) => d.code).join(", "); + const n = gate.length; + return `${worst === "error" ? "✕" : "!"} ${n} gate ${worst === "error" ? (n === 1 ? "error" : "errors") : n === 1 ? "warning" : "warnings"}`; +} + +/** The disposition pill (`accepted`, `deferred`). */ +export function dispositionPill(r: ReqEntry): string { + const d = r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]; + return typeof d === "string" ? `${esc(d)}` : ""; +} + +/** The roll-up: a stacked bar of the declared statuses below, drawn apart from any chip. */ +export function rollupBar(c: Rollup): string { + const total = STATUSES.reduce((a, s) => a + (c[s] ?? 0), 0); + const title = STATUSES.filter((s) => (c[s] ?? 0) > 0).map((s) => `${c[s]} ${s}`).join(", "); + if (total === 0) return `
`; + const spans = STATUSES.filter((s) => (c[s] ?? 0) > 0) + .map((s) => ``) + .join(""); + return ``; +} + +/** A width that prints the same on every run and every platform. */ +function pct(x: number): string { + return `${(Math.round(x * 10000) / 100).toString()}%`; +} + +/** The legend every requirement view carries. */ +export function legendHtml(withUnclaimed: boolean): string { + const chips = STATUSES.map((s) => statusChip(s)).join(""); + const unclaimed = withUnclaimed ? `unclaimed` : ""; + return `
${chips}${unclaimed}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`; +} + +/** A path from one page to another, both relative to the site root. */ +export function relHref(fromPage: string, toPage: string): string { + const depth = fromPage.split("/").length - 1; + return "../".repeat(depth) + toPage; +} diff --git a/server/typescript/packages/docs-site/src/explorer/index-model.ts b/server/typescript/packages/docs-site/src/explorer/index-model.ts new file mode 100644 index 0000000000..6b1014a831 --- /dev/null +++ b/server/typescript/packages/docs-site/src/explorer/index-model.ts @@ -0,0 +1,343 @@ +// An in-memory index over one `explorer.json`: the lookups every explorer page shares. +// +// It reads the document and nothing else. A view asks this index; it never walks the loader, so +// what a page shows is exactly what the data spine states (design report §3.1, "views never +// re-derive model facts"). The only arithmetic here is the explorer's own: the roll-up of the +// statuses below a requirement, which §4.2 calls computable and ungated, and which a page shows +// as a separate bar, never as the requirement's colour. + +import { + OBJECT_SUBTYPE_ENTITY, + OBJECT_SUBTYPE_PROJECTION, + OBJECT_SUBTYPE_REPORT, + OBJECT_SUBTYPE_VALUE, + SOURCE_ATTR_KIND, + SOURCE_ATTR_TABLE, + SOURCE_ATTR_VIEW, + SOURCE_KIND_VIEW, + TEMPLATE_SUBTYPE_PROMPT, + TYPE_FIELD, + TYPE_OBJECT, + TYPE_REQUIREMENT, + TYPE_SOURCE, + TYPE_TEMPLATE, +} from "@metaobjectsdev/metadata/constants"; +import { + REQUIREMENT_ATTR_LEVEL, + REQUIREMENT_ATTR_STATUS, + REQUIREMENT_SUBTYPE_ARCHITECTURAL, + REQUIREMENT_SUBTYPE_FUNCTIONAL, + REQUIREMENT_STATUSES, + REQUIREMENT_STATUS_LIVE, + REQUIREMENT_STATUS_PARTIAL, + REQUIREMENT_STATUS_PLANNED, + REQUIREMENT_STATUS_RETIRED, +} from "@metaobjectsdev/metadata"; +import type { ExplorerEdge, ExplorerGeneratedFile, ExplorerJson, ExplorerLedgerRow, ExplorerNode, ExplorerRoute, ExplorerSlice } from "./types.js"; + +/** The four declared statuses, in the order every bar and legend draws them: live first, since + * it is the claim a reader looks for, and the bar reads left to right as "done". */ +export const STATUSES: readonly string[] = [ + REQUIREMENT_STATUS_LIVE, + REQUIREMENT_STATUS_PARTIAL, + REQUIREMENT_STATUS_PLANNED, + REQUIREMENT_STATUS_RETIRED, +].filter((s) => (REQUIREMENT_STATUSES as readonly string[]).includes(s)); +const STATUS_ORDER = STATUSES; + +/** The glyph for each status, so the colour is never the only signal (§4.2). */ +export const STATUS_GLYPH: Readonly> = { + [REQUIREMENT_STATUS_LIVE]: "●", + [REQUIREMENT_STATUS_PARTIAL]: "◐", + [REQUIREMENT_STATUS_PLANNED]: "○", + [REQUIREMENT_STATUS_RETIRED]: "⊘", +}; + +/** Edges drawn between model nodes on the map and the mini-maps. */ +export const MODEL_EDGE_KINDS: readonly string[] = ["references", "association", "objectRef", "payload", "reply", "extends"]; + +const byCodeUnit = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0); + +/** One requirement as the pages read it: the node, its ledger row, its place in the tree. */ +export interface ReqEntry { + node: ExplorerNode; + row?: ExplorerLedgerRow; + parent?: ReqEntry; + children: ReqEntry[]; + level?: number; + status: string; + /** functional | architectural */ + kind: string; +} + +/** A requirement's claim on a model node, as the ledger resolved it. */ +export interface Claim { + req: ReqEntry; + /** The member path when the claim names a member (`Order.reference`), else undefined. */ + member?: string; +} + +export type Rollup = Record; + +export class ExplorerIndex { + readonly doc: ExplorerJson; + readonly byId = new Map(); + private readonly kids = new Map(); + /** Top-level object nodes (entity, value, projection, report, …), by id. */ + readonly objects: ExplorerNode[] = []; + /** Top-level template nodes (prompt, output, …), by id. */ + readonly templates: ExplorerNode[] = []; + /** Every requirement, in document order (the ledger's order when there is one). */ + readonly requirements: ReqEntry[] = []; + readonly reqById = new Map(); + /** The top of each requirement tree, in document order. */ + readonly topRequirements: ReqEntry[] = []; + private readonly claimsOn = new Map(); + private readonly generatedOf = new Map(); + private readonly routesOf = new Map(); + readonly packages: string[]; + + constructor(doc: ExplorerJson) { + this.doc = doc; + for (const n of doc.nodes) this.byId.set(n.id, n); + for (const n of doc.nodes) { + if (n.parent === undefined) continue; + const list = this.kids.get(n.parent) ?? []; + list.push(n); + this.kids.set(n.parent, list); + } + for (const list of this.kids.values()) list.sort((a, b) => a.order - b.order || byCodeUnit(a.id, b.id)); + for (const n of doc.nodes) { + if (n.parent !== undefined) continue; + if (n.type === TYPE_OBJECT) this.objects.push(n); + else if (n.type === TYPE_TEMPLATE) this.templates.push(n); + } + this.packages = [...new Set(doc.nodes.filter((n) => n.parent === undefined).map((n) => n.package))].sort(byCodeUnit); + this.indexRequirements(); + for (const e of doc.edges) { + if (e.kind !== "implementedBy") continue; + const req = this.reqById.get(e.from); + if (req === undefined) continue; + const owner = this.ownerOf(e.to); + const member = owner === e.to ? undefined : e.to.slice(owner.length + 1); + const list = this.claimsOn.get(owner) ?? []; + list.push({ req, ...(member !== undefined ? { member } : {}) }); + this.claimsOn.set(owner, list); + } + for (const g of doc.generated ?? []) this.generatedOf.set(g.node, g.files); + for (const r of doc.api ?? []) { + const list = this.routesOf.get(r.node) ?? []; + list.push(r); + this.routesOf.set(r.node, list); + } + } + + private indexRequirements(): void { + const rows = new Map((this.doc.ledger?.rows ?? []).map((r) => [r.node, r] as const)); + const reqNodes = this.doc.nodes.filter((n) => n.type === TYPE_REQUIREMENT); + // Document order: the ledger's when there is one (the verify payload walks the model in + // declaration order), else each node's sibling order under its parent. + const ledgerOrder = new Map((this.doc.ledger?.rows ?? []).map((r, i) => [r.node, i] as const)); + const depthFirst: ExplorerNode[] = []; + const visit = (n: ExplorerNode): void => { + depthFirst.push(n); + for (const c of this.children(n.id)) if (c.type === TYPE_REQUIREMENT) visit(c); + }; + const tops = reqNodes + .filter((n) => n.parent === undefined || this.byId.get(n.parent)?.type !== TYPE_REQUIREMENT) + .sort((a, b) => (ledgerOrder.get(a.id) ?? Infinity) - (ledgerOrder.get(b.id) ?? Infinity) || a.order - b.order || byCodeUnit(a.id, b.id)); + for (const t of tops) visit(t); + for (const n of depthFirst) { + const row = rows.get(n.id); + const level = typeof n.attrs[REQUIREMENT_ATTR_LEVEL] === "number" ? (n.attrs[REQUIREMENT_ATTR_LEVEL] as number) : row?.level; + const status = typeof n.attrs[REQUIREMENT_ATTR_STATUS] === "string" ? (n.attrs[REQUIREMENT_ATTR_STATUS] as string) : (row?.status ?? ""); + const parent = n.parent !== undefined ? this.reqById.get(n.parent) : undefined; + const entry: ReqEntry = { + node: n, + ...(row !== undefined ? { row } : {}), + ...(parent !== undefined ? { parent } : {}), + children: [], + ...(level !== undefined ? { level } : {}), + status, + kind: n.subType, + }; + this.requirements.push(entry); + this.reqById.set(n.id, entry); + if (parent !== undefined) parent.children.push(entry); + else this.topRequirements.push(entry); + } + } + + /** Direct children of a node, in declaration order. */ + children(id: string): ExplorerNode[] { + return this.kids.get(id) ?? []; + } + + /** The top-level node a node sits under (itself at the top). */ + ownerOf(id: string): string { + let cur = this.byId.get(id); + while (cur?.parent !== undefined) cur = this.byId.get(cur.parent); + return cur?.id ?? id; + } + + fields(id: string): ExplorerNode[] { + return this.children(id).filter((c) => c.type === TYPE_FIELD); + } + + /** The node's `source.*` child, when it declares one. */ + source(id: string): ExplorerNode | undefined { + return this.children(id).find((c) => c.type === TYPE_SOURCE); + } + + /** `table x`, `view v_x`, or undefined: what the source declares, never a derived name. */ + storage(id: string): { kind: "table" | "view"; name?: string } | undefined { + const s = this.source(id); + if (s === undefined) return undefined; + const view = s.attrs[SOURCE_ATTR_VIEW]; + const table = s.attrs[SOURCE_ATTR_TABLE]; + const isView = s.attrs[SOURCE_ATTR_KIND] === SOURCE_KIND_VIEW || typeof view === "string"; + const name = typeof view === "string" ? view : typeof table === "string" ? table : undefined; + return { kind: isView ? "view" : "table", ...(name !== undefined ? { name } : {}) }; + } + + isEntity(n: ExplorerNode): boolean { + return n.type === TYPE_OBJECT && n.subType === OBJECT_SUBTYPE_ENTITY; + } + + isPrompt(n: ExplorerNode): boolean { + return n.type === TYPE_TEMPLATE && n.subType === TEMPLATE_SUBTYPE_PROMPT; + } + + /** The kind a page and the map name a top-level node by. */ + kindOf(n: ExplorerNode): "entity" | "value" | "projection" | "report" | "prompt" | "template" | "object" { + if (n.type === TYPE_TEMPLATE) return n.subType === TEMPLATE_SUBTYPE_PROMPT ? "prompt" : "template"; + if (n.subType === OBJECT_SUBTYPE_ENTITY) return "entity"; + if (n.subType === OBJECT_SUBTYPE_VALUE) return "value"; + if (n.subType === OBJECT_SUBTYPE_PROJECTION) return "projection"; + if (n.subType === OBJECT_SUBTYPE_REPORT) return "report"; + return "object"; + } + + /** Concrete stored entities: `object.entity`, not abstract. */ + storedEntities(): ExplorerNode[] { + return this.objects.filter((o) => this.isEntity(o) && o.abstract !== true); + } + + claims(id: string): Claim[] { + return this.claimsOn.get(id) ?? []; + } + + generated(id: string): ExplorerGeneratedFile[] { + return this.generatedOf.get(id) ?? []; + } + + routes(id: string): ExplorerRoute[] { + return this.routesOf.get(id) ?? []; + } + + hasRequirements(): boolean { + return this.requirements.length > 0; + } + + /** Whether any requirement claims anything: object coverage only means something then. */ + hasClaims(): boolean { + return this.claimsOn.size > 0; + } + + /** The requirement and every requirement below it, depth first. */ + subtree(r: ReqEntry): ReqEntry[] { + const out: ReqEntry[] = []; + const walk = (x: ReqEntry): void => { + out.push(x); + for (const c of x.children) walk(c); + }; + walk(r); + return out; + } + + below(r: ReqEntry): ReqEntry[] { + return this.subtree(r).slice(1); + } + + /** The declared statuses of the entries below that name the model (L4, L5, or a flat + * architectural policy with links), counted. A leaf counts itself. */ + rollup(r: ReqEntry): Rollup { + const linked = this.subtree(r).filter((x) => (x.level ?? 0) >= 4 || (x.level === undefined && (x.row?.implementedBy.length ?? 0) > 0)); + const counted = linked.length > 0 ? linked : [r]; + const c: Rollup = {}; + for (const x of counted) if (x.status !== "") c[x.status] = (c[x.status] ?? 0) + 1; + return c; + } + + /** The model nodes the subtree claims (owners, deduplicated, sorted). */ + targetsOf(r: ReqEntry): string[] { + const set = new Set(); + for (const x of this.subtree(r)) { + for (const l of x.row?.implementedBy ?? []) if (l.target !== undefined && this.byId.has(l.target)) set.add(this.ownerOf(l.target)); + } + return [...set].sort(byCodeUnit); + } + + /** The ledger's gate verdict for a requirement: "error" | "warn" | "clean" | "". */ + verdict(r: ReqEntry): string { + return r.row?.verdict ?? ""; + } + + /** The L1 feature (functional top) with the most claims on a node, by document order on a tie. */ + featureOf(id: string): ReqEntry | undefined { + const count = new Map(); + for (const c of this.claims(id)) { + let top = c.req; + while (top.parent !== undefined) top = top.parent; + if (top.kind !== REQUIREMENT_SUBTYPE_FUNCTIONAL) continue; + count.set(top, (count.get(top) ?? 0) + 1); + } + let best: ReqEntry | undefined; + for (const t of this.features()) { + const n = count.get(t) ?? 0; + if (n > 0 && (best === undefined || n > (count.get(best) ?? 0))) best = t; + } + return best; + } + + features(): ReqEntry[] { + return this.topRequirements.filter((r) => r.kind === REQUIREMENT_SUBTYPE_FUNCTIONAL); + } + + qualities(): ReqEntry[] { + return this.topRequirements.filter((r) => r.kind === REQUIREMENT_SUBTYPE_ARCHITECTURAL); + } + + /** The best declared status among a node's claims, or "unclaimed". */ + claimStatus(id: string): string { + const cl = this.claims(id); + if (cl.length === 0) return "unclaimed"; + for (const s of STATUS_ORDER) if (cl.some((c) => c.req.status === s)) return s; + return "unclaimed"; + } + + /** Model edges between two top-level nodes (a member's edge is drawn from its owner). */ + modelEdges(): ExplorerEdge[] { + const out: ExplorerEdge[] = []; + const seen = new Set(); + for (const e of this.doc.edges) { + if (!MODEL_EDGE_KINDS.includes(e.kind)) continue; + const from = this.ownerOf(e.from); + const to = this.ownerOf(e.to); + if (from === to) continue; + const a = this.byId.get(from); + const b = this.byId.get(to); + if (a === undefined || b === undefined) continue; + if (a.type === TYPE_REQUIREMENT || b.type === TYPE_REQUIREMENT) continue; + const key = `${e.kind}\u0000${from}\u0000${to}`; + if (seen.has(key)) continue; + seen.add(key); + out.push({ kind: e.kind, from, to, ...(e.via !== undefined ? { via: e.via } : {}) }); + } + return out; + } + + slice(id: string): ExplorerSlice | undefined { + return this.doc.slices.find((s) => s.id === id); + } +} diff --git a/server/typescript/packages/docs-site/src/explorer/pages.ts b/server/typescript/packages/docs-site/src/explorer/pages.ts new file mode 100644 index 0000000000..684729f76c --- /dev/null +++ b/server/typescript/packages/docs-site/src/explorer/pages.ts @@ -0,0 +1,977 @@ +// The explorer's page models: one function per screen (design report §3.3, S1 to S9, plus the +// API index, the package pages and the prompt index). Each returns the payload its Mustache +// template renders; every string in it is already HTML-escaped, because the renderer's text +// format does not escape. +// +// Every fact a page states is read off the ExplorerIndex, which reads only `explorer.json`. The +// pages add presentation (grouping, ordering, wording) and the explorer checks the gaps page +// labels as such; they never recompute what the loader or the gate decided. + +import { + FIELD_ATTR_COLUMN, + FIELD_ATTR_DEFAULT, + FIELD_ATTR_FILTERABLE, + FIELD_ATTR_MAX_LENGTH, + FIELD_ATTR_OBJECT_REF, + FIELD_ATTR_REQUIRED, + FIELD_ATTR_SORTABLE, + FIELD_ATTR_VALUES, + FIELD_SUBTYPE_ENUM, + IDENTITY_ATTR_FIELDS, + IDENTITY_REFERENCE_ATTR_REFERENCES, + OBJECT_REPORT_ATTR_DIMENSIONS, + OBJECT_REPORT_ATTR_FILTER, + OBJECT_REPORT_ATTR_FROM, + OBJECT_REPORT_ATTR_MEASURES, + OBJECT_REPORT_ATTR_SEGMENT, + OBJECT_REPORT_ATTR_SPINE, + ORIGIN_AGGREGATE_ATTR_AGG, + ORIGIN_AGGREGATE_ATTR_FILTER, + ORIGIN_AGGREGATE_ATTR_OF, + ORIGIN_AGGREGATE_ATTR_VIA, + ORIGIN_COMPUTED_ATTR_EXPR, + ORIGIN_PASSTHROUGH_ATTR_FROM, + RELATIONSHIP_ATTR_CARDINALITY, + RELATIONSHIP_ATTR_OBJECT_REF, + RELATIONSHIP_ATTR_THROUGH, + REPORTING_ATTR_AGG, + REPORTING_ATTR_DEFAULT, + REPORTING_ATTR_DENOMINATOR, + REPORTING_ATTR_FILTER, + REPORTING_ATTR_GRAINS, + REPORTING_ATTR_NUMERATOR, + REPORTING_ATTR_OF, + REPORTING_ATTR_SEGMENT, + REPORTING_ATTR_VIA, + TEMPLATE_ATTR_FORMAT, + TEMPLATE_ATTR_MAX_TOKENS, + TEMPLATE_ATTR_MODEL, + TEMPLATE_ATTR_PAYLOAD_REF, + TEMPLATE_ATTR_PROMPT_STYLE, + TEMPLATE_ATTR_RESPONSE_FORMAT, + TEMPLATE_ATTR_RESPONSE_REF, + TEMPLATE_ATTR_TEXT_REF, + DOC_ATTR_DESCRIPTION, + DOC_ATTR_SUMMARY, + DOC_ATTR_TITLE, + TYPE_DIMENSION, + TYPE_FIELD, + TYPE_IDENTITY, + TYPE_INDEX, + TYPE_LAYOUT, + TYPE_MEASURE, + TYPE_ORIGIN, + TYPE_RELATIONSHIP, + TYPE_REQUIREMENT, + TYPE_SEGMENT, +} from "@metaobjectsdev/metadata/constants"; +import { + LAYOUT_DATA_GRID_ATTR_COLUMNS, + LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD, + LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER, + LAYOUT_DATA_GRID_ATTR_PAGE_SIZE, + REQUIREMENT_ATTR_COUNTEREXAMPLE, + REQUIREMENT_ATTR_DISPOSITION, + REQUIREMENT_ATTR_STATEMENT, + REQUIREMENT_ATTR_TRACKED_BY, + REQUIREMENT_LEVEL_OBJECT, + REQUIREMENT_LEVEL_SERVICE, + REQUIREMENT_STATUS_LIVE, + REQUIREMENT_STATUS_PLANNED, + REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK, + REQUIREMENT_SUBTYPE_ARCHITECTURAL, + REQUIREMENT_SUBTYPE_FUNCTIONAL, +} from "@metaobjectsdev/metadata"; +import type { ExplorerIndex, ReqEntry } from "./index-model.js"; +import { STATUSES } from "./index-model.js"; +import type { ExplorerNode } from "./types.js"; +import { + dispositionPill, + esc, + GATE_SOURCE, + levelBadge, + relHref, + rollupBar, + statusChip, + statusGlyph, + verdictBadge, +} from "./html.js"; + +// ─── Where every page lives ────────────────────────────────────────────────────────────────── + +export const PAGE_OVERVIEW = "index.html"; +export const PAGE_MAP = "map.html"; +export const PAGE_FEATURES = "requirements/features.html"; +export const PAGE_QUALITIES = "requirements/qualities.html"; +export const PAGE_MATRIX = "matrix.html"; +export const PAGE_TRACE = "trace.html"; +export const PAGE_PROMPTS = "prompts.html"; +export const PAGE_API = "api.html"; +export const PAGE_GAPS = "gaps.html"; +export const PAGE_MODEL = "model/index.html"; + +/** The member types a page gives an anchor, so an L5 link can land on its row. */ +const ANCHORED_TYPES = new Set([TYPE_FIELD, TYPE_IDENTITY, TYPE_INDEX, TYPE_RELATIONSHIP, TYPE_DIMENSION, TYPE_MEASURE, TYPE_SEGMENT]); + +/** A member row's anchor: `m-` for a field, `m--` for anything else, since + * siblings of different types may share a name. */ +const memberAnchor = (n: ExplorerNode): string => (n.type === TYPE_FIELD ? `m-${n.name}` : `m-${n.type}-${n.name}`); + +/** The gate codes that report the level and nesting rules (the proof table's "Level rules"). */ +const LEVEL_RULE_CODES = new Set(["ERR_REQUIREMENT_BAD_LEVEL", "ERR_REQUIREMENT_LEVEL_NESTING", "ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]); +const CODE_OBJECT_UNCLAIMED = "WARN_REQUIREMENT_OBJECT_UNCLAIMED"; + +const byCodeUnit = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0); +const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined); +const strs = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : typeof v === "string" ? [v] : []); + +/** The directory of a package's pages. A package segment is an identifier, so `-root` (for + * the empty package) cannot be one. */ +function pkgDir(pkg: string): string { + return pkg === "" ? "-root" : pkg.split("::").join("/"); +} + +/** A page's file stem: the name, unless it would take the package page's `index.html` (on a + * case-insensitive file system too). */ +function pageStem(name: string): string { + return name.toLowerCase() === "index" ? `${name}.node` : name; +} + +/** A short form of an id for display: the part after the package. */ +export function localName(id: string): string { + const i = id.lastIndexOf("::"); + return i < 0 ? id : id.slice(i + 2); +} + +export class Pages { + constructor(readonly ix: ExplorerIndex) {} + + // ─── Addresses ─────────────────────────────────────────────────────────────── + + objectPage(n: ExplorerNode): string { + return `model/${pkgDir(n.package)}/${pageStem(n.name)}.html`; + } + + packagePage(pkg: string): string { + return `model/${pkgDir(pkg)}/index.html`; + } + + reqPage(r: ReqEntry): string { + return `requirements/${pkgDir(r.node.package)}/${pageStem(this.reqPath(r))}.html`; + } + + /** The requirement's dotted path, as every `verify` diagnostic prints it. */ + reqPath(r: ReqEntry): string { + if (r.row !== undefined) return r.row.path; + const prefix = r.node.package === "" ? "" : `${r.node.package}::`; + return r.node.id.startsWith(prefix) ? r.node.id.slice(prefix.length) : r.node.id; + } + + reqLabel(r: ReqEntry): string { + return str(r.node.attrs[DOC_ATTR_TITLE]) ?? r.node.name; + } + + /** Where a node id lands: its own page, or its owner's page at the member's row. */ + pageOf(id: string): string | undefined { + const req = this.ix.reqById.get(id); + if (req !== undefined) return this.reqPage(req); + const ownerId = this.ix.ownerOf(id); + const owner = this.ix.byId.get(ownerId); + if (owner === undefined || owner.type === TYPE_REQUIREMENT) return undefined; + const page = this.objectPage(owner); + if (ownerId === id) return page; + const member = this.memberOf(ownerId, id); + return member !== undefined && ANCHORED_TYPES.has(member.type) ? `${page}#${memberAnchor(member)}` : page; + } + + /** The direct child of `ownerId` that `id` sits in (or is). */ + private memberOf(ownerId: string, id: string): ExplorerNode | undefined { + let cur = this.ix.byId.get(id); + while (cur !== undefined && cur.parent !== ownerId) cur = cur.parent !== undefined ? this.ix.byId.get(cur.parent) : undefined; + return cur; + } + + kindClass(n: ExplorerNode): string { + return `k-${this.ix.kindOf(n)}`; + } + + /** A link to any node, relative to `from`; an unknown id renders as a red "unresolved" chip. */ + link(from: string, id: string, label?: string): string { + const page = this.pageOf(id); + const n = this.ix.byId.get(this.ix.ownerOf(id)); + if (page === undefined || n === undefined) return `${esc(label ?? localName(id))} (unresolved)`; + const req = this.ix.reqById.get(id); + const text = label ?? (req !== undefined ? this.reqLabel(req) : id === n.id ? n.name : `${n.name}.${id.slice(n.id.length + 1)}`); + const cls = req !== undefined ? "" : ` class="${this.kindClass(n)}"`; + return `${esc(text)}`; + } + + reqLink(from: string, r: ReqEntry): string { + return `${esc(this.reqLabel(r))}`; + } + + description(n: ExplorerNode): string { + return esc(str(n.attrs[DOC_ATTR_DESCRIPTION]) ?? str(n.attrs[DOC_ATTR_SUMMARY]) ?? ""); + } + + topOf(r: ReqEntry): ReqEntry { + let t = r; + while (t.parent !== undefined) t = t.parent; + return t; + } + + // ─── S1: What it does ──────────────────────────────────────────────────────── + + overview(title: string): Record { + const ix = this.ix; + const from = PAGE_OVERVIEW; + const stored = ix.storedEntities(); + const abstract = ix.objects.filter((o) => ix.isEntity(o) && o.abstract === true).length; + const prompts = ix.templates.filter((t) => ix.isPrompt(t)); + const values = ix.objects.filter((o) => ix.kindOf(o) === "value").length; + const projections = ix.objects.filter((o) => ix.kindOf(o) === "projection").length; + const reports = ix.objects.filter((o) => ix.kindOf(o) === "report").length; + const counts = ix.doc.ledger?.counts ?? {}; + const num = (k: string): number | undefined => (typeof counts[k] === "number" ? (counts[k] as number) : undefined); + const features = ix.requirements.filter((r) => r.kind === REQUIREMENT_SUBTYPE_FUNCTIONAL).length; + const qualities = ix.requirements.filter((r) => r.kind === REQUIREMENT_SUBTYPE_ARCHITECTURAL).length; + const tiles: { n: string; l: string; href: string }[] = []; + tiles.push({ n: `${stored.length}`, l: `stored entities${abstract > 0 ? ` (${abstract} abstract base${abstract === 1 ? "" : "s"})` : ""}`, href: relHref(from, PAGE_MAP) }); + tiles.push({ n: `${prompts.length}`, l: `declared prompt${prompts.length === 1 ? "" : "s"}, ${count(values, "payload or reply type", "payload and reply types")}`, href: relHref(from, PAGE_PROMPTS) }); + if (ix.hasRequirements()) { + tiles.push({ n: `${num("total") ?? ix.requirements.length}`, l: `requirements: ${count(num("functional") ?? features, "feature")}, ${count(num("architectural") ?? qualities, "quality", "qualities")}`, href: relHref(from, PAGE_FEATURES) }); + } else { + tiles.push({ n: `${projections + reports}`, l: `read models: ${projections} projection${projections === 1 ? "" : "s"}, ${reports} report${reports === 1 ? "" : "s"}`, href: relHref(from, PAGE_MODEL) }); + } + const claimed = num("entitiesClaimed"); + const claimTotal = num("entitiesTotal"); + if (claimed !== undefined && claimTotal !== undefined && claimTotal > 0) { + tiles.push({ n: `${claimed}/${claimTotal}`, l: "entities claimed by a requirement (gate)", href: relHref(from, PAGE_GAPS) }); + } else { + tiles.push({ n: `${ix.packages.length}`, l: `package${ix.packages.length === 1 ? "" : "s"} in the model`, href: relHref(from, PAGE_MODEL) }); + } + if (ix.doc.api !== undefined) { + const routed = ix.objects.filter((o) => ix.routes(o.id).length > 0).length; + tiles.push({ n: `${routed}`, l: "objects with mounted REST routes", href: relHref(from, PAGE_API) }); + } else { + tiles.push({ n: "—", l: "REST routes: none recorded by this run", href: relHref(from, PAGE_API) }); + } + const genFiles = new Set((ix.doc.generated ?? []).flatMap((g) => g.files.map((f) => f.path))); + tiles.push({ + n: ix.doc.generated !== undefined ? `${genFiles.size}` : "—", + l: ix.doc.generated !== undefined ? "generated files traced to a node" : "generated files: no manifest read", + href: relHref(from, PAGE_TRACE), + }); + const sources = ["the effective model"]; + if (ix.doc.ledger !== undefined) sources.push("the requirement gate's ledger"); + if (ix.doc.generated !== undefined) sources.push("the generation manifest"); + return { + heading: esc(`What ${title} does`), + sourcesLine: esc(joinAnd(sources)), + tiles: tiles.map((t) => ({ n: esc(t.n), l: esc(t.l), href: esc(t.href) })), + hasRequirements: ix.hasRequirements(), + featureCards: ix.features().map((r) => this.capCard(from, r)), + qualityCards: ix.qualities().map((r) => this.capCard(from, r)), + hasFeatures: ix.features().length > 0, + hasQualities: ix.qualities().length > 0, + packageCards: ix.packages.map((p) => this.packageCard(from, p)), + }; + } + + private capCard(from: string, r: ReqEntry): Record { + const below = this.ix.below(r).length; + const claimed = this.ix.targetsOf(r).length; + return { + levelHtml: levelBadge(r), + linkHtml: this.reqLink(from, r), + statusHtml: statusChip(r.status), + verdictHtml: verdictBadge(r), + statement: esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT]) ?? ""), + barHtml: rollupBar(this.ix.rollup(r)), + countsLine: esc(`${below} requirement${below === 1 ? "" : "s"} below · ${claimed} model node${claimed === 1 ? "" : "s"} claimed`), + children: r.children.map((c) => ({ levelHtml: levelBadge(c), linkHtml: this.reqLink(from, c), glyphHtml: statusGlyph(c.status) })), + hasChildren: r.children.length > 0, + }; + } + + private packageCard(from: string, pkg: string): Record { + const members = [...this.ix.objects, ...this.ix.templates].filter((n) => n.package === pkg); + const kinds = new Map(); + for (const m of members) kinds.set(this.ix.kindOf(m), (kinds.get(this.ix.kindOf(m)) ?? 0) + 1); + const order = ["entity", "value", "projection", "report", "prompt", "template", "object"]; + const kindLine = order.filter((k) => kinds.has(k)).map((k) => `● ${kinds.get(k)} ${plural(k, kinds.get(k) ?? 0)}`).join(" · "); + const shown = members.slice(0, 12); + return { + name: esc(pkg === "" ? "(no package)" : pkg), + href: esc(relHref(from, this.packagePage(pkg))), + kindLineHtml: kindLine, + membersHtml: shown.map((m) => this.link(from, m.id)).join(", ") + (members.length > shown.length ? ` +${members.length - shown.length}` : ""), + }; + } + + // ─── S2: Model map ─────────────────────────────────────────────────────────── + + map(): Record { + const ix = this.ix; + const groups: { label: string; options: { value: string; label: string }[] }[] = []; + const base = [{ value: "", label: "Whole model" }]; + if (ix.templates.some((t) => ix.isPrompt(t))) base.push({ value: "@prompts", label: "Prompts and their payloads" }); + groups.push({ label: "Model", options: base }); + for (const top of ix.topRequirements) { + const opts: { value: string; label: string }[] = []; + for (const r of [top, ...top.children]) { + const s = ix.slice(`requirement:${r.node.id}`); + if (s === undefined) continue; + const depth = r === top ? "" : " "; + opts.push({ value: s.id, label: `${depth}${r.level !== undefined ? `L${r.level} ` : ""}${this.reqLabel(r)} (${ix.targetsOf(r).length})` }); + } + if (opts.length > 0) groups.push({ label: `${top.kind === REQUIREMENT_SUBTYPE_FUNCTIONAL ? "Feature" : "Quality"}: ${this.reqLabel(top)}`, options: opts }); + } + if (ix.packages.length > 1) groups.push({ label: "Package", options: ix.packages.map((p) => ({ value: `package:${p}`, label: p === "" ? "(no package)" : p })) }); + return { + sliceGroups: groups.map((g) => ({ label: esc(g.label), options: g.options.map((o) => ({ value: esc(o.value), label: esc(o.label) })) })), + hasRequirements: ix.hasRequirements(), + }; + } + + // ─── S3: Object page (entity, value, projection, report) ───────────────────── + + object(n: ExplorerNode): Record { + const ix = this.ix; + const from = this.objectPage(n); + const kind = ix.kindOf(n); + const claims = ix.claims(n.id); + const storage = ix.storage(n.id); + const storageLine = storage === undefined ? (kind === "value" ? "value object: no storage" : "no source") : `${storage.kind}${storage.name !== undefined ? ` ${storage.name}` : ""}`; + const fields = ix.fields(n.id).map((f) => this.fieldRow(from, n, f)); + const hasColumn = fields.some((f) => f.column !== ""); + const keys = ix.children(n.id).filter((c) => c.type === TYPE_IDENTITY || c.type === TYPE_INDEX || c.type === TYPE_RELATIONSHIP).map((c) => this.keyRow(from, c)); + const reporting = ix.children(n.id).filter((c) => c.type === TYPE_DIMENSION || c.type === TYPE_MEASURE || c.type === TYPE_SEGMENT).map((c) => this.reportingRow(from, c)); + const layouts = ix.children(n.id).filter((c) => c.type === TYPE_LAYOUT).map((l) => this.layoutRow(l)); + const isUnclaimed = this.unclaimedEntity(n); + const whyRows = this.whyRows(from, n); + const usedBy = ix.doc.edges.filter((e) => (e.kind === "payload" || e.kind === "reply") && e.to === n.id).map((e) => this.link(from, e.from)); + const refBy = [...new Set(ix.modelEdges().filter((e) => e.to === n.id && e.kind !== "payload" && e.kind !== "reply").map((e) => e.from))].sort(byCodeUnit).map((id) => this.link(from, id)); + const ext = n.extends !== undefined ? this.link(from, n.extends) : ""; + return { + id: esc(n.id), + name: esc(n.name), + kindLabel: esc(`object.${n.subType}`), + crumbsHtml: `Model › ${esc(n.package === "" ? "(no package)" : n.package)} › object.${esc(n.subType)}`, + isAbstract: n.abstract === true, + isUnclaimed, + isReadOnly: storage?.kind === "view", + kindBadge: esc(kind), + description: this.description(n), + storageLine: esc(storageLine), + extendsHtml: ext, + whyRows, + hasWhy: whyRows.length > 0, + whyEmptyHtml: this.whyEmpty(n), + fields, + hasFields: fields.length > 0, + hasColumn, + // The L5 column only where the model declares requirements to claim a field. + showClaims: this.ix.hasRequirements(), + keys, + hasKeys: keys.length > 0, + reporting, + hasReporting: reporting.length > 0, + layouts, + hasLayouts: layouts.length > 0, + projection: kind === "projection" ? this.projectionBlock(from, n) : undefined, + report: kind === "report" ? this.reportBlock(from, n) : undefined, + routes: ix.routes(n.id).map((r) => ({ method: esc(r.method), path: esc(r.path) })), + hasRoutes: ix.routes(n.id).length > 0, + routesNote: ix.doc.api === undefined ? "This run recorded no routes." : "No generated routes are mounted for it.", + usedByHtml: usedBy.join(", "), + referencedByHtml: refBy.join(", "), + generated: this.generatedGroups(n.id), + hasGenerated: ix.generated(n.id).length > 0, + generatedNote: ix.doc.generated === undefined ? "No generation manifest was read." : "Nothing generated is traced to it.", + claimCount: claims.length, + }; + } + + /** A concrete entity that no requirement claims, once any requirement claims anything. That + * is the gate's object coverage (`WARN_REQUIREMENT_OBJECT_UNCLAIMED`), which only activates + * when the project's requirements claim something. */ + unclaimedEntity(n: ExplorerNode): boolean { + const ix = this.ix; + if (!ix.isEntity(n) || n.abstract === true) return false; + const diags = ix.doc.ledger?.diagnostics ?? []; + return diags.some((d) => isDiag(d) && d.code === CODE_OBJECT_UNCLAIMED && d.node === n.id); + } + + private whyRows(from: string, n: ExplorerNode): Record[] { + const claims = [...this.ix.claims(n.id)].sort((a, b) => this.ix.requirements.indexOf(a.req) - this.ix.requirements.indexOf(b.req)); + const rows: Record[] = []; + let lastTop: ReqEntry | undefined; + for (const c of claims) { + const top = this.topOf(c.req); + rows.push({ + capabilityHtml: top === lastTop ? "" : this.reqLink(from, top), + reqHtml: this.reqLink(from, c.req), + statement: esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT]) ?? ""), + levelHtml: levelBadge(c.req), + statusHtml: statusChip(c.req.status), + onHtml: c.member !== undefined ? `${esc(c.member)}` : `whole object`, + }); + lastTop = top; + } + return rows; + } + + private whyEmpty(n: ExplorerNode): string { + if (!this.ix.hasRequirements()) return `This model declares no requirements, so nothing states why ${esc(n.name)} exists.`; + if (this.unclaimedEntity(n)) return `No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`; + return `No requirement claims ${esc(n.name)}.`; + } + + private fieldRow(from: string, owner: ExplorerNode, f: ExplorerNode): { [k: string]: unknown; column: string } { + const ref = str(f.attrs[FIELD_ATTR_OBJECT_REF]); + const values = f.subType === FIELD_SUBTYPE_ENUM ? strs(f.attrs[FIELD_ATTR_VALUES]) : []; + const flags: string[] = []; + if (f.attrs[FIELD_ATTR_REQUIRED] === true) flags.push("required"); + if (f.attrs[FIELD_ATTR_FILTERABLE] === true) flags.push("filterable"); + if (f.attrs[FIELD_ATTR_SORTABLE] === true) flags.push("sortable"); + if (f.attrs[FIELD_ATTR_MAX_LENGTH] !== undefined) flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`); + if (f.attrs[FIELD_ATTR_DEFAULT] !== undefined) flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`); + if (this.ix.children(f.id).some((c) => c.type === TYPE_ORIGIN)) flags.push("derived"); + const claims = this.ix.claims(owner.id).filter((c) => c.member !== undefined && c.member.split(".")[0] === f.name); + return { + anchor: esc(memberAnchor(f)), + name: esc(f.name), + inheritedHtml: f.inheritedFrom !== undefined ? `inherited` : "", + type: esc(`${f.subType}${f.isArray === true ? "[]" : ""}`), + refHtml: ref !== undefined ? ` → ${this.link(from, ref)}` : "", + valuesHtml: values.length > 0 ? `
${values.map(esc).join(" | ")}
` : "", + column: esc(str(f.attrs[FIELD_ATTR_COLUMN]) ?? ""), + flagsHtml: flags.map((x) => `${esc(x)}`).join(""), + claimsHtml: claims.map((c) => `${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
"), + }; + } + + private keyRow(from: string, c: ExplorerNode): Record { + const fields = strs(c.attrs[IDENTITY_ATTR_FIELDS]); + const target = str(c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]) ?? str(c.attrs[RELATIONSHIP_ATTR_OBJECT_REF]); + const through = str(c.attrs[RELATIONSHIP_ATTR_THROUGH]); + const card = str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]); + const shape = c.type === TYPE_RELATIONSHIP ? [card, through !== undefined ? `through ${localName(through)}` : undefined].filter((x) => x !== undefined).join(", ") : `(${fields.join(", ")})`; + return { + anchor: esc(memberAnchor(c)), + kind: esc(`${c.type}.${c.subType}`), + name: esc(c.name), + inheritedHtml: c.inheritedFrom !== undefined ? `inherited` : "", + shape: esc(shape), + targetHtml: target !== undefined ? `→ ${this.link(from, target)}` : "", + }; + } + + private reportingRow(from: string, c: ExplorerNode): Record { + const a = c.attrs; + const parts: string[] = []; + const agg = str(a[REPORTING_ATTR_AGG]); + const of = strs(a[REPORTING_ATTR_OF]); + if (agg !== undefined) parts.push(`${esc(agg)}(${of.map((o) => this.link(from, o, localName(o))).join(", ")})`); + else if (of.length > 0) parts.push(`of ${of.map((o) => this.link(from, o, localName(o))).join(", ")}`); + const num = str(a[REPORTING_ATTR_NUMERATOR]); + const den = str(a[REPORTING_ATTR_DENOMINATOR]); + if (num !== undefined && den !== undefined) parts.push(`${esc(num)} ÷ ${esc(den)}`); + const via = str(a[REPORTING_ATTR_VIA]); + if (via !== undefined) parts.push(`via ${esc(localName(via))}`); + const grains = strs(a[REPORTING_ATTR_GRAINS]); + if (grains.length > 0) parts.push(`grains ${grains.map((g) => `${esc(g)}`).join(" ")}`); + const seg = str(a[REPORTING_ATTR_SEGMENT]); + if (seg !== undefined) parts.push(`segment ${esc(seg)}`); + if (a[REPORTING_ATTR_FILTER] !== undefined) parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`); + if (a[REPORTING_ATTR_DEFAULT] !== undefined) parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`); + return { anchor: esc(memberAnchor(c)), kind: esc(`${c.type}.${c.subType}`), name: esc(c.name), definitionHtml: parts.join(" · ") }; + } + + private layoutRow(l: ExplorerNode): Record { + const parts: string[] = []; + const cols = strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]); + if (cols.length > 0) parts.push(`columns ${cols.map((c) => `${esc(c)}`).join(", ")}`); + const sort = str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]); + if (sort !== undefined) parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]) !== undefined ? ` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}` : ""}`); + if (typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE] === "number") parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`); + return { kind: esc(`${l.type}.${l.subType}`), name: esc(l.name), detailHtml: parts.join(", ") }; + } + + private projectionBlock(from: string, n: ExplorerNode): Record { + const ix = this.ix; + const rows: Record[] = []; + const bases = new Set(); + for (const f of ix.fields(n.id)) { + if (f.extends !== undefined) bases.add(ix.ownerOf(f.extends)); + for (const o of ix.children(f.id).filter((c) => c.type === TYPE_ORIGIN)) { + const def = this.originDefinition(from, o); + const src = str(o.attrs[ORIGIN_PASSTHROUGH_ATTR_FROM]); + if (src !== undefined && ix.byId.has(src)) bases.add(ix.ownerOf(src)); + rows.push({ field: esc(f.name), origin: esc(`origin.${o.subType}`), definitionHtml: def }); + } + } + return { + basesHtml: [...bases].filter((b) => b !== n.id).sort(byCodeUnit).map((b) => this.link(from, b)).join(", "), + origins: rows, + hasOrigins: rows.length > 0, + }; + } + + private originDefinition(from: string, o: ExplorerNode): string { + const a = o.attrs; + const ref = (v: unknown): string => { + const s = str(v); + return s === undefined ? "" : this.ix.byId.has(s) ? this.link(from, s, localName(s)) : `${esc(localName(s))}`; + }; + const parts: string[] = []; + const agg = str(a[ORIGIN_AGGREGATE_ATTR_AGG]); + if (agg !== undefined) parts.push(`${esc(agg)}(${ref(a[ORIGIN_AGGREGATE_ATTR_OF])})`); + else if (a[ORIGIN_AGGREGATE_ATTR_OF] !== undefined) parts.push(`of ${ref(a[ORIGIN_AGGREGATE_ATTR_OF])}`); + if (a[ORIGIN_PASSTHROUGH_ATTR_FROM] !== undefined) parts.push(`from ${ref(a[ORIGIN_PASSTHROUGH_ATTR_FROM])}`); + if (a[ORIGIN_AGGREGATE_ATTR_VIA] !== undefined) parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`); + if (a[ORIGIN_COMPUTED_ATTR_EXPR] !== undefined) parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`); + if (a[ORIGIN_AGGREGATE_ATTR_FILTER] !== undefined) parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`); + return parts.join(" · "); + } + + private reportBlock(from: string, n: ExplorerNode): Record { + const a = n.attrs; + const fromId = str(a[OBJECT_REPORT_ATTR_FROM]); + const resolve = (name: string, kindType: string): string => { + const candidates = [fromId !== undefined ? `${fromId}.${name}` : undefined, `${n.package === "" ? "" : `${n.package}::`}${name}`].filter((x): x is string => x !== undefined); + const hit = candidates.find((c) => this.ix.byId.get(c)?.type === kindType || (this.ix.byId.has(c) && name.includes("."))); + return hit !== undefined ? this.link(from, hit, name) : `${esc(name)}`; + }; + const spine = str(a[OBJECT_REPORT_ATTR_SPINE]); + return { + fromHtml: fromId !== undefined ? this.link(from, fromId) : "", + spineHtml: spine !== undefined ? `${esc(spine)}` : "", + dimensionsHtml: strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d) => resolve(d, TYPE_DIMENSION)).join(", "), + measuresHtml: strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m) => resolve(m, TYPE_MEASURE)).join(", "), + segmentHtml: strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s) => resolve(s, TYPE_SEGMENT)).join(", "), + filterHtml: a[OBJECT_REPORT_ATTR_FILTER] !== undefined ? `${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}` : "", + }; + } + + private generatedGroups(id: string): Record[] { + const groups = new Map(); + for (const f of this.ix.generated(id)) groups.set(f.generatedBy, [...(groups.get(f.generatedBy) ?? []), f.path]); + return [...groups.keys()].sort(byCodeUnit).map((g) => ({ generator: esc(g), files: (groups.get(g) ?? []).map((p) => esc(p)) })); + } + + // ─── S4: Prompt (and other template) page ──────────────────────────────────── + + prompt(n: ExplorerNode, text: string | undefined): Record { + const ix = this.ix; + const from = this.objectPage(n); + const payloadId = str(n.attrs[TEMPLATE_ATTR_PAYLOAD_REF]); + const replyId = str(n.attrs[TEMPLATE_ATTR_RESPONSE_REF]); + const vars = text !== undefined ? templateVariables(text) : undefined; + const payload = payloadId !== undefined ? ix.byId.get(payloadId) : undefined; + const reply = replyId !== undefined ? ix.byId.get(replyId) : undefined; + const payloadRows = payload !== undefined ? ix.fields(payload.id).map((f) => ({ + name: esc(f.name), + requiredHtml: f.attrs[FIELD_ATTR_REQUIRED] === true ? `required` : "", + type: esc(`${f.subType}${f.isArray === true ? "[]" : ""}`), + refHtml: str(f.attrs[FIELD_ATTR_OBJECT_REF]) !== undefined ? ` → ${this.link(from, str(f.attrs[FIELD_ATTR_OBJECT_REF])!)}` : "", + usedHtml: vars === undefined ? `text not read` : vars.has(f.name) ? "yes" : `no`, + })) : []; + const replyRows = reply !== undefined ? ix.fields(reply.id).map((f) => ({ + name: esc(f.name), + type: esc(`${f.subType}${f.isArray === true ? "[]" : ""}`), + valuesHtml: f.subType === FIELD_SUBTYPE_ENUM ? `
${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
` : "", + })) : []; + const textRef = str(n.attrs[TEMPLATE_ATTR_TEXT_REF]) ?? ""; + const lines = text !== undefined ? text.replace(/\n$/, "").split("\n").length : 0; + const attrs = [TEMPLATE_ATTR_FORMAT, TEMPLATE_ATTR_RESPONSE_FORMAT, TEMPLATE_ATTR_PROMPT_STYLE, TEMPLATE_ATTR_MODEL, TEMPLATE_ATTR_MAX_TOKENS] + .filter((k) => n.attrs[k] !== undefined) + .map((k) => `@${esc(k)} ${esc(fmt(n.attrs[k]))}`) + .join(""); + const claimed = ix.claims(n.id); + const whyRows = this.whyRows(from, n); + return { + name: esc(n.name), + kindLabel: esc(`template.${n.subType}`), + crumbsHtml: `Prompts › ${esc(n.package === "" ? "(no package)" : n.package)} › template.${esc(n.subType)}`, + isUnclaimed: ix.hasClaims() && claimed.length === 0, + description: this.description(n), + attrsHtml: attrs, + payloadHtml: payload !== undefined ? this.link(from, payload.id) : "none", + payloadRows, + hasPayload: payload !== undefined, + replyHtml: reply !== undefined ? this.link(from, reply.id) : "none", + replyRows, + hasReply: reply !== undefined, + textRef: esc(textRef), + textMeta: esc(text !== undefined ? `${textRef}.mustache · ${lines} line${lines === 1 ? "" : "s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT]) !== undefined ? ` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}` : ""}` : `${textRef}.mustache`), + textHtml: text !== undefined ? highlightVariables(text) : "", + hasText: text !== undefined, + generated: this.generatedGroups(n.id), + hasGenerated: ix.generated(n.id).length > 0, + generatedNote: ix.doc.generated === undefined ? "No generation manifest was read." : "Nothing generated is traced to it.", + whyRows, + hasWhy: whyRows.length > 0, + whyEmptyHtml: ix.hasRequirements() ? `No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.` : `This model declares no requirements.`, + }; + } + + // ─── Prompt index ──────────────────────────────────────────────────────────── + + prompts(): Record { + const from = PAGE_PROMPTS; + const rows = this.ix.templates.map((p) => { + const payload = str(p.attrs[TEMPLATE_ATTR_PAYLOAD_REF]); + const reply = str(p.attrs[TEMPLATE_ATTR_RESPONSE_REF]); + const claims = this.ix.claims(p.id); + return { + linkHtml: this.link(from, p.id), + kind: esc(`template.${p.subType}`), + description: this.description(p), + payloadHtml: payload !== undefined ? this.link(from, payload) : `none`, + replyHtml: reply !== undefined ? this.link(from, reply) : `none (outbound only)`, + claimsHtml: claims.length > 0 ? claims.map((c) => statusChip(c.req.status)).join("") : this.ix.hasClaims() ? `unclaimed` : `—`, + }; + }); + return { rows, hasRows: rows.length > 0 }; + } + + // ─── S5: Requirements tree ─────────────────────────────────────────────────── + + requirements(kind: string, page: string): Record { + const tops = this.ix.topRequirements.filter((r) => r.kind === kind); + const treeHtml = tops.length > 0 ? `
    ${tops.map((r) => this.treeNode(page, r)).join("")}
` : ""; + return { + isFeatures: kind === REQUIREMENT_SUBTYPE_FUNCTIONAL, + featuresHref: esc(relHref(page, PAGE_FEATURES)), + qualitiesHref: esc(relHref(page, PAGE_QUALITIES)), + featureCount: this.ix.requirements.filter((r) => r.kind === REQUIREMENT_SUBTYPE_FUNCTIONAL).length, + qualityCount: this.ix.requirements.filter((r) => r.kind === REQUIREMENT_SUBTYPE_ARCHITECTURAL).length, + treeHtml, + hasTree: tops.length > 0, + emptyNote: kind === REQUIREMENT_SUBTYPE_FUNCTIONAL ? "No requirement.functional is declared." : "No requirement.architectural is declared.", + }; + } + + private treeNode(from: string, r: ReqEntry): string { + const links = (r.row?.implementedBy ?? []).map((l) => { + if (l.target !== undefined && this.ix.byId.has(l.target)) return `${this.link(from, l.target, l.ref)}`; + return r.status === REQUIREMENT_STATUS_PLANNED + ? `${esc(l.ref)} (not yet)` + : `${esc(l.ref)} (dangling)`; + }); + const bar = r.children.length > 0 ? `${rollupBar(this.ix.rollup(r))}` : ""; + const row = `
${levelBadge(r)}${this.reqLink(from, r)} ${statusChip(r.status)}${dispositionPill(r)}${verdictBadge(r)}${bar}${links.join("")}
${esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT]) ?? "")}
`; + return `
  • ${row}${r.children.length > 0 ? `
      ${r.children.map((c) => this.treeNode(from, c)).join("")}
    ` : ""}
  • `; + } + + // ─── S6: Requirement page ──────────────────────────────────────────────────── + + requirement(r: ReqEntry): Record { + const ix = this.ix; + const from = this.reqPage(r); + const chain: ReqEntry[] = []; + for (let x: ReqEntry | undefined = r; x !== undefined; x = x.parent) chain.unshift(x); + const tab = r.kind === REQUIREMENT_SUBTYPE_FUNCTIONAL ? { href: PAGE_FEATURES, label: "Features" } : { href: PAGE_QUALITIES, label: "Qualities" }; + const row = r.row; + const links = row?.implementedBy ?? []; + const linkRows = links.map((l) => { + const target = l.target !== undefined ? ix.byId.get(l.target) : undefined; + return { + refHtml: target !== undefined ? this.link(from, target.id, l.ref) : `${esc(l.ref)}`, + kind: esc(target !== undefined ? `${target.type}.${target.subType}` : ""), + resolvesHtml: l.resolves + ? `resolves` + : r.status === REQUIREMENT_STATUS_PLANNED + ? `not yet (allowed on planned)` + : `dangling`, + }; + }); + const findings = (row?.diagnostics ?? []).filter((d) => d.source === GATE_SOURCE); + const advisories = (row?.diagnostics ?? []).filter((d) => d.source !== GATE_SOURCE); + const levelFinding = row?.diagnostics.some((d) => LEVEL_RULE_CODES.has(d.code)) ?? false; + const testable = r.kind === REQUIREMENT_SUBTYPE_FUNCTIONAL && (r.level ?? 0) >= REQUIREMENT_LEVEL_OBJECT; + const linksOk = links.length === 0 ? "none" : links.every((l) => l.resolves) ? "yes" : "no"; + const below = ix.below(r); + const slice = ix.slice(`requirement:${r.node.id}`); + let traceStart: ReqEntry | undefined = r; + while (traceStart !== undefined && (traceStart.level ?? 0) > REQUIREMENT_LEVEL_SERVICE) traceStart = traceStart.parent; + const tracked = strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]); + const desc = this.description(r.node); + return { + crumbsHtml: `${tab.label} › ${chain.map((x) => (x === r ? esc(this.reqLabel(x)) : this.reqLink(from, x))).join(" › ")}`, + levelHtml: levelBadge(r), + name: esc(this.reqLabel(r)), + statusHtml: statusChip(r.status), + dispositionHtml: dispositionPill(r), + verdictHtml: verdictBadge(r), + address: esc(`${row?.qualifiedPath ?? r.node.id} · requirement.${r.kind}`), + statement: esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT]) ?? ""), + counterexample: esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE]) ?? ""), + description: desc, + hasDescription: desc !== "", + linkRows, + hasLinks: linkRows.length > 0, + linksEmpty: r.level !== undefined && r.level < REQUIREMENT_LEVEL_OBJECT ? "Levels 1 to 3 never name the model." : "Names nothing.", + belowCount: below.length, + childCount: r.children.length, + deeper: below.length > r.children.length, + hasBelow: r.children.length > 0, + belowBarHtml: rollupBar(ix.rollup(r)), + children: r.children.map((c) => ({ levelHtml: levelBadge(c), linkHtml: this.reqLink(from, c), statusHtml: statusChip(c.status) })), + sliceHref: slice !== undefined ? esc(`${relHref(from, PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`) : "", + traceHref: traceStart !== undefined ? esc(`${relHref(from, PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`) : "", + proof: [ + { what: "Loads", verdictHtml: `yes`, how: "The loader enforces the closed @status enum and the required statement and counterexample." }, + { + what: "Links resolve", + verdictHtml: linksOk === "none" ? `no links` : linksOk === "yes" ? `yes` : `no`, + how: "ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead.", + }, + { what: "Level rules", verdictHtml: levelFinding ? `no` : `yes`, how: "Nesting agrees with level, and links sit only at L4 and L5." }, + { + what: "Gate findings", + verdictHtml: findings.length > 0 ? `${findings.length}` : row !== undefined ? `none` : `not read`, + how: findings.length > 0 ? findings.map((d) => `${esc(d.code)} ${esc(d.message)}`).join("
    ") : row !== undefined ? "Nothing reported for this entry." : "This build read no meta verify output.", + }, + { + what: "Authoring advisories", + verdictHtml: row !== undefined ? `${advisories.length}` : `not read`, + how: advisories.length > 0 + ? advisories.map((d) => `${esc(d.code)} ${esc(d.message)}`).join("
    ") + : row !== undefined ? "None. The authoring lint never fails a build." : "This build read no meta verify output.", + }, + { + what: "Test exists", + verdictHtml: testable ? `by generator` : `not by default`, + how: testable + ? "The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger." + : "The stock requirement-tests generator selects functional L4 and L5 entries only.", + }, + { what: "Test passes", verdictHtml: `not read`, how: "verify never reads test results, so nothing here is coloured by one." }, + { what: "Status is true", verdictHtml: `unprovable`, how: "No gate can prove the status. The colour is the author's claim, held to referential integrity." }, + ].map((p) => ({ what: esc(p.what), verdictHtml: p.verdictHtml, howHtml: p.how })), + trackedHtml: tracked.map((t) => `${esc(t)}`).join(" "), + digest: esc(row?.digest ?? ""), + }; + } + + // ─── S7: Matrix ────────────────────────────────────────────────────────────── + + matrix(): Record { + const ix = this.ix; + const from = PAGE_MATRIX; + // Stored entities and prompts, plus anything else a row claims (an abstract base a policy + // names), so no claim lands outside the grid. + const claimed = ix.requirements.flatMap((r) => (r.row?.implementedBy ?? []).flatMap((l) => (l.target !== undefined ? [ix.ownerOf(l.target)] : []))); + const colSet = new Set([...ix.storedEntities(), ...ix.templates.filter((t) => ix.isPrompt(t))].map((n) => n.id)); + for (const id of claimed) if (ix.byId.get(id)?.parent === undefined && ix.byId.get(id)?.type !== TYPE_REQUIREMENT) colSet.add(id); + const cols = [...colSet].map((id) => ix.byId.get(id)!).sort( + (a, b) => ix.claims(b.id).length - ix.claims(a.id).length || byCodeUnit(a.name, b.name) || byCodeUnit(a.id, b.id), + ); + const head = `${cols.map((o) => `
    ${this.link(from, o.id)}
    `).join("")}`; + const rows: string[] = []; + for (const top of ix.topRequirements) { + const leaves = ix.subtree(top).filter((x) => (x.row?.implementedBy.length ?? 0) > 0); + if (leaves.length === 0) continue; + rows.push(`${top.kind === REQUIREMENT_SUBTYPE_FUNCTIONAL ? "Feature" : "Quality"}: ${this.reqLink(from, top)}${cols.map(() => ``).join("")}`); + for (const r of leaves) { + const tg = new Set((r.row?.implementedBy ?? []).filter((l) => l.target !== undefined).map((l) => ix.ownerOf(l.target!))); + const label = this.reqPath(r).split(".").slice(1).join(".") || this.reqLabel(r); + rows.push( + `${levelBadge(r)}${esc(label)}${cols + .map((o) => (tg.has(o.id) ? `${statusGlyph(r.status)}` : ``)) + .join("")}`, + ); + } + } + return { tableHtml: rows.length > 0 ? `${head}${rows.join("")}
    ` : "", hasRows: rows.length > 0, hasRequirements: ix.hasRequirements() }; + } + + // ─── S8: Trace ─────────────────────────────────────────────────────────────── + + trace(): Record { + const starts = this.ix.requirements.filter((r) => r.level !== undefined && r.level <= REQUIREMENT_LEVEL_SERVICE); + const fallback = starts.length === 0 ? this.ix.topRequirements : []; + return { + options: [...starts, ...fallback].map((r) => ({ value: esc(r.node.id), label: esc(`${" ".repeat(Math.max(0, (r.level ?? 1) - 1))}${r.level !== undefined ? `L${r.level} ` : ""}${this.reqLabel(r)}`) })), + hasStarts: starts.length + fallback.length > 0, + hasUsage: false, + }; + } + + // ─── S9: Gaps ──────────────────────────────────────────────────────────────── + + gaps(): Record { + const ix = this.ix; + const from = PAGE_GAPS; + const cards: Record[] = []; + const card = (title: string, count: number | string, source: string, why: string, bodyHtml: string): void => { + cards.push({ title: esc(title), count: esc(String(count)), source: esc(source), isGate: source === "meta verify", whyHtml: why, bodyHtml }); + }; + if (ix.doc.ledger !== undefined) { + // Each requirement's own findings come from its ledger row, which the gate scoped to that + // node; the flat list contributes only the findings with no requirement subject. + const findingsOf = (gate: boolean): { req?: ReqEntry; d: { code: string; severity: string; message: string } }[] => [ + ...ix.requirements.flatMap((req) => (req.row?.diagnostics ?? []).filter((d) => (d.source === GATE_SOURCE) === gate).map((d) => ({ req, d }))), + ...(ix.doc.ledger?.diagnostics ?? []).filter((d): d is Diag => isDiag(d) && d.path === "" && (d.source === GATE_SOURCE) === gate).map((d) => ({ d })), + ]; + const table = (rows: ReturnType, chip: (severity: string) => string): string => + rows.length === 0 + ? `
    None.
    ` + : `${rows.map(({ req, d }) => ``).join("")}
    ${esc(d.code)}${req !== undefined ? this.reqLink(from, req) : ""}
    ${esc(d.message)}
    `; + const gate = findingsOf(true); + card("Gate findings", gate.length, "meta verify", "Printed by every run of the requirement gate.", table(gate, (sev) => `chip v-${sev === "error" ? "error" : "warn"}`)); + const advisories = findingsOf(false); + card("Authoring advisories", advisories.length, "authoring lint", "Printed beside the gate's findings, and never able to fail a build.", table(advisories, () => "chip")); + const unclaimed = ix.storedEntities().filter((e) => this.unclaimedEntity(e)); + card("Entities no requirement claims", unclaimed.length, "meta verify", "The gate's coverage warning. Each is a capability nobody has written down.", unclaimed.length > 0 ? unclaimed.map((e) => this.link(from, e.id)).join(", ") : `
    None.
    `); + const outstanding = (r: ReqEntry): boolean => (REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK as readonly string[]).includes(r.status); + const undecided = ix.requirements.filter((r) => outstanding(r) && r.node.attrs[REQUIREMENT_ATTR_DISPOSITION] === undefined && !ix.below(r).some(outstanding)); + const counted = ix.doc.ledger.counts["undecided"]; + card("Undecided gaps", typeof counted === "number" ? counted : "—", "meta verify", "A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.", list(undecided.map((r) => `${levelBadge(r)}${this.reqLink(from, r)} ${statusChip(r.status)}`))); + } + if (ix.hasRequirements()) { + const behind = ix.requirements.filter((r) => r.status === REQUIREMENT_STATUS_PLANNED && ix.below(r).some((x) => x.status === REQUIREMENT_STATUS_LIVE)); + card("Planned, with live work below", behind.length, "explorer check", "L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.", list(behind.map((r) => `${levelBadge(r)}${this.reqLink(from, r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`))); + const prompts = ix.templates.filter((t) => ix.isPrompt(t) && ix.claims(t.id).length === 0); + card("Prompts no requirement claims", prompts.length, "explorer check", "The gate counts entity coverage only. An L4 may claim a prompt.", prompts.length > 0 ? prompts.map((p) => this.link(from, p.id)).join(", ") : `
    None.
    `); + } + card("Generated modules nothing imports", "—", "explorer check", "Needs a scan of hand-written imports, which this build does not run.", `
    Not scanned.
    `); + const implied = ix.storedEntities().flatMap((e) => { + const declared = new Set(ix.children(e.id).filter((c) => c.type === TYPE_IDENTITY && c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES] !== undefined).flatMap((c) => strs(c.attrs[IDENTITY_ATTR_FIELDS]))); + return ix.fields(e.id).filter((f) => /[a-z]Id$/.test(f.name) && !declared.has(f.name)); + }); + card("Fields that look like references but are not declared", implied.length, "explorer check", "A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.", list(implied.map((f) => `${this.link(from, f.id)} ${esc(f.subType)}`))); + if (ix.templates.length > 0) { + const unused = this.unusedPayload(); + card("Payload fields the prompt text never uses", unused === undefined ? "—" : unused.length, "explorer check", "The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.", unused === undefined ? `
    No prompt text was read.
    ` : list(unused.map(({ p, f }) => `${this.link(from, p.id)}: ${this.link(from, f.id, f.name)}`))); + } + return { cards }; + } + + /** Set by the site builder: prompt id → text, for the gaps page's payload check. */ + texts = new Map(); + + private unusedPayload(): { p: ExplorerNode; f: ExplorerNode }[] | undefined { + const out: { p: ExplorerNode; f: ExplorerNode }[] = []; + let read = false; + for (const p of this.ix.templates) { + const text = this.texts.get(p.id); + const payload = str(p.attrs[TEMPLATE_ATTR_PAYLOAD_REF]); + if (text === undefined || payload === undefined) continue; + read = true; + const vars = templateVariables(text); + for (const f of this.ix.fields(payload)) if (!vars.has(f.name)) out.push({ p, f }); + } + return read ? out : undefined; + } + + // ─── API index ─────────────────────────────────────────────────────────────── + + api(): Record { + const ix = this.ix; + const from = PAGE_API; + const groups = ix.objects.filter((o) => ix.routes(o.id).length > 0).map((o) => ({ + linkHtml: this.link(from, o.id), + kind: esc(ix.kindOf(o)), + isReadOnly: ix.storage(o.id)?.kind === "view", + routes: ix.routes(o.id).map((r) => ({ method: esc(r.method), methodClass: esc(r.method.toLowerCase()), path: esc(r.path) })), + })); + const total = groups.reduce((a, g) => a + g.routes.length, 0); + return { + groups, + hasGroups: groups.length > 0, + recorded: ix.doc.api !== undefined, + summary: esc(`${total} route${total === 1 ? "" : "s"} on ${groups.length} object${groups.length === 1 ? "" : "s"}`), + }; + } + + // ─── Model index and package pages ─────────────────────────────────────────── + + model(): Record { + return { packageCards: this.ix.packages.map((p) => this.packageCard(PAGE_MODEL, p)) }; + } + + packageIndex(pkg: string): Record { + const ix = this.ix; + const from = this.packagePage(pkg); + const rows = [...ix.objects, ...ix.templates].filter((n) => n.package === pkg).map((n) => { + const s = ix.storage(n.id); + const st = ix.claimStatus(n.id); + return { + linkHtml: this.link(from, n.id), + kind: esc(`${n.type}.${n.subType}`), + abstractHtml: n.abstract === true ? `abstract` : "", + storage: esc(s === undefined ? "" : `${s.kind}${s.name !== undefined ? ` ${s.name}` : ""}`), + fieldCount: ix.fields(n.id).length, + statusHtml: st === "unclaimed" ? (this.unclaimedEntity(n) ? `unclaimed` : "") : statusChip(st), + description: this.description(n), + }; + }); + return { name: esc(pkg === "" ? "(no package)" : pkg), crumbsHtml: `Model › ${esc(pkg === "" ? "(no package)" : pkg)}`, rows }; + } +} + +// ─── Small helpers ─────────────────────────────────────────────────────────────────────────── + +interface Diag { + code: string; + path: string; + severity: string; + source?: string; + /** The entity an object-coverage finding is about; "" or absent otherwise. */ + node?: string; + message: string; +} + +function isDiag(d: unknown): d is Diag { + if (typeof d !== "object" || d === null) return false; + const r = d as Record; + return typeof r["code"] === "string" && typeof r["path"] === "string" && typeof r["message"] === "string" && typeof r["severity"] === "string"; +} + +function list(items: string[]): string { + return items.length === 0 ? `
    None.
    ` : `
      ${items.map((i) => `
    • ${i}
    • `).join("")}
    `; +} + +function fmt(v: unknown): string { + return typeof v === "string" ? v : JSON.stringify(v); +} + +function joinAnd(xs: string[]): string { + return xs.length <= 1 ? (xs[0] ?? "") : `${xs.slice(0, -1).join(", ")} and ${xs[xs.length - 1]}`; +} + +function count(n: number, one: string, many = `${one}s`): string { + return `${n} ${n === 1 ? one : many}`; +} + +function plural(kind: string, n: number): string { + if (n === 1) return kind; + return kind === "entity" ? "entities" : `${kind}s`; +} + +const TAG = /\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g; + +/** The first path segment of every variable a Mustache text names (`{{a.b}}`, `{{#a}}`). */ +export function templateVariables(text: string): Set { + const out = new Set(); + for (const m of text.matchAll(TAG)) if (m[1] !== "/") out.add(m[2]!.split(".")[0]!); + return out; +} + +/** The text, escaped, with every tag picked out. */ +export function highlightVariables(text: string): string { + let out = ""; + let last = 0; + for (const m of text.matchAll(/\{\{[^}]*\}?\}\}/g)) { + out += esc(text.slice(last, m.index)); + out += `${esc(m[0])}`; + last = m.index! + m[0].length; + } + return out + esc(text.slice(last)); +} + +export { STATUSES }; diff --git a/server/typescript/packages/docs-site/src/explorer/site.ts b/server/typescript/packages/docs-site/src/explorer/site.ts new file mode 100644 index 0000000000..ca6782e70a --- /dev/null +++ b/server/typescript/packages/docs-site/src/explorer/site.ts @@ -0,0 +1,294 @@ +// generateExplorerSite(): the model explorer as a static site (design report §3.3, phase P1). +// +// It reads one `explorer.json` (and, for the prompt pages, the prompt texts), renders a page per +// screen through the bundled Mustache templates, and writes: +// +// index.html S1 what the project does +// map.html S2 the model map (slices, colour-by) +// model//.html S3 an object page (entity, value, projection, report) +// S4 a prompt page (and any other template) +// requirements/{features,qualities}.html S5 +// requirements//.html S6 +// matrix.html, trace.html, gaps.html, api.html, prompts.html, model/index.html, model//index.html +// assets/explorer.css, assets/explorer.js the theme (`meta eject docs-site` copies them) +// assets/explorer-data.js the graph and the search index the scripts read +// explorer.json the data spine itself, byte for byte +// +// The output depends on its inputs alone (no clock, no random layout seed in the files), so the +// site can sit under `meta verify --codegen`. Search works offline from explorer-data.js; when the +// published site has been indexed with Pagefind (`npx pagefind --site `), the search box uses +// that index instead. The pages carry Pagefind's markup for it. + +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, isAbsolute, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { render, InMemoryProvider } from "@metaobjectsdev/render"; +import { REQUIREMENT_ATTR_STATEMENT, REQUIREMENT_SUBTYPE_ARCHITECTURAL, REQUIREMENT_SUBTYPE_FUNCTIONAL } from "@metaobjectsdev/metadata"; +import { TEMPLATE_ATTR_TEXT_REF, TYPE_REQUIREMENT, DOC_ATTR_DESCRIPTION, OBJECT_SUBTYPE_REPORT, OBJECT_REPORT_ATTR_FROM } from "@metaobjectsdev/metadata/constants"; +import { checkLinks } from "../link-check.js"; +import { EXPLORER_ASSET_NAMES, EXPLORER_TEMPLATE_NAMES } from "../scaffold.js"; +import { ExplorerIndex } from "./index-model.js"; +import { serializeExplorer } from "./build.js"; +import { esc, legendHtml, relHref } from "./html.js"; +import { + PAGE_API, + PAGE_FEATURES, + PAGE_GAPS, + PAGE_MAP, + PAGE_MATRIX, + PAGE_MODEL, + PAGE_OVERVIEW, + PAGE_PROMPTS, + PAGE_QUALITIES, + PAGE_TRACE, + Pages, +} from "./pages.js"; +import type { ExplorerJson } from "./types.js"; + +export { EXPLORER_ASSET_NAMES, EXPLORER_TEMPLATE_NAMES }; + +/** The graph library the map, mini-maps and trace load from `assetBase`. */ +export const CYTOSCAPE_PATH = "cytoscape@3.30.2/dist/cytoscape.min.js"; + +const DEFAULT_ASSET_BASE = "https://cdn.jsdelivr.net/npm"; + +export interface ExplorerSiteOptions { + explorer: ExplorerJson; + outDir: string; + /** The project's name, as the header and the home page print it. */ + title: string; + /** Printed in every footer. Default none, so the pages depend on the model alone. */ + stamp?: string; + /** Prompt text by template node id, for the prompt pages and the unused-payload check. */ + texts?: ReadonlyMap; + /** Override dirs: a file of the same basename there wins over the bundled one. */ + templatesDir?: string; + assetsDir?: string; + /** Where Cytoscape is loaded from. Default `https://cdn.jsdelivr.net/npm`. */ + assetBase?: string; +} + +export interface ExplorerSiteResult { + /** Every HTML page written, site-relative, in write order. */ + pages: string[]; + /** Every file written (pages, assets, data), site-relative, sorted. */ + files: string[]; +} + +const SELF_DIR = dirname(fileURLToPath(import.meta.url)); +const BUNDLED_TEMPLATES = resolve(SELF_DIR, "../../templates"); +const BUNDLED_ASSETS = resolve(SELF_DIR, "../../assets"); + +function loadFrom(bundled: string, name: string, overrideDir?: string): string { + if (overrideDir !== undefined) { + const candidate = join(overrideDir, name); + if (existsSync(candidate)) return readFileSync(candidate, "utf8"); + } + return readFileSync(join(bundled, name), "utf8"); +} + +interface NavItem { + key: string; + label: string; + href: string; +} + +const NAV: readonly NavItem[] = [ + { key: "overview", label: "Overview", href: PAGE_OVERVIEW }, + { key: "map", label: "Model map", href: PAGE_MAP }, + { key: "requirements", label: "Requirements", href: PAGE_FEATURES }, + { key: "matrix", label: "Matrix", href: PAGE_MATRIX }, + { key: "trace", label: "Trace", href: PAGE_TRACE }, + { key: "prompts", label: "Prompts", href: PAGE_PROMPTS }, + { key: "api", label: "API", href: PAGE_API }, + { key: "gaps", label: "Gaps", href: PAGE_GAPS }, +]; + +/** Read each prompt's `.mustache` text from the directories the model's `@textRef` resolves in. */ +export function readPromptTexts(explorer: ExplorerJson, dirs: readonly string[]): Map { + const out = new Map(); + for (const n of explorer.nodes) { + const ref = n.attrs[TEMPLATE_ATTR_TEXT_REF]; + if (n.parent !== undefined || typeof ref !== "string") continue; + // A ref names a file below one of the directories: an absolute ref, or one that climbs out + // with `..`, is not read, so a model cannot pull an arbitrary file into a published page. + const segments = ref.split(/[\\/]/); + if (isAbsolute(ref) || segments.some((s) => s === ".." || s === "")) continue; + for (const d of dirs) { + const p = join(d, ...segments) + ".mustache"; + if (existsSync(p)) { + out.set(n.id, readFileSync(p, "utf8")); + break; + } + } + } + return out; +} + +export function generateExplorerSite(opts: ExplorerSiteOptions): ExplorerSiteResult { + const ix = new ExplorerIndex(opts.explorer); + const pagesModel = new Pages(ix); + for (const [id, text] of opts.texts ?? []) pagesModel.texts.set(id, text); + // The one partial: the requirement card S1 repeats (`{{> card}}`). + const provider = new InMemoryProvider({ card: loadFrom(BUNDLED_TEMPLATES, "explorer-card.mustache", opts.templatesDir) }); + const head = loadFrom(BUNDLED_TEMPLATES, "explorer-head.mustache", opts.templatesDir); + const foot = loadFrom(BUNDLED_TEMPLATES, "explorer-foot.mustache", opts.templatesDir); + const assetBase = (opts.assetBase ?? DEFAULT_ASSET_BASE).replace(/\/+$/, ""); + const legend = legendHtml(ix.hasClaims()); + const pages: string[] = []; + const files: string[] = []; + // Each body template is read once, not once per page it renders. + const bodies = new Map(); + + const written = new Set(); + const write = (rel: string, content: string): void => { + // Two nodes that map to one page would silently keep only the last; refuse instead. + if (written.has(rel)) throw new Error(`docs-site explorer: two pages map to ${rel}`); + written.add(rel); + const abs = join(opts.outDir, rel); + mkdirSync(dirname(abs), { recursive: true }); + writeFileSync(abs, content); + files.push(rel); + }; + + const page = (template: string, href: string, nav: string, pageTitle: string, data: Record, graph = false): void => { + const relRoot = relHref(href, ""); + let body = bodies.get(template); + if (body === undefined) { + body = loadFrom(BUNDLED_TEMPLATES, template, opts.templatesDir); + bodies.set(template, body); + } + const payload = { + ...data, + siteTitle: esc(opts.title), + pageTitle: esc(pageTitle), + stamp: esc(opts.stamp ?? ""), + relRoot, + assetBase, + cytoscapeSrc: `${assetBase}/${CYTOSCAPE_PATH}`, + needsGraph: graph, + pageKey: nav, + nav: NAV.map((n) => ({ label: n.label, href: relHref(href, n.href), on: n.key === nav })), + legendHtml: legend, + }; + write(href, render({ template: head + body + foot, payload, provider, format: "text" })); + pages.push(href); + }; + + // S1 and the indexes. + page("explorer-overview.html.mustache", PAGE_OVERVIEW, "overview", "Overview", pagesModel.overview(opts.title)); + page("explorer-map.html.mustache", PAGE_MAP, "map", "Model map", pagesModel.map(), true); + page("explorer-requirements.html.mustache", PAGE_FEATURES, "requirements", "Features", pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL, PAGE_FEATURES)); + page("explorer-requirements.html.mustache", PAGE_QUALITIES, "requirements", "Qualities", pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL, PAGE_QUALITIES)); + page("explorer-matrix.html.mustache", PAGE_MATRIX, "matrix", "Matrix", pagesModel.matrix()); + page("explorer-trace.html.mustache", PAGE_TRACE, "trace", "Trace", pagesModel.trace(), true); + page("explorer-prompts.html.mustache", PAGE_PROMPTS, "prompts", "Prompts", pagesModel.prompts()); + page("explorer-api.html.mustache", PAGE_API, "api", "API", pagesModel.api()); + page("explorer-gaps.html.mustache", PAGE_GAPS, "gaps", "Gaps", pagesModel.gaps()); + page("explorer-model.html.mustache", PAGE_MODEL, "map", "Packages", pagesModel.model()); + + for (const pkg of ix.packages) { + const data = pagesModel.packageIndex(pkg); + page("explorer-package.html.mustache", pagesModel.packagePage(pkg), "map", pkg === "" ? "(no package)" : pkg, data); + } + for (const n of ix.objects) page("explorer-object.html.mustache", pagesModel.objectPage(n), "map", n.name, pagesModel.object(n), true); + for (const t of ix.templates) page("explorer-prompt.html.mustache", pagesModel.objectPage(t), "prompts", t.name, pagesModel.prompt(t, opts.texts?.get(t.id))); + for (const r of ix.requirements) page("explorer-requirement.html.mustache", pagesModel.reqPage(r), "requirements", pagesModel.reqLabel(r), pagesModel.requirement(r)); + + for (const a of EXPLORER_ASSET_NAMES) write(`assets/${a}`, loadFrom(BUNDLED_ASSETS, a, opts.assetsDir)); + write("assets/explorer-data.js", `window.MO_EXPLORER = ${JSON.stringify(graphData(ix, pagesModel))};\n`); + write("explorer.json", serializeExplorer(opts.explorer)); + + const dangling = checkLinks(opts.outDir, pages); + if (dangling.length > 0) throw new Error("explorer link check failed:\n" + dangling.join("\n")); + return { pages, files: [...files].sort() }; +} + +/** The data the map, mini-maps, trace and search read. Every value comes off the index. */ +function graphData(ix: ExplorerIndex, p: Pages): Record { + const features = ix.features(); + const top = [...ix.objects, ...ix.templates]; + const nodes = top.map((n) => { + const feature = ix.featureOf(n.id); + const claims = ix.claims(n.id); + return { + id: n.id, + name: n.name, + kind: ix.kindOf(n), + pkg: n.package, + href: p.objectPage(n), + abstract: n.abstract === true ? 1 : 0, + fields: ix.fields(n.id).length, + claims: claims.length, + status: ix.claimStatus(n.id), + feature: feature !== undefined ? features.indexOf(feature) : -1, + quality: claims.length > 0 && claims.every((c) => c.req.kind === REQUIREMENT_SUBTYPE_ARCHITECTURAL) ? 1 : 0, + unclaimed: p.unclaimedEntity(n) ? 1 : 0, + api: ix.routes(n.id).map((r) => `${r.method} ${r.path}`), + gen: ix.generated(n.id).length, + storage: ix.storage(n.id)?.kind ?? "", + }; + }); + const ids = new Set(top.map((n) => n.id)); + const slices: Record = {}; + for (const s of ix.doc.slices) slices[s.id] = [...new Set(s.nodes.map((x) => ix.ownerOf(x)).filter((x) => ids.has(x)))].sort(); + const reqs = ix.requirements.map((r) => ({ + id: r.node.id, + label: p.reqLabel(r), + path: p.reqPath(r), + level: r.level ?? 0, + status: r.status, + kind: r.kind, + parent: r.parent?.node.id ?? "", + href: p.reqPage(r), + targets: (r.row?.implementedBy ?? []).filter((l) => l.target !== undefined && ix.byId.has(l.target)).map((l) => ix.ownerOf(l.target!)), + statement: typeof r.node.attrs[REQUIREMENT_ATTR_STATEMENT] === "string" ? r.node.attrs[REQUIREMENT_ATTR_STATEMENT] : "", + rollup: ix.rollup(r), + claimed: ix.targetsOf(r).length, + })); + const generated: Record = {}; + for (const n of top) { + const by = new Map(); + for (const f of ix.generated(n.id)) by.set(f.generatedBy, (by.get(f.generatedBy) ?? 0) + 1); + if (by.size > 0) generated[n.id] = [...by.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); + } + const search: { t: string; s: string; h: string; k: string }[] = []; + for (const n of top) { + const desc = typeof n.attrs[DOC_ATTR_DESCRIPTION] === "string" ? (n.attrs[DOC_ATTR_DESCRIPTION] as string) : ""; + search.push({ t: n.name, s: `${n.type}.${n.subType}${n.package !== "" ? ` · ${n.package}` : ""}`, h: p.objectPage(n), k: `${n.name} ${n.id} ${desc}`.toLowerCase() }); + for (const f of ix.fields(n.id)) { + if (f.inheritedFrom !== undefined) continue; + search.push({ t: `${n.name}.${f.name}`, s: `field.${f.subType}`, h: p.pageOf(f.id) ?? p.objectPage(n), k: `${n.name}.${f.name} ${f.id}`.toLowerCase() }); + } + } + for (const r of ix.requirements) { + search.push({ + t: p.reqLabel(r), + s: `${r.level !== undefined ? `L${r.level}` : "—"} ${r.kind}${r.status !== "" ? ` · ${r.status}` : ""} · ${p.reqPath(r)}`, + h: p.reqPage(r), + k: `${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${String(r.node.attrs[REQUIREMENT_ATTR_STATEMENT] ?? "")}`.toLowerCase(), + }); + } + return { + nodes, + edges: [ + ...ix.modelEdges().map((e) => ({ s: e.from, t: e.to, k: e.kind, ...(e.via !== undefined ? { v: localTail(e.via) } : {}) })), + // A report reads its rows from the `@from` entity: drawn so a report is not an island. + ...ix.objects + .filter((n) => n.subType === OBJECT_SUBTYPE_REPORT && typeof n.attrs[OBJECT_REPORT_ATTR_FROM] === "string" && ix.byId.has(n.attrs[OBJECT_REPORT_ATTR_FROM] as string)) + .map((n) => ({ s: n.id, t: n.attrs[OBJECT_REPORT_ATTR_FROM] as string, k: "from" })), + ], + slices, + features: features.map((f) => ({ id: f.node.id, label: p.reqLabel(f) })), + reqs, + generated, + search, + hasClaims: ix.hasClaims(), + requirementType: TYPE_REQUIREMENT, + }; +} + +function localTail(id: string): string { + const i = id.lastIndexOf("."); + return i < 0 ? id : id.slice(i + 1); +} diff --git a/server/typescript/packages/docs-site/src/explorer/types.ts b/server/typescript/packages/docs-site/src/explorer/types.ts index 9fc5a69ce5..30dcaf5c39 100644 --- a/server/typescript/packages/docs-site/src/explorer/types.ts +++ b/server/typescript/packages/docs-site/src/explorer/types.ts @@ -19,6 +19,9 @@ export interface ExplorerNode { name: string; /** The package of the node's top-level ancestor, "" when it has none. */ package: string; + /** Its position among its siblings in the effective tree (0-based): declaration order, + * which `nodes` (sorted by id) does not keep. */ + order: number; /** The id of the node this one is nested in; absent on a top-level node. */ parent?: string; /** The id `extends` names, as the effective tree spells it. */ @@ -70,7 +73,7 @@ export interface ExplorerLedgerRow { digest: string; implementedBy: { ref: string; resolves: boolean; target?: string }[]; supersededBy?: { ref: string; resolves: boolean; target?: string }; - diagnostics: { code: string; severity: string; source: string }[]; + diagnostics: { code: string; severity: string; source: string; message: string }[]; verdict: string; } @@ -109,6 +112,15 @@ export interface ExplorerSlice { nodes: string[]; } +/** One HTTP route the project mounts for a node, as the run that generated the routes states + * it. */ +export interface ExplorerRoute { + node: string; + method: string; + /** The mounted path, with the project's `apiPrefix`: `/api/orders/{id}`. */ + path: string; +} + export interface ExplorerJson { format: typeof EXPLORER_FORMAT; nodes: ExplorerNode[]; @@ -117,5 +129,7 @@ export interface ExplorerJson { ledger?: ExplorerLedger; /** Absent without a manifest. */ generated?: ExplorerGenerated[]; + /** Absent without a routes input. Sorted by node, then path, then method. */ + api?: ExplorerRoute[]; slices: ExplorerSlice[]; } diff --git a/server/typescript/packages/docs-site/src/index.ts b/server/typescript/packages/docs-site/src/index.ts index 6fdf286c97..98f363b62c 100644 --- a/server/typescript/packages/docs-site/src/index.ts +++ b/server/typescript/packages/docs-site/src/index.ts @@ -1,6 +1,6 @@ export { generateSite, DEFAULT_ASSET_BASE } from "./site.js"; export type { SiteOptions, SiteResult } from "./site.js"; -export { SITE_TEMPLATE_NAMES, SITE_ASSET_NAMES, readSiteFile } from "./scaffold.js"; +export { SITE_TEMPLATE_NAMES, SITE_ASSET_NAMES, CLASSIC_TEMPLATE_NAMES, CLASSIC_ASSET_NAMES, readSiteFile } from "./scaffold.js"; export type { MetaDataTypeProvider } from "@metaobjectsdev/metadata"; export { buildExplorer, serializeExplorer } from "./explorer/build.js"; export type { ExplorerInput } from "./explorer/build.js"; @@ -17,3 +17,6 @@ export type { ExplorerSlice, ExplorerSliceKind, } from "./explorer/types.js"; +export { generateExplorerSite, readPromptTexts, EXPLORER_TEMPLATE_NAMES, EXPLORER_ASSET_NAMES, CYTOSCAPE_PATH } from "./explorer/site.js"; +export type { ExplorerSiteOptions, ExplorerSiteResult } from "./explorer/site.js"; +export type { ExplorerRoute } from "./explorer/types.js"; diff --git a/server/typescript/packages/docs-site/src/link-check.ts b/server/typescript/packages/docs-site/src/link-check.ts index 14fcd55977..f71405e812 100644 --- a/server/typescript/packages/docs-site/src/link-check.ts +++ b/server/typescript/packages/docs-site/src/link-check.ts @@ -15,7 +15,9 @@ export function checkLinks(outDir: string, pages: string[]): string[] { // A root-relative href is served from outside the site (an `assetBase` mirror); the site's // own links are all relative. if (/^(https?:|mailto:|#$|\/)/.test(href)) continue; - const [file = "", anchor] = href.split("#"); + const [target0 = "", anchor] = href.split("#"); + // A query string selects a view on the page (`map.html?slice=…`); the file is what must exist. + const file = target0.split("?")[0] ?? ""; const target = file === "" ? page : normalize(join(dirname(page), file)); const abs = join(outDir, target); if (!existsSync(abs)) { errs.push(`${page} -> ${href}`); continue; } diff --git a/server/typescript/packages/docs-site/src/scaffold.ts b/server/typescript/packages/docs-site/src/scaffold.ts index e0636338e2..972dbbf205 100644 --- a/server/typescript/packages/docs-site/src/scaffold.ts +++ b/server/typescript/packages/docs-site/src/scaffold.ts @@ -2,8 +2,8 @@ import { readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -/** The 9 mustache templates the site is built from (basenames under templates/). */ -export const SITE_TEMPLATE_NAMES: readonly string[] = [ +/** The classic site's 9 mustache templates (basenames under templates/). */ +export const CLASSIC_TEMPLATE_NAMES: readonly string[] = [ "chrome-head.mustache", "chrome-foot.mustache", "index.html.mustache", @@ -15,8 +15,37 @@ export const SITE_TEMPLATE_NAMES: readonly string[] = [ "coverage.html.mustache", ]; -/** The site's themeable assets (basenames under assets/). search-index.json is generated, not themed. */ -export const SITE_ASSET_NAMES: readonly string[] = ["site.css", "site.js"]; +/** The classic site's themeable assets. search-index.json is generated, not themed. */ +export const CLASSIC_ASSET_NAMES: readonly string[] = ["site.css", "site.js"]; + +/** The explorer's templates (basenames under templates/), which `meta eject docs-site` copies. */ +export const EXPLORER_TEMPLATE_NAMES: readonly string[] = [ + "explorer-head.mustache", + "explorer-foot.mustache", + "explorer-card.mustache", + "explorer-overview.html.mustache", + "explorer-map.html.mustache", + "explorer-object.html.mustache", + "explorer-prompt.html.mustache", + "explorer-prompts.html.mustache", + "explorer-requirements.html.mustache", + "explorer-requirement.html.mustache", + "explorer-matrix.html.mustache", + "explorer-trace.html.mustache", + "explorer-gaps.html.mustache", + "explorer-api.html.mustache", + "explorer-model.html.mustache", + "explorer-package.html.mustache", +]; + +/** The explorer's themeable assets (basenames under assets/). */ +export const EXPLORER_ASSET_NAMES: readonly string[] = ["explorer.css", "explorer.js"]; + +/** Every template `meta eject docs-site` copies: both sites' themes, so either can be owned. */ +export const SITE_TEMPLATE_NAMES: readonly string[] = [...CLASSIC_TEMPLATE_NAMES, ...EXPLORER_TEMPLATE_NAMES]; + +/** Every asset `meta eject docs-site` copies. */ +export const SITE_ASSET_NAMES: readonly string[] = [...CLASSIC_ASSET_NAMES, ...EXPLORER_ASSET_NAMES]; /** Read a bundled template or asset by basename (for scaffolding into a consumer). */ export function readSiteFile(kind: "template" | "asset", name: string): string { diff --git a/server/typescript/packages/docs-site/templates/explorer-api.html.mustache b/server/typescript/packages/docs-site/templates/explorer-api.html.mustache new file mode 100644 index 0000000000..62b5695a83 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-api.html.mustache @@ -0,0 +1,5 @@ +

    API

    +{{#recorded}}
    Every route the generated code mounts, by the object it serves: {{{summary}}}.
    +{{#hasGroups}}
    {{#groups}}

    {{{linkHtml}}} {{{kind}}}{{#isReadOnly}} read-only{{/isReadOnly}}

    {{#routes}}
    {{{method}}} {{{path}}}
    {{/routes}}
    {{/groups}}
    {{/hasGroups}} +{{^hasGroups}}
    The run generated no routes.
    {{/hasGroups}}{{/recorded}} +{{^recorded}}
    The run that built this site recorded no routes: it generated none, or ran without the routes generator.
    {{/recorded}} diff --git a/server/typescript/packages/docs-site/templates/explorer-card.mustache b/server/typescript/packages/docs-site/templates/explorer-card.mustache new file mode 100644 index 0000000000..80980b53c0 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-card.mustache @@ -0,0 +1,7 @@ +
    +

    {{{levelHtml}}}{{{linkHtml}}} {{{statusHtml}}}{{{verdictHtml}}}

    +
    {{{statement}}}
    +
    {{{barHtml}}}
    {{{countsLine}}}
    + {{#hasChildren}}
      {{#children}}
    • {{{levelHtml}}}{{{linkHtml}}} {{{glyphHtml}}}
    • {{/children}}
    {{/hasChildren}} +
    Summary from the levels below
    No summary is generated in this build.
    +
    diff --git a/server/typescript/packages/docs-site/templates/explorer-foot.mustache b/server/typescript/packages/docs-site/templates/explorer-foot.mustache new file mode 100644 index 0000000000..04793fa69f --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-foot.mustache @@ -0,0 +1,7 @@ + +
    Built from explorer.json by the metaobjects docs-site generator{{#stamp}} · {{{stamp}}}{{/stamp}}. Static: no server, no LLM call.
    + +{{#needsGraph}}{{/needsGraph}} + + + diff --git a/server/typescript/packages/docs-site/templates/explorer-gaps.html.mustache b/server/typescript/packages/docs-site/templates/explorer-gaps.html.mustache new file mode 100644 index 0000000000..cddd165931 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-gaps.html.mustache @@ -0,0 +1,5 @@ +

    Gaps

    +
    What the model and the gate can already point at. Each card says whether it comes from the shipped gate or is a check this explorer adds.
    +
    +{{#cards}}

    {{{title}}} {{{count}}} {{{source}}}

    {{{whyHtml}}}
    {{{bodyHtml}}}
    +{{/cards}}
    diff --git a/server/typescript/packages/docs-site/templates/explorer-head.mustache b/server/typescript/packages/docs-site/templates/explorer-head.mustache new file mode 100644 index 0000000000..c29d481267 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-head.mustache @@ -0,0 +1,19 @@ + + + + + +{{{pageTitle}}} · {{{siteTitle}}} + + + + + +
    + {{{siteTitle}}} model explorer + + + +
    +
    + diff --git a/server/typescript/packages/docs-site/templates/explorer-map.html.mustache b/server/typescript/packages/docs-site/templates/explorer-map.html.mustache new file mode 100644 index 0000000000..05893b9e7a --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-map.html.mustache @@ -0,0 +1,13 @@ +

    Model map

    +
    Entities and the references between them. A slice is the set of model nodes a requirement subtree claims, a package holds, or a prompt reads and returns.
    +
    + + + + + + +
    +
    Click a node to see why it exists, what it holds and what was generated from it. Double-click to open its page.
    +
    + diff --git a/server/typescript/packages/docs-site/templates/explorer-matrix.html.mustache b/server/typescript/packages/docs-site/templates/explorer-matrix.html.mustache new file mode 100644 index 0000000000..655821bd40 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-matrix.html.mustache @@ -0,0 +1,5 @@ +

    Traceability matrix

    +
    Rows are requirements that name the model; columns are stored entities and prompts, most claimed first. An empty column is a node nothing claims; a cell's colour and glyph are the row's declared status.
    +{{#hasRows}}
    {{{legendHtml}}}
    +
    {{{tableHtml}}}
    {{/hasRows}} +{{^hasRows}}
    {{#hasRequirements}}No requirement names the model yet: only L4 and L5 entries do.{{/hasRequirements}}{{^hasRequirements}}This model declares no requirements, so there is nothing to trace.{{/hasRequirements}}
    {{/hasRows}} diff --git a/server/typescript/packages/docs-site/templates/explorer-model.html.mustache b/server/typescript/packages/docs-site/templates/explorer-model.html.mustache new file mode 100644 index 0000000000..b71705cae9 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-model.html.mustache @@ -0,0 +1,5 @@ +

    Packages

    +
    Every package in the model and what it declares.
    +
    +{{#packageCards}}

    {{{name}}}

    {{{kindLineHtml}}}
    {{{membersHtml}}}
    +{{/packageCards}}
    diff --git a/server/typescript/packages/docs-site/templates/explorer-object.html.mustache b/server/typescript/packages/docs-site/templates/explorer-object.html.mustache new file mode 100644 index 0000000000..24d87b772d --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-object.html.mustache @@ -0,0 +1,56 @@ +
    {{{crumbsHtml}}}
    +

    {{{name}}} {{#isAbstract}}abstract{{/isAbstract}}{{#isReadOnly}}read-only view{{/isReadOnly}}{{#isUnclaimed}}unclaimed{{/isUnclaimed}}

    + +{{#description}}
    {{{description}}}
    {{/description}} +
    {{{kindLabel}}} · {{{storageLine}}}{{#extendsHtml}} · extends {{{extendsHtml}}}{{/extendsHtml}}
    +
    +
    +

    Why it exists

    + {{#hasWhy}}
    + {{#whyRows}} + {{/whyRows}}
    CapabilityRequirementLevelStatusOn
    {{{capabilityHtml}}}{{{reqHtml}}}
    {{{statement}}}
    {{{levelHtml}}}{{{statusHtml}}}{{{onHtml}}}
    {{/hasWhy}} + {{^hasWhy}}
    {{{whyEmptyHtml}}}
    {{/hasWhy}} + {{#projection}} +

    Read model

    +
    + {{#basesHtml}}
    Surfaces fields of {{{basesHtml}}}.
    {{/basesHtml}} + {{#hasOrigins}}
    {{#origins}}{{/origins}}
    FieldOriginDefinition
    {{{field}}}{{{origin}}}{{{definitionHtml}}}
    {{/hasOrigins}} +
    + {{/projection}} + {{#report}} +

    Report

    +
    + {{#fromHtml}}{{/fromHtml}} + {{#spineHtml}}{{/spineHtml}} + {{#dimensionsHtml}}{{/dimensionsHtml}} + {{#measuresHtml}}{{/measuresHtml}} + {{#segmentHtml}}{{/segmentHtml}} + {{#filterHtml}}{{/filterHtml}} +
    From{{{fromHtml}}}
    Spine{{{spineHtml}}}
    Dimensions{{{dimensionsHtml}}}
    Measures{{{measuresHtml}}}
    Segment{{{segmentHtml}}}
    Filter{{{filterHtml}}}
    + {{/report}} + {{#hasFields}}

    Fields

    +
    {{#hasColumn}}{{/hasColumn}}{{#showClaims}}{{/showClaims}} + {{#fields}}{{#hasColumn}}{{/hasColumn}}{{#showClaims}}{{/showClaims}} + {{/fields}}
    FieldTypeColumnFlagsClaimed at L5
    {{{name}}} {{{inheritedHtml}}}{{{type}}}{{{refHtml}}}{{{valuesHtml}}}{{{column}}}{{{flagsHtml}}}{{{claimsHtml}}}
    {{/hasFields}} + {{#hasKeys}}

    Keys and references

    +
    {{#keys}}{{/keys}}
    {{{kind}}} {{{name}}} {{{inheritedHtml}}}{{{shape}}}{{{targetHtml}}}
    {{/hasKeys}} + {{#hasReporting}}

    Reporting vocabulary

    +
    {{#reporting}}{{/reporting}}
    NameKindDefinition
    {{{name}}}{{{kind}}}{{{definitionHtml}}}
    {{/hasReporting}} + {{#hasLayouts}}

    Screens declared

    {{#layouts}}
    {{{kind}}} {{{name}}}{{#detailHtml}}: {{{detailHtml}}}{{/detailHtml}}
    {{/layouts}}{{/hasLayouts}} +
    + +
    diff --git a/server/typescript/packages/docs-site/templates/explorer-overview.html.mustache b/server/typescript/packages/docs-site/templates/explorer-overview.html.mustache new file mode 100644 index 0000000000..4a96540ac3 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-overview.html.mustache @@ -0,0 +1,25 @@ +

    {{{heading}}}

    +
    Built from {{{sourcesLine}}}. Every number below is computed from the project's metadata or the gate's own output.
    +
    +{{#tiles}}
    {{{n}}}
    {{{l}}}
    +{{/tiles}}
    +{{#hasRequirements}}{{{legendHtml}}}{{/hasRequirements}} +{{#hasRequirements}} +

    Features requirement.functional, by level

    +{{#hasFeatures}}
    +{{#featureCards}}{{> card}}{{/featureCards}} +
    {{/hasFeatures}} +{{^hasFeatures}}
    No requirement.functional is declared.
    {{/hasFeatures}} +

    Qualities requirement.architectural, the non-functional policies

    +{{#hasQualities}}
    +{{#qualityCards}}{{> card}}{{/qualityCards}} +
    {{/hasQualities}} +{{^hasQualities}}
    No requirement.architectural is declared.
    {{/hasQualities}} +{{/hasRequirements}} +{{^hasRequirements}} +
    This model declares no requirements yet, so this page cannot say what each part is for. Declare requirement.functional entries (levels 1 to 3 for the problem, 4 and 5 naming the model) and this page opens on them, with every entity traced to the feature it serves.
    +{{/hasRequirements}} +

    Packages what the model holds

    +
    +{{#packageCards}}

    {{{name}}}

    {{{kindLineHtml}}}
    {{{membersHtml}}}
    +{{/packageCards}}
    diff --git a/server/typescript/packages/docs-site/templates/explorer-package.html.mustache b/server/typescript/packages/docs-site/templates/explorer-package.html.mustache new file mode 100644 index 0000000000..1a7b656913 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-package.html.mustache @@ -0,0 +1,5 @@ +
    {{{crumbsHtml}}}
    +

    {{{name}}}

    +
    +{{#rows}} +{{/rows}}
    NameKindStorageFieldsClaim
    {{{linkHtml}}} {{{abstractHtml}}}{{#description}}
    {{{description}}}
    {{/description}}
    {{{kind}}}{{{storage}}}{{fieldCount}}{{{statusHtml}}}
    diff --git a/server/typescript/packages/docs-site/templates/explorer-prompt.html.mustache b/server/typescript/packages/docs-site/templates/explorer-prompt.html.mustache new file mode 100644 index 0000000000..913025221f --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-prompt.html.mustache @@ -0,0 +1,27 @@ +
    {{{crumbsHtml}}}
    +

    {{{name}}} {{#isUnclaimed}}unclaimed{{/isUnclaimed}}

    + +{{#description}}
    {{{description}}}
    {{/description}} +
    {{{attrsHtml}}}
    +
    +
    +

    Payload: {{{payloadHtml}}}

    + {{#hasPayload}}
    {{#payloadRows}}{{/payloadRows}}
    FieldTypeUsed in text
    {{{name}}} {{{requiredHtml}}}{{{type}}}{{{refHtml}}}{{{usedHtml}}}
    {{/hasPayload}} + {{^hasPayload}}
    No payload: the text renders from nothing typed.
    {{/hasPayload}} +

    Reply: {{{replyHtml}}}

    + {{#hasReply}}
    {{#replyRows}}{{/replyRows}}
    FieldType
    {{{name}}}{{{type}}}{{{valuesHtml}}}
    {{/hasReply}} + {{^hasReply}}
    Outbound only: no reply parser.
    {{/hasReply}} +

    Why it exists

    + {{#hasWhy}}
    {{#whyRows}}{{/whyRows}}
    CapabilityRequirementLevelStatus
    {{{capabilityHtml}}}{{{reqHtml}}}
    {{{statement}}}
    {{{levelHtml}}}{{{statusHtml}}}
    {{/hasWhy}} + {{^hasWhy}}
    {{{whyEmptyHtml}}}
    {{/hasWhy}} +
    +
    +

    Text {{{textMeta}}}

    + {{#hasText}}
    {{{textHtml}}}
    {{/hasText}} + {{^hasText}}
    The text {{{textRef}}} was not found beside the model, so this page cannot show it.
    {{/hasText}} +

    Generated

    + {{#hasGenerated}}{{#generated}}
    {{{generator}}}{{#files}}
    {{{.}}}
    {{/files}}
    {{/generated}}{{/hasGenerated}} + {{^hasGenerated}}
    {{{generatedNote}}}
    {{/hasGenerated}} +
    Proven today: meta verify --templates fails if the text names a variable the payload lacks. This page shows the other direction too: payload fields the text never uses.
    +
    +
    diff --git a/server/typescript/packages/docs-site/templates/explorer-prompts.html.mustache b/server/typescript/packages/docs-site/templates/explorer-prompts.html.mustache new file mode 100644 index 0000000000..65b8bc94d7 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-prompts.html.mustache @@ -0,0 +1,6 @@ +

    Prompts

    +
    Each declared template, its typed payload, its reply type, and the requirements that claim it.
    +{{#hasRows}}
    +{{#rows}} +{{/rows}}
    TemplatePayloadReplyClaimed by
    {{{linkHtml}}} {{{kind}}}{{#description}}
    {{{description}}}
    {{/description}}
    {{{payloadHtml}}}{{{replyHtml}}}{{{claimsHtml}}}
    {{/hasRows}} +{{^hasRows}}
    This model declares no template.*.
    {{/hasRows}} diff --git a/server/typescript/packages/docs-site/templates/explorer-requirement.html.mustache b/server/typescript/packages/docs-site/templates/explorer-requirement.html.mustache new file mode 100644 index 0000000000..de8d0825e6 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-requirement.html.mustache @@ -0,0 +1,20 @@ +
    {{{crumbsHtml}}}
    +

    {{{levelHtml}}}{{{name}}} {{{statusHtml}}}{{{dispositionHtml}}}{{{verdictHtml}}}

    + +
    {{{address}}}
    +
    +
    +

    Statement

    {{{statement}}}

    Counterexample

    {{{counterexample}}}{{#hasDescription}}

    Scope

    {{{description}}}
    {{/hasDescription}}
    +

    Implemented by

    + {{#hasLinks}}
    {{#linkRows}}{{/linkRows}}
    ReferenceKindResolves
    {{{refHtml}}}{{{kind}}}{{{resolvesHtml}}}
    {{/hasLinks}} + {{^hasLinks}}
    {{{linksEmpty}}}
    {{/hasLinks}} + {{#hasBelow}}

    Below ({{childCount}}){{#deeper}} {{belowCount}} in all{{/deeper}}

    {{{belowBarHtml}}}
      {{#children}}
    • {{{levelHtml}}}{{{linkHtml}}} {{{statusHtml}}}
    • {{/children}}
    {{/hasBelow}} +
    {{#sliceHref}}Show this slice on the model map{{/sliceHref}}{{#sliceHref}}{{#traceHref}} · {{/traceHref}}{{/sliceHref}}{{#traceHref}}Trace to code{{/traceHref}}
    +
    +
    +

    What the build proves about this entry

    +
    {{#proof}}{{/proof}}
    {{{what}}}{{{verdictHtml}}}{{{howHtml}}}
    + {{#trackedHtml}}

    Tracked by

    {{{trackedHtml}}}{{/trackedHtml}} + {{#digest}}

    Statement digest

    {{{digest}}}
    Moves when the statement changes; a summary of this entry would be pinned to it.
    {{/digest}} +
    +
    diff --git a/server/typescript/packages/docs-site/templates/explorer-requirements.html.mustache b/server/typescript/packages/docs-site/templates/explorer-requirements.html.mustache new file mode 100644 index 0000000000..b4ec94a992 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-requirements.html.mustache @@ -0,0 +1,6 @@ +

    Requirements

    +
    Hierarchy is nesting. L1 to L3 describe the problem; only L4 (an object or prompt) and L5 (a member) may name the model.
    + +{{{legendHtml}}} +{{#hasTree}}
    {{{treeHtml}}}
    {{/hasTree}} +{{^hasTree}}
    {{{emptyNote}}}
    {{/hasTree}} diff --git a/server/typescript/packages/docs-site/templates/explorer-trace.html.mustache b/server/typescript/packages/docs-site/templates/explorer-trace.html.mustache new file mode 100644 index 0000000000..f6f5ca414d --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-trace.html.mustache @@ -0,0 +1,6 @@ +

    Trace

    +
    From intent to code: requirement levels, then the model nodes they name, then the files generated from those nodes.
    +{{#hasStarts}}
    + +
    Hand-written modules that import the generated files are not scanned in this build, so the trace stops at the generated files. Click a requirement or a model node to open its page.
    {{/hasStarts}} +{{^hasStarts}}
    This model declares no requirements, so there is nothing to trace from. Every object's generated files are listed on its own page.
    {{/hasStarts}} diff --git a/server/typescript/packages/docs-site/test/explorer-build.test.ts b/server/typescript/packages/docs-site/test/explorer-build.test.ts index 00718de1eb..7f0fc1f0f7 100644 --- a/server/typescript/packages/docs-site/test/explorer-build.test.ts +++ b/server/typescript/packages/docs-site/test/explorer-build.test.ts @@ -61,6 +61,26 @@ describe("buildExplorer", () => { expect(build({ verify: true }).generated).toBeUndefined(); }); + test("routes are kept per known node, sorted, deduplicated; without them there is no api", () => { + const api = buildExplorer({ + model: json("effective.json"), + routes: [ + { node: "acme::shop::Order", method: "post", path: "/api/orders" }, + { node: "acme::shop::Order", method: "GET", path: "/api/orders" }, + { node: "acme::shop::Order", method: "GET", path: "/api/orders" }, + { node: "acme::shop::Customer", method: "GET", path: "/api/customers/{id}" }, + { node: "acme::shop::Gone", method: "GET", path: "/api/gone" }, + { node: "acme::shop::Order", path: "/api/no-method" }, + ], + }).api; + expect(api).toEqual([ + { node: "acme::shop::Customer", method: "GET", path: "/api/customers/{id}" }, + { node: "acme::shop::Order", method: "GET", path: "/api/orders" }, + { node: "acme::shop::Order", method: "POST", path: "/api/orders" }, + ]); + expect(build().api).toBeUndefined(); + }); + test("a requirement slice holds the subtree, its targets and the owner of a claimed member", () => { const slice = build().slices.find((s) => s.id === "requirement:acme::shop::Shop.Checkout.Orders.Recorded"); expect(slice?.nodes).toEqual([ diff --git a/server/typescript/packages/docs-site/test/explorer-site.test.ts b/server/typescript/packages/docs-site/test/explorer-site.test.ts new file mode 100644 index 0000000000..56dade146e --- /dev/null +++ b/server/typescript/packages/docs-site/test/explorer-site.test.ts @@ -0,0 +1,247 @@ +// The model explorer site (`generateExplorerSite`) over the public fixtures: the shop +// explorer-conformance fixture (requirements, a prompt, an unclaimed entity) and the +// persistence-conformance fitness model (projections, reports, no requirements). +import { afterAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative, resolve } from "node:path"; +import { MetaDataLoader, canonicalSerializeEffective } from "@metaobjectsdev/metadata"; +import { FileSource } from "@metaobjectsdev/metadata/core"; +import { + buildExplorer, + EXPLORER_ASSET_NAMES, + generateExplorerSite, + readPromptTexts, + type ExplorerJson, +} from "../src/index.js"; + +const REPO = resolve(import.meta.dir, "../../../../.."); +const SHOP = join(REPO, "fixtures/explorer-conformance/shop"); +const FITNESS = join(REPO, "fixtures/persistence-conformance/canonical"); + +const dirs: string[] = []; +const scratch = (): string => { + const d = mkdtempSync(join(tmpdir(), "explorer-site-")); + dirs.push(d); + return d; +}; +afterAll(() => { + for (const d of dirs) rmSync(d, { recursive: true, force: true }); +}); + +function filesUnder(dir: string): string[] { + return readdirSync(dir, { recursive: true, withFileTypes: true }) + .filter((f) => f.isFile()) + .map((f) => relative(dir, join(f.parentPath, f.name)).split("\\").join("/")) + .sort(); +} + +const shopExplorer = (): ExplorerJson => JSON.parse(readFileSync(join(SHOP, "expected.json"), "utf8")) as ExplorerJson; + +function buildShop(): { out: string; pages: string[]; files: string[]; page: (p: string) => string } { + const explorer = shopExplorer(); + const out = scratch(); + const r = generateExplorerSite({ + explorer, + outDir: out, + title: "Shop", + texts: readPromptTexts(explorer, [join(SHOP, "project/prompts"), join(SHOP, "project")]), + }); + return { out, pages: r.pages, files: r.files, page: (p) => readFileSync(join(out, p), "utf8") }; +} + +async function buildFitness(): Promise<{ page: (p: string) => string; files: string[] }> { + const root = (await new MetaDataLoader().load([new FileSource(join(FITNESS, "meta.fitness.json"))])).root; + const explorer = buildExplorer({ model: JSON.parse(canonicalSerializeEffective(root)) as unknown }); + const out = scratch(); + const r = generateExplorerSite({ explorer, outDir: out, title: "Fitness", texts: readPromptTexts(explorer, [join(FITNESS, "prompts"), FITNESS]) }); + return { files: r.files, page: (p) => readFileSync(join(out, p), "utf8") }; +} + +describe("explorer site over explorer-conformance/shop", () => { + const shop = buildShop(); + + test("writes every screen, one page per object, prompt and requirement, and passes its own link check", () => { + for (const p of [ + "index.html", "map.html", "matrix.html", "trace.html", "prompts.html", "api.html", "gaps.html", + "requirements/features.html", "requirements/qualities.html", "model/index.html", + "model/acme/shop/Order.html", "model/acme/shop/AuditEntry.html", "model/acme/shop/OrderNotePrompt.html", + "requirements/acme/shop/Shop.html", "requirements/acme/shop/Shop.Checkout.Orders.Recorded.Quotable.html", + "requirements/acme/shop/Addressable.html", + ]) expect(shop.pages).toContain(p); + // generateExplorerSite throws on a dangling link, so reaching here is the link check passing. + for (const a of EXPLORER_ASSET_NAMES) expect(shop.files).toContain(`assets/${a}`); + expect(shop.files).toContain("assets/explorer-data.js"); + expect(shop.files).toContain("explorer.json"); + expect(filesUnder(shop.out)).toEqual([...shop.files].sort()); + }); + + test("is deterministic: a second build writes the same bytes", () => { + const again = buildShop(); + for (const f of shop.files) expect(again.page(f)).toBe(shop.page(f)); + }); + + test("the explorer.json it ships is the one it read", () => { + expect(shop.page("explorer.json")).toBe(readFileSync(join(SHOP, "expected.json"), "utf8")); + }); + + test("S1, the main page: what the software does, from the counts and the requirement tree", () => { + const index = shop.page("index.html"); + expect(index).toContain("

    What Shop does

    "); + expect(index.match(/class="card tile"/g)?.length).toBe(6); + expect(index).toContain('
    2/3
    '); + expect(index).toContain("requirements: 8 features, 1 quality"); + // A feature card: level badge, declared status, the roll-up bar, the level below. + expect(index).toContain('L1'); + expect(index).toContain('href="requirements/acme/shop/Shop.html"'); + expect(index).toContain('