diff --git a/AGENTS.md b/AGENTS.md index bc1185979e..8e533a22a7 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/` (584 fixtures; 46 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (584 fixtures; 48 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python byte-identical; C# and Rust each carry a `KnownDrift` render ledger, recorded in `docs/CONFORMANCE.md`. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/changelog.d/metadata-reference-sources.md b/changelog.d/metadata-reference-sources.md new file mode 100644 index 0000000000..17be64ca5f --- /dev/null +++ b/changelog.d/metadata-reference-sources.md @@ -0,0 +1,9 @@ +- **Reference sources: name a prompt's reply type that another run generates.** A `sources` + entry may carry `"reference": true` (Maven: ``). Its files load into + the same tree, so a prompt's `@responseRef` (and any other reference) resolves against them, + and no generator emits a type for a node declared only there. The prompt keeps its parser, + output-format fragment and extractor, naming the reply type the other run generates. Before + this, a reply type owned by another generator run could not be named at all (the load + refused the unresolved `@responseRef`), and merging its files into the prompt's tree generated + every reply type a second time. A `template.*` declared only in a reference source is refused + (`ERR_REFERENCE_SOURCE_TEMPLATE`). Every port, pinned by `fixtures/reference-source-conformance/`. diff --git a/changelog.d/rust-verify-templates.md b/changelog.d/rust-verify-templates.md new file mode 100644 index 0000000000..43907816bb --- /dev/null +++ b/changelog.d/rust-verify-templates.md @@ -0,0 +1,10 @@ +- **Rust: `cargo meta verify --templates`, the template drift gate.** It checks every `template.*` + body (and its partials) against the payload value object it renders over + (`ERR_VAR_NOT_ON_PAYLOAD`, `ERR_PARTIAL_UNRESOLVED`, `ERR_OUTPUT_TAG_MISSING`, + `ERR_REQUIRED_SLOT_UNUSED`, `ERR_TEMPLATE_SYNTAX`) and each prompt's reply, reading + `@payloadRef`, `@textRef`, `@requiredTags` and `@responseRef` through `extends`. Bodies live + under `prompts/` (`--prompts ` to move it), and a bare `verify` runs the gate beside the + codegen and rules gates. The `metaobjects-render` crate gains `verify`, held to + `fixtures/verify-conformance/` (all 45 cases). A Jinja body is refused + (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`): the Rust renderer runs Mustache only. The old refusal + of `--templates` is gone. diff --git a/changelog.d/verify-templates-reads-response-ref.md b/changelog.d/verify-templates-reads-response-ref.md new file mode 100644 index 0000000000..4aee32092f --- /dev/null +++ b/changelog.d/verify-templates-reads-response-ref.md @@ -0,0 +1,5 @@ +- **The template check reads `@responseRef`.** `verify`'s template gate now reports + `ERR_RESPONSE_UNRESOLVED` (error) for a reply type with no readable field, and + `ERR_RESPONSE_TAG_UNDECLARED` (warning) for an xml prompt's `@requiredTags` tag that names + neither the reply type nor a field in it. TypeScript, Java (and so Kotlin), C#, Python and + Rust, pinned by `fixtures/response-verify-conformance/`. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index fb243195dc..204964eff6 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -1,6 +1,6 @@ # Conformance coverage -The MetaObjects standard ships **46 shared conformance corpora** under +The MetaObjects standard ships **48 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 @@ -47,7 +47,9 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/template-output-render-conformance/`](../fixtures/template-output-render-conformance/) | 5 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/generator-registry-conformance/`](../fixtures/generator-registry-conformance/) | 1 canonical manifest | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/provider-composition-conformance/`](../fixtures/provider-composition-conformance/) | 18 (11 error-shape + 4 compose-load + 3 attr-ownership) | ✓ | ✓ | — (JVM registry via Java) | ✓ | ✓ | -| [`fixtures/source-resolution-conformance/`](../fixtures/source-resolution-conformance/) | 28 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | +| [`fixtures/source-resolution-conformance/`](../fixtures/source-resolution-conformance/) | 30 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | +| [`fixtures/reference-source-conformance/`](../fixtures/reference-source-conformance/) | 6 cases | ✓ (reference implementation) | ✓ | inherits via Java (plus its own codegen exclusion test) | ✓ | ✓ | +| [`fixtures/response-verify-conformance/`](../fixtures/response-verify-conformance/) | 7 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/scope-conformance/`](../fixtures/scope-conformance/) | 10 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | | [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (all 15; `test_shared_model_conformance.py`) | @@ -80,13 +82,15 @@ green, with every validation pass the TypeScript loader runs, in the same order, `rules-check-conformance` (all 16 cases, the `verify` business-rules gate); `yaml-conformance`, 18 of 19 (the one on `yaml-conformance-expected-failures.json`, `yaml-ref-root-escape`, waits for the ADR-0059 root-level `::` reference rules, which are -reference resolution, not a validation pass); `source-resolution-conformance` (all 28 -cases); `naming-conformance` (all of it); `codegen-skip-conformance` (ADR-0064), on both its +reference resolution, not a validation pass); `source-resolution-conformance` (all 30 +cases); `reference-source-conformance` (all 6 cases); `naming-conformance` (all of it); `codegen-skip-conformance` (ADR-0064), on both its `gen` and its `verify` columns, for every case the port can meet (the three it cannot, two about templates and one about the three-way merge, are named with their reason in its runner); `validation-conformance`, every case, through the generated `validate()`; `decimal-wire` and `duration-wire`, every vector, against the code the generated support -crate carries; `render-conformance`, every case but the three ledgered below (`mustache-ng` has its own name lookup, data model and truthiness), `extract-conformance`, all 58 +crate carries; `render-conformance`, every case but the three ledgered below (`mustache-ng` has its own name lookup, data model and truthiness), `verify-conformance`, all 45 +cases, and `response-verify-conformance`, all 7 (the template gate, `verify --templates`), +`extract-conformance`, all 58 cases, and `output-prompt-conformance`, all 17 in all three styles with the round trip, in the `metaobjects-render` crate; the `core` cases of `writer-conformance` (ADR-0063); and `generator-registry-conformance`, with the eject contract's census, completeness and depth @@ -426,7 +430,7 @@ Per-port runners + commands: | Kotlin | `cd server/java && mvn -pl codegen-kotlin test` (snapshot suite) | `mvn -f server/java/integration-tests-kotlin/pom.xml test` (needs Docker) | `mvn -f server/java/integration-tests-kotlin/pom.xml test -Dtest=ApiContractConformanceTest` (needs Docker) | | C# | `dotnet test` (per project) | `scripts/integration-test.sh csharp` (needs Docker) | `dotnet test server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj --filter "FullyQualifiedName~ApiContractConformanceTest"` (needs Docker) | | Python | `pytest` (per package) | `scripts/integration-test.sh python` (needs Docker) | `cd server/python && uv run --extra integration pytest tests/integration/test_api_contract.py` (needs Docker) | -| Rust | `cd server/rust && cargo test` (registry, metamodel, YAML, source-resolution, naming, skip, validation, wire-vector, writer, generator-registry, render, extract and output-prompt corpora; the codegen-compile and scale gates, which run `cargo check` on generated crates and drive the generated client over HTTP against a local stub) | — | — | +| Rust | `cd server/rust && cargo test` (registry, metamodel, YAML, source-resolution, reference-source, naming, skip, validation, wire-vector, writer, generator-registry, render, verify, response-verify, extract and output-prompt corpora, and the `verify --templates` CLI test; the codegen-compile and scale gates, which run `cargo check` on generated crates and drive the generated client over HTTP against a local stub) | — | — | The `persistence-conformance` corpus is intentionally **on-demand** — none of the unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. @@ -510,9 +514,9 @@ The verify corpus reuses `verify-conformance/`'s `payload.json` field-tree shape `ERR_TEMPLATE_SYNTAX` finding's path is the parser's own message, so runners compare it as empty. -### `fixtures/verify-conformance/` (37) +### `fixtures/verify-conformance/` (45) -All 37 fixtures → [features/migrations-and-drift.md](features/migrations-and-drift.md) +All 45 fixtures → [features/migrations-and-drift.md](features/migrations-and-drift.md) (template drift section — `Renderer.verify`). A node of a fixture's `payload.json` field tree may carry `"isArray": true`; with `fields` it is a list of objects, without it a list of scalars. The six `verify-positional-accessor-*` cases pin where `-last` is available. @@ -578,9 +582,9 @@ that reads real views, so it runs full stack on Postgres, SQLite and MySQL port, and on D1's local runtime in TypeScript. The `decimal/` sub-corpus does the same over decimal columns. -### `fixtures/source-resolution-conformance/` (28 cases) +### `fixtures/source-resolution-conformance/` (30 cases) -All 28 cases → [features/metadata-sources.md](features/metadata-sources.md) (how a +All 30 cases → [features/metadata-sources.md](features/metadata-sources.md) (how a declared `sources` set resolves to a file list). Companion to `scope-conformance/` below — `sources` decides which files are read, `scope` filters what is emitted from them. The corpus is file-shaped: one committed @@ -603,6 +607,28 @@ the same Maven plugin as Java): `server/python/tests/conformance/test_source_resolution_conformance.py`, and `server/java/metadata/src/test/java/com/metaobjects/config/SourceResolutionConformanceTest.java`. +### `fixtures/reference-source-conformance/` (6 cases) + +All 6 cases → [features/metadata-sources.md](features/metadata-sources.md#reference-sources--loaded-to-resolve-against-never-generated). +A `sources` entry with `"reference": true` loads its files into the same tree, so a +prompt's `@responseRef` resolves against them, and its nodes are excluded from every +generator. The corpus pins the reference-node SET (every declaring file a reference file; +an ordinary declaration or an ordinary spec reaching the same file wins) and the refusal of +a reference-only template (`ERR_REFERENCE_SOURCE_TEMPLATE`). Runners: +`server/typescript/packages/sdk/test/reference-source-conformance.test.ts`, C# +`ReferenceSourceConformanceTests`, Java `ReferenceSourceConformanceTest` (Kotlin through the +same loader), Python `test_reference_source_conformance.py` and Rust +`metaobjects/tests/reference_source_conformance.rs`. That codegen emits no type for a +reference node while a local prompt's parser still emits is proven by a per-port codegen test +(TypeScript, C#, Java, Kotlin and Python; Rust, which emits no prompt code, proves the exclusion alone). + +### `fixtures/response-verify-conformance/` (7 cases) + +All 7 cases → [features/templates-and-payloads.md](features/templates-and-payloads.md#drift-detection-verify). +What the template gate reports about a prompt's reply: `ERR_RESPONSE_UNRESOLVED` and, for an +xml prompt, `ERR_RESPONSE_TAG_UNDECLARED`. Run by TypeScript, C#, Java (Kotlin through the +same Maven goal), Python and Rust (`server/rust/metaobjects-cli/tests/response_verify_conformance.rs`). + ### `fixtures/scope-conformance/` (10 cases) All 10 cases → [features/metadata-sources.md](features/metadata-sources.md) (the @@ -882,7 +908,7 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) The fixtures in the nine corpora mapped above (metamodel 584 + yaml 19 + verify 45 -+ render 26 + persistence 68 + api-contract 179 + source-resolution 28 + scope 10 + ++ render 26 + persistence 68 + api-contract 179 + source-resolution 30 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the `cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining corpora in the totals table gate tooling contracts (registry manifests, provider diff --git a/docs/features/cli.md b/docs/features/cli.md index da109ea53b..32a64b34f8 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -43,7 +43,7 @@ command surface splits in two: | Java/Kotlin scaffold | Maven plugin | `mvn metaobjects:init` | writes the port-neutral `.metaobjects/config.json` and an empty `metaobjects/meta.app.json`, each only when missing; it never edits `pom.xml` and wires no generator. Details and the `-Dmeta.init.withDocs=true` opt-in: [docs/ports/java.md](../ports/java.md) | | Java/Kotlin verify | Maven plugin | `mvn metaobjects:verify -Dmeta.verify.mode=codegen\|templates\|deps` (`metaobjects:verify`) | parameter-driven ADR-0021 D2 modes (one goal covers BOTH Java + Kotlin): unset (default — `codegen` and `templates`; the template gate is skipped with a note when `templateRoot` is unset) / `codegen` (regen + fail on drift vs committed output, generator-neutral) / `templates` (`{{field}}`↔payload drift via the render `Verify` engine) / `deps` (opt-in dependency drift, the `path` transport only). `db` rejected ("schema verify is the migrate engine, ADR-0015") | | Python codegen | console-script | `metaobjects gen` / `verify --codegen` / `verify --templates` | `[project.scripts] metaobjects` — **not** `meta` (that's the Node schema CLI); ships the ADR-0021 D2 subverbs (`--db` rejected, exit 2). **The generator list is `metaobjects.config.yaml`** (ADR-0034 Amendment 9, [below](#declarative-config-metaobjectsconfigyaml--python-codegen)): `gen` and `verify --codegen` run each target's `generators` (and its `templateSpec`, the declarative Mustache template-codegen surface shared with C#) into its `outDir`, and with no config they exit 2 and write nothing. `--generators` only narrows the list to declared entries. `metaobjects docs` was removed in 1.1.0: it prints the line that points at [the migration section](migrations/docs-are-generators.md#python) and exits 2 | -| Rust codegen (ADR-0065) | `cargo-meta` (`metaobjects-cli`, unpublished; installed from a checkout) | `cargo meta init` / `gen` / `verify --codegen` / `eject` | A Cargo subcommand, invoked `cargo meta` so it never shadows the Node `meta`. Three generators ship, each writing one crate per metadata package: `entity`, `client` and `commands` (the last Rust-only by decision, ADR-0065 Amendment 1). `gen` skips a run whose key matches (ADR-0064), writes only changed bytes, removes a generated file nothing emits any more, and refuses to overwrite or delete a hand-edited generated file (exit 1). `verify` ships the ADR-0021 D2 subverbs it can: a bare `verify` is `--codegen`, which renders in memory and exits 1 on drift (`--full`, or a set `CI`, never answers from the stored key); `--db`, `--templates` and `--deps` are rejected, exit 2. **The generator list is the shipped three until the project owns one**: `cargo meta eject ` writes a `codegen/` crate (`Cargo.toml`, `main.rs`, `generators/.rs`), and `gen` / `verify` then build and run that crate; `--generators` only narrows the list. No `fmt`, no template generator and no `migrate`. `cargo meta --help` lists the options; [the Rust port page](../ports/rust.md) has the detail | +| Rust codegen (ADR-0065) | `cargo-meta` (`metaobjects-cli`, unpublished; installed from a checkout) | `cargo meta init` / `gen` / `verify --codegen` / `verify --templates` / `eject` | A Cargo subcommand, invoked `cargo meta` so it never shadows the Node `meta`. Three generators ship, each writing one crate per metadata package: `entity`, `client` and `commands` (the last Rust-only by decision, ADR-0065 Amendment 1). `gen` skips a run whose key matches (ADR-0064), writes only changed bytes, removes a generated file nothing emits any more, and refuses to overwrite or delete a hand-edited generated file (exit 1). `verify` ships the ADR-0021 D2 subverbs it can: a bare `verify` runs the gates (`--codegen`, which renders in memory and exits 1 on drift, `--templates` and the rules gate) (`--full`, or a set `CI`, never answers from the stored key); `--templates` is the template drift gate (`template.*` bodies under `prompts/`, or `--prompts `, against their payload value objects, plus each prompt's reply), and a bare `verify` runs it too; `--db` and `--deps` are rejected, exit 2. **The generator list is the shipped three until the project owns one**: `cargo meta eject ` writes a `codegen/` crate (`Cargo.toml`, `main.rs`, `generators/.rs`), and `gen` / `verify` then build and run that crate; `--generators` only narrows the list. No `fmt`, no template generator and no `migrate`. `cargo meta --help` lists the options; [the Rust port page](../ports/rust.md) has the detail | ## `verify` is one verb with explicit subverbs (ADR-0021 D2) @@ -178,7 +178,7 @@ Rules of the contract: It is not a subverb and nothing mutes it. A model with no operation and no transition gets no line. A model with one gets a summary line, and an error-severity finding exits non-zero. The codes, settings and the checks are in [business-rules.md](business-rules.md#what-verify-reports). - Rust's bare `cargo meta verify` runs it too, beside the codegen drift gate; `verify --codegen` runs the drift gate alone. + Rust's bare `cargo meta verify` runs it too, beside the codegen drift and template gates; `verify --codegen` or `verify --templates` runs that gate alone. ### The prompt directory: `--prompts` everywhere (F101) @@ -245,7 +245,13 @@ field tree via the render `Verify` engine, resolving refs through a filesystem p at `-Dmeta.verify.templateRoot`), and `-Dmeta.verify.mode=deps` (opt-in, never in the unset default set: the dependency drift check of `verify --deps`, resolving `path` dependencies only; see the Java port page). The one goal covers BOTH Java (`codegen-spring`) and Kotlin (`codegen-kotlin`) since they share it. `mode=db` is **cleanly rejected** ("schema verify is the migrate engine, ADR-0015"); an unknown mode fails listing the valid ones. (Schema `--db` remains -Node-only by the ADR-0015 design — see below.) +Node-only by the ADR-0015 design — see below.) The **Rust `cargo meta`** port runs the codegen +and template gates: bare `cargo meta verify` renders the generated crates in memory and diffs +them (a local run may answer from the stored skip key; `--full`, or a set `CI`, always renders), +checks every `template.*` body under `prompts/` (or `--prompts `) against its payload value +object plus each prompt's `@responseRef` reply, and runs the business-rules gate; `--codegen` and +`--templates` run one gate alone, and the port has no requirement gate ([the Rust port +page](../ports/rust.md)). ## Owned generators: the unchanged-copy notice, `eject --undo`, and `gen --strict` diff --git a/docs/features/metadata-sources.md b/docs/features/metadata-sources.md index 32ef81e8b5..a53bf9e372 100644 --- a/docs/features/metadata-sources.md +++ b/docs/features/metadata-sources.md @@ -188,6 +188,42 @@ Consequences worth knowing: records). - Symlinked subdirectories are followed, matching the loader's own directory walk. +### Reference sources — loaded to resolve against, never generated + +```jsonc +"sources": [ + { "path": "metaobjects" }, + { "path": "replies", "reference": true } // types another generator run owns +] +``` + +A `path` source may carry `"reference": true`. Its files load into the same tree as every +other source, so `@responseRef`, `@objectRef`, `extends` and every other reference resolve +against them, and they validate like any other file. What changes is codegen: **no generator +emits code for a reference object**, because another run already generates those types. + +- A top-level node is a *reference node* when **every** file that declares it, overlays + included, is a reference source. One declaration in an ordinary source makes it the + project's own, and a file an ordinary source also reaches is ordinary. +- A prompt in an ordinary source whose `@responseRef` names a reference node keeps its + parser, output-format fragment and extractor; they name the reply type exactly as they + would if it were generated here, which is the type the owning run generates. +- A `template.*` declared only in reference sources is refused + (`ERR_REFERENCE_SOURCE_TEMPLATE`): its parser and payload would be generated by nobody. +- It is a **codegen** setting and nothing else. A reference object stays in the expected + schema (`meta migrate`, `verify --db`) and in the requirement ledger's coverage, because the + schema and the ledger describe the whole model, not one generator run. Put a table another + project owns behind a metadata dependency instead. +- The exclusion is per object (`object.*`). A reference source is for shapes; declare an + `api.*` there and the generators that read the whole model still see it. +- `reference` must be a boolean. Maven projects set the same thing with + `…`. + +The typical use: a project already generates a prompt's reply types in one run (POJOs, say) +and generates the prompt in another. Naming the first run's files as a reference source lets +the prompt's `@responseRef` resolve without generating those types a second time. Pinned +cross-port by `fixtures/reference-source-conformance/`. + ### `resource` and `package` are declared but not resolved ```jsonc @@ -568,6 +604,7 @@ the per-level walk order layer 1 preserves is pinned by | `ERR_SOURCE_KIND_UNSUPPORTED` | A `resource` or `package` source was declared; this toolchain resolves `path` only | | `ERR_SCOPE_PATTERN_INVALID` | A scope pattern is empty, has an empty segment, or has a malformed `::` separator | | `ERR_COLLECTION_NOT_FOUND` | No `sources` were declared **and** no default `metaobjects/` directory exists | +| `ERR_REFERENCE_SOURCE_TEMPLATE` | A `template.*` is declared only in reference sources | A schema violation in `.metaobjects/config.json` itself (an unknown key, a wrong type) surfaces as the TypeScript config load error and stops the command. The C# port diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 4f2a002ab9..1c461a627a 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -769,7 +769,9 @@ Postgres's text. If the metadata does not load, the baseline is written as befor ## Drift verify commands per port A bare `verify` runs the same default gate set in every port: **codegen drift**, -**prompt-template drift**, the **requirement ledger** and the **business-rules gate**. What a check does when the run has +**prompt-template drift**, the **requirement ledger** and the **business-rules gate** — one +exception: Rust has no requirement gate, so a bare `cargo meta verify` runs the codegen, +template and business-rules gates ([the Rust port page](../ports/rust.md)). What a check does when the run has no configuration for it differs by port. TypeScript, Java and Python skip it with a one-line note and do not fail: TypeScript skips the codegen gate when there is no `metaobjects.config.ts` (and its template gate passes with a note when the model has no `template.*` nodes), Java skips @@ -786,10 +788,11 @@ needs a `prompts/` (else `templates/`) directory, or `--templates `, and e | Kotlin | `mvn metaobjects:verify` (the same goal as Java) | As Java. `MetadataStartupValidator` adds a startup check. | As Java | | C# | `dotnet meta verify` | Codegen: an output directory (`csharp.outDir` in `.metaobjects/config.json`, or `--out `) and `codegen/Generators.cs`. Templates: `--templates `, or a `prompts/` (else `templates/`) directory in the working directory; with neither, a bare run exits 2. | `dotnet meta verify --codegen`, `dotnet meta verify --templates ` | | Python | `metaobjects verify` | Codegen: `metaobjects.config.yaml`. Templates: `metaobjects.config.yaml` or `--prompts `. | `metaobjects verify --codegen`, `metaobjects verify --templates` | +| Rust | `cargo meta verify` | Codegen: `.metaobjects/config.json` and the project's generator list (`metaobjects.config.json`; every generator runs when it is absent). Templates: a `prompts/` (else `--prompts `) directory under the project root. | `cargo meta verify --codegen`, `cargo meta verify --templates` | Schema drift is a separate, opt-in check and Node-only (ADR-0015): `meta verify --db ` -introspects the live database and reports database-versus-metadata drift. The other four -ports reject `--db` (C#, Python and the Maven goal exit 2 or fail with a pointer to the +introspects the live database and reports database-versus-metadata drift. The other five +ports reject `--db` (C#, Python, Rust and the Maven goal exit 2 or fail with a pointer to the TypeScript CLI); the live-DB-schema `metaobjects:verify` goal was removed along with the runtime auto-create validator. diff --git a/docs/features/templates-and-payloads.md b/docs/features/templates-and-payloads.md index 717538fdcf..e14dd56c1a 100644 --- a/docs/features/templates-and-payloads.md +++ b/docs/features/templates-and-payloads.md @@ -216,7 +216,7 @@ with jinja2 (`pip install "metaobjects[jinja]"`), TypeScript with nunjucks, whic body includes Jinja templates. A partial whose file is the other engine's is refused with `ERR_TEMPLATE_ENGINE_UNSUPPORTED`, in `verify` and at render time, rather than spliced in as text the including engine would misread. -- **Java, Kotlin and C# do not render Jinja.** Their providers refuse a Jinja-only body with +- **Java, Kotlin, C# and Rust do not render Jinja.** Their providers refuse a Jinja-only body with `ERR_TEMPLATE_ENGINE_UNSUPPORTED`, and their `verify` reports it on that template, so a model that needs those ports keeps its bodies in Mustache. @@ -559,6 +559,12 @@ parser, the render function, the output-format fragment, the extractor — is na the template. The tolerant tier's all-nullable mirror is named after the value object (`Extracted`). +**When another run already generates the reply type**, declare its files as a *reference +source* (`{ "path": "replies", "reference": true }` in `sources`; `` in +Maven). The reply type loads, so `@responseRef` resolves, and no value-object generator emits +it — the parser imports the type the other run generates, by the same name. See +[metadata-sources.md](metadata-sources.md#reference-sources--loaded-to-resolve-against-never-generated). + `meta verify` walks both subtypes, catching payload ↔ template drift at build time. **On malformed metadata, generators behave slightly differently** — TS throws @@ -728,12 +734,25 @@ Java, Kotlin and C#; `verify=` in Python) also checks names against the declared [`fixtures/template-output-render-conformance/runtime-drift/`](../../fixtures/template-output-render-conformance/runtime-drift/), and by the `render-error-missing-variable` and `render-error-missing-dotted-path` render fixtures. +**The reply is checked too.** For every `template.prompt` carrying `@responseRef`, `verify` +reports `ERR_RESPONSE_UNRESOLVED` (an error) when the reply type has no field a parser could +read, and, for an `@responseFormat: xml` prompt, `ERR_RESPONSE_TAG_UNDECLARED` (a warning) +for each `@requiredTags` tag that names neither the reply type nor any field in its tree. The +body is already held to those tags (`ERR_OUTPUT_TAG_MISSING`); this ties them to the type the +extractor reads, so renaming a reply field without renaming the tag the prompt asks for is +caught. Pinned by [`fixtures/response-verify-conformance/`](../../fixtures/response-verify-conformance/) +in TypeScript, Java (and so Kotlin), C#, Python and Rust. + A bare `verify` also checks generated code and the requirement ledger; name the template check to run it alone. Java and Python skip this check with a note when no template root is configured; C# does not skip, and a bare run with no `prompts/` or `templates/` directory (and no `--templates `) exits 2 ([cli.md](cli.md#verify-is-one-verb-with-explicit-subverbs-adr-0021-d2)). +Rust's check reads Mustache bodies only: a body resolving to a `.jinja` / `.j2` file is +reported as `ERR_TEMPLATE_ENGINE_UNSUPPORTED`. Its engine, `verify` in `metaobjects-render`, +is held to `fixtures/verify-conformance/` with no ledgered case. + | Port | Bare command (runs this check) | This check alone | |---|---|---| | TypeScript | `meta verify` | `meta verify --templates` | @@ -741,6 +760,7 @@ configured; C# does not skip, and a bare run with no `prompts/` or `templates/` | Kotlin | `mvn metaobjects:verify` (same Maven goal) | `-Dmeta.verify.mode=templates` | | C# | `dotnet meta verify` (needs a `prompts/` or `templates/` directory, else exits 2) | `dotnet meta verify --templates ` | | Python | `metaobjects verify` (needs `metaobjects.config.yaml` or `--prompts `) | `metaobjects verify --templates` | +| Rust | `cargo meta verify` (bodies under `prompts/`, or `--prompts `; a project with no `template.*` node prints nothing) | `cargo meta verify --templates` | ## Determinism contract diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 3e5eca3200..b02fcb2507 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -3,7 +3,7 @@ The Rust port is a full language of 1.3.0 ([ADR-0065](../../spec/decisions/ADR-0065-rust-is-the-sixth-port.md)). It reads a project, validates it, serializes it and generates code from it, and it is held to the same shared conformance corpora as the other five ports. Its command, `cargo meta`, runs the whole -codegen loop on a JSON or YAML model: `init`, `gen`, `verify --codegen` and `eject`. Three generators +codegen loop on a JSON or YAML model: `init`, `gen`, `verify --codegen`, `verify --templates` and `eject`. Three generators ship: `entity`, `client` and `commands`, and a project chooses which of them run in `metaobjects.config.json`. The four crates are **ready to publish but not published**: they package and build from their packages (a `cargo publish --dry-run` runs in the `rust` lane), and there is no release @@ -53,7 +53,7 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log |---|---| | `cargo meta init [--project ]` | Scaffolds `.metaobjects/config.json`, `.metaobjects/.gitignore` (which keeps `.gen-state/.hashes/` committed), a first `metaobjects/meta.app.yaml` and `metaobjects.config.json`, the list of generators to run (see [Choosing generators](#choosing-generators)). It writes only what is missing, and never adds an empty metadata file to a project that already has metadata. | | `cargo meta gen [ENTITY...]` | Generates the crates. It skips the whole run when the model, the project config and the generators are unchanged ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)), writes only files whose bytes changed, removes a generated file nothing emits any more, and refuses to overwrite or delete a generated file that was edited by hand. It prints what it created, updated and removed, and the crates to re-check. | -| `cargo meta verify [--codegen] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. `--codegen` runs that gate alone. A bare `verify` also runs the business-rules gate ([ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)) on the loaded model, and prints nothing about it when the model declares no operation and no transition; an error-severity finding (a `rules.permissions.names` of `require`, or `verify.lifecycle.unreachable` of `error`) exits 1. `--db`, `--templates` and `--deps` exit 2 with the reason and where that check lives. | +| `cargo meta verify [--codegen] [--templates] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. `--codegen` runs that gate alone. `--templates` is the template drift gate: each `template.*` body (under `prompts/`, or `--prompts `) against its payload value object, and each prompt's `@responseRef` reply; a bare `verify` runs it too, and a Jinja body is refused (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`). A bare `verify` also runs the business-rules gate ([ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)) on the loaded model, and prints nothing about it when the model declares no operation and no transition; an error-severity finding (a `rules.permissions.names` of `require`, or `verify.lifecycle.unreachable` of `error`) exits 1. `--db` and `--deps` exit 2 with the reason and where that check lives. | | `cargo meta eject ...` | Copies a shipped generator into the project to own. An existing copy is refused; `--force` replaces it with the reference, and leaves a copy that already matches untouched. `--undo` takes back copies still identical to the shipped source; `--list` shows what can be ejected and how each owned copy compares. See [Owning a generator](#owning-a-generator). | `gen` and `verify` share `--project `, `--out ` (default `generated`), `--generators `, @@ -278,7 +278,8 @@ outright. | `registry-conformance` | byte-identical manifest | | `conformance` (the metamodel corpus) | **584 of 584**, and the ledger is empty | | `yaml-conformance` | 18 of 19. The one on the ledger, `yaml-ref-root-escape`, waits for the root-level `::` reference rules of [ADR-0059](../../spec/decisions/ADR-0059-references-resolve-once-after-the-tree.md), which are reference resolution, not a validation pass. | -| `source-resolution-conformance` | all 28 cases | +| `source-resolution-conformance` | all 30 cases | +| `reference-source-conformance` | all 6 cases: a `reference: true` source loads so references resolve against it, a node declared only in reference files is a reference node no generator emits, and a `template.*` declared only there is refused (`ERR_REFERENCE_SOURCE_TEMPLATE`) | | `naming-conformance` | all of it | | `codegen-skip-conformance` | every case the port can meet, on both columns (what `gen` must do and what a local `verify --codegen` may do), including an edited owned generator and a forced CI verify ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)). The three it cannot meet (two about templates, one about the three-way merge) are named with their reason in the runner. | | `rules-check-conformance` | all 16 cases: the diagnostics (severity, code, node address, message text) and the summary of the `verify` business-rules gate, under each case's `rules` and `verify` settings | @@ -287,6 +288,8 @@ outright. | `writer-conformance` | every `core` case of the code writer ([ADR-0063](../../spec/decisions/ADR-0063-generators-own-layout.md)) | | `generator-registry-conformance` | the shipped generators are exactly the registry's `rust` entries, with its tier and layer, and the eject contract's census, completeness and depth hold (ADR-0034 Amendment 8) | | `render-conformance` | every case but the three the ledger holds — `render-shadowed-dotted-prefix`, `render-list-length`, `render-zero-falsiness` (`mustache-ng` has its own name lookup, data model and truthiness); a ledgered case must still differ, the rest render byte-identical through `metaobjects_render::render` (the Mustache engine underneath is `mustache-ng`) | +| `verify-conformance` | all 45 cases, through `metaobjects_render::verify`, with no ledgered case | +| `response-verify-conformance` | all 7 cases: the reply check the template gate adds — `ERR_RESPONSE_UNRESOLVED`, and, for an xml prompt, `ERR_RESPONSE_TAG_UNDECLARED` | | `extract-conformance` | all 58 cases, through `metaobjects_render::extract::extract` | | `output-prompt-conformance` | all 17 cases in all three `@promptStyle` styles, with the extract round trip, through `metaobjects_render::prompt::render_output_format` | @@ -323,14 +326,14 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to - **Other generators.** There is no server-side route, ORM or repository generator, no template generator and no documentation generator. Projections and reports get no client yet. -- **Other gates.** `verify --codegen` and the business-rules gate are the ones it has. There is no - template gate, no requirement gate and no `fmt`. +- **Other gates.** `verify --codegen`, `verify --templates` and the business-rules gate are the ones it has. + There is no requirement gate and no `fmt`. - **A three-way merge.** A hand-edited generated file is refused by name, as in every port but TypeScript; change the model or own the generator instead. - **The service tier.** No `ObjectManager`, no persistence drivers and no web adapters. - **Prompt codegen.** The render engine and the reply parser exist as a library; no generator yet - writes a template's payload type or its response parser from the model, and there is no template - gate in `verify`. + writes a template's payload type or its response parser from the model. (`verify --templates` + does check the bodies and the reply against the model.) - **Publication.** The crates are publishable and the lane proves they package (`cargo publish --dry-run`), but nothing is published: there is no crates.io release yet, and publishing waits for the owner's go ([ADR-0065](../../spec/decisions/ADR-0065-rust-is-the-sixth-port.md) Amendment 3). diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index b3f791afd9..84198022c1 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -8,7 +8,7 @@ }, "counts": { "fixtures": 584, - "corpora": 46, + "corpora": 48, "baseTypes": 21 }, "snippets": { diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index 757bc735b6..737dbc341a 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -69,6 +69,7 @@ "ERR_SOURCE_NO_PRIMARY": "An object declares source nodes but none has role=primary.", "ERR_SOURCE_MULTIPLE_PRIMARY": "An object declares more than one source node with role=primary.", "ERR_SOURCE_KIND_UNSUPPORTED": "Phase-1 metadata-source-resolution: a declared source kind (resource or package) is not supported by this toolchain.", + "ERR_REFERENCE_SOURCE_TEMPLATE": "Phase-1 metadata-source-resolution: a template.* node is declared only in reference sources (a `sources` entry with \"reference\": true), whose nodes no generator emits, so its parser and payload would be generated by nobody.", "ERR_SOURCE_UNRESOLVED": "Phase-1 metadata-source-resolution: a path source declared in .metaobjects/config.json does not exist on disk.", "ERR_PHYSICAL_NAME_KIND_MISMATCH": "FR-016 / ADR-0018: a source.rdb declares a kind-aware physical-name alias (@view/@materializedView/@proc/@function) that does not match its @kind. The legacy @table-for-non-table case warns rather than errors.", "ERR_PHYSICAL_NAME_MULTIPLE": "FR-016 / ADR-0018: a source.rdb declares two or more kind-aware physical-name aliases at once (e.g. both @table and @view). Exactly one is permitted.", diff --git a/fixtures/reference-source-conformance/README.md b/fixtures/reference-source-conformance/README.md new file mode 100644 index 0000000000..87d95a8a61 --- /dev/null +++ b/fixtures/reference-source-conformance/README.md @@ -0,0 +1,38 @@ +# reference-source-conformance + +Pins **reference sources**: a `sources` entry `{ "path": …, "reference": true }` in +`.metaobjects/config.json` whose files load (so references resolve against them) but whose +nodes no generator emits, because another generator run owns those types. + +``` +cases.json # { cases: [{ name, note?, tree, config, expectReference? | expectLoadError? }] } +``` + +Each case: + +- **`tree`** — project-root-relative path → file content, materialized under a fresh + temp root. +- **`config`** — written to `/.metaobjects/config.json`. +- **`expectReference`** — the **exhaustive** set of top-level resolution keys + (`package::Name`) the port reports as reference nodes after a project-aware load, + compared as an unordered set. `[]` means "loads, and nothing is a reference node." +- **`expectLoadError`** — instead of the above: the load must fail with exactly this code. + +Rules the corpus pins: + +1. A reference source's files load into the same root as every other source; a prompt's + `@responseRef` naming a type there resolves (the first case shows the same tree failing + `ERR_INVALID_TEMPLATE` without the reference source). +2. A top-level node is a reference node iff **every** file declaring it (overlays included) is + a reference file. One declaration in an ordinary source makes it the project's own. +3. A file an ordinary source also reaches is ordinary. +4. A `template.*` declared only in reference sources is refused with + `ERR_REFERENCE_SOURCE_TEMPLATE`. + +What a port does with the set — exclude it from every generator's selection while a local +prompt's parser for a reference reply type still emits — is proven by each port's own +codegen test, since the emitted file names are per-port. + +Runners: TypeScript `server/typescript/packages/sdk/test/reference-source-conformance.test.ts` +(reference implementation) and one per port; see `docs/CONFORMANCE.md`. Design: +`docs/features/metadata-sources.md`, "Reference sources". diff --git a/fixtures/reference-source-conformance/cases.json b/fixtures/reference-source-conformance/cases.json new file mode 100644 index 0000000000..57302b3eb7 --- /dev/null +++ b/fixtures/reference-source-conformance/cases.json @@ -0,0 +1,127 @@ +{ + "cases": [ + { + "name": "reply-type-outside-the-loaded-sources-does-not-resolve", + "note": "The blocker as measured: the reply types live in files this load does not read, so the prompt's @responseRef names nothing and the load is refused.", + "tree": { + "model/meta.prompts.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportRequest\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"question\",\n \"@required\": true\n }\n }\n ]\n }\n },\n {\n \"template.prompt\": {\n \"name\": \"SupportAnswerPrompt\",\n \"@payloadRef\": \"acme::support::SupportRequest\",\n \"@responseRef\": \"acme::support::SupportAnswer\",\n \"@textRef\": \"support/answer\",\n \"@format\": \"text\"\n }\n }\n ]\n }\n}\n", + "replies/meta.replies.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportAnswer\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"text\",\n \"@required\": true\n }\n },\n {\n \"field.object\": {\n \"name\": \"source\",\n \"@objectRef\": \"acme::support::AnswerSource\"\n }\n }\n ]\n }\n },\n {\n \"object.value\": {\n \"name\": \"AnswerSource\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"url\"\n }\n }\n ]\n }\n }\n ]\n }\n}\n" + }, + "config": { + "schema_version": 1, + "sources": [ + { + "path": "model" + } + ] + }, + "expectLoadError": "ERR_INVALID_TEMPLATE" + }, + { + "name": "reply-type-in-a-reference-source-resolves-and-is-not-generated", + "note": "The same files with replies/ declared as a reference source: the reference resolves, and the reply type and the value object it nests are reference nodes.", + "tree": { + "model/meta.prompts.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportRequest\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"question\",\n \"@required\": true\n }\n }\n ]\n }\n },\n {\n \"template.prompt\": {\n \"name\": \"SupportAnswerPrompt\",\n \"@payloadRef\": \"acme::support::SupportRequest\",\n \"@responseRef\": \"acme::support::SupportAnswer\",\n \"@textRef\": \"support/answer\",\n \"@format\": \"text\"\n }\n }\n ]\n }\n}\n", + "replies/meta.replies.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportAnswer\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"text\",\n \"@required\": true\n }\n },\n {\n \"field.object\": {\n \"name\": \"source\",\n \"@objectRef\": \"acme::support::AnswerSource\"\n }\n }\n ]\n }\n },\n {\n \"object.value\": {\n \"name\": \"AnswerSource\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"url\"\n }\n }\n ]\n }\n }\n ]\n }\n}\n" + }, + "config": { + "schema_version": 1, + "sources": [ + { + "path": "model" + }, + { + "path": "replies", + "reference": true + } + ] + }, + "expectReference": [ + "acme::support::AnswerSource", + "acme::support::SupportAnswer" + ] + }, + { + "name": "no-reference-source-means-no-reference-nodes", + "tree": { + "model/meta.prompts.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportRequest\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"question\",\n \"@required\": true\n }\n }\n ]\n }\n },\n {\n \"template.prompt\": {\n \"name\": \"SupportAnswerPrompt\",\n \"@payloadRef\": \"acme::support::SupportRequest\",\n \"@responseRef\": \"acme::support::SupportAnswer\",\n \"@textRef\": \"support/answer\",\n \"@format\": \"text\"\n }\n }\n ]\n }\n}\n", + "model/meta.replies.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportAnswer\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"text\",\n \"@required\": true\n }\n },\n {\n \"field.object\": {\n \"name\": \"source\",\n \"@objectRef\": \"acme::support::AnswerSource\"\n }\n }\n ]\n }\n },\n {\n \"object.value\": {\n \"name\": \"AnswerSource\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"url\"\n }\n }\n ]\n }\n }\n ]\n }\n}\n" + }, + "config": { + "schema_version": 1, + "sources": [ + { + "path": "model" + } + ] + }, + "expectReference": [] + }, + { + "name": "an-overlay-in-an-own-source-makes-the-node-the-projects-own", + "note": "A node is a reference node only when EVERY file declaring it is a reference file. SupportAnswer is overlaid from an own file, so it is the project's own; AnswerSource stays a reference node.", + "tree": { + "model/meta.prompts.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportRequest\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"question\",\n \"@required\": true\n }\n }\n ]\n }\n },\n {\n \"template.prompt\": {\n \"name\": \"SupportAnswerPrompt\",\n \"@payloadRef\": \"acme::support::SupportRequest\",\n \"@responseRef\": \"acme::support::SupportAnswer\",\n \"@textRef\": \"support/answer\",\n \"@format\": \"text\"\n }\n }\n ]\n }\n}\n", + "replies/meta.replies.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportAnswer\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"text\",\n \"@required\": true\n }\n },\n {\n \"field.object\": {\n \"name\": \"source\",\n \"@objectRef\": \"acme::support::AnswerSource\"\n }\n }\n ]\n }\n },\n {\n \"object.value\": {\n \"name\": \"AnswerSource\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"url\"\n }\n }\n ]\n }\n }\n ]\n }\n}\n", + "model/meta.answer-overlay.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportAnswer\",\n \"overlay\": true,\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"note\"\n }\n }\n ]\n }\n }\n ]\n }\n}\n" + }, + "config": { + "schema_version": 1, + "sources": [ + { + "path": "model" + }, + { + "path": "replies", + "reference": true + } + ] + }, + "expectReference": [ + "acme::support::AnswerSource" + ] + }, + { + "name": "a-file-an-ordinary-source-also-reaches-is-the-projects-own", + "note": "model/ is declared as an ordinary source and one of its files again as a reference source: the ordinary declaration wins.", + "tree": { + "model/meta.prompts.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportRequest\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"question\",\n \"@required\": true\n }\n }\n ]\n }\n },\n {\n \"template.prompt\": {\n \"name\": \"SupportAnswerPrompt\",\n \"@payloadRef\": \"acme::support::SupportRequest\",\n \"@responseRef\": \"acme::support::SupportAnswer\",\n \"@textRef\": \"support/answer\",\n \"@format\": \"text\"\n }\n }\n ]\n }\n}\n", + "model/meta.replies.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportAnswer\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"text\",\n \"@required\": true\n }\n },\n {\n \"field.object\": {\n \"name\": \"source\",\n \"@objectRef\": \"acme::support::AnswerSource\"\n }\n }\n ]\n }\n },\n {\n \"object.value\": {\n \"name\": \"AnswerSource\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"url\"\n }\n }\n ]\n }\n }\n ]\n }\n}\n" + }, + "config": { + "schema_version": 1, + "sources": [ + { + "path": "model" + }, + { + "path": "model/meta.replies.json", + "reference": true + } + ] + }, + "expectReference": [] + }, + { + "name": "a-template-in-a-reference-source-is-refused", + "note": "A reference source holds shapes another run generates; a prompt there would have its parser and payload generated by nobody, so it is refused.", + "tree": { + "model/meta.prompts.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportRequest\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"question\",\n \"@required\": true\n }\n }\n ]\n }\n }\n ]\n }\n}\n", + "replies/meta.replies.json": "{\n \"metadata.root\": {\n \"package\": \"acme::support\",\n \"children\": [\n {\n \"object.value\": {\n \"name\": \"SupportAnswer\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"text\",\n \"@required\": true\n }\n },\n {\n \"field.object\": {\n \"name\": \"source\",\n \"@objectRef\": \"acme::support::AnswerSource\"\n }\n }\n ]\n }\n },\n {\n \"object.value\": {\n \"name\": \"AnswerSource\",\n \"children\": [\n {\n \"field.string\": {\n \"name\": \"url\"\n }\n }\n ]\n }\n },\n {\n \"template.prompt\": {\n \"name\": \"SupportAnswerPrompt\",\n \"@payloadRef\": \"acme::support::SupportRequest\",\n \"@responseRef\": \"acme::support::SupportAnswer\",\n \"@textRef\": \"support/answer\",\n \"@format\": \"text\"\n }\n }\n ]\n }\n}\n" + }, + "config": { + "schema_version": 1, + "sources": [ + { + "path": "model" + }, + { + "path": "replies", + "reference": true + } + ] + }, + "expectLoadError": "ERR_REFERENCE_SOURCE_TEMPLATE" + } + ] +} diff --git a/fixtures/response-verify-conformance/README.md b/fixtures/response-verify-conformance/README.md new file mode 100644 index 0000000000..7089af8fcc --- /dev/null +++ b/fixtures/response-verify-conformance/README.md @@ -0,0 +1,27 @@ +# response-verify-conformance + +Pins what the template drift gate (`meta verify --templates` and each port's counterpart) +reports about a prompt's **reply** — the `@responseRef` value object a model's answer is +parsed into. + +``` +cases.json # { cases: [{ name, note?, metadata, expect: [{ template, code, path, severity }] }] } +``` + +Each case's `metadata` is one canonical-JSON file. Load it, and for every `template.*` node +collect the reply findings; `expect` is the **exhaustive** list, compared as an unordered set. + +| Code | Severity | Raised when | `path` | +|---|---|---|---| +| `ERR_RESPONSE_UNRESOLVED` | error | a `template.prompt` carries `@responseRef` and the reply resolves to no loaded value shape with at least one field | the `@responseRef` value | +| `ERR_RESPONSE_TAG_UNDECLARED` | warning | `@responseFormat: xml`, and a `@requiredTags` entry is neither the reply type's short name nor the name of a field anywhere in the reply tree (nested value objects included) | the tag | + +`@responseRef`, `@responseFormat` and `@requiredTags` are read **resolving** (ADR-0039): a +prompt that inherits them through `extends` is checked with the inherited values. A prompt +with no `@responseRef`, and a json prompt's tags, produce nothing here. The body checks the +gate already runs (`ERR_OUTPUT_TAG_MISSING`, `ERR_REQUIRED_SLOT_UNUSED`, …) are not part of +this corpus. + +Runners: TypeScript `server/typescript/packages/cli/test/response-verify-conformance.test.ts` +(reference implementation) and one per port that ships a template gate (Rust's is `server/rust/metaobjects-cli/tests/response_verify_conformance.rs`). See +`docs/CONFORMANCE.md`. diff --git a/fixtures/response-verify-conformance/cases.json b/fixtures/response-verify-conformance/cases.json new file mode 100644 index 0000000000..730da2fff9 --- /dev/null +++ b/fixtures/response-verify-conformance/cases.json @@ -0,0 +1,554 @@ +{ + "cases": [ + { + "name": "a-prompt-with-no-reply-has-nothing-to-check", + "metadata": { + "metadata.root": { + "package": "acme::support", + "children": [ + { + "object.value": { + "name": "SupportRequest", + "children": [ + { + "field.string": { + "name": "question", + "@required": true + } + } + ] + } + }, + { + "object.value": { + "name": "AnswerSource", + "children": [ + { + "field.string": { + "name": "url" + } + } + ] + } + }, + { + "object.value": { + "name": "SupportAnswer", + "children": [ + { + "field.string": { + "name": "text", + "@required": true + } + }, + { + "field.object": { + "name": "source", + "@objectRef": "acme::support::AnswerSource" + } + } + ] + } + }, + { + "object.value": { + "name": "EmptyAnswer", + "children": [] + } + }, + { + "template.prompt": { + "name": "SupportAnswerPrompt", + "@payloadRef": "acme::support::SupportRequest", + "@textRef": "support/answer", + "@format": "text" + } + } + ] + } + }, + "expect": [] + }, + { + "name": "a-json-reply-that-resolves-is-clean", + "metadata": { + "metadata.root": { + "package": "acme::support", + "children": [ + { + "object.value": { + "name": "SupportRequest", + "children": [ + { + "field.string": { + "name": "question", + "@required": true + } + } + ] + } + }, + { + "object.value": { + "name": "AnswerSource", + "children": [ + { + "field.string": { + "name": "url" + } + } + ] + } + }, + { + "object.value": { + "name": "SupportAnswer", + "children": [ + { + "field.string": { + "name": "text", + "@required": true + } + }, + { + "field.object": { + "name": "source", + "@objectRef": "acme::support::AnswerSource" + } + } + ] + } + }, + { + "object.value": { + "name": "EmptyAnswer", + "children": [] + } + }, + { + "template.prompt": { + "name": "SupportAnswerPrompt", + "@payloadRef": "acme::support::SupportRequest", + "@textRef": "support/answer", + "@format": "text", + "@responseRef": "acme::support::SupportAnswer", + "@responseFormat": "json" + } + } + ] + } + }, + "expect": [] + }, + { + "name": "a-reply-with-no-fields-is-unresolved", + "note": "The loader accepts an empty value object, and a parser for it reads nothing.", + "metadata": { + "metadata.root": { + "package": "acme::support", + "children": [ + { + "object.value": { + "name": "SupportRequest", + "children": [ + { + "field.string": { + "name": "question", + "@required": true + } + } + ] + } + }, + { + "object.value": { + "name": "AnswerSource", + "children": [ + { + "field.string": { + "name": "url" + } + } + ] + } + }, + { + "object.value": { + "name": "SupportAnswer", + "children": [ + { + "field.string": { + "name": "text", + "@required": true + } + }, + { + "field.object": { + "name": "source", + "@objectRef": "acme::support::AnswerSource" + } + } + ] + } + }, + { + "object.value": { + "name": "EmptyAnswer", + "children": [] + } + }, + { + "template.prompt": { + "name": "SupportAnswerPrompt", + "@payloadRef": "acme::support::SupportRequest", + "@textRef": "support/answer", + "@format": "text", + "@responseRef": "acme::support::EmptyAnswer" + } + } + ] + } + }, + "expect": [ + { + "template": "SupportAnswerPrompt", + "code": "ERR_RESPONSE_UNRESOLVED", + "path": "acme::support::EmptyAnswer", + "severity": "error" + } + ] + }, + { + "name": "xml-required-tags-that-name-the-reply-and-its-fields-are-clean", + "note": "The reply type's own name and any field in its tree, nested ones included.", + "metadata": { + "metadata.root": { + "package": "acme::support", + "children": [ + { + "object.value": { + "name": "SupportRequest", + "children": [ + { + "field.string": { + "name": "question", + "@required": true + } + } + ] + } + }, + { + "object.value": { + "name": "AnswerSource", + "children": [ + { + "field.string": { + "name": "url" + } + } + ] + } + }, + { + "object.value": { + "name": "SupportAnswer", + "children": [ + { + "field.string": { + "name": "text", + "@required": true + } + }, + { + "field.object": { + "name": "source", + "@objectRef": "acme::support::AnswerSource" + } + } + ] + } + }, + { + "object.value": { + "name": "EmptyAnswer", + "children": [] + } + }, + { + "template.prompt": { + "name": "SupportAnswerPrompt", + "@payloadRef": "acme::support::SupportRequest", + "@textRef": "support/answer", + "@format": "text", + "@responseRef": "acme::support::SupportAnswer", + "@responseFormat": "xml", + "@requiredTags": [ + "SupportAnswer", + "text", + "source", + "url" + ] + } + } + ] + } + }, + "expect": [] + }, + { + "name": "an-xml-required-tag-the-reply-does-not-declare-is-reported", + "metadata": { + "metadata.root": { + "package": "acme::support", + "children": [ + { + "object.value": { + "name": "SupportRequest", + "children": [ + { + "field.string": { + "name": "question", + "@required": true + } + } + ] + } + }, + { + "object.value": { + "name": "AnswerSource", + "children": [ + { + "field.string": { + "name": "url" + } + } + ] + } + }, + { + "object.value": { + "name": "SupportAnswer", + "children": [ + { + "field.string": { + "name": "text", + "@required": true + } + }, + { + "field.object": { + "name": "source", + "@objectRef": "acme::support::AnswerSource" + } + } + ] + } + }, + { + "object.value": { + "name": "EmptyAnswer", + "children": [] + } + }, + { + "template.prompt": { + "name": "SupportAnswerPrompt", + "@payloadRef": "acme::support::SupportRequest", + "@textRef": "support/answer", + "@format": "text", + "@responseRef": "acme::support::SupportAnswer", + "@responseFormat": "xml", + "@requiredTags": [ + "text", + "answer", + "confidence" + ] + } + } + ] + } + }, + "expect": [ + { + "template": "SupportAnswerPrompt", + "code": "ERR_RESPONSE_TAG_UNDECLARED", + "path": "answer", + "severity": "warning" + }, + { + "template": "SupportAnswerPrompt", + "code": "ERR_RESPONSE_TAG_UNDECLARED", + "path": "confidence", + "severity": "warning" + } + ] + }, + { + "name": "required-tags-on-a-json-reply-are-not-checked-against-it", + "metadata": { + "metadata.root": { + "package": "acme::support", + "children": [ + { + "object.value": { + "name": "SupportRequest", + "children": [ + { + "field.string": { + "name": "question", + "@required": true + } + } + ] + } + }, + { + "object.value": { + "name": "AnswerSource", + "children": [ + { + "field.string": { + "name": "url" + } + } + ] + } + }, + { + "object.value": { + "name": "SupportAnswer", + "children": [ + { + "field.string": { + "name": "text", + "@required": true + } + }, + { + "field.object": { + "name": "source", + "@objectRef": "acme::support::AnswerSource" + } + } + ] + } + }, + { + "object.value": { + "name": "EmptyAnswer", + "children": [] + } + }, + { + "template.prompt": { + "name": "SupportAnswerPrompt", + "@payloadRef": "acme::support::SupportRequest", + "@textRef": "support/answer", + "@format": "text", + "@responseRef": "acme::support::SupportAnswer", + "@responseFormat": "json", + "@requiredTags": [ + "answer" + ] + } + } + ] + } + }, + "expect": [] + }, + { + "name": "a-reply-inherited-from-an-abstract-prompt-is-checked", + "note": "@responseRef / @responseFormat / @requiredTags are read resolving (ADR-0039): an extends-inherited reply is the prompt's reply.", + "metadata": { + "metadata.root": { + "package": "acme::support", + "children": [ + { + "object.value": { + "name": "SupportRequest", + "children": [ + { + "field.string": { + "name": "question", + "@required": true + } + } + ] + } + }, + { + "object.value": { + "name": "AnswerSource", + "children": [ + { + "field.string": { + "name": "url" + } + } + ] + } + }, + { + "object.value": { + "name": "SupportAnswer", + "children": [ + { + "field.string": { + "name": "text", + "@required": true + } + }, + { + "field.object": { + "name": "source", + "@objectRef": "acme::support::AnswerSource" + } + } + ] + } + }, + { + "object.value": { + "name": "EmptyAnswer", + "children": [] + } + }, + { + "template.prompt": { + "name": "BasePrompt", + "abstract": true, + "@payloadRef": "acme::support::SupportRequest", + "@responseRef": "acme::support::SupportAnswer", + "@responseFormat": "xml", + "@format": "text", + "@textRef": "support/base" + } + }, + { + "template.prompt": { + "name": "ChildPrompt", + "extends": "BasePrompt", + "@textRef": "support/answer", + "@requiredTags": [ + "text", + "missing" + ] + } + } + ] + } + }, + "expect": [ + { + "template": "ChildPrompt", + "code": "ERR_RESPONSE_TAG_UNDECLARED", + "path": "missing", + "severity": "warning" + } + ] + } + ] +} diff --git a/fixtures/source-resolution-conformance/cases.json b/fixtures/source-resolution-conformance/cases.json index e367db2f77..ec58bbfeeb 100644 --- a/fixtures/source-resolution-conformance/cases.json +++ b/fixtures/source-resolution-conformance/cases.json @@ -274,6 +274,23 @@ "config": { "schema_version": 1, "sources": [{ "path": "model" }] }, "expectError": true, "errorIsNative": true + }, + { + "name": "a-reference-source-resolves-its-files-like-any-other", + "tree": { + "model/meta.users.json": "{\"metadata.root\":{\"children\":[]}}", + "replies/meta.replies.json": "{\"metadata.root\":{\"children\":[]}}" + }, + "config": { "schema_version": 1, "sources": [{ "path": "model" }, { "path": "replies", "reference": true }] }, + "expectFiles": ["model/meta.users.json", "replies/meta.replies.json"] + }, + { + "name": "a-reference-flag-that-is-not-a-boolean-is-an-error", + "tree": { + "model/meta.users.json": "{\"metadata.root\":{\"children\":[]}}" + }, + "config": { "schema_version": 1, "sources": [{ "path": "model", "reference": "yes" }] }, + "expectError": true } ] } diff --git a/server/csharp/MetaObjects.Cli.Tests/ResponseVerifyConformanceTests.cs b/server/csharp/MetaObjects.Cli.Tests/ResponseVerifyConformanceTests.cs new file mode 100644 index 0000000000..aa9e456bd6 --- /dev/null +++ b/server/csharp/MetaObjects.Cli.Tests/ResponseVerifyConformanceTests.cs @@ -0,0 +1,67 @@ +// Runs the shared response-verify corpus (fixtures/response-verify-conformance/cases.json) against this +// port's template gate. Contract: server/typescript/packages/cli/src/lib/response-verify.ts. +using System.Text.Json; +using MetaObjects.Cli; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Cli.Tests; + +public sealed class ResponseVerifyConformanceTests +{ + private sealed record Case(string Name, string MetadataText, List<(string Template, string Code, string Path, string Severity)> Expect); + + public static TheoryData CaseNames() + { + var data = new TheoryData(); + foreach (var c in LoadCases()) data.Add(c.Name); + return data; + } + + private static string CorpusPath() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !Directory.Exists(Path.Combine(dir.FullName, "fixtures"))) + dir = dir.Parent; + Assert.NotNull(dir); + return Path.Combine(dir!.FullName, "fixtures", "response-verify-conformance", "cases.json"); + } + + private static List LoadCases() + { + using var doc = JsonDocument.Parse(File.ReadAllText(CorpusPath())); + return doc.RootElement.GetProperty("cases").EnumerateArray().Select(el => new Case( + el.GetProperty("name").GetString()!, + el.GetProperty("metadata").GetRawText(), + el.GetProperty("expect").EnumerateArray().Select(e => + (e.GetProperty("template").GetString()!, e.GetProperty("code").GetString()!, + e.GetProperty("path").GetString()!, e.GetProperty("severity").GetString()!)).ToList())).ToList(); + } + + [Theory] + [MemberData(nameof(CaseNames))] + public void ReportsTheReplyFindingsTheCorpusPins(string name) + { + var c = LoadCases().Single(x => x.Name == name); + var load = new MetaDataLoader().Load([new InMemoryStringSource(c.MetadataText, id: "case.json")]); + Assert.Empty(load.Errors); + + var templates = Path.Combine(Path.GetTempPath(), "mo-resp-verify-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(templates); + try + { + var outcome = VerifyCommand.Run(load, templates); + static bool IsReply(string code) => code is ResponseVerify.ERR_RESPONSE_UNRESOLVED or ResponseVerify.ERR_RESPONSE_TAG_UNDECLARED; + var got = outcome.Errors.Select(d => (d.Template, d.Code, d.Path, Severity: "error")) + .Concat(outcome.Warnings.Select(d => (d.Template, d.Code, d.Path, Severity: "warning"))) + .Where(d => IsReply(d.Code)) + .OrderBy(d => d.Template, StringComparer.Ordinal).ThenBy(d => d.Path, StringComparer.Ordinal).ToList(); + var want = c.Expect.OrderBy(d => d.Template, StringComparer.Ordinal).ThenBy(d => d.Path, StringComparer.Ordinal).ToList(); + Assert.Equal(want, got); + } + finally + { + Directory.Delete(templates, recursive: true); + } + } +} diff --git a/server/csharp/MetaObjects.Cli/Program.cs b/server/csharp/MetaObjects.Cli/Program.cs index 4a5fab3b53..77a619daea 100644 --- a/server/csharp/MetaObjects.Cli/Program.cs +++ b/server/csharp/MetaObjects.Cli/Program.cs @@ -570,6 +570,7 @@ static int RunVerify(string[] rest) // ResolveMetadataDirOrExit). Libraries = resolvedMeta.Libraries, Imports = resolvedMeta.Imports, + ReferenceFiles = resolvedMeta.ReferenceFiles, Providers = resolvedMeta.Providers, // ADR-0058 — same source as Libraries; the --codegen gate's regen reads it from // the loaded root rather than a flag (see VerifyCommand.RunCodegenDrift). diff --git a/server/csharp/MetaObjects.Cli/ResponseVerify.cs b/server/csharp/MetaObjects.Cli/ResponseVerify.cs new file mode 100644 index 0000000000..bb8f52016f --- /dev/null +++ b/server/csharp/MetaObjects.Cli/ResponseVerify.cs @@ -0,0 +1,72 @@ +// What `dotnet meta verify --templates` checks about a prompt's REPLY (`@responseRef`). +// +// Behavioral contract: server/typescript/packages/cli/src/lib/response-verify.ts, pinned cross-port by +// fixtures/response-verify-conformance/cases.json. The loader already refuses a `@responseRef` that names +// nothing, so this gate checks what loading cannot: +// - the reply type has a field tree a parser can read (ERR_RESPONSE_UNRESOLVED, an error); +// - for an `@responseFormat: xml` prompt, every `@requiredTags` tag names the reply type or one of its +// fields (ERR_RESPONSE_TAG_UNDECLARED, a warning). + +using MetaObjects.Codegen; +using MetaObjects.Meta; +using MetaObjects.Render; +using static MetaObjects.Shared.BaseTypes; +using static MetaObjects.Template.TemplateConstants; + +namespace MetaObjects.Cli; + +public static class ResponseVerify +{ + /// A responding prompt's @responseRef names no loaded value shape with fields. + public const string ERR_RESPONSE_UNRESOLVED = "ERR_RESPONSE_UNRESOLVED"; + /// An xml prompt's @requiredTags tag names neither the reply type nor a reply field (warning). + public const string ERR_RESPONSE_TAG_UNDECLARED = "ERR_RESPONSE_TAG_UNDECLARED"; + + /// One reply finding. is the @responseRef value or the offending tag. + public sealed record Finding(string Code, string Path, bool IsError); + + /// + /// The reply findings for one template. Empty for anything that is not a template.prompt + /// carrying @responseRef — a prompt that does not elicit a typed reply has nothing here. + /// + public static IReadOnlyList Findings(MetaData tmpl) + { + if (tmpl.Type != TYPE_TEMPLATE || tmpl.SubType != TEMPLATE_SUBTYPE_PROMPT) return []; + // ADR-0039: effective attrs — a prompt may inherit @responseRef / @responseFormat / @requiredTags. + if (tmpl.Attr(TEMPLATE_ATTR_RESPONSE_REF) is not string responseRef) return []; + + var reply = global::MetaObjects.NamingRefs.RefTarget(tmpl, TEMPLATE_ATTR_RESPONSE_REF); + var tree = reply is null ? [] : PayloadFieldTree.Build(reply); + if (reply is null || tree.Count == 0) + return [new Finding(ERR_RESPONSE_UNRESOLVED, responseRef, IsError: true)]; + + if (tmpl.Attr(TEMPLATE_ATTR_RESPONSE_FORMAT) is not string format + || !string.Equals(format, RESPONSE_FORMAT_XML, StringComparison.OrdinalIgnoreCase)) return []; + if (tmpl.Attr(TEMPLATE_ATTR_REQUIRED_TAGS) is not { } tagsAttr) return []; + var tags = tagsAttr switch + { + IReadOnlyList ss => ss.ToList(), + IReadOnlyList os => os.OfType().ToList(), + _ => [], + }; + var known = new HashSet(StringComparer.Ordinal) { ShortName(reply.Name) }; + FieldNames(tree, known); + return tags.Where(t => !known.Contains(t)) + .Select(t => new Finding(ERR_RESPONSE_TAG_UNDECLARED, t, IsError: false)).ToList(); + } + + private static void FieldNames(IReadOnlyList tree, HashSet into) + { + foreach (var f in tree) + { + into.Add(f.Name); + if (f.Fields is not null) FieldNames(f.Fields, into); + } + } + + private static string ShortName(string name) + { + var i = name.LastIndexOf("::", StringComparison.Ordinal); + return i == -1 ? name : name[(i + 2)..]; + } +} diff --git a/server/csharp/MetaObjects.Cli/VerifyCommand.cs b/server/csharp/MetaObjects.Cli/VerifyCommand.cs index 3b6e911fbe..692e467bc8 100644 --- a/server/csharp/MetaObjects.Cli/VerifyCommand.cs +++ b/server/csharp/MetaObjects.Cli/VerifyCommand.cs @@ -113,6 +113,8 @@ public sealed record Options /// was imported so the --codegen gate regenerates exactly what gen wrote. Null: none. /// public MetaObjects.Config.ImportScope? Imports { get; init; } + /// The reference files among ({ "path": ..., "reference": true } sources); the load records the nodes only they declare so the --codegen gate skips them as gen does. + public IReadOnlySet? ReferenceFiles { get; init; } /// csharp.providers, instantiated; composed with the core providers on every load. Null: core only. public IReadOnlyList? Providers { get; init; } /// @@ -286,7 +288,7 @@ private static LoadResult LoadMetadata(Options opts) // The same load `gen` runs (ResolvedMetadata.Load): libraries, then the dependency snapshots, then the // project's own files; ADR-0058 naming and the wire format set on the root; the imports recorded on it. return new MetaObjects.Config.ResolvedMetadata( - opts.MetadataDir, opts.MetadataFiles, opts.Libraries, opts.Naming, opts.Wire, null, opts.Imports, null, opts.Providers) { Api = opts.Api } + opts.MetadataDir, opts.MetadataFiles, opts.Libraries, opts.Naming, opts.Wire, null, opts.Imports, null, opts.Providers) { Api = opts.Api, ReferenceFiles = opts.ReferenceFiles } .Load(opts.Strict); } @@ -563,6 +565,14 @@ public static Outcome Run(LoadResult load, string templatesRoot) foreach (var tmpl in load.Root.OwnChildren().Where(c => c.Type == TYPE_TEMPLATE)) { + // The reply (`@responseRef`): its field tree, and an xml prompt's tag contract against it. + // Independent of the payload check below, so it runs first. + foreach (var f in ResponseVerify.Findings(tmpl)) + { + var finding = new Drift(tmpl.Name, KIND_PROMPT, f.Code, f.Path); + if (f.IsError) errors.Add(finding); else warnings.Add(finding); + } + // ADR-0039: @payloadRef may be inherited via an abstract template (templates // CAN extend) → resolving Attr, not OwnAttr. Missing is a load error already. if (tmpl.Attr(TEMPLATE_ATTR_PAYLOAD_REF) is not string payloadRef) diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReferenceNodesGenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReferenceNodesGenTests.cs new file mode 100644 index 0000000000..87b6ceb732 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/ReferenceNodesGenTests.cs @@ -0,0 +1,83 @@ +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Config; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +/// +/// A reply type declared in a reference source ({ "path": ..., "reference": true }) resolves for +/// the prompt that names it, but no generator emits it: another run owns the type. The prompt's output +/// parser still emits and names the reply type exactly as it would have if generated here. Mirrors +/// server/typescript/packages/codegen-ts/test/reference-nodes-gen.test.ts. +/// +public sealed class ReferenceNodesGenTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "mo-ref-gen-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + try { Directory.Delete(_root, recursive: true); } catch { /* best effort */ } + } + + private const string Prompts = """ + { "metadata.root": { "package": "acme::support", "children": [ + { "object.value": { "name": "SupportRequest", "children": [ { "field.string": { "name": "question", "@required": true } } ] } }, + { "template.prompt": { "name": "SupportAnswerPrompt", "@payloadRef": "acme::support::SupportRequest", + "@responseRef": "acme::support::SupportAnswer", "@textRef": "support/answer", "@format": "text" } } + ]}} + """; + + private const string Replies = """ + { "metadata.root": { "package": "acme::support", "children": [ + { "object.value": { "name": "SupportAnswer", "children": [ + { "field.string": { "name": "text", "@required": true } }, + { "field.object": { "name": "source", "@objectRef": "acme::support::AnswerSource" } } ] } }, + { "object.value": { "name": "AnswerSource", "children": [ { "field.string": { "name": "url" } } ] } } + ]}} + """; + + private Dictionary Generate(bool reference) + { + Directory.CreateDirectory(Path.Combine(_root, ".metaobjects")); + Directory.CreateDirectory(Path.Combine(_root, "model")); + File.WriteAllText(Path.Combine(_root, "model", "meta.prompts.json"), Prompts); + // The control keeps the reply file in the one ordinary source; the case under test moves it to a reference source. + var replies = reference ? "replies" : "model"; + Directory.CreateDirectory(Path.Combine(_root, replies)); + File.WriteAllText(Path.Combine(_root, replies, "meta.replies.json"), Replies); + var sources = reference + ? """[ { "path": "model" }, { "path": "replies", "reference": true } ]""" + : """[ { "path": "model" } ]"""; + File.WriteAllText(Path.Combine(_root, ".metaobjects", "config.json"), $$"""{ "schema_version": 1, "sources": {{sources}} }"""); + + var load = MetadataLocation.Resolve(null, _root).Load(); + Assert.Empty(load.Errors); + + var outDir = Path.Combine(_root, "out"); + CodegenRunner.Run(new GenConfig { OutDir = outDir, Namespace = "Acme.Generated" }, load.Root, + [new EntityGenerator(), new OutputParserGenerator()]); + return Directory.EnumerateFiles(outDir, "*.cs", SearchOption.AllDirectories) + .ToDictionary(f => Path.GetRelativePath(outDir, f).Replace('\\', '/'), File.ReadAllText); + } + + [Fact] + public void A_reference_reply_type_gets_no_poco_but_its_parser_still_emits() + { + var files = Generate(reference: true); + // The prompt's own payload type is the project's; the reply type and the value object it nests are not. + Assert.Contains(files.Values, c => c.Contains("class SupportRequest") || c.Contains("record SupportRequest")); + Assert.DoesNotContain(files.Values, c => c.Contains("class SupportAnswer ") || c.Contains("record SupportAnswer ")); + Assert.DoesNotContain(files.Values, c => c.Contains("class AnswerSource ") || c.Contains("record AnswerSource ")); + // The parser is emitted and names the reply type as it would have if it were generated here. + var parser = Assert.Single(files, f => f.Key.EndsWith("SupportAnswerPrompt.response.cs", StringComparison.Ordinal)); + Assert.Contains("SupportAnswer", parser.Value); + } + + [Fact] + public void The_same_files_as_an_ordinary_source_do_emit_the_reply_type() + { + var files = Generate(reference: false); + Assert.Contains(files.Values, c => c.Contains("class SupportAnswer") || c.Contains("record SupportAnswer")); + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index 54ebf7af3b..a3ea492cf0 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -1054,7 +1054,8 @@ protected virtual IEnumerable EmitSharedEnumFiles(GenContext ctx, I // codegen-time error (ADR-0026), even though @provided emits no file content. // FR-023: an imported value object this run emits a POCO for (a generated type needs it), so // the enums IT uses are part of the output too. - var importedShapes = valueShapes.Where(vo => !ctx.Root.InScope(vo)).ToList(); + // A reference node is the project's own to name, not to emit: another run generates its type. + var importedShapes = valueShapes.Where(vo => !ctx.Root.InScope(vo) && !ctx.Root.IsReference(vo)).ToList(); // A narrowed run (Include) declares the enums of the objects it accepts and of every value // object it emits beyond them (a reached closure POCO), not the whole model's; another entry // declares the rest, and an enum both use is declared once (below). Un-narrowed, the set is @@ -3008,7 +3009,7 @@ protected static List ReferencedValueObjects(IReadOnlyList c.Type == global::MetaObjects.Shared.BaseTypes.TYPE_TEMPLATE)) foreach (var attr in new[] { global::MetaObjects.Template.TemplateConstants.TEMPLATE_ATTR_PAYLOAD_REF, global::MetaObjects.Template.TemplateConstants.TEMPLATE_ATTR_RESPONSE_REF }) - if (ValueObjectNames.PayloadShapeOf(tmpl, attr) is MetaObject { IsAbstract: false } shape && seen.Add(shape.ResolutionKey())) + if (ValueObjectNames.PayloadShapeOf(tmpl, attr) is MetaObject { IsAbstract: false } shape && !ctx.Root.IsReference(shape) && seen.Add(shape.ResolutionKey())) queue.Enqueue(shape); while (queue.Count > 0) @@ -3024,7 +3025,8 @@ void Enqueue(MetaObject? target) { // Only plain value objects (no source) become POCOs; entities/projections // are already in `mapped`. Deduped by FQN: two value objects may share a short name. - if (target is null || !target.IsValue() || target.DbView is not null) return; + // A reference value object is generated by the run that owns it, never here. + if (target is null || !target.IsValue() || target.DbView is not null || ctx.Root.IsReference(target)) return; if (seen.Add(target.ResolutionKey())) queue.Enqueue(target); } } diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReferenceSourceConformanceTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReferenceSourceConformanceTests.cs new file mode 100644 index 0000000000..f883e1ca35 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/ReferenceSourceConformanceTests.cs @@ -0,0 +1,83 @@ +// Runs the shared reference-source corpus against this port. Reads the single committed +// fixtures/reference-source-conformance/cases.json — no per-port fixture. The corpus is the contract; +// see server/typescript/packages/sdk/src/memory.ts (`referenceNodesOf`) for the reference behavior. +using System.Text.Json; +using MetaObjects; +using MetaObjects.Config; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +public class ReferenceSourceConformanceTests +{ + private sealed record Case( + string Name, Dictionary Tree, string ConfigText, string[]? ExpectReference, string? ExpectLoadError); + + public static TheoryData CaseNames() + { + var data = new TheoryData(); + foreach (var c in LoadCases()) data.Add(c.Name); + return data; + } + + private static string CorpusPath() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !Directory.Exists(Path.Combine(dir.FullName, "fixtures"))) + dir = dir.Parent; + Assert.NotNull(dir); + return Path.Combine(dir!.FullName, "fixtures", "reference-source-conformance", "cases.json"); + } + + private static List LoadCases() + { + using var doc = JsonDocument.Parse(File.ReadAllText(CorpusPath())); + var cases = new List(); + foreach (var el in doc.RootElement.GetProperty("cases").EnumerateArray()) + { + var tree = new Dictionary(); + foreach (var p in el.GetProperty("tree").EnumerateObject()) tree[p.Name] = p.Value.GetString() ?? ""; + string[]? expectReference = el.TryGetProperty("expectReference", out var er) + ? er.EnumerateArray().Select(x => x.GetString()!).ToArray() : null; + string? expectLoadError = el.TryGetProperty("expectLoadError", out var ee) ? ee.GetString() : null; + cases.Add(new Case(el.GetProperty("name").GetString()!, tree, el.GetProperty("config").GetRawText(), expectReference, expectLoadError)); + } + return cases; + } + + [Theory] + [MemberData(nameof(CaseNames))] + public void LoadsReferenceSourcesAndNamesTheReferenceNodes(string name) + { + var c = LoadCases().Single(x => x.Name == name); + var root = Path.Combine(Path.GetTempPath(), "mo-ref-conf-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + foreach (var (rel, content) in c.Tree) + { + var abs = Path.Combine(root, rel.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(abs)!); + File.WriteAllText(abs, content); + } + var cfgDir = Path.Combine(root, ".metaobjects"); + Directory.CreateDirectory(cfgDir); + File.WriteAllText(Path.Combine(cfgDir, "config.json"), c.ConfigText); + + var load = MetadataLocation.Resolve(null, root).Load(); + if (c.ExpectLoadError is not null) + { + Assert.Contains(load.Errors, e => e.Code.ToString() == c.ExpectLoadError); + return; + } + Assert.Empty(load.Errors); + // EXHAUSTIVE over the loaded top-level objects: the reference predicate is true for exactly these. + var got = load.Root.Objects().Where(o => load.Root.IsReference(o)).Select(o => o.ResolutionKey()).OrderBy(x => x, StringComparer.Ordinal).ToList(); + Assert.Equal(c.ExpectReference!.OrderBy(x => x, StringComparer.Ordinal).ToList(), got); + } + finally + { + Directory.Delete(root, recursive: true); + } + } +} diff --git a/server/csharp/MetaObjects/Config/MetadataLocation.cs b/server/csharp/MetaObjects/Config/MetadataLocation.cs index ef2f0cca99..5ac1e89a29 100644 --- a/server/csharp/MetaObjects/Config/MetadataLocation.cs +++ b/server/csharp/MetaObjects/Config/MetadataLocation.cs @@ -58,6 +58,11 @@ public sealed record ResolvedMetadata( /// constructor and Deconstruct keep the signatures they had. public EnumDefaults? Enums { get; init; } + /// The absolute paths of the project's reference files ({ "path": ..., "reference": true } + /// sources), a subset of . records the nodes only they declare on + /// the root (), which every generator skips. + public IReadOnlySet? ReferenceFiles { get; init; } + /// ADR-0066 — the project's business-rules settings (rules and verify in config.json); null when no config was read. public RulesSettings? Rules { get; init; } @@ -80,6 +85,11 @@ public LoadResult Load(bool strict = false) result.Root.Api = Api ?? ApiSettings.Default; result.Root.EnumDefaults = Enums ?? EnumDefaults.Default; result.Root.Rules = Rules ?? RulesSettings.Default; + if (ReferenceFiles is { Count: > 0 } referenceFiles && result.Errors.Count == 0) + { + result.Root.ReferenceNodes = ReferenceSources.NodesOf(result.Root, referenceFiles, out var referenceRefusal); + if (referenceRefusal is not null) return result with { Errors = [referenceRefusal], State = "error" }; + } if (Imports is null) return result; result.Root.ImportScope = Imports; @@ -176,6 +186,22 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd, bool val return new ResolvedMetadata(Path.Combine(cwd, NeutralConfig.DefaultMetadataDir), defaultFiles, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, LoadProviders(cfg)) { Enums = cfg?.Enums, Rules = cfg?.Rules, Api = cfg?.Api }; } + var hasReference = specs.Any(sp => sp.ContainsKey(SourceResolver.SourceKeyReference)); + if (specs.Count > 1 && hasReference) + { + // Reference sources load through the resolved FILE list into the one root, so several + // sources are fine here; the directory is the first ordinary source (what a Files-less + // caller would have walked), and only the ordinary sources' files are the project's own. + var resolvedFiles = SourceResolver.ResolveSourceFiles(cwd, specs); + var firstOrdinary = specs.FirstOrDefault(sp => !sp.ContainsKey(SourceResolver.SourceKeyReference) && sp.ContainsKey("path")); + var dir = firstOrdinary is null ? cwd : Path.GetFullPath(Path.Combine(cwd, firstOrdinary["path"])); + return new ResolvedMetadata(dir, resolvedFiles.Select(f => f.Path).ToList(), libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, LoadProviders(cfg)) + { + Enums = cfg?.Enums, Rules = cfg?.Rules, Api = cfg?.Api, + ReferenceFiles = resolvedFiles.Where(f => f.Reference).Select(f => f.Path).ToHashSet(StringComparer.Ordinal), + }; + } + if (specs.Count > 1) { // MetaDataLoader.FromDirectory takes ONE directory; refuse rather than load @@ -189,7 +215,8 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd, bool val // Exactly one declared source. ResolveSources validates it (ERR_SOURCE_KIND_UNSUPPORTED / // ERR_SOURCE_UNRESOLVED) and returns the `_pending`-excluded file list to load. - var files = SourceResolver.ResolveSources(cwd, specs); + var sourceFiles = SourceResolver.ResolveSourceFiles(cwd, specs); + var files = sourceFiles.Select(f => f.Path).ToList(); var rawPath = specs[0]["path"]; // present: ResolveSources would have thrown otherwise var resolved = Path.IsPathRooted(rawPath) ? rawPath : Path.GetFullPath(Path.Combine(cwd, rawPath)); @@ -203,6 +230,10 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd, bool val "\"sources\" at the file's containing directory."); } - return new ResolvedMetadata(resolved, files, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, LoadProviders(cfg)) { Enums = cfg?.Enums, Rules = cfg?.Rules, Api = cfg?.Api }; + return new ResolvedMetadata(resolved, files, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, LoadProviders(cfg)) + { + Enums = cfg?.Enums, Rules = cfg?.Rules, Api = cfg?.Api, + ReferenceFiles = sourceFiles.Any(f => f.Reference) ? sourceFiles.Where(f => f.Reference).Select(f => f.Path).ToHashSet(StringComparer.Ordinal) : null, + }; } } diff --git a/server/csharp/MetaObjects/Config/NeutralConfig.cs b/server/csharp/MetaObjects/Config/NeutralConfig.cs index e9f5aefa63..2b3381c32c 100644 --- a/server/csharp/MetaObjects/Config/NeutralConfig.cs +++ b/server/csharp/MetaObjects/Config/NeutralConfig.cs @@ -301,6 +301,16 @@ private static bool ReadMigrateForeignKeyIndexes(JsonElement root) => var d = new Dictionary(); foreach (var p in s.EnumerateObject()) { + // `reference` is the one boolean key a spec may carry beside `path`: the files + // load so references resolve against them, and no generator emits what only + // they declare. Carried on the spec as the string "true" (see SourceResolver.SourceKeyReference). + if (p.Name == SourceResolver.SourceKeyReference) + { + if (p.Value.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) + throw new MetaModelException($"{path}: \"sources\" entry \"{p.Name}\" must be a boolean", ErrorCode.ERR_BAD_ATTR_VALUE); + if (p.Value.GetBoolean()) d[p.Name] = "true"; + continue; + } // Every source-spec value (`path`/`resource`/`package`) is a // string — silently stringifying a non-string (the prior // behavior) would let {"path": 123} load a directory @@ -314,7 +324,9 @@ private static bool ReadMigrateForeignKeyIndexes(JsonElement root) => d[p.Name] = value; } - if (d.Count != 1) + // Exactly one source key (path/resource/package); `reference` rides along on a path. + var keys = d.Count - (d.ContainsKey(SourceResolver.SourceKeyReference) ? 1 : 0); + if (keys != 1 || (d.ContainsKey(SourceResolver.SourceKeyReference) && !d.ContainsKey("path"))) throw new MetaModelException($"{path}: each \"sources\" entry must have exactly one key", ErrorCode.ERR_BAD_ATTR_VALUE); specs.Add(d); diff --git a/server/csharp/MetaObjects/Config/ReferenceSources.cs b/server/csharp/MetaObjects/Config/ReferenceSources.cs new file mode 100644 index 0000000000..db01cb84f7 --- /dev/null +++ b/server/csharp/MetaObjects/Config/ReferenceSources.cs @@ -0,0 +1,57 @@ +// Reference sources: `{ "path": "replies", "reference": true }` in `.metaobjects/config.json`. +// +// Behavioral contract: server/typescript/packages/sdk/src/memory.ts `referenceNodesOf` and +// fixtures/reference-source-conformance/cases.json. The files load into the SAME root as every other +// source, so a `@responseRef`, `extends` or `@objectRef` resolves against them; a top-level node is a +// reference node only when EVERY file that declares it (an overlay included) is a reference file. + +using MetaObjects.Meta; +using MetaObjects.Source; + +namespace MetaObjects.Config; + +public static class ReferenceSources +{ + /// + /// The resolution keys of the top-level nodes only declare. A + /// template.* among them is refused (): a + /// reference source holds shapes another run generates, so a prompt there would have its parser and + /// payload type generated by nobody. Returns the refusal in . + /// + public static IReadOnlySet NodesOf(MetaRoot root, IReadOnlySet referenceFiles, out MetaError? refusal) + { + refusal = null; + var ids = referenceFiles.Select(Normalize).ToHashSet(StringComparer.Ordinal); + var nodes = new HashSet(StringComparer.Ordinal); + // ADR-0039: own — the metadata root has no super chain, so its own children are its nodes. + foreach (var node in root.OwnChildren()) + { + var files = FilesOf(node.Source); + if (files.Count == 0 || !files.All(f => ids.Contains(Normalize(f)))) continue; + if (node.Type == MetaObjects.Shared.BaseTypes.TYPE_TEMPLATE) + { + refusal ??= new MetaError( + $"template \"{node.ResolutionKey()}\" is declared only in a reference source ({string.Join(", ", files)}). " + + "A reference source holds shapes another run generates; declare the prompt in one of the " + + "project's own sources, where its parser and payload are generated.", + ErrorCode.ERR_REFERENCE_SOURCE_TEMPLATE); + continue; + } + nodes.Add(node.ResolutionKey()); + } + return nodes; + } + + /// Every file in a node's provenance, every overlay contributor included. + private static IReadOnlyList FilesOf(ErrorSource source) => source switch + { + MergedSource m => m.Files.Concat(m.Contributors.Select(c => c.File)).Distinct().ToList(), + JsonSource j => j.Files, + YamlSource y => y.Files, + _ => [], + }; + + /// A source id may be a file URI or a path; compare them as full local paths. + private static string Normalize(string id) => + Uri.TryCreate(id, UriKind.Absolute, out var uri) && uri.IsFile ? Path.GetFullPath(uri.LocalPath) : id; +} diff --git a/server/csharp/MetaObjects/Config/SourceResolver.cs b/server/csharp/MetaObjects/Config/SourceResolver.cs index f1cc4c1fa5..ac6d05c8f8 100644 --- a/server/csharp/MetaObjects/Config/SourceResolver.cs +++ b/server/csharp/MetaObjects/Config/SourceResolver.cs @@ -11,8 +11,15 @@ namespace MetaObjects.Config; +/// One resolved metadata file; when every spec reaching it is a reference source. +public sealed record ResolvedSourceFile(string Path, bool Reference); + public static class SourceResolver { + /// The boolean key a path source may carry: { "path": "replies", "reference": true }. + /// Held on the spec dictionary as the string "true" (a false value is dropped at read time). + public const string SourceKeyReference = "reference"; + /// Resolve a declared source SET to a de-duplicated list of metadata files. /// A relative `path` resolves against `configDir` — the directory HOLDING the /// `.metaobjects/` folder — never against the process working directory. @@ -32,14 +39,21 @@ public static class SourceResolver public static IReadOnlyList ResolveSources( string configDir, IReadOnlyList> specs) + => ResolveSourceFiles(configDir, specs).Select(f => f.Path).ToList(); + + /// that also says which files are reference files: a file is + /// one only when EVERY spec reaching it is a reference spec (an ordinary spec wins). + public static IReadOnlyList ResolveSourceFiles( + string configDir, + IReadOnlyList> specs) { // Pass 1 — kind validation across the WHOLE set, no filesystem I/O yet. - var pathSpecs = new List(specs.Count); + var pathSpecs = new List<(string Path, bool Reference)>(specs.Count); foreach (var spec in specs) { if (spec.TryGetValue("path", out var rawPath)) { - pathSpecs.Add(rawPath); + pathSpecs.Add((rawPath, spec.ContainsKey(SourceKeyReference))); } else { @@ -57,13 +71,18 @@ public static IReadOnlyList ResolveSources( // order-independent); only decides which declared path's // `ERR_SOURCE_UNRESOLVED` fires first when more than one is // simultaneously unresolvable. - pathSpecs.Sort(StringComparer.Ordinal); + pathSpecs.Sort((a, b) => + { + var c = StringComparer.Ordinal.Compare(a.Path, b.Path); + return c != 0 ? c : a.Reference.CompareTo(b.Reference); + }); // Pass 2 — resolve each validated path spec against the filesystem. var seen = new List(); var known = new HashSet(StringComparer.Ordinal); + var ordinary = new HashSet(StringComparer.Ordinal); - foreach (var rawPath in pathSpecs) + foreach (var (rawPath, isReference) in pathSpecs) { var target = Path.IsPathRooted(rawPath) ? rawPath : Path.GetFullPath(Path.Combine(configDir, rawPath)); @@ -94,16 +113,21 @@ public static IReadOnlyList ResolveSources( { var full = Path.GetFullPath(f); if (known.Add(full)) seen.Add(full); + if (!isReference) ordinary.Add(full); } } - return seen; + return seen.Select(f => new ResolvedSourceFile(f, !ordinary.Contains(f))).ToList(); } /// The full ladder: declared `sources`, else the default directory. /// Only the DEFAULT may be silently absent — a declared source that does not /// resolve is `ERR_SOURCE_UNRESOLVED`, a louder failure than "nothing declared". public static IReadOnlyList ResolveCollection(string root) + => ResolveCollectionFiles(root).Select(f => f.Path).ToList(); + + /// with each file's reference flag. + public static IReadOnlyList ResolveCollectionFiles(string root) { root = Path.GetFullPath(root); // Only `sources` is read here; `naming` is the caller's to check (MetadataLocation reads @@ -125,6 +149,6 @@ public static IReadOnlyList ResolveCollection(string root) }; } - return ResolveSources(root, specs); + return ResolveSourceFiles(root, specs); } } diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index ca72657be3..2d340e59e8 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -150,6 +150,8 @@ public enum ErrorCode ERR_SOURCE_UNRESOLVED, // Phase-1 metadata-source-resolution: a declared source kind (resource or package) is not supported by this toolchain. ERR_SOURCE_KIND_UNSUPPORTED, + // A template.* is declared only in reference sources (`{ "path": ..., "reference": true }`): its parser and payload would be generated by nobody. + ERR_REFERENCE_SOURCE_TEMPLATE, // Phase-1 metadata-source-resolution: a scope include/exclude package pattern is malformed (empty pattern or empty :: segment). ERR_SCOPE_PATTERN_INVALID, // Phase-1 metadata-source-resolution: no metadata collection was discovered — no config declaring sources, and no default metaobjects/ directory. diff --git a/server/csharp/MetaObjects/Meta/MetaRoot.cs b/server/csharp/MetaObjects/Meta/MetaRoot.cs index f7280534fe..e9a9d2a6f0 100644 --- a/server/csharp/MetaObjects/Meta/MetaRoot.cs +++ b/server/csharp/MetaObjects/Meta/MetaRoot.cs @@ -57,7 +57,18 @@ public class MetaRoot(TypeId typeId, string name) : MetaData(typeId, name) /// ledger's denominator)? False for an object a dependency owns, unless the project's /// scope.include names its package. Always true when nothing is imported. /// - public bool InScope(MetaObject obj) => ImportScope?.InScope(obj.ResolutionKey()) ?? true; + public bool InScope(MetaObject obj) => !IsReference(obj) && (ImportScope?.InScope(obj.ResolutionKey()) ?? true); + + /// + /// The resolution keys of the top-level nodes only REFERENCE sources declare + /// ({ "path": ..., "reference": true } in .metaobjects/config.json). They load and resolve + /// like any node, and no generator emits them: another run owns them. Set by the project-aware load; + /// empty for a tree loaded with no reference source. + /// + public IReadOnlySet ReferenceNodes { get; set; } = new HashSet(StringComparer.Ordinal); + + /// Is a reference node ()? + public bool IsReference(MetaData obj) => ReferenceNodes.Count > 0 && ReferenceNodes.Contains(obj.ResolutionKey()); /// Object entities defined at this root level. public IReadOnlyList Objects() diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratorUtil.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratorUtil.java index 21d731e014..04ca5d8533 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratorUtil.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratorUtil.java @@ -31,11 +31,16 @@ public static Collection getFilteredMetaData(MetaDataLoader loader, Me * another project's to generate: a generator emits nothing for it, exactly as the TypeScript * and Python selection points do. False for anything that is not an object, and for every tree * loaded without dependencies. + * + *

Also true for a REFERENCE node: one declared only by sources the project marks + * {@code "reference": true}. It loads and resolves, but another run generates it.

*/ public static boolean isImported(MetaData md) { if (!(md instanceof MetaObject)) return false; MetaDataLoader loader = md.getLoader(); if (loader == null) return false; + // A reference node (declared only by `reference` sources) is another run's to generate. + if (loader.getRoot().getReferenceNodes().contains(md.getName())) return true; com.metaobjects.config.DependencySet deps = loader.getRoot().getDependencySet(); return !deps.isEmpty() && !deps.inScope(md.getName()); } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/verify/TemplateVerify.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/verify/TemplateVerify.java index 0b251ed6c7..2f1ec0e297 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/verify/TemplateVerify.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/verify/TemplateVerify.java @@ -67,6 +67,19 @@ private TemplateVerify() { /* no instances */ } */ public static final String ERR_PAYLOAD_REF_UNRESOLVED = "ERR_PAYLOAD_REF_UNRESOLVED"; + /** A responding prompt's {@code @responseRef} names no loaded value shape with fields (an error). */ + public static final String ERR_RESPONSE_UNRESOLVED = "ERR_RESPONSE_UNRESOLVED"; + + /** + * An xml prompt's {@code @requiredTags} entry names neither the reply type nor one of its + * fields (a warning): the body teaches the model the tag and the extractor reads the reply + * type's fields, so a renamed reply field stops matching a tag the prompt still asks for. + */ + public static final String ERR_RESPONSE_TAG_UNDECLARED = "ERR_RESPONSE_TAG_UNDECLARED"; + + /** One reply finding: the code, the {@code @responseRef} value or offending tag, and whether it is a warning. */ + public record ResponseFinding(String code, String path, boolean warning) {} + /** A single drift finding: which template, prompt-vs-output, the error code, the path. */ public record Drift(String template, String kind, String code, String path) {} @@ -101,6 +114,14 @@ public static Outcome run(MetaDataLoader loader, Path templateRoot) { for (com.metaobjects.MetaData child : loader.getRoot().getChildren()) { if (!(child instanceof MetaTemplate tmpl)) continue; + // The reply (@responseRef): its field tree, and an xml prompt's tag contract against it. + // Independent of the payload check below, so it runs first. + for (ResponseFinding f : responseFindings(loader, tmpl)) { + Drift drift = new Drift(tmpl.getName(), KIND_PROMPT, f.code(), f.path()); + if (f.warning()) warnings.add(drift); + else errors.add(drift); + } + String payloadRef = tmpl.getPayloadRef(); // Missing @payloadRef is already a load-time error (prompt schema requires it). if (payloadRef == null || payloadRef.isEmpty()) continue; @@ -179,6 +200,49 @@ public static Outcome run(MetaDataLoader loader, Path templateRoot) { return new Outcome(errors, warnings, unresolved); } + /** + * The reply findings for one template, matching {@code response-verify.ts} (pinned by + * {@code fixtures/response-verify-conformance}). Empty for anything that is not a + * {@code template.prompt} carrying {@code @responseRef} — a prompt that elicits no typed reply + * has nothing here. Every read is the resolving one (ADR-0039): a prompt may inherit + * {@code @responseRef}, {@code @responseFormat} and {@code @requiredTags} via {@code extends}. + */ + public static List responseFindings(MetaDataLoader loader, MetaTemplate tmpl) { + if (!TemplateConstants.SUBTYPE_PROMPT.equals(tmpl.getSubType())) return List.of(); + String responseRef = attrString(tmpl, TemplateConstants.ATTR_RESPONSE_REF); + if (responseRef == null) return List.of(); + + MetaObject reply = valueObjectOrNull(References.refTarget(tmpl, TemplateConstants.ATTR_RESPONSE_REF)); + List tree = reply == null + ? List.of() + : derivePayloadFieldTree(loader, reply, new LinkedHashSet<>()); + if (tree.isEmpty()) { + return List.of(new ResponseFinding(ERR_RESPONSE_UNRESOLVED, responseRef, false)); + } + + String format = attrString(tmpl, TemplateConstants.ATTR_RESPONSE_FORMAT); + if (format == null || !TemplateConstants.RESPONSE_FORMAT_XML.equals(format.toLowerCase(java.util.Locale.ROOT))) { + return List.of(); + } + List tags = tmpl.getRequiredTags(); + if (tags == null) return List.of(); + Set known = new LinkedHashSet<>(); + known.add(reply.getShortName()); + collectFieldNames(tree, known); + List out = new ArrayList<>(); + for (String tag : tags) { + if (!known.contains(tag)) out.add(new ResponseFinding(ERR_RESPONSE_TAG_UNDECLARED, tag, true)); + } + return out; + } + + private static void collectFieldNames(List tree, Set out) { + for (PayloadField f : tree) { + out.add(f.name()); + if (f.fields() != null) collectFieldNames(f.fields(), out); + } + } + // ------------------------------------------------------------------------- // Payload field-tree walk — mirrors SpringRenderHelperGenerator.derivePayloadFieldTree // (object-ref fields recurse; a `seen` set guards reference cycles; bare-shortname diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/verify/ResponseVerifyConformanceTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/verify/ResponseVerifyConformanceTest.java new file mode 100644 index 0000000000..a694fde738 --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/verify/ResponseVerifyConformanceTest.java @@ -0,0 +1,106 @@ +package com.metaobjects.generator.verify; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.MetaData; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.loader.uri.URIHelper; +import com.metaobjects.registry.SharedRegistryTestBase; +import com.metaobjects.template.MetaTemplate; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Runs the shared reply-check corpus ({@code fixtures/response-verify-conformance/cases.json}) + * against this port: what {@code metaobjects:verify mode=templates} reports about each prompt's + * {@code @responseRef}. {@code expect} is the exhaustive finding list for the case's templates. + */ +@RunWith(Parameterized.class) +public class ResponseVerifyConformanceTest extends SharedRegistryTestBase { + + private record Case(String name, String metadata, List expect) {} + + @Parameters(name = "{0}") + public static Collection cases() throws IOException { + Path dir = Paths.get("").toAbsolutePath(); + while (dir != null && !Files.isDirectory(dir.resolve("fixtures"))) dir = dir.getParent(); + assertNotNull("could not locate the repository fixtures/ directory", dir); + Path corpus = dir.resolve("fixtures/response-verify-conformance/cases.json"); + JsonArray arr = JsonParser.parseString(Files.readString(corpus, StandardCharsets.UTF_8)) + .getAsJsonObject().getAsJsonArray("cases"); + List rows = new ArrayList<>(); + for (JsonElement el : arr) { + JsonObject c = el.getAsJsonObject(); + List expect = new ArrayList<>(); + for (JsonElement f : c.getAsJsonArray("expect")) { + JsonObject o = f.getAsJsonObject(); + expect.add(o.get("template").getAsString() + "|" + o.get("code").getAsString() + "|" + + o.get("path").getAsString() + "|" + o.get("severity").getAsString()); + } + expect.sort(String::compareTo); + String name = c.get("name").getAsString(); + rows.add(new Object[]{name, new Case(name, c.get("metadata").toString(), expect)}); + } + return rows; + } + + @Parameter(0) + public String caseName; + + @Parameter(1) + public Case testCase; + + @Test + public void reportsTheSameReplyFindings() throws Exception { + Path tmp = Files.createTempDirectory("mo-reply-verify-"); + try { + Path file = tmp.resolve("meta.json"); + Files.writeString(file, testCase.metadata(), StandardCharsets.UTF_8); + List uris = List.of(URIHelper.toURI("model:file:" + file.toAbsolutePath().toString().replace('\\', '/'))); + MetaDataLoader loader = new MetaDataLoader( + LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "reply-" + testCase.name()); + loader.setSourceURIs(uris); + loader.init(); + + List got = new ArrayList<>(); + for (MetaData child : loader.getRoot().getChildren()) { + if (!(child instanceof MetaTemplate tmpl)) continue; + for (TemplateVerify.ResponseFinding f : TemplateVerify.responseFindings(loader, tmpl)) { + got.add(tmpl.getShortName() + "|" + f.code() + "|" + f.path() + "|" + + (f.warning() ? "warning" : "error")); + } + } + got.sort(String::compareTo); + assertEquals(testCase.expect(), got); + } finally { + try (var walk = Files.walk(tmp)) { + walk.sorted(java.util.Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); + } + } + } + + @Test + public void corpusIsNotEmpty() throws Exception { + assertTrue(cases().size() > 0); + } +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinReferenceSourceExclusionTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinReferenceSourceExclusionTest.kt new file mode 100644 index 0000000000..2d7fa737f3 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinReferenceSourceExclusionTest.kt @@ -0,0 +1,100 @@ +package com.metaobjects.generator.kotlin + +import com.google.gson.JsonParser +import com.metaobjects.config.SourceResolver +import com.metaobjects.generator.Generator +import com.metaobjects.generator.util.GeneratedFileWriter +import com.metaobjects.loader.FileSource +import com.metaobjects.loader.LoaderOptions +import com.metaobjects.loader.MetaDataLoader +import com.metaobjects.loader.MetaDataSource +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * A node declared only by a REFERENCE source (`{"path": ..., "reference": true}`) loads and resolves + * but is another run's to generate: no Kotlin generator writes a data class for it (nor for a reference + * value object it nests), while the output parser of a LOCAL prompt whose `@responseRef` names it still + * emits. The project is the shared `fixtures/reference-source-conformance` corpus case the other ports load. + */ +class KotlinReferenceSourceExclusionTest { + + private val caseName = "reply-type-in-a-reference-source-resolves-and-is-not-generated" + private val referenceIdPrefix = "ref:" + + private fun corpus(): Path { + var dir: Path? = Paths.get("").toAbsolutePath() + while (dir != null && !Files.isDirectory(dir.resolve("fixtures"))) dir = dir.parent + return dir!!.resolve("fixtures/reference-source-conformance/cases.json") + } + + @Test fun `no Kotlin generator emits for a reference node but the parser still names it`() { + val project = Files.createTempDirectory("kref-project-") + val outDir = Files.createTempDirectory("kref-out-") + try { + val case = JsonParser.parseString(Files.readString(corpus())) + .asJsonObject.getAsJsonArray("cases") + .map { it.asJsonObject }.first { it["name"].asString == caseName } + for ((k, v) in case.getAsJsonObject("tree").entrySet()) { + val p = project.resolve(k) + Files.createDirectories(p.parent) + Files.write(p, v.asString.toByteArray()) + } + val cfg = project.resolve(".metaobjects/config.json") + Files.createDirectories(cfg.parent) + Files.write(cfg, case.getAsJsonObject("config").toString().toByteArray()) + + val collection = SourceResolver.resolveCollectionWithDependencies(project) + val sources = ArrayList() + val referenceIds = HashSet() + for (file in collection.ownFiles()) { + if (collection.referenceFiles().contains(file)) { + val id = referenceIdPrefix + project.relativize(file).toString().replace('\\', '/') + referenceIds.add(id) + sources.add(FileSource(file, id)) + } else { + sources.add(FileSource(file)) + } + } + val loader = MetaDataLoader(LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "kref") + loader.init() + loader.setReferenceSourceIds(referenceIds) + loader.load(sources) + assertEquals(setOf("acme::support::SupportAnswer", "acme::support::AnswerSource"), + loader.root.referenceNodes) + + val generators: List = listOf( + KotlinEntityGenerator(), KotlinExposedTableGenerator(), KotlinRelationsGenerator(), + KotlinRepositoryGenerator(), KotlinNamesGenerator(), KotlinFilterAllowlistGenerator(), + KotlinSpringControllerGenerator(), KotlinReportExportGenerator(), + KotlinStoredProcGenerator(), KotlinExtractorGenerator(), KotlinOutputParserGenerator(), + ) + GeneratedFileWriter.beginRun().use { run -> + for (gen in generators) { + run.attributeTo(gen.javaClass.simpleName) + gen.setArgs(mapOf("outputDir" to outDir.toString(), "packageName" to "demo")).execute(loader) + } + } + + val files = Files.walk(outDir).use { s -> s.filter { Files.isRegularFile(it) }.toList() } + val names = files.map { outDir.relativize(it).toString() } + assertTrue(names.any { it.endsWith("SupportRequest.kt") }, "the project's own payload still generates: $names") + for (n in names) { + assertFalse(n.endsWith("/SupportAnswer.kt") || n.endsWith("/AnswerSource.kt"), + "a file was emitted for a reference node: $n") + } + val parser = files.firstOrNull { it.fileName.toString().endsWith("SupportAnswerPromptParser.kt") } + assertTrue(parser != null, "the local prompt's parser must still emit: $names") + assertTrue("acme.support.SupportAnswer" in Files.readString(parser!!), + "the parser names the reference reply type") + } finally { + project.toFile().deleteRecursively() + outDir.toFile().deleteRecursively() + } + } +} diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReferenceSourceExclusionTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReferenceSourceExclusionTest.java new file mode 100644 index 0000000000..9fe1ee77ef --- /dev/null +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReferenceSourceExclusionTest.java @@ -0,0 +1,128 @@ +package com.metaobjects.generator.spring; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.config.SourceResolver; +import com.metaobjects.generator.Generator; +import com.metaobjects.generator.util.GeneratedFileWriter; +import com.metaobjects.loader.FileSource; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.loader.MetaDataSource; +import com.metaobjects.registry.SharedRegistryTestBase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * A node declared only by a REFERENCE source ({@code {"path": ..., "reference": true}}) loads and + * resolves but is another run's to generate: no value-object record is written for it (nor for a + * reference value object it nests), while the output parser of a LOCAL prompt whose + * {@code @responseRef} names it still emits, naming the reply type the owning run generates. The + * project and its sources come from the shared {@code fixtures/reference-source-conformance} corpus. + */ +public class ReferenceSourceExclusionTest extends SharedRegistryTestBase { + + private static final String CASE = "reply-type-in-a-reference-source-resolves-and-is-not-generated"; + private static final String REFERENCE_ID_PREFIX = "ref:"; + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + private static Path corpus() { + Path dir = Paths.get("").toAbsolutePath(); + while (dir != null && !Files.isDirectory(dir.resolve("fixtures"))) dir = dir.getParent(); + return dir.resolve("fixtures/reference-source-conformance/cases.json"); + } + + private Path materialize() throws Exception { + JsonObject all = JsonParser.parseString(Files.readString(corpus(), StandardCharsets.UTF_8)).getAsJsonObject(); + JsonObject c = null; + for (JsonElement el : all.getAsJsonArray("cases")) { + if (CASE.equals(el.getAsJsonObject().get("name").getAsString())) c = el.getAsJsonObject(); + } + assertTrue("corpus case missing: " + CASE, c != null); + Path root = tempFolder.newFolder("project").toPath(); + for (Map.Entry e : c.getAsJsonObject("tree").entrySet()) { + Path p = root.resolve(e.getKey()); + Files.createDirectories(p.getParent()); + Files.writeString(p, e.getValue().getAsString(), StandardCharsets.UTF_8); + } + Path cfg = root.resolve(".metaobjects/config.json"); + Files.createDirectories(cfg.getParent()); + Files.writeString(cfg, c.getAsJsonObject("config").toString(), StandardCharsets.UTF_8); + return root; + } + + @Test + public void noGeneratorEmitsForAReferenceNodeButTheParserStillNamesIt() throws Exception { + Path root = materialize(); + SourceResolver.ResolvedCollection collection = SourceResolver.resolveCollectionWithDependencies(root); + List sources = new ArrayList<>(); + Set referenceIds = new TreeSet<>(); + for (Path file : collection.ownFiles()) { + String rel = root.relativize(file).toString().replace('\\', '/'); + if (collection.referenceFiles().contains(file)) { + referenceIds.add(REFERENCE_ID_PREFIX + rel); + sources.add(new FileSource(file, REFERENCE_ID_PREFIX + rel)); + } else { + sources.add(new FileSource(file)); + } + } + MetaDataLoader loader = new MetaDataLoader( + LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "reference-exclusion"); + loader.init(); + loader.setReferenceSourceIds(referenceIds); + loader.load(sources); + assertTrue("loader errors: " + loader.getErrors(), loader.getErrors().isEmpty()); + assertEquals(Set.of("acme::support::SupportAnswer", "acme::support::AnswerSource"), + loader.getRoot().getReferenceNodes()); + + Path outDir = tempFolder.newFolder("gen").toPath(); + List generators = List.of( + new SpringValueObjectGenerator(), new SpringDtoGenerator(), new SpringRepositoryGenerator(), + new SpringNamesGenerator(), new SpringControllerGenerator(), + new SpringOutputParserGenerator(), new SpringOutputPromptGenerator()); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + for (Generator gen : generators) { + run.attributeTo(gen.getClass().getSimpleName()); + gen.setArgs(Map.of("outputDir", outDir.toString(), "type", "class", "flavor", "pojoAware")) + .execute(loader); + } + } + + List files; + try (Stream s = Files.walk(outDir)) { + files = s.filter(Files::isRegularFile).map(p -> outDir.relativize(p).toString()).sorted() + .collect(Collectors.toList()); + } + assertTrue("the project's own payload record still generates: " + files, + files.contains("acme/support/SupportRequest.java")); + for (String f : files) { + assertFalse("a file was emitted for a reference node: " + f, + f.endsWith("/SupportAnswer.java") || f.endsWith("/AnswerSource.java")); + } + String parserPath = files.stream().filter(f -> f.endsWith("SupportAnswerPromptParser.java")).findFirst() + .orElseThrow(() -> new AssertionError("the local prompt's parser must still emit: " + files)); + String parser = Files.readString(outDir.resolve(parserPath), StandardCharsets.UTF_8); + assertTrue("the parser names the reference reply type: " + parser, + parser.contains("acme.support.SupportAnswer")); + } +} diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java index 496915ea46..a7016f6fae 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java @@ -795,7 +795,8 @@ protected List fingerprintBaseInputs() throws java.io.IOEx LoaderParam lp = getLoader(); in.add(config("loader", String.join("|", String.valueOf(lp.getClassname()), String.valueOf(lp.getName()), String.valueOf(lp.getSourceDir()), String.valueOf(lp.getSources()), - String.valueOf(lp.getLibraries()), String.valueOf(lp.getFilters())))); + String.valueOf(lp.getLibraries()), String.valueOf(lp.getFilters()), + String.valueOf(lp.getReferenceSources())))); in.add(config("strict", String.valueOf(!lax))); in.add(config("globals", new java.util.TreeMap<>(globals == null ? Map.of() : globals).toString())); if ( getGenerators() != null ) { @@ -1078,6 +1079,14 @@ protected MetaDataLoader createLoader(ClassLoader projectClassLoader) { // , fall back to the port-neutral .metaobjects/config.json (else the // built-in default directory) instead of silently loading nothing. List sources = loaderConfig.getSources(); + // Reference sources: the pom's when it names any, else (when the pom + // names no location) the `reference: true` entries of the neutral config. They load into + // the same model but no generator emits a node only they declare. A pom naming only + // still takes its ordinary sources from the ladder below. + List pomReferenceSources = loaderConfig.getReferenceSources(); + List referenceSources = pomReferenceSources != null && !pomReferenceSources.isEmpty() + ? pomReferenceSources + : resolveNeutralReferenceSourcesIfPomIsSilent(loaderConfig); List neutralSources = resolveNeutralSourcesIfPomIsSilent(loaderConfig); if (!neutralSources.isEmpty()) { sources = neutralSources; @@ -1136,7 +1145,7 @@ protected MetaDataLoader createLoader(ClassLoader projectClassLoader) { resolveProjectConfigDir(srcDir).orElse(getProjectBaseDir().toPath().toAbsolutePath().normalize())); MavenLoaderConfiguration.configure(configurable, sourceDir, projectClassLoader, - sources, libraries, dependencies, loaderArgs(strict)); + sources, referenceSources, libraries, dependencies, loaderArgs(strict)); MetaDataLoader loader = configurable.getLoader(); @@ -1498,6 +1507,22 @@ protected List expandSourceDir(File srcDir) { } protected List resolveNeutralSourcesIfPomIsSilent(LoaderParam loaderConfig) { + return neutralSourcesIfPomIsSilent(loaderConfig, false); + } + + /** + * The files of the neutral config's {@code reference: true} sources, in the same + * {@code model:file:} form as {@link #resolveNeutralSourcesIfPomIsSilent}; empty when the pom + * names a location (it then owns the whole concern) or the config declares none. + */ + protected List resolveNeutralReferenceSourcesIfPomIsSilent(LoaderParam loaderConfig) { + return neutralSourcesIfPomIsSilent(loaderConfig, true); + } + + /** The resolved neutral collection, once per mojo run (both source lists read it). */ + private com.metaobjects.config.SourceResolver.ResolvedFiles neutralFiles; + + private List neutralSourcesIfPomIsSilent(LoaderParam loaderConfig, boolean reference) { boolean pomNamesLocation = (loaderConfig.getSourceDir() != null && !loaderConfig.getSourceDir().isBlank()) || (loaderConfig.getSources() != null && !loaderConfig.getSources().isEmpty()); @@ -1512,9 +1537,12 @@ protected List resolveNeutralSourcesIfPomIsSilent(LoaderParam loaderConf // paths (SourceResolver.resolveCollection), so there is nothing to sniff: // say "file" outright, the same shape processSources itself already builds // for its own `new File(s).exists()` branch. - return com.metaobjects.config.SourceResolver - .resolveCollection(getProjectBaseDir().toPath()) - .stream() + if (neutralFiles == null) { + neutralFiles = com.metaobjects.config.SourceResolver.resolveCollectionFiles(getProjectBaseDir().toPath()); + } + com.metaobjects.config.SourceResolver.ResolvedFiles resolved = neutralFiles; + return resolved.files().stream() + .filter(p -> resolved.reference().contains(p) == reference) .map(p -> "model:file:" + p.toString().replace(java.io.File.separatorChar, '/')) .toList(); } diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/LoaderParam.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/LoaderParam.java index 3145fddf06..514340431a 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/LoaderParam.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/LoaderParam.java @@ -14,6 +14,7 @@ public class LoaderParam { private String classname = null; private String sourceDir = null; private List sources = null; + private List referenceSources = null; private List libraries = null; private List filters = null; @@ -110,6 +111,26 @@ public void setSources(List sources) { this.sources = sources; } + /** + * Reference sources — {@code …}: metadata + * files resolved like {@link #getSources()} that load into the same model (so {@code @responseRef}, + * {@code extends} and {@code @objectRef} resolve against them) but that no generator emits when + * only they declare a node. Another run owns those nodes' generated types. + * + * @return the reference source paths, or null if not set + */ + public List getReferenceSources() { + return referenceSources; + } + + /** + * Set the reference sources. + * @param referenceSources reference source file paths + */ + public void setReferenceSources(List referenceSources) { + this.referenceSources = referenceSources; + } + /** * Get the list of filters to apply during loading * @return List of filters, or null if not set diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MavenLoaderConfiguration.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MavenLoaderConfiguration.java index 46cbfdb252..68948f8663 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MavenLoaderConfiguration.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MavenLoaderConfiguration.java @@ -78,6 +78,24 @@ public static void configure(LoaderConfigurable configurable, List libraries, com.metaobjects.config.DependencySet dependencies, Map globals) { + configure(configurable, sourceDir, classLoader, sources, null, libraries, dependencies, globals); + } + + /** + * {@link #configure(LoaderConfigurable, String, ClassLoader, List, List, com.metaobjects.config.DependencySet, Map)} + * with reference sources: files that load into the same model but whose nodes only they declare + * no generator emits. + * + * @param referenceSources reference source paths, resolved like {@code sources}; may be null + */ + public static void configure(LoaderConfigurable configurable, + String sourceDir, + ClassLoader classLoader, + List sources, + List referenceSources, + List libraries, + com.metaobjects.config.DependencySet dependencies, + Map globals) { // Trigger lazy initialization of ServiceLoader type discovery @@ -91,6 +109,7 @@ public static void configure(LoaderConfigurable configurable, .sourceDir(sourceDir) .classLoader(classLoader) .sources(sources) + .referenceSources(referenceSources) .libraries(libraries) .dependencies(dependencies) .arguments(globals) diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MavenLoaderReferenceSourcesTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MavenLoaderReferenceSourcesTest.java new file mode 100644 index 0000000000..1fc1c33aeb --- /dev/null +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/MavenLoaderReferenceSourcesTest.java @@ -0,0 +1,88 @@ +package com.metaobjects.mojo; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.MetaDataException; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** + * The production build-time path for {@code }: the same + * {@link MavenLoaderConfiguration#configure} + {@link MetaDataLoader#configure} sequence + * {@code AbstractMetaDataMojo.createLoader} runs. The reference files load into the one model, the + * nodes only they declare are the reference nodes, and a template declared only there is refused. + * The tree is the shared {@code fixtures/reference-source-conformance} corpus. + */ +public class MavenLoaderReferenceSourcesTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private static Path corpus() { + Path dir = Paths.get("").toAbsolutePath(); + while (dir != null && !Files.isDirectory(dir.resolve("fixtures"))) dir = dir.getParent(); + return dir.resolve("fixtures/reference-source-conformance/cases.json"); + } + + private Path project(String caseName) throws Exception { + JsonObject all = JsonParser.parseString(Files.readString(corpus(), StandardCharsets.UTF_8)).getAsJsonObject(); + JsonObject c = null; + for (JsonElement el : all.getAsJsonArray("cases")) { + if (caseName.equals(el.getAsJsonObject().get("name").getAsString())) c = el.getAsJsonObject(); + } + assertTrue("corpus case missing: " + caseName, c != null); + Path root = tmp.newFolder().toPath(); + for (Map.Entry e : c.getAsJsonObject("tree").entrySet()) { + Path p = root.resolve(e.getKey()); + Files.createDirectories(p.getParent()); + Files.writeString(p, e.getValue().getAsString(), StandardCharsets.UTF_8); + } + return root; + } + + private static MetaDataLoader load(Path root) { + MetaDataLoader loader = new MetaDataLoader( + LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "mojo-reference"); + MavenLoaderConfiguration.configure(loader, null, MavenLoaderReferenceSourcesTest.class.getClassLoader(), + List.of(root.resolve("model/meta.prompts.json").toString()), + List.of(root.resolve("replies/meta.replies.json").toString()), + null, null, Map.of()); + return loader; + } + + @Test + public void referenceSourcesLoadIntoTheModelAndTheirNodesAreReferenceNodes() throws Exception { + MetaDataLoader loader = load(project("reply-type-in-a-reference-source-resolves-and-is-not-generated")); + assertTrue("loader errors: " + loader.getErrors(), loader.getErrors().isEmpty()); + assertEquals(Set.of("acme::support::SupportAnswer", "acme::support::AnswerSource"), + loader.getRoot().getReferenceNodes()); + } + + @Test + public void aTemplateDeclaredOnlyInAReferenceSourceIsRefused() throws Exception { + Path project = project("a-template-in-a-reference-source-is-refused"); + // Refused by the load itself, so every Java entry point refuses it; init() may wrap it. + Throwable t = assertThrows(RuntimeException.class, () -> load(project)); + String code = ""; + for (; t != null; t = t.getCause()) { + if (t instanceof MetaDataException m && m.getCode().isPresent()) { code = m.getCode().get().name(); break; } + } + assertEquals("ERR_REFERENCE_SOURCE_TEMPLATE", code); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java index 6ac72efaf7..6e41b4c17d 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java +++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java @@ -392,6 +392,13 @@ public enum ErrorCode { /** FR-023: a local top-level node is declared into a package owned by a dependency. */ ERR_DEPENDENCY_PACKAGE_NOT_OWNED, + /** + * A {@code template.*} is declared only in reference sources + * ({@code {"path": ..., "reference": true}}): its parser and payload type would be generated + * by nobody, so the load refuses it. + */ + ERR_REFERENCE_SOURCE_TEMPLATE, + /** FR-023: a dependency's {@code metamodelVersion} major differs from this toolchain's. */ ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE, diff --git a/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java b/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java index 7b817b6e8b..6cdeb08e3d 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java +++ b/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java @@ -291,6 +291,23 @@ public void setDependencySet(com.metaobjects.config.DependencySet dependencySet) this.dependencySet = (dependencySet != null) ? dependencySet : com.metaobjects.config.DependencySet.EMPTY; } + /** + * The resolution keys (FQNs) of the top-level nodes only REFERENCE sources declare + * ({@code {"path": ..., "reference": true}}). They load and resolve like any other node; no + * generator emits them, because another run owns them. Set by the project-aware load. + */ + private transient java.util.Set referenceNodes = java.util.Set.of(); + + /** The reference nodes of this tree; empty when no reference source was loaded. Never {@code null}. */ + public java.util.Set getReferenceNodes() { + return referenceNodes; + } + + /** Sets the reference nodes ({@code null} restores the empty set). */ + public void setReferenceNodes(java.util.Set referenceNodes) { + this.referenceNodes = (referenceNodes != null) ? java.util.Set.copyOf(referenceNodes) : java.util.Set.of(); + } + /** * Returns all {@code object} children of this root node. * diff --git a/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java b/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java index f3d233c7c8..9c21da9a1c 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java +++ b/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java @@ -63,6 +63,10 @@ public final class NeutralConfig { */ public static final String DEFAULT_METADATA_DIR = "metaobjects"; + /** The {@code sources} key naming a path source, and the boolean modifier that makes it a reference source. */ + public static final String SOURCE_KEY_PATH = "path"; + public static final String SOURCE_KEY_REFERENCE = "reference"; + private static final String METAOBJECTS_DIR = ".metaobjects"; private static final String CONFIG_FILE = "config.json"; private static final int SUPPORTED_SCHEMA_VERSION = 1; @@ -93,7 +97,8 @@ private NeutralConfig(List> sources, List> getSources() { return sources; @@ -292,13 +297,29 @@ public static NeutralConfig parse(String content, String origin) { ErrorCode.ERR_BAD_ATTR_VALUE); } JsonObject entry = el.getAsJsonObject(); - if (entry.size() != 1) { + // `reference` is a modifier on a path source, not a kind of its own: it does not + // count toward "exactly one key", and it must be a JSON boolean. + JsonElement reference = entry.get(SOURCE_KEY_REFERENCE); + if (reference != null + && !(reference.isJsonPrimitive() && reference.getAsJsonPrimitive().isBoolean())) { + throw new MetaDataException( + origin + ": \"sources\" entry \"" + SOURCE_KEY_REFERENCE + "\" must be a boolean", + ErrorCode.ERR_BAD_ATTR_VALUE); + } + if (entry.size() - (reference != null ? 1 : 0) != 1) { throw new MetaDataException( origin + ": each \"sources\" entry must have exactly one key", ErrorCode.ERR_BAD_ATTR_VALUE); } + if (reference != null && !entry.has(SOURCE_KEY_PATH)) { + throw new MetaDataException( + origin + ": \"" + SOURCE_KEY_REFERENCE + "\" is only valid on a \"" + SOURCE_KEY_PATH + + "\" source", + ErrorCode.ERR_BAD_ATTR_VALUE); + } Map spec = new LinkedHashMap<>(); for (Map.Entry e : entry.entrySet()) { + if (SOURCE_KEY_REFERENCE.equals(e.getKey())) continue; JsonElement v = e.getValue(); if (!v.isJsonPrimitive() || !v.getAsJsonPrimitive().isString()) { // Every source-spec value (`path`/`resource`/`package`) is a @@ -318,6 +339,7 @@ public static NeutralConfig parse(String content, String origin) { } spec.put(e.getKey(), value); } + if (reference != null && reference.getAsBoolean()) spec.put(SOURCE_KEY_REFERENCE, "true"); specs.add(spec); } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/config/SourceResolver.java b/server/java/metadata/src/main/java/com/metaobjects/config/SourceResolver.java index cb7cab0574..6cfd93271f 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/config/SourceResolver.java +++ b/server/java/metadata/src/main/java/com/metaobjects/config/SourceResolver.java @@ -73,10 +73,27 @@ private SourceResolver() {} * is simultaneously unresolvable, which order-independence alone cannot pin. */ public static List resolveSources(Path configDir, List> specs) { + return resolveSourceFiles(configDir, specs).files(); + } + + /** + * The resolved file set of {@link #resolveSources}, split into the files every reaching spec + * declares a REFERENCE source ({@code "reference": "true"} beside the {@code path}) and the + * rest. A file an ordinary spec also reaches is the project's own — ordinary wins. + * + * @param files every resolved file, de-duplicated + * @param reference the subset of {@code files} only reference specs reach + */ + public record ResolvedFiles(List files, java.util.Set reference) {} + + /** {@link #resolveSources} that also reports which files are reference-only. */ + public static ResolvedFiles resolveSourceFiles(Path configDir, List> specs) { // Pass 1 — kind validation across the WHOLE set, no filesystem I/O yet. List pathSpecs = new ArrayList<>(specs.size()); + java.util.Set referencePaths = new java.util.HashSet<>(); + java.util.Set ordinaryPaths = new java.util.HashSet<>(); for (Map spec : specs) { - String rawPath = spec.get("path"); + String rawPath = spec.get(NeutralConfig.SOURCE_KEY_PATH); if (rawPath == null) { String kind = spec.keySet().stream().findFirst().orElse(""); throw new MetaDataException( @@ -84,12 +101,16 @@ public static List resolveSources(Path configDir, List ErrorCode.ERR_SOURCE_KIND_UNSUPPORTED); } pathSpecs.add(rawPath); + (Boolean.parseBoolean(spec.get(NeutralConfig.SOURCE_KEY_REFERENCE)) ? referencePaths : ordinaryPaths) + .add(rawPath); } Collections.sort(pathSpecs); // Pass 2 — resolve each validated path spec against the filesystem. LinkedHashSet seen = new LinkedHashSet<>(); + java.util.Set ordinary = new java.util.HashSet<>(); for (String rawPath : pathSpecs) { + List found = new ArrayList<>(); Path raw = Path.of(rawPath); Path target = raw.isAbsolute() ? raw : configDir.resolve(raw).normalize(); @@ -119,14 +140,21 @@ public static List resolveSources(Path configDir, List // with no `close()` leaks it on every directory source resolved. try (Stream stream = new DirectorySource(target, new DirectorySource.Options().setExcludePending(true)).expand()) { - stream.forEach(fs -> seen.add(fs.getPath().toAbsolutePath().normalize())); + stream.forEach(fs -> found.add(fs.getPath().toAbsolutePath().normalize())); } } else { - seen.add(target.toAbsolutePath().normalize()); + found.add(target.toAbsolutePath().normalize()); } + seen.addAll(found); + // A file is reference-only unless some ordinary spec reaches it. + if (ordinaryPaths.contains(rawPath)) ordinary.addAll(found); } - return new ArrayList<>(seen); + java.util.Set reference = new java.util.LinkedHashSet<>(); + if (!referencePaths.isEmpty()) { + for (Path p : seen) if (!ordinary.contains(p)) reference.add(p); + } + return new ResolvedFiles(new ArrayList<>(seen), reference); } /** @@ -135,6 +163,11 @@ public static List resolveSources(Path configDir, List * {@code ERR_SOURCE_UNRESOLVED}, a louder failure than "nothing declared". */ public static List resolveCollection(Path root) { + return resolveCollectionFiles(root).files(); + } + + /** {@link #resolveCollection(Path)} that also reports which files are reference-only. */ + public static ResolvedFiles resolveCollectionFiles(Path root) { Path base = root.toAbsolutePath().normalize(); List> specs = NeutralConfig.read(base) .map(NeutralConfig::getSources) @@ -149,10 +182,10 @@ public static List resolveCollection(Path root) { + ".metaobjects/config.json, or run 'meta init' to scaffold.", ErrorCode.ERR_COLLECTION_NOT_FOUND); } - specs = List.of(Map.of("path", NeutralConfig.DEFAULT_METADATA_DIR)); + specs = List.of(Map.of(NeutralConfig.SOURCE_KEY_PATH, NeutralConfig.DEFAULT_METADATA_DIR)); } - return resolveSources(base, specs); + return resolveSourceFiles(base, specs); } /** @@ -160,10 +193,16 @@ public static List resolveCollection(Path root) { * leads the load. * * @param ownFiles the project's own metadata files, as {@link #resolveCollection} returns them + * (reference files included: they load into the same root) + * @param referenceFiles the subset of {@code ownFiles} only reference sources reach * @param dependencies the verified dependencies and the predicates over them; {@link DependencySet#EMPTY} * when the project declares none */ - public record ResolvedCollection(List ownFiles, DependencySet dependencies) { + public record ResolvedCollection(List ownFiles, DependencySet dependencies, java.util.Set referenceFiles) { + + public ResolvedCollection(List ownFiles, DependencySet dependencies) { + this(ownFiles, dependencies, java.util.Set.of()); + } /** * Every file the load reads, in order: dependency artifacts (in dependency-NAME order) @@ -185,8 +224,8 @@ public List files() { */ public static ResolvedCollection resolveCollectionWithDependencies(Path root) { Path base = root.toAbsolutePath().normalize(); - List own = resolveCollection(base); - return new ResolvedCollection(own, DependencySet.resolve(base)); + ResolvedFiles own = resolveCollectionFiles(base); + return new ResolvedCollection(own.files(), DependencySet.resolve(base), own.reference()); } /** diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderConfigurable.java b/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderConfigurable.java index 9c6fcbe8c0..5193c2365f 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderConfigurable.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderConfigurable.java @@ -70,6 +70,17 @@ default List getLibraries() { return java.util.Collections.emptyList(); } + /** + * Reference sources: metadata files that load into the same root as {@link #getSources()} (so + * references resolve against them) but whose nodes no generator emits when only they declare + * them. A {@code default} for the same reason as {@link #getLibraries()}. + * + * @return source strings in the same forms {@link #getSources()} accepts; never null + */ + default List getReferenceSources() { + return java.util.Collections.emptyList(); + } + /** * FR-023 — the project's resolved metadata dependencies. Their committed snapshot artifacts * are loaded FIRST, ahead of {@link #getSources()}, each under its {@code dep:/} diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderConfigurationBuilder.java b/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderConfigurationBuilder.java index d9f46e54eb..70cb6e1a57 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderConfigurationBuilder.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/LoaderConfigurationBuilder.java @@ -31,6 +31,7 @@ public class LoaderConfigurationBuilder { private ClassLoader classLoader; private List sources = new ArrayList<>(); private List libraries = new ArrayList<>(); + private List referenceSources = new ArrayList<>(); private Map arguments = new HashMap<>(); private com.metaobjects.config.DependencySet dependencies = com.metaobjects.config.DependencySet.EMPTY; @@ -59,6 +60,19 @@ public LoaderConfigurationBuilder sources(List sources) { return this; } + /** + * Reference sources — see {@link LoaderConfigurable.LoaderConfiguration#getReferenceSources()}. + * + * @param referenceSources source strings in the forms {@link #sources} accepts; null is ignored + * @return this builder + */ + public LoaderConfigurationBuilder referenceSources(List referenceSources) { + if (referenceSources != null) { + this.referenceSources.addAll(referenceSources); + } + return this; + } + /** * MetaObjects-shipped library packages to load alongside the sources — see * {@link LoaderConfigurable.LoaderConfiguration#getLibraries()}. @@ -111,7 +125,8 @@ public LoaderConfigurationBuilder strict(boolean strict) { public LoaderConfigurable.LoaderConfiguration build() { return new LoaderConfigurationImpl(sourceDir, classLoader, new ArrayList<>(sources), - new ArrayList<>(libraries), new HashMap<>(arguments), dependencies); + new ArrayList<>(libraries), new HashMap<>(arguments), dependencies, + new ArrayList<>(referenceSources)); } /** @@ -124,17 +139,25 @@ private static class LoaderConfigurationImpl implements LoaderConfigurable.Loade private final List libraries; private final Map arguments; private final com.metaobjects.config.DependencySet dependencies; + private final List referenceSources; public LoaderConfigurationImpl(String sourceDir, ClassLoader classLoader, List sources, List libraries, Map arguments, - com.metaobjects.config.DependencySet dependencies) { + com.metaobjects.config.DependencySet dependencies, + List referenceSources) { this.sourceDir = sourceDir; this.classLoader = classLoader; this.sources = sources; this.libraries = libraries; this.arguments = arguments; this.dependencies = dependencies; + this.referenceSources = referenceSources; + } + + @Override + public List getReferenceSources() { + return referenceSources; } @Override diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java b/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java index c7a37d4035..09dd3cecda 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java @@ -133,6 +133,15 @@ public class MetaDataLoader implements LoaderConfigurable { // If set before init(), sources are loaded automatically during init(). private List sourceURIs = null; + /** Reference sources (see {@link #setReferenceURIs}): loaded with the sources, generated by nobody here. */ + private List referenceURIs = null; + + /** The {@link MetaDataSource#getId() ids} of the reference sources; a node only they declare is a reference node. */ + private java.util.Set referenceSourceIds = java.util.Set.of(); + + /** Top-level node FQN to the ids of EVERY source that declared it (overlays included). */ + private final Map> topLevelDeclaredIn = new java.util.LinkedHashMap<>(); + // MetaObjects-shipped library packages this loader opts into (#332). If set before // init(), their sources are loaded FIRST, so an `extends` onto a library-shipped // abstract base resolves. Opt-in and empty by default: a library package registers @@ -1195,6 +1204,72 @@ public ClassLoader getMetaDataClassLoader() { /////////////////////////////////////////////////////////////////////// // Source URIs (H3a Task 5: lifted from SimpleLoader) + /** + * Reference sources: files that load into this same root (so {@code @responseRef}, + * {@code extends}, {@code @objectRef} resolve against them) but whose top-level nodes no + * generator emits when ONLY reference files declare them. Read once during {@link #init()}, + * after {@link #setSourceURIs}; a file also named there is the project's own. + */ + public MetaDataLoader setReferenceURIs(List referenceURIs) { + this.referenceURIs = referenceURIs; + java.util.Set ids = new java.util.HashSet<>(); + if (referenceURIs != null) for (URI uri : referenceURIs) ids.add(new UriSource(uri).getId()); + setReferenceSourceIds(ids); + return this; + } + + /** + * The ids ({@link MetaDataSource#getId()}) of the sources that are reference sources. A caller + * that hands {@link #load(List)} its own sources names the reference ones here, before loading. + */ + public MetaDataLoader setReferenceSourceIds(java.util.Set ids) { + this.referenceSourceIds = (ids == null) ? java.util.Set.of() : java.util.Set.copyOf(ids); + return this; + } + + /** Parser hook: records that source {@code sourceId} declared (or overlaid) the top-level node {@code node}. */ + public void recordTopLevelDeclaration(MetaData node, String sourceId) { + // Nothing to record on a load with no reference source (the common case). + if (referenceSourceIds.isEmpty()) return; + topLevelDeclaredIn.computeIfAbsent(node.getName(), k -> new java.util.LinkedHashSet<>()).add(sourceId); + } + + /** + * The top-level nodes every one of whose declaring sources is a reference source, computed + * from what the parser recorded. A node with no recorded declaration (a library's, say) is + * never one. + */ + private java.util.Set computeReferenceNodes() { + java.util.Set out = new java.util.TreeSet<>(); + if (referenceSourceIds.isEmpty()) return out; + for (Map.Entry> e : topLevelDeclaredIn.entrySet()) { + if (!e.getValue().isEmpty() && referenceSourceIds.containsAll(e.getValue())) out.add(e.getKey()); + } + return out; + } + + /** + * Refuses a {@code template.*} declared ONLY in reference sources + * ({@link ErrorCode#ERR_REFERENCE_SOURCE_TEMPLATE}): template generators read the whole root, not + * the selection, so a reference-source prompt would be generated by both runs. Run by + * {@link #load(List)} after the validation passes. + */ + public void refuseReferenceTemplates() { + java.util.Set referenceNodes = getRoot().getReferenceNodes(); + if (referenceNodes.isEmpty()) return; + for (MetaData node : getRoot().getChildren()) { + String fqn = node.getName(); + if (referenceNodes.contains(fqn) + && com.metaobjects.template.TemplateConstants.TYPE_TEMPLATE.equals(node.getType())) { + throw new MetaDataException( + "template \"" + fqn + "\" is declared only in a reference source. A reference source holds " + + "shapes another run generates; declare the prompt in one of the project's own " + + "sources, where its parser and payload are generated.", + ErrorCode.ERR_REFERENCE_SOURCE_TEMPLATE); + } + } + } + /** * Set the URI list to be loaded during {@link #init()}. * @@ -1465,6 +1540,10 @@ public void configure(LoaderConfiguration config) { processSources(configSourceDir, config.getSources()); } + if (config.getReferenceSources() != null && !config.getReferenceSources().isEmpty()) { + setReferenceURIs(toSourceURIs(configSourceDir, config.getReferenceSources())); + } + // Set BEFORE init(): both this and the URI list are read once during // initialization, and configure() is the call that ends in init(). if (config.getLibraries() != null && !config.getLibraries().isEmpty()) { @@ -1488,7 +1567,10 @@ public void configure(LoaderConfiguration config) { protected void processSources(String sourceDir, List sourceList) { if (sourceList == null) throw new IllegalArgumentException( "sourceList was null on processSources for " + getName()); + setSourceURIs(toSourceURIs(sourceDir, sourceList)); + } + private List toSourceURIs(String sourceDir, List sourceList) { List uris = new ArrayList<>(); for (String s : sourceList) { if (s.indexOf(':') < 0) { @@ -1502,7 +1584,7 @@ protected void processSources(String sourceDir, List sourceList) { } uris.add(URIHelper.toURI(s)); } - setSourceURIs(uris); + return uris; } protected void processArguments(Map args) { @@ -1692,7 +1774,8 @@ public List getLibraries() { private void loadSourceURIsIfPresent() { boolean hasSources = sourceURIs != null && !sourceURIs.isEmpty(); - if (!hasSources && dependencies.isEmpty()) return; + boolean hasReferences = referenceURIs != null && !referenceURIs.isEmpty(); + if (!hasSources && !hasReferences && dependencies.isEmpty()) return; // FR-023: a dependency's snapshot artifacts LEAD the batch, in dependency-name order, so // the project's own files overlay and extend them. They share the batch rather than loading @@ -1704,6 +1787,22 @@ private void loadSourceURIsIfPresent() { sources.add(new UriSource(uri)); } } + if (hasReferences) { + // After the project's own sources; a file the project also names as its own loads once, as its own. + java.util.Set own = new java.util.HashSet<>(); + for (MetaDataSource s : sources) own.add(s.getId()); + java.util.Set ownedReferences = new java.util.HashSet<>(); + for (URI uri : referenceURIs) { + UriSource ref = new UriSource(uri); + if (own.contains(ref.getId())) ownedReferences.add(ref.getId()); + else sources.add(ref); + } + if (!ownedReferences.isEmpty()) { + java.util.Set ids = new java.util.HashSet<>(referenceSourceIds); + ids.removeAll(ownedReferences); + referenceSourceIds = java.util.Set.copyOf(ids); + } + } load(sources); } @@ -1912,6 +2011,12 @@ public MetaDataLoader load(List sources) { // {@link #addWarning(String)} (errors continue to be eager-thrown). ValidationPhase.run(root, this); + // Which top-level nodes only reference sources declare (read by every generator's selection). + root.setReferenceNodes(computeReferenceNodes()); + // Refused here, like a validation error, so every Java entry point (the mojo, a + // programmatic loader, the runtime) refuses a reference-only template as every port does. + refuseReferenceTemplates(); + return this; } diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java index 4c86219a63..847cad7581 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java @@ -904,6 +904,10 @@ private void processNode(MetaData parent, String type, String subType, return; } + // Reference sources: remember which source declared (or overlaid) each top-level node, so the + // loader can tell a node only reference files declare from the project's own. + if (isRoot) getLoader().recordTopLevelDeclaration(md, getFilename()); + // FR5c — capture pre-merge state BEFORE re-tagging the node's source. // If the existing source is a JsonSource / YamlSource / MergedSource, a // prior file already declared this node and the current file is a diff --git a/server/java/metadata/src/test/java/com/metaobjects/config/ReferenceSourceConformanceTest.java b/server/java/metadata/src/test/java/com/metaobjects/config/ReferenceSourceConformanceTest.java new file mode 100644 index 0000000000..18c26f2dce --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/config/ReferenceSourceConformanceTest.java @@ -0,0 +1,178 @@ +/* + * Copyright 2003 Doug Mealing LLC dba Meta Objects + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.metaobjects.config; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.MetaDataException; +import com.metaobjects.loader.FileSource; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.loader.MetaDataSource; +import com.metaobjects.object.MetaObject; +import com.metaobjects.registry.SharedRegistryTestBase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * Runs the shared reference-source corpus against this port: the single committed + * {@code fixtures/reference-source-conformance/cases.json}. A source declared + * {@code "reference": true} loads into the same root, and the top-level nodes ONLY reference files + * declare are the reference nodes ({@link com.metaobjects.MetaRoot#getReferenceNodes()}) that no + * generator emits. {@code expectReference} is the exhaustive set over the loaded top-level objects. + */ +@RunWith(Parameterized.class) +public class ReferenceSourceConformanceTest extends SharedRegistryTestBase { + + /** The id prefix a reference file loads under, so its provenance cannot collide with an own file's. */ + private static final String REFERENCE_ID_PREFIX = "ref:"; + + private record Case(String name, Map tree, JsonObject config, + Set expectReference, String expectLoadError) {} + + @Parameters(name = "{0}") + public static Collection cases() throws IOException { + Path dir = Paths.get("").toAbsolutePath(); + while (dir != null && !Files.isDirectory(dir.resolve("fixtures"))) dir = dir.getParent(); + assertNotNull("could not locate the repository fixtures/ directory", dir); + Path corpus = dir.resolve("fixtures/reference-source-conformance/cases.json"); + JsonArray arr = JsonParser.parseString(Files.readString(corpus, StandardCharsets.UTF_8)) + .getAsJsonObject().getAsJsonArray("cases"); + List rows = new ArrayList<>(); + for (JsonElement el : arr) { + JsonObject c = el.getAsJsonObject(); + Map tree = new LinkedHashMap<>(); + for (Map.Entry e : c.getAsJsonObject("tree").entrySet()) { + tree.put(e.getKey(), e.getValue().getAsString()); + } + Set expect = null; + if (c.has("expectReference")) { + expect = new TreeSet<>(); + for (JsonElement f : c.getAsJsonArray("expectReference")) expect.add(f.getAsString()); + } + String err = c.has("expectLoadError") ? c.get("expectLoadError").getAsString() : null; + String name = c.get("name").getAsString(); + rows.add(new Object[]{name, new Case(name, tree, c.getAsJsonObject("config"), expect, err)}); + } + return rows; + } + + @Parameter(0) + public String caseName; + + @Parameter(1) + public Case testCase; + + @Test + public void reportsTheSameReferenceNodes() throws Exception { + Path root = Files.createTempDirectory("mo-ref-source-").toAbsolutePath().normalize(); + try { + for (Map.Entry entry : testCase.tree().entrySet()) { + Path abs = root.resolve(entry.getKey()); + Files.createDirectories(abs.getParent()); + Files.write(abs, entry.getValue().getBytes(StandardCharsets.UTF_8)); + } + Path dotMo = root.resolve(".metaobjects"); + Files.createDirectories(dotMo); + Files.write(dotMo.resolve("config.json"), testCase.config().toString().getBytes(StandardCharsets.UTF_8)); + + SourceResolver.ResolvedCollection collection = SourceResolver.resolveCollectionWithDependencies(root); + List sources = new ArrayList<>(); + Set referenceIds = new TreeSet<>(); + for (Path file : collection.ownFiles()) { + if (collection.referenceFiles().contains(file)) { + String id = REFERENCE_ID_PREFIX + root.relativize(file).toString().replace('\\', '/'); + referenceIds.add(id); + sources.add(new FileSource(file, id)); + } else { + sources.add(new FileSource(file, root.relativize(file).toString().replace('\\', '/'))); + } + } + + MetaDataLoader loader = new MetaDataLoader( + LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "ref-" + testCase.name()); + loader.init(); + loader.setReferenceSourceIds(referenceIds); + try { + loader.load(sources); + } catch (MetaDataException e) { + assertRefusal(e); + return; + } + if (testCase.expectLoadError() != null) { + for (MetaDataException e : loader.getErrors()) { + if (e.getCode().filter(c -> c.name().equals(testCase.expectLoadError())).isPresent()) return; + } + fail("expected " + testCase.expectLoadError() + " for case " + testCase.name() + + ", got errors " + loader.getErrors()); + } + assertTrue("unexpected load errors: " + loader.getErrors(), loader.getErrors().isEmpty()); + + // Exhaustive over the loaded top-level objects: a reference-node set naming anything else + // (or missing an object) fails here. + Set got = new TreeSet<>(); + for (MetaObject o : loader.getMetaObjects()) { + if (loader.getRoot().getReferenceNodes().contains(o.getName())) got.add(o.getName()); + } + assertEquals(testCase.expectReference(), got); + } finally { + deleteRecursive(root); + } + } + + private void assertRefusal(MetaDataException e) { + assertNotNull("case " + testCase.name() + " raised an uncoded error: " + e, e.getCode().orElse(null)); + assertEquals(testCase.expectLoadError(), e.getCode().orElseThrow().name()); + } + + private static void deleteRecursive(Path dir) throws IOException { + if (!Files.exists(dir)) return; + try (Stream walk = Files.walk(dir)) { + walk.sorted(Comparator.reverseOrder()).forEach(p -> { + try { + Files.delete(p); + } catch (IOException ignored) { + // best-effort temp-dir cleanup + } + }); + } + } +} diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index be285004a3..394df51ca4 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -72,6 +72,7 @@ Collection, imported_from, refuse_library_package_misuse, + reference_nodes_of, refuse_unowned_packages, ) from metaobjects.config.dependencies import read_lock @@ -179,6 +180,7 @@ removed_naming_source_message, ) from metaobjects.render.engine import template_engine_of +from metaobjects.response_verify import SEVERITY_ERROR, response_findings from metaobjects.render.filesystem_provider import FilesystemProvider from metaobjects.render.verify import ( ERR_REQUIRED_SLOT_UNUSED, @@ -607,6 +609,9 @@ def _load_collection_result( # ejected copy, still opted in) and one it does not (a new node in someone # else's package). refuse_library_package_misuse(result.root, all_libraries) + # Reference sources: the nodes only `reference: true` files declare (codegen skips them). + if collection.reference_ids: + result.root.reference_nodes = reference_nodes_of(result.root, collection.reference_ids) # ADR-0058 Decision 3 — the resolved `Collection` already carries this # project's ONE naming setting (read at the same rung as `libraries`); attach # it to the loaded root so codegen, the runtime and `verify` agree. @@ -2969,14 +2974,15 @@ def _verify_templates(args: argparse.Namespace) -> int: print("metaobjects verify --templates: no template.* nodes found.") return 0 - error_count = 0 - checked = 0 - for tmpl in sorted(templates, key=lambda c: c.name): + def _verify_body(tmpl: MetaData) -> tuple[int, int]: + """One template's body against its payload: ``(drift errors, refs checked)``.""" + error_count = 0 + checked = 0 payload_ref = tmpl.get_meta_attr(tc.TEMPLATE_ATTR_PAYLOAD_REF) # ADR-0039: template attr resolves via extends (not origin; templates CAN extend) if not isinstance(payload_ref, str) or not payload_ref: print(f"error: [{tmpl.name}] missing @payloadRef.", file=sys.stderr) error_count += 1 - continue + return error_count, checked vo = bound_payload_vo(tmpl, tc.TEMPLATE_ATTR_PAYLOAD_REF) if vo is None: print( @@ -2985,7 +2991,7 @@ def _verify_templates(args: argparse.Namespace) -> int: file=sys.stderr, ) error_count += 1 - continue + return error_count, checked fields: list[PayloadField] = _derive_payload_field_tree(root, vo, frozenset()) @@ -3002,7 +3008,7 @@ def _verify_templates(args: argparse.Namespace) -> int: file=sys.stderr, ) error_count += 1 - continue + return error_count, checked # #193/#230: @requiredSlots/@requiredTags are a template.prompt concept — enforced ONLY on # the prompt path (the email/document output gate does not apply them per-part; the #193 @@ -3037,6 +3043,29 @@ def _verify_templates(args: argparse.Namespace) -> int: file=sys.stderr, ) error_count += 1 + return error_count, checked + + error_count = 0 + checked = 0 + for tmpl in sorted(templates, key=lambda c: c.name): + # The reply (`@responseRef`): its field tree, and an xml prompt's tag contract against + # it. Independent of the payload check, so it runs first. + reply_error = False + for finding in response_findings(root, tmpl): + line = f"[{tmpl.name}] (reply) {finding.code}: {finding.path}" + if finding.severity == SEVERITY_ERROR: + print(f"error: {line}", file=sys.stderr) + error_count += 1 + reply_error = True + else: + print(f"warning: {line}", file=sys.stderr) + body_errors, body_checked = _verify_body(tmpl) + error_count += body_errors + checked += body_checked + # As TypeScript counts: a template the body check did not engage with still counts + # when its reply check raised an error. + if body_checked == 0 and reply_error: + checked += 1 if error_count > 0: print( diff --git a/server/python/src/metaobjects/codegen/runner.py b/server/python/src/metaobjects/codegen/runner.py index 2e18db69b1..8e3d68f566 100644 --- a/server/python/src/metaobjects/codegen/runner.py +++ b/server/python/src/metaobjects/codegen/runner.py @@ -106,6 +106,17 @@ def run_gen( if not isinstance(metadata, MetaRoot): raise ValueError("run_gen: metadata must be a loaded MetaRoot.") + # Reference nodes (declared only by `{"path": ..., "reference": true}` sources) load so + # references resolve against them, and another run owns their generated types - so they + # leave the selection here, at the single choke point. With no reference source this is + # ``select`` unchanged. + reference_nodes = metadata.reference_nodes + if reference_nodes: + outer_select = select + + def select(fqn: str) -> bool: # noqa: F811 - the composed selection replaces the argument + return fqn not in reference_nodes and (outer_select is None or outer_select(fqn)) + objs = _objects(metadata) model_has_objects = bool(objs) # The WHOLE model in scope. `entity_filter` narrows what is written, never what a diff --git a/server/python/src/metaobjects/config/dependencies.py b/server/python/src/metaobjects/config/dependencies.py index 17830370c1..1a280026d0 100644 --- a/server/python/src/metaobjects/config/dependencies.py +++ b/server/python/src/metaobjects/config/dependencies.py @@ -21,7 +21,7 @@ from metaobjects.rules_settings import RulesSettings from metaobjects.wire import WireFormat from metaobjects.registry_manifest import METAMODEL_VERSION -from metaobjects.shared.base_types import TYPE_OBJECT, TYPE_REQUIREMENT +from metaobjects.shared.base_types import TYPE_OBJECT, TYPE_REQUIREMENT, TYPE_TEMPLATE #: Directory (under `.metaobjects/`) holding the synced snapshot artifacts, #: one subdirectory per dependency name: `.metaobjects/deps//`. @@ -531,6 +531,34 @@ def refuse_unowned_packages( ) +def reference_nodes_of(root: MetaData, reference_ids: frozenset[str]) -> frozenset[str]: + """The top-level nodes only reference files declare: every file in a node's provenance + (``source.files``, which lists every contributor of a merged overlay) is one of + ``reference_ids``. One declaration in an ordinary file makes the node the project's own. + + A ``template.*`` here is refused (``ERR_REFERENCE_SOURCE_TEMPLATE``): a reference source + carries shapes another run generates, and nothing here could honour a prompt in one - its + parser and payload type would be generated by nobody. Mirrors the TS ``referenceNodesOf``. + """ + out: set[str] = set() + # ADR-0039 SANCTIONED own-accessor case: a root-level scan - `MetaRoot` has no super, so + # its own children are the tree's top-level nodes. + for node in root.own_children(): + files = list(getattr(node.source, "files", None) or ()) + if not files or not all(f in reference_ids for f in files): + continue + if node.type == TYPE_TEMPLATE: + raise ParseError( + f'template "{node.resolution_key()}" is declared only in a reference source ' + f"({', '.join(files)}). A reference source holds shapes another run generates; " + "declare the prompt in one of the project's own sources, where its parser and " + "payload are generated.", + code=ErrorCode.ERR_REFERENCE_SOURCE_TEMPLATE, + ) + out.add(node.resolution_key()) + return frozenset(out) + + def refuse_library_package_misuse( root: MetaData, selection: Sequence[str] | None, @@ -689,6 +717,12 @@ class Collection: #: FR-023 — the declared `requirements.inherit` patterns, for `in_ledger`. requirements_inherit: tuple[str, ...] = () + #: The `FileSource` ids of this project's REFERENCE files (`{"path": ..., "reference": + #: true}` sources): `ref:`, also keys of `file_ids`. A top-level node + #: every one of whose declarations came from these ids is a reference node (`MetaRoot. + #: reference_nodes`): it loads and resolves, and no generator here emits it. + reference_ids: frozenset[str] = frozenset() + def imported(self, fqn: str) -> bool: """Is `fqn` in a package one of this project's dependencies owns?""" return package_of_resolution_key(fqn) in self.imported_packages diff --git a/server/python/src/metaobjects/config/neutral_config.py b/server/python/src/metaobjects/config/neutral_config.py index 909d9270dd..e92b7ce969 100644 --- a/server/python/src/metaobjects/config/neutral_config.py +++ b/server/python/src/metaobjects/config/neutral_config.py @@ -56,7 +56,7 @@ class NeutralConfig: """The port-neutral subset of `.metaobjects/config.json`.""" #: Raw source specs, each a single-key mapping (`path` / `resource` / `package`). - sources: list[dict[str, str]] + sources: list[dict[str, object]] #: Declared metadata dependencies (FR-023) — each dict already validated: #: `name`, exactly one transport key (`path` / `npm` / `python` / `maven` / @@ -122,6 +122,29 @@ class NeutralConfig: api: ApiSettings = ApiSettings() +#: A `path` source may carry this boolean beside it: its files load so references resolve +#: against them, and the nodes only they declare are generated by nobody here. +SOURCE_KEY_REFERENCE = "reference" + + +def _is_source_spec(spec: object) -> bool: + """One `sources` entry: a single `path` / `resource` / `package` key whose value is a + non-empty (after stripping) string - a bare number/boolean/null would otherwise reach + `Path()` downstream and raise an uncaught TypeError instead of a coded error, and an + empty `path` would resolve to the config-holding directory itself. A `path` entry may + add `reference`, which must be a real boolean (`"yes"` and `1` are refused). + """ + if not isinstance(spec, dict): + return False + if SOURCE_KEY_REFERENCE in spec: + if not isinstance(spec[SOURCE_KEY_REFERENCE], bool) or "path" not in spec: + return False + rest = {k: v for k, v in spec.items() if k != SOURCE_KEY_REFERENCE} + else: + rest = spec + return len(rest) == 1 and all(isinstance(v, str) and v.strip() for v in rest.values()) + + def find_project_dir(start: Path) -> Path | None: """The nearest directory at or above *start* that holds ``.metaobjects/config.json``, or ``None``. THE project-config finder for a load that is handed a metadata @@ -200,21 +223,11 @@ def read_neutral_config(config_dir: Path) -> NeutralConfig | None: # `isinstance(sources, list)` check below rather than silently reading as # "absent" and falling back to the default directory with no diagnostic. sources = raw.get("sources", []) - if not isinstance(sources, list) or not all( - isinstance(s, dict) - and len(s) == 1 - # Every source-spec value (`path`/`resource`/`package`) must be a - # non-empty (after stripping whitespace) string — a bare number/ - # boolean/null would otherwise reach `Path()` downstream and raise an - # uncaught TypeError instead of this coded error, and an empty or - # whitespace-only `path` would resolve to the config-holding directory - # itself rather than failing loudly on the typo'd config. - and all(isinstance(v, str) and v.strip() for v in s.values()) - for s in sources - ): + if not isinstance(sources, list) or not all(_is_source_spec(s) for s in sources): raise ParseError( - f"{path}: 'sources' must be an array of single-key objects, each " - "value a non-empty string", + f"{path}: 'sources' must be an array of objects with one non-empty string " + f"value (`path` / `resource` / `package`), and a `path` may add " + f"`{SOURCE_KEY_REFERENCE}: true|false`", code=ErrorCode.ERR_COLLECTION_NOT_FOUND, ) diff --git a/server/python/src/metaobjects/config/source_resolver.py b/server/python/src/metaobjects/config/source_resolver.py index 56088dcf4a..8946354cae 100644 --- a/server/python/src/metaobjects/config/source_resolver.py +++ b/server/python/src/metaobjects/config/source_resolver.py @@ -19,7 +19,7 @@ read_lock, verify_snapshot, ) -from .neutral_config import DEFAULT_METADATA_DIR, NeutralConfig, read_neutral_config +from .neutral_config import DEFAULT_METADATA_DIR, SOURCE_KEY_REFERENCE, NeutralConfig, read_neutral_config def _list_metadata_files(directory: Path) -> list[Path]: @@ -56,7 +56,7 @@ def _normalize(p: Path) -> Path: return Path(os.path.abspath(p)) -def _validate_kinds(specs: list[dict[str, str]]) -> None: +def _validate_kinds(specs: list[dict[str, object]]) -> None: """Validate every spec's kind before ANY filesystem access. Mirrors `sources.ts`'s `orderedPathSpecs` (`.map(toPathSpec)` runs over the @@ -76,12 +76,21 @@ def _validate_kinds(specs: list[dict[str, str]]) -> None: ) -def resolve_sources(config_dir: Path, specs: list[dict[str, str]]) -> list[Path]: +def resolve_sources(config_dir: Path, specs: list[dict[str, object]]) -> list[Path]: """Resolve a declared source SET to a de-duplicated list of metadata files. A relative ``path`` resolves against ``config_dir`` — the directory HOLDING the ``.metaobjects/`` folder — never against the process working directory. """ + return resolve_sources_with_reference(config_dir, specs)[0] + + +def resolve_sources_with_reference( + config_dir: Path, specs: list[dict[str, object]] +) -> tuple[list[Path], frozenset[Path]]: + """:func:`resolve_sources`, plus which of those files are REFERENCE files: reached only + by ``{"path": ..., "reference": true}`` specs. One ordinary spec reaching the same file + makes it the project's own (ordinary wins).""" # Whole-list kind validation FIRST — see `_validate_kinds`. _validate_kinds(specs) @@ -92,12 +101,13 @@ def resolve_sources(config_dir: Path, specs: list[dict[str, str]]) -> list[Path] # de-dup below is order-independent); only decides which declared path's # `ERR_SOURCE_UNRESOLVED` fires first when more than one is simultaneously # unresolvable. - ordered_specs = sorted(specs, key=lambda s: s["path"]) + ordered_specs = sorted(specs, key=lambda s: str(s["path"])) seen: dict[Path, None] = {} + ordinary: set[Path] = set() for spec in ordered_specs: - raw = Path(spec["path"]) + raw = Path(str(spec["path"])) target = raw if raw.is_absolute() else (config_dir / raw) if not target.exists(): @@ -109,9 +119,12 @@ def resolve_sources(config_dir: Path, specs: list[dict[str, str]]) -> list[Path] found = _list_metadata_files(target) if target.is_dir() else [target] for f in found: - seen.setdefault(_normalize(f), None) + n = _normalize(f) + seen.setdefault(n, None) + if spec.get(SOURCE_KEY_REFERENCE) is not True: + ordinary.add(n) - return list(seen) + return list(seen), frozenset(p for p in seen if p not in ordinary) def _make_in_migrate_scope( @@ -142,8 +155,17 @@ def predicate(fqn: str) -> bool: return predicate +#: The `FileSource` id prefix of a reference source's file (`ref:`), +#: like a dependency artifact's `dep:` — its provenance can never be mistaken for one of the +#: project's own files. +REFERENCE_ID_PREFIX = "ref:" + + def _collection_from_own_files( - root: Path, own_files: list[Path], cfg: NeutralConfig | None + root: Path, + own_files: list[Path], + cfg: NeutralConfig | None, + reference_files: frozenset[Path] = frozenset(), ) -> Collection: """The tail shared by `resolve_collection_full` (own files via the source ladder) and `build_collection` (own files from an external surface, e.g. @@ -176,6 +198,12 @@ def _collection_from_own_files( # own return order) — see `Collection.files`. dep_paths = [Path(dep.artifact_path) for dep in dependencies] file_ids: dict[Path, str] = {p: dep.source_id for p, dep in zip(dep_paths, dependencies)} + reference_file_ids = { + p: f"{REFERENCE_ID_PREFIX}{Path(os.path.relpath(p, root)).as_posix()}" + for p in own_files + if p in reference_files + } + file_ids.update(reference_file_ids) own_files_t = tuple(own_files) return Collection( @@ -195,6 +223,7 @@ def _collection_from_own_files( rules=rules, api=api, requirements_inherit=tuple(cfg.requirements_inherit if cfg is not None else []), + reference_ids=frozenset(reference_file_ids.values()), ) @@ -235,8 +264,8 @@ def resolve_collection_full(root: Path) -> Collection: ) specs = [{"path": DEFAULT_METADATA_DIR}] - own_files = resolve_sources(root, specs) - return _collection_from_own_files(root, own_files, cfg) + own_files, reference_files = resolve_sources_with_reference(root, specs) + return _collection_from_own_files(root, own_files, cfg, reference_files) def resolve_collection(root: Path) -> list[Path]: diff --git a/server/python/src/metaobjects/errors.py b/server/python/src/metaobjects/errors.py index e8c47055c2..d63f5bb73a 100644 --- a/server/python/src/metaobjects/errors.py +++ b/server/python/src/metaobjects/errors.py @@ -183,6 +183,9 @@ class ErrorCode(str, Enum): # (§11.5 — imported-ness is package-keyed; a genuinely new object in a dependency's # package would otherwise silently never generate). ERR_DEPENDENCY_PACKAGE_NOT_OWNED = "ERR_DEPENDENCY_PACKAGE_NOT_OWNED" + # A `template.*` is declared only in a reference source (`{"path": ..., "reference": true}`): + # its parser and payload type would be generated by nobody. + ERR_REFERENCE_SOURCE_TEMPLATE = "ERR_REFERENCE_SOURCE_TEMPLATE" # FR-023 — a dependency's metamodelVersion major differs from this toolchain's. ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE = "ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE" # FR-023 — `meta deps check` / `verify --deps` found the installed dependency differs diff --git a/server/python/src/metaobjects/meta/meta_root.py b/server/python/src/metaobjects/meta/meta_root.py index 8af20a3dfa..7f9aee7749 100644 --- a/server/python/src/metaobjects/meta/meta_root.py +++ b/server/python/src/metaobjects/meta/meta_root.py @@ -28,3 +28,8 @@ def __init__(self, type_: str, sub_type: str, name: str) -> None: self.rules_settings: RulesSettings = DEFAULT_RULES_SETTINGS # The project `api` setting (page size, unknown-field rule), attached the same way; read with `api_of()`. self.api: ApiSettings = ApiSettings() + # The resolution keys of the top-level nodes only REFERENCE sources declare + # (`{"path": ..., "reference": true}` in `.metaobjects/config.json`). They load and + # resolve like any other node; no generator emits them, because another run owns them. + # Set by the project-aware load; empty for a tree loaded with no reference source. + self.reference_nodes: frozenset[str] = frozenset() diff --git a/server/python/src/metaobjects/response_verify.py b/server/python/src/metaobjects/response_verify.py new file mode 100644 index 0000000000..abcf572655 --- /dev/null +++ b/server/python/src/metaobjects/response_verify.py @@ -0,0 +1,87 @@ +"""What ``metaobjects verify --templates`` checks about a prompt's REPLY (``@responseRef``). + +Mirrors the TypeScript ``response-verify.ts``. The loader already refuses a ``@responseRef`` +that names nothing (``ERR_INVALID_TEMPLATE``), so this gate checks what loading cannot: + +* the reply type has a field tree a parser can read (``ERR_RESPONSE_UNRESOLVED``, an error: + a reply with no fields parses into nothing); +* for an ``@responseFormat: xml`` prompt, every ``@requiredTags`` tag - which the body is + already held to (``ERR_OUTPUT_TAG_MISSING``) - names the reply type or one of its fields + (``ERR_RESPONSE_TAG_UNDECLARED``, a warning). The body teaches the model those tags and the + extractor reads the reply type's fields; this is the link between them. + +Pinned cross-port by ``fixtures/response-verify-conformance/``. +""" +from __future__ import annotations + +from dataclasses import dataclass + +from metaobjects.codegen.generators.render_helper_generator import _derive_payload_field_tree +from metaobjects.meta.meta_data import MetaData +from metaobjects.meta.core.object.meta_object import MetaObject +from metaobjects.meta.template import template_constants as tc +from metaobjects.naming_refs import ref_target +from metaobjects.shared.base_types import TYPE_TEMPLATE +from metaobjects.shared.separators import PACKAGE_SEP +from metaobjects.render.verify import PayloadField + +#: A responding prompt's ``@responseRef`` names no loaded value shape with fields. +ERR_RESPONSE_UNRESOLVED = "ERR_RESPONSE_UNRESOLVED" +#: An xml prompt's ``@requiredTags`` tag names neither the reply type nor a reply field (warning). +ERR_RESPONSE_TAG_UNDECLARED = "ERR_RESPONSE_TAG_UNDECLARED" + +SEVERITY_ERROR = "error" +SEVERITY_WARNING = "warning" + + + +@dataclass(frozen=True) +class ResponseFinding: + code: str + #: The ``@responseRef`` value, or the offending tag. + path: str + severity: str + + +def _field_names(tree: list[PayloadField], out: set[str]) -> set[str]: + for f in tree: + out.add(f.name) + children = getattr(f, "fields", None) + if children: + _field_names(list(children), out) + return out + + +def _short_name(name: str) -> str: + i = name.rfind(PACKAGE_SEP) + return name if i == -1 else name[i + len(PACKAGE_SEP):] + + +def response_findings(root: MetaData, tmpl: MetaData) -> list[ResponseFinding]: + """The reply findings for one template. Empty for anything that is not a + ``template.prompt`` carrying ``@responseRef`` - a prompt that does not elicit a typed + reply has nothing here.""" + if tmpl.type != TYPE_TEMPLATE or tmpl.sub_type != tc.TEMPLATE_SUBTYPE_PROMPT: + return [] + # ADR-0039: resolving reads - a prompt may inherit @responseRef / @responseFormat / @requiredTags. + response_ref = tmpl.get_meta_attr(tc.TEMPLATE_ATTR_RESPONSE_REF) + if not isinstance(response_ref, str): + return [] + + reply = ref_target(tmpl, tc.TEMPLATE_ATTR_RESPONSE_REF) + tree = _derive_payload_field_tree(root, reply, frozenset()) if isinstance(reply, MetaObject) else [] + if reply is None or not tree: + return [ResponseFinding(ERR_RESPONSE_UNRESOLVED, response_ref, SEVERITY_ERROR)] + + fmt = tmpl.get_meta_attr(tc.TEMPLATE_ATTR_RESPONSE_FORMAT) + if not isinstance(fmt, str) or fmt.lower() != tc.RESPONSE_FORMAT_XML: + return [] + tags = tmpl.get_meta_attr(tc.TEMPLATE_ATTR_REQUIRED_TAGS) + if not isinstance(tags, (list, tuple)): + return [] + known = _field_names(tree, {_short_name(reply.name)}) + return [ + ResponseFinding(ERR_RESPONSE_TAG_UNDECLARED, t, SEVERITY_WARNING) + for t in tags + if isinstance(t, str) and t not in known + ] diff --git a/server/python/tests/codegen/test_reference_nodes_gen.py b/server/python/tests/codegen/test_reference_nodes_gen.py new file mode 100644 index 0000000000..4c739f312b --- /dev/null +++ b/server/python/tests/codegen/test_reference_nodes_gen.py @@ -0,0 +1,69 @@ +"""A reference source's reply type is resolved against, never generated. + +Materializes the `reply-type-in-a-reference-source-resolves-and-is-not-generated` case of +`fixtures/reference-source-conformance/cases.json` and runs `metaobjects gen`: no model is +emitted for the reply type (or the value object it nests), while the output parser, the +output-format fragment and the extractor of the local prompt still name it. +""" +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from metaobjects.cli import main + +_CORPUS = ( + Path(__file__).resolve().parents[4] + / "fixtures" + / "reference-source-conformance" + / "cases.json" +) +_CASE_NAME = "reply-type-in-a-reference-source-resolves-and-is-not-generated" +_GENERATORS = "[entity, output-parser, output-prompt, extractor]" + + +def _project(root: Path, reference: bool) -> None: + case = next(c for c in json.loads(_CORPUS.read_text())["cases"] if c["name"] == _CASE_NAME) + for rel, content in case["tree"].items(): + p = root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(content) + config = json.loads(json.dumps(case["config"])) + if not reference: + config["sources"] = [{"path": "model"}, {"path": "replies"}] + (root / ".metaobjects").mkdir(exist_ok=True) + (root / ".metaobjects" / "config.json").write_text(json.dumps(config)) + (root / "metaobjects.config.yaml").write_text( + f"targets:\n main:\n outDir: out\n generators: {_GENERATORS}\n" + ) + + +def _emitted(root: Path) -> set[str]: + return {p.name for p in (root / "out").iterdir()} + + +def test_reference_reply_type_is_not_generated_but_its_parser_is( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _project(tmp_path, reference=True) + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + names = _emitted(tmp_path) + assert "SupportAnswer.py" not in names + assert "AnswerSource.py" not in names + assert "SupportRequest.py" in names # the local payload is the project's own + assert "support_answer_prompt_response_parser.py" in names + assert "from .SupportAnswer import SupportAnswer" in ( + tmp_path / "out" / "support_answer_prompt_response_parser.py" + ).read_text() + + +def test_the_same_reply_type_as_an_ordinary_source_is_generated( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _project(tmp_path, reference=False) + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + assert {"SupportAnswer.py", "AnswerSource.py"} <= _emitted(tmp_path) diff --git a/server/python/tests/conformance/test_reference_source_conformance.py b/server/python/tests/conformance/test_reference_source_conformance.py new file mode 100644 index 0000000000..931426ca89 --- /dev/null +++ b/server/python/tests/conformance/test_reference_source_conformance.py @@ -0,0 +1,59 @@ +"""Runs the shared reference-source corpus against this port. + +Reads `fixtures/reference-source-conformance/cases.json` - the single committed source of +truth. Each case materializes `tree` + `config`, loads the project through the collection +ladder, and compares the exhaustive reference-node set (`expectReference`) or the load +error code (`expectLoadError`). +""" +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from metaobjects.cli import _load_collection_result +from metaobjects.config.source_resolver import resolve_collection_full +from metaobjects.errors import ParseError + +_CORPUS = ( + Path(__file__).resolve().parents[4] + / "fixtures" + / "reference-source-conformance" + / "cases.json" +) +_CASES = json.loads(_CORPUS.read_text())["cases"] + + +def test_corpus_is_non_empty() -> None: + assert len(_CASES) > 0 + + +def _materialize(case: dict, root: Path) -> None: + for rel, content in case["tree"].items(): + p = root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(content) + d = root / ".metaobjects" + d.mkdir(parents=True, exist_ok=True) + (d / "config.json").write_text(json.dumps(case["config"])) + + +@pytest.mark.parametrize("case", _CASES, ids=[c["name"] for c in _CASES]) +def test_reference_source_conformance(case: dict, tmp_path: Path) -> None: + _materialize(case, tmp_path) + collection = resolve_collection_full(tmp_path) + + if "expectLoadError" in case: + expected = case["expectLoadError"] + try: + result = _load_collection_result(collection) + except ParseError as e: + assert e.code.value == expected + return + assert expected in {str(getattr(e.code, "value", e.code)) for e in result.errors} + return + + result = _load_collection_result(collection) + assert not result.errors + assert sorted(result.root.reference_nodes) == sorted(case.get("expectReference", [])) diff --git a/server/python/tests/conformance/test_response_verify_conformance.py b/server/python/tests/conformance/test_response_verify_conformance.py new file mode 100644 index 0000000000..b9a8b3fcbe --- /dev/null +++ b/server/python/tests/conformance/test_response_verify_conformance.py @@ -0,0 +1,86 @@ +"""Runs the shared reply-check corpus against this port. + +Reads `fixtures/response-verify-conformance/cases.json`: what `metaobjects verify +--templates` reports about each prompt's `@responseRef` (`ERR_RESPONSE_UNRESOLVED`, +`ERR_RESPONSE_TAG_UNDECLARED`). Also drives the real command for one case, to pin the +exit codes and the warning/error split of the gate itself. +""" +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from metaobjects.cli import main +from metaobjects import MetaDataLoader +from metaobjects.response_verify import response_findings +from metaobjects.shared.base_types import TYPE_TEMPLATE + +_CORPUS = ( + Path(__file__).resolve().parents[4] + / "fixtures" + / "response-verify-conformance" + / "cases.json" +) +_CASES = json.loads(_CORPUS.read_text())["cases"] + + +def test_corpus_is_non_empty() -> None: + assert len(_CASES) > 0 + + +def _load(case: dict, tmp_path: Path): + (tmp_path / ".metaobjects").mkdir() + (tmp_path / ".metaobjects" / "config.json").write_text(json.dumps({"schema_version": 1})) + model = tmp_path / "model" + model.mkdir() + (model / "meta.json").write_text(json.dumps(case["metadata"])) + result = MetaDataLoader.from_directory(model) + assert not result.errors, result.errors + return result.root + + +def _key(f: dict) -> tuple[str, str, str]: + return (f["template"], f["code"], f["path"]) + + +@pytest.mark.parametrize("case", _CASES, ids=[c["name"] for c in _CASES]) +def test_response_verify_conformance(case: dict, tmp_path: Path) -> None: + root = _load(case, tmp_path) + got = [ + {"template": t.name, "code": f.code, "path": f.path, "severity": f.severity} + # ADR-0039 sanctioned own: top-level scan on the loader ROOT (never extended). + for t in root.own_children() + if t.type == TYPE_TEMPLATE + for f in response_findings(root, t) + ] + assert sorted(got, key=_key) == sorted(case["expect"], key=_key) + + +def _gate(case_name: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys) -> tuple[int, str]: + case = next(c for c in _CASES if c["name"] == case_name) + meta = tmp_path / "model" + meta.mkdir() + (meta / "meta.json").write_text(json.dumps(case["metadata"])) + prompts = tmp_path / "prompts" / "support" + prompts.mkdir(parents=True) + (prompts / "answer.mustache").write_text( + "Answer {{question}}. Reply as .. ..." + ) + monkeypatch.chdir(tmp_path) + rc = main(["verify", "--templates", str(meta), "--prompts", str(tmp_path / "prompts")]) + return rc, capsys.readouterr().err + + +def test_gate_fails_on_an_unresolved_reply(tmp_path, monkeypatch, capsys) -> None: + rc, err = _gate("a-reply-with-no-fields-is-unresolved", tmp_path, monkeypatch, capsys) + assert rc == 1 + assert "(reply) ERR_RESPONSE_UNRESOLVED: acme::support::EmptyAnswer" in err + + +def test_gate_warns_but_passes_on_an_undeclared_tag(tmp_path, monkeypatch, capsys) -> None: + rc, err = _gate("an-xml-required-tag-the-reply-does-not-declare-is-reported", tmp_path, monkeypatch, capsys) + assert "(reply) ERR_RESPONSE_TAG_UNDECLARED: answer" in err + assert "warning:" in err + assert "error: [SupportAnswerPrompt] (reply)" not in err diff --git a/server/rust/Cargo.lock b/server/rust/Cargo.lock index 0115910fce..9a9c532e27 100644 --- a/server/rust/Cargo.lock +++ b/server/rust/Cargo.lock @@ -113,6 +113,7 @@ version = "0.1.0" dependencies = [ "metaobjects", "metaobjects-codegen", + "metaobjects-render", "serde_json", ] diff --git a/server/rust/metaobjects-cli/Cargo.toml b/server/rust/metaobjects-cli/Cargo.toml index c4d7b9a5ad..6b5e102d22 100644 --- a/server/rust/metaobjects-cli/Cargo.toml +++ b/server/rust/metaobjects-cli/Cargo.toml @@ -26,9 +26,9 @@ path = "src/main.rs" [dependencies] metaobjects = { path = "../metaobjects", version = "0.1.0" } metaobjects-codegen = { path = "../metaobjects-codegen", version = "0.1.0" } - -[dev-dependencies] +metaobjects-render = { path = "../metaobjects-render", version = "0.1.0" } serde_json.workspace = true + [lints] workspace = true diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 4e8afe0f1c..1adbfb4db1 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -25,8 +25,11 @@ use metaobjects_codegen::engine::{ ChangeKind, OWNED_MANIFEST, Outcome, RunError, RunOptions, RunReport, VerifyReport, }; use metaobjects_codegen::generator_list::{self, GENERATOR_LIST_FILE}; +use metaobjects_codegen::project::load_project; use metaobjects_codegen::{Generator, run, shipped_generators, verify}; +pub mod templates; + /// The tool's name in messages. const TOOL: &str = "cargo meta"; @@ -36,7 +39,7 @@ cargo meta: MetaObjects for Rust USAGE: cargo meta init [--project ] cargo meta gen [OPTIONS] [ENTITY...] - cargo meta verify [--codegen] [--full] [OPTIONS] + cargo meta verify [--codegen] [--templates] [--full] [OPTIONS] cargo meta eject ... [--force] [--engine ] cargo meta eject --undo [...] [--force] cargo meta eject --list @@ -50,7 +53,8 @@ COMMANDS: whose bytes changed; removes a generated file nothing emits any more; refuses to overwrite or delete a generated file that was edited by hand. verify Check that the generated crates are what `gen` would write, in memory and - without writing anything. Exits 1 on drift. + without writing anything, that every template body matches the payload it + renders over, and the business rules. Exits 1 on drift. eject Copy a shipped generator into codegen/generators/ to own and change. --undo takes back copies that are still identical to the shipped generator. The owned crate builds against this release of the engine from crates.io; @@ -63,7 +67,9 @@ OPTIONS (gen and verify): a sub-directory of it. Default: generated --generators Run only these generators, from the project's list (`cargo meta gen --list` shows both). - --strict Load strictly: an attribute no provider declares is an error. + --strict Load strictly: an attribute no provider declares is an error + Off by default here, unlike the other ports' `verify`: the Rust + generated-code skip key records the load mode `gen` used. --timings Print the time spent in each stage. OPTIONS (gen): @@ -72,8 +78,13 @@ OPTIONS (gen): owned copy compares. OPTIONS (verify): - --codegen The generated-code gate only: no business-rules gate. A bare - `verify` runs both. + --codegen The generated-code gate only: no business-rules gate. + --templates The template gate only: each template.* body against its payload + value object (unknown variables, unresolved partials, missing + required tags and slots) and each prompt's reply (@responseRef). + A bare `verify` runs every gate; naming one or both runs only those. + --prompts Where template bodies live, relative to the project root. + Default: prompts --full Render and compare even when a local run could answer from the stored key. Always on when CI is set. @@ -129,6 +140,7 @@ const VERIFY_FLAGS: &[Flag] = &[ valued("--generators"), valued("--out"), valued("--project"), + valued("--prompts"), switch("--strict"), switch("--templates"), switch("--timings"), @@ -569,11 +581,6 @@ fn cmd_verify( "`{TOOL} verify --db` does not exist: checking a schema against a live database is the Node `meta` command's for every server language (`meta verify --db`, ADR-0015)." ))); } - if s.has("--templates") { - return Err(Usage(format!( - "`{TOOL} verify --templates` does not exist yet: the Rust port ships no prompt or template generator, so it has no template gate. `{TOOL} verify --codegen` is the generated-code gate." - ))); - } if s.has("--deps") { return Err(Usage(format!( "`{TOOL} verify --deps` does not exist: metadata dependencies are resolved and checked by the Node `meta` command (`meta deps check`)." @@ -581,7 +588,59 @@ fn cmd_verify( } let mut options = run_options(&s, cwd, generators)?; options.force = s.has("--full") || ci_forces_render(std::env::var_os("CI")); - match verify(&options, generators) { + // Naming a gate runs only the named ones; a bare `verify` runs them all. + let named = s.has("--codegen") || s.has("--templates"); + let mut code = 0; + if s.has("--codegen") || !named { + code = verify_codegen(&s, &options, generators, out, err); + } + if s.has("--templates") || !named { + let prompts = s.value("--prompts").map(PathBuf::from); + code = code.max(verify_templates( + &options, + prompts.as_deref(), + s.has("--templates"), + out, + err, + )); + } + Ok(code) +} + +/// The template gate: load the project and check every template body and reply. +fn verify_templates( + options: &RunOptions, + prompts: Option<&Path>, + announce_empty: bool, + out: &mut dyn Write, + err: &mut dyn Write, +) -> i32 { + let project = match load_project( + &options.start_dir, + options.project_dir.as_deref(), + options.strict, + ) { + Ok(p) => p, + Err(errors) => { + let lines: Vec = errors.iter().map(ToString::to_string).collect(); + let _ = writeln!(err, "{TOOL} verify failed:\n{}", lines.join("\n")); + return 1; + } + }; + let root = &project.collection.config_dir; + let dir = root.join(prompts.unwrap_or_else(|| Path::new(templates::DEFAULT_PROMPTS_DIR))); + templates::run(&project, &dir, TOOL, announce_empty, out, err) +} + +/// The generated-code gate, and (on a bare `verify`) the rules gate. +fn verify_codegen( + s: &Split, + options: &RunOptions, + generators: &[Box], + out: &mut dyn Write, + err: &mut dyn Write, +) -> i32 { + match verify(options, generators) { Ok(report) => { print_warnings(err, &report.warnings); let (to_out, to_err) = verify_lines(&report); @@ -591,7 +650,7 @@ fn cmd_verify( for line in to_err { let _ = writeln!(err, "{line}"); } - let rules = !s.has("--codegen"); + let rules = !s.has("--codegen") && !s.has("--templates"); if rules { for line in rules_lines(&report) { let _ = writeln!(err, "{line}"); @@ -600,15 +659,15 @@ fn cmd_verify( if s.has("--timings") { print_timings(out, &report.timings); } - Ok(if report.in_sync() && !(rules && report.rules_failed()) { + if report.in_sync() && !(rules && report.rules_failed()) { 0 } else { 1 - }) + } } Err(e) => { let _ = writeln!(err, "{TOOL} verify failed:\n{e}"); - Ok(1) + 1 } } } @@ -972,7 +1031,6 @@ mod tests { let (code, _, err) = run_cli(&["meta", "verify", "--db"]); assert_eq!(code, 2); assert!(err.contains("meta verify --db"), "{err}"); - assert_eq!(run_cli(&["meta", "verify", "--templates"]).0, 2); assert_eq!(run_cli(&["meta", "verify", "--deps"]).0, 2); } diff --git a/server/rust/metaobjects-cli/src/templates.rs b/server/rust/metaobjects-cli/src/templates.rs new file mode 100644 index 0000000000..ecd225485c --- /dev/null +++ b/server/rust/metaobjects-cli/src/templates.rs @@ -0,0 +1,465 @@ +//! The template drift gate: `cargo meta verify --templates`. +//! +//! Every `template.*` node's body is checked against the payload value object it renders +//! over ([`metaobjects_render::verify`]), and a prompt's reply (`@responseRef`) is checked +//! against the tags the prompt asks the model to write. Follows the TypeScript gate +//! (`runTemplateVerify` in the CLI's `verify.ts`, and `response-verify.ts`); the reply rules +//! are pinned by `fixtures/response-verify-conformance/`. +//! +//! ADR-0039 holds throughout: every attribute and child is read through the resolving +//! accessors, so a template that inherits `@payloadRef`, `@textRef`, `@requiredTags` or +//! `@responseRef` through `extends` is checked with the inherited values. + +use std::collections::HashSet; +use std::io::Write; +use std::path::{Path, PathBuf}; + +use metaobjects::naming::strip_package; +use metaobjects::node::{NodeId, Tree}; +use metaobjects::parser::TYPE_FIELD; +use metaobjects::validate::prompt::{ + ATTR_HTML_BODY_REF, ATTR_KIND, ATTR_OBJECT_REF, ATTR_PAYLOAD_REF, ATTR_REQUIRED_SLOTS, + ATTR_RESPONSE_REF, ATTR_SUBJECT_REF, ATTR_TEXT_REF, FIELD_SUBTYPE_OBJECT as SUBTYPE_OBJECT, + KIND_EMAIL, SUBTYPE_OUTPUT, SUBTYPE_PROMPT, TYPE_TEMPLATE, +}; +use metaobjects::validate::rules::{str_attr, string_list}; +use metaobjects::validate::util::ObjectIndex; +use metaobjects_codegen::project::LoadedProject; +use metaobjects_render::verify::{ + ERR_PARTIAL_UNRESOLVED, ERR_REQUIRED_SLOT_UNUSED, ERR_RESPONSE_TAG_UNDECLARED, + ERR_RESPONSE_UNRESOLVED, ERR_TEMPLATE_ENGINE_UNSUPPORTED, PayloadField, VerifyOptions, verify, +}; +use metaobjects_render::{Provider, tags}; + +/// The directory template bodies live in, under the project root, unless `--prompts` says so. +pub const DEFAULT_PROMPTS_DIR: &str = "prompts"; + +const KIND_DEFAULT: &str = "document"; +const FORMAT_XML: &str = "xml"; +const ATTR_TEXT_BODY_REF: &str = "textBodyRef"; +const ATTR_REQUIRED_TAGS: &str = "requiredTags"; +const ATTR_RESPONSE_FORMAT: &str = "responseFormat"; + +/// How a finding counts: an error fails the gate, a warning is printed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Severity { + Error, + Warning, +} + +/// One finding about a prompt's reply. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResponseFinding { + pub code: &'static str, + /// The `@responseRef` value, or the offending tag. + pub path: String, + pub severity: Severity, +} + +/// The payload field tree of a value object, walked as the payload generator walks it: +/// scalars are leaves, a `field.object` with an `@objectRef` recurses into the object the +/// loader bound. A reference cycle stops; an unresolved `vo` gives an empty tree. +#[must_use] +pub fn derive_payload_field_tree( + tree: &Tree, + index: &ObjectIndex, + vo: Option, +) -> Vec { + fn walk( + tree: &Tree, + index: &ObjectIndex, + vo: NodeId, + seen: &mut Vec, + ) -> Vec { + if seen.contains(&vo) { + return Vec::new(); + } + seen.push(vo); + let fields = tree + .children(vo) + .iter() + .map(|&f| (f, tree.node(f))) + .filter(|(_, n)| n.type_name == TYPE_FIELD) + .map(|(f, n)| { + let nested = (n.sub_type == SUBTYPE_OBJECT + && str_attr(tree, f, ATTR_OBJECT_REF).is_some()) + .then(|| { + index + .ref_target(tree, f, ATTR_OBJECT_REF) + .map(|t| walk(tree, index, t, seen)) + .unwrap_or_default() + }); + PayloadField { + name: n.name.clone(), + fields: nested, + // Effective array-ness: `isArray` may be inherited through `extends`. + is_array: tree.resolved_is_array(f), + } + }) + .collect(); + seen.pop(); + fields + } + vo.map(|v| walk(tree, index, v, &mut Vec::new())) + .unwrap_or_default() +} + +fn field_names(fields: &[PayloadField], out: &mut HashSet) { + for f in fields { + out.insert(f.name.clone()); + if let Some(nested) = &f.fields { + field_names(nested, out); + } + } +} + +/// The reply findings for one template. Empty for anything that is not a `template.prompt` +/// carrying `@responseRef`: a prompt that does not elicit a typed reply has nothing here. +#[must_use] +pub fn response_findings(tree: &Tree, index: &ObjectIndex, tmpl: NodeId) -> Vec { + let node = tree.node(tmpl); + if node.type_name != TYPE_TEMPLATE || node.sub_type != SUBTYPE_PROMPT { + return Vec::new(); + } + // ADR-0039: effective attrs, a prompt may inherit @responseRef, @responseFormat and @requiredTags. + let Some(response_ref) = str_attr(tree, tmpl, ATTR_RESPONSE_REF) else { + return Vec::new(); + }; + let reply = index.ref_target(tree, tmpl, ATTR_RESPONSE_REF); + let fields = derive_payload_field_tree(tree, index, reply); + let Some(reply) = reply.filter(|_| !fields.is_empty()) else { + return vec![ResponseFinding { + code: ERR_RESPONSE_UNRESOLVED, + path: response_ref.to_string(), + severity: Severity::Error, + }]; + }; + let is_xml = str_attr(tree, tmpl, ATTR_RESPONSE_FORMAT) + .is_some_and(|f| f.eq_ignore_ascii_case(FORMAT_XML)); + if !is_xml { + return Vec::new(); + } + let mut known = HashSet::from([strip_package(&tree.node(reply).name).to_string()]); + field_names(&fields, &mut known); + string_list(tree, tmpl, ATTR_REQUIRED_TAGS) + .into_iter() + .filter(|t| !known.contains(*t)) + .map(|t| ResponseFinding { + code: ERR_RESPONSE_TAG_UNDECLARED, + path: t.to_string(), + severity: Severity::Warning, + }) + .collect() +} + +/// Mustache first, then Jinja, then plain text: when both a `.mustache` and a `.jinja` body +/// exist, the Mustache one wins. +const EXTENSIONS: [&str; 6] = [".mustache", ".jinja", ".j2", ".jinja2", ".txt", ""]; +const JINJA_EXTENSIONS: [&str; 3] = [".jinja", ".j2", ".jinja2"]; + +/// Maps a logical reference (`group/source`) onto a file under a base directory, trying the +/// conventional extensions. +pub struct FileProvider { + base: PathBuf, +} + +impl FileProvider { + #[must_use] + pub fn new(base: impl Into) -> Self { + Self { base: base.into() } + } + + /// The file `reference` resolves to, if any is a file. + #[must_use] + pub fn path_of(&self, reference: &str) -> Option { + EXTENSIONS.iter().find_map(|ext| { + let mut name = self.base.join(reference).into_os_string(); + name.push(ext); + let path = PathBuf::from(name); + path.is_file().then_some(path) + }) + } +} + +impl Provider for FileProvider { + fn resolve(&self, reference: &str) -> Option { + self.path_of(reference) + .and_then(|p| std::fs::read_to_string(p).ok()) + } + + fn is_jinja(&self, reference: &str) -> Option { + self.path_of(reference).map(|p| is_jinja_path(&p)) + } +} + +fn is_jinja_path(path: &Path) -> bool { + let name = path.to_string_lossy().to_lowercase(); + JINJA_EXTENSIONS.iter().any(|e| name.ends_with(e)) +} + +/// The 1-based line of the first tag naming `path` (or its head segment) in a body, over +/// tags scanned once per body. +struct TagLines<'t> { + text: &'t str, + found: Vec, +} + +impl<'t> TagLines<'t> { + fn new(text: &'t str) -> Self { + Self { + text, + found: tags::scan(text).unwrap_or_default(), + } + } + + fn line_of(&self, path: &str) -> Option { + use tags::TagKind::{Amp, Inverted, Name, Section, Triple}; + let head = path.split('.').next().unwrap_or(path); + let names: Vec<&str> = if head == path { + vec![path] + } else { + vec![path, head] + }; + names.iter().find_map(|name| { + self.found + .iter() + .find(|t| { + matches!(t.kind, Name | Triple | Amp | Section | Inverted) && t.value == *name + }) + .map(|t| self.text[..t.start].matches('\n').count() + 1) + }) + } +} + +/// The bodies a template renders, as `(label, ref)`, and whether the prompt-only +/// `@requiredSlots` / `@requiredTags` rules apply. `None` for a subtype this gate does not +/// know; an empty list for a template with no body reference (a loader concern, not this gate's). +fn body_refs(tree: &Tree, tmpl: NodeId) -> Option<(Vec<(&'static str, String)>, bool)> { + let text = |name| str_attr(tree, tmpl, name).map(str::to_string); + match tree.node(tmpl).sub_type.as_str() { + SUBTYPE_PROMPT => Some(( + text(ATTR_TEXT_REF) + .map(|r| ("prompt", r)) + .into_iter() + .collect(), + true, + )), + SUBTYPE_OUTPUT => { + let kind = str_attr(tree, tmpl, ATTR_KIND) + .unwrap_or(KIND_DEFAULT) + .to_lowercase(); + let refs = if kind == KIND_EMAIL { + [ + ("email/subject", ATTR_SUBJECT_REF), + ("email/html", ATTR_HTML_BODY_REF), + ("email/text", ATTR_TEXT_BODY_REF), + ] + .into_iter() + .filter_map(|(label, attr)| text(attr).map(|r| (label, r))) + .collect() + } else { + text(ATTR_TEXT_REF) + .map(|r| ("document", r)) + .into_iter() + .collect() + }; + Some((refs, false)) + } + _ => None, + } +} + +fn owned(items: Vec<&str>) -> Vec { + items.into_iter().map(str::to_string).collect() +} + +/// What a run of the gate counted. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Tally { + pub errors: usize, + pub warnings: usize, + /// Templates the check engaged with: one whose body verified, or one that errored. + pub checked: usize, +} + +struct Gate<'a> { + tree: &'a Tree, + index: &'a ObjectIndex, + provider: &'a FileProvider, + prompts_dir: &'a Path, + project_root: &'a Path, + err: &'a mut dyn Write, + tally: Tally, +} + +impl Gate<'_> { + fn error(&mut self, line: &str) { + self.tally.errors += 1; + let _ = writeln!(self.err, "error: {line}"); + } + + fn warn(&mut self, line: &str) { + self.tally.warnings += 1; + let _ = writeln!(self.err, "warning: {line}"); + } + + fn template(&mut self, tmpl: NodeId) { + let name = self.tree.node(tmpl).name.clone(); + let mut reply_error = false; + for f in response_findings(self.tree, self.index, tmpl) { + let line = format!("[{name}] (reply) {}: {}", f.code, f.path); + match f.severity { + Severity::Error => { + self.error(&line); + reply_error = true; + } + Severity::Warning => self.warn(&line), + } + } + if self.body(tmpl, &name) || reply_error { + self.tally.checked += 1; + } + } + + /// One template's body against its payload; true when the check engaged with it. + fn body(&mut self, tmpl: NodeId, name: &str) -> bool { + let tree = self.tree; + // ADR-0039: effective attrs, @payloadRef may be inherited via an abstract template. + // A typeless or absent @payloadRef is a loader-schema concern, not this gate's. + let Some(payload_ref) = str_attr(tree, tmpl, ATTR_PAYLOAD_REF) else { + return false; + }; + let sub_type = tree.node(tmpl).sub_type.clone(); + let fields = derive_payload_field_tree( + tree, + self.index, + self.index.ref_target(tree, tmpl, ATTR_PAYLOAD_REF), + ); + if fields.is_empty() { + self.error(&format!( + "[{name}] ({sub_type}) {ERR_PARTIAL_UNRESOLVED}: @payloadRef \"{payload_ref}\" did not resolve to a loaded object.value" + )); + return true; + } + let Some((refs, prompt_rules)) = body_refs(tree, tmpl) else { + return false; + }; + if refs.is_empty() { + return false; + } + let (required_slots, required_tags) = if prompt_rules { + ( + owned(string_list(tree, tmpl, ATTR_REQUIRED_SLOTS)), + owned(string_list(tree, tmpl, ATTR_REQUIRED_TAGS)), + ) + } else { + (Vec::new(), Vec::new()) + }; + let opts = VerifyOptions { + provider: Some(self.provider), + required_slots, + required_tags, + }; + let (mut any_checked, mut any_error) = (false, false); + for (label, reference) in refs { + let file = self.provider.path_of(&reference); + let Some(text) = file.as_ref().and_then(|p| std::fs::read_to_string(p).ok()) else { + let dir = self.prompts_dir.display(); + self.error(&format!( + "[{name}] ({label}) {ERR_PARTIAL_UNRESOLVED}: ref \"{reference}\" did not resolve under {dir} — create {dir}/{reference}.mustache (or .txt), or point --prompts at the directory that holds it" + )); + any_error = true; + continue; + }; + if file.as_deref().is_some_and(is_jinja_path) { + self.error(&format!( + "[{name}] ({label}) {ERR_TEMPLATE_ENGINE_UNSUPPORTED}: {reference} is a Jinja template; the Rust port checks Mustache only" + )); + any_error = true; + continue; + } + any_checked = true; + let lines = TagLines::new(&text); + for finding in verify(&text, &fields, &opts) { + let line = lines.line_of(&finding.path).map(|l| format!(":{l}")); + let at = file.as_deref().map_or_else(String::new, |f| { + let rel = f.strip_prefix(self.project_root).unwrap_or(f); + format!(" ({}{})", rel.display(), line.unwrap_or_default()) + }); + let line = format!("[{name}] ({label}) {}: {}{at}", finding.code, finding.path); + if finding.code == ERR_REQUIRED_SLOT_UNUSED { + self.warn(&line); + } else { + self.error(&line); + any_error = true; + } + } + } + any_checked || any_error + } +} + +/// Run the gate over a loaded project, printing findings to `err` and the verdict line to +/// `out` or `err`. Returns the exit status: 0 clean, 1 on any error. A project with no +/// `template.*` node says so only when `announce_empty` (the gate was asked for by name); +/// inside a bare `verify` it stays silent, as a model with no operations is on the rules gate. +pub fn run( + project: &LoadedProject, + prompts_dir: &Path, + tool: &str, + announce_empty: bool, + out: &mut dyn Write, + err: &mut dyn Write, +) -> i32 { + let result = &project.result; + let tree = &result.tree; + let index = ObjectIndex::build(tree, result.root); + // ADR-0039: effective children, resolved rather than relying on the root being unextended. + let templates: Vec = tree + .children(result.root) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_TEMPLATE) + .collect(); + if templates.is_empty() { + if announce_empty { + let _ = writeln!( + out, + "{tool} verify — no template.* nodes found; the template gate had nothing to check." + ); + } + return 0; + } + let provider = FileProvider::new(prompts_dir); + let mut gate = Gate { + tree, + index: &index, + provider: &provider, + prompts_dir, + project_root: &project.collection.config_dir, + err, + tally: Tally::default(), + }; + for tmpl in templates { + gate.template(tmpl); + } + let Tally { + errors, + warnings, + checked, + } = gate.tally; + if errors > 0 { + let _ = writeln!( + err, + "{tool} verify — {errors} drift error(s) across {checked} template(s)." + ); + return 1; + } + let note = if warnings > 0 { + format!(" ({warnings} warning(s))") + } else { + String::new() + }; + let _ = writeln!(out, "{tool} verify — {checked} template(s) clean{note}."); + 0 +} diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs index 5396154871..c2dbdc83b7 100644 --- a/server/rust/metaobjects-cli/tests/cli.rs +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -888,3 +888,151 @@ fn verify_runs_the_rules_gate_and_a_setting_decides_whether_a_finding_fails_it() "{err}" ); } + +/// A prompt over a payload value object, replying with a typed answer in xml. +fn prompt_model(required_tags: &str) -> String { + format!( + r#"{{ "metadata.root": {{ "package": "acme::support", "children": [ + {{ "object.value": {{ "name": "SupportRequest", "children": [ + {{ "field.string": {{ "name": "question" }} }} + ] }} }}, + {{ "object.value": {{ "name": "SupportAnswer", "children": [ + {{ "field.string": {{ "name": "text" }} }} + ] }} }}, + {{ "template.prompt": {{ "name": "AnswerPrompt", + "@payloadRef": "acme::support::SupportRequest", + "@textRef": "support/answer", + "@responseRef": "acme::support::SupportAnswer", + "@responseFormat": "xml", + "@requiredTags": {required_tags} }} }} +] }} }}"# + ) +} + +const ANSWER_BODY: &str = + "Answer {{question}} inside ..\n"; + +fn template_project(tag: &str, required_tags: &str) -> Project { + let p = Project::new(tag); + std::fs::write( + p.0.join("metaobjects/meta.shop.json"), + prompt_model(required_tags), + ) + .unwrap(); + std::fs::create_dir_all(p.0.join("prompts/support")).unwrap(); + std::fs::write(p.0.join("prompts/support/answer.mustache"), ANSWER_BODY).unwrap(); + p +} + +#[test] +fn verify_templates_passes_a_clean_project_and_needs_no_gen() { + let p = template_project("tpl-clean", r#"["SupportAnswer", "text"]"#); + let r = p.run(&["meta", "verify", "--templates"]); + let out = ok(&r); + assert!(out.contains("1 template(s) clean."), "{out}"); + assert!(!text(&r.stderr).contains("warning"), "{}", text(&r.stderr)); +} + +#[test] +fn verify_templates_fails_on_drift_and_names_the_file_and_line() { + let p = template_project("tpl-drift", r#"["SupportAnswer"]"#); + std::fs::write( + p.0.join("prompts/support/answer.mustache"), + "Intro\nAnswer {{qustion}} x\n", + ) + .unwrap(); + let r = p.run(&["meta", "verify", "--templates"]); + let err = text(&r.stderr); + assert_eq!(r.status.code(), Some(1), "{err}"); + assert!( + err.contains("[AnswerPrompt] (prompt) ERR_VAR_NOT_ON_PAYLOAD: qustion (prompts/support/answer.mustache:2)"), + "{err}" + ); + assert!( + err.contains("1 drift error(s) across 1 template(s)."), + "{err}" + ); + + // A body that is not there is an error too, and --prompts points the gate elsewhere. + std::fs::remove_file(p.0.join("prompts/support/answer.mustache")).unwrap(); + let r = p.run(&["meta", "verify", "--templates"]); + assert_eq!(r.status.code(), Some(1)); + assert!( + text(&r.stderr).contains("ERR_PARTIAL_UNRESOLVED"), + "{}", + text(&r.stderr) + ); + std::fs::create_dir_all(p.0.join("bodies/support")).unwrap(); + std::fs::write(p.0.join("bodies/support/answer.mustache"), ANSWER_BODY).unwrap(); + ok(&p.run(&["meta", "verify", "--templates", "--prompts", "bodies"])); +} + +#[test] +fn verify_templates_prints_a_reply_warning_without_failing() { + // `confidence` is neither the reply type nor one of its fields. + let p = template_project("tpl-reply", r#"["SupportAnswer", "text", "confidence"]"#); + std::fs::write( + p.0.join("prompts/support/answer.mustache"), + "{{question}} a 1", + ) + .unwrap(); + let r = p.run(&["meta", "verify", "--templates"]); + let err = text(&r.stderr); + assert_eq!(r.status.code(), Some(0), "{err}"); + assert!( + err.contains("[AnswerPrompt] (reply) ERR_RESPONSE_TAG_UNDECLARED: confidence"), + "{err}" + ); + assert!(text(&r.stdout).contains("1 template(s) clean (1 warning(s)).")); +} + +#[test] +fn a_bare_verify_runs_the_template_gate_beside_the_codegen_gate() { + let p = template_project("tpl-bare", r#"["SupportAnswer"]"#); + ok(&p.run(&["meta", "gen"])); + ok(&p.run(&["meta", "verify"])); + std::fs::write(p.0.join("prompts/support/answer.mustache"), "{{nope}}").unwrap(); + let r = p.run(&["meta", "verify"]); + assert_eq!(r.status.code(), Some(1)); + assert!(text(&r.stderr).contains("ERR_VAR_NOT_ON_PAYLOAD: nope")); + // `--codegen` alone never reads the templates. + ok(&p.run(&["meta", "verify", "--codegen"])); +} + +#[test] +fn verify_strict_rejects_the_unregistered_attribute_the_corpus_pins() { + // fixtures/verify-strict-conformance/unregistered-attr: a field carries an attribute no + // provider declares. The loader's code is the corpus's; the Rust port loads strictly on + // `--strict` (the other ports' `verify` is strict by default, `--lax` opting out), so the + // two halves of the expectation are `--strict` and the bare command. + let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../../fixtures/verify-strict-conformance/unregistered-attr"); + let expected: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(fixture.join("expected.json")).unwrap()) + .unwrap(); + let p = Project::new("strict"); + std::fs::copy( + fixture.join("input/meta.users.json"), + p.0.join("metaobjects/meta.shop.json"), + ) + .unwrap(); + ok(&p.run(&["meta", "gen"])); + let strict = p.run(&["meta", "verify", "--templates", "--strict"]); + assert_eq!( + strict.status.success(), + !expected["strict"]["exitNonZero"].as_bool().unwrap() + ); + let code = expected["strict"]["errorCode"].as_str().unwrap(); + assert!( + text(&strict.stderr).contains(code), + "{}", + text(&strict.stderr) + ); + let lax = p.run(&["meta", "verify"]); + assert_eq!( + lax.status.success(), + expected["lax"]["exitZero"].as_bool().unwrap(), + "{}", + text(&lax.stderr) + ); +} diff --git a/server/rust/metaobjects-cli/tests/response_verify_conformance.rs b/server/rust/metaobjects-cli/tests/response_verify_conformance.rs new file mode 100644 index 0000000000..418cacf88e --- /dev/null +++ b/server/rust/metaobjects-cli/tests/response_verify_conformance.rs @@ -0,0 +1,96 @@ +//! The shared reply-check corpus (`fixtures/response-verify-conformance/cases.json`): per +//! case, one canonical metadata document and the exhaustive set of reply findings the +//! template gate reports for it, compared as an unordered set of +//! `(template, code, path, severity)`. + +use std::collections::BTreeSet; +use std::path::PathBuf; + +use serde_json::Value; + +use metaobjects::loader::Loader; +use metaobjects::providers::default_registry; +use metaobjects::validate::prompt::TYPE_TEMPLATE; +use metaobjects::validate::util::ObjectIndex; +use metaobjects_cli::templates::{Severity, response_findings}; + +/// The corpus size: a deleted case fails here rather than silently shrinking coverage. +const CASES: usize = 7; + +type Finding = (String, String, String, String); + +fn cases() -> Vec { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../../fixtures/response-verify-conformance/cases.json"); + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}")); + let doc: Value = serde_json::from_str(&text).expect("cases.json"); + doc["cases"].as_array().expect("cases").clone() +} + +fn findings_of(metadata: &Value) -> BTreeSet { + let mut registry = default_registry().expect("registry"); + registry.seal(); + let result = + Loader::new(®istry).load_sources(&[("case.json".to_string(), metadata.to_string())]); + assert!( + result.errors.is_empty(), + "case does not load: {:?}", + result.errors + ); + let tree = &result.tree; + let index = ObjectIndex::build(tree, result.root); + tree.children(result.root) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_TEMPLATE) + .flat_map(|t| { + let name = tree.node(t).name.clone(); + response_findings(tree, &index, t) + .into_iter() + .map(move |f| { + let severity = match f.severity { + Severity::Error => "error", + Severity::Warning => "warning", + }; + ( + name.clone(), + f.code.to_string(), + f.path, + severity.to_string(), + ) + }) + }) + .collect() +} + +fn expected_of(case: &Value) -> BTreeSet { + case["expect"] + .as_array() + .expect("expect") + .iter() + .map(|e| { + let field = |k: &str| e[k].as_str().expect("string field").to_string(); + ( + field("template"), + field("code"), + field("path"), + field("severity"), + ) + }) + .collect() +} + +#[test] +fn the_reply_corpus_holds() { + let cases = cases(); + assert_eq!(cases.len(), CASES, "the corpus changed size"); + let failures: Vec = cases + .iter() + .filter_map(|case| { + let (actual, expected) = (findings_of(&case["metadata"]), expected_of(case)); + (actual != expected) + .then(|| format!("{}: expected {expected:?}, got {actual:?}", case["name"])) + }) + .collect(); + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index e0e18dc1e4..23726156c7 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -503,6 +503,7 @@ fn render(p: &mut Prepared<'_>, opts: &RunOptions) -> Result, R root: p.loaded.result.root, entities: &opts.entities, collection: &p.loaded.collection, + reference_nodes: &p.loaded.reference_nodes, }; let mut emitted: Vec = Vec::new(); for g in &p.selected { diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs index 5f36c6e5e0..3ffd047c6d 100644 --- a/server/rust/metaobjects-codegen/src/generator.rs +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -4,6 +4,7 @@ //! disk and writes nothing itself. The run engine owns reading and writing, so a file whose //! bytes did not change is never rewritten and the manifest is saved once per run. +use std::collections::BTreeSet; use std::fmt; use metaobjects::collection::Collection; @@ -36,6 +37,8 @@ pub struct GenContext<'a> { pub entities: &'a [String], /// The resolved project: its naming and wire settings (`.metaobjects/config.json`). pub collection: &'a Collection, + /// Resolution keys of the nodes only reference sources declare (computed once at load). + pub reference_nodes: &'a BTreeSet, } /// A generator failed: a shared-style error code and a message for people. diff --git a/server/rust/metaobjects-codegen/src/plan.rs b/server/rust/metaobjects-codegen/src/plan.rs index d7a2644e02..294cd53d25 100644 --- a/server/rust/metaobjects-codegen/src/plan.rs +++ b/server/rust/metaobjects-codegen/src/plan.rs @@ -841,19 +841,27 @@ fn field_rules( impl Plan { /// The plan of the model a generator was handed. pub fn of(ctx: &GenContext<'_>) -> Result { - Plan::build(ctx.tree, ctx.root, ctx.collection) + Plan::build(ctx.tree, ctx.root, ctx.collection, ctx.reference_nodes) } - pub fn build(tree: &Tree, root: NodeId, collection: &Collection) -> Result { + pub fn build( + tree: &Tree, + root: NodeId, + collection: &Collection, + reference: &BTreeSet, + ) -> Result { // Every concrete entity and value object, in model order. let mut structs: Vec = Vec::new(); let mut by_node: HashMap = HashMap::new(); let index = ObjectIndex::build(tree, root); + // A reference node loads and resolves but another run owns it (`reference` is the + // set the load computed and already vetted). for &id in tree.own_children(root) { let n = tree.node(id); if n.type_name != TYPE_OBJECT || !matches!(n.sub_type.as_str(), OBJECT_ENTITY | OBJECT_VALUE) || n.is_abstract + || reference.contains(&tree.resolution_key(id)) { continue; } diff --git a/server/rust/metaobjects-codegen/src/project.rs b/server/rust/metaobjects-codegen/src/project.rs index 9cd8622363..25c50b5776 100644 --- a/server/rust/metaobjects-codegen/src/project.rs +++ b/server/rust/metaobjects-codegen/src/project.rs @@ -1,6 +1,7 @@ //! Reading a project the way the other ports read it: find its collection, read its //! config, gather its files (YAML and JSON, plus the opted-in libraries), and load them. +use std::collections::BTreeSet; use std::path::Path; use metaobjects::collection::{Collection, resolve_collection}; @@ -8,12 +9,16 @@ use metaobjects::errors::MetaError; use metaobjects::loader::{LoadResult, Loader}; use metaobjects::naming::NamingRegistry; use metaobjects::providers::default_registry; +use metaobjects::reference::reference_nodes_of; /// A loaded project: the resolved collection and the model it loaded. #[derive(Debug)] pub struct LoadedProject { pub collection: Collection, pub result: LoadResult, + /// The resolution keys of the reference nodes (declared only in reference sources): + /// loaded and resolvable, generated by nobody here. + pub reference_nodes: BTreeSet, } /// Resolve and load the project that `start_dir` belongs to (or `explicit_dir`, when given). @@ -37,5 +42,11 @@ pub fn load_project( if !read_errors.is_empty() { return Err(read_errors); } - Ok(LoadedProject { collection, result }) + let reference_nodes = reference_nodes_of(&result.tree, result.root, &collection.reference_ids) + .map_err(|e| vec![e])?; + Ok(LoadedProject { + collection, + result, + reference_nodes, + }) } diff --git a/server/rust/metaobjects-codegen/tests/entity_edges.rs b/server/rust/metaobjects-codegen/tests/entity_edges.rs index 884c32944b..6002d6c26e 100644 --- a/server/rust/metaobjects-codegen/tests/entity_edges.rs +++ b/server/rust/metaobjects-codegen/tests/entity_edges.rs @@ -26,6 +26,7 @@ fn generate_named( root: loaded.result.root, entities: &names, collection: &loaded.collection, + reference_nodes: &loaded.reference_nodes, }; EntityGenerator .generate(&ctx) diff --git a/server/rust/metaobjects-codegen/tests/golden.rs b/server/rust/metaobjects-codegen/tests/golden.rs index 8decf44c57..7a15de3fb8 100644 --- a/server/rust/metaobjects-codegen/tests/golden.rs +++ b/server/rust/metaobjects-codegen/tests/golden.rs @@ -26,6 +26,7 @@ fn generate(files: &[(&str, &str)]) -> BTreeMap { root: loaded.result.root, entities: &[], collection: &loaded.collection, + reference_nodes: &loaded.reference_nodes, }; shipped_generators() .iter() @@ -114,6 +115,7 @@ fn the_support_crate_is_the_emitted_modules() { root: loaded.result.root, entities: &[], collection: &loaded.collection, + reference_nodes: &loaded.reference_nodes, }; let files = EntityGenerator .generate(&ctx) diff --git a/server/rust/metaobjects-codegen/tests/reference_nodes.rs b/server/rust/metaobjects-codegen/tests/reference_nodes.rs new file mode 100644 index 0000000000..6867f2c878 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/reference_nodes.rs @@ -0,0 +1,62 @@ +//! Reference sources (`{ "path": …, "reference": true }`): a reference node loads and +//! resolves, and the entity generator emits nothing for it. + +mod common; + +use common::Scratch; +use metaobjects_codegen::generator::GenContext; +use metaobjects_codegen::project::load_project; +use metaobjects_codegen::{EntityGenerator, Generator}; + +const CONFIG: &str = r#"{ "schema_version": 1, "sources": [ + { "path": "model" }, { "path": "replies", "reference": true } ] }"#; + +const OWN: &str = r#"{ "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Request", "children": [ { "field.string": { "name": "question" } } ] } }, + { "object.entity": { "name": "Ticket", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } + ] } } +] } }"#; + +const REPLY: &str = r#"{ "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Answer", "children": [ { "field.string": { "name": "text" } } ] } } +] } }"#; + +#[test] +fn a_reference_node_is_loaded_and_not_generated() { + let project = Scratch::project( + "reference", + &[ + (".metaobjects/config.json", CONFIG), + ("model/meta.own.json", OWN), + ("replies/meta.replies.json", REPLY), + ], + ); + let loaded = load_project(project.path(), None, false).expect("the model loads clean"); + assert_eq!( + loaded.reference_nodes.iter().cloned().collect::>(), + vec!["acme::Answer".to_string()] + ); + let ctx = GenContext { + tree: &loaded.result.tree, + root: loaded.result.root, + entities: &[], + collection: &loaded.collection, + reference_nodes: &loaded.reference_nodes, + }; + let files = EntityGenerator.generate(&ctx).expect("generates"); + let all: String = files.iter().map(|f| f.content.as_str()).collect(); + assert!( + all.contains("Ticket"), + "the project's own entity is emitted" + ); + assert!( + all.contains("Request"), + "the project's own value object is emitted" + ); + assert!( + !all.contains("Answer"), + "the reference value object is not emitted:\n{all}" + ); +} diff --git a/server/rust/metaobjects-codegen/tests/rules_inert.rs b/server/rust/metaobjects-codegen/tests/rules_inert.rs index 728e1c1578..6fc1eb63d2 100644 --- a/server/rust/metaobjects-codegen/tests/rules_inert.rs +++ b/server/rust/metaobjects-codegen/tests/rules_inert.rs @@ -38,6 +38,7 @@ fn emit(variant: &str) -> BTreeMap { root: loaded.result.root, entities: &[], collection: &loaded.collection, + reference_nodes: &loaded.reference_nodes, }; let mut files = BTreeMap::new(); for g in shipped_generators() { diff --git a/server/rust/metaobjects-render/src/lib.rs b/server/rust/metaobjects-render/src/lib.rs index cdb9328952..7673ecbe23 100644 --- a/server/rust/metaobjects-render/src/lib.rs +++ b/server/rust/metaobjects-render/src/lib.rs @@ -10,6 +10,9 @@ //! //! [`extract`] is the other half of a prompt: the tolerant reply parser that reads a typed //! answer back out of a model's reply, held to `fixtures/extract-conformance/`. +//! [`verify`] is the build-time half: it checks a template's variables, partials and +//! contracted output tags against the payload's declared field tree, held to +//! `fixtures/verify-conformance/`. //! [`prompt`] writes the output-format fragment that asks for that answer. pub mod accessors; @@ -19,6 +22,7 @@ pub mod presence; pub mod prompt; pub mod render; pub mod tags; +pub mod verify; pub use render::{ Body, InMemoryProvider, MAX_DEPTH, Provider, RenderError, RenderRequest, render, diff --git a/server/rust/metaobjects-render/src/presence.rs b/server/rust/metaobjects-render/src/presence.rs index 28a89add4d..d456dfc0b9 100644 --- a/server/rust/metaobjects-render/src/presence.rs +++ b/server/rust/metaobjects-render/src/presence.rs @@ -79,7 +79,7 @@ fn walk<'a>(tags: &[Tag], stack: &mut Vec<&'a Value>) -> Option { /// The index of the close tag that ends the section opened at `open`. The scanner has /// already refused unbalanced sections, so a close always exists; the end of the list is /// the fallback. -fn matching_close(tags: &[Tag], open: usize) -> usize { +pub(crate) fn matching_close(tags: &[Tag], open: usize) -> usize { let mut depth = 0usize; for (offset, tag) in tags[open + 1..].iter().enumerate() { match tag.kind { diff --git a/server/rust/metaobjects-render/src/render.rs b/server/rust/metaobjects-render/src/render.rs index f6569a3430..29ceb25331 100644 --- a/server/rust/metaobjects-render/src/render.rs +++ b/server/rust/metaobjects-render/src/render.rs @@ -56,6 +56,13 @@ fn err(message: impl Into) -> Result { pub trait Provider { /// The text `reference` names, or `None` when there is none. fn resolve(&self, reference: &str) -> Option; + + /// Whether `reference` is a file written for the Jinja engine (ADR-0061), when the + /// provider knows. `None` (the default) means it does not, and the text is Mustache. + /// The template drift check refuses a Jinja partial rather than read it as Mustache. + fn is_jinja(&self, _reference: &str) -> Option { + None + } } /// A provider over a fixed map of references to bodies. diff --git a/server/rust/metaobjects-render/src/verify.rs b/server/rust/metaobjects-render/src/verify.rs new file mode 100644 index 0000000000..738344fff8 --- /dev/null +++ b/server/rust/metaobjects-render/src/verify.rs @@ -0,0 +1,416 @@ +//! The template drift check: a template body against the payload it is rendered over. +//! +//! [`render`](crate::render) refuses a variable the payload lacks at render time; `verify` is +//! the build-time half. It walks the template's tags against a PLAIN field tree (the declared +//! shape of the payload, not data), so a field renamed on the payload is caught before a +//! prompt ships with a hole in it. The rules and finding codes are the TypeScript engine's +//! (`render/src/verify.ts`), held to `fixtures/verify-conformance/`: +//! +//! - A variable resolves through the context stack, innermost first; a section over a +//! container field pushes that field's element fields, a section over anything else keeps +//! the current context. +//! - `{{#hasX}}` is a derived boolean accessor when a field `x` is in reach, and `-last` is +//! the positional accessor inside a section over a list of objects. +//! - Partials resolve through the provider and are walked in the section's context; a cycle +//! or a chain past [`MAX_DEPTH`] stops quietly. +//! - After the walk, each `requiredSlots` name must have been used at the payload root +//! (a warning when not), and each `requiredTags` tag must appear as an opening and a +//! closing form in the body and its partials. + +use std::collections::HashSet; + +use serde_json::Value; + +use crate::accessors::{HAS_PREFIX, LAST_ACCESSOR, has_accessor_name}; +use crate::presence::{ERR_VAR_NOT_ON_PAYLOAD, matching_close}; +use crate::render::{MAX_DEPTH, Provider}; +use crate::tags::{self, Tag, TagKind}; + +/// A partial reference the provider does not resolve. +pub const ERR_PARTIAL_UNRESOLVED: &str = "ERR_PARTIAL_UNRESOLVED"; +/// A declared `@requiredSlots` slot the template never references (a warning). +pub const ERR_REQUIRED_SLOT_UNUSED: &str = "ERR_REQUIRED_SLOT_UNUSED"; +/// A declared `@requiredTags` output tag absent from the template text. +pub const ERR_OUTPUT_TAG_MISSING: &str = "ERR_OUTPUT_TAG_MISSING"; +/// The template text does not parse, or changes delimiters where that cannot render. +pub const ERR_TEMPLATE_SYNTAX: &str = "ERR_TEMPLATE_SYNTAX"; +/// A responding prompt's `@responseRef` names no loaded value shape with fields. +pub const ERR_RESPONSE_UNRESOLVED: &str = "ERR_RESPONSE_UNRESOLVED"; +/// An xml prompt's `@requiredTags` tag names neither the reply type nor a reply field. +pub const ERR_RESPONSE_TAG_UNDECLARED: &str = "ERR_RESPONSE_TAG_UNDECLARED"; +/// A body written for an engine this port does not run (Jinja). +pub const ERR_TEMPLATE_ENGINE_UNSUPPORTED: &str = "ERR_TEMPLATE_ENGINE_UNSUPPORTED"; + +/// One node of the payload's declared field tree. +/// +/// `fields` present: a context-pushing field (an object, or a list of objects). Absent: a +/// scalar, or a list of scalars. `is_array` is the field's effective array-ness. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct PayloadField { + pub name: String, + pub fields: Option>, + pub is_array: bool, +} + +impl PayloadField { + /// A scalar field. + #[must_use] + pub fn scalar(name: &str) -> Self { + Self { + name: name.to_string(), + fields: None, + is_array: false, + } + } + + /// A field tree from the corpus's `payload.json` shape: `[{ name, fields?, isArray? }]`. + #[must_use] + pub fn from_json(list: &Value) -> Vec { + list.as_array() + .map(|items| { + items + .iter() + .map(|f| Self { + name: f["name"].as_str().unwrap_or_default().to_string(), + fields: f.get("fields").map(Self::from_json), + is_array: f["isArray"].as_bool().unwrap_or(false), + }) + .collect() + }) + .unwrap_or_default() + } +} + +/// One drift finding. `path` is the offending variable path, partial reference, slot or tag. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct Finding { + pub code: &'static str, + pub path: String, +} + +impl Finding { + fn new(code: &'static str, path: impl Into) -> Self { + Self { + code, + path: path.into(), + } + } +} + +/// What a check may consult beyond the body and the field tree. +#[derive(Default)] +pub struct VerifyOptions<'a> { + /// When given, partials are resolved and their bodies walked. + pub provider: Option<&'a dyn Provider>, + /// Slots that must be referenced at the payload root; an unused one is a warning. + pub required_slots: Vec, + /// Tags the rendered text is contracted to contain, as an opening and a closing form. + pub required_tags: Vec, +} + +/// The context stack: innermost last. +type Stack<'a> = Vec<&'a [PayloadField]>; + +/// Check `template` against the payload field tree `fields`. +#[must_use] +pub fn verify(template: &str, fields: &[PayloadField], opts: &VerifyOptions<'_>) -> Vec { + let body = match tags::scan(template) { + Ok(t) => t, + Err(e) => return vec![Finding::new(ERR_TEMPLATE_SYNTAX, e.section)], + }; + let mut walker = Walker { + provider: opts.provider, + findings: Vec::new(), + referenced_at_root: HashSet::new(), + static_texts: Vec::new(), + }; + if let Some(at) = delimiter_conflict(&body, None) { + walker.findings.push(Finding::new(ERR_TEMPLATE_SYNTAX, at)); + } + walker.static_texts.push(without_comments(template, &body)); + let mut stack: Stack<'_> = vec![fields]; + walker.walk(&body, &mut stack, &[], false); + + let Walker { + mut findings, + referenced_at_root, + static_texts, + .. + } = walker; + findings.extend(slot_and_tag_findings( + &referenced_at_root, + &static_texts, + opts, + )); + findings +} + +struct Walker<'p> { + provider: Option<&'p dyn Provider>, + findings: Vec, + referenced_at_root: HashSet, + /// The text the output-tag check scans: the body plus every resolved partial body. + static_texts: Vec, +} + +impl Walker<'_> { + fn note_root(&mut self, stack: &Stack<'_>, name: &str) { + if stack.len() == 1 { + let head = name.split('.').next().unwrap_or(name); + self.referenced_at_root.insert(head.to_string()); + } + } + + fn walk<'a>(&mut self, tags: &[Tag], stack: &mut Stack<'a>, seen: &[String], positional: bool) { + let mut i = 0; + while i < tags.len() { + let tag = &tags[i]; + match tag.kind { + TagKind::Name | TagKind::Triple | TagKind::Amp => { + if tag.value != "." { + self.note_root(stack, &tag.value); + if resolve(stack, &tag.value).is_none() + && !is_boolean_accessor(stack, &tag.value) + && !is_positional_accessor(positional, &tag.value) + { + self.findings + .push(Finding::new(ERR_VAR_NOT_ON_PAYLOAD, tag.value.clone())); + } + } + } + TagKind::Section | TagKind::Inverted => { + let close = matching_close(tags, i); + let sub = &tags[i + 1..close]; + self.section(tag, sub, stack, seen, positional); + i = close; + } + TagKind::Partial => self.partial(&tag.value, stack, seen, positional), + TagKind::Close | TagKind::Comment | TagKind::Delimiters => {} + } + i += 1; + } + } + + fn section<'a>( + &mut self, + tag: &Tag, + sub: &[Tag], + stack: &mut Stack<'a>, + seen: &[String], + positional: bool, + ) { + let name = tag.value.as_str(); + if name == "." { + self.walk(sub, stack, seen, positional); + return; + } + self.note_root(stack, name); + let Some(field) = resolve(stack, name) else { + // A positional or derived `has` gate is a boolean on the current scope: it + // pushes nothing, so the body walks in the same scope. Anything else is drift, + // and its body is skipped (its context is unknowable). + if is_positional_accessor(positional, name) || is_boolean_accessor(stack, name) { + self.walk(sub, stack, seen, positional); + } else { + self.findings + .push(Finding::new(ERR_VAR_NOT_ON_PAYLOAD, name.to_string())); + } + return; + }; + // `#` over a container pushes its element fields; `^` and a `#` over a scalar keep + // the current context. Only a `#` over an array moves the positional scope. + let pushes = tag.kind == TagKind::Section && field.fields.is_some(); + let iterates = tag.kind == TagKind::Section && field.is_array; + let inner = if iterates { + field.fields.is_some() + } else { + positional + }; + if let (true, Some(nested)) = (pushes, field.fields.as_deref()) { + stack.push(nested); + self.walk(sub, stack, seen, inner); + stack.pop(); + } else { + self.walk(sub, stack, seen, inner); + } + } + + fn partial<'a>( + &mut self, + reference: &str, + stack: &mut Stack<'a>, + seen: &[String], + positional: bool, + ) { + let Some(provider) = self.provider else { + return; + }; + if seen.iter().any(|s| s == reference) || seen.len() >= MAX_DEPTH { + return; + } + let Some(text) = provider.resolve(reference) else { + self.findings + .push(Finding::new(ERR_PARTIAL_UNRESOLVED, reference)); + return; + }; + if provider.is_jinja(reference) == Some(true) { + self.findings + .push(Finding::new(ERR_TEMPLATE_ENGINE_UNSUPPORTED, reference)); + return; + } + let parsed = match tags::scan(&text) { + Ok(t) => t, + Err(e) => { + self.findings + .push(Finding::new(ERR_TEMPLATE_SYNTAX, e.section)); + return; + } + }; + if let Some(at) = delimiter_conflict(&parsed, Some(reference)) { + self.findings.push(Finding::new(ERR_TEMPLATE_SYNTAX, at)); + } + self.static_texts.push(without_comments(&text, &parsed)); + let mut chain = seen.to_vec(); + chain.push(reference.to_string()); + self.walk(&parsed, stack, &chain, positional); + } +} + +/// Where a text that changes delimiters cannot render, if it is one. Inlined text is parsed +/// under the surrounding delimiters, so a partial body (`inlined_as` is its reference) that +/// changes them is reported at that reference, and a body that changes them and inlines a +/// partial at its first partial. +fn delimiter_conflict(tags: &[Tag], inlined_as: Option<&str>) -> Option { + if !tags.iter().any(|t| t.kind == TagKind::Delimiters) { + return None; + } + inlined_as.map(str::to_string).or_else(|| { + tags.iter() + .find(|t| t.kind == TagKind::Partial) + .map(|t| t.value.clone()) + }) +} + +/// `text` with its comments cut out: what a tag-presence check may scan. +fn without_comments(text: &str, tags: &[Tag]) -> String { + let mut out = String::with_capacity(text.len()); + let mut pos = 0; + for tag in tags.iter().filter(|t| t.kind == TagKind::Comment) { + out.push_str(&text[pos..tag.start]); + pos = tag.end; + } + out.push_str(&text[pos..]); + out +} + +fn find_field<'a>(fields: &'a [PayloadField], name: &str) -> Option<&'a PayloadField> { + fields.iter().find(|f| f.name == name) +} + +/// Resolve a (possibly dotted) path the way Mustache does: the first segment through the +/// stack, innermost first, each later one a direct descent into the resolved field. +fn resolve<'a>(stack: &Stack<'a>, path: &str) -> Option<&'a PayloadField> { + let mut segments = path.split('.'); + let head = segments.next()?; + let mut current = stack + .iter() + .rev() + .find_map(|frame| find_field(frame, head))?; + for segment in segments { + current = find_field(current.fields.as_deref()?, segment)?; + } + Some(current) +} + +/// `has` over a field reachable on the stack. Acceptance keys off the field existing, +/// not its type, as in every port. +fn is_boolean_accessor(stack: &Stack<'_>, name: &str) -> bool { + !name.contains('.') + && name.starts_with(HAS_PREFIX) + && stack + .iter() + .any(|frame| frame.iter().any(|f| has_accessor_name(&f.name) == name)) +} + +/// `-last`, available when the innermost enclosing array section iterates objects. +fn is_positional_accessor(positional: bool, name: &str) -> bool { + positional && name == LAST_ACCESSOR +} + +/// An opening tag is `` or XML whitespace (attributes allowed); a longer +/// name (`` for `answer`) does not count. +fn has_open_tag(text: &str, tag: &str) -> bool { + let needle = format!("<{tag}"); + text.match_indices(&needle).any(|(i, _)| { + text[i + needle.len()..] + .chars() + .next() + .is_some_and(|c| matches!(c, '>' | ' ' | '\t' | '\n' | '\r')) + }) +} + +/// A closing tag is the exact literal ``; a self-closing form never satisfies one. +fn has_close_tag(text: &str, tag: &str) -> bool { + text.contains(&format!("")) +} + +fn slot_and_tag_findings( + referenced_at_root: &HashSet, + static_texts: &[String], + opts: &VerifyOptions<'_>, +) -> Vec { + let mut out: Vec = opts + .required_slots + .iter() + .filter(|slot| !referenced_at_root.contains(*slot)) + .map(|slot| Finding::new(ERR_REQUIRED_SLOT_UNUSED, slot.clone())) + .collect(); + // Body and partials scan as one string: a tag may straddle the boundary, and the newline + // only stops a tag being spliced together from two fragments. + let haystack = static_texts.join("\n"); + out.extend( + opts.required_tags + .iter() + .filter(|tag| !has_open_tag(&haystack, tag) || !has_close_tag(&haystack, tag)) + .map(|tag| Finding::new(ERR_OUTPUT_TAG_MISSING, tag.clone())), + ); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn codes(template: &str, fields: &[PayloadField]) -> Vec<(&'static str, String)> { + verify(template, fields, &VerifyOptions::default()) + .into_iter() + .map(|f| (f.code, f.path)) + .collect() + } + + #[test] + fn a_renamed_field_is_drift_and_a_present_one_is_not() { + let fields = [PayloadField::scalar("name")]; + assert!(codes("Hi {{name}}", &fields).is_empty()); + assert_eq!( + codes("Hi {{nmae}}", &fields), + vec![(ERR_VAR_NOT_ON_PAYLOAD, "nmae".to_string())] + ); + } + + #[test] + fn an_unbalanced_section_is_a_syntax_finding_alone() { + let fields = [PayloadField::scalar("a")]; + assert_eq!( + codes("{{#a}}{{missing}}", &fields), + vec![(ERR_TEMPLATE_SYNTAX, "a".to_string())] + ); + } + + #[test] + fn required_tags_need_both_forms_and_an_exact_name() { + assert!(has_open_tag("x", "answer")); + assert!(!has_open_tag("", "answer")); + assert!(!has_close_tag("", "answer")); + } +} diff --git a/server/rust/metaobjects-render/tests/verify_conformance.rs b/server/rust/metaobjects-render/tests/verify_conformance.rs new file mode 100644 index 0000000000..c53f10fe38 --- /dev/null +++ b/server/rust/metaobjects-render/tests/verify_conformance.rs @@ -0,0 +1,142 @@ +//! The shared template drift corpus (`fixtures/verify-conformance/`): the same payload field +//! tree, template, partials and options give the same findings in every port. +//! +//! Each case directory holds `payload.json` (the declared field tree, not render data), +//! `template.mustache`, optional `partials/.mustache` (referenced as +//! `partials/`), optional `options.json` (`requiredSlots`, `requiredTags`, and +//! `provider`: `with` or `without`; the default is `with` exactly when a `partials/` +//! directory exists) and `expected-drift.json`, a list of `{ code, path }` compared as a +//! sorted multiset. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use metaobjects_render::InMemoryProvider; +use metaobjects_render::presence::ERR_VAR_NOT_ON_PAYLOAD; +use metaobjects_render::verify::{ + ERR_OUTPUT_TAG_MISSING, ERR_PARTIAL_UNRESOLVED, ERR_REQUIRED_SLOT_UNUSED, ERR_TEMPLATE_SYNTAX, + PayloadField, VerifyOptions, verify, +}; + +/// The corpus size: a deleted case fails here rather than silently shrinking coverage. +const CASES: usize = 45; + +/// The closed set of codes a case may expect; anything else is a typo in the fixture. +const KNOWN_CODES: [&str; 5] = [ + ERR_VAR_NOT_ON_PAYLOAD, + ERR_PARTIAL_UNRESOLVED, + ERR_REQUIRED_SLOT_UNUSED, + ERR_OUTPUT_TAG_MISSING, + ERR_TEMPLATE_SYNTAX, +]; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/verify-conformance") +} + +fn read(path: &Path) -> String { + std::fs::read_to_string(path).unwrap_or_else(|e| panic!("{path:?}: {e}")) +} + +fn strings(value: &Value) -> Vec { + value + .as_array() + .map(|a| { + a.iter() + .filter_map(|s| s.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default() +} + +fn run_case(dir: &Path) -> Result<(), String> { + let fields = PayloadField::from_json( + &serde_json::from_str(&read(&dir.join("payload.json"))).map_err(|e| e.to_string())?, + ); + let template = read(&dir.join("template.mustache")); + let options: Value = if dir.join("options.json").is_file() { + serde_json::from_str(&read(&dir.join("options.json"))).map_err(|e| e.to_string())? + } else { + Value::Null + }; + let partials_dir = dir.join("partials"); + let mut partials = HashMap::new(); + if partials_dir.is_dir() { + for entry in std::fs::read_dir(&partials_dir).map_err(|e| e.to_string())? { + let path = entry.map_err(|e| e.to_string())?.path(); + if path.extension().is_some_and(|x| x == "mustache") { + let stem = path.file_stem().expect("stem").to_string_lossy(); + partials.insert(format!("partials/{stem}"), read(&path)); + } + } + } + let with_provider = match options["provider"].as_str() { + Some("with") => true, + Some("without") => false, + _ => partials_dir.is_dir(), + }; + let provider = InMemoryProvider::new(partials); + let opts = VerifyOptions { + provider: with_provider.then_some(&provider as &dyn metaobjects_render::Provider), + required_slots: strings(&options["requiredSlots"]), + required_tags: strings(&options["requiredTags"]), + }; + + let expected: Vec<(String, String)> = + serde_json::from_str::>(&read(&dir.join("expected-drift.json"))) + .map_err(|e| e.to_string())? + .iter() + .map(|e| { + ( + e["code"].as_str().unwrap_or_default().to_string(), + e["path"].as_str().unwrap_or_default().to_string(), + ) + }) + .collect(); + if let Some((code, _)) = expected + .iter() + .find(|(c, _)| !KNOWN_CODES.contains(&c.as_str())) + { + return Err(format!("expected-drift.json names an unknown code {code}")); + } + let mut actual: Vec<(String, String)> = verify(&template, &fields, &opts) + .into_iter() + .map(|f| (f.code.to_string(), f.path)) + .collect(); + actual.sort(); + let mut want = expected; + want.sort(); + if actual == want { + Ok(()) + } else { + Err(format!("expected {want:?}, got {actual:?}")) + } +} + +#[test] +fn the_verify_corpus_holds() { + let mut names: Vec = std::fs::read_dir(corpus()) + .expect("corpus") + .filter_map(Result::ok) + .filter(|e| e.path().is_dir()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + assert_eq!(names.len(), CASES, "the corpus changed size: {names:?}"); + let failures: Vec = names + .iter() + .filter_map(|n| { + run_case(&corpus().join(n)) + .err() + .map(|e| format!("{n}: {e}")) + }) + .collect(); + assert!( + failures.is_empty(), + "{} of {CASES} failed:\n{}", + failures.len(), + failures.join("\n") + ); +} diff --git a/server/rust/metaobjects/data/ERROR-CODES.json b/server/rust/metaobjects/data/ERROR-CODES.json index 757bc735b6..737dbc341a 100644 --- a/server/rust/metaobjects/data/ERROR-CODES.json +++ b/server/rust/metaobjects/data/ERROR-CODES.json @@ -69,6 +69,7 @@ "ERR_SOURCE_NO_PRIMARY": "An object declares source nodes but none has role=primary.", "ERR_SOURCE_MULTIPLE_PRIMARY": "An object declares more than one source node with role=primary.", "ERR_SOURCE_KIND_UNSUPPORTED": "Phase-1 metadata-source-resolution: a declared source kind (resource or package) is not supported by this toolchain.", + "ERR_REFERENCE_SOURCE_TEMPLATE": "Phase-1 metadata-source-resolution: a template.* node is declared only in reference sources (a `sources` entry with \"reference\": true), whose nodes no generator emits, so its parser and payload would be generated by nobody.", "ERR_SOURCE_UNRESOLVED": "Phase-1 metadata-source-resolution: a path source declared in .metaobjects/config.json does not exist on disk.", "ERR_PHYSICAL_NAME_KIND_MISMATCH": "FR-016 / ADR-0018: a source.rdb declares a kind-aware physical-name alias (@view/@materializedView/@proc/@function) that does not match its @kind. The legacy @table-for-non-table case warns rather than errors.", "ERR_PHYSICAL_NAME_MULTIPLE": "FR-016 / ADR-0018: a source.rdb declares two or more kind-aware physical-name aliases at once (e.g. both @table and @view). Exactly one is permitted.", diff --git a/server/rust/metaobjects/src/collection.rs b/server/rust/metaobjects/src/collection.rs index 1d6336b1e8..f6079f0100 100644 --- a/server/rust/metaobjects/src/collection.rs +++ b/server/rust/metaobjects/src/collection.rs @@ -5,6 +5,7 @@ //! Dependency snapshots are not resolved here: a config that declares //! `dependencies` gets them back unresolved in [`Collection::dependencies`]. +use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use crate::config::{ @@ -41,6 +42,9 @@ pub struct Collection { pub source_roots: Vec, /// The project's own metadata files. pub own_files: Vec, + /// The loader ids ([`Collection::read_sources`]) of the REFERENCE files: those only + /// `{ "path": …, "reference": true }` sources reach. Empty when none is declared. + pub reference_ids: BTreeSet, /// Declared dependencies, validated but NOT resolved against any snapshot. pub dependencies: Vec, /// The shipped-library selection as authored. @@ -278,9 +282,16 @@ pub fn resolve_collection( } } + let reference_ids: BTreeSet = own_sources + .iter() + .filter(|s| s.reference) + .map(|s| s.file.to_string_lossy().into_owned()) + .collect(); + let migrate = config.migrate.clone(); Ok(Collection { config_dir, + reference_ids, files: own_files.clone(), own_files, sources: own_sources, diff --git a/server/rust/metaobjects/src/config.rs b/server/rust/metaobjects/src/config.rs index 5d9183f1b8..a86bd1b580 100644 --- a/server/rust/metaobjects/src/config.rs +++ b/server/rust/metaobjects/src/config.rs @@ -569,29 +569,64 @@ fn parse_sources(v: &Value, issues: &mut Issues) -> Vec { issues.add(&at, expected("object", entry)); continue; }; - let spec = (o.len() == 1) - .then(|| o.iter().next()) - .flatten() - .and_then(|(k, v)| { - let s = v.as_str().filter(|s| !s.is_empty())?.to_string(); - match k.as_str() { - "path" => Some(SourceSpec::Path(s)), - "resource" => Some(SourceSpec::Resource(s)), - "package" => Some(SourceSpec::Package(s)), - _ => None, - } - }); - match spec { - Some(s) => out.push(s), - None => issues.add( - &at, - "expected exactly one of \"path\", \"resource\" or \"package\", set to a non-empty string", - ), - } + let spec = parse_source_spec(o, &at, issues); + out.extend(spec); } out } +/// The `reference` flag of a `path` source: loads the files so references resolve against +/// them, and leaves the nodes only they declare to another run. +const SOURCE_REFERENCE_KEY: &str = "reference"; + +/// One `sources` entry. A `resource` or `package` entry takes exactly its one key; a `path` +/// entry may add `reference`, which must be a boolean. Every problem is reported on `issues`. +fn parse_source_spec( + o: &serde_json::Map, + at: &str, + issues: &mut Issues, +) -> Option { + let shape = + "expected exactly one of \"path\", \"resource\" or \"package\", set to a non-empty string"; + let non_empty = |v: &Value| v.as_str().filter(|s| !s.is_empty()).map(str::to_string); + if let Some(path) = o.get("path") { + let Some(path) = non_empty(path) else { + issues.add(at, shape); + return None; + }; + return match o.get(SOURCE_REFERENCE_KEY) { + None if o.len() == 1 => Some(SourceSpec::Path(path)), + Some(Value::Bool(flag)) if o.len() == 2 => Some(SourceSpec::PathFlagged(path, *flag)), + Some(v) if !v.is_boolean() => { + issues.add( + &format!("{at}.{SOURCE_REFERENCE_KEY}"), + expected("boolean", v), + ); + None + } + _ => { + issues.add(at, shape); + None + } + }; + } + let spec = (o.len() == 1) + .then(|| o.iter().next()) + .flatten() + .and_then(|(k, v)| { + let s = non_empty(v)?; + match k.as_str() { + "resource" => Some(SourceSpec::Resource(s)), + "package" => Some(SourceSpec::Package(s)), + _ => None, + } + }); + if spec.is_none() { + issues.add(at, shape); + } + spec +} + fn dependency_name_ok(name: &str) -> bool { let mut chars = name.chars(); chars diff --git a/server/rust/metaobjects/src/errors.rs b/server/rust/metaobjects/src/errors.rs index 19fb246d7f..5601f22ecb 100644 --- a/server/rust/metaobjects/src/errors.rs +++ b/server/rust/metaobjects/src/errors.rs @@ -44,6 +44,8 @@ pub const ERR_SOURCE_KIND_UNSUPPORTED: &str = "ERR_SOURCE_KIND_UNSUPPORTED"; pub const ERR_COLLECTION_NOT_FOUND: &str = "ERR_COLLECTION_NOT_FOUND"; pub const ERR_COLLECTION_NAME_COLLISION: &str = "ERR_COLLECTION_NAME_COLLISION"; pub const ERR_UNKNOWN_LIBRARY: &str = "ERR_UNKNOWN_LIBRARY"; +/// A `template.*` declared only in reference sources. +pub const ERR_REFERENCE_SOURCE_TEMPLATE: &str = "ERR_REFERENCE_SOURCE_TEMPLATE"; /// The code reported for a failure that carries none (a programming error in a /// provider definition, say). @@ -80,6 +82,7 @@ pub const ALL_CODES: &[&str] = &[ ERR_COLLECTION_NOT_FOUND, ERR_COLLECTION_NAME_COLLISION, ERR_UNKNOWN_LIBRARY, + ERR_REFERENCE_SOURCE_TEMPLATE, ERR_UNKNOWN, ]; diff --git a/server/rust/metaobjects/src/lib.rs b/server/rust/metaobjects/src/lib.rs index 8fda8ae594..8e2c41bf57 100644 --- a/server/rust/metaobjects/src/lib.rs +++ b/server/rust/metaobjects/src/lib.rs @@ -17,6 +17,7 @@ pub mod naming; pub mod node; pub mod parser; pub mod providers; +pub mod reference; pub mod registry; pub mod rules_check; pub mod serializer; diff --git a/server/rust/metaobjects/src/reference.rs b/server/rust/metaobjects/src/reference.rs new file mode 100644 index 0000000000..94e820eb07 --- /dev/null +++ b/server/rust/metaobjects/src/reference.rs @@ -0,0 +1,52 @@ +//! Reference nodes: the top-level nodes only REFERENCE sources declare +//! (`{ "path": …, "reference": true }` in `.metaobjects/config.json`). +//! +//! They load, validate and resolve like any other node, so a prompt's `@responseRef` +//! can name a reply type another run generates; no generator here emits them. +//! Ported from the TypeScript SDK (`memory.ts`, `referenceNodesOf`). + +use std::collections::BTreeSet; + +use crate::errors::{ERR_REFERENCE_SOURCE_TEMPLATE, MetaError}; +use crate::node::{NodeId, Tree}; +use crate::validate::prompt::TYPE_TEMPLATE; + +/// The resolution keys of the top-level nodes every one of whose declaring files (every +/// overlay contributor included) is in `reference_ids`. One declaration in an ordinary +/// file makes the node the project's own. +/// +/// A `template.*` declared only in reference files is refused with +/// `ERR_REFERENCE_SOURCE_TEMPLATE`: a reference source holds shapes another run generates, +/// and nothing here could honour a prompt in one. +pub fn reference_nodes_of( + tree: &Tree, + root: NodeId, + reference_ids: &BTreeSet, +) -> Result, MetaError> { + let mut out = BTreeSet::new(); + if reference_ids.is_empty() { + return Ok(out); + } + // ADR-0039 sanctioned own: the metadata root has no super chain, so its own children + // are its top-level nodes. + for &id in tree.own_children(root) { + let node = tree.node(id); + let files = node.source.files(); + if files.is_empty() || !files.iter().all(|f| reference_ids.contains(f)) { + continue; + } + let key = tree.resolution_key(id); + if node.type_name == TYPE_TEMPLATE { + return Err(MetaError::at( + ERR_REFERENCE_SOURCE_TEMPLATE, + format!( + "template \"{key}\" is declared only in a reference source ({}). A reference source holds shapes another run generates; declare the prompt in one of the project's own sources, where its parser and payload are generated.", + files.join(", ") + ), + node.source.clone(), + )); + } + out.insert(key); + } + Ok(out) +} diff --git a/server/rust/metaobjects/src/sources.rs b/server/rust/metaobjects/src/sources.rs index 4651b7e671..53d26b82d0 100644 --- a/server/rust/metaobjects/src/sources.rs +++ b/server/rust/metaobjects/src/sources.rs @@ -28,7 +28,11 @@ pub const METADATA_EXTENSIONS: &[&str] = &[".json", ".yaml", ".yml"]; /// is stable, but resolve nowhere yet. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SourceSpec { + /// `{ "path": … }`. Path(String), + /// `{ "path": …, "reference": }`: the flag as written. `true` makes it a REFERENCE + /// source; `false` is an ordinary one that still orders by its own canonical text. + PathFlagged(String, bool), Resource(String), Package(String), } @@ -37,15 +41,24 @@ impl SourceSpec { /// The spec as the canonical JSON text TypeScript orders by: `{"path":"a"}`. pub fn canonical_json(&self) -> String { let (key, value) = match self { - SourceSpec::Path(v) => ("path", v), + SourceSpec::Path(v) | SourceSpec::PathFlagged(v, _) => ("path", v), SourceSpec::Resource(v) => ("resource", v), SourceSpec::Package(v) => ("package", v), }; + let flag = match self { + SourceSpec::PathFlagged(_, f) => format!(",\"reference\":{f}"), + _ => String::new(), + }; format!( - "{{\"{key}\":{}}}", + "{{\"{key}\":{}{flag}}}", serde_json::to_string(value).unwrap_or_default() ) } + + /// True for a `path` source declared `"reference": true`. + pub fn is_reference(&self) -> bool { + matches!(self, SourceSpec::PathFlagged(_, true)) + } } /// The default `sources`: exactly one `path` source, the default directory. @@ -60,6 +73,10 @@ pub struct ResolvedSource { pub file: PathBuf, /// The spec that contributed it (provenance for diagnostics). pub spec: SourceSpec, + /// True when EVERY spec that reaches this file is a reference source: the file loads so + /// references resolve against it, and the nodes only it declares are generated by nobody + /// here. One ordinary spec reaching the same file makes it the project's own. + pub reference: bool, } /// True when `name` ends in a metadata extension, matched case-insensitively. @@ -116,7 +133,9 @@ pub fn ordered_path_specs(specs: &[SourceSpec]) -> Result out.push((p.clone(), spec.clone())), + SourceSpec::Path(p) | SourceSpec::PathFlagged(p, _) => { + out.push((p.clone(), spec.clone())) + } SourceSpec::Resource(_) | SourceSpec::Package(_) => { let kind = if matches!(spec, SourceSpec::Resource(_)) { "resource" @@ -211,6 +230,8 @@ pub fn resolve_sources( ) -> Result, MetaError> { let ordered = ordered_path_specs(specs)?; let mut seen = HashSet::new(); + // A file is a reference file only when EVERY spec reaching it is a reference spec. + let mut ordinary: HashSet = HashSet::new(); let mut out = Vec::new(); for (path, spec) in ordered { let target = resolve_spec_path(config_dir, &path); @@ -230,13 +251,20 @@ pub fn resolve_sources( vec![target] }; for file in found { + if !spec.is_reference() { + ordinary.insert(file.clone()); + } if seen.insert(file.clone()) { out.push(ResolvedSource { file, spec: spec.clone(), + reference: false, }); } } } + for source in &mut out { + source.reference = !ordinary.contains(&source.file); + } Ok(out) } diff --git a/server/rust/metaobjects/src/validate/prompt.rs b/server/rust/metaobjects/src/validate/prompt.rs index f6261d9f52..9ff92dfb06 100644 --- a/server/rust/metaobjects/src/validate/prompt.rs +++ b/server/rust/metaobjects/src/validate/prompt.rs @@ -21,25 +21,25 @@ pub const ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS: &str = pub const ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED: &str = "ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED"; -const TYPE_TEMPLATE: &str = "template"; +pub const TYPE_TEMPLATE: &str = "template"; const TYPE_OBJECT: &str = "object"; const TYPE_FIELD: &str = "field"; const TYPE_SOURCE: &str = "source"; const TYPE_REQUIREMENT: &str = "requirement"; -const SUBTYPE_OUTPUT: &str = "output"; -const SUBTYPE_PROMPT: &str = "prompt"; +pub const SUBTYPE_OUTPUT: &str = "output"; +pub const SUBTYPE_PROMPT: &str = "prompt"; const OBJECT_SUBTYPE_VALUE: &str = "value"; const OBJECT_SUBTYPE_PROJECTION: &str = "projection"; -const FIELD_SUBTYPE_OBJECT: &str = "object"; -const ATTR_KIND: &str = "kind"; -const KIND_EMAIL: &str = "email"; -const ATTR_SUBJECT_REF: &str = "subjectRef"; -const ATTR_HTML_BODY_REF: &str = "htmlBodyRef"; -const ATTR_TEXT_REF: &str = "textRef"; -const ATTR_PAYLOAD_REF: &str = "payloadRef"; -const ATTR_RESPONSE_REF: &str = "responseRef"; -const ATTR_REQUIRED_SLOTS: &str = "requiredSlots"; -const ATTR_OBJECT_REF: &str = "objectRef"; +pub const FIELD_SUBTYPE_OBJECT: &str = "object"; +pub const ATTR_KIND: &str = "kind"; +pub const KIND_EMAIL: &str = "email"; +pub const ATTR_SUBJECT_REF: &str = "subjectRef"; +pub const ATTR_HTML_BODY_REF: &str = "htmlBodyRef"; +pub const ATTR_TEXT_REF: &str = "textRef"; +pub const ATTR_PAYLOAD_REF: &str = "payloadRef"; +pub const ATTR_RESPONSE_REF: &str = "responseRef"; +pub const ATTR_REQUIRED_SLOTS: &str = "requiredSlots"; +pub const ATTR_OBJECT_REF: &str = "objectRef"; const ATTR_STATUS: &str = "status"; const ATTR_IMPLEMENTED_BY: &str = "implementedBy"; const ATTR_SUPERSEDED_BY: &str = "supersededBy"; diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index 72079bc5d4..d558705820 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -249,7 +249,7 @@ fn label(tree: &Tree, node: NodeId) -> String { } /// A string-array attr read resolving; a bare string is one element. -pub(crate) fn string_list<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Vec<&'a str> { +pub fn string_list<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Vec<&'a str> { match tree.attr(node, attr) { Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(), Some(Value::String(s)) => vec![s.as_str()], @@ -257,7 +257,7 @@ pub(crate) fn string_list<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Vec<& } } -pub(crate) fn str_attr<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Option<&'a str> { +pub fn str_attr<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Option<&'a str> { tree.attr(node, attr).and_then(Value::as_str) } diff --git a/server/rust/metaobjects/tests/reference_source_conformance.rs b/server/rust/metaobjects/tests/reference_source_conformance.rs new file mode 100644 index 0000000000..97a7eb2a65 --- /dev/null +++ b/server/rust/metaobjects/tests/reference_source_conformance.rs @@ -0,0 +1,119 @@ +//! The reference-source gate: every case of the shared +//! `fixtures/reference-source-conformance/cases.json` must load (or fail) as every other +//! port does, and the set of reference nodes must match EXACTLY. +//! +//! A reference source's files load into the same root as every other source, so +//! `@responseRef` resolves against them; the top-level nodes only reference files declare +//! are the reference nodes. A `template.*` declared only in reference files is refused. + +use std::collections::BTreeSet; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU32, Ordering}; + +use metaobjects::collection::resolve_collection; +use metaobjects::loader::Loader; +use metaobjects::naming::NamingRegistry; +use metaobjects::providers::default_registry; +use metaobjects::reference::reference_nodes_of; +use serde_json::Value; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../../fixtures/reference-source-conformance/cases.json") +} + +/// A fresh directory under `$DEV_SCRATCH` (RAM) or the system temp dir, removed on drop. +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + static N: AtomicU32 = AtomicU32::new(0); + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!( + "mo-reference-source-{}-{}", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Load one case; `Ok` is the reference-node set, `Err` the first error code and message. +fn load(case: &Value) -> Result, (String, String)> { + let scratch = Scratch::new(); + let root = &scratch.0; + for (rel, content) in case["tree"].as_object().unwrap() { + let p = root.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, content.as_str().unwrap()).unwrap(); + } + std::fs::create_dir_all(root.join(".metaobjects")).unwrap(); + std::fs::write( + root.join(".metaobjects/config.json"), + serde_json::to_string(&case["config"]).unwrap(), + ) + .unwrap(); + + let fail = |e: metaobjects::MetaError| (e.code.to_string(), e.message); + let collection = + resolve_collection(root, Some(root), &NamingRegistry::builtin()).map_err(fail)?; + let (sources, read_errors) = collection.read_sources(); + if let Some(e) = read_errors.into_iter().next() { + return Err(fail(e)); + } + let mut registry = default_registry().expect("the built-in providers compose"); + registry.seal(); + let result = Loader::new(®istry).load_sources(&sources); + if let Some(e) = result.errors.into_iter().next() { + return Err(fail(e)); + } + reference_nodes_of(&result.tree, result.root, &collection.reference_ids).map_err(fail) +} + +#[test] +fn every_case_loads_as_pinned() { + let cases: Value = serde_json::from_str(&std::fs::read_to_string(corpus()).unwrap()).unwrap(); + let cases = cases["cases"].as_array().unwrap(); + assert!( + cases.len() >= 6, + "the corpus shrank to {} cases", + cases.len() + ); + let mut failed = Vec::new(); + for case in cases { + let name = case["name"].as_str().unwrap(); + let outcome = load(case); + let verdict = match (case.get("expectLoadError"), outcome) { + (Some(Value::String(code)), Err((got, _))) if &got == code => Ok(()), + (Some(code), Err((got, msg))) => Err(format!("failed with {got} not {code}: {msg}")), + (Some(code), Ok(_)) => Err(format!("loaded, expected {code}")), + (None, Err((got, msg))) => Err(format!("unexpected {got}: {msg}")), + (None, Ok(got)) => { + let want: BTreeSet = case["expectReference"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap().to_string()) + .collect(); + if got == want { + Ok(()) + } else { + Err(format!("reference nodes {got:?} != expected {want:?}")) + } + } + }; + if let Err(why) = verdict { + failed.push(format!("{name}: {why}")); + } + } + assert!(failed.is_empty(), "cases failed:\n{}", failed.join("\n")); +} diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index 1309104de3..ab24edaec0 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -38,6 +38,7 @@ import { scanForRemovedProps, type RemovedPropFinding } from "../lib/removed-pro import { replayRemedy } from "../lib/replay-remedy.js"; import { FileProvider, templateReferenceLine } from "../lib/file-provider.js"; import { derivePayloadFieldTree } from "../lib/payload-field-tree.js"; +import { responseFindings } from "../lib/response-verify.js"; import { loadMemoryOptionsFrom, loadMetaobjectsConfig, RemovedNamingConfigError, resolveGenCollection, resolveGenConfigDir } from "../lib/load-metaobjects-config.js"; import { collectionLoadOptions } from "../lib/collection-load-options.js"; import { schemaBuildOptions, type SchemaBuildOptions } from "../lib/schema-build-options.js"; @@ -144,6 +145,7 @@ import { WIRE_KEY_NULL_MEMBERS, WIRE_KEY_DURATIONS, type WireFormat, + type MetaData, } from "@metaobjectsdev/metadata"; import { verify, @@ -1280,12 +1282,31 @@ export async function verifyCommand( let checkedTemplates = 0; for (const tmpl of templates) { + // The reply (`@responseRef`): its field tree, and an xml prompt's tag contract + // against it. Independent of the payload check below, so it runs first. + let replyError = false; + for (const f of responseFindings(tmpl)) { + const line = `[${tmpl.name}] (reply) ${f.code}: ${f.path}`; + if (f.severity === "error") { + log.error(line); + errorCount++; + replyError = true; + } else { + log.warn(line); + warnCount++; + } + } + if (verifyTemplateBody(tmpl) || replyError) checkedTemplates++; + } + + // One template's body against its payload; true when the check engaged with it. + function verifyTemplateBody(tmpl: MetaData): boolean { // ADR-0039: effective attrs — @payloadRef may be inherited via an abstract template. const payloadRef = tmpl.attr(TEMPLATE_ATTR_PAYLOAD_REF); // A typeless/absent @payloadRef is a loader-schema concern, not verify's. Every // renderable template needs it (do NOT gate on @textRef — an @kind=email output // has no @textRef, and gating on it silently skipped email drift; #193). - if (typeof payloadRef !== "string") continue; + if (typeof payloadRef !== "string") return false; // @payloadRef must resolve to a loaded object.value (drives the field tree // every render-engine drift check runs against). @@ -1296,8 +1317,7 @@ export async function verifyCommand( `@payloadRef "${payloadRef}" did not resolve to a loaded object.value`, ); errorCount++; - checkedTemplates++; - continue; + return true; } // Collect every renderable mustache ref for this template + whether the @@ -1328,12 +1348,12 @@ export async function verifyCommand( if (typeof textRef === "string") refs = [{ label: "document", ref: textRef }]; } } else { - continue; // unknown subtype — loader-schema concern. + return false; // unknown subtype — loader-schema concern. } // No renderable body ref present — absent required refs are a loader-schema // concern, not verify's (mirrors the pre-#193 behavior for a bodyless template). - if (refs.length === 0) continue; + if (refs.length === 0) return false; // Slot/tag requirements are a template.prompt concept; the render-helper's // email/document gate does NOT apply them per part (they would false-flag a @@ -1381,7 +1401,7 @@ export async function verifyCommand( } } } - if (anyBodyChecked || anyErrorHere) checkedTemplates++; + return anyBodyChecked || anyErrorHere; } if (errorCount > 0) { diff --git a/server/typescript/packages/cli/src/lib/collection-load-options.ts b/server/typescript/packages/cli/src/lib/collection-load-options.ts index e615403a9c..206081f046 100644 --- a/server/typescript/packages/cli/src/lib/collection-load-options.ts +++ b/server/typescript/packages/cli/src/lib/collection-load-options.ts @@ -27,12 +27,14 @@ import type { Collection, LoadMemoryOptions } from "@metaobjectsdev/sdk"; */ export function collectionLoadOptions( collection: Collection, -): Required> { +): Required> { return { files: collection.files, fileIds: collection.fileIds, importedPackages: collection.importedPackages, importedNodes: collection.importedNodes, + // Reference sources: their nodes land in MetaRoot.referenceNodes, which codegen skips. + referenceIds: collection.referenceIds, // FR-043 — the shipped-library selection moved here from metaobjects.config.ts, so // it now rides the same helper as everything else the collection contributes. That // is the point of the move as much as the neutrality is: `libraries` used to be diff --git a/server/typescript/packages/cli/src/lib/response-verify.ts b/server/typescript/packages/cli/src/lib/response-verify.ts new file mode 100644 index 0000000000..7ffc3b8361 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/response-verify.ts @@ -0,0 +1,78 @@ +// What `meta verify --templates` checks about a prompt's REPLY (`@responseRef`). +// +// The loader already refuses a `@responseRef` that names nothing (`ERR_INVALID_TEMPLATE`), +// so this gate checks what loading cannot: +// +// - the reply type has a field tree a parser can read (`ERR_RESPONSE_UNRESOLVED`, an +// error: a reply with no fields parses into nothing); +// - for an `@responseFormat: xml` prompt, every `@requiredTags` tag — which the body is +// already held to (`ERR_OUTPUT_TAG_MISSING`) — names the reply type or one of its +// fields (`ERR_RESPONSE_TAG_UNDECLARED`, a warning). The body teaches the model those +// tags and the extractor reads the reply type's fields; this is the link between them, +// so a renamed reply field stops matching the tag the prompt still asks for. +// +// Pinned cross-port by fixtures/response-verify-conformance/. + +import { + type MetaData, + RESPONSE_FORMAT_XML, + TEMPLATE_ATTR_REQUIRED_TAGS, + TEMPLATE_ATTR_RESPONSE_FORMAT, + TEMPLATE_ATTR_RESPONSE_REF, + TEMPLATE_SUBTYPE_PROMPT, + TYPE_TEMPLATE, + refTarget, +} from "@metaobjectsdev/metadata"; +import type { PayloadField } from "@metaobjectsdev/render"; +import { derivePayloadFieldTree } from "./payload-field-tree.js"; + +/** A responding prompt's `@responseRef` names no loaded value shape with fields. */ +export const ERR_RESPONSE_UNRESOLVED = "ERR_RESPONSE_UNRESOLVED"; +/** An xml prompt's `@requiredTags` tag names neither the reply type nor a reply field (warning). */ +export const ERR_RESPONSE_TAG_UNDECLARED = "ERR_RESPONSE_TAG_UNDECLARED"; + +export interface ResponseFinding { + readonly code: string; + /** The `@responseRef` value, or the offending tag. */ + readonly path: string; + readonly severity: "error" | "warning"; +} + +function fieldNames(tree: readonly PayloadField[], out: Set): Set { + for (const f of tree) { + out.add(f.name); + if (f.fields !== undefined) fieldNames(f.fields, out); + } + return out; +} + +function shortName(name: string): string { + const i = name.lastIndexOf("::"); + return i === -1 ? name : name.slice(i + 2); +} + +/** + * The reply findings for one template. Empty for anything that is not a `template.prompt` + * carrying `@responseRef` — a prompt that does not elicit a typed reply has nothing here. + */ +export function responseFindings(tmpl: MetaData): ResponseFinding[] { + if (tmpl.type !== TYPE_TEMPLATE || tmpl.subType !== TEMPLATE_SUBTYPE_PROMPT) return []; + // ADR-0039: effective attrs — a prompt may inherit @responseRef / @responseFormat / @requiredTags. + const responseRef = tmpl.attr(TEMPLATE_ATTR_RESPONSE_REF); + if (typeof responseRef !== "string") return []; + + const reply = refTarget(tmpl, TEMPLATE_ATTR_RESPONSE_REF); + const tree = derivePayloadFieldTree(reply); + if (reply === undefined || tree.length === 0) { + return [{ code: ERR_RESPONSE_UNRESOLVED, path: responseRef, severity: "error" }]; + } + + const format = tmpl.attr(TEMPLATE_ATTR_RESPONSE_FORMAT); + if (typeof format !== "string" || format.toLowerCase() !== RESPONSE_FORMAT_XML) return []; + const tags = tmpl.attr(TEMPLATE_ATTR_REQUIRED_TAGS); + if (!Array.isArray(tags)) return []; + const known = fieldNames(tree, new Set([shortName(reply.name)])); + return tags + .filter((t): t is string => typeof t === "string" && !known.has(t)) + .map((t) => ({ code: ERR_RESPONSE_TAG_UNDECLARED, path: t, severity: "warning" as const })); +} diff --git a/server/typescript/packages/cli/test/response-verify-conformance.test.ts b/server/typescript/packages/cli/test/response-verify-conformance.test.ts new file mode 100644 index 0000000000..fa666fdd2b --- /dev/null +++ b/server/typescript/packages/cli/test/response-verify-conformance.test.ts @@ -0,0 +1,49 @@ +// Runs the shared reply-check corpus (fixtures/response-verify-conformance/) against the +// TypeScript reference: what `meta verify --templates` reports about each prompt's +// `@responseRef`. Every port that ships a template gate runs this same file. +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { TYPE_TEMPLATE } from "@metaobjectsdev/metadata"; +import { loadMemory } from "@metaobjectsdev/sdk"; +import { responseFindings } from "../src/lib/response-verify.js"; + +interface Finding { + readonly template: string; + readonly code: string; + readonly path: string; + readonly severity: string; +} +interface Case { + readonly name: string; + readonly metadata: unknown; + readonly expect: readonly Finding[]; +} + +const CORPUS = resolve(import.meta.dir, "../../../../../fixtures/response-verify-conformance/cases.json"); +const cases = (JSON.parse(await readFile(CORPUS, "utf8")) as { cases: Case[] }).cases; +const scratch = await mkdtemp(join(process.env["DEV_SCRATCH"] ?? tmpdir(), "mo-reply-verify-")); +afterAll(() => rm(scratch, { recursive: true, force: true })); + +const order = (a: Finding, b: Finding): number => + `${a.template}\0${a.code}\0${a.path}`.localeCompare(`${b.template}\0${b.code}\0${b.path}`); + +describe("response-verify-conformance", () => { + test("the corpus is not empty", () => { + expect(cases.length).toBeGreaterThan(0); + }); + + for (const c of cases) { + test(c.name, async () => { + const file = join(scratch, `${c.name}.json`); + await writeFile(file, JSON.stringify(c.metadata)); + const root = await loadMemory(scratch, { files: [file] }); + const got: Finding[] = root + .children() + .filter((t) => t.type === TYPE_TEMPLATE) + .flatMap((t) => responseFindings(t).map((f) => ({ template: t.name, ...f }))); + expect(got.sort(order)).toEqual([...c.expect].sort(order)); + }); + } +}); diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index 97626d912a..105edb2239 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -474,7 +474,16 @@ export async function runGen(opts: RunGenOpts): Promise { const afterEntityFilter = entityFilter ? allObjects.filter((o) => entityFilter.includes(o.name)) : allObjects; - const scope = opts.scope; + // Reference nodes (declared only by `{ "path": …, "reference": true }` sources) load + // so references resolve against them, and another run owns their generated types — so + // they leave the selection here, at the single choke point, and `select` (which every + // whole-root render reads) excludes them too. With no reference source this is + // `opts.scope` unchanged. + const referenceNodes = root.referenceNodes; + const scope: ((fqn: string) => boolean) | undefined = + referenceNodes.size === 0 + ? opts.scope + : (fqn: string): boolean => !referenceNodes.has(fqn) && (opts.scope?.(fqn) ?? true); const filtered = scope ? afterEntityFilter.filter((o) => scope(o.resolutionKey())) : afterEntityFilter; @@ -501,6 +510,10 @@ export async function runGen(opts: RunGenOpts): Promise { reason = "root has no object children"; } else if (afterEntityFilter.length === 0) { reason = "no object children match the provided entityFilter"; + } else if (afterEntityFilter.every((o) => referenceNodes.has(o.resolutionKey()))) { + // Only reference nodes remained: name the reference sources, not a `scope` the + // project may never have written. + reason = "every object is declared only in a reference source"; } else { reason = "no object children match the configured scope"; } diff --git a/server/typescript/packages/codegen-ts/test/reference-nodes-gen.test.ts b/server/typescript/packages/codegen-ts/test/reference-nodes-gen.test.ts new file mode 100644 index 0000000000..13e5df4b51 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/reference-nodes-gen.test.ts @@ -0,0 +1,63 @@ +// Reference nodes (`{ "path": …, "reference": true }` sources) load so a prompt's +// `@responseRef` resolves, and no generator emits a type for them: another run owns those +// types. The responding prompt's parser still emits, naming the reply type as usual. +// Corpus for the load half: fixtures/reference-source-conformance/. +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdtempSync, readdirSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative } from "node:path"; +import { InMemoryStringSource, MetaDataLoader } from "@metaobjectsdev/metadata"; +import { runGen } from "../src/runner.js"; +import { defineConfig } from "../src/metaobjects-config.js"; +import { entityFile } from "../src/generators/entity-file.js"; +import { outputParser } from "../src/generators/output-parser-file.js"; +import { removeTree } from "../src/scratch-dir.js"; + +const TEMP: string[] = []; +afterAll(() => TEMP.forEach(removeTree)); + +const META = JSON.stringify({ "metadata.root": { package: "acme::support", children: [ + { "object.value": { name: "SupportRequest", children: [{ "field.string": { name: "question" } }] } }, + { "object.value": { name: "AnswerSource", children: [{ "field.string": { name: "url" } }] } }, + { "object.value": { name: "SupportAnswer", children: [ + { "field.string": { name: "text" } }, + { "field.object": { name: "source", "@objectRef": "acme::support::AnswerSource" } }, + ] } }, + { "template.prompt": { name: "SupportAnswerPrompt", "@payloadRef": "acme::support::SupportRequest", + "@responseRef": "acme::support::SupportAnswer", "@textRef": "support/answer", "@format": "text" } }, +] } }); + +async function gen(reference: readonly string[]): Promise> { + const res = await new MetaDataLoader().load([new InMemoryStringSource(META)]); + expect(res.errors).toEqual([]); + res.root.referenceNodes = new Set(reference); + const dir = mkdtempSync(join(process.env["DEV_SCRATCH"] ?? tmpdir(), "mo-ref-gen-")); + TEMP.push(dir); + const result = await runGen({ + config: defineConfig({ outDir: dir, extStyle: "js", dbImport: "../db", dialect: "postgres", generators: [entityFile(), outputParser()] }), + metadata: res.root, + }); + expect(result.conflicts).toEqual([]); + const out = new Map(); + for (const e of readdirSync(dir, { recursive: true, withFileTypes: true })) { + if (e.isFile()) out.set(relative(dir, join(e.parentPath, e.name)), readFileSync(join(e.parentPath, e.name), "utf8")); + } + return out; +} + +describe("reference nodes in codegen", () => { + test("a reference reply type emits no type of its own, and its parser still emits", async () => { + const all = await gen([]); + const ref = await gen(["acme::support::SupportAnswer", "acme::support::AnswerSource"]); + const has = (m: Map, n: string) => [...m.keys()].some((k) => k.endsWith(`${n}.ts`)); + expect(has(all, "SupportAnswer")).toBe(true); + expect(has(all, "AnswerSource")).toBe(true); + expect(has(ref, "SupportAnswer")).toBe(false); + expect(has(ref, "AnswerSource")).toBe(false); + expect(has(ref, "SupportRequest")).toBe(true); + const parser = [...ref.entries()].find(([k]) => k.endsWith("SupportAnswerPrompt.response.ts")); + expect(parser).toBeDefined(); + // The parser names the reply type the owning run generates, exactly as it would here. + expect(parser![1]).toBe(all.get(parser![0])!); + }); +}); diff --git a/server/typescript/packages/metadata/src/errors.ts b/server/typescript/packages/metadata/src/errors.ts index 5af954eb22..8ad5c605c8 100644 --- a/server/typescript/packages/metadata/src/errors.ts +++ b/server/typescript/packages/metadata/src/errors.ts @@ -333,6 +333,9 @@ export const ERROR_CODES = [ // Phase-1 metadata-source-resolution — no metadata collection was discovered: // no config declaring sources, and no default metaobjects/ directory. "ERR_COLLECTION_NOT_FOUND", + // Phase-1 metadata-source-resolution — a template.* is declared only in + // reference sources (`"reference": true`), whose nodes no generator emits. + "ERR_REFERENCE_SOURCE_TEMPLATE", // FR-043 — `.metaobjects/config.json`'s `libraries` names a shipped library or layer // this build does not have. A HUMAN typed it, so it is refused with the available // tokens rather than skipped: skipped, it resurfaces as ERR_UNRESOLVED_SUPER against diff --git a/server/typescript/packages/metadata/src/shared/meta-root.ts b/server/typescript/packages/metadata/src/shared/meta-root.ts index 0f13a21c63..2b13816100 100644 --- a/server/typescript/packages/metadata/src/shared/meta-root.ts +++ b/server/typescript/packages/metadata/src/shared/meta-root.ts @@ -56,6 +56,14 @@ export class MetaRoot extends MetaData { */ rulesSettings: RulesSettings = DEFAULT_RULES_SETTINGS; + /** + * The resolution keys of the top-level nodes only REFERENCE sources declare + * (`{ "path": …, "reference": true }` in `.metaobjects/config.json`). They load and + * resolve like any other node; no generator emits them, because another run owns them. + * Set by the project-aware load; empty for a tree loaded with no reference source. + */ + referenceNodes: ReadonlySet = new Set(); + /** Object entities defined at this root level. */ objects(): MetaObject[] { return this.cached("objects", () => diff --git a/server/typescript/packages/sdk/src/collection.ts b/server/typescript/packages/sdk/src/collection.ts index 004e4c23e1..bea914d6be 100644 --- a/server/typescript/packages/sdk/src/collection.ts +++ b/server/typescript/packages/sdk/src/collection.ts @@ -10,7 +10,7 @@ // today (`DEFAULT_SOURCES` in `sources.ts`); a project that declares // `sources` can point anywhere. No other call site may assume the directory // name — this is where that assumption is allowed to live, exactly once. -import { dirname, extname, join, resolve } from "node:path"; +import { dirname, extname, join, relative, resolve, sep } from "node:path"; import { readdir, readFile } from "node:fs/promises"; import { ParseError, @@ -51,6 +51,9 @@ import { type SourceSpec, } from "./sources.js"; +/** The `FileSource` id prefix of a reference source's file (`ref:`). */ +export const REFERENCE_ID_PREFIX = "ref:"; + export interface Collection { /** Directory whose config declared this collection (or the resolved start * directory, when nothing was discovered and the default applies). */ @@ -127,6 +130,12 @@ export interface Collection { * contributed carries provenance naming the dependency rather than a filename * that reads like a local file. */ readonly fileIds: ReadonlyMap; + /** The `FileSource` ids of the project's REFERENCE files (`{ "path": …, "reference": true }` + * sources): `ref:`, also present in {@link fileIds}. A top-level node + * every one of whose declarations came from these ids is a reference node — it loads and + * resolves, and no generator here emits it (`MetaRoot.referenceNodes`). Empty when the + * project declares no reference source. */ + readonly referenceIds: ReadonlySet; /** FR-023 — the sorted union of every dependency's `packages`: THE exclusion * key (DESIGN §11.5). Package-keyed, not node-keyed. */ readonly importedPackages: readonly string[]; @@ -445,6 +454,14 @@ export async function resolveCollection( id: d.sourceId, })); const ownFiles = ownSources.map((s) => s.file); + // A reference file loads under `ref:` — a prefixed id, like a + // dependency artifact's `dep:`, so its provenance can never be mistaken for (or collide + // by basename with) one of the project's own files. + const referenceFileIds = new Map( + ownSources + .filter((s) => s.reference === true) + .map((s): [string, string] => [s.file, `${REFERENCE_ID_PREFIX}${relative(configDir, s.file).split(sep).join("/")}`]), + ); const scope = compileScope(toScope(scopeSpec)); const inCoverage = (fqn: string): boolean => { @@ -477,7 +494,11 @@ export async function resolveCollection( foreignKeyIndexes, foreignKeyTargets, handEdits, - fileIds: new Map(dependencies.map((d) => [d.artifactPath, d.sourceId])), + fileIds: new Map([ + ...dependencies.map((d): [string, string] => [d.artifactPath, d.sourceId]), + ...referenceFileIds, + ]), + referenceIds: new Set(referenceFileIds.values()), importedPackages: [...importedPackages].sort(), importedNodes, imported, diff --git a/server/typescript/packages/sdk/src/config.ts b/server/typescript/packages/sdk/src/config.ts index c33034a007..bfd1ce0f89 100644 --- a/server/typescript/packages/sdk/src/config.ts +++ b/server/typescript/packages/sdk/src/config.ts @@ -148,7 +148,9 @@ const MigrateBlock = z.object({ * schema. */ const SourceSpecSchema = z.union([ - z.object({ path: z.string().min(1) }).strict(), + // `reference: true` — the files load so references resolve against them, and the + // nodes only they declare are generated by nobody here (another run owns them). + z.object({ path: z.string().min(1), reference: z.boolean().optional() }).strict(), z.object({ resource: z.string().min(1) }).strict(), z.object({ package: z.string().min(1) }).strict(), ]); diff --git a/server/typescript/packages/sdk/src/index.ts b/server/typescript/packages/sdk/src/index.ts index 04859f3980..20299be42d 100644 --- a/server/typescript/packages/sdk/src/index.ts +++ b/server/typescript/packages/sdk/src/index.ts @@ -99,7 +99,7 @@ export type { ForgeType, ForgeAttr } from "./forge-types.js"; // Memory loader — read a project's resolved metadata into a MetaData tree. // Where those files come from is `resolveCollection`'s decision (below), which // `loadMemory` calls when the caller supplies no explicit file set. -export { loadErrors, loadMemory, loadMemoryWithFindings, unknownAttributeFindings, defaultLoadMemoryProviders } from "./memory.js"; +export { loadErrors, loadMemory, loadMemoryWithFindings, unknownAttributeFindings, defaultLoadMemoryProviders, referenceNodesOf, ERR_REFERENCE_SOURCE_TEMPLATE } from "./memory.js"; export type { LoadMemoryOptions } from "./memory.js"; // Default project layout — the DEFAULT value of `sources` (applied by @@ -121,7 +121,7 @@ export { discoverCollectionRoot, resolveConfigDir } from "./discovery.js"; export type { DiscoveredRoot } from "./discovery.js"; // Collection — the single authority on where a project's metadata lives -export { resolveCollection } from "./collection.js"; +export { resolveCollection, REFERENCE_ID_PREFIX } from "./collection.js"; export type { Collection } from "./collection.js"; // DEPRECATED (removed in 2.0) — workspace discovery over the v0.3 package.meta.json diff --git a/server/typescript/packages/sdk/src/memory.ts b/server/typescript/packages/sdk/src/memory.ts index a9c2baf8f9..e427472fdd 100644 --- a/server/typescript/packages/sdk/src/memory.ts +++ b/server/typescript/packages/sdk/src/memory.ts @@ -7,7 +7,9 @@ import { ParseError, TYPE_OBJECT, TYPE_REQUIREMENT, + TYPE_TEMPLATE, type ErrorSource, + type MetaData, type LoaderError, type LoadResult, type TypeRegistry, @@ -99,6 +101,13 @@ export interface LoadMemoryOptions { * declaration in the dependency's package (refused). */ importedNodes?: ReadonlySet; + /** + * The `FileSource` ids of the project's reference files + * (`resolveCollection(...).referenceIds`). A top-level node all of whose declarations + * come from these ids lands in `MetaRoot.referenceNodes`, which every generator skips. + * Read only on the caller-supplied-`files` arm, same as {@link fileIds}. + */ + referenceIds?: ReadonlySet; /** * MetaObjects-shipped library packages to load ALONGSIDE the project's own files * (e.g. `["ai"]` for `metaobjects::ai::LlmCallBase`). Prepended, so an @@ -220,7 +229,7 @@ type RawLoad = Awaited>; /** The checks {@link loadMemory} makes after the loader, and the root they leave. */ function finishLoad(run: RawLoad): MetaRoot { - const { result, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, enumDefaults, apiPagination, apiUnknownFields, rulesSettings } = run; + const { result, importedPackages, importedNodes, referenceIds, libraries, physicalNaming, wireFormat, enumDefaults, apiPagination, apiUnknownFields, rulesSettings } = run; if (result.errors.length > 0) { const first = result.errors[0]!; @@ -238,6 +247,9 @@ function finishLoad(run: RawLoad): MetaRoot { // copy, still opted in) and one it does not (a new node in someone else's package). refuseLibraryPackageMisuse(result.root, libraries); + if (referenceIds !== undefined && referenceIds.size > 0) { + result.root.referenceNodes = referenceNodesOf(result.root, referenceIds); + } if (physicalNaming !== undefined) result.root.physicalNaming = physicalNaming; if (wireFormat !== undefined) result.root.wireFormat = wireFormat; if (enumDefaults !== undefined) result.root.enumDefaults = enumDefaults; @@ -327,6 +339,7 @@ async function loadCollectionRaw( registry: TypeRegistry; importedPackages: readonly string[] | undefined; importedNodes: ReadonlySet | undefined; + referenceIds: ReadonlySet | undefined; libraries: readonly string[] | undefined; physicalNaming: PhysicalNaming | undefined; wireFormat: WireFormat | undefined; @@ -359,6 +372,7 @@ async function loadCollectionRaw( let fileIds: ReadonlyMap | undefined; let importedPackages: readonly string[] | undefined; let importedNodes: ReadonlySet | undefined; + let referenceIds: ReadonlySet | undefined; let libraries: readonly string[] | undefined = options?.libraries; let physicalNaming: PhysicalNaming | undefined = options?.physicalNaming; let wireFormat: WireFormat | undefined = options?.wireFormat; @@ -371,6 +385,7 @@ async function loadCollectionRaw( fileIds = options.fileIds; importedPackages = options.importedPackages; importedNodes = options.importedNodes; + referenceIds = options.referenceIds; } else { // FR-023: on this arm the COLLECTION is the authority for all of these, never // the caller — an embedder calling `loadMemory(repoRoot)` with no `files` @@ -383,6 +398,7 @@ async function loadCollectionRaw( fileIds = collection.fileIds; importedPackages = collection.importedPackages; importedNodes = collection.importedNodes; + referenceIds = collection.referenceIds; libraries ??= collection.libraries; physicalNaming ??= collection.physicalNaming; wireFormat ??= collection.wireFormat; @@ -415,7 +431,7 @@ async function loadCollectionRaw( return id === undefined ? new FileSource(p) : new FileSource(p, { id }); }), ]); - return { result, registry, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, enumDefaults, apiPagination, apiUnknownFields, rulesSettings }; + return { result, registry, importedPackages, importedNodes, referenceIds, libraries, physicalNaming, wireFormat, enumDefaults, apiPagination, apiUnknownFields, rulesSettings }; } /** Every source file that contributed to a node, across the envelope variants that @@ -555,3 +571,34 @@ function refuseUnownedPackages( ); } } + +/** + * The top-level nodes only reference files declare: every file in a node's provenance + * (`source.files`, which lists every contributor of a merged overlay) is one of + * `referenceIds`. One declaration in an ordinary file makes the node the project's own. + * + * A `template.*` here is refused (`ERR_REFERENCE_SOURCE_TEMPLATE`): a reference source + * carries shapes another run generates, and nothing here could honour a prompt in one — + * its parser and payload type would be generated by nobody. + */ +export function referenceNodesOf(root: MetaData, referenceIds: ReadonlySet): ReadonlySet { + const out = new Set(); + // ADR-0039: own — the metadata root has no super chain, so its own children are its nodes. + for (const node of root.ownChildren()) { + const files = node.source !== undefined && "files" in node.source ? node.source.files : []; + if (files.length === 0 || !files.every((f) => referenceIds.has(f))) continue; + if (node.type === TYPE_TEMPLATE) { + throw new ParseError( + `template "${node.resolutionKey()}" is declared only in a reference source (${files.join(", ")}). ` + + `A reference source holds shapes another run generates; declare the prompt in one of the ` + + `project's own sources, where its parser and payload are generated.`, + { code: ERR_REFERENCE_SOURCE_TEMPLATE, source: node.source! }, + ); + } + out.add(node.resolutionKey()); + } + return out; +} + +/** A `template.*` is declared only in a reference source. */ +export const ERR_REFERENCE_SOURCE_TEMPLATE = "ERR_REFERENCE_SOURCE_TEMPLATE"; diff --git a/server/typescript/packages/sdk/src/sources.ts b/server/typescript/packages/sdk/src/sources.ts index 80328eef59..70fe312db5 100644 --- a/server/typescript/packages/sdk/src/sources.ts +++ b/server/typescript/packages/sdk/src/sources.ts @@ -29,7 +29,7 @@ import { DEFAULT_METADATA_DIR, listMetadataFiles } from "./metadata-files.js"; * the config shape is stable across phases; only `path` resolves in phase 1 — * `resource`/`package` throw `ERR_SOURCE_KIND_UNSUPPORTED`. */ export type SourceSpec = - | { readonly path: string } + | { readonly path: string; readonly reference?: boolean | undefined } | { readonly resource: string } | { readonly package: string }; @@ -48,6 +48,11 @@ export interface ResolvedSource { * set alongside `dependency`. Absent for own files, which keep the default * `basename(path)`. */ readonly id?: string; + /** Set when every declared spec that reaches this file is a REFERENCE source + * (`{ "path": …, "reference": true }`): the file loads so references resolve + * against it, and the nodes only it declares are generated by nobody here. One + * ordinary spec reaching the same file makes it the project's own. */ + readonly reference?: true; } /** Used when `sources` is absent or empty in `.metaobjects/config.json`. A @@ -67,7 +72,7 @@ export const DEFAULT_SOURCES: readonly SourceSpec[] = [{ path: DEFAULT_METADATA_ * asserting so one call both validates and narrows: an `asserts` signature has * to be re-invoked wherever TypeScript's control-flow analysis cannot carry the * narrowing, which is a language workaround masquerading as a second check. */ -function toPathSpec(spec: SourceSpec): { readonly path: string } { +function toPathSpec(spec: SourceSpec): { readonly path: string; readonly reference?: boolean | undefined } { if ("path" in spec) return spec; const kind = "resource" in spec ? "resource" : "package"; throw new ParseError( @@ -92,7 +97,7 @@ function toPathSpec(spec: SourceSpec): { readonly path: string } { * specs and must use this identical ordering; a second sort would be a second * definition of "canonical". */ -export function orderedPathSpecs(specs: readonly SourceSpec[]): { readonly path: string }[] { +export function orderedPathSpecs(specs: readonly SourceSpec[]): { readonly path: string; readonly reference?: boolean | undefined }[] { return specs.map(toPathSpec).sort((a, b) => { const [ja, jb] = [JSON.stringify(a), JSON.stringify(b)]; return ja < jb ? -1 : ja > jb ? 1 : 0; @@ -149,6 +154,8 @@ export async function resolveSources( // order above survives to the caller. First contributor wins a shared file, // which is content-determined because `ordered` is. const byFile = new Map(); + // A file is a reference file only when EVERY spec reaching it is a reference spec. + const ordinary = new Set(); for (const spec of ordered) { const target = resolveSpecPath(configDir, spec); @@ -163,8 +170,11 @@ export async function resolveSources( const found = stats.isDirectory() ? await listMetadataFiles(target) : [target]; for (const file of found) { if (!byFile.has(file)) byFile.set(file, spec); + if (spec.reference !== true) ordinary.add(file); } } - return [...byFile].map(([file, spec]) => ({ file, spec })); + return [...byFile].map(([file, spec]) => + ordinary.has(file) ? { file, spec } : { file, spec, reference: true as const }, + ); } diff --git a/server/typescript/packages/sdk/test/reference-source-conformance.test.ts b/server/typescript/packages/sdk/test/reference-source-conformance.test.ts new file mode 100644 index 0000000000..690b233bf5 --- /dev/null +++ b/server/typescript/packages/sdk/test/reference-source-conformance.test.ts @@ -0,0 +1,52 @@ +// Runs the shared reference-source corpus (fixtures/reference-source-conformance/) +// against the TypeScript reference implementation. Every port ships an equivalent +// runner reading this same file; see its README for the case schema. +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { loadMemory } from "../src/memory.js"; + +interface Case { + readonly name: string; + readonly tree: Record; + readonly config: unknown; + readonly expectReference?: readonly string[]; + readonly expectLoadError?: string; +} + +const CORPUS = resolve(import.meta.dir, "../../../../../fixtures/reference-source-conformance/cases.json"); +const cases = (JSON.parse(await readFile(CORPUS, "utf8")) as { cases: Case[] }).cases; +const scratch = await mkdtemp(join(process.env["DEV_SCRATCH"] ?? tmpdir(), "mo-ref-src-")); +afterAll(() => rm(scratch, { recursive: true, force: true })); + +async function materialize(c: Case): Promise { + const root = join(scratch, c.name); + for (const [rel, content] of Object.entries(c.tree)) { + await mkdir(dirname(join(root, rel)), { recursive: true }); + await writeFile(join(root, rel), content); + } + await mkdir(join(root, ".metaobjects"), { recursive: true }); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify(c.config)); + return root; +} + +describe("reference-source-conformance", () => { + test("the corpus is not empty", () => { + expect(cases.length).toBeGreaterThan(0); + }); + + for (const c of cases) { + test(c.name, async () => { + const root = await materialize(c); + // The project-aware arm: loadMemory resolves the collection itself, reference ids included. + const load = loadMemory(root); + if (c.expectLoadError !== undefined) { + await expect(load).rejects.toMatchObject({ code: c.expectLoadError }); + return; + } + const loaded = await load; + expect([...loaded.referenceNodes].sort()).toEqual([...(c.expectReference ?? [])].sort()); + }); + } +}); diff --git a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md index d64faa96d6..44d7754285 100644 --- a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md +++ b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md @@ -147,9 +147,13 @@ so they are not re-derived. (`docs/features/cli.md`): exit 0 on success, 1 when the run failed (a model that does not load, a refused file, drift), 2 for a usage error; an unknown flag names the flags the command takes. `verify` is the one verb of ADR-0021 D2, and `--codegen` is the only gate this port ships, so a - bare `verify` runs it. `--db`, `--templates` and `--deps` exit 2 and say where that check lives. + bare `verify` runs it. *(Gates superseded by Amendment 6: the port now ships `verify --templates` + too, and a bare `verify` runs the codegen, template and rules gates.)* `--db`, `--templates` and + `--deps` exit 2 and say where that check lives. *(The `--templates` refusal is superseded by + Amendment 6; `--db` and `--deps` still exit 2.)* This corrects Decision 6, which listed `fmt`: the command today is `init`, `gen`, `verify --codegen` and `eject`. `fmt` and the template gate come with the phases that need them. + *(The template gate has arrived — Amendment 6; there is still no `fmt`.)* **No `migrate` and no `verify --db`, permanently** (ADR-0015): `init` and `--help` both say that the schema is the Node `meta` tool's. 5. **An owned generator is a crate the project builds.** Rust is compiled, so a generator cannot @@ -324,3 +328,18 @@ replaced; the first half stands. `docs/ports/rust.md` says this where it describes the owned crate. The T7-RS row adds the name-level snapshot test. + +## Amendment 6: the template gate shipped (2026-11-25) + +Ruling 4 said `--codegen` was the only gate the port ships, that `--templates` exits 2, and that +`fmt` and the template gate "come with the phases that need them". The template phase has arrived +without a template *generator*: `cargo meta +verify --templates` checks every `template.*` body (Mustache, under `prompts/` or `--prompts `) +against its payload value object and checks each prompt's `@responseRef` reply, through the new +`verify` module of `metaobjects-render`. A bare `verify` runs the codegen, template and rules gates; +`--codegen` or `--templates` alone runs that one gate. `--db` and `--deps` still exit 2, and there is +still no `fmt`, no `migrate`, no `verify --db` (ADR-0015) and no template generator. A Jinja body is +refused (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`), as ruling 6 already stated. The port runs +`fixtures/verify-conformance/` (all 45 cases), `fixtures/response-verify-conformance/` (all 7) and +`fixtures/reference-source-conformance/` (all 6); `docs/features/cli.md` and `docs/ports/rust.md` +carry the command surface.