From 5ca4dff0e3967ee3cc9aee489bba0601f19ef2e2 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 18:02:14 -0500 Subject: [PATCH 1/6] test(conformance): add the model-lint conformance corpus fixtures/model-lint-conformance/ (18 cases) pins the codes, addresses and message text of the three advisory model authoring lints verify prints: WARN_OVERLAY_IMPLICIT, WARN_NAME_SURROUNDING_WHITESPACE / WARN_NAME_INTERNAL_WHITESPACE and WARN_DEPRECATED_REFERENCE. The corpus is byte-identical to the Python lane's copy, so whichever lands second rebases cleanly. The corpora count moves to 44 and CONFORMANCE.md gains its row. --- AGENTS.md | 2 +- docs/CONFORMANCE.md | 4 +- fixtures/model-lint-conformance/README.md | 52 +++++++ .../clean/expected.json | 3 + .../clean/input/meta.app.json | 66 +++++++++ .../deprecation-dotted-field/expected.json | 9 ++ .../input/meta.app.json | 75 ++++++++++ .../expected.json | 14 ++ .../input/meta.app.json | 42 ++++++ .../deprecation-passthrough/expected.json | 9 ++ .../input/meta.app.json | 128 ++++++++++++++++++ .../expected.json | 14 ++ .../input/meta.app.json | 85 ++++++++++++ .../expected.json | 14 ++ .../input/meta.app.json | 95 +++++++++++++ .../expected.json | 3 + .../input/meta.app.json | 42 ++++++ .../expected.json | 9 ++ .../input/meta.app.json | 45 ++++++ .../name-internal-space-object/expected.json | 9 ++ .../input/meta.app.json | 27 ++++ .../name-no-break-space/expected.json | 9 ++ .../name-no-break-space/input/meta.app.json | 32 +++++ .../expected.json | 9 ++ .../input/meta.app.json | 27 ++++ .../name-trailing-space-field/expected.json | 9 ++ .../input/meta.app.json | 32 +++++ .../name-whitespace-only/expected.json | 9 ++ .../name-whitespace-only/input/meta.app.json | 32 +++++ .../overlay-flagged-clean/expected.json | 3 + .../overlay-flagged-clean/input/meta.app.json | 27 ++++ .../input/meta.app.ui.json | 20 +++ .../overlay-implicit-yaml/expected.json | 9 ++ .../input/meta.a-user.yaml | 10 ++ .../input/meta.b-user-ui.yaml | 7 + .../input/meta.c-user-db.yaml | 8 ++ .../overlay-implicit/expected.json | 9 ++ .../overlay-implicit/input/meta.app.json | 27 ++++ .../overlay-implicit/input/meta.app.ui.json | 19 +++ .../overlay-relative-package/expected.json | 9 ++ .../input/meta.garage.json | 28 ++++ .../input/meta.garage.ui.json | 19 +++ 42 files changed, 1099 insertions(+), 2 deletions(-) create mode 100644 fixtures/model-lint-conformance/README.md create mode 100644 fixtures/model-lint-conformance/clean/expected.json create mode 100644 fixtures/model-lint-conformance/clean/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/deprecation-dotted-field/expected.json create mode 100644 fixtures/model-lint-conformance/deprecation-dotted-field/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/deprecation-extends-inherited/expected.json create mode 100644 fixtures/model-lint-conformance/deprecation-extends-inherited/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/deprecation-passthrough/expected.json create mode 100644 fixtures/model-lint-conformance/deprecation-passthrough/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/deprecation-reason-ends-sentence/expected.json create mode 100644 fixtures/model-lint-conformance/deprecation-reason-ends-sentence/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/deprecation-references-entity/expected.json create mode 100644 fixtures/model-lint-conformance/deprecation-references-entity/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/deprecation-self-reference-clean/expected.json create mode 100644 fixtures/model-lint-conformance/deprecation-self-reference-clean/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/name-inherited-reported-once/expected.json create mode 100644 fixtures/model-lint-conformance/name-inherited-reported-once/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/name-internal-space-object/expected.json create mode 100644 fixtures/model-lint-conformance/name-internal-space-object/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/name-no-break-space/expected.json create mode 100644 fixtures/model-lint-conformance/name-no-break-space/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/name-surrounding-and-internal-identity/expected.json create mode 100644 fixtures/model-lint-conformance/name-surrounding-and-internal-identity/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/name-trailing-space-field/expected.json create mode 100644 fixtures/model-lint-conformance/name-trailing-space-field/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/name-whitespace-only/expected.json create mode 100644 fixtures/model-lint-conformance/name-whitespace-only/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/overlay-flagged-clean/expected.json create mode 100644 fixtures/model-lint-conformance/overlay-flagged-clean/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/overlay-flagged-clean/input/meta.app.ui.json create mode 100644 fixtures/model-lint-conformance/overlay-implicit-yaml/expected.json create mode 100644 fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.a-user.yaml create mode 100644 fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.b-user-ui.yaml create mode 100644 fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.c-user-db.yaml create mode 100644 fixtures/model-lint-conformance/overlay-implicit/expected.json create mode 100644 fixtures/model-lint-conformance/overlay-implicit/input/meta.app.json create mode 100644 fixtures/model-lint-conformance/overlay-implicit/input/meta.app.ui.json create mode 100644 fixtures/model-lint-conformance/overlay-relative-package/expected.json create mode 100644 fixtures/model-lint-conformance/overlay-relative-package/input/meta.garage.json create mode 100644 fixtures/model-lint-conformance/overlay-relative-package/input/meta.garage.ui.json diff --git a/AGENTS.md b/AGENTS.md index 81d09c4325..ffcb86b822 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (578 fixtures; 43 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (578 fixtures; 44 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/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index d564c614ea..19170673a8 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -1,6 +1,6 @@ # Conformance coverage -The MetaObjects standard ships **43 shared conformance corpora** under +The MetaObjects standard ships **44 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 @@ -55,6 +55,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) | 1 | ✓ (docs emit is TS-owned) | — | — | — | — | | [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | +| [`fixtures/model-lint-conformance/`](../fixtures/model-lint-conformance/) (the `verify` overlay, node-name and deprecated-reference authoring lints) | 18 | ✓ (reference) | ✓ | — (1.3.0 build, D8) | — (1.3.0 build, D8) | — (1.3.0 build, D8) | | [`fixtures/requirement-check-conformance/`](../fixtures/requirement-check-conformance/) (the `verify` requirement gate, ADR-0057) | 49 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | | [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 27 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | | [`fixtures/rules-check-conformance/`](../fixtures/rules-check-conformance/) (the `verify` business-rules gate, ADR-0066) | 16 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | @@ -120,6 +121,7 @@ the contracts and the conformance kits that hold every port to them. scenarios), `agent-context-conformance/`, `metamodel-docs/`, `fmt-conformance/` (the canonical serializer, surfaced per-file — ADR-0034's "canonical format" is core), `field-lint-conformance/` (the advisory field lint every port's `verify` prints), + `model-lint-conformance/` (the advisory overlay, node-name and deprecated-reference lints), `requirement-check-conformance/` (the requirement gate every port's `verify` runs; a drift gate is core, and it is not ejectable in any port), `rules-check-conformance/` (the business-rules gate every port's `verify` runs, ADR-0066) and diff --git a/fixtures/model-lint-conformance/README.md b/fixtures/model-lint-conformance/README.md new file mode 100644 index 0000000000..995f169799 --- /dev/null +++ b/fixtures/model-lint-conformance/README.md @@ -0,0 +1,52 @@ +# `verify` model-lint conformance corpus + +`meta verify` prints three advisory **model authoring lints** about metadata that loads +with no error: + +| Code | What it reports | +|---|---| +| `WARN_OVERLAY_IMPLICIT` | A root-level declaration redeclared in a second file without `overlay: true`. | +| `WARN_NAME_SURROUNDING_WHITESPACE` | A node name with leading or trailing whitespace. | +| `WARN_NAME_INTERNAL_WHITESPACE` | A node name with whitespace inside it. | +| `WARN_DEPRECATED_REFERENCE` | A node that depends on a `deprecated` node through `extends`, `@objectRef`, `@references`, or an origin's `@from` / `@of` / `@via`. | + +All are warnings and never a load error, and none reaches an exit code. The rules each one +applies are in [`docs/features/cli.md`](../../docs/features/cli.md). This corpus is the +shared source of truth for the codes, the addresses and the message text. + +Runners today: TypeScript (the reference, `packages/cli/test/model-lint-conformance.test.ts`) +and Python (`tests/conformance/test_model_lint_conformance.py`). + +## Fixture format + +Each case is a directory: + +- `input/` holds one or more metadata documents (`.json` or `.yaml`). +- `expected.json` holds `{ "findings": [{ "code", "path", "message" }] }`. + +A runner does three things, in this order: + +1. Load `input/` with the port's loader, strict, and assert **no load errors**. This is + what proves each condition loads today. +2. Run the overlay lint over the files of `input/` **sorted by name** (that order is the + load order: the first unflagged declaration of a key is its base), naming each file + relative to `input/`. Run the name lint and the deprecation lint over the loaded model. +3. Compare the findings with `expected.json` as an unordered set of + `(code, path, message)`. + +## Paths + +- An overlay finding is about a file, not a node: its `path` is `""`, and the message + names the file. +- A name finding's `path` is the node's address: the root-level node's + `::`, then `.`-joined child names. A segment holding whitespace is + JSON-quoted, so the whitespace stays visible (`acme::app::Account."code "`). +- A deprecation finding's `path` is the referring node's address: `::`, then + `.`-joined child names. An origin reports against the field that carries it. + +## Whitespace + +"Whitespace" is exactly the ECMAScript `\s` class, the same set `String.prototype.trim` +strips: ASCII space, tab, LF, CR, VT and FF, plus U+00A0, U+1680, U+2000–U+200A, U+2028, +U+2029, U+202F, U+205F, U+3000 and U+FEFF. A port whose regex `\s` differs (Python's +includes U+001C–U+001F and U+0085, and omits U+FEFF) spells the class out. diff --git a/fixtures/model-lint-conformance/clean/expected.json b/fixtures/model-lint-conformance/clean/expected.json new file mode 100644 index 0000000000..2ef5648615 --- /dev/null +++ b/fixtures/model-lint-conformance/clean/expected.json @@ -0,0 +1,3 @@ +{ + "findings": [] +} diff --git a/fixtures/model-lint-conformance/clean/input/meta.app.json b/fixtures/model-lint-conformance/clean/input/meta.app.json new file mode 100644 index 0000000000..546acd2f8c --- /dev/null +++ b/fixtures/model-lint-conformance/clean/input/meta.app.json @@ -0,0 +1,66 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Team", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "name" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Player", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "teamId" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "team_fk", + "@fields": [ + "teamId" + ], + "@references": "Team" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/deprecation-dotted-field/expected.json b/fixtures/model-lint-conformance/deprecation-dotted-field/expected.json new file mode 100644 index 0000000000..44a5765376 --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-dotted-field/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_DEPRECATED_REFERENCE", + "path": "acme::app::Match.team_fk", + "message": "references (@references) deprecated field.string acme::app::Team.code" + } + ] +} diff --git a/fixtures/model-lint-conformance/deprecation-dotted-field/input/meta.app.json b/fixtures/model-lint-conformance/deprecation-dotted-field/input/meta.app.json new file mode 100644 index 0000000000..da7c0e1e35 --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-dotted-field/input/meta.app.json @@ -0,0 +1,75 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Team", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "code", + "@deprecated": "" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "identity.secondary": { + "name": "code_uk", + "@fields": [ + "code" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Match", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "teamCode" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "team_fk", + "@fields": [ + "teamCode" + ], + "@references": "Team.code" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/deprecation-extends-inherited/expected.json b/fixtures/model-lint-conformance/deprecation-extends-inherited/expected.json new file mode 100644 index 0000000000..adb9f43fe2 --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-extends-inherited/expected.json @@ -0,0 +1,14 @@ +{ + "findings": [ + { + "code": "WARN_DEPRECATED_REFERENCE", + "path": "acme::app::Middle", + "message": "extends deprecated object.entity acme::app::Legacy: use Modern" + }, + { + "code": "WARN_DEPRECATED_REFERENCE", + "path": "acme::app::Widget", + "message": "extends deprecated object.entity acme::app::Middle: use Modern" + } + ] +} diff --git a/fixtures/model-lint-conformance/deprecation-extends-inherited/input/meta.app.json b/fixtures/model-lint-conformance/deprecation-extends-inherited/input/meta.app.json new file mode 100644 index 0000000000..2bfb9f1244 --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-extends-inherited/input/meta.app.json @@ -0,0 +1,42 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Legacy", + "abstract": true, + "@deprecated": "use Modern", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Middle", + "abstract": true, + "extends": "Legacy" + } + }, + { + "object.entity": { + "name": "Widget", + "extends": "Middle" + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/deprecation-passthrough/expected.json b/fixtures/model-lint-conformance/deprecation-passthrough/expected.json new file mode 100644 index 0000000000..60fa71ecbd --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-passthrough/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_DEPRECATED_REFERENCE", + "path": "acme::app::AddressView.countryName", + "message": "origin.passthrough @from references deprecated field.string acme::app::Country.name: use isoName. Replaced by isoName." + } + ] +} diff --git a/fixtures/model-lint-conformance/deprecation-passthrough/input/meta.app.json b/fixtures/model-lint-conformance/deprecation-passthrough/input/meta.app.json new file mode 100644 index 0000000000..eb2bd4ceb4 --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-passthrough/input/meta.app.json @@ -0,0 +1,128 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Country", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "name", + "@deprecated": "use isoName", + "@replacedBy": "isoName" + } + }, + { + "field.string": { + "name": "isoName" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "source.rdb": { + "@table": "countries" + } + } + ] + } + }, + { + "object.entity": { + "name": "Address", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "countryId" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "source.rdb": { + "@table": "addresses" + } + }, + { + "identity.reference": { + "name": "country_fk", + "@fields": [ + "countryId" + ], + "@references": "Country" + } + }, + { + "relationship.association": { + "name": "country", + "@objectRef": "Country", + "@cardinality": "one" + } + } + ] + } + }, + { + "object.projection": { + "name": "AddressView", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_address" + } + }, + { + "field.long": { + "name": "id", + "extends": "Address.id" + } + }, + { + "field.string": { + "name": "countryName", + "children": [ + { + "origin.passthrough": { + "@from": "Country.name", + "@via": "Address.country" + } + } + ] + } + }, + { + "identity.primary": { + "name": "pk", + "extends": "Address.pk" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/deprecation-reason-ends-sentence/expected.json b/fixtures/model-lint-conformance/deprecation-reason-ends-sentence/expected.json new file mode 100644 index 0000000000..9fec3add25 --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-reason-ends-sentence/expected.json @@ -0,0 +1,14 @@ +{ + "findings": [ + { + "code": "WARN_DEPRECATED_REFERENCE", + "path": "acme::app::Doohickey", + "message": "extends deprecated object.entity acme::app::Gizmo. Replaced by acme::app::Modern." + }, + { + "code": "WARN_DEPRECATED_REFERENCE", + "path": "acme::app::Widget", + "message": "extends deprecated object.entity acme::app::Legacy: Merged into Modern. Replaced by acme::app::Modern." + } + ] +} diff --git a/fixtures/model-lint-conformance/deprecation-reason-ends-sentence/input/meta.app.json b/fixtures/model-lint-conformance/deprecation-reason-ends-sentence/input/meta.app.json new file mode 100644 index 0000000000..c154c8f09e --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-reason-ends-sentence/input/meta.app.json @@ -0,0 +1,85 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Legacy", + "abstract": true, + "@deprecated": "Merged into Modern.", + "@replacedBy": "acme::app::Modern", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Modern", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Widget", + "extends": "Legacy" + } + }, + { + "object.entity": { + "name": "Gizmo", + "abstract": true, + "@deprecated": "", + "@replacedBy": "acme::app::Modern", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Doohickey", + "extends": "Gizmo" + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/deprecation-references-entity/expected.json b/fixtures/model-lint-conformance/deprecation-references-entity/expected.json new file mode 100644 index 0000000000..689bfbcca2 --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-references-entity/expected.json @@ -0,0 +1,14 @@ +{ + "findings": [ + { + "code": "WARN_DEPRECATED_REFERENCE", + "path": "acme::app::Match.home_fk", + "message": "references (@references) deprecated object.entity acme::app::Team: the league no longer tracks teams. Replaced by acme::app::Club." + }, + { + "code": "WARN_DEPRECATED_REFERENCE", + "path": "acme::app::Match.homeTeam", + "message": "references (@objectRef) deprecated object.entity acme::app::Team: the league no longer tracks teams. Replaced by acme::app::Club." + } + ] +} diff --git a/fixtures/model-lint-conformance/deprecation-references-entity/input/meta.app.json b/fixtures/model-lint-conformance/deprecation-references-entity/input/meta.app.json new file mode 100644 index 0000000000..c0f7e54cbf --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-references-entity/input/meta.app.json @@ -0,0 +1,95 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Team", + "@deprecated": "the league no longer tracks teams", + "@replacedBy": "acme::app::Club", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "code" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Club", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Match", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "homeTeamId" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "home_fk", + "@fields": [ + "homeTeamId" + ], + "@references": "Team" + } + }, + { + "relationship.association": { + "name": "homeTeam", + "@objectRef": "Team", + "@cardinality": "one" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/deprecation-self-reference-clean/expected.json b/fixtures/model-lint-conformance/deprecation-self-reference-clean/expected.json new file mode 100644 index 0000000000..2ef5648615 --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-self-reference-clean/expected.json @@ -0,0 +1,3 @@ +{ + "findings": [] +} diff --git a/fixtures/model-lint-conformance/deprecation-self-reference-clean/input/meta.app.json b/fixtures/model-lint-conformance/deprecation-self-reference-clean/input/meta.app.json new file mode 100644 index 0000000000..3363c941bb --- /dev/null +++ b/fixtures/model-lint-conformance/deprecation-self-reference-clean/input/meta.app.json @@ -0,0 +1,42 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Category", + "@deprecated": "categories are flat now", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "parentId" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "parent_fk", + "@fields": [ + "parentId" + ], + "@references": "Category" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/name-inherited-reported-once/expected.json b/fixtures/model-lint-conformance/name-inherited-reported-once/expected.json new file mode 100644 index 0000000000..d1ec0fedd2 --- /dev/null +++ b/fixtures/model-lint-conformance/name-inherited-reported-once/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_NAME_SURROUNDING_WHITESPACE", + "path": "acme::app::Base.\"code \"", + "message": "field.string name \"code \" has leading or trailing whitespace, which is almost certainly unintended — rename it (to \"code\", presumably), and pin @column if the physical column must keep its name. The whitespace is carried into every identifier, column and wire key derived from the name." + } + ] +} diff --git a/fixtures/model-lint-conformance/name-inherited-reported-once/input/meta.app.json b/fixtures/model-lint-conformance/name-inherited-reported-once/input/meta.app.json new file mode 100644 index 0000000000..8bd703caf0 --- /dev/null +++ b/fixtures/model-lint-conformance/name-inherited-reported-once/input/meta.app.json @@ -0,0 +1,45 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Base", + "abstract": true, + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "code " + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Widget", + "extends": "Base" + } + }, + { + "object.entity": { + "name": "Gadget", + "extends": "Base" + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/name-internal-space-object/expected.json b/fixtures/model-lint-conformance/name-internal-space-object/expected.json new file mode 100644 index 0000000000..9849a2a751 --- /dev/null +++ b/fixtures/model-lint-conformance/name-internal-space-object/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_NAME_INTERNAL_WHITESPACE", + "path": "acme::app::\"Line Item\"", + "message": "object.entity name \"Line Item\" contains whitespace. A name is an identifier: derived column names and wire keys carry the space, and generated code cannot use it as one. Consider renaming it." + } + ] +} diff --git a/fixtures/model-lint-conformance/name-internal-space-object/input/meta.app.json b/fixtures/model-lint-conformance/name-internal-space-object/input/meta.app.json new file mode 100644 index 0000000000..ffe43be49b --- /dev/null +++ b/fixtures/model-lint-conformance/name-internal-space-object/input/meta.app.json @@ -0,0 +1,27 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Line Item", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/name-no-break-space/expected.json b/fixtures/model-lint-conformance/name-no-break-space/expected.json new file mode 100644 index 0000000000..e3451c781e --- /dev/null +++ b/fixtures/model-lint-conformance/name-no-break-space/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_NAME_SURROUNDING_WHITESPACE", + "path": "acme::app::Account.\"label \"", + "message": "field.string name \"label \" has leading or trailing whitespace, which is almost certainly unintended — rename it (to \"label\", presumably), and pin @column if the physical column must keep its name. The whitespace is carried into every identifier, column and wire key derived from the name." + } + ] +} diff --git a/fixtures/model-lint-conformance/name-no-break-space/input/meta.app.json b/fixtures/model-lint-conformance/name-no-break-space/input/meta.app.json new file mode 100644 index 0000000000..48ae4627d7 --- /dev/null +++ b/fixtures/model-lint-conformance/name-no-break-space/input/meta.app.json @@ -0,0 +1,32 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Account", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "label " + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/name-surrounding-and-internal-identity/expected.json b/fixtures/model-lint-conformance/name-surrounding-and-internal-identity/expected.json new file mode 100644 index 0000000000..32da308d86 --- /dev/null +++ b/fixtures/model-lint-conformance/name-surrounding-and-internal-identity/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_NAME_SURROUNDING_WHITESPACE", + "path": "acme::app::Account.\" account pk\"", + "message": "identity.primary name \" account pk\" has leading or trailing whitespace, which is almost certainly unintended — rename it (to \"account pk\", presumably). The whitespace is carried into every identifier, column and wire key derived from the name. It also contains whitespace inside it." + } + ] +} diff --git a/fixtures/model-lint-conformance/name-surrounding-and-internal-identity/input/meta.app.json b/fixtures/model-lint-conformance/name-surrounding-and-internal-identity/input/meta.app.json new file mode 100644 index 0000000000..c2ed0a8fda --- /dev/null +++ b/fixtures/model-lint-conformance/name-surrounding-and-internal-identity/input/meta.app.json @@ -0,0 +1,27 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Account", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": " account pk", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/name-trailing-space-field/expected.json b/fixtures/model-lint-conformance/name-trailing-space-field/expected.json new file mode 100644 index 0000000000..6343d79418 --- /dev/null +++ b/fixtures/model-lint-conformance/name-trailing-space-field/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_NAME_SURROUNDING_WHITESPACE", + "path": "acme::app::Account.\"defaultCurrencyId \"", + "message": "field.long name \"defaultCurrencyId \" has leading or trailing whitespace, which is almost certainly unintended — rename it (to \"defaultCurrencyId\", presumably), and pin @column if the physical column must keep its name. The whitespace is carried into every identifier, column and wire key derived from the name." + } + ] +} diff --git a/fixtures/model-lint-conformance/name-trailing-space-field/input/meta.app.json b/fixtures/model-lint-conformance/name-trailing-space-field/input/meta.app.json new file mode 100644 index 0000000000..0974a95b8a --- /dev/null +++ b/fixtures/model-lint-conformance/name-trailing-space-field/input/meta.app.json @@ -0,0 +1,32 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Account", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "defaultCurrencyId " + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/name-whitespace-only/expected.json b/fixtures/model-lint-conformance/name-whitespace-only/expected.json new file mode 100644 index 0000000000..f0cfb793ad --- /dev/null +++ b/fixtures/model-lint-conformance/name-whitespace-only/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_NAME_SURROUNDING_WHITESPACE", + "path": "acme::app::Account.\" \"", + "message": "field.string name \" \" has leading or trailing whitespace, which is almost certainly unintended — rename it, and pin @column if the physical column must keep its name. The whitespace is carried into every identifier, column and wire key derived from the name." + } + ] +} diff --git a/fixtures/model-lint-conformance/name-whitespace-only/input/meta.app.json b/fixtures/model-lint-conformance/name-whitespace-only/input/meta.app.json new file mode 100644 index 0000000000..c0fba6c3da --- /dev/null +++ b/fixtures/model-lint-conformance/name-whitespace-only/input/meta.app.json @@ -0,0 +1,32 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "Account", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": " " + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/overlay-flagged-clean/expected.json b/fixtures/model-lint-conformance/overlay-flagged-clean/expected.json new file mode 100644 index 0000000000..2ef5648615 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-flagged-clean/expected.json @@ -0,0 +1,3 @@ +{ + "findings": [] +} diff --git a/fixtures/model-lint-conformance/overlay-flagged-clean/input/meta.app.json b/fixtures/model-lint-conformance/overlay-flagged-clean/input/meta.app.json new file mode 100644 index 0000000000..2363cc7737 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-flagged-clean/input/meta.app.json @@ -0,0 +1,27 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "User", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/overlay-flagged-clean/input/meta.app.ui.json b/fixtures/model-lint-conformance/overlay-flagged-clean/input/meta.app.ui.json new file mode 100644 index 0000000000..22d6e8f6a7 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-flagged-clean/input/meta.app.ui.json @@ -0,0 +1,20 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "User", + "overlay": true, + "children": [ + { + "field.string": { + "name": "displayName" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/overlay-implicit-yaml/expected.json b/fixtures/model-lint-conformance/overlay-implicit-yaml/expected.json new file mode 100644 index 0000000000..a0d4845087 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-implicit-yaml/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_OVERLAY_IMPLICIT", + "path": "", + "message": "acme::app::User is redeclared in meta.b-user-ui.yaml without overlay: true — add the flag so a removed or renamed target fails loudly (ERR_OVERLAY_NO_TARGET) instead of silently becoming a new object" + } + ] +} diff --git a/fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.a-user.yaml b/fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.a-user.yaml new file mode 100644 index 0000000000..2feec84fba --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.a-user.yaml @@ -0,0 +1,10 @@ +metadata: + package: acme::app + children: + - object.entity: + name: User + children: + - field.long: id + - identity.primary: + name: pk + fields: [id] diff --git a/fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.b-user-ui.yaml b/fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.b-user-ui.yaml new file mode 100644 index 0000000000..d458f78bf6 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.b-user-ui.yaml @@ -0,0 +1,7 @@ +metadata: + package: acme::app + children: + - object.entity: + name: User + children: + - field.string: displayName diff --git a/fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.c-user-db.yaml b/fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.c-user-db.yaml new file mode 100644 index 0000000000..e289f57c09 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-implicit-yaml/input/meta.c-user-db.yaml @@ -0,0 +1,8 @@ +metadata: + package: acme::app + children: + - object.entity: + name: User + overlay: true + children: + - field.string: email diff --git a/fixtures/model-lint-conformance/overlay-implicit/expected.json b/fixtures/model-lint-conformance/overlay-implicit/expected.json new file mode 100644 index 0000000000..1ba47733de --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-implicit/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_OVERLAY_IMPLICIT", + "path": "", + "message": "acme::app::User is redeclared in meta.app.ui.json without overlay: true — add the flag so a removed or renamed target fails loudly (ERR_OVERLAY_NO_TARGET) instead of silently becoming a new object" + } + ] +} diff --git a/fixtures/model-lint-conformance/overlay-implicit/input/meta.app.json b/fixtures/model-lint-conformance/overlay-implicit/input/meta.app.json new file mode 100644 index 0000000000..2363cc7737 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-implicit/input/meta.app.json @@ -0,0 +1,27 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "User", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/overlay-implicit/input/meta.app.ui.json b/fixtures/model-lint-conformance/overlay-implicit/input/meta.app.ui.json new file mode 100644 index 0000000000..0d6cdad795 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-implicit/input/meta.app.ui.json @@ -0,0 +1,19 @@ +{ + "metadata.root": { + "package": "acme::app", + "children": [ + { + "object.entity": { + "name": "User", + "children": [ + { + "field.string": { + "name": "displayName" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/overlay-relative-package/expected.json b/fixtures/model-lint-conformance/overlay-relative-package/expected.json new file mode 100644 index 0000000000..1b07079f12 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-relative-package/expected.json @@ -0,0 +1,9 @@ +{ + "findings": [ + { + "code": "WARN_OVERLAY_IMPLICIT", + "path": "", + "message": "acme::garage::Garage is redeclared in meta.garage.ui.json without overlay: true — add the flag so a removed or renamed target fails loudly (ERR_OVERLAY_NO_TARGET) instead of silently becoming a new object" + } + ] +} diff --git a/fixtures/model-lint-conformance/overlay-relative-package/input/meta.garage.json b/fixtures/model-lint-conformance/overlay-relative-package/input/meta.garage.json new file mode 100644 index 0000000000..6bfeed5a27 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-relative-package/input/meta.garage.json @@ -0,0 +1,28 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Garage", + "package": "::garage", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/model-lint-conformance/overlay-relative-package/input/meta.garage.ui.json b/fixtures/model-lint-conformance/overlay-relative-package/input/meta.garage.ui.json new file mode 100644 index 0000000000..3c6d2545e6 --- /dev/null +++ b/fixtures/model-lint-conformance/overlay-relative-package/input/meta.garage.ui.json @@ -0,0 +1,19 @@ +{ + "metadata.root": { + "package": "acme::garage", + "children": [ + { + "object.entity": { + "name": "Garage", + "children": [ + { + "field.string": { + "name": "label" + } + } + ] + } + } + ] + } +} From 346a649b360d73d9c396181f20515af658884f42 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 17:59:15 -0500 Subject: [PATCH 2/6] feat(csharp): run the overlay, name and deprecation lints in verify (D8) dotnet meta verify now prints the three model authoring lints Node meta verify has: WARN_OVERLAY_IMPLICIT, WARN_NAME_SURROUNDING_WHITESPACE / WARN_NAME_INTERNAL_WHITESPACE and WARN_DEPRECATED_REFERENCE, in the Node order (overlays, names, deprecations) before the field lint. They are advisory, never change the exit code, and each is muted by its own --no-*-lint flag or META_NO_*_LINT=1. The raw-document reader moves out of FieldLint into RawDocument and now reads booleans (overlay: true), keeping the text YAML wrote so a field literally named true still reads as a name. ModelLintConformanceTests runs the shared fixtures/model-lint-conformance/ corpus; VerifyModelLintTests drives the built CLI for the order, the flags and the variables. --- CHANGELOG.md | 8 + docs/features/cli.md | 4 + docs/ports/csharp.md | 8 + .../MetaObjects.Cli.Tests/CliProcess.cs | 2 + .../ModelLintConformanceTests.cs | 61 ++++++ .../VerifyModelLintTests.cs | 123 ++++++++++++ .../csharp/MetaObjects.Cli/DeprecationLint.cs | 189 ++++++++++++++++++ server/csharp/MetaObjects.Cli/FieldLint.cs | 85 +------- server/csharp/MetaObjects.Cli/LintFinding.cs | 49 +++++ server/csharp/MetaObjects.Cli/ModelLints.cs | 68 +++++++ server/csharp/MetaObjects.Cli/NameLint.cs | 106 ++++++++++ server/csharp/MetaObjects.Cli/OverlayLint.cs | 132 ++++++++++++ server/csharp/MetaObjects.Cli/Program.cs | 19 +- server/csharp/MetaObjects.Cli/RawDocument.cs | 110 ++++++++++ 14 files changed, 886 insertions(+), 78 deletions(-) create mode 100644 server/csharp/MetaObjects.Cli.Tests/ModelLintConformanceTests.cs create mode 100644 server/csharp/MetaObjects.Cli.Tests/VerifyModelLintTests.cs create mode 100644 server/csharp/MetaObjects.Cli/DeprecationLint.cs create mode 100644 server/csharp/MetaObjects.Cli/LintFinding.cs create mode 100644 server/csharp/MetaObjects.Cli/ModelLints.cs create mode 100644 server/csharp/MetaObjects.Cli/NameLint.cs create mode 100644 server/csharp/MetaObjects.Cli/OverlayLint.cs create mode 100644 server/csharp/MetaObjects.Cli/RawDocument.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 58140a2a8d..a2ec1fe7d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,14 @@ here.** ## [Unreleased] +- **C#: `dotnet meta verify` runs the three model authoring lints.** The overlay lint + (`WARN_OVERLAY_IMPLICIT`), the node-name lint (`WARN_NAME_SURROUNDING_WHITESPACE`, + `WARN_NAME_INTERNAL_WHITESPACE`) and the deprecated-reference lint (`WARN_DEPRECATED_REFERENCE`) + now print on every `dotnet meta verify`, as they do in Node `meta verify`, before the field lint. + They are advisory, never change the exit code, and are muted by `--no-overlay-lint`, + `--no-name-lint` and `--no-deprecation-lint`, or by `META_NO_OVERLAY_LINT=1`, + `META_NO_NAME_LINT=1` and `META_NO_DEPRECATION_LINT=1`. C# runs the shared + `fixtures/model-lint-conformance/` corpus. - **C#: an unchanged file is never rewritten.** `dotnet meta gen` already left identical output alone when the project keeps a hash manifest. It now does the same on the path with no manifest (output written outside the project, or a program that runs the generators with no state directory), which diff --git a/docs/features/cli.md b/docs/features/cli.md index 106509d071..9ba7de66a5 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -128,6 +128,10 @@ Rules of the contract: `deprecated` inherited through the TARGET's own `extends` chain still counts. Advisory only, appears as `deprecations` in `--format json|toon`, and is muted with `--no-deprecation-lint` or `META_NO_DEPRECATION_LINT=1`. +- **The three lints above also run in `dotnet meta verify`**, with the same flags and + environment variables, printed as text on stderr in the same order (overlays, names, + deprecations), before the field lint. The codes, addresses and message text are gated by + [`fixtures/model-lint-conformance/`](../../fixtures/model-lint-conformance/README.md). - **The field authoring lint runs on every `verify`, in every port.** It reports two mistakes that load with no error. `WARN_REFERENCE_FIELD_NOT_FOUND` flags an `identity.reference` whose `@fields` names a field the object does not have; a field diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 96b3cdd002..59c9dbc4d4 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -243,6 +243,14 @@ against `prompts/` when it exists, else `templates/`, and fails the same way whe exists. It also runs the codegen gate when `--out ` and `codegen/Generators.cs` are present, and skips it with a note otherwise; name both subverbs to require both. +Every `dotnet meta verify` also prints the advisory authoring lints on stderr, whichever gates +run: unflagged cross-file redeclarations (`WARN_OVERLAY_IMPLICIT`), whitespace in a node name +(`WARN_NAME_SURROUNDING_WHITESPACE`, `WARN_NAME_INTERNAL_WHITESPACE`), references to a +`deprecated` node (`WARN_DEPRECATED_REFERENCE`), then the field lint. None changes the exit code. +Mute each with `--no-overlay-lint`, `--no-name-lint`, `--no-deprecation-lint` or +`--no-field-lint`, or the matching `META_NO_*_LINT=1`. The codes and message text match Node +`meta verify`, gated by `fixtures/model-lint-conformance/` and `fixtures/field-lint-conformance/`. + The output directory and the namespace are project settings, so `gen` and `verify` cannot disagree about them. Declare them once in `.metaobjects/config.json`; `outDir` is relative to the directory holding `.metaobjects/`: diff --git a/server/csharp/MetaObjects.Cli.Tests/CliProcess.cs b/server/csharp/MetaObjects.Cli.Tests/CliProcess.cs index 047de8a2fe..ed89bc785b 100644 --- a/server/csharp/MetaObjects.Cli.Tests/CliProcess.cs +++ b/server/csharp/MetaObjects.Cli.Tests/CliProcess.cs @@ -30,6 +30,8 @@ internal static (int ExitCode, string Stdout, string Stderr) RunWithEnvironment( // The child inherits the runner's environment, so a variable that changes the CLI's behaviour // is removed unless the test sets it: an exported META_REQUIRE_IMPLEMENTERS must not flip a test. psi.Environment.Remove("META_REQUIRE_IMPLEMENTERS"); + foreach (var optOut in new[] { FieldLint.EnvOptOut, OverlayLint.EnvOptOut, NameLint.EnvOptOut, DeprecationLint.EnvOptOut }) + psi.Environment.Remove(optOut); foreach (var (key, value) in environment) psi.Environment[key] = value; psi.ArgumentList.Add(ResolveCliDll()); foreach (var a in args) psi.ArgumentList.Add(a); diff --git a/server/csharp/MetaObjects.Cli.Tests/ModelLintConformanceTests.cs b/server/csharp/MetaObjects.Cli.Tests/ModelLintConformanceTests.cs new file mode 100644 index 0000000000..a0e5c0ce5d --- /dev/null +++ b/server/csharp/MetaObjects.Cli.Tests/ModelLintConformanceTests.cs @@ -0,0 +1,61 @@ +using System.Text.Json; +using MetaObjects.Cli; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Cli.Tests; + +/// +/// Cross-port model-lint conformance corpus — fixtures/model-lint-conformance/ (the overlay, +/// node-name and deprecated-reference lints). See that directory's README.md for the fixture +/// format. Every case is LOADED strict first, so "this loads with no error today" is proven by the +/// fixture, and only then linted. A mismatch here is a bug in THIS port's lint, never in the fixture. +/// +public class ModelLintConformanceTests +{ + private static readonly string CorpusDir = ResolveCorpusDir(); + + private static string ResolveCorpusDir() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null) + { + var candidate = Path.Combine(dir.FullName, "fixtures", "model-lint-conformance"); + if (Directory.Exists(candidate)) return candidate; + dir = dir.Parent; + } + throw new DirectoryNotFoundException( + "Could not locate fixtures/model-lint-conformance/ by walking up from " + AppContext.BaseDirectory); + } + + public static IEnumerable Fixtures() => + Directory.GetDirectories(CorpusDir).OrderBy(d => d, StringComparer.Ordinal).Select(d => new object[] { Path.GetFileName(d) }); + + [Fact] + public void Discovers_the_corpus() => Assert.NotEmpty(Fixtures()); + + [Theory] + [MemberData(nameof(Fixtures))] + public void Fixture(string name) + { + var input = Path.Combine(CorpusDir, name, "input"); + using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(CorpusDir, name, "expected.json"))); + var expected = doc.RootElement.GetProperty("findings").EnumerateArray() + .Select(f => (f.GetProperty("code").GetString()!, f.GetProperty("path").GetString()!, f.GetProperty("message").GetString()!)) + .Order().ToList(); + + var load = MetaDataLoader.FromDirectory(input, strict: true); + Assert.Empty(load.Errors.Select(e => e.Code + ": " + e.Message)); + + // The overlay lint names each file relative to input/, in the order the loader reads them. + var sources = Directory.GetFiles(input).OrderBy(f => f, StringComparer.Ordinal) + .Select(f => (IMetaDataSource)new FileSource(f, Path.GetFileName(f))); + var actual = OverlayLint.Lint(sources) + .Concat(NameLint.Lint(load.Root)) + .Concat(DeprecationLint.Lint(load.Root)) + .Select(f => (f.Code, f.Path, f.Message)) + .Order().ToList(); + + Assert.Equal(expected, actual); + } +} diff --git a/server/csharp/MetaObjects.Cli.Tests/VerifyModelLintTests.cs b/server/csharp/MetaObjects.Cli.Tests/VerifyModelLintTests.cs new file mode 100644 index 0000000000..b623fcd9b6 --- /dev/null +++ b/server/csharp/MetaObjects.Cli.Tests/VerifyModelLintTests.cs @@ -0,0 +1,123 @@ +using Xunit; + +namespace MetaObjects.Cli.Tests; + +/// +/// dotnet meta verify — the three model authoring lints, end to end: each printed as its own +/// advisory section on stderr in the Node order (overlays, names, deprecations, then fields), none +/// reaching the exit code, each muted by its own flag and by its own environment variable. Drives +/// the BUILT CLI () so this proves the wiring; the finding text is gated +/// cross-port by . +/// +public sealed class VerifyModelLintTests : IDisposable +{ + private const string OverlayHeader = "dotnet meta verify — overlays: 1 unflagged cross-file redeclaration(s) (advisory — does not fail the build):"; + private const string NamesHeader = "dotnet meta verify — names: 1 authoring warning(s) (advisory — does not fail the build):"; + private const string DeprecationsHeader = "dotnet meta verify — deprecations: 1 reference(s) to a deprecated node (advisory — does not fail the build):"; + + private readonly string _tmp = Directory.CreateTempSubdirectory("mo-model-lint-").FullName; + + public void Dispose() + { + try { Directory.Delete(_tmp, recursive: true); } catch { /* best effort */ } + } + + /// + /// One finding per lint: Owner redeclared in a second file without overlay: true, + /// a field named "label ", and Item extending the deprecated Legacy. + /// + private (string Model, string Templates) Project(bool clean = false) + { + var model = Path.Combine(_tmp, "model"); + Directory.CreateDirectory(model); + var label = clean ? "label" : "label "; + var deprecated = clean ? "" : "\"@deprecated\": \"use Item\","; + File.WriteAllText(Path.Combine(model, "meta.app.json"), $$""" + { "metadata.root": { "package": "app", "children": [ + { "object.entity": { "name": "Owner", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } ] } }, + { "object.entity": { "name": "Legacy", "abstract": true, {{deprecated}} "children": [ + { "field.string": { "name": "{{label}}" } } ] } }, + { "object.entity": { "name": "Item", "extends": "Legacy", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } ] } } + ] } } + """); + var overlay = clean ? "\"overlay\": true," : ""; + File.WriteAllText(Path.Combine(model, "meta.app.ui.json"), $$""" + { "metadata.root": { "package": "app", "children": [ + { "object.entity": { "name": "Owner", {{overlay}} "children": [ + { "field.string": { "name": "nickname" } } ] } } + ] } } + """); + var templates = Path.Combine(_tmp, "templates"); + Directory.CreateDirectory(templates); + return (model, templates); + } + + private (int ExitCode, string Stderr) Verify(IReadOnlyDictionary? env = null, params string[] extra) + { + var (model, templates) = Project(); + var (exitCode, stdout, stderr) = CliProcess.RunWithEnvironment( + _tmp, env ?? new Dictionary(), ["verify", model, "--templates", "--prompts", templates, .. extra]); + Assert.True(exitCode == 0, $"exit={exitCode}\nstdout={stdout}\nstderr={stderr}"); + return (exitCode, stderr); + } + + [Fact] + public void Findings_print_in_order_and_do_not_change_the_exit_code() + { + var (_, stderr) = Verify(); + + var overlays = stderr.IndexOf(OverlayHeader, StringComparison.Ordinal); + var names = stderr.IndexOf(NamesHeader, StringComparison.Ordinal); + var deprecations = stderr.IndexOf(DeprecationsHeader, StringComparison.Ordinal); + Assert.True(overlays >= 0 && names > overlays && deprecations > names, stderr); + // The file is named relative to the explicit metadata directory. + Assert.Contains(" WARN_OVERLAY_IMPLICIT: app::Owner is redeclared in meta.app.ui.json without overlay: true", stderr); + Assert.Contains(" WARN_NAME_SURROUNDING_WHITESPACE [app::Legacy.\"label \"]: ", stderr); + Assert.Contains(" WARN_DEPRECATED_REFERENCE [app::Item]: extends deprecated object.entity app::Legacy: use Item", stderr); + } + + [Fact] + public void Clean_metadata_prints_no_section() + { + var (model, templates) = Project(clean: true); + var (exitCode, _, stderr) = CliProcess.Run(_tmp, "verify", model, "--templates", "--prompts", templates); + + Assert.Equal(0, exitCode); + Assert.DoesNotContain("overlays:", stderr); + Assert.DoesNotContain("names:", stderr); + Assert.DoesNotContain("deprecations:", stderr); + } + + public static TheoryData OptOuts() => new() + { + { "--no-overlay-lint", OverlayLint.EnvOptOut, "WARN_OVERLAY_IMPLICIT" }, + { "--no-name-lint", NameLint.EnvOptOut, "WARN_NAME_SURROUNDING_WHITESPACE" }, + { "--no-deprecation-lint", DeprecationLint.EnvOptOut, "WARN_DEPRECATED_REFERENCE" }, + }; + + [Theory] + [MemberData(nameof(OptOuts))] + public void Each_flag_mutes_only_its_own_lint(string flag, string _, string code) + { + var (_, stderr) = Verify(null, flag); + + Assert.DoesNotContain(code, stderr); + foreach (var other in new[] { "WARN_OVERLAY_IMPLICIT", "WARN_NAME_SURROUNDING_WHITESPACE", "WARN_DEPRECATED_REFERENCE" }.Where(c => c != code)) + Assert.Contains(other, stderr); + } + + [Theory] + [MemberData(nameof(OptOuts))] + public void Each_environment_variable_mutes_only_its_own_lint(string _, string env, string code) + { + var (_, stderr) = Verify(new Dictionary { [env] = "1" }); + + Assert.DoesNotContain(code, stderr); + foreach (var other in new[] { "WARN_OVERLAY_IMPLICIT", "WARN_NAME_SURROUNDING_WHITESPACE", "WARN_DEPRECATED_REFERENCE" }.Where(c => c != code)) + Assert.Contains(other, stderr); + } +} diff --git a/server/csharp/MetaObjects.Cli/DeprecationLint.cs b/server/csharp/MetaObjects.Cli/DeprecationLint.cs new file mode 100644 index 0000000000..51308be0d0 --- /dev/null +++ b/server/csharp/MetaObjects.Cli/DeprecationLint.cs @@ -0,0 +1,189 @@ +// `dotnet meta verify` — the deprecated-REFERENCE authoring lint (#305). +// +// `deprecated` / `replacedBy` are registered documentation attributes that nothing else reads. This +// lint warns when a node DEPENDS on a node carrying `deprecated`, through the reference kinds the +// metamodel has: `extends`, `@objectRef`, `@references` and an origin's `@from` / `@of` / `@via`. +// When the deprecated node also carries `replacedBy`, the finding names the replacement. Warnings +// only: nothing here reaches an exit code. +// +// SELF-REFERENCE IS NOT A FINDING, but only the literal case: the same node, or one of its own +// ANCESTORS (the recursive-FK shape, `Category.parentId` pointing back at `Category`). A different +// node under the same entity, such as a passthrough reading a deprecated sibling field, is a real +// dependency and warns. +// +// It reads the LOADED model through the RESOLVING accessors (ADR-0039), so a target that inherits +// `deprecated` from its abstract base counts, and walks DECLARATIONS (OwnChildren()), so an +// inherited reference is reported once. +// +// Mirrors the TS reference (server/typescript/packages/cli/src/lib/deprecation-lint.ts). The code, +// the message text and the fixtures are shared: fixtures/model-lint-conformance/. + +using MetaObjects.Meta; +using static MetaObjects.Core.Documentation.DocumentationConstants; +using static MetaObjects.Core.Field.FieldConstants; +using static MetaObjects.Core.Identity.IdentityConstants; +using static MetaObjects.Core.Relationship.RelationshipConstants; +using static MetaObjects.Persistence.Origin.OriginConstants; +using static MetaObjects.Shared.BaseTypes; + +namespace MetaObjects.Cli; + +/// The advisory deprecated-reference lint dotnet meta verify runs on every invocation. +public static class DeprecationLint +{ + /// A node depends on a node that carries deprecated. + public const string WARN_DEPRECATED_REFERENCE = "WARN_DEPRECATED_REFERENCE"; + + /// Opt-out environment variable, beside --no-deprecation-lint (Node meta parity). + public const string EnvOptOut = "META_NO_DEPRECATION_LINT"; + + /// Report every reference INTO a deprecated node. + public static List Lint(MetaData root) + { + var findings = new List(); + Walk(root, root, "", findings); + return findings; + } + + private static void Walk(MetaData root, MetaData node, string prefix, List findings) + { + // OWN-ONLY (ADR-0039 sanctioned case): report each reference at its declaration. + foreach (var child in node.OwnChildren()) + { + // An origin has no name of its own: report it against the field it belongs to. + var path = child.Type == TYPE_ORIGIN ? prefix + : prefix == "" ? child.ResolutionKey() + : $"{prefix}.{child.Name}"; + CheckNode(root, child, path, findings); + Walk(root, child, path, findings); + } + } + + private static string PackageOf(MetaData node) => node.Package ?? node.FileDefaultPackage ?? ""; + + /// The nearest enclosing object.* (objects are never nested in this metamodel). + private static MetaObject? OwningObject(MetaData node) + { + var cursor = node.Parent; + while (cursor is not null and not MetaObject) cursor = cursor.Parent; + return cursor as MetaObject; + } + + /// The object's FQN, or <object FQN>.<name> for something nested inside one. + private static string AddressOf(MetaData node) + { + if (node is MetaObject obj) return obj.ResolutionKey(); + return OwningObject(node) is { } owner ? $"{owner.ResolutionKey()}.{node.Name}" : node.Name; + } + + /// The same node, or one of 's ancestors. Deliberately not symmetric. + private static bool IsSelfReference(MetaData referrer, MetaData target) + { + for (MetaData? cursor = referrer; cursor is not null; cursor = cursor.Parent) + if (ReferenceEquals(cursor, target)) return true; + return false; + } + + /// Report when it carries deprecated; true when a finding was added. + private static bool Consider(MetaData referrer, string path, string verb, MetaData target, List findings) + { + if (IsSelfReference(referrer, target)) return false; + // RESOLVING (ADR-0039): `deprecated` inherited through the target's own extends chain counts. + // Presence means deprecated: an empty reason still counts. Only an absent attr does not. + if (target.Attr(DOC_ATTR_DEPRECATED) is not string reason) return false; + var message = $"{verb} deprecated {target.Type}.{target.SubType} {AddressOf(target)}{(reason != "" ? ": " + reason : "")}"; + if (target.Attr(DOC_ATTR_REPLACED_BY) is string { Length: > 0 } replacedBy) + { + // The replacement is its own sentence, so the one before it ends first. + var ended = message.EndsWith('.') || message.EndsWith('!') || message.EndsWith('?') ? message : message + "."; + message = $"{ended} Replaced by {replacedBy}."; + } + findings.Add(new LintFinding(WARN_DEPRECATED_REFERENCE, path, message)); + return true; + } + + private static string HeadOf(string raw) + { + var dot = raw.IndexOf('.'); + return dot < 0 ? raw : raw[..dot]; + } + + private static MetaObject? ResolveEntity(MetaData root, string reference, string referrerPkg) => + NamingRefs.ResolveObjectRef(root, reference, referrerPkg) as MetaObject; + + /// The relationship or identity.reference child named . + private static MetaData? FindHop(MetaObject entity, string hopName) => + // RESOLVING (ADR-0039): an inherited hop counts. + entity.Children().FirstOrDefault(c => c.Name == hopName + && (c.Type == TYPE_RELATIONSHIP || (c.Type == TYPE_IDENTITY && c.SubType == IDENTITY_SUBTYPE_REFERENCE))); + + private static MetaObject? HopTarget(MetaData hop) => + NamingRefs.RefTarget(hop, hop.Type == TYPE_RELATIONSHIP ? RELATIONSHIP_ATTR_OBJECT_REF : IDENTITY_REFERENCE_ATTR_REFERENCES) as MetaObject; + + /// + /// A dotted Entity or Entity.field reference: the field first (the more specific + /// target), the entity only when the field was silent. A failed resolution is silent. + /// + private static void CheckEntityFieldPath( + MetaData referrer, string path, string verb, string raw, MetaObject? entity, List findings) + { + if (entity is null) return; + var head = HeadOf(raw); + var fieldName = raw.Length > head.Length ? raw[(head.Length + 1)..] : ""; + if (fieldName != "" && entity.FindField(fieldName) is { } field && Consider(referrer, path, verb, field, findings)) return; + Consider(referrer, path, verb, entity, findings); + } + + /// Walk an @via path, checking the head entity and every hop; stop at the first segment that does not resolve. + private static void CheckVia(MetaData root, MetaData origin, string path, string verb, string via, string pkg, List findings) + { + var segments = via.Split('.'); + if (segments[0] == "") return; + var current = ResolveEntity(root, segments[0], pkg); + if (current is null) return; + Consider(origin, path, verb, current, findings); + foreach (var hopName in segments.Skip(1)) + { + var hop = FindHop(current, hopName); + if (hop is null) return; + Consider(origin, path, verb, hop, findings); + var next = HopTarget(hop); + if (next is null) return; + Consider(origin, path, verb, next, findings); + current = next; + } + } + + private static void CheckOrigin(MetaData root, MetaData origin, string path, List findings) + { + var pkg = OwningObject(origin) is { } owner ? PackageOf(owner) : ""; + var label = $"origin.{origin.SubType}"; + // ADR-0039: own — origin.* never inherits (ADR-0029). + if (origin.OwnAttr(ORIGIN_PASSTHROUGH_ATTR_FROM) is string { Length: > 0 } from) + CheckEntityFieldPath(origin, path, $"{label} @from references", from, ResolveEntity(root, HeadOf(from), pkg), findings); + if (origin.OwnAttr(ORIGIN_AGGREGATE_ATTR_OF) is string { Length: > 0 } of) + CheckEntityFieldPath(origin, path, $"{label} @of references", of, ResolveEntity(root, HeadOf(of), pkg), findings); + if (origin.OwnAttr(ORIGIN_PASSTHROUGH_ATTR_VIA) is string { Length: > 0 } via) + CheckVia(root, origin, path, $"{label} @via references", via, pkg, findings); + } + + private static void CheckNode(MetaData root, MetaData node, string path, List findings) + { + if (node.SuperData is { } super) Consider(node, path, "extends", super, findings); + + if (node.Type is TYPE_RELATIONSHIP or TYPE_FIELD) + { + // ADR-0059 R7: the target the loader bound, resolved where @objectRef was declared. + var attr = node.Type == TYPE_RELATIONSHIP ? RELATIONSHIP_ATTR_OBJECT_REF : FIELD_ATTR_OBJECT_REF; + if (NamingRefs.RefTarget(node, attr) is MetaObject target) + Consider(node, path, "references (@objectRef)", target, findings); + } + + if (node.Type == TYPE_IDENTITY && node.SubType == IDENTITY_SUBTYPE_REFERENCE + && node.Attr(IDENTITY_REFERENCE_ATTR_REFERENCES) is string { Length: > 0 } raw) + CheckEntityFieldPath(node, path, "references (@references)", raw, + NamingRefs.RefTarget(node, IDENTITY_REFERENCE_ATTR_REFERENCES) as MetaObject, findings); + + if (node.Type == TYPE_ORIGIN) CheckOrigin(root, node, path, findings); + } +} diff --git a/server/csharp/MetaObjects.Cli/FieldLint.cs b/server/csharp/MetaObjects.Cli/FieldLint.cs index 72cf1128c4..784abc8932 100644 --- a/server/csharp/MetaObjects.Cli/FieldLint.cs +++ b/server/csharp/MetaObjects.Cli/FieldLint.cs @@ -45,12 +45,9 @@ public static class FieldLint /// Opt-out environment variable, beside --no-field-lint (Node meta parity). public const string EnvOptOut = "META_NO_FIELD_LINT"; - private const string KeyName = "name"; private const string KeyPackage = "package"; private const string KeyChildren = "children"; private const char TypeSubTypeSeparator = '.'; - /// The YAML authoring sugar for isArray: true — a suffix on the wrapper key. - private const string ArraySuffix = "[]"; /// One advisory finding: its code, the node's address, and the message. public sealed record Finding(string Code, string Path, string Message); @@ -118,24 +115,24 @@ public static List DeclaredDuplicateFields(string content, MetaDataForm { var findings = new List(); var normalized = content.Length > 0 && content[0] == '' ? content[1..] : content; - var parsed = format == MetaDataFormat.Yaml ? ParseYaml(normalized) : ParseJson(normalized); + var parsed = format == MetaDataFormat.Yaml ? RawDocument.ParseYaml(normalized) : RawDocument.ParseJson(normalized); if (parsed is not List> document) return findings; // JSON fuses the subtype onto the root key; sigil-free YAML may write the bare type. - var rootBody = Get(document, $"{TYPE_METADATA}{TypeSubTypeSeparator}{SUBTYPE_ROOT}") ?? Get(document, TYPE_METADATA); + var rootBody = RawDocument.Get(document, $"{TYPE_METADATA}{TypeSubTypeSeparator}{SUBTYPE_ROOT}") ?? RawDocument.Get(document, TYPE_METADATA); if (rootBody is not List> root) return findings; - var rootPkg = Get(root, KeyPackage) as string ?? ""; - if (Get(root, KeyChildren) is not List children) return findings; + var rootPkg = RawDocument.Get(root, KeyPackage) as string ?? ""; + if (RawDocument.Get(root, KeyChildren) is not List children) return findings; foreach (var child in children) { if (child is not List> wrapper) continue; foreach (var (wrapperKey, bodyValue) in wrapper) { - if (WrapperType(wrapperKey) != TYPE_OBJECT) continue; + if (RawDocument.WrapperType(wrapperKey) != TYPE_OBJECT) continue; if (bodyValue is not List> body) continue; - var name = DeclaredName(body); - if (name is null || Get(body, KeyChildren) is not List members) continue; + var name = RawDocument.DeclaredName(body); + if (name is null || RawDocument.Get(body, KeyChildren) is not List members) continue; // Insertion-ordered, so findings come out in document order. var order = new List(); @@ -145,8 +142,8 @@ public static List DeclaredDuplicateFields(string content, MetaDataForm if (member is not List> memberWrapper) continue; foreach (var (memberKey, memberBody) in memberWrapper) { - if (WrapperType(memberKey) != TYPE_FIELD) continue; - var fieldName = DeclaredName(memberBody); + if (RawDocument.WrapperType(memberKey) != TYPE_FIELD) continue; + var fieldName = RawDocument.DeclaredName(memberBody); if (fieldName is null) continue; if (!counts.TryGetValue(fieldName, out var seen)) order.Add(fieldName); counts[fieldName] = seen + 1; @@ -155,12 +152,7 @@ public static List DeclaredDuplicateFields(string content, MetaDataForm // The resolution key the parser gives a root-level node: its own `package` // (a `::`-prefixed one is relative to the root's), else the root's. - var ownPkg = Get(body, KeyPackage) as string; - var pkg = string.IsNullOrEmpty(ownPkg) - ? rootPkg - : rootPkg.Trim() != "" && ownPkg.StartsWith(PACKAGE_SEPARATOR, StringComparison.Ordinal) - ? rootPkg + ownPkg - : ownPkg; + var pkg = RawDocument.ResolvePackage(rootPkg, RawDocument.Get(body, KeyPackage) as string); var address = pkg != "" ? $"{pkg}{PACKAGE_SEPARATOR}{name}" : name; foreach (var fieldName in order) { @@ -228,61 +220,4 @@ public static void RunAdvisory( stderr.WriteLine($"dotnet meta verify — fields: {findings.Count} authoring warning(s) (advisory — does not fail the build):"); foreach (var f in findings) stderr.WriteLine($" {f.Code} [{f.Path}]: {f.Message}"); } - - // -- raw document model --------------------------------------------------- - // A mapping is an ORDERED list of pairs, a sequence a List, a scalar a string. - - private static object? Get(List> mapping, string key) - { - foreach (var (k, v) in mapping) - if (k == key) return v; - return null; - } - - /// The TYPE segment of a wrapper key: field.string[] and bare field are both field. - private static string WrapperType(string key) - { - var dot = key.IndexOf(TypeSubTypeSeparator); - var head = dot < 0 ? key : key[..dot]; - return head.EndsWith(ArraySuffix, StringComparison.Ordinal) ? head[..^ArraySuffix.Length] : head; - } - - /// A node's declared name: the body's name, or the body itself when YAML wrote a scalar. - private static string? DeclaredName(object? body) - { - var name = body is List> mapping ? Get(mapping, KeyName) : body; - return name is string s && s != "" ? s : null; - } - - private static object? ParseJson(string text) - { - using var doc = JsonDocument.Parse(text); - return FromJson(doc.RootElement); - } - - private static object? FromJson(JsonElement element) => element.ValueKind switch - { - JsonValueKind.Object => element.EnumerateObject() - .Select(p => new KeyValuePair(p.Name, FromJson(p.Value))).ToList(), - JsonValueKind.Array => element.EnumerateArray().Select(FromJson).ToList(), - JsonValueKind.String => element.GetString(), - _ => null, - }; - - private static object? ParseYaml(string text) - { - var stream = new YamlStream(); - stream.Load(new StringReader(text)); - return stream.Documents.Count == 0 ? null : FromYaml(stream.Documents[0].RootNode); - } - - private static object? FromYaml(YamlNode node) => node switch - { - YamlMappingNode mapping => mapping.Children - .Where(p => p.Key is YamlScalarNode) - .Select(p => new KeyValuePair(((YamlScalarNode)p.Key).Value ?? "", FromYaml(p.Value))).ToList(), - YamlSequenceNode sequence => sequence.Children.Select(FromYaml).ToList(), - YamlScalarNode scalar => scalar.Value, - _ => null, - }; } diff --git a/server/csharp/MetaObjects.Cli/LintFinding.cs b/server/csharp/MetaObjects.Cli/LintFinding.cs new file mode 100644 index 0000000000..f61e0a0db0 --- /dev/null +++ b/server/csharp/MetaObjects.Cli/LintFinding.cs @@ -0,0 +1,49 @@ +namespace MetaObjects.Cli; + +/// +/// One advisory finding of a model authoring lint (, , +/// ): its code, the node's address ("" when the finding is about a +/// file, not a node), and the message. A finding is always a warning: no lint reaches the exit code. +/// +public sealed record LintFinding(string Code, string Path, string Message); + +/// The one string quoting the lints share. +internal static class LintText +{ + /// + /// JSON.stringify of a string, so the message text is byte-identical to the TypeScript + /// reference: only ", \ and the C0 controls are escaped, and everything else, a + /// no-break space or a byte-order mark included, is written as itself. + /// + internal static string Quote(string value) + { + var sb = new System.Text.StringBuilder(value.Length + 2).Append('"'); + foreach (var c in value) + { + switch (c) + { + case '"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + case '\b': sb.Append("\\b"); break; + case '\f': sb.Append("\\f"); break; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + case '\t': sb.Append("\\t"); break; + default: + if (c < ' ') sb.Append("\\u").Append(((int)c).ToString("x4", System.Globalization.CultureInfo.InvariantCulture)); + else sb.Append(c); + break; + } + } + return sb.Append('"').ToString(); + } + + /// Print one lint section: its header, then a line per finding. Nothing for no findings. + internal static void Print(TextWriter stderr, string header, IReadOnlyList findings) + { + if (findings.Count == 0) return; + stderr.WriteLine($"dotnet meta verify — {header} (advisory — does not fail the build):"); + foreach (var f in findings) + stderr.WriteLine(f.Path == "" ? $" {f.Code}: {f.Message}" : $" {f.Code} [{f.Path}]: {f.Message}"); + } +} diff --git a/server/csharp/MetaObjects.Cli/ModelLints.cs b/server/csharp/MetaObjects.Cli/ModelLints.cs new file mode 100644 index 0000000000..ac7657f246 --- /dev/null +++ b/server/csharp/MetaObjects.Cli/ModelLints.cs @@ -0,0 +1,68 @@ +// `dotnet meta verify` — runs the three MODEL authoring lints (overlay, node names, deprecated +// references) and prints them in the Node `meta verify` order: overlays, names, deprecations. Each +// is advisory and muted by its own flag or environment variable; none reaches the exit code. + +using MetaObjects.Config; +using MetaObjects.Loader; + +namespace MetaObjects.Cli; + +/// The three model authoring lints dotnet meta verify runs on every invocation. +public static class ModelLints +{ + /// Which of the three lints run; each is on unless its flag or environment variable mutes it. + public sealed record Selection(bool Overlays, bool Names, bool Deprecations) + { + /// The selection the flags leave, with each lint's META_NO_*_LINT=1 applied. + public static Selection From(bool noOverlay, bool noNames, bool noDeprecations) => new( + !noOverlay && !OptedOut(OverlayLint.EnvOptOut), + !noNames && !OptedOut(NameLint.EnvOptOut), + !noDeprecations && !OptedOut(DeprecationLint.EnvOptOut)); + + private static bool OptedOut(string env) => Environment.GetEnvironmentVariable(env) == "1"; + } + + /// + /// Every metadata source in LOAD ORDER, dependency snapshots first under their dep: ids, then + /// the project's own files named relative to with forward slashes. + /// + public static List Sources(ResolvedMetadata meta, string baseDir) + { + var sources = new List(meta.Imports?.Sources() ?? []); + var files = meta.Files ?? new DirectorySource(meta.Directory).Expand().Select(f => f.FilePath).ToList(); + foreach (var file in files) + sources.Add(new FileSource(file, Path.GetRelativePath(baseDir, file).Replace('\\', '/'))); + return sources; + } + + /// + /// Run the selected lints and print their findings to . The overlay lint + /// reads the raw files, so it runs even when the model does not load; the other two read the loaded + /// model and stay silent when it does not (the load failure is reported by the gates). + /// + public static void RunAdvisory(ResolvedMetadata meta, string baseDir, Selection selection, TextWriter stderr) + { + if (!selection.Overlays && !selection.Names && !selection.Deprecations) return; + List overlays = [], names = [], deprecations = []; + try + { + if (selection.Overlays) overlays = OverlayLint.Lint(Sources(meta, baseDir)); + if (selection.Names || selection.Deprecations) + { + var load = meta.Load(); + if (load.Errors.Count == 0) + { + if (selection.Names) names = NameLint.Lint(load.Root); + if (selection.Deprecations) deprecations = DeprecationLint.Lint(load.Root); + } + } + } + catch (Exception) + { + // an advisory lint never breaks verify; print what was gathered + } + LintText.Print(stderr, $"overlays: {overlays.Count} unflagged cross-file redeclaration(s)", overlays); + LintText.Print(stderr, $"names: {names.Count} authoring warning(s)", names); + LintText.Print(stderr, $"deprecations: {deprecations.Count} reference(s) to a deprecated node", deprecations); + } +} diff --git a/server/csharp/MetaObjects.Cli/NameLint.cs b/server/csharp/MetaObjects.Cli/NameLint.cs new file mode 100644 index 0000000000..a8c3d487e2 --- /dev/null +++ b/server/csharp/MetaObjects.Cli/NameLint.cs @@ -0,0 +1,106 @@ +// `dotnet meta verify` — the node-name AUTHORING lint. +// +// The loader accepts any string as a node `name`, on every port. An adopter's metadata carried a +// field named "defaultCurrencyId " (a trailing space, copied from legacy XML); it loaded with no error. +// +// WHY THIS IS A WARNING AND NOT A LOAD ERROR. A whitespace name WORKS today on the core path +// (`meta migrate` quotes the column, the ObjectManager round-trips the key), so refusing it at load +// would break metadata that does what its author asked (docs/compatibility-policy.md). Nothing here +// reaches an exit code. +// +// REQUIREMENTS ARE NOT LINTED HERE: a requirement's name is its dotted address, and the requirement +// lint owns it. +// +// Mirrors the TS reference (server/typescript/packages/cli/src/lib/name-lint.ts). The codes, the +// message text and the fixtures are shared: fixtures/model-lint-conformance/. + +using MetaObjects.Meta; +using static MetaObjects.Shared.BaseTypes; +using static MetaObjects.Shared.Structural; + +namespace MetaObjects.Cli; + +/// The advisory node-name lint dotnet meta verify runs on every invocation. +public static class NameLint +{ + /// Leading or trailing whitespace — the strong finding. + public const string WARN_NAME_SURROUNDING_WHITESPACE = "WARN_NAME_SURROUNDING_WHITESPACE"; + /// Whitespace inside an otherwise trimmed name — the plain advisory. + public const string WARN_NAME_INTERNAL_WHITESPACE = "WARN_NAME_INTERNAL_WHITESPACE"; + + /// Opt-out environment variable, beside --no-name-lint (Node meta parity). + public const string EnvOptOut = "META_NO_NAME_LINT"; + + /// + /// What counts as whitespace: EXACTLY the ECMAScript \s class (the set + /// String.prototype.trim strips), so every port reports the same names. .NET's + /// char.IsWhiteSpace and regex \s differ from it (they include U+0085 and + /// U+001C–U+001F, and omit U+FEFF), so the class is spelled out. + /// + private static readonly char[] Whitespace = + [ + '\t', '\n', '\v', '\f', '\r', ' ', '\u00A0', '\u1680', + '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200A', + '\u2028', '\u2029', '\u202F', '\u205F', '\u3000', '\uFEFF', + ]; + + private static bool HasWhitespace(string name) => name.IndexOfAny(Whitespace) >= 0; + + /// One segment of a node's address, quoted when it has whitespace so the whitespace stays visible. + private static string Segment(string name) => HasWhitespace(name) ? LintText.Quote(name) : name; + + /// Lint the name of every named node in the loaded model, requirements excepted. + public static List Lint(MetaData root) + { + var findings = new List(); + Walk(root, "", findings); + return findings; + } + + private static void Walk(MetaData node, string prefix, List findings) + { + // OWN-ONLY (ADR-0039 sanctioned case): report each DECLARATION once, at the node that + // declares it. The resolving Children() would repeat an inherited field on every subtype. + foreach (var child in node.OwnChildren()) + { + if (child.Type == TYPE_REQUIREMENT) continue; // owned by the requirement lint — see the header + var path = prefix == "" ? TopLevelAddress(child) : $"{prefix}.{Segment(child.Name)}"; + Check(child, path, findings); + Walk(child, path, findings); + } + } + + /// A root-level node's address, package-qualified the way ResolutionKey() is. + private static string TopLevelAddress(MetaData node) + { + var pkg = node.Package ?? node.FileDefaultPackage; + return string.IsNullOrEmpty(pkg) ? Segment(node.Name) : $"{pkg}{PACKAGE_SEPARATOR}{Segment(node.Name)}"; + } + + private static void Check(MetaData node, string path, List findings) + { + var name = node.Name; + if (name == "" || !HasWhitespace(name)) return; + var kind = $"{node.Type}.{node.SubType}"; + var quoted = LintText.Quote(name); + // @column is a FIELD attribute: advising an object author to pin it would send them looking + // for a slot that does not exist on the node. + var pin = node.Type == TYPE_FIELD ? ", and pin @column if the physical column must keep its name" : ""; + var trimmed = name.Trim(Whitespace); + if (trimmed != name) + { + var inner = HasWhitespace(trimmed) ? " It also contains whitespace inside it." : ""; + var target = trimmed == "" ? "" : $" (to {LintText.Quote(trimmed)}, presumably)"; + findings.Add(new LintFinding( + WARN_NAME_SURROUNDING_WHITESPACE, path, + $"{kind} name {quoted} has leading or trailing whitespace, which is almost certainly unintended — " + + $"rename it{target}{pin}. The whitespace is carried into every identifier, column and wire key " + + $"derived from the name.{inner}")); + return; + } + findings.Add(new LintFinding( + WARN_NAME_INTERNAL_WHITESPACE, path, + $"{kind} name {quoted} contains whitespace. A name is an identifier: derived column names and wire " + + $"keys carry the space, and generated code cannot use it as one. Consider renaming it{pin}.")); + } +} diff --git a/server/csharp/MetaObjects.Cli/OverlayLint.cs b/server/csharp/MetaObjects.Cli/OverlayLint.cs new file mode 100644 index 0000000000..ed4e157b97 --- /dev/null +++ b/server/csharp/MetaObjects.Cli/OverlayLint.cs @@ -0,0 +1,132 @@ +// `dotnet meta verify` — the overlay AUTHORING lint. +// +// A root-level declaration redeclared in a second file merges into the first whether or not the +// second carries `overlay: true`. Leaving the flag off is what turns a renamed or removed target +// into a silent second object instead of a loud ERR_OVERLAY_NO_TARGET, so every unflagged +// redeclaration after the first is reported. Warnings only: nothing here reaches an exit code. +// +// It reads the RAW FILES, never the merged model: the merged tree has already lost which file +// contributed which declaration. +// +// Mirrors the TS reference (server/typescript/packages/cli/src/lib/overlay-lint.ts and +// `declaredTopLevelKeys` in the TS loader). The code, the message text and the fixtures are +// shared: fixtures/model-lint-conformance/. + +using MetaObjects.Loader; +using static MetaObjects.Shared.BaseTypes; +using static MetaObjects.Shared.Structural; + +namespace MetaObjects.Cli; + +/// The advisory overlay lint dotnet meta verify runs on every invocation. +public static class OverlayLint +{ + /// A root-level declaration redeclared in a second file without overlay: true. + public const string WARN_OVERLAY_IMPLICIT = "WARN_OVERLAY_IMPLICIT"; + + /// Opt-out environment variable, beside --no-overlay-lint (Node meta parity). + public const string EnvOptOut = "META_NO_OVERLAY_LINT"; + + private const string KeyName = "name"; + private const string KeyPackage = "package"; + private const string KeyChildren = "children"; + private const string KeyOverlay = "overlay"; + private const char TypeSubTypeSeparator = '.'; + + /// One root-level declaration as the raw document states it. + /// The wrapper key's TYPE segment (object for object.entity). + /// The resolution key the declaration would carry once parsed. + /// Whether the body carries overlay: true. + public sealed record DeclaredTopLevelKey(string Type, string Key, bool Overlay); + + /// + /// Structurally scan one document and report every declaration under metadata.root.children. + /// A declaration with no non-empty string name is skipped; a malformed root shape returns an + /// empty list; a syntax error throws, as the parser's would. + /// + public static List DeclaredTopLevelKeys(string content, MetaDataFormat format) + { + var declared = new List(); + var normalized = content.Length > 0 && content[0] == '\uFEFF' ? content[1..] : content; + var parsed = format == MetaDataFormat.Yaml ? RawDocument.ParseYaml(normalized) : RawDocument.ParseJson(normalized); + if (parsed is not List> document) return declared; + // JSON fuses the subtype onto the root key; sigil-free YAML may write the bare type. + var rootBody = RawDocument.Get(document, $"{TYPE_METADATA}{TypeSubTypeSeparator}{SUBTYPE_ROOT}") ?? RawDocument.Get(document, TYPE_METADATA); + if (rootBody is not List> root) return declared; + var rootPkg = RawDocument.Get(root, KeyPackage) as string ?? ""; + if (RawDocument.Get(root, KeyChildren) is not List children) return declared; + + foreach (var child in children) + { + if (child is not List> wrapper) continue; + foreach (var (wrapperKey, bodyValue) in wrapper) + { + if (bodyValue is not List> body) continue; + if (RawDocument.Get(body, KeyName) is not string { Length: > 0 } name) continue; + var pkg = RawDocument.ResolvePackage(rootPkg, RawDocument.Get(body, KeyPackage) as string); + var dot = wrapperKey.IndexOf(TypeSubTypeSeparator); + declared.Add(new DeclaredTopLevelKey( + dot < 0 ? wrapperKey : wrapperKey[..dot], + pkg != "" ? $"{pkg}{PACKAGE_SEPARATOR}{name}" : name, + RawDocument.IsTrue(RawDocument.Get(body, KeyOverlay)))); + } + } + return declared; + } + + /// + /// Report every unflagged cross-file redeclaration after the first. is + /// the whole collection in LOAD ORDER, dependency artifacts first (they are the bases a project's own + /// declarations amend), and each source's is the name a finding + /// prints. Declarations group by (type, resolution key), as the parser's merge lookup does. + /// Unreadable or unparsable sources are skipped: the loader reports those itself. + /// + public static List Lint(IEnumerable sources) + { + // Insertion-ordered, so findings come out in load order. + var groups = new List<(string Type, string Key, List<(string File, bool Overlay)> Declarations)>(); + var index = new Dictionary<(string, string), int>(); + foreach (var source in sources) + { + List declared; + try + { + declared = DeclaredTopLevelKeys(source.Read(), source.Format); + } + catch (Exception) + { + continue; // an advisory scan never breaks verify + } + foreach (var decl in declared) + { + if (!index.TryGetValue((decl.Type, decl.Key), out var i)) + { + index[(decl.Type, decl.Key)] = i = groups.Count; + groups.Add((decl.Type, decl.Key, [])); + } + groups[i].Declarations.Add((source.Id, decl.Overlay)); + } + } + + var findings = new List(); + foreach (var (_, fqn, declarations) in groups) + { + if (declarations.Count < 2) continue; + var baseSeen = false; + foreach (var (file, overlay) in declarations) + { + if (overlay) continue; + if (!baseSeen) + { + baseSeen = true; + continue; + } + findings.Add(new LintFinding( + WARN_OVERLAY_IMPLICIT, "", + $"{fqn} is redeclared in {file} without overlay: true — add the flag so a removed or renamed " + + "target fails loudly (ERR_OVERLAY_NO_TARGET) instead of silently becoming a new object")); + } + } + return findings; + } +} diff --git a/server/csharp/MetaObjects.Cli/Program.cs b/server/csharp/MetaObjects.Cli/Program.cs index 1a69176988..08d3db9902 100644 --- a/server/csharp/MetaObjects.Cli/Program.cs +++ b/server/csharp/MetaObjects.Cli/Program.cs @@ -388,7 +388,7 @@ static int RunVerify(string[] rest) string? entitiesCsv = null; string? templateRoot = null; string? columnNamingRaw = null; - bool templates = false, codegen = false, deps = false, db = false, lax = false, noFieldLint = false, requireImplementers = false, full = false; + bool templates = false, codegen = false, deps = false, db = false, lax = false, noFieldLint = false, noOverlayLint = false, noNameLint = false, noDeprecationLint = false, requireImplementers = false, full = false; for (int i = 0; i < rest.Length; i++) { @@ -421,6 +421,9 @@ static int RunVerify(string[] rest) // Mutes the advisory field AUTHORING lint (FieldLint) — never a gate, so this // changes what is printed and nothing else. META_NO_FIELD_LINT=1 does the same. else if (a == "--no-field-lint") noFieldLint = true; + else if (a == "--no-overlay-lint") noOverlayLint = true; + else if (a == "--no-name-lint") noNameLint = true; + else if (a == "--no-deprecation-lint") noDeprecationLint = true; // Raises WARN_REQUIREMENT_NOTHING_IMPLEMENTS to an error (ADR-0057) — for a project whose // ledger has caught up with its links. META_REQUIRE_IMPLEMENTERS=1 does the same. else if (a == "--require-implementers") requireImplementers = true; @@ -667,6 +670,16 @@ static int RunVerify(string[] rest) // line and no exit-code change. Its errors fold into the exit code like any other gate's. var rulesExit = VerifyCommand.RunRulesGate(opts, Console.Error); + // The model AUTHORING lints — an unflagged cross-file redeclaration, whitespace in a node name, + // a reference to a deprecated node. Printed before the field lint, in the Node `meta verify` + // order. A finding names a file relative to an explicit metadata directory, else the project root. + // Warnings ONLY, never the exit code. + ModelLints.RunAdvisory( + resolvedMeta, + metadataDir is not null ? Path.GetFullPath(metadataDir) : Directory.GetCurrentDirectory(), + ModelLints.Selection.From(noOverlayLint, noNameLint, noDeprecationLint), + Console.Error); + // The field AUTHORING lint — a reference identity over a field the object lacks, a // field name declared twice in one children list. Both load clean on every port. Runs // on every `verify`, whichever gates were selected; warnings ONLY, never the exit code. @@ -734,7 +747,7 @@ partial class Program static readonly string[] GenBoolFlags = ["--list", "--emit-abstract-shapes", "--strict", "--force"]; static readonly string[] VerifyValueFlags = ["--prompts", "--out", "--namespace", "--generators", "--template-root", "--column-naming", "--entities"]; - static readonly string[] VerifyBoolFlags = ["--templates", "--codegen", "--deps", "--db", "--lax", "--no-field-lint", "--require-implementers", "--full"]; + static readonly string[] VerifyBoolFlags = ["--templates", "--codegen", "--deps", "--db", "--lax", "--no-field-lint", "--no-overlay-lint", "--no-name-lint", "--no-deprecation-lint", "--require-implementers", "--full"]; /// Each command's usage, printed by dotnet meta <command> --help. static readonly Dictionary CommandUsage = new() @@ -754,7 +767,7 @@ partial class Program " column/table naming: \"naming\" in .metaobjects/config.json (ADR-0058), not a flag here", ["init"] = "usage: dotnet meta init [--root ] [--with-docs]\n" + " --with-docs lists the api-docs generator in codegen/Generators.cs (written to docs/csharp)", - ["verify"] = "usage: dotnet meta verify [--templates [--prompts ]] [--codegen --out [--namespace ] [--generators ] [--entities ] [--template-root ]] [--deps] [--db] [--lax] [--no-field-lint] [--require-implementers] [--full]\n" + + ["verify"] = "usage: dotnet meta verify [--templates [--prompts ]] [--codegen --out [--namespace ] [--generators ] [--entities ] [--template-root ]] [--deps] [--db] [--lax] [--no-field-lint] [--no-overlay-lint] [--no-name-lint] [--no-deprecation-lint] [--require-implementers] [--full]\n" + " --full: render and compare even when a local run could answer from the stored key (CI always renders)", ["fmt"] = "usage: dotnet meta fmt [] [--check]", ["eject"] = "usage: dotnet meta eject ... [--force] [--root ]\n" + diff --git a/server/csharp/MetaObjects.Cli/RawDocument.cs b/server/csharp/MetaObjects.Cli/RawDocument.cs new file mode 100644 index 0000000000..6bc7b28089 --- /dev/null +++ b/server/csharp/MetaObjects.Cli/RawDocument.cs @@ -0,0 +1,110 @@ +// The raw document model the authoring lints read: a metadata file as written, before the +// parser merges it. The field lint's duplicate half and the overlay lint both need it, because +// the merged model has already lost what they look for (a second declaration of a field, the file +// a declaration came from). +// +// A mapping is an ORDERED list of pairs, a sequence a List, a string scalar a string, +// and a boolean a RawBool, which keeps the text YAML wrote. Everything else reads as null. + +using System.Text.Json; +using YamlDotNet.Core; +using YamlDotNet.RepresentationModel; +using static MetaObjects.Shared.Structural; + +namespace MetaObjects.Cli; + +/// A boolean scalar, with the text it was written as (a YAML name may be a plain true). +internal sealed record RawBool(bool Value, string Text); + +internal static class RawDocument +{ + private const string KeyName = "name"; + private const char TypeSubTypeSeparator = '.'; + /// The YAML authoring sugar for isArray: true — a suffix on the wrapper key. + private const string ArraySuffix = "[]"; + + internal static object? Get(List> mapping, string key) + { + foreach (var (k, v) in mapping) + if (k == key) return v; + return null; + } + + /// The TYPE segment of a wrapper key: field.string[] and bare field are both field. + internal static string WrapperType(string key) + { + var dot = key.IndexOf(TypeSubTypeSeparator); + var head = dot < 0 ? key : key[..dot]; + return head.EndsWith(ArraySuffix, StringComparison.Ordinal) ? head[..^ArraySuffix.Length] : head; + } + + /// A node's declared name: the body's name, or the body itself when YAML wrote a scalar. + internal static string? DeclaredName(object? body) + { + var name = body is List> mapping ? Get(mapping, KeyName) : body; + return name switch + { + string s when s != "" => s, + RawBool b => b.Text, + _ => null, + }; + } + + /// Whether is the boolean true. + internal static bool IsTrue(object? value) => value is RawBool { Value: true }; + + /// + /// The package the parser gives a root-level node: its own package (a ::-prefixed one + /// is relative to the root's), else the root's. + /// + internal static string ResolvePackage(string rootPkg, string? ownPkg) => + string.IsNullOrEmpty(ownPkg) + ? rootPkg + : rootPkg.Trim() != "" && ownPkg.StartsWith(PACKAGE_SEPARATOR, StringComparison.Ordinal) + ? rootPkg + ownPkg + : ownPkg; + + internal static object? ParseJson(string text) + { + using var doc = JsonDocument.Parse(text); + return FromJson(doc.RootElement); + } + + private static object? FromJson(JsonElement element) => element.ValueKind switch + { + JsonValueKind.Object => element.EnumerateObject() + .Select(p => new KeyValuePair(p.Name, FromJson(p.Value))).ToList(), + JsonValueKind.Array => element.EnumerateArray().Select(FromJson).ToList(), + JsonValueKind.String => element.GetString(), + JsonValueKind.True => new RawBool(true, "true"), + JsonValueKind.False => new RawBool(false, "false"), + _ => null, + }; + + internal static object? ParseYaml(string text) + { + var stream = new YamlStream(); + stream.Load(new StringReader(text)); + return stream.Documents.Count == 0 ? null : FromYaml(stream.Documents[0].RootNode); + } + + private static object? FromYaml(YamlNode node) => node switch + { + YamlMappingNode mapping => mapping.Children + .Where(p => p.Key is YamlScalarNode) + .Select(p => new KeyValuePair(((YamlScalarNode)p.Key).Value ?? "", FromYaml(p.Value))).ToList(), + YamlSequenceNode sequence => sequence.Children.Select(FromYaml).ToList(), + YamlScalarNode scalar => Scalar(scalar), + _ => null, + }; + + // A PLAIN true/false is a YAML 1.2 boolean; a quoted one is the string, as the loader reads it. + private static object? Scalar(YamlScalarNode scalar) => scalar.Style == ScalarStyle.Plain + ? scalar.Value switch + { + "true" or "True" or "TRUE" => new RawBool(true, scalar.Value), + "false" or "False" or "FALSE" => new RawBool(false, scalar.Value), + _ => scalar.Value, + } + : scalar.Value; +} From 6ee8cd9188957e48321196b0fe5220fc71276ead Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 18:33:35 -0500 Subject: [PATCH 3/6] no-mistakes(review): Make TS deprecation lint pass model-lint corpus --- CHANGELOG.md | 2 + .../packages/cli/src/lib/deprecation-lint.ts | 3 +- .../packages/cli/src/lib/overlay-lint.ts | 2 +- .../cli/test/model-lint-conformance.test.ts | 52 +++++++++++++++++++ 4 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 server/typescript/packages/cli/test/model-lint-conformance.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a2ec1fe7d5..8b7948ad4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ here.** ## [Unreleased] +- **The deprecated-reference finding ends its sentence before naming the replacement.** It read `…Team: the league no longer tracks teams Replaced by acme::app::Club.`; it now reads `…tracks teams. Replaced by acme::app::Club.` A reason that already ends in `.`, `!` or `?` is left as written. + - **C#: `dotnet meta verify` runs the three model authoring lints.** The overlay lint (`WARN_OVERLAY_IMPLICIT`), the node-name lint (`WARN_NAME_SURROUNDING_WHITESPACE`, `WARN_NAME_INTERNAL_WHITESPACE`) and the deprecated-reference lint (`WARN_DEPRECATED_REFERENCE`) diff --git a/server/typescript/packages/cli/src/lib/deprecation-lint.ts b/server/typescript/packages/cli/src/lib/deprecation-lint.ts index 0547969446..115ee48222 100644 --- a/server/typescript/packages/cli/src/lib/deprecation-lint.ts +++ b/server/typescript/packages/cli/src/lib/deprecation-lint.ts @@ -133,10 +133,11 @@ function considerTarget(referrer: MetaData, referrerPath: string, verb: string, const replacedBy = typeof replacedByRaw === "string" && replacedByRaw !== "" ? replacedByRaw : undefined; const targetKind = `${target.type}.${target.subType}`; const reasonClause = reason !== "" ? `: ${reason}` : ""; + const sentenceEnd = replacedBy !== undefined && !/[.!?]$/.test(reason) ? "." : ""; out.push( warn( referrerPath, - `${verb} deprecated ${targetKind} ${addressOf(target)}${reasonClause}` + + `${verb} deprecated ${targetKind} ${addressOf(target)}${reasonClause}${sentenceEnd}` + (replacedBy !== undefined ? ` Replaced by ${replacedBy}.` : ""), ), ); diff --git a/server/typescript/packages/cli/src/lib/overlay-lint.ts b/server/typescript/packages/cli/src/lib/overlay-lint.ts index 42221b0045..15f902d66b 100644 --- a/server/typescript/packages/cli/src/lib/overlay-lint.ts +++ b/server/typescript/packages/cli/src/lib/overlay-lint.ts @@ -74,7 +74,7 @@ interface Declaration { * same message. */ export async function lintOverlays( - collection: Collection, + collection: Pick, readSource: ReadSource, ): Promise { // type -> resolutionKey -> every declaration seen for it, in file order. diff --git a/server/typescript/packages/cli/test/model-lint-conformance.test.ts b/server/typescript/packages/cli/test/model-lint-conformance.test.ts new file mode 100644 index 0000000000..37c9dd72db --- /dev/null +++ b/server/typescript/packages/cli/test/model-lint-conformance.test.ts @@ -0,0 +1,52 @@ +// Cross-port model-lint conformance corpus — fixtures/model-lint-conformance/. +// +// Every case is LOADED strict first, so "this loads with no error today" is proven by +// the fixture rather than asserted in prose, and only then linted. The other ports' +// runners assert the same `expected.json`, so the codes, addresses and message text +// cannot drift between the ports. +import { describe, test, expect } from "bun:test"; +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { MetaDataLoader } from "@metaobjectsdev/metadata"; +import { FileSource } from "@metaobjectsdev/metadata/core"; +import { lintOverlays } from "../src/lib/overlay-lint.js"; +import { lintNodeNames } from "../src/lib/name-lint.js"; +import { lintDeprecatedReferences } from "../src/lib/deprecation-lint.js"; + +const CORPUS_DIR = join(import.meta.dir, "../../../../../fixtures/model-lint-conformance"); + +interface Finding { code: string; path: string; message: string } + +const order = (a: Finding, b: Finding): number => + a.code.localeCompare(b.code) || a.path.localeCompare(b.path) || a.message.localeCompare(b.message); + +const cases = readdirSync(CORPUS_DIR).filter((n) => statSync(join(CORPUS_DIR, n)).isDirectory()).sort(); + +describe("model-lint conformance corpus", () => { + test("discovers the corpus", () => { + expect(cases.length).toBeGreaterThan(0); + }); + + for (const name of cases) { + test(name, async () => { + const input = join(CORPUS_DIR, name, "input"); + const expected = JSON.parse(readFileSync(join(CORPUS_DIR, name, "expected.json"), "utf8")) as { findings: Finding[] }; + + const result = await MetaDataLoader.fromDirectory(input, { strict: true }); + expect(result.errors.map(String)).toEqual([]); + + const files = readdirSync(input).sort().map((f) => join(input, f)); + const overlay = await lintOverlays( + { files, fileIds: new Map(), configDir: input }, + (path) => new FileSource(path), + ); + const actual = [ + ...overlay, + ...lintNodeNames(result.root), + ...lintDeprecatedReferences(result.root), + ].map(({ code, path, message }) => ({ code, path: path ?? "", message })); + + expect(actual.sort(order)).toEqual([...expected.findings].sort(order)); + }); + } +}); From ed1e6036ac80d89e711e36f0148989cf46d42153 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 18:50:10 -0500 Subject: [PATCH 4/6] no-mistakes(test): Load model lints with verify's strictness --- .../VerifyModelLintTests.cs | 22 +++++++++++++++++++ server/csharp/MetaObjects.Cli/ModelLints.cs | 4 ++-- server/csharp/MetaObjects.Cli/Program.cs | 3 ++- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/server/csharp/MetaObjects.Cli.Tests/VerifyModelLintTests.cs b/server/csharp/MetaObjects.Cli.Tests/VerifyModelLintTests.cs index b623fcd9b6..3646bc66f9 100644 --- a/server/csharp/MetaObjects.Cli.Tests/VerifyModelLintTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/VerifyModelLintTests.cs @@ -92,6 +92,28 @@ public void Clean_metadata_prints_no_section() Assert.DoesNotContain("deprecations:", stderr); } + [Fact] + public void Name_and_deprecation_lints_read_the_same_load_the_gate_reports() + { + var (model, templates) = Project(); + var file = Path.Combine(model, "meta.app.json"); + File.WriteAllText(file, File.ReadAllText(file).Replace("\"name\": \"Item\",", "\"name\": \"Item\", \"@bogusAttr\": \"x\",")); + + // Strict (default): the model does not load, so the load-reading lints stay silent; the + // overlay lint reads raw files and still reports. + var (strictExit, _, strict) = CliProcess.Run(_tmp, "verify", model, "--templates", "--prompts", templates); + Assert.NotEqual(0, strictExit); + Assert.DoesNotContain("names:", strict); + Assert.DoesNotContain("deprecations:", strict); + Assert.Contains("WARN_OVERLAY_IMPLICIT", strict); + + // --lax: the same model loads, so both sections print. + var (laxExit, laxOut, lax) = CliProcess.Run(_tmp, "verify", model, "--templates", "--prompts", templates, "--lax"); + Assert.True(laxExit == 0, $"stdout={laxOut}\nstderr={lax}"); + Assert.Contains(NamesHeader, lax); + Assert.Contains(DeprecationsHeader, lax); + } + public static TheoryData OptOuts() => new() { { "--no-overlay-lint", OverlayLint.EnvOptOut, "WARN_OVERLAY_IMPLICIT" }, diff --git a/server/csharp/MetaObjects.Cli/ModelLints.cs b/server/csharp/MetaObjects.Cli/ModelLints.cs index ac7657f246..2093a0ea90 100644 --- a/server/csharp/MetaObjects.Cli/ModelLints.cs +++ b/server/csharp/MetaObjects.Cli/ModelLints.cs @@ -40,7 +40,7 @@ public static List Sources(ResolvedMetadata meta, string baseDi /// reads the raw files, so it runs even when the model does not load; the other two read the loaded /// model and stay silent when it does not (the load failure is reported by the gates). /// - public static void RunAdvisory(ResolvedMetadata meta, string baseDir, Selection selection, TextWriter stderr) + public static void RunAdvisory(ResolvedMetadata meta, string baseDir, Selection selection, TextWriter stderr, bool strict = true) { if (!selection.Overlays && !selection.Names && !selection.Deprecations) return; List overlays = [], names = [], deprecations = []; @@ -49,7 +49,7 @@ public static void RunAdvisory(ResolvedMetadata meta, string baseDir, Selection if (selection.Overlays) overlays = OverlayLint.Lint(Sources(meta, baseDir)); if (selection.Names || selection.Deprecations) { - var load = meta.Load(); + var load = meta.Load(strict); if (load.Errors.Count == 0) { if (selection.Names) names = NameLint.Lint(load.Root); diff --git a/server/csharp/MetaObjects.Cli/Program.cs b/server/csharp/MetaObjects.Cli/Program.cs index 08d3db9902..4a5fab3b53 100644 --- a/server/csharp/MetaObjects.Cli/Program.cs +++ b/server/csharp/MetaObjects.Cli/Program.cs @@ -678,7 +678,8 @@ static int RunVerify(string[] rest) resolvedMeta, metadataDir is not null ? Path.GetFullPath(metadataDir) : Directory.GetCurrentDirectory(), ModelLints.Selection.From(noOverlayLint, noNameLint, noDeprecationLint), - Console.Error); + Console.Error, + strict: !lax); // The field AUTHORING lint — a reference identity over a field the object lacks, a // field name declared twice in one children list. Both load clean on every port. Runs From e5c2aada7c586927e0fbb9752d1be4d3d80c2b70 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 20:16:19 -0500 Subject: [PATCH 5/6] no-mistakes(document): Correct model-lint row and corpus count --- docs/CONFORMANCE.md | 2 +- examples/showcase/site-payload.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 19170673a8..a9366a83c0 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -55,7 +55,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) | 1 | ✓ (docs emit is TS-owned) | — | — | — | — | | [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/model-lint-conformance/`](../fixtures/model-lint-conformance/) (the `verify` overlay, node-name and deprecated-reference authoring lints) | 18 | ✓ (reference) | ✓ | — (1.3.0 build, D8) | — (1.3.0 build, D8) | — (1.3.0 build, D8) | +| [`fixtures/model-lint-conformance/`](../fixtures/model-lint-conformance/) (the `verify` overlay, node-name and deprecated-reference authoring lints) | 17 | ✓ (reference) | — (1.3.0 build, D8) | — (1.3.0 build, D8) | ✓ | — (1.3.0 build, D8) | | [`fixtures/requirement-check-conformance/`](../fixtures/requirement-check-conformance/) (the `verify` requirement gate, ADR-0057) | 49 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | | [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 27 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | | [`fixtures/rules-check-conformance/`](../fixtures/rules-check-conformance/) (the `verify` business-rules gate, ADR-0066) | 16 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 1ba85b43c7..bbe3a216b2 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -8,7 +8,7 @@ }, "counts": { "fixtures": 578, - "corpora": 43, + "corpora": 44, "baseTypes": 21 }, "snippets": { From 2735f4154df4ae5c85dfddd422222abc6648ffb9 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 15:21:42 -0500 Subject: [PATCH 6/6] no-mistakes(document): correct model-lint docs and stale corpus counts --- README.md | 4 ++-- docs/CONFORMANCE.md | 2 +- docs/ports/csharp.md | 3 +++ fixtures/model-lint-conformance/README.md | 4 ++-- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 73c784fced..e68c94f233 100644 --- a/README.md +++ b/README.md @@ -299,8 +299,8 @@ metaobjects/ ├── README.md # you are here ├── CLAUDE.md # project instructions for Claude ├── spec/ # canonical metamodel docs, ADRs, roadmap -├── fixtures/ # 25 cross-language conformance corpora — the oracle -│ ├── conformance/ # metamodel (loader + serializer + navigation), 410 fixtures +├── fixtures/ # cross-language conformance corpora — the oracle (counted in docs/CONFORMANCE.md) +│ ├── conformance/ # metamodel (loader + serializer + navigation) │ ├── yaml-conformance/ # YAML authoring desugar │ ├── render-conformance/ # FR-004 byte-identical render oracle │ ├── verify-conformance/ # FR-004 template-drift gate diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 37a81e7245..457065f410 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -57,7 +57,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) | 1 | ✓ (docs emit is TS-owned) | — | — | — | — | | [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/model-lint-conformance/`](../fixtures/model-lint-conformance/) (the `verify` overlay, node-name and deprecated-reference authoring lints) | 17 | ✓ (reference) | — (1.3.0 build, D8) | — (1.3.0 build, D8) | ✓ | — (1.3.0 build, D8) | +| [`fixtures/model-lint-conformance/`](../fixtures/model-lint-conformance/) (the `verify` overlay, node-name and deprecated-reference authoring lints) | 17 | ✓ (reference) | planned | planned (through Java) | ✓ | planned | | [`fixtures/requirement-check-conformance/`](../fixtures/requirement-check-conformance/) (the `verify` requirement gate, ADR-0057) | 49 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | | [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 27 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | | [`fixtures/rules-check-conformance/`](../fixtures/rules-check-conformance/) (the `verify` business-rules gate, ADR-0066) | 16 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 59c9dbc4d4..923d5dcec1 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -247,6 +247,9 @@ Every `dotnet meta verify` also prints the advisory authoring lints on stderr, w run: unflagged cross-file redeclarations (`WARN_OVERLAY_IMPLICIT`), whitespace in a node name (`WARN_NAME_SURROUNDING_WHITESPACE`, `WARN_NAME_INTERNAL_WHITESPACE`), references to a `deprecated` node (`WARN_DEPRECATED_REFERENCE`), then the field lint. None changes the exit code. +The overlay lint reads the raw files, so it runs even when the model does not load; the name and +deprecation lints read the loaded model and print nothing when it does not load (the load error +is the gate's report). Mute each with `--no-overlay-lint`, `--no-name-lint`, `--no-deprecation-lint` or `--no-field-lint`, or the matching `META_NO_*_LINT=1`. The codes and message text match Node `meta verify`, gated by `fixtures/model-lint-conformance/` and `fixtures/field-lint-conformance/`. diff --git a/fixtures/model-lint-conformance/README.md b/fixtures/model-lint-conformance/README.md index 995f169799..4d2913386e 100644 --- a/fixtures/model-lint-conformance/README.md +++ b/fixtures/model-lint-conformance/README.md @@ -14,8 +14,8 @@ All are warnings and never a load error, and none reaches an exit code. The rule applies are in [`docs/features/cli.md`](../../docs/features/cli.md). This corpus is the shared source of truth for the codes, the addresses and the message text. -Runners today: TypeScript (the reference, `packages/cli/test/model-lint-conformance.test.ts`) -and Python (`tests/conformance/test_model_lint_conformance.py`). +Runners today: TypeScript (the reference, `server/typescript/packages/cli/test/model-lint-conformance.test.ts`) +and C# (`server/csharp/MetaObjects.Cli.Tests/ModelLintConformanceTests.cs`). ## Fixture format