From 44d0927fd1bf0aae35189862c8ce7d4f8cfc4755 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 11:59:34 -0500 Subject: [PATCH 1/5] feat(rust): add the metaobjects-render crate: prompt render, reply parser and output-format fragment The Rust port's prompt pillar, as a fourth publishable crate: - render: a template.* body rendered over a JSON payload on mustache-ng, with partials expanded ahead of time, per-format escaping, derived has and -last accessors and a fail-closed maxChars budget. Passes render-conformance byte-identically. - extract: the FR-010/011 tolerant reply parser (strip, locate, forgiving JSON and XML readers, coercion, classification). Passes all 58 extract-conformance cases. - prompt: the output-format fragment in guide, inline and exampleOnly styles. Passes all 17 output-prompt-conformance cases, with the extract round trip. Rust joins the extract FieldKind parity gate. The port and conformance docs say what runs, and what prompt codegen is still to come. --- docs/CONFORMANCE.md | 8 +- docs/ports/rust.md | 16 +- .../expected-field-kinds.json | 3 +- scripts/check-extract-field-kinds.mjs | 8 + server/rust/Cargo.lock | 26 + server/rust/Cargo.toml | 2 +- server/rust/metaobjects-render/Cargo.toml | 24 + server/rust/metaobjects-render/LICENSE | 202 +++++++ server/rust/metaobjects-render/README.md | 24 + .../rust/metaobjects-render/src/accessors.rs | 122 ++++ .../rust/metaobjects-render/src/escapers.rs | 165 ++++++ .../metaobjects-render/src/extract/coerce.rs | 286 +++++++++ .../metaobjects-render/src/extract/engine.rs | 295 ++++++++++ .../src/extract/json_reader.rs | 342 +++++++++++ .../metaobjects-render/src/extract/locate.rs | 192 +++++++ .../metaobjects-render/src/extract/mod.rs | 24 + .../src/extract/normalize.rs | 77 +++ .../metaobjects-render/src/extract/strip.rs | 160 ++++++ .../metaobjects-render/src/extract/types.rs | 451 +++++++++++++++ .../src/extract/xml_reader.rs | 542 ++++++++++++++++++ server/rust/metaobjects-render/src/lib.rs | 24 + server/rust/metaobjects-render/src/prompt.rs | 371 ++++++++++++ server/rust/metaobjects-render/src/render.rs | 395 +++++++++++++ server/rust/metaobjects-render/src/tags.rs | 213 +++++++ .../tests/extract_conformance.rs | 241 ++++++++ .../tests/output_prompt_conformance.rs | 176 ++++++ .../tests/render_conformance.rs | 83 +++ 27 files changed, 4461 insertions(+), 11 deletions(-) create mode 100644 server/rust/metaobjects-render/Cargo.toml create mode 100644 server/rust/metaobjects-render/LICENSE create mode 100644 server/rust/metaobjects-render/README.md create mode 100644 server/rust/metaobjects-render/src/accessors.rs create mode 100644 server/rust/metaobjects-render/src/escapers.rs create mode 100644 server/rust/metaobjects-render/src/extract/coerce.rs create mode 100644 server/rust/metaobjects-render/src/extract/engine.rs create mode 100644 server/rust/metaobjects-render/src/extract/json_reader.rs create mode 100644 server/rust/metaobjects-render/src/extract/locate.rs create mode 100644 server/rust/metaobjects-render/src/extract/mod.rs create mode 100644 server/rust/metaobjects-render/src/extract/normalize.rs create mode 100644 server/rust/metaobjects-render/src/extract/strip.rs create mode 100644 server/rust/metaobjects-render/src/extract/types.rs create mode 100644 server/rust/metaobjects-render/src/extract/xml_reader.rs create mode 100644 server/rust/metaobjects-render/src/lib.rs create mode 100644 server/rust/metaobjects-render/src/prompt.rs create mode 100644 server/rust/metaobjects-render/src/render.rs create mode 100644 server/rust/metaobjects-render/src/tags.rs create mode 100644 server/rust/metaobjects-render/tests/extract_conformance.rs create mode 100644 server/rust/metaobjects-render/tests/output_prompt_conformance.rs create mode 100644 server/rust/metaobjects-render/tests/render_conformance.rs diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 91b7e8f5df..d564c614ea 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -83,7 +83,9 @@ cases); `naming-conformance` (all of it); `codegen-skip-conformance` (ADR-0064), about templates and one about the three-way merge, are named with their reason in its runner); `validation-conformance`, every case, through the generated `validate()`; `decimal-wire` and `duration-wire`, every vector, against the code the generated support -crate carries; the `core` cases of `writer-conformance` (ADR-0063); and +crate carries; `render-conformance`, every case byte-identical, `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 (ADR-0034 Amendment 8). It also runs the codegen-compile gate (below) with every shipped generator, and a scale gate over twenty copies of the fitness model. The ledgers above may @@ -91,7 +93,7 @@ only shrink; the corpora without one assert each case outright. A new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard failure when ADR-0065 turns the warning off. A regression still fails: the ledger's `minPassing` (578) is the number of fixtures known to pass, and the -run fails when fewer do. The column joins this table when the port runs the render, persistence and API-contract corpora. +run fails when fewer do. The column joins this table when the port runs the persistence and API-contract corpora. A ✓ means the port runs the corpus green; an explicit `n / m` is used where a port carries a ledgered divergence. The ledgered YAML fixtures are documented divergences (see the @@ -416,7 +418,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 and generator-registry 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, 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) | — | — | The `persistence-conformance` corpus is intentionally **on-demand** — none of the unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 4ffe46d1fc..45c986892c 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -5,7 +5,7 @@ It reads a project, validates it, serializes it and generates code from it, and 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 ship: `entity`, `client` and `commands`, and a project chooses which of them run in -`metaobjects.config.json`. The three crates are **ready to publish but not published**: they package and +`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 on crates.io yet, so there is nothing to `cargo add` or `cargo install` from a registry. You work from a checkout of this repository until the first release. @@ -16,8 +16,8 @@ decisions behind the port (why Rust, the layout, the conformance rules), read th ## What works today The loader is the `metaobjects` crate, and the workspace at `server/rust/` adds the codegen crate -(`metaobjects-codegen`, the run engine and generator) and the CLI crate (`metaobjects-cli`, the -`cargo-meta` binary). What each area does: +(`metaobjects-codegen`, the run engine and generator), the CLI crate (`metaobjects-cli`, the +`cargo-meta` binary) and the prompt crate (`metaobjects-render`, render and the reply parser). What each area does: | Area | What it does | |---|---| @@ -27,6 +27,8 @@ The loader is the `metaobjects` crate, and the workspace at `server/rust/` adds | Registry | The type registry and the built-in providers. It is strict and sealed after bootstrap, with the same `ERR_*` codes as the other ports. | | Validation | All 41 validation passes the TypeScript loader runs, in the same order, the business-rules pass among them (operations, permission names and lifecycles, [ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)). The ordered list is `PASSES` in `server/rust/metaobjects/src/validate/mod.rs`. | | Serializer | The canonical serializer. A tree it loads serializes to the same bytes the other ports write. | +| Prompt rendering | `metaobjects_render::render` renders a `template.*` body over a JSON payload as every port does: partials expanded ahead of time, each `{{value}}` escaped for the template's format (`text`, `markdown`, `html`, `xml`, `csv`, `spreadsheet`, `json`), derived `has` and `-last` accessors, and a fail-closed `maxChars` budget. The Mustache engine underneath is the `mustache-ng` crate. | +| Reply parser | `metaobjects_render::extract::extract` reads a typed answer out of a model's reply (FR-010, FR-011): fences, prose, comments, trailing commas and cut-off values tolerated, every declared field classified (`EXTRACTED`, `DEFAULTED`, `LOST_OPTIONAL`, `LOST_REQUIRED`, `MALFORMED`) and coerced to its kind, under a `STRICT`, `NORMAL` or `LOOSE` tolerance. `metaobjects_render::prompt::render_output_format` writes the output-format fragment that asks for that answer, in the `guide`, `inline` and `exampleOnly` styles. | | Frozen tree | The loader freezes the tree when it finishes. A frozen tree memoizes its resolved reads (effective children, attributes and array-ness), so many readers can share one. | | Timings | Every load records how long each phase and each validation pass took (`LoadResult::timings`). | | Code generation (`cargo meta`) | The run engine, three generators (`entity`, `client`, `commands`), the codegen drift gate and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | @@ -296,8 +298,8 @@ Two gates have no corpus of their own: a slow machine. Rust is not yet a column in the [per-corpus table](../CONFORMANCE.md#per-corpus-totals); it joins -when the port runs the render, persistence and API-contract corpora. The other corpora (render, persistence, API contract) need code the -port does not have yet. +when the port runs the persistence and API-contract corpora, which need a service tier the port does +not have yet. It runs the render, extract and output-format corpora today. ### Load benchmark @@ -319,7 +321,9 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to - **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. -- **Templates and prompts.** No render engine, no payload value objects and no output parser. +- **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`. - **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/fixtures/extract-conformance/expected-field-kinds.json b/fixtures/extract-conformance/expected-field-kinds.json index c879a73bee..191f49d364 100644 --- a/fixtures/extract-conformance/expected-field-kinds.json +++ b/fixtures/extract-conformance/expected-field-kinds.json @@ -14,7 +14,8 @@ "java": "server/java/render/src/main/java/com/metaobjects/render/extract/FieldKind.java", "csharp": "server/csharp/MetaObjects.Render/Extract/FieldKind.cs", "typescript": "server/typescript/packages/render/src/extract/types.ts", - "python": "server/python/src/metaobjects/render/extract/types.py" + "python": "server/python/src/metaobjects/render/extract/types.py", + "rust": "server/rust/metaobjects-render/src/extract/types.rs" }, "kotlinReusesJava": true, "$kotlinNote": "Kotlin ships no extract engine of its own — metadata-ktx drives the shared Java one, so there is no Kotlin FieldKind to check and adding one would itself be the drift.", diff --git a/scripts/check-extract-field-kinds.mjs b/scripts/check-extract-field-kinds.mjs index e1d778cfcb..e5d61ebaa5 100644 --- a/scripts/check-extract-field-kinds.mjs +++ b/scripts/check-extract-field-kinds.mjs @@ -47,6 +47,14 @@ function membersOf(port, src) { return m[1].split(",").map((s) => s.trim()).filter(Boolean) .map((s) => s.toUpperCase()); } + case "rust": { + // pub enum FieldKind { String, Int, ... } (PascalCase variants; doc comments and + // attributes on their own lines are stripped first) + const m = src.match(/enum\s+FieldKind\s*\{([^}]*)\}/); + if (!m) return null; + return m[1].split("\n").filter((l) => !/^\s*(\/\/|#\[)/.test(l)).join("\n") + .split(",").map((s) => s.trim()).filter(Boolean).map((s) => s.toUpperCase()); + } case "typescript": { // export const FieldKind = { STRING: "STRING", ... } as const; const m = src.match(/const\s+FieldKind\s*=\s*\{([\s\S]*?)\}\s*as\s+const/); diff --git a/server/rust/Cargo.lock b/server/rust/Cargo.lock index 9b9d2bbed1..0115910fce 100644 --- a/server/rust/Cargo.lock +++ b/server/rust/Cargo.lock @@ -86,6 +86,12 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + [[package]] name = "memchr" version = "2.8.3" @@ -120,12 +126,32 @@ dependencies = [ "serde_json", ] +[[package]] +name = "metaobjects-render" +version = "0.1.0" +dependencies = [ + "indexmap", + "mustache-ng", + "serde", + "serde_json", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" +[[package]] +name = "mustache-ng" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26ccc530f826bda40b9e9cb2014feac34984d23aec58a559a6b4232a7f1e133b" +dependencies = [ + "log", + "serde", +] + [[package]] name = "num-traits" version = "0.2.19" diff --git a/server/rust/Cargo.toml b/server/rust/Cargo.toml index 2be70283ca..42dbe9d272 100644 --- a/server/rust/Cargo.toml +++ b/server/rust/Cargo.toml @@ -8,7 +8,7 @@ # `metaobjects-cli` the `cargo-meta` binary, so `cargo meta gen` works. [workspace] resolver = "3" -members = ["metaobjects", "metaobjects-codegen", "metaobjects-cli"] +members = ["metaobjects", "metaobjects-codegen", "metaobjects-cli", "metaobjects-render"] [workspace.package] version = "0.1.0" diff --git a/server/rust/metaobjects-render/Cargo.toml b/server/rust/metaobjects-render/Cargo.toml new file mode 100644 index 0000000000..cb56376f15 --- /dev/null +++ b/server/rust/metaobjects-render/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "metaobjects-render" +description = "MetaObjects prompt rendering for Rust: deterministic, format-escaped Mustache render over a typed payload." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true +authors.workspace = true +readme = "README.md" +keywords = ["metadata", "prompt", "mustache", "template", "llm"] +categories = ["template-engine", "text-processing"] + +[dependencies] +# The maintained fork of the `mustache` crate (MIT/Apache-2.0). Its library name is +# still `mustache`, so the code says `use mustache::`. +mustache-ng = "0.10.0" +serde_json.workspace = true +serde.workspace = true +indexmap.workspace = true + +[lints] +workspace = true diff --git a/server/rust/metaobjects-render/LICENSE b/server/rust/metaobjects-render/LICENSE new file mode 100644 index 0000000000..387490ed86 --- /dev/null +++ b/server/rust/metaobjects-render/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 MetaObjects Contributors + + 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. diff --git a/server/rust/metaobjects-render/README.md b/server/rust/metaobjects-render/README.md new file mode 100644 index 0000000000..a54a357f64 --- /dev/null +++ b/server/rust/metaobjects-render/README.md @@ -0,0 +1,24 @@ +# metaobjects-render + +Prompt rendering for the MetaObjects Rust port. A `template.*` body is plain Mustache; this crate +renders it over a payload deterministically, so the same template and payload give the same bytes +in every MetaObjects port: + +- partials are expanded ahead of time, with a cycle guard and a depth limit; +- every `{{value}}` is escaped for the template's format (`text`, `markdown`, `html`, `xml`, `csv`, + `spreadsheet`, `json`), and `{{{value}}}` / `{{&value}}` bypass it; +- a payload carries derived `has` booleans and a `-last` flag on each object element of a list; +- `maxChars` is a fail-closed budget: an over-budget render is an error, never a truncation. + +The Mustache engine underneath is [`mustache-ng`](https://crates.io/crates/mustache-ng). The +behaviour is held to the shared `fixtures/render-conformance/` corpus that every port runs. + +The other half of a prompt is the answer. `extract::extract` reads a typed answer out of a model's +reply, tolerating fences, prose, comments, trailing commas and cut-off values, and reports how each +declared field came out (`EXTRACTED`, `DEFAULTED`, `LOST_OPTIONAL`, `LOST_REQUIRED`, `MALFORMED`) +rather than failing. `prompt::render_output_format` writes the fragment that asks the model for that +answer. Both are held to `fixtures/extract-conformance/` and `fixtures/output-prompt-conformance/`. + +- Documentation: +- Source and the Rust port's page: (`docs/ports/rust.md`) +- License: Apache-2.0 diff --git a/server/rust/metaobjects-render/src/accessors.rs b/server/rust/metaobjects-render/src/accessors.rs new file mode 100644 index 0000000000..89491ce27d --- /dev/null +++ b/server/rust/metaobjects-render/src/accessors.rs @@ -0,0 +1,122 @@ +//! Derived payload accessors: `{{#hasFoo}}` over a payload field `foo`, and `-last` on +//! each object element of a list. +//! +//! A prompt needs conditional sections ("include the abilities block only when there ARE +//! abilities"), and the payload contract answers that with a DERIVED accessor rather than +//! an authored boolean: the author declares `abilities`, and `hasAbilities` follows from it. +//! The rule is shared across the ports on purpose (the JVM's `PayloadAccessors`, Python's +//! `payload_accessors.py`) and is gated by the `render-derived-has-accessor` case. + +use serde_json::{Map, Value}; + +/// The prefix every derived boolean accessor carries. +pub const HAS_PREFIX: &str = "has"; + +/// The positional accessor on every object element of a list, so a separator needs no +/// hand-computed flag: `{{#items}}{{name}}{{^-last}}, {{/-last}}{{/items}}`. The leading +/// `-` cannot collide with a field name. Scalar elements carry none. +pub const LAST_ACCESSOR: &str = "-last"; + +const MAX_DEPTH: usize = 32; + +/// Upper-case the first character and leave the rest alone (`abilities` -> `Abilities`). +#[must_use] +pub fn capitalize(s: &str) -> String { + let mut chars = s.chars(); + match chars.next() { + Some(first) => first.to_uppercase().chain(chars).collect(), + None => String::new(), + } +} + +/// `"has" + capitalize(name)`: `abilities` -> `hasAbilities`. +#[must_use] +pub fn has_accessor_name(field_name: &str) -> String { + format!("{HAS_PREFIX}{}", capitalize(field_name)) +} + +/// Is `value` "present" for `has`? A string must be non-blank, a list non-empty, +/// anything else non-null. Numbers and booleans get no accessor at all (`None`): they are +/// always-present scalars, and `{{#hasCount}}` over a number is drift, not a condition. +#[must_use] +pub fn accessor_value(value: &Value) -> Option { + match value { + Value::Null => Some(false), + Value::String(s) => Some(!s.trim().is_empty()), + Value::Number(_) | Value::Bool(_) => None, + Value::Array(a) => Some(!a.is_empty()), + Value::Object(_) => Some(true), + } +} + +/// A copy of `payload` carrying its derived accessors, recursively. An authored key always +/// wins: a payload that really carries `hasFoo` keeps its own value. +#[must_use] +pub fn with_derived_accessors(payload: &Value) -> Value { + derive(payload, 0) +} + +fn derive(payload: &Value, depth: usize) -> Value { + if depth > MAX_DEPTH { + return payload.clone(); + } + match payload { + Value::Object(map) => { + let mut out: Map = map + .iter() + .map(|(k, v)| (k.clone(), derive(v, depth + 1))) + .collect(); + for (k, v) in map { + let name = has_accessor_name(k); + if map.contains_key(&name) { + continue; + } + if let Some(present) = accessor_value(v) { + out.insert(name, Value::Bool(present)); + } + } + Value::Object(out) + } + Value::Array(items) => { + let last = items.len().saturating_sub(1); + Value::Array( + items + .iter() + .enumerate() + .map(|(i, v)| { + let mut el = derive(v, depth + 1); + if let Value::Object(m) = &mut el { + m.entry(LAST_ACCESSOR).or_insert(Value::Bool(i == last)); + } + el + }) + .collect(), + ) + } + other => other.clone(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn derives_has_flags_and_last() { + let v = with_derived_accessors(&json!({ + "bio": " ", "tags": ["a"], "count": 3, "items": [{"n": 1}, {"n": 2}], "hasBio": true + })); + assert_eq!(v["hasBio"], json!(true), "authored key wins"); + assert_eq!(v["hasTags"], json!(true)); + assert!(v.get("hasCount").is_none()); + assert_eq!(v["items"][0]["-last"], json!(false)); + assert_eq!(v["items"][1]["-last"], json!(true)); + } + + #[test] + fn capitalize_keeps_the_rest() { + assert_eq!(capitalize("fooBar"), "FooBar"); + assert_eq!(has_accessor_name("URL"), "hasURL"); + } +} diff --git a/server/rust/metaobjects-render/src/escapers.rs b/server/rust/metaobjects-render/src/escapers.rs new file mode 100644 index 0000000000..2d9e787cc5 --- /dev/null +++ b/server/rust/metaobjects-render/src/escapers.rs @@ -0,0 +1,165 @@ +//! Format-keyed escapers (FR-004). +//! +//! Every `{{value}}` substitution is escaped for the template's format; `{{{value}}}` and +//! `{{&value}}` bypass it. The behaviour is character-for-character the same as the +//! TypeScript reference (`server/typescript/packages/render/src/escapers.ts`) and the C#, +//! Java and Python ports, and the render-conformance corpus holds every port to it. + +/// No escaping. +pub const FORMAT_TEXT: &str = "text"; +/// No escaping: markdown is text a model reads. +pub const FORMAT_MARKDOWN: &str = "markdown"; +/// The XML entity set (FR-004 gives HTML the same one). +pub const FORMAT_HTML: &str = "html"; +/// `& < > " '` as entities. +pub const FORMAT_XML: &str = "xml"; +/// The formula-injection guard, then RFC 4180 quoting when a cell needs it. +pub const FORMAT_CSV: &str = "csv"; +/// XML escaping, then the formula-injection guard. +pub const FORMAT_SPREADSHEET: &str = "spreadsheet"; +/// The inside of a JSON string literal, as `JSON.stringify(s).slice(1, -1)` writes it. +pub const FORMAT_JSON: &str = "json"; + +/// Every registered format, in the order the reference registers them. +pub const FORMATS: [&str; 7] = [ + FORMAT_TEXT, + FORMAT_MARKDOWN, + FORMAT_HTML, + FORMAT_XML, + FORMAT_CSV, + FORMAT_SPREADSHEET, + FORMAT_JSON, +]; + +/// Is `format` one of [`FORMATS`]? +#[must_use] +pub fn is_format(format: &str) -> bool { + FORMATS.contains(&format) +} + +/// Does `format` leave every value unchanged? A render in such a format needs no +/// per-value escaping pass. +#[must_use] +pub fn is_identity(format: &str) -> bool { + format == FORMAT_TEXT || format == FORMAT_MARKDOWN +} + +/// Escape `value` for `format`, or `None` when the format is not registered. +#[must_use] +pub fn escape(format: &str, value: &str) -> Option { + Some(match format { + FORMAT_TEXT | FORMAT_MARKDOWN => value.to_string(), + FORMAT_HTML | FORMAT_XML => escape_xml(value), + FORMAT_CSV => escape_csv(value), + FORMAT_SPREADSHEET => injection_guard(&escape_xml(value)), + FORMAT_JSON => escape_json(value), + _ => return None, + }) +} + +fn escape_xml(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(c), + } + } + out +} + +/// `-?[0-9]+(\.[0-9]+)?` over the whole string, ASCII digits only. A strict numeric +/// literal such as `-5` is data, not a formula, so the guard leaves it alone. +fn is_strict_numeric(s: &str) -> bool { + let body = s.strip_prefix('-').unwrap_or(s); + let (int, frac) = match body.split_once('.') { + Some((i, f)) => (i, Some(f)), + None => (body, None), + }; + let digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()); + digits(int) && frac.is_none_or(digits) +} + +/// The OWASP CSV formula-injection guard: a cell that starts with `= + - @`, a tab or a +/// carriage return gets a leading apostrophe, unless it is a strict numeric literal. +fn injection_guard(s: &str) -> String { + match s.chars().next() { + Some('=' | '+' | '-' | '@' | '\t' | '\r') if !is_strict_numeric(s) => format!("'{s}"), + _ => s.to_string(), + } +} + +fn escape_csv(s: &str) -> String { + let guarded = injection_guard(s); + if guarded.contains([',', '"', '\n', '\r']) { + format!("\"{}\"", guarded.replace('"', "\"\"")) + } else { + guarded + } +} + +fn escape_json(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\u{08}' => out.push_str("\\b"), + '\u{0C}' => out.push_str("\\f"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn xml_escapes_the_five_entities() { + assert_eq!( + escape(FORMAT_XML, "a&b\"d'").unwrap(), + "a&b<c>"d'" + ); + } + + #[test] + fn csv_guards_and_quotes() { + assert_eq!(escape(FORMAT_CSV, "=cmd()").unwrap(), "'=cmd()"); + assert_eq!(escape(FORMAT_CSV, "a,b").unwrap(), "\"a,b\""); + assert_eq!(escape(FORMAT_CSV, "-5.25").unwrap(), "-5.25"); + assert_eq!(escape(FORMAT_CSV, "-5.").unwrap(), "'-5."); + assert_eq!( + escape(FORMAT_CSV, "say \"hi\"").unwrap(), + "\"say \"\"hi\"\"\"" + ); + } + + #[test] + fn spreadsheet_escapes_then_guards() { + assert_eq!(escape(FORMAT_SPREADSHEET, "=a&b").unwrap(), "'=a&b"); + } + + #[test] + fn json_escapes_controls_only() { + assert_eq!( + escape(FORMAT_JSON, "a\"b\\c\n\u{01}<").unwrap(), + "a\\\"b\\\\c\\n\\u0001<" + ); + } + + #[test] + fn unknown_format_is_none() { + assert!(escape("yaml", "x").is_none()); + assert!(!is_format("yaml")); + } +} diff --git a/server/rust/metaobjects-render/src/extract/coerce.rs b/server/rust/metaobjects-render/src/extract/coerce.rs new file mode 100644 index 0000000000..76b7f43322 --- /dev/null +++ b/server/rust/metaobjects-render/src/extract/coerce.rs @@ -0,0 +1,286 @@ +//! Stage 7: canonicalize a raw scalar per its [`FieldSpec`]. `None` is `MALFORMED`: the +//! value was present but could not be coerced. Mirrors `coerce.py`. +//! +//! Number rules shared with the C#, TS and Python ports: non-finite values are malformed, +//! radix prefixes (`0x..`) are rejected, and only an ASCII numeric literal parses. + +use serde_json::Value; + +use super::normalize::{self, normalize_enum}; +use super::types::{Coercion, ExtractOptions, ExtractionReport, FieldKind, FieldSpec, Tolerance}; + +/// `^[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$` +pub(crate) fn is_ascii_numeric(s: &str) -> bool { + let b = s.as_bytes(); + let mut i = 0; + if i < b.len() && (b[i] == b'+' || b[i] == b'-') { + i += 1; + } + let int_start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + let int_digits = i - int_start; + if i < b.len() && b[i] == b'.' { + i += 1; + let frac_start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if int_digits == 0 && i == frac_start { + return false; + } + } else if int_digits == 0 { + return false; + } + if i < b.len() && (b[i] == b'e' || b[i] == b'E') { + i += 1; + if i < b.len() && (b[i] == b'+' || b[i] == b'-') { + i += 1; + } + let exp_start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if i == exp_start { + return false; + } + } + i == b.len() +} + +/// Canonicalize `raw` for `spec`, or `None` when it is malformed. +pub(crate) fn value( + raw: &str, + spec: &FieldSpec, + opts: &ExtractOptions, + path: &str, + report: &mut ExtractionReport, +) -> Option { + if let Some(hook) = &opts.on_field + && let Some(v) = hook(path, raw, spec) + { + report.add_coercion(Coercion::new(path, raw, &value_text(&v), "onField")); + return Some(v); + } + let norm = opts + .normalizers + .get(path) + .or_else(|| opts.normalizers.get(&spec.name)); + if let Some(norm) = norm + && let Some(v) = norm(raw) + { + report.add_coercion(Coercion::new(path, raw, &value_text(&v), "normalizer")); + return Some(v); + } + let ci = opts.tolerance != Tolerance::Strict; + match spec.kind { + FieldKind::Enum => coerce_enum(raw, spec, opts, path, report, ci), + FieldKind::Int | FieldKind::Long => coerce_number(raw, spec, path, report, ci, true), + FieldKind::Double => coerce_number(raw, spec, path, report, ci, false), + FieldKind::Boolean => coerce_bool(raw, ci), + FieldKind::String | FieldKind::Object => Some(Value::String(raw.to_string())), + } +} + +/// Coerce a `@default` string to the field's kind with no side effects: it comes from the +/// metadata, not the reply. +pub(crate) fn scalar(raw: &str, spec: &FieldSpec) -> Option { + match spec.kind { + FieldKind::Int | FieldKind::Long => { + let t = raw.trim(); + if !is_ascii_numeric(t) { + return None; + } + if let Ok(n) = t.parse::() { + return Some(Value::from(n)); + } + let d: f64 = t.parse().ok()?; + d.is_finite().then(|| int_value(d.trunc())) + } + FieldKind::Double => { + let t = raw.trim(); + if !is_ascii_numeric(t) { + return None; + } + let d: f64 = t.parse().ok()?; + d.is_finite().then(|| Value::from(d)) + } + FieldKind::Boolean => coerce_bool(raw, true), + _ => Some(Value::String(raw.to_string())), + } +} + +fn value_text(v: &Value) -> String { + match v { + Value::String(s) => s.clone(), + other => other.to_string(), + } +} + +fn coerce_enum( + raw: &str, + spec: &FieldSpec, + opts: &ExtractOptions, + path: &str, + report: &mut ExtractionReport, + ci: bool, +) -> Option { + let mode = if ci { + spec.normalize.as_str() + } else { + normalize::NONE + }; + let values = spec.enum_values.as_deref().unwrap_or_default(); + if let Some(v) = values.iter().find(|v| *v == raw) { + return Some(Value::String(v.clone())); + } + if mode != normalize::NONE { + let norm_raw = normalize_enum(raw, mode); + if let Some(v) = values.iter().find(|v| normalize_enum(v, mode) == norm_raw) { + report.add_coercion(Coercion::new(path, raw, v, "normalize")); + return Some(Value::String(v.clone())); + } + } + let schema_target = lookup_alias(raw, &spec.enum_alias, mode); + if let Some(runtime) = lookup_alias(raw, &opts.aliases, mode) { + let kind = if schema_target.as_ref().is_some_and(|s| *s != runtime) { + "runtime-alias-override" + } else { + "alias" + }; + report.add_coercion(Coercion::new(path, raw, &runtime, kind)); + return Some(Value::String(runtime)); + } + if let Some(target) = schema_target { + report.add_coercion(Coercion::new(path, raw, &target, "alias")); + return Some(Value::String(target)); + } + if let Some(d) = &spec.coerce_default + && values.contains(d) + { + report.add_coercion(Coercion::new(path, raw, d, "coerceDefault")); + return Some(Value::String(d.clone())); + } + None +} + +fn lookup_alias(raw: &str, aliases: &[(String, String)], mode: &str) -> Option { + if let Some((_, t)) = aliases.iter().find(|(k, _)| k == raw) { + return Some(t.clone()); + } + if mode == normalize::NONE { + return None; + } + let norm_raw = normalize_enum(raw, mode); + aliases + .iter() + .find(|(k, _)| normalize_enum(k, mode) == norm_raw) + .map(|(_, t)| t.clone()) +} + +/// A whole number as a JSON integer when it fits, else as a float. +fn int_value(d: f64) -> Value { + #[allow(clippy::cast_possible_truncation)] + if d.abs() < 9.2e18 { + Value::from(d as i64) + } else { + Value::from(d) + } +} + +fn coerce_number( + raw: &str, + spec: &FieldSpec, + path: &str, + report: &mut ExtractionReport, + lenient: bool, + integer: bool, +) -> Option { + let t = raw.trim(); + if !is_ascii_numeric(t) { + return None; + } + // An integer parse first, so a long above 2^53 is not rounded through a float. + if integer && let Ok(n) = t.parse::() { + #[allow(clippy::cast_precision_loss)] + let f = n as f64; + let in_range = spec.min.is_none_or(|m| f >= m) && spec.max.is_none_or(|m| f <= m); + if in_range { + return Some(Value::from(n)); + } + return clamp(f, spec, path, report, lenient, integer); + } + let d: f64 = t.parse().ok()?; + clamp(d, spec, path, report, lenient, integer) +} + +/// Apply the field's range: clamp (recorded) when lenient, malformed when strict. +fn clamp( + n: f64, + spec: &FieldSpec, + path: &str, + report: &mut ExtractionReport, + lenient: bool, + integer: bool, +) -> Option { + if !n.is_finite() { + return None; + } + let mut c = n; + if let Some(min) = spec.min + && c < min + { + c = min; + } + if let Some(max) = spec.max + && c > max + { + c = max; + } + #[allow(clippy::float_cmp)] + if c != n { + if !lenient { + return None; + } + report.add_coercion(Coercion::new(path, &num_text(n), &num_text(c), "clamp")); + } + Some(if integer { + int_value(c.trunc()) + } else { + Value::from(c) + }) +} + +fn num_text(n: f64) -> String { + if n.is_finite() && n.fract() == 0.0 && n.abs() < 1e21 { + format!("{n:.0}") + } else { + n.to_string() + } +} + +fn coerce_bool(raw: &str, ci: bool) -> Option { + let t = raw.trim(); + let t = if ci { t.to_lowercase() } else { t.to_string() }; + match t.as_str() { + "true" | "yes" | "1" => Some(Value::Bool(true)), + "false" | "no" | "0" => Some(Value::Bool(false)), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numeric_literal_shape() { + for ok in ["1", "-1", "+1.5", ".5", "1.", "1e5", "2.5E-3"] { + assert!(is_ascii_numeric(ok), "{ok}"); + } + for bad in ["", ".", "0x10", "1_000", "1", "1e", "NaN", "inf"] { + assert!(!is_ascii_numeric(bad), "{bad}"); + } + } +} diff --git a/server/rust/metaobjects-render/src/extract/engine.rs b/server/rust/metaobjects-render/src/extract/engine.rs new file mode 100644 index 0000000000..e932752851 --- /dev/null +++ b/server/rust/metaobjects-render/src/extract/engine.rs @@ -0,0 +1,295 @@ +//! The extract pipeline: strip fences, locate the payload, read it tolerantly, then +//! classify and coerce every declared field. Never fails. Mirrors `extract.py`. + +use indexmap::IndexMap; +use serde_json::{Map, Value}; + +use super::coerce; +use super::json_reader::{self, Raw}; +use super::locate; +use super::strip; +use super::types::{ + Coercion, ExtractOptions, ExtractSchema, ExtractionOutcome, ExtractionReport, FieldExtraction, + FieldKind, FieldSpec, Format, Tolerance, +}; +use super::xml_reader::{self, TEXT_KEY}; + +/// Extract structured data from a model's reply per `schema`. +#[must_use] +pub fn extract( + text: Option<&str>, + schema: &ExtractSchema, + opts: &ExtractOptions, +) -> ExtractionOutcome { + let mut report = ExtractionReport::default(); + let mut data = Map::new(); + let stripped = strip::strip(text); + let ci = opts.tolerance != Tolerance::Strict; + + let located = opts + .on_locate + .as_ref() + .and_then(|hook| hook(text.unwrap_or(""), schema.format)); + + let (raw, region_blank) = if let Some(span) = located { + let raw = match schema.format { + Format::Json => json_reader::read(&span), + Format::Xml if opts.rootless => xml_reader::read_rootless(&span, ci), + Format::Xml => xml_reader::read(&span, ci), + }; + // The located span's LENGTH, not its text: the report should not carry a copy of + // an arbitrarily large reply. + report.add_coercion(Coercion::new( + "", + "", + &span.chars().count().to_string(), + "onLocate", + )); + (raw, span.trim().is_empty()) + } else { + let span = match schema.format { + Format::Json => select_json(text, &stripped, &schema.fields, ci), + Format::Xml if opts.rootless => (!stripped.is_empty()).then(|| stripped.clone()), + Format::Xml => locate::xml(&stripped, &schema.root_name, ci), + }; + let raw = match (&span, schema.format) { + (None, _) => IndexMap::new(), + (Some(s), Format::Json) => json_reader::read(s), + (Some(s), Format::Xml) if opts.rootless => xml_reader::read_rootless(s, ci), + (Some(s), Format::Xml) => xml_reader::read(s, ci), + }; + (raw, stripped.is_empty() || span.is_none()) + }; + + if raw.is_empty() && region_blank { + report.mark_empty(); + } + extract_fields(&schema.fields, &raw, "", &mut data, &mut report, opts, ci); + ExtractionOutcome { data, report } +} + +fn lost(f: &FieldSpec) -> FieldExtraction { + if f.required { + FieldExtraction::LostRequired + } else { + FieldExtraction::LostOptional + } +} + +fn extract_fields( + fields: &[FieldSpec], + raw: &IndexMap, + prefix: &str, + data: &mut Map, + report: &mut ExtractionReport, + opts: &ExtractOptions, + ci: bool, +) { + for f in fields { + let path = if prefix.is_empty() { + f.name.clone() + } else { + format!("{prefix}.{}", f.name) + }; + let present = if f.text_content { + raw.get(TEXT_KEY) + } else { + lookup(raw, &f.name, ci) + }; + let Some(present) = present else { + // An absent field with a @default is filled from it, DEFAULTED, which satisfies + // @required. A default that does not coerce to the field's kind is no default. + if let Some(d) = &f.default_value { + let coerced = if f.kind == FieldKind::Enum { + Some(Value::String(d.clone())) + } else { + coerce::scalar(d, f) + }; + if let Some(v) = coerced { + data.insert(f.name.clone(), v); + report.add_coercion(Coercion::new(&path, "", d, "default")); + report.set(&path, FieldExtraction::Defaulted); + if f.required { + report.mark_defaulted_required(&path); + } + continue; + } + } + report.set(&path, lost(f)); + continue; + }; + match present { + Raw::Truncated => { + mark_malformed(report, &path, f); + continue; + } + // An explicit null is a value, not an omission: the field stays null and its + // @default does not apply. + Raw::Null => { + report.set(&path, lost(f)); + continue; + } + _ => {} + } + if f.array { + let single = [present.clone()]; + let elements: &[Raw] = match present { + Raw::List(xs) => xs, + _ => &single, + }; + let mut out = Vec::new(); + let mut any_malformed = false; + let enum_elements = f.kind == FieldKind::Enum; + for (idx, el) in elements.iter().enumerate() { + let elem_path = format!("{path}[{idx}]"); + match extract_value(f, el, &elem_path, report, opts, ci) { + None => { + any_malformed = true; + if enum_elements { + report.set(&elem_path, FieldExtraction::Malformed); + } + } + Some(v) => { + out.push(v); + if enum_elements { + let state = classify_coerced(&elem_path, report); + report.set(&elem_path, state); + } + } + } + } + // A malformed array keeps the elements that did coerce. Bounds: too many are + // truncated (recorded) unless strict; too few cannot be repaired. + let mut out_of_bounds = false; + if !any_malformed + && let Some(max) = f.max_items + && out.len() > max + { + if opts.tolerance == Tolerance::Strict { + out_of_bounds = true; + } else { + report.add_coercion(Coercion::new( + &path, + &out.len().to_string(), + &max.to_string(), + "truncate", + )); + out.truncate(max); + } + } + if !any_malformed + && let Some(min) = f.min_items + && out.len() < min + { + out_of_bounds = true; + } + data.insert(f.name.clone(), Value::Array(out)); + if any_malformed || out_of_bounds { + mark_malformed(report, &path, f); + } else { + report.set(&path, FieldExtraction::Extracted); + } + continue; + } + if matches!(present, Raw::List(_)) { + mark_malformed(report, &path, f); + continue; + } + match extract_value(f, present, &path, report, opts, ci) { + None => mark_malformed(report, &path, f), + Some(v) => { + data.insert(f.name.clone(), v); + let state = classify_coerced(&path, report); + report.set(&path, state); + } + } + } +} + +fn mark_malformed(report: &mut ExtractionReport, path: &str, f: &FieldSpec) { + report.set(path, FieldExtraction::Malformed); + if f.required { + report.mark_malformed_required(path); + } +} + +/// DEFAULTED when the last coercion recorded for `path` is a default-class fallback. +fn classify_coerced(path: &str, report: &ExtractionReport) -> FieldExtraction { + let terminal = report + .coercions() + .iter() + .rev() + .find(|c| c.field_path == path) + .map(|c| c.kind.as_str()); + match terminal { + Some("coerceDefault" | "default") => FieldExtraction::Defaulted, + _ => FieldExtraction::Extracted, + } +} + +fn extract_value( + f: &FieldSpec, + present: &Raw, + path: &str, + report: &mut ExtractionReport, + opts: &ExtractOptions, + ci: bool, +) -> Option { + if f.kind == FieldKind::Object { + let (Some(nested), Raw::Map(m)) = (&f.nested, present) else { + return None; + }; + let mut nested_data = Map::new(); + extract_fields(&nested.fields, m, path, &mut nested_data, report, opts, ci); + return Some(Value::Object(nested_data)); + } + let text = match present { + Raw::Str(s) => s.as_str(), + // An element with attributes carries its text under #text; one with only child + // elements is not a scalar value. + Raw::Map(m) => match m.get(TEXT_KEY) { + Some(Raw::Str(s)) => s.as_str(), + _ => return None, + }, + Raw::List(_) | Raw::Truncated | Raw::Null => return None, + }; + coerce::value(text, f, opts, path, report) +} + +/// Pick the JSON object that answers the schema: fenced blocks first, then the whole +/// reply, the first object carrying a declared field; else the first-object rule. +fn select_json( + text: Option<&str>, + stripped: &str, + fields: &[FieldSpec], + ci: bool, +) -> Option { + let mut regions = strip::fenced_bodies(text); + regions.push(stripped.to_string()); + for region in ®ions { + for candidate in locate::json_candidates(region) { + let parsed = json_reader::read(&candidate); + if fields + .iter() + .any(|f| lookup(&parsed, &f.name, ci).is_some()) + { + return Some(candidate); + } + } + } + locate::json(stripped) +} + +fn lookup<'a>(raw: &'a IndexMap, name: &str, ci: bool) -> Option<&'a Raw> { + if let Some(v) = raw.get(name) { + return Some(v); + } + if ci { + let lower = name.to_lowercase(); + return raw + .iter() + .find(|(k, _)| k.to_lowercase() == lower) + .map(|(_, v)| v); + } + None +} diff --git a/server/rust/metaobjects-render/src/extract/json_reader.rs b/server/rust/metaobjects-render/src/extract/json_reader.rs new file mode 100644 index 0000000000..32c0c5a8a5 --- /dev/null +++ b/server/rust/metaobjects-render/src/extract/json_reader.rs @@ -0,0 +1,342 @@ +//! Stage 4: the tolerant JSON reader for the bounded malformation set. Never fails. +//! +//! A key whose value is empty or cut off is recorded as [`Raw::Truncated`], so the field +//! classifies `MALFORMED` rather than lost; the `null` literal is [`Raw::Null`]. Bare +//! scalars (numbers, `true`) stay text: coercion types them. Mirrors +//! `json_forgiving_reader.py`. + +use indexmap::IndexMap; + +/// A value the tolerant readers produce. +#[derive(Debug, Clone, PartialEq)] +pub enum Raw { + Str(String), + Map(IndexMap), + List(Vec), + /// A key that appeared with an empty or cut-off value. + Truncated, + /// The JSON `null` literal. + Null, +} + +/// Container nesting past which the reader skips a container rather than recursing. +const MAX_DEPTH: usize = 100; + +/// Parse `span` as a forgiving JSON object; empty for garbage or a non-object root. +#[must_use] +pub fn read(span: &str) -> IndexMap { + let mut r = Reader { + s: span.chars().collect(), + i: 0, + depth: 0, + }; + r.ws(); + if r.peek() != Some('{') { + return IndexMap::new(); + } + match r.read_value() { + Some(Raw::Map(m)) => m, + _ => IndexMap::new(), + } +} + +struct Reader { + s: Vec, + i: usize, + depth: usize, +} + +impl Reader { + fn peek(&self) -> Option { + self.s.get(self.i).copied() + } + + fn at(&self, c: char) -> bool { + self.peek() == Some(c) + } + + fn read_value(&mut self) -> Option { + self.ws(); + let c = self.peek()?; + if c == '{' || c == '[' { + if self.depth >= MAX_DEPTH { + self.skip_balanced(); + return None; + } + self.depth += 1; + let v = if c == '{' { + Raw::Map(self.read_object()) + } else { + Raw::List(self.read_array()) + }; + self.depth -= 1; + return Some(v); + } + if c == '"' || c == '\'' { + return Some(Raw::Str(self.read_string(c))); + } + self.read_bare_scalar() + } + + fn skip_balanced(&mut self) { + let mut depth = 0i32; + while let Some(ch) = self.peek() { + if ch == '"' || ch == '\'' { + self.read_string(ch); + continue; + } + self.i += 1; + if ch == '{' || ch == '[' { + depth += 1; + } else if ch == '}' || ch == ']' { + depth -= 1; + if depth <= 0 { + return; + } + } + } + } + + fn read_object(&mut self) -> IndexMap { + let mut m = IndexMap::new(); + self.i += 1; + loop { + self.ws(); + match self.peek() { + None => return m, + Some('}') => { + self.i += 1; + return m; + } + _ => {} + } + let Some(key) = self.read_key() else { + return m; + }; + self.ws(); + if !self.at(':') { + return m; + } + self.i += 1; + self.ws(); + if self.peek().is_none() { + m.insert(key, Raw::Truncated); + return m; + } + let Some(v) = self.read_value() else { + m.insert(key, Raw::Truncated); + self.ws(); + if self.at(',') { + self.i += 1; + continue; + } + if self.at('}') { + self.i += 1; + } + return m; + }; + m.insert(key, v); + self.ws(); + if self.at(',') { + self.i += 1; + } + } + } + + fn read_array(&mut self) -> Vec { + let mut xs = Vec::new(); + self.i += 1; + loop { + self.ws(); + match self.peek() { + None => return xs, + Some(']' | '}') => { + self.i += 1; + return xs; + } + _ => {} + } + let Some(v) = self.read_value() else { + self.ws(); + if self.at(']') || self.at('}') { + self.i += 1; + } + return xs; + }; + xs.push(v); + self.ws(); + if self.at(',') { + self.i += 1; + } else if self.at(']') { + self.i += 1; + return xs; + } else { + return xs; + } + } + } + + fn read_key(&mut self) -> Option { + self.ws(); + let c = self.peek()?; + if c == '"' || c == '\'' { + return Some(self.read_string(c)); + } + let start = self.i; + while self.peek().is_some_and(|c| c.is_alphanumeric() || c == '_') { + self.i += 1; + } + (self.i > start).then(|| self.s[start..self.i].iter().collect()) + } + + fn read_string(&mut self, quote: char) -> String { + self.i += 1; + let mut out = String::new(); + while let Some(c) = self.peek() { + self.i += 1; + if c == '\\' { + out.push_str(&self.read_escape()); + } else if c == quote { + return out; + } else { + out.push(c); + } + } + out + } + + fn read_escape(&mut self) -> String { + let Some(c) = self.peek() else { + return String::new(); + }; + self.i += 1; + let simple = match c { + 'n' => Some('\n'), + 't' => Some('\t'), + 'r' => Some('\r'), + 'b' => Some('\u{08}'), + 'f' => Some('\u{0C}'), + _ => None, + }; + if let Some(s) = simple { + return s.to_string(); + } + if c != 'u' { + return c.to_string(); + } + let Some(unit) = self.hex4() else { + return "u".to_string(); + }; + if (0xD800..0xDC00).contains(&unit) + && self.s.get(self.i) == Some(&'\\') + && self.s.get(self.i + 1) == Some(&'u') + { + let save = self.i; + self.i += 2; + if let Some(low) = self.hex4() + && (0xDC00..0xE000).contains(&low) + { + let cp = 0x10000 + ((unit - 0xD800) << 10) + (low - 0xDC00); + return char::from_u32(cp).map(String::from).unwrap_or_default(); + } + self.i = save; + } + // A lone surrogate has no `char`; it becomes U+FFFD, the nearest a Rust string holds. + char::from_u32(unit).unwrap_or('\u{FFFD}').to_string() + } + + fn hex4(&mut self) -> Option { + let digits: String = self.s.get(self.i..self.i + 4)?.iter().collect(); + if digits.chars().all(|d| d.is_ascii_hexdigit()) { + self.i += 4; + u32::from_str_radix(&digits, 16).ok() + } else { + None + } + } + + fn read_bare_scalar(&mut self) -> Option { + let start = self.i; + while let Some(c) = self.peek() { + if c == ',' || c == '}' || c == ']' { + break; + } + if self.i > start + && self.s[self.i - 1].is_whitespace() + && comment_opens_at(&self.s, self.i) + { + break; + } + self.i += 1; + } + let text: String = self.s[start..self.i].iter().collect(); + let text = text.trim(); + if text.is_empty() { + return None; + } + if text == "null" { + return Some(Raw::Null); + } + Some(Raw::Str(text.to_string())) + } + + fn ws(&mut self) { + loop { + while self.peek().is_some_and(char::is_whitespace) { + self.i += 1; + } + match comment_end(&self.s, self.i) { + Some(end) => self.i = end, + None => return, + } + } + } +} + +/// Does a `//` or `/*` comment open at `i`? +pub(crate) fn comment_opens_at(s: &[char], i: usize) -> bool { + i + 1 < s.len() && s[i] == '/' && (s[i + 1] == '/' || s[i + 1] == '*') +} + +/// When a comment opens at `i`, the index just past it (a line comment runs to its line +/// end, a block comment to its `*/` or the end of the text). +pub(crate) fn comment_end(s: &[char], i: usize) -> Option { + if !comment_opens_at(s, i) { + return None; + } + if s[i + 1] == '/' { + let mut j = i + 2; + while j < s.len() && s[j] != '\n' && s[j] != '\r' { + j += 1; + } + return Some(j); + } + let mut j = i + 2; + while j + 1 < s.len() { + if s[j] == '*' && s[j + 1] == '/' { + return Some(j + 2); + } + j += 1; + } + Some(s.len()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn forgiving_reads() { + let m = read("{\"a\": 1, b: 'x', \"c\": null, \"d\": , \"e\": [1, 2,] // tail\n}"); + assert_eq!(m["a"], Raw::Str("1".into())); + assert_eq!(m["b"], Raw::Str("x".into())); + assert_eq!(m["c"], Raw::Null); + assert_eq!(m["d"], Raw::Truncated); + assert_eq!( + m["e"], + Raw::List(vec![Raw::Str("1".into()), Raw::Str("2".into())]) + ); + assert!(read("[1]").is_empty()); + assert_eq!(read("{\"xs\":[}").len(), 1); + } +} diff --git a/server/rust/metaobjects-render/src/extract/locate.rs b/server/rust/metaobjects-render/src/extract/locate.rs new file mode 100644 index 0000000000..2b006d83d7 --- /dev/null +++ b/server/rust/metaobjects-render/src/extract/locate.rs @@ -0,0 +1,192 @@ +//! Stages 2 and 3: isolate the payload span. Mirrors `locate.py`. + +use super::json_reader::comment_end; +use super::xml_reader::mask_non_markup; + +/// The first balanced `{...}`; when none closes, the first `{` to the end; `None` when +/// there is no `{`. +#[must_use] +pub fn json(text: &str) -> Option { + let s: Vec = text.chars().collect(); + let mut first_open = None; + for i in 0..s.len() { + if s[i] == '{' { + first_open.get_or_insert(i); + if let Some(end) = scan_balanced(&s, i) { + return Some(s[i..=end].iter().collect()); + } + } + } + first_open.map(|i| s[i..].iter().collect()) +} + +/// Every top-level object span in `text`, in order: each balanced `{...}`, and, for a `{` +/// that never closes, the text from it to the end. +#[must_use] +pub fn json_candidates(text: &str) -> Vec { + let s: Vec = text.chars().collect(); + let mut out = Vec::new(); + let mut tail_added = false; + let mut i = 0; + while i < s.len() { + if s[i] == '{' { + match scan_balanced(&s, i) { + Some(end) => { + out.push(s[i..=end].iter().collect()); + i = end; + } + None if !tail_added => { + out.push(s[i..].iter().collect()); + tail_added = true; + } + None => {} + } + } + i += 1; + } + out +} + +/// The index of the `}` matching the `{` at `open`. String-aware, and comment-aware: a +/// comment opening after whitespace or a separator is skipped (`http://x` is not one). +fn scan_balanced(s: &[char], open: usize) -> Option { + let mut depth = 0i32; + let mut in_str = false; + let mut esc = false; + let mut i = open; + while i < s.len() { + let c = s[i]; + if in_str { + if esc { + esc = false; + } else if c == '\\' { + esc = true; + } else if c == '"' { + in_str = false; + } + i += 1; + continue; + } + if i > open + && (s[i - 1].is_whitespace() || matches!(s[i - 1], ',' | '{' | '[')) + && let Some(end) = comment_end(s, i) + { + i = end; + continue; + } + match c { + '"' => in_str = true, + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + return Some(i); + } + } + _ => {} + } + i += 1; + } + None +} + +/// The span of `...`; when the close is absent, the opener to the end; `None` +/// when there is no opener. Comments and CDATA are not searched, and when another opener of +/// the same root sits between the first and its close, the span starts at the last one: a +/// root does not nest in itself. +#[must_use] +pub fn xml(text: &str, root: &str, ci: bool) -> Option { + let view = mask_non_markup(text); + let (open_start, open_end) = find_root_open(&view, root, ci, 0)?; + let Some(close_end) = find_root_close(&view, root, ci, open_end) else { + return Some(text[open_start..].to_string()); + }; + let close_start = close_end.0; + let mut start = open_start; + let mut at = open_end; + while let Some((s, e)) = find_root_open(&view, root, ci, at) { + if s >= close_start { + break; + } + start = s; + at = e; + } + Some(text[start..close_end.1].to_string()) +} + +fn name_at(s: &str, at: usize, name: &str, ci: bool) -> bool { + s.get(at..at + name.len()).is_some_and(|got| { + if ci { + got.eq_ignore_ascii_case(name) + } else { + got == name + } + }) +} + +/// `]*)?>` from `from`, as `(start, end)`. +fn find_root_open(s: &str, root: &str, ci: bool, from: usize) -> Option<(usize, usize)> { + let mut at = from; + while let Some(rel) = s.get(at..)?.find('<') { + let i = at + rel; + if name_at(s, i + 1, root, ci) { + let after = i + 1 + root.len(); + let rest = &s[after..]; + if rest.starts_with('>') { + return Some((i, after + 1)); + } + if rest.chars().next().is_some_and(char::is_whitespace) + && let Some(gt) = rest.find('>') + { + return Some((i, after + gt + 1)); + } + } + at = i + 1; + } + None +} + +/// `` from `from`, as `(start, end)`. +fn find_root_close(s: &str, root: &str, ci: bool, from: usize) -> Option<(usize, usize)> { + let mut at = from; + while let Some(rel) = s.get(at..)?.find("') { + return Some((i, after + (rest.len() - trimmed.len()) + 1)); + } + } + at = i + 2; + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn json_spans() { + assert_eq!( + json("pre {\"a\":{\"b\":1}} post").unwrap(), + "{\"a\":{\"b\":1}}" + ); + assert_eq!(json("x {\"a\":1").unwrap(), "{\"a\":1"); + assert!(json("none").is_none()); + assert_eq!( + json_candidates("{a} {b"), + vec!["{a}".to_string(), "{b".to_string()] + ); + } + + #[test] + fn xml_span_takes_the_last_opener() { + assert_eq!( + xml("use then ", "doc", true).unwrap(), + "" + ); + } +} diff --git a/server/rust/metaobjects-render/src/extract/mod.rs b/server/rust/metaobjects-render/src/extract/mod.rs new file mode 100644 index 0000000000..d0560e4ed9 --- /dev/null +++ b/server/rust/metaobjects-render/src/extract/mod.rs @@ -0,0 +1,24 @@ +//! The reply parser (FR-010, FR-011): tolerant extraction of a typed answer from a model's +//! dirty reply. +//! +//! A model asked for JSON or XML answers with fences, prose, comments, trailing commas, +//! cut-off values and synonyms. [`extract`] reads what it can, classifies every declared +//! field ([`FieldExtraction`]) and coerces each value to its kind, and never fails: a +//! caller decides from the report whether the answer is good enough +//! ([`ExtractionReport::fails_strict`]). The shared `fixtures/extract-conformance/` corpus +//! holds this module to the other ports. + +pub(crate) mod coerce; +mod engine; +pub mod json_reader; +pub mod locate; +pub mod normalize; +pub mod strip; +mod types; +pub mod xml_reader; + +pub use engine::extract; +pub use types::{ + Coercion, ExtractOptions, ExtractSchema, ExtractionOutcome, ExtractionReport, FieldExtraction, + FieldKind, FieldSpec, Format, Normalizer, OnField, OnLocate, Tolerance, +}; diff --git a/server/rust/metaobjects-render/src/extract/normalize.rs b/server/rust/metaobjects-render/src/extract/normalize.rs new file mode 100644 index 0000000000..ee3adaa0f9 --- /dev/null +++ b/server/rust/metaobjects-render/src/extract/normalize.rs @@ -0,0 +1,77 @@ +//! FR-011 enum-variant normalization, ASCII-only by design so it is byte-identical across +//! ports and immune to locale case-folding. Mirrors `normalize.py` and the TS, C# and Java +//! ports. + +/// Exact match only. +pub const NONE: &str = "none"; +/// ASCII upper-case, trim, and collapse runs of whitespace, `_` and `-` to one `_`. +pub const COLLAPSE: &str = "collapse"; +/// ASCII upper-case and keep only `[A-Z0-9]`. +pub const STRIP: &str = "strip"; +/// The mode when none is declared. +pub const DEFAULT: &str = STRIP; + +/// The JS `\s` class plus `_` and `-`. +fn is_separator(c: char) -> bool { + matches!( + c, + '_' | '-' + | ' ' + | '\t' + | '\n' + | '\u{0B}' + | '\u{0C}' + | '\r' + | '\u{A0}' + | '\u{1680}' + | '\u{2028}' + | '\u{2029}' + | '\u{202F}' + | '\u{205F}' + | '\u{3000}' + | '\u{FEFF}' + | '\u{2000}'..='\u{200A}' + ) +} + +/// Normalize `s` under `mode`; an unknown mode is `strip`. +#[must_use] +pub fn normalize_enum(s: &str, mode: &str) -> String { + if mode == NONE { + return s.to_string(); + } + let up = s.trim().to_ascii_uppercase(); + if mode == COLLAPSE { + let mut out = String::with_capacity(up.len()); + let mut in_run = false; + for c in up.chars() { + if is_separator(c) { + if !in_run { + out.push('_'); + in_run = true; + } + } else { + out.push(c); + in_run = false; + } + } + out + } else { + up.chars() + .filter(|c| c.is_ascii_uppercase() || c.is_ascii_digit()) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn modes() { + assert_eq!(normalize_enum(" in-progress ", STRIP), "INPROGRESS"); + assert_eq!(normalize_enum("in - progress", COLLAPSE), "IN_PROGRESS"); + assert_eq!(normalize_enum("x", NONE), "x"); + assert_eq!(normalize_enum("é-a", STRIP), "A"); + } +} diff --git a/server/rust/metaobjects-render/src/extract/strip.rs b/server/rust/metaobjects-render/src/extract/strip.rs new file mode 100644 index 0000000000..90b85a232a --- /dev/null +++ b/server/rust/metaobjects-render/src/extract/strip.rs @@ -0,0 +1,160 @@ +//! Stage 1: remove markdown code-fence markers. Prose around the payload is left for +//! `locate`. Mirrors `strip.py`. + +struct Fence { + start: usize, + end: usize, + body_start: usize, + body_end: usize, +} + +/// An opening fence at `i`: three or more backticks, an optional language tag, then +/// whitespace that holds a line end. Returns `(run width, index just past the last line +/// end of that whitespace)`. +fn open_at(b: &[u8], i: usize) -> Option<(usize, usize)> { + let mut j = i; + while j < b.len() && b[j] == b'`' { + j += 1; + } + let width = j - i; + if width < 3 { + return None; + } + while j < b.len() && (b[j].is_ascii_alphanumeric() || b[j] == b'_' || b[j] == b'-') { + j += 1; + } + let mut last_nl = None; + while j < b.len() && b[j].is_ascii_whitespace() { + if b[j] == b'\n' { + last_nl = Some(j); + } + j += 1; + } + last_nl.map(|nl| (width, nl + 1)) +} + +fn fences(raw: &str) -> Vec { + let b = raw.as_bytes(); + let mut out = Vec::new(); + let mut pos = 0; + 'search: while pos < b.len() { + let mut i = pos; + while i < b.len() { + if b[i] == b'`' + && let Some((width, body_start)) = open_at(b, i) + { + match find_close(raw, body_start, width) { + Some((body_end, end)) => { + out.push(Fence { + start: i, + end, + body_start, + body_end, + }); + pos = end; + } + None => pos = body_start, + } + continue 'search; + } + i += 1; + } + break; + } + out +} + +fn find_close(raw: &str, start: usize, width: usize) -> Option<(usize, usize)> { + let b = raw.as_bytes(); + let mut ls = start; + while ls <= b.len() { + let mut i = ls; + while i < b.len() && (b[i] == b' ' || b[i] == b'\t') && i - ls < 4 { + i += 1; + } + let mut j = i; + while j < b.len() && b[j] == b'`' { + j += 1; + } + if j - i >= width { + let mut k = j; + while k < b.len() && (b[k] == b' ' || b[k] == b'\t') { + k += 1; + } + if k >= b.len() || b[k] == b'\r' || b[k] == b'\n' { + return Some((body_end(b, start, ls), j)); + } + } + match raw[ls..].find('\n') { + Some(nl) => ls = ls + nl + 1, + None => break, + } + } + // No closing line: accept a final backtick run that ends the text on the payload's line. + let tail = raw.trim_end().as_bytes(); + let mut k = tail.len(); + while k > start && tail[k - 1] == b'`' { + k -= 1; + } + if tail.len() - k >= width && k > start { + return Some((k, tail.len())); + } + None +} + +fn body_end(b: &[u8], start: usize, line_start: usize) -> usize { + let mut e = line_start; + if e > start && b[e - 1] == b'\n' { + e -= 1; + } + if e > start && b[e - 1] == b'\r' { + e -= 1; + } + e +} + +/// Strip the first code fence, splicing its body back in place; otherwise trim. +#[must_use] +pub fn strip(raw: Option<&str>) -> String { + let Some(raw) = raw else { + return String::new(); + }; + match fences(raw).first() { + Some(f) => format!( + "{}{}{}", + &raw[..f.start], + &raw[f.body_start..f.body_end], + &raw[f.end..] + ) + .trim() + .to_string(), + None => raw.trim().to_string(), + } +} + +/// The body of every fenced block, in order. +#[must_use] +pub fn fenced_bodies(raw: Option<&str>) -> Vec { + let Some(raw) = raw else { + return Vec::new(); + }; + fences(raw) + .iter() + .map(|f| raw[f.body_start..f.body_end].to_string()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strips_a_fence() { + assert_eq!( + strip(Some("hi\n```json\n{\"a\":1}\n```\nbye")), + "hi\n{\"a\":1}\nbye" + ); + assert_eq!(fenced_bodies(Some("```\nx\n```")), vec!["x".to_string()]); + assert_eq!(strip(Some(" plain ")), "plain"); + } +} diff --git a/server/rust/metaobjects-render/src/extract/types.rs b/server/rust/metaobjects-render/src/extract/types.rs new file mode 100644 index 0000000000..4cd75730d2 --- /dev/null +++ b/server/rust/metaobjects-render/src/extract/types.rs @@ -0,0 +1,451 @@ +//! The FR-010 extract model and report. +//! +//! [`FieldExtraction`], [`FieldKind`], [`Tolerance`] and [`Format`] are frozen cross-port +//! vocabularies: the extract-conformance corpus serializes them as upper-case tokens, and +//! `scripts/check-extract-field-kinds.mjs` reads [`FieldKind`] from this file. + +use std::collections::HashMap; +use std::fmt; + +use indexmap::IndexMap; +use serde_json::{Map, Value}; + +use super::normalize; + +/// The document format a reply is parsed as. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Format { + Json, + Xml, +} + +impl Format { + /// The corpus token (`JSON`, `XML`). + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Json => "JSON", + Self::Xml => "XML", + } + } + + /// The format a corpus token names. + #[must_use] + pub fn parse(token: &str) -> Option { + match token { + "JSON" => Some(Self::Json), + "XML" => Some(Self::Xml), + _ => None, + } + } +} + +/// The coercion targets the engine understands; `Object` is a nested schema. The corpus +/// tokens are the upper-cased names (`STRING`, `INT`, ...). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FieldKind { + String, + Int, + Long, + Double, + Boolean, + Enum, + Object, +} + +impl FieldKind { + /// The corpus token. + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::String => "STRING", + Self::Int => "INT", + Self::Long => "LONG", + Self::Double => "DOUBLE", + Self::Boolean => "BOOLEAN", + Self::Enum => "ENUM", + Self::Object => "OBJECT", + } + } + + /// The kind a corpus token names. + #[must_use] + pub fn parse(token: &str) -> Option { + Some(match token { + "STRING" => Self::String, + "INT" => Self::Int, + "LONG" => Self::Long, + "DOUBLE" => Self::Double, + "BOOLEAN" => Self::Boolean, + "ENUM" => Self::Enum, + "OBJECT" => Self::Object, + _ => return None, + }) + } +} + +/// The frozen cross-port classification of one field. Do not reorder or add without an ADR. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FieldExtraction { + /// Read from the reply and coerced cleanly. + Extracted, + /// Reached through `@coerceDefault` (present but uncoercible) or `@default` (absent). + Defaulted, + /// Absent, and not required. + LostOptional, + /// Absent, and required. + LostRequired, + /// Present, but unusable. + Malformed, +} + +impl FieldExtraction { + /// The corpus token (`EXTRACTED`, `LOST_REQUIRED`, ...). + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Extracted => "EXTRACTED", + Self::Defaulted => "DEFAULTED", + Self::LostOptional => "LOST_OPTIONAL", + Self::LostRequired => "LOST_REQUIRED", + Self::Malformed => "MALFORMED", + } + } +} + +impl fmt::Display for FieldExtraction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// How much repair the engine attempts. `Strict` is case-sensitive and rejects what it +/// would otherwise clamp or truncate; `Normal` (the default) is case-insensitive; `Loose` +/// behaves as `Normal` today and is reserved for more repair. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Tolerance { + Strict, + #[default] + Normal, + Loose, +} + +impl Tolerance { + /// The tolerance a corpus token names. + #[must_use] + pub fn parse(token: &str) -> Option { + match token { + "STRICT" => Some(Self::Strict), + "NORMAL" => Some(Self::Normal), + "LOOSE" => Some(Self::Loose), + _ => None, + } + } +} + +/// One recorded normalization or coercion. `kind` is e.g. `normalize`, `alias`, +/// `runtime-alias-override`, `clamp`, `truncate`, `coerceDefault`, `default`, `onField`, +/// `normalizer` or `onLocate`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Coercion { + pub field_path: String, + pub from: String, + pub to: String, + pub kind: String, +} + +impl Coercion { + pub(crate) fn new(path: &str, from: &str, to: &str, kind: &str) -> Self { + Self { + field_path: path.to_string(), + from: from.to_string(), + to: to.to_string(), + kind: kind.to_string(), + } + } +} + +/// One field's extract descriptor. +#[derive(Debug, Clone, PartialEq)] +pub struct FieldSpec { + pub name: String, + pub kind: FieldKind, + pub required: bool, + pub array: bool, + /// Member symbols (`Enum` only). + pub enum_values: Option>, + /// `@enumAlias`: synonym to member, in declaration order (`Enum` only). + pub enum_alias: Vec<(String, String)>, + /// The numeric range, from the field's numeric validator. + pub min: Option, + pub max: Option, + /// The nested schema (`Object` only). + pub nested: Option>, + /// `@coerceDefault`: the member a present but uncoercible value falls back to. + pub coerce_default: Option, + /// `@default`: the value an absent field is filled with. + pub default_value: Option, + /// `@normalize`: `none`, `collapse` or `strip`. + pub normalize: String, + /// `@xmlText`: the field receives its element's text body. + pub text_content: bool, + /// `validator.array` element-count bounds. + pub min_items: Option, + pub max_items: Option, +} + +impl FieldSpec { + /// A scalar field of `kind`. + #[must_use] + pub fn scalar(name: &str, kind: FieldKind, required: bool) -> Self { + Self { + name: name.to_string(), + kind, + required, + array: false, + enum_values: None, + enum_alias: Vec::new(), + min: None, + max: None, + nested: None, + coerce_default: None, + default_value: None, + normalize: normalize::DEFAULT.to_string(), + text_content: false, + min_items: None, + max_items: None, + } + } + + /// An enum field over `values`. + #[must_use] + pub fn enumeration(name: &str, required: bool, values: Vec) -> Self { + Self { + enum_values: Some(values), + ..Self::scalar(name, FieldKind::Enum, required) + } + } + + /// An object field over `nested`. + #[must_use] + pub fn object(name: &str, required: bool, nested: ExtractSchema) -> Self { + Self { + nested: Some(Box::new(nested)), + ..Self::scalar(name, FieldKind::Object, required) + } + } + + /// The same field as a list. + #[must_use] + pub fn array(mut self) -> Self { + self.array = true; + self + } + + /// The same field with an `@enumAlias` map. + #[must_use] + pub fn aliases(mut self, aliases: Vec<(String, String)>) -> Self { + self.enum_alias = aliases; + self + } + + /// The same field with a numeric range. + #[must_use] + pub fn range(mut self, min: Option, max: Option) -> Self { + self.min = min; + self.max = max; + self + } + + /// The same field with a `@default`. + #[must_use] + pub fn default_value(mut self, value: Option) -> Self { + self.default_value = value; + self + } + + /// The same field with a `@coerceDefault`. + #[must_use] + pub fn coerce_default(mut self, value: Option) -> Self { + self.coerce_default = value; + self + } + + /// The same field with a `@normalize` mode. + #[must_use] + pub fn normalize(mut self, mode: &str) -> Self { + self.normalize = mode.to_string(); + self + } + + /// The same field reading its element's text body (`@xmlText`). + #[must_use] + pub fn text_content(mut self) -> Self { + self.text_content = true; + self + } + + /// The same field with `validator.array` element-count bounds. + #[must_use] + pub fn item_bounds(mut self, min: Option, max: Option) -> Self { + self.min_items = min; + self.max_items = max; + self + } +} + +/// The top-level extract descriptor. `root_name` is the XML root tag, or the logical JSON +/// root name. +#[derive(Debug, Clone, PartialEq)] +pub struct ExtractSchema { + pub format: Format, + pub root_name: String, + pub fields: Vec, +} + +/// A per-field coercion hook: `(field_path, raw, spec)` to a value, or `None` to fall +/// through to the default coercion. +pub type OnField = Box Option>; +/// A per-field normalizer, keyed by path or simple name: `raw` to a value, or `None`. +pub type Normalizer = Box Option>; +/// The document-level locate hook: `(text, format)` to the payload text, or `None` for the +/// default locator. It only decides WHICH text is parsed, never how. +pub type OnLocate = Box Option>; + +/// The bounded runtime override surface. +#[derive(Default)] +pub struct ExtractOptions { + pub tolerance: Tolerance, + /// Runtime enum aliases; they win over the schema's on a key conflict. + pub aliases: Vec<(String, String)>, + pub normalizers: HashMap, + pub on_field: Option, + pub on_locate: Option, + /// XML only: the reply has no enclosing root; its top-level elements are the fields. + pub rootless: bool, +} + +impl ExtractOptions { + /// The same options at `tolerance`. + #[must_use] + pub fn tolerance(mut self, tolerance: Tolerance) -> Self { + self.tolerance = tolerance; + self + } + + /// The same options with `rootless` set. + #[must_use] + pub fn rootless(mut self, rootless: bool) -> Self { + self.rootless = rootless; + self + } +} + +/// What the engine returns: the forgiving data map and its report. +#[derive(Debug, Clone)] +pub struct ExtractionOutcome { + pub data: Map, + pub report: ExtractionReport, +} + +/// Per-field classification, the empty flag and the coercion notes. +#[derive(Debug, Clone, Default)] +pub struct ExtractionReport { + states: IndexMap, + coercions: Vec, + defaulted_required: Vec, + malformed_required: Vec, + empty: bool, +} + +impl ExtractionReport { + pub(crate) fn set(&mut self, path: &str, state: FieldExtraction) { + self.states.insert(path.to_string(), state); + } + + pub(crate) fn add_coercion(&mut self, c: Coercion) { + self.coercions.push(c); + } + + pub(crate) fn mark_empty(&mut self) { + self.empty = true; + } + + pub(crate) fn mark_malformed_required(&mut self, path: &str) { + if !self.malformed_required.iter().any(|p| p == path) { + self.malformed_required.push(path.to_string()); + } + } + + pub(crate) fn mark_defaulted_required(&mut self, path: &str) { + if !self.defaulted_required.iter().any(|p| p == path) { + self.defaulted_required.push(path.to_string()); + } + } + + /// Was there nothing to parse? + #[must_use] + pub fn is_empty(&self) -> bool { + self.empty + } + + /// Every classified path, in classification order. + #[must_use] + pub fn states(&self) -> &IndexMap { + &self.states + } + + /// Every recorded coercion, in order. + #[must_use] + pub fn coercions(&self) -> &[Coercion] { + &self.coercions + } + + fn by_state(&self, s: FieldExtraction) -> Vec { + self.states + .iter() + .filter(|(_, v)| **v == s) + .map(|(k, _)| k.clone()) + .collect() + } + + /// The required fields the reply did not answer. + #[must_use] + pub fn lost_required(&self) -> Vec { + self.by_state(FieldExtraction::LostRequired) + } + + /// Every field classified `MALFORMED`. + #[must_use] + pub fn malformed(&self) -> Vec { + self.by_state(FieldExtraction::Malformed) + } + + /// The required fields the reply answered with a value that could not be used. Their + /// value is absent from the data, as a lost field's is, so the strict gate fails on + /// these too. + #[must_use] + pub fn malformed_required(&self) -> &[String] { + &self.malformed_required + } + + /// Every field whose value came from its `@default`. + #[must_use] + pub fn defaulted(&self) -> Vec { + self.by_state(FieldExtraction::Defaulted) + } + + /// The required fields the reply did not answer whose value was supplied by their + /// `@default`. A default IS an answer, so these are not in [`Self::lost_required`]: + /// a `@default` switches off loss detection for its field, and this is how to see it. + #[must_use] + pub fn defaulted_required(&self) -> &[String] { + &self.defaulted_required + } + + /// Is a required field lost or malformed? This is the strict gate. + #[must_use] + pub fn fails_strict(&self) -> bool { + !self.lost_required().is_empty() || !self.malformed_required.is_empty() + } +} diff --git a/server/rust/metaobjects-render/src/extract/xml_reader.rs b/server/rust/metaobjects-render/src/extract/xml_reader.rs new file mode 100644 index 0000000000..817fd2aac5 --- /dev/null +++ b/server/rust/metaobjects-render/src/extract/xml_reader.rs @@ -0,0 +1,542 @@ +//! Stage 4: the tolerant XML reader for the bounded malformation set. Never fails. +//! +//! An element's child elements, text and attributes map into the field map: +//! +//! - a text-only element with no attributes is its trimmed text; +//! - a self-closing or attributes-only element is a map of its attributes; +//! - an element with child elements is a map of its attributes plus its children (a child +//! wins a name collision), with its own text, if any, under [`TEXT_KEY`]; +//! - an element with text and attributes is the attributes plus the text under [`TEXT_KEY`]; +//! - repeated sibling tags are a list. +//! +//! Mirrors `xml_forgiving_reader.py` and the Java `XmlForgivingReader`. The tag patterns are +//! matched by hand; each function names the pattern it implements. + +use indexmap::IndexMap; + +use super::json_reader::Raw; + +/// The key holding an element's own text when the element is a map. `#` is not a legal +/// XML name character, so it never collides with an attribute or a child. +pub const TEXT_KEY: &str = "#text"; + +const COMMENT_OPEN: &str = ""; +const CDATA_OPEN: &str = ""; + +fn is_name_start(b: u8) -> bool { + b.is_ascii_alphabetic() || b == b'_' +} + +fn is_name_char(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' +} + +/// An open tag: `<([A-Za-z_][A-Za-z0-9_]*)([^>]*?)>`. +struct OpenTag { + start: usize, + end: usize, + name: (usize, usize), + attrs: (usize, usize), +} + +fn find_open_tag(s: &str, from: usize) -> Option { + let b = s.as_bytes(); + let mut i = from; + while i < b.len() { + if b[i] == b'<' && i + 1 < b.len() && is_name_start(b[i + 1]) { + let mut j = i + 2; + while j < b.len() && is_name_char(b[j]) { + j += 1; + } + let gt = s[j..].find('>')? + j; + return Some(OpenTag { + start: i, + end: gt + 1, + name: (i + 1, j), + attrs: (j, gt), + }); + } + i += 1; + } + None +} + +/// The length of `\s*>` at `at`, if there is one. +fn ws_then_gt(s: &str, at: usize) -> Option { + let rest = &s[at..]; + let trimmed = rest.trim_start(); + trimmed + .starts_with('>') + .then(|| rest.len() - trimmed.len() + 1) +} + +/// Any close tag in `s[from..to]`: ``, as `(start, end, name)`. +fn find_any_close(s: &str, from: usize, to: usize) -> Option<(usize, usize, String)> { + let s = &s[..to]; + let b = s.as_bytes(); + let mut i = from; + while i + 2 < b.len() { + if b[i] == b'<' && b[i + 1] == b'/' && is_name_start(b[i + 2]) { + let mut j = i + 3; + while j < b.len() && is_name_char(b[j]) { + j += 1; + } + if let Some(n) = ws_then_gt(s, j) { + return Some((i, j + n, s[i + 2..j].to_string())); + } + } + i += 1; + } + None +} + +fn name_at(s: &str, at: usize, name: &str, ci: bool) -> bool { + s.get(at..at + name.len()).is_some_and(|got| { + if ci { + got.eq_ignore_ascii_case(name) + } else { + got == name + } + }) +} + +/// The close tag of `name`, from `from`: ``. +fn find_named_close(s: &str, from: usize, name: &str, ci: bool) -> Option<(usize, usize)> { + let mut at = from; + while let Some(rel) = s[at..].find("])`? +fn has_named_open(s: &str, from: usize, to: usize, name: &str, ci: bool) -> bool { + let s = &s[..to]; + let mut at = from; + while let Some(rel) = s[at..].find('<') { + let i = at + rel; + if name_at(s, i + 1, name, ci) { + let next = s[i + 1 + name.len()..].chars().next(); + if next.is_some_and(|c| c.is_whitespace() || c == '/' || c == '>') { + return true; + } + } + at = i + 1; + } + false +} + +/// Rewrite every comment and CDATA section through `replace(is_comment, region)`, scanning +/// left to right so a comment marker inside CDATA (or the reverse) is not markup. An +/// unclosed comment stays text; an unclosed CDATA section runs to the end. +fn rewrite_regions(text: &str, replace: impl Fn(bool, &str) -> String) -> String { + let mut out = String::with_capacity(text.len()); + let mut pos = 0; + let mut from = 0; + loop { + let c = text[from..].find(COMMENT_OPEN).map(|x| x + from); + let d = text[from..].find(CDATA_OPEN).map(|x| x + from); + let is_comment = match (c, d) { + (Some(c), Some(d)) => c < d, + (Some(_), None) => true, + _ => false, + }; + let Some(start) = (if is_comment { c } else { d }) else { + break; + }; + let end = if is_comment { + match text[start + COMMENT_OPEN.len()..].find(COMMENT_CLOSE) { + Some(e) => start + COMMENT_OPEN.len() + e + COMMENT_CLOSE.len(), + None => { + from = start + COMMENT_OPEN.len(); + continue; + } + } + } else { + match text[start + CDATA_OPEN.len()..].find(CDATA_CLOSE) { + Some(e) => start + CDATA_OPEN.len() + e + CDATA_CLOSE.len(), + None => text.len(), + } + }; + out.push_str(&text[pos..start]); + out.push_str(&replace(is_comment, &text[start..end])); + pos = end; + from = end; + } + out.push_str(&text[pos..]); + out +} + +/// `text` with comments and CDATA blanked to spaces, byte for byte, so indices hold: the +/// view the locators search. +#[must_use] +pub fn mask_non_markup(text: &str) -> String { + rewrite_regions(text, |_, region| " ".repeat(region.len())) +} + +/// Drop comments; turn CDATA into its text with `& < >` escaped, so the tag scanner cannot +/// split it and the entity decode restores it exactly. +fn prepare(text: &str) -> String { + rewrite_regions(text, |is_comment, region| { + if is_comment { + return String::new(); + } + let body = region + .strip_prefix(CDATA_OPEN) + .map(|r| r.strip_suffix(CDATA_CLOSE).unwrap_or(r)) + .unwrap_or(region); + body.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + }) +} + +/// Decode the predefined entities and numeric references in one pass. An unknown or +/// out-of-range reference stays as written. +fn decode_entities(s: &str) -> String { + if !s.contains('&') { + return s.to_string(); + } + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(amp) = rest.find('&') { + out.push_str(&rest[..amp]); + let after = &rest[amp + 1..]; + match decode_one(after) { + Some((decoded, used)) => { + out.push(decoded); + rest = &after[used..]; + } + None => { + out.push('&'); + rest = after; + } + } + } + out.push_str(rest); + out +} + +/// One entity body after `&` (`#x[0-9a-fA-F]+;`, `#[0-9]+;` or a named one), as the +/// character and the bytes it used. +fn decode_one(after: &str) -> Option<(char, usize)> { + for (name, c) in [ + ("lt;", '<'), + ("gt;", '>'), + ("amp;", '&'), + ("quot;", '"'), + ("apos;", '\''), + ] { + if after.starts_with(name) { + return Some((c, name.len())); + } + } + let num = after.strip_prefix('#')?; + let (digits, radix, skip) = match num.strip_prefix('x') { + Some(hex) => (hex, 16, 2), + None => (num, 10, 1), + }; + let len = digits + .bytes() + .take_while(|b| { + if radix == 16 { + b.is_ascii_hexdigit() + } else { + b.is_ascii_digit() + } + }) + .count(); + if len == 0 || !digits[len..].starts_with(';') { + return None; + } + let cp = u32::from_str_radix(&digits[..len], radix).ok()?; + if cp == 0 { + return None; + } + char::from_u32(cp).map(|c| (c, skip + len + 1)) +} + +/// Parse `raw_span` (a `...` span) into its fields. +#[must_use] +pub fn read(raw_span: &str, ci: bool) -> IndexMap { + let mut out = IndexMap::new(); + if raw_span.trim().is_empty() { + return out; + } + let span = prepare(raw_span); + let Some(gt) = span.find('>') else { + return out; + }; + let inner_end = match span.rfind(" gt => root_end, + _ => span.len(), + }; + parse_children(&span[gt + 1..inner_end], ci, &mut out, None, false); + out +} + +/// Parse a rootless reply: its top-level elements are the fields. +#[must_use] +pub fn read_rootless(text: &str, ci: bool) -> IndexMap { + let mut out = IndexMap::new(); + if text.trim().is_empty() { + return out; + } + parse_children(&prepare(text), ci, &mut out, None, false); + out +} + +/// Parse `inner`'s elements into `out`. With `loose`, the text between the elements (an +/// element's own text in mixed content) is appended to it. `literal_unclosed` is set for +/// the body of an element that DID close: an open tag there that directly follows an +/// identifier character and has no close tag after it (`List and ...`) is prose. +fn parse_children( + inner: &str, + ci: bool, + out: &mut IndexMap, + mut loose: Option<&mut Vec>, + literal_unclosed: bool, +) { + let b = inner.as_bytes(); + let mut pos = 0; + let mut scan = 0; + while let Some(m) = find_open_tag(inner, scan) { + let attrs_text = &inner[m.attrs.0..m.attrs.1]; + if literal_unclosed + && m.start > 0 + && is_name_char(b[m.start - 1]) + && !attrs_text.trim_end().ends_with('/') + && find_any_close(inner, m.end, inner.len()).is_none() + { + scan = m.end; + continue; + } + if let Some(l) = loose.as_deref_mut() { + l.push(inner[pos..m.start].to_string()); + } + let tag = &inner[m.name.0..m.name.1]; + let key = if ci { + tag.to_lowercase() + } else { + tag.to_string() + }; + + let mut raw_attrs = attrs_text.trim(); + let self_closing = raw_attrs.ends_with('/'); + if self_closing { + raw_attrs = raw_attrs[..raw_attrs.len() - 1].trim(); + } + let attrs = parse_attrs(raw_attrs, ci); + + if self_closing { + let v = if attrs.is_empty() { + Raw::Str(String::new()) + } else { + Raw::Map(attrs) + }; + accumulate(out, key, v); + pos = m.end; + scan = pos; + continue; + } + + let content_start = m.end; + let close = find_named_close(inner, content_start, tag, ci); + let (mut content_end, mut next) = match close { + Some((cs, ce)) => (cs, ce), + None => { + let (ce, nx) = match find_open_tag(inner, content_start) { + Some(sib) if inner[content_start..sib.start].trim().is_empty() => { + (inner.len(), inner.len()) + } + Some(sib) => (sib.start, sib.start), + None => (inner.len(), inner.len()), + }; + (ce, nx) + } + }; + if close.is_none() + && let Some((s, e)) = find_stray_close(inner, content_start, content_end, ci) + { + content_end = s; + next = e; + } + let content = &inner[content_start..content_end]; + accumulate(out, key, combine(attrs, content, ci, close.is_some())); + pos = next; + scan = next; + } + if let Some(l) = loose { + l.push(inner[pos..].to_string()); + } +} + +/// The first close tag in `inner[from..to]` whose element was never opened after `from`. +fn find_stray_close(inner: &str, from: usize, to: usize, ci: bool) -> Option<(usize, usize)> { + let mut at = from; + loop { + let (s, e, name) = find_any_close(inner, at, to)?; + if !has_named_open(inner, from, s, &name, ci) { + return Some((s, e)); + } + at = e; + } +} + +fn combine(attrs: IndexMap, content: &str, ci: bool, closed: bool) -> Raw { + if content.contains('<') { + let mut nested = IndexMap::new(); + let mut loose = Vec::new(); + parse_children(content, ci, &mut nested, Some(&mut loose), closed); + if !nested.is_empty() { + let mut merged = attrs; + for (k, v) in nested { + merged.insert(k, v); + } + let text = mixed_text(&loose); + if !text.is_empty() { + merged.insert(TEXT_KEY.to_string(), Raw::Str(text)); + } + return Raw::Map(merged); + } + } + text_value(attrs, content) +} + +fn remove_close_tags(seg: &str) -> String { + let mut out = String::with_capacity(seg.len()); + let mut pos = 0; + while let Some((s, e, _)) = find_any_close(seg, pos, seg.len()) { + out.push_str(&seg[pos..s]); + pos = e; + } + out.push_str(&seg[pos..]); + out +} + +fn mixed_text(segments: &[String]) -> String { + segments + .iter() + .map(|seg| decode_entities(remove_close_tags(seg).trim())) + .filter(|t| !t.is_empty()) + .collect::>() + .join(" ") +} + +fn text_value(attrs: IndexMap, content: &str) -> Raw { + let text = decode_entities(content.trim()); + if attrs.is_empty() { + return Raw::Str(text); + } + let mut m = attrs; + m.insert(TEXT_KEY.to_string(), Raw::Str(text)); + Raw::Map(m) +} + +/// Attributes: `([A-Za-z_:][A-Za-z0-9_:.\-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))`, +/// every match in order. The first of a repeated name wins. +fn parse_attrs(raw: &str, ci: bool) -> IndexMap { + let mut attrs = IndexMap::new(); + let b = raw.as_bytes(); + let mut i = 0; + while i < b.len() { + let Some((name, value, end)) = attr_at(raw, i) else { + i += 1; + continue; + }; + let name = if ci { name.to_lowercase() } else { name }; + attrs + .entry(name) + .or_insert_with(|| Raw::Str(decode_entities(&value))); + i = end; + } + attrs +} + +fn attr_at(raw: &str, i: usize) -> Option<(String, String, usize)> { + let b = raw.as_bytes(); + if !(b[i].is_ascii_alphabetic() || b[i] == b'_' || b[i] == b':') { + return None; + } + let mut j = i + 1; + while j < b.len() && (b[j].is_ascii_alphanumeric() || matches!(b[j], b'_' | b':' | b'.' | b'-')) + { + j += 1; + } + let name = raw[i..j].to_string(); + let rest = &raw[j..]; + let after_ws = rest.trim_start(); + let after_eq = after_ws.strip_prefix('=')?; + let value_part = after_eq.trim_start(); + let value_start = raw.len() - value_part.len(); + for q in ['"', '\''] { + if let Some(body) = value_part.strip_prefix(q) + && let Some(close) = body.find(q) + { + return Some((name, body[..close].to_string(), value_start + 1 + close + 1)); + } + } + let len = value_part + .find(|c: char| c.is_whitespace() || c == '/' || c == '>') + .unwrap_or(value_part.len()); + if len == 0 { + return None; + } + Some((name, value_part[..len].to_string(), value_start + len)) +} + +fn accumulate(out: &mut IndexMap, key: String, value: Raw) { + match out.get_mut(&key) { + None => { + out.insert(key, value); + } + Some(Raw::List(xs)) => xs.push(value), + Some(existing) => { + let first = std::mem::replace(existing, Raw::Null); + *existing = Raw::List(vec![first, value]); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(v: &str) -> Raw { + Raw::Str(v.to_string()) + } + + #[test] + fn reads_children_attrs_and_repeats() { + let m = read( + "1hi & bye3", + true, + ); + assert_eq!(m["a"], Raw::List(vec![s("1"), s("3")])); + let Raw::Map(b) = &m["b"] else { panic!() }; + assert_eq!(b["x"], s("2")); + let Raw::Map(t) = &m["t"] else { panic!() }; + assert_eq!(t[TEXT_KEY], s("hi & bye")); + } + + #[test] + fn cdata_and_comments() { + let m = read("", true); + assert_eq!(m["a"], s("xonetwo", true); + assert_eq!(m["a"], s("one")); + assert_eq!(m["b"], s("two")); + } +} diff --git a/server/rust/metaobjects-render/src/lib.rs b/server/rust/metaobjects-render/src/lib.rs new file mode 100644 index 0000000000..80d4615020 --- /dev/null +++ b/server/rust/metaobjects-render/src/lib.rs @@ -0,0 +1,24 @@ +//! MetaObjects prompt rendering for Rust (FR-004). +//! +//! A `template.*` body is plain Mustache. [`render`] renders it over a JSON payload the +//! same way every MetaObjects port does: partials expanded ahead of time, every +//! `{{value}}` escaped for the template's format, derived `has` and `-last` +//! accessors on the payload, and a fail-closed `maxChars` budget. The engine underneath is +//! the `mustache-ng` crate; what is specific to MetaObjects sits here, on top of it. The +//! shared `fixtures/render-conformance/` corpus holds this crate to the other ports. +//! +//! [`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/`. +//! [`prompt`] writes the output-format fragment that asks for that answer. + +pub mod accessors; +pub mod escapers; +pub mod extract; +pub mod prompt; +pub mod render; +pub mod tags; + +pub use render::{ + Body, InMemoryProvider, MAX_DEPTH, Provider, RenderError, RenderRequest, render, + render_serialize, +}; diff --git a/server/rust/metaobjects-render/src/prompt.rs b/server/rust/metaobjects-render/src/prompt.rs new file mode 100644 index 0000000000..c6d52128e6 --- /dev/null +++ b/server/rust/metaobjects-render/src/prompt.rs @@ -0,0 +1,371 @@ +//! The output-format prompt fragment (FR-010): "produce your answer like this". +//! +//! Renders an [`OutputFormatSpec`] into the text that teaches a model how to shape its +//! answer, in one of three styles ([`PromptStyle`]) and two formats. Guidance lives in +//! prose, inline placeholders or a filled skeleton, never in comments, which models ignore. +//! The text is byte-identical to the reference (`OutputFormatRenderer` in every port), +//! held by `fixtures/output-prompt-conformance/`. + +use std::collections::{HashMap, HashSet}; + +use crate::escapers::{self, FORMAT_JSON, FORMAT_XML}; +use crate::extract::coerce::is_ascii_numeric; +use crate::extract::{FieldKind, Format}; + +const INDENT: &str = " "; +const MAX_NEST_DEPTH: usize = 8; + +/// How the fragment teaches the model. The `@promptStyle` values are `guide` (the +/// default), `inline` and `exampleOnly`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum PromptStyle { + /// A prose field list, then an example skeleton. + #[default] + Guide, + /// One skeleton whose values are placeholders or enum choices. + Inline, + /// A filled example skeleton and nothing else. + ExampleOnly, +} + +impl PromptStyle { + /// The style a `@promptStyle` value names; absent or unknown is `Guide`. + #[must_use] + pub fn from_attr(value: Option<&str>) -> Self { + match value { + Some("inline") => Self::Inline, + Some("exampleOnly") => Self::ExampleOnly, + _ => Self::Guide, + } + } +} + +/// One field of the fragment. `name` must be identifier-safe: it is not escaped. +#[derive(Debug, Clone, PartialEq)] +pub struct PromptField { + pub name: String, + pub kind: FieldKind, + pub required: bool, + pub array: bool, + pub enum_values: Option>, + /// Member to its documentation, shown under the member list in `guide`. + pub enum_doc: Option>, + pub example: Option, + pub instruction: Option, + pub nested: Option>, +} + +impl PromptField { + /// A field with no example, instruction, members or nested shape. + #[must_use] + pub fn new(name: &str, kind: FieldKind, required: bool) -> Self { + Self { + name: name.to_string(), + kind, + required, + array: false, + enum_values: None, + enum_doc: None, + example: None, + instruction: None, + nested: None, + } + } +} + +/// A complete output-format descriptor. `root_name` must be identifier-safe. +#[derive(Debug, Clone, PartialEq)] +pub struct OutputFormatSpec { + pub format: Format, + pub root_name: String, + pub style: PromptStyle, + pub fields: Vec, +} + +/// Render-time overrides of the metadata defaults: a style, and per-field examples and +/// instructions. +#[derive(Debug, Clone, Default)] +pub struct PromptOverrides { + pub style: Option, + pub examples: HashMap, + pub instructions: HashMap, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Mode { + Example, + Inline, +} + +/// The specs on the current nesting path, by address: two equal sibling specs must both +/// expand, so the guard is identity, not equality. +type Path = HashSet; + +fn key(spec: &OutputFormatSpec) -> usize { + std::ptr::from_ref(spec) as usize +} + +/// Render `spec` as an output-format fragment. The style is the override's, else the spec's. +#[must_use] +pub fn render_output_format(spec: &OutputFormatSpec, overrides: &PromptOverrides) -> String { + let r = Renderer { o: overrides }; + match overrides.style.unwrap_or(spec.style) { + PromptStyle::ExampleOnly => r.skeleton(spec, Mode::Example), + PromptStyle::Inline => r.skeleton(spec, Mode::Inline), + PromptStyle::Guide => { + let mut path = Path::from([key(spec)]); + format!( + "Fill in each field as described below:\n{}\nRespond exactly like this:\n{}", + r.guide_fields(spec, "", &mut path, 0), + r.skeleton(spec, Mode::Example) + ) + } + } +} + +fn esc(format: &str, s: &str) -> String { + escapers::escape(format, s).unwrap_or_else(|| s.to_string()) +} + +struct Renderer<'a> { + o: &'a PromptOverrides, +} + +impl Renderer<'_> { + fn skeleton(&self, spec: &OutputFormatSpec, mode: Mode) -> String { + let mut path = Path::from([key(spec)]); + match spec.format { + Format::Xml => format!( + "<{root}>\n{}", + self.xml_body(spec, INDENT, mode, &mut path, 0), + root = spec.root_name + ), + Format::Json => self.json_object(spec, "", mode, &mut path, 0), + } + } + + fn instruction<'f>(&'f self, f: &'f PromptField) -> Option<&'f str> { + self.o + .instructions + .get(&f.name) + .map(String::as_str) + .or(f.instruction.as_deref()) + } + + fn declared_example<'f>(&'f self, f: &'f PromptField) -> Option<&'f str> { + self.o + .examples + .get(&f.name) + .map(String::as_str) + .or(f.example.as_deref()) + } + + /// An enum with no declared example shows its members, never one pre-filled member: + /// a model shown a filled-in value copies it. + fn example(&self, f: &PromptField) -> String { + if let Some(e) = self.declared_example(f) { + return e.to_string(); + } + match &f.enum_values { + Some(values) if f.kind == FieldKind::Enum && !values.is_empty() => values.join(" | "), + _ => format!("{{{}}}", f.name), + } + } + + fn inline_content(&self, f: &PromptField) -> String { + if f.kind == FieldKind::Enum + && let Some(values) = f.enum_values.as_ref().filter(|v| !v.is_empty()) + { + return values.join(" | "); + } + if f.kind == FieldKind::Boolean { + return "true | false".to_string(); + } + format!("{{{}}}", self.instruction(f).unwrap_or(&f.name)) + } + + fn guide_fields( + &self, + spec: &OutputFormatSpec, + prefix: &str, + path: &mut Path, + depth: usize, + ) -> String { + let mut sb = String::new(); + for f in &spec.fields { + let display = format!("{prefix}{}", f.name); + sb.push_str(&self.guide_entry(f, &display)); + if let Some(nested) = expandable(f, path, depth) { + let child = if f.array { + format!("{display}[].") + } else { + format!("{display}.") + }; + path.insert(key(nested)); + sb.push_str(&self.guide_fields(nested, &child, path, depth + 1)); + path.remove(&key(nested)); + } + } + sb + } + + fn guide_entry(&self, f: &PromptField, display: &str) -> String { + let req = if f.required { "required" } else { "optional" }; + let mut sb = format!("- {display} ({req})"); + if let Some(i) = self.instruction(f) { + sb.push_str(&format!(": {i}")); + } + sb.push('\n'); + if f.kind == FieldKind::Enum + && let Some(values) = f.enum_values.as_ref().filter(|v| !v.is_empty()) + { + sb.push_str(&format!(" one of {}\n", values.join(", "))); + if let Some(doc) = &f.enum_doc { + for v in values { + if let Some(d) = doc.get(v) { + sb.push_str(&format!(" {v} = {d}\n")); + } + } + } + } + if let Some(eg) = self.declared_example(f) { + sb.push_str(&format!(" e.g. {eg}\n")); + } + sb + } + + fn json_object( + &self, + spec: &OutputFormatSpec, + brace_indent: &str, + mode: Mode, + path: &mut Path, + depth: usize, + ) -> String { + if spec.fields.is_empty() { + return format!("{{\n{brace_indent}}}"); + } + let field_indent = format!("{brace_indent}{INDENT}"); + let lines: Vec = spec + .fields + .iter() + .map(|f| { + format!( + "{field_indent}\"{}\": {}", + f.name, + self.json_value(f, &field_indent, mode, path, depth) + ) + }) + .collect(); + format!("{{\n{}\n{brace_indent}}}", lines.join(",\n")) + } + + fn json_value( + &self, + f: &PromptField, + indent: &str, + mode: Mode, + path: &mut Path, + depth: usize, + ) -> String { + if f.array { + let elem_indent = format!("{indent}{INDENT}"); + let elem = match expandable(f, path, depth) { + Some(nested) => { + path.insert(key(nested)); + let e = self.json_object(nested, &elem_indent, mode, path, depth + 1); + path.remove(&key(nested)); + e + } + None => self.json_leaf(f, mode), + }; + return format!("[\n{elem_indent}{elem}\n{indent}]"); + } + if f.kind == FieldKind::Object + && let Some(nested) = expandable(f, path, depth) + { + path.insert(key(nested)); + let out = self.json_object(nested, indent, mode, path, depth + 1); + path.remove(&key(nested)); + return out; + } + self.json_leaf(f, mode) + } + + /// A number or boolean is unquoted wherever the skeleton holds its placeholder: a + /// quoted one taught the model to answer a number as a JSON string. + fn json_leaf(&self, f: &PromptField, mode: Mode) -> String { + let unquoted = is_numeric_kind(f.kind); + if mode == Mode::Inline { + let content = self.inline_content(f); + return if unquoted { + content + } else { + format!("\"{}\"", esc(FORMAT_JSON, &content)) + }; + } + if unquoted && self.declared_example(f).is_none() { + return format!("{{{}}}", f.name); + } + let value = self.example(f); + if unquoted && (value == "true" || value == "false" || is_ascii_numeric(value.trim())) { + return value; + } + format!("\"{}\"", esc(FORMAT_JSON, &value)) + } + + fn xml_body( + &self, + spec: &OutputFormatSpec, + indent: &str, + mode: Mode, + path: &mut Path, + depth: usize, + ) -> String { + spec.fields + .iter() + .map(|f| self.xml_field(f, indent, mode, path, depth)) + .collect() + } + + fn xml_field( + &self, + f: &PromptField, + indent: &str, + mode: Mode, + path: &mut Path, + depth: usize, + ) -> String { + if let Some(nested) = expandable(f, path, depth) { + path.insert(key(nested)); + let body = self.xml_body(nested, &format!("{indent}{INDENT}"), mode, path, depth + 1); + path.remove(&key(nested)); + return format!("{indent}<{n}>\n{body}{indent}\n", n = f.name); + } + let content = match mode { + Mode::Inline => self.inline_content(f), + Mode::Example => self.example(f), + }; + format!( + "{indent}<{n}>{}\n", + esc(FORMAT_XML, &content), + n = f.name + ) + } +} + +fn is_numeric_kind(kind: FieldKind) -> bool { + matches!( + kind, + FieldKind::Int | FieldKind::Long | FieldKind::Double | FieldKind::Boolean + ) +} + +/// The nested spec of an OBJECT field that may expand here: within the depth bound and not +/// already on the path. +fn expandable<'f>(f: &'f PromptField, path: &Path, depth: usize) -> Option<&'f OutputFormatSpec> { + if f.kind != FieldKind::Object || depth >= MAX_NEST_DEPTH { + return None; + } + f.nested.as_deref().filter(|n| !path.contains(&key(n))) +} diff --git a/server/rust/metaobjects-render/src/render.rs b/server/rust/metaobjects-render/src/render.rs new file mode 100644 index 0000000000..aedb0fdcea --- /dev/null +++ b/server/rust/metaobjects-render/src/render.rs @@ -0,0 +1,395 @@ +//! The render pipeline for `template.*` (FR-004). +//! +//! Resolve the body (inline, or by reference through a [`Provider`]), expand partials ahead +//! of time (cycle-guarded, at most [`MAX_DEPTH`] deep), render the result with the +//! `mustache-ng` engine over the payload and its derived accessors, escaping every +//! `{{value}}` for the template's format, then apply the `maxChars` budget, which fails +//! rather than truncates. +//! +//! Expanding partials first gives the same whitespace in every port and keeps cycle +//! detection here. The engine's own HTML escaping is never used: each escaped tag is +//! rewritten to a raw one between two marker characters, and the text between the markers +//! is escaped for the format once the engine has finished. Set-delimiter tags are refused, +//! as the Python and C# renderers refuse them. + +use std::collections::HashMap; +use std::fmt; + +use mustache::Data; +use serde::Serialize; +use serde_json::Value; + +use crate::accessors::with_derived_accessors; +use crate::escapers::{self, FORMAT_TEXT}; +use crate::tags::{self, TagKind}; + +/// How deep partials may nest before the render fails. +pub const MAX_DEPTH: usize = 32; + +/// Opens an escaped value in the engine's output. U+FDD0 and U+FDD1 are Unicode +/// noncharacters, reserved for exactly this kind of internal use. +const OPEN_MARK: char = '\u{FDD0}'; +/// Closes an escaped value in the engine's output. +const CLOSE_MARK: char = '\u{FDD1}'; + +/// File extensions of Jinja templates (ADR-0061), which this renderer does not run. +const JINJA_EXTENSIONS: [&str; 2] = [".jinja", ".j2"]; + +/// Anything that goes wrong in a render. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RenderError(pub String); + +impl fmt::Display for RenderError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for RenderError {} + +fn err(message: impl Into) -> Result { + Err(RenderError(message.into())) +} + +/// Resolves a template or partial reference to its text. +pub trait Provider { + /// The text `reference` names, or `None` when there is none. + fn resolve(&self, reference: &str) -> Option; +} + +/// A provider over a fixed map of references to bodies. +#[derive(Debug, Clone, Default)] +pub struct InMemoryProvider { + entries: HashMap, +} + +impl InMemoryProvider { + /// A provider over `entries`. + #[must_use] + pub fn new(entries: HashMap) -> Self { + Self { entries } + } +} + +impl Provider for InMemoryProvider { + fn resolve(&self, reference: &str) -> Option { + self.entries.get(reference).cloned() + } +} + +/// Where a render's body comes from. +#[derive(Debug, Clone, Copy)] +pub enum Body<'a> { + /// Inline template text. + Inline(&'a str), + /// A reference the provider resolves. + Ref(&'a str), +} + +/// One render call. +pub struct RenderRequest<'a> { + /// The template body. + pub body: Body<'a>, + /// The data the template walks. + pub payload: &'a Value, + /// Resolves partials, and the body when it is a reference. + pub provider: &'a dyn Provider, + /// One of [`escapers::FORMATS`]; `text` escapes nothing. + pub format: &'a str, + /// A fail-closed output budget in characters. + pub max_chars: Option, +} + +impl<'a> RenderRequest<'a> { + /// A `text` render of `body` over `payload` with no budget. + #[must_use] + pub fn new(body: Body<'a>, payload: &'a Value, provider: &'a dyn Provider) -> Self { + Self { + body, + payload, + provider, + format: FORMAT_TEXT, + max_chars: None, + } + } + + /// The same request in `format`. + #[must_use] + pub fn format(mut self, format: &'a str) -> Self { + self.format = format; + self + } + + /// The same request with a `maxChars` budget. + #[must_use] + pub fn max_chars(mut self, max_chars: Option) -> Self { + self.max_chars = max_chars; + self + } +} + +/// Render `request`. +/// +/// # Errors +/// An unknown format, an unresolved body or partial, a partial cycle or one nested deeper +/// than [`MAX_DEPTH`], a Jinja partial, a template syntax error, a set-delimiter tag, a +/// marker character in the template or payload, or output over the `maxChars` budget. +pub fn render(request: &RenderRequest<'_>) -> Result { + if !escapers::is_format(request.format) { + return err(format!("unknown render format \"{}\"", request.format)); + } + let body = match request.body { + Body::Inline(text) => text.to_string(), + Body::Ref(reference) => { + refuse_jinja(reference)?; + match request.provider.resolve(reference) { + Some(text) => text, + None => return err(format!("unresolved ref: {reference}")), + } + } + }; + let expanded = pre_expand_partials(&body, request.provider, &mut Vec::new())?; + let source = mark_escaped_tags(&expanded, request.format)?; + let payload = with_derived_accessors(request.payload); + let data = to_data(&payload)?; + let template = mustache::compile_str(&source) + .map_err(|e| RenderError(format!("template syntax error: {e}")))?; + let raw = template + .render_data_to_string(&data) + .map_err(|e| RenderError(format!("render failed: {e}")))?; + let out = escape_marked(&raw, request.format)?; + check_budget(out, request.max_chars) +} + +/// Render `template` over a serializable payload (a generated payload type, say). +/// +/// # Errors +/// The payload does not serialize to JSON, or anything [`render`] refuses. +pub fn render_serialize( + body: Body<'_>, + payload: &T, + provider: &dyn Provider, + format: &str, + max_chars: Option, +) -> Result { + let value = serde_json::to_value(payload) + .map_err(|e| RenderError(format!("payload does not serialize: {e}")))?; + render(&RenderRequest { + body, + payload: &value, + provider, + format, + max_chars, + }) +} + +fn check_budget(out: String, max_chars: Option) -> Result { + if let Some(cap) = max_chars { + let len = out.chars().count(); + if len > cap { + return err(format!("render exceeded maxChars budget: {len} > {cap}")); + } + } + Ok(out) +} + +fn refuse_jinja(reference: &str) -> Result<(), RenderError> { + if JINJA_EXTENSIONS.iter().any(|ext| reference.ends_with(ext)) { + return err(format!( + "\"{reference}\" is a Jinja template (ADR-0061); the Rust renderer runs Mustache only" + )); + } + Ok(()) +} + +fn syntax(e: &tags::SyntaxError) -> RenderError { + RenderError(format!("template syntax error: {e}")) +} + +fn pre_expand_partials( + text: &str, + provider: &dyn Provider, + stack: &mut Vec, +) -> Result { + if stack.len() >= MAX_DEPTH { + return err(format!( + "partial depth exceeded {MAX_DEPTH} (chain: {})", + stack.join(" -> ") + )); + } + let found = tags::scan(text).map_err(|e| syntax(&e))?; + if found.iter().any(|t| t.kind == TagKind::Delimiters) { + return err("set-delimiter tags ({{=<% %>=}}) are not supported by the Rust renderer"); + } + let mut out = String::with_capacity(text.len()); + let mut pos = 0; + for tag in found.iter().filter(|t| t.kind == TagKind::Partial) { + let reference = &tag.value; + if stack.contains(reference) { + return err(format!( + "partial cycle: {} -> {reference}", + stack.join(" -> ") + )); + } + refuse_jinja(reference)?; + let Some(body) = provider.resolve(reference) else { + return err(format!("unresolved partial: {reference}")); + }; + stack.push(reference.clone()); + let expanded = pre_expand_partials(&body, provider, stack); + stack.pop(); + out.push_str(&text[pos..tag.start]); + out.push_str(&expanded?); + pos = tag.end; + } + out.push_str(&text[pos..]); + Ok(out) +} + +/// Rewrite every escaped `{{name}}` as a raw `{{&name}}`, between the markers unless the +/// format escapes nothing. Raw tags stay as they are. +fn mark_escaped_tags(text: &str, format: &str) -> Result { + if text.contains([OPEN_MARK, CLOSE_MARK]) { + return err("template contains a reserved character (U+FDD0 or U+FDD1)"); + } + let found = tags::scan(text).map_err(|e| syntax(&e))?; + let identity = escapers::is_identity(format); + let mut out = String::with_capacity(text.len() + 16); + let mut pos = 0; + for tag in found.iter().filter(|t| t.kind == TagKind::Name) { + out.push_str(&text[pos..tag.start]); + if identity { + out.push_str(&format!("{{{{&{}}}}}", tag.value)); + } else { + out.push(OPEN_MARK); + out.push_str(&format!("{{{{&{}}}}}", tag.value)); + out.push(CLOSE_MARK); + } + pos = tag.end; + } + out.push_str(&text[pos..]); + Ok(out) +} + +fn escape_marked(raw: &str, format: &str) -> Result { + if escapers::is_identity(format) { + return Ok(raw.to_string()); + } + let mut out = String::with_capacity(raw.len()); + let mut rest = raw; + while let Some(open) = rest.find(OPEN_MARK) { + out.push_str(&rest[..open]); + let after = &rest[open + OPEN_MARK.len_utf8()..]; + let Some(close) = after.find(CLOSE_MARK) else { + return err("internal: unterminated escape marker"); + }; + let escaped = escapers::escape(format, &after[..close]) + .ok_or_else(|| RenderError(format!("unknown render format \"{format}\"")))?; + out.push_str(&escaped); + rest = &after[close + CLOSE_MARK.len_utf8()..]; + } + out.push_str(rest); + Ok(out) +} + +/// The payload as the engine's data. Numbers become their shortest text, with a whole +/// float written as an integer (`2.0` -> `2`), as the other ports write them. +fn to_data(value: &Value) -> Result { + Ok(match value { + Value::Null => Data::Null, + Value::Bool(b) => Data::Bool(*b), + Value::Number(n) => Data::String(number_text(n)), + Value::String(s) => { + if s.contains([OPEN_MARK, CLOSE_MARK]) { + return err("payload contains a reserved character (U+FDD0 or U+FDD1)"); + } + // An empty string is falsy for a section AND for an inverted section. The + // engine skips `{{#x}}` over "" but also skips `{{^x}}`, so "" goes in as + // null, which renders the same in every other position. + if s.is_empty() { + Data::Null + } else { + Data::String(s.clone()) + } + } + Value::Array(items) => Data::Vec(items.iter().map(to_data).collect::>()?), + Value::Object(map) => Data::Map( + map.iter() + .map(|(k, v)| Ok((k.clone(), to_data(v)?))) + .collect::>()?, + ), + }) +} + +fn number_text(n: &serde_json::Number) -> String { + if n.is_i64() || n.is_u64() { + return n.to_string(); + } + match n.as_f64() { + Some(f) if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e21 => format!("{f:.0}"), + Some(f) => f.to_string(), + None => n.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn run(template: &str, payload: &Value, format: &str) -> Result { + let provider = InMemoryProvider::default(); + render(&RenderRequest::new(Body::Inline(template), payload, &provider).format(format)) + } + + #[test] + fn escapes_per_format_and_raw_bypasses() { + let p = json!({"v": "a 3"); + } + + #[test] + fn partial_cycles_and_missing_partials_fail() { + let provider = InMemoryProvider::new(HashMap::from([ + ("a".to_string(), "{{> b}}".to_string()), + ("b".to_string(), "{{> a}}".to_string()), + ])); + let p = json!({}); + let e = render(&RenderRequest::new(Body::Ref("a"), &p, &provider)).unwrap_err(); + assert!(e.0.starts_with("partial cycle"), "{e}"); + let e = run("{{> nope}}", &p, "text").unwrap_err(); + assert_eq!(e.0, "unresolved partial: nope"); + } + + #[test] + fn refuses_what_it_does_not_run() { + let p = json!({}); + assert!(run("{{=<% %>=}}", &p, "text").is_err()); + assert!(run("x", &p, "yaml").is_err()); + assert!(run("\u{FDD0}", &p, "text").is_err()); + let provider = InMemoryProvider::default(); + assert!(render(&RenderRequest::new(Body::Ref("t.jinja"), &p, &provider)).is_err()); + } +} diff --git a/server/rust/metaobjects-render/src/tags.rs b/server/rust/metaobjects-render/src/tags.rs new file mode 100644 index 0000000000..002c47e1e7 --- /dev/null +++ b/server/rust/metaobjects-render/src/tags.rs @@ -0,0 +1,213 @@ +//! One Mustache tag scanner, shared by partial expansion and the escaping rewrite. +//! +//! It follows the Mustache spec where finding a tag needs it: a comment ends at the first +//! closing delimiter, `{{=<% %>=}}` changes the delimiters, and a section close must name +//! the section it closes. Mirrors `mustache_tags.py` in the Python port and `MustacheTags` +//! in the C# and Java ports. + +use std::fmt; + +const DEFAULT_OPEN: &str = "{{"; +const DEFAULT_CLOSE: &str = "}}"; + +/// What a tag is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TagKind { + /// `{{x}}`: an escaped interpolation. + Name, + /// `{{{x}}}`: a raw interpolation. + Triple, + /// `{{&x}}`: a raw interpolation. + Amp, + /// `{{#x}}` + Section, + /// `{{^x}}` + Inverted, + /// `{{/x}}` + Close, + /// `{{>x}}` + Partial, + /// `{{!x}}` + Comment, + /// `{{=<% %>=}}` + Delimiters, +} + +/// One tag: its kind, its trimmed name, and its `[start, end)` byte span in the text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Tag { + pub kind: TagKind, + pub value: String, + pub start: usize, + pub end: usize, +} + +/// An unbalanced section. `section` is the section the finding is about: the unopened +/// close's name, or the section left open. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SyntaxError { + pub message: String, + pub section: String, +} + +impl fmt::Display for SyntaxError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for SyntaxError {} + +/// Every tag in `text`, in order, honouring comments and delimiter changes. +/// +/// # Errors +/// A close with no open, a close naming a different section than the one open, or a +/// section never closed. An unterminated tag ends the scan (the rest is text). +pub fn scan(text: &str) -> Result, SyntaxError> { + let mut tags = Vec::new(); + let mut open_delim = DEFAULT_OPEN.to_string(); + let mut close_delim = DEFAULT_CLOSE.to_string(); + let mut open_sections: Vec = Vec::new(); + let mut pos = 0; + while pos < text.len() { + let Some(found) = text[pos..].find(open_delim.as_str()) else { + break; + }; + let start = pos + found; + let mut content_start = start + open_delim.len(); + let triple = text[content_start..].starts_with('{'); + let end_delim = if triple { + format!("}}{close_delim}") + } else { + close_delim.clone() + }; + if triple { + content_start += 1; + } + let Some(close_rel) = text[content_start..].find(end_delim.as_str()) else { + break; + }; + let close = content_start + close_rel; + let content = text[content_start..close].trim(); + let end = close + end_delim.len(); + pos = end; + + let push = |tags: &mut Vec, kind: TagKind, value: &str| { + tags.push(Tag { + kind, + value: value.to_string(), + start, + end, + }); + }; + if triple { + push(&mut tags, TagKind::Triple, content); + continue; + } + let Some(sigil) = content.chars().next() else { + continue; + }; + let name = content[sigil.len_utf8()..].trim(); + match sigil { + '!' => push(&mut tags, TagKind::Comment, name), + '=' => { + if let Some(inner) = content[1..].strip_suffix('=') { + let parts: Vec<&str> = inner.split_whitespace().collect(); + if let [o, c] = parts.as_slice() { + open_delim = (*o).to_string(); + close_delim = (*c).to_string(); + } + } + push(&mut tags, TagKind::Delimiters, name); + } + '#' | '^' => { + open_sections.push(name.to_string()); + let kind = if sigil == '#' { + TagKind::Section + } else { + TagKind::Inverted + }; + push(&mut tags, kind, name); + } + '/' => { + let Some(opened) = open_sections.pop() else { + return Err(SyntaxError { + message: format!("Unopened section \"{name}\""), + section: name.to_string(), + }); + }; + if opened != name { + return Err(SyntaxError { + message: format!("Unclosed section \"{opened}\""), + section: opened, + }); + } + push(&mut tags, TagKind::Close, name); + } + '>' => push(&mut tags, TagKind::Partial, name), + '&' => push(&mut tags, TagKind::Amp, name), + _ => push(&mut tags, TagKind::Name, content), + } + } + if let Some(opened) = open_sections.pop() { + return Err(SyntaxError { + message: format!("Unclosed section \"{opened}\""), + section: opened, + }); + } + Ok(tags) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kinds(text: &str) -> Vec<(TagKind, String)> { + scan(text) + .unwrap() + .into_iter() + .map(|t| (t.kind, t.value)) + .collect() + } + + #[test] + fn finds_every_kind() { + let k = kinds("{{a}}{{{b}}}{{&c}}{{#d}}{{/d}}{{^e}}{{/e}}{{> p }}{{! note }}"); + assert_eq!( + k, + vec![ + (TagKind::Name, "a".into()), + (TagKind::Triple, "b".into()), + (TagKind::Amp, "c".into()), + (TagKind::Section, "d".into()), + (TagKind::Close, "d".into()), + (TagKind::Inverted, "e".into()), + (TagKind::Close, "e".into()), + (TagKind::Partial, "p".into()), + (TagKind::Comment, "note".into()), + ] + ); + } + + #[test] + fn a_comment_hides_the_partial_inside_it() { + assert_eq!( + kinds("{{! see {{> p}} }}"), + vec![(TagKind::Comment, "see {{> p".into())] + ); + } + + #[test] + fn mismatched_close_is_an_error() { + let err = scan("{{#a}}{{/b}}").unwrap_err(); + assert_eq!(err.section, "a"); + assert!(scan("{{/a}}").is_err()); + assert!(scan("{{#a}}").is_err()); + } + + #[test] + fn delimiter_change_is_followed() { + let k = kinds("{{=<% %>=}}<% a %>"); + assert_eq!(k[1], (TagKind::Name, "a".into())); + } +} diff --git a/server/rust/metaobjects-render/tests/extract_conformance.rs b/server/rust/metaobjects-render/tests/extract_conformance.rs new file mode 100644 index 0000000000..f9b77588e9 --- /dev/null +++ b/server/rust/metaobjects-render/tests/extract_conformance.rs @@ -0,0 +1,241 @@ +//! The shared reply-parser corpus (`fixtures/extract-conformance/`): per case, `schema.json` +//! (format, rootName, fields, optional tolerance and rootless), `input.txt` (a deliberately +//! dirty model reply) and `expected.json` (`empty`, per-path `states`, `malformedRequired`, +//! and the data as dotted leaf paths). Numbers compare within 1e-9, as every runner does. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use metaobjects_render::extract::{ + ExtractOptions, ExtractSchema, FieldKind, FieldSpec, Format, Tolerance, extract, +}; + +/// The corpus size: a deleted case fails here rather than silently shrinking coverage. +const CASES: usize = 58; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/extract-conformance") +} + +fn read_json(path: &Path) -> Value { + let text = std::fs::read_to_string(path).unwrap_or_else(|e| panic!("{path:?}: {e}")); + serde_json::from_str(&text).unwrap_or_else(|e| panic!("{path:?}: {e}")) +} + +fn opt_string(f: &Value, key: &str) -> Option { + f.get(key) + .map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_string)) +} + +fn opt_usize(f: &Value, key: &str) -> Option { + f.get(key) + .and_then(Value::as_u64) + .map(|n| usize::try_from(n).expect("fits")) +} + +fn parse_field(f: &Value) -> FieldSpec { + let name = f["name"].as_str().expect("name"); + let kind = FieldKind::parse(f["kind"].as_str().expect("kind")).expect("known kind"); + let required = f["required"].as_bool().unwrap_or(false); + let array = f["array"].as_bool().unwrap_or(false); + let mut spec = match kind { + FieldKind::Enum => { + let values = f["enumValues"] + .as_array() + .map(|a| { + a.iter() + .map(|v| v.as_str().expect("member").to_string()) + .collect() + }) + .unwrap_or_default(); + let aliases = f["enumAlias"] + .as_object() + .map(|m| { + m.iter() + .map(|(k, v)| (k.clone(), v.as_str().expect("member").to_string())) + .collect() + }) + .unwrap_or_default(); + FieldSpec::enumeration(name, required, values) + .aliases(aliases) + .coerce_default(opt_string(f, "coerceDefault")) + .normalize(f["normalize"].as_str().unwrap_or("strip")) + } + FieldKind::Object => { + let nested = f["fields"] + .as_array() + .map(|a| a.iter().map(parse_field).collect()) + .unwrap_or_default(); + FieldSpec::object( + name, + required, + ExtractSchema { + format: Format::Json, + root_name: name.to_string(), + fields: nested, + }, + ) + } + _ => { + let spec = + FieldSpec::scalar(name, kind, required).range(f["min"].as_f64(), f["max"].as_f64()); + if f["textContent"].as_bool().unwrap_or(false) { + spec.text_content() + } else { + spec + } + } + }; + spec = spec.default_value(opt_string(f, "default")); + if array { + spec = spec.array(); + } + spec.item_bounds(opt_usize(f, "minItems"), opt_usize(f, "maxItems")) +} + +fn flatten(prefix: &str, value: &Value, out: &mut Vec<(String, Value)>) { + match value { + Value::Object(m) => { + for (k, v) in m { + let key = if prefix.is_empty() { + k.clone() + } else { + format!("{prefix}.{k}") + }; + flatten(&key, v, out); + } + } + Value::Array(xs) => { + for (i, v) in xs.iter().enumerate() { + flatten(&format!("{prefix}[{i}]"), v, out); + } + } + other => out.push((prefix.to_string(), other.clone())), + } +} + +fn run_case(dir: &Path) -> Result<(), String> { + let node = read_json(&dir.join("schema.json")); + let schema = ExtractSchema { + format: Format::parse(node["format"].as_str().expect("format")).expect("known format"), + root_name: node["rootName"].as_str().expect("rootName").to_string(), + fields: node["fields"] + .as_array() + .expect("fields") + .iter() + .map(parse_field) + .collect(), + }; + let text = std::fs::read_to_string(dir.join("input.txt")).map_err(|e| e.to_string())?; + let expected = read_json(&dir.join("expected.json")); + let mut opts = ExtractOptions::default().rootless(node["rootless"].as_bool().unwrap_or(false)); + if let Some(t) = node["tolerance"].as_str() { + opts = opts.tolerance(Tolerance::parse(t).expect("known tolerance")); + } + let outcome = extract(Some(&text), &schema, &opts); + let mut problems = Vec::new(); + + if outcome.report.is_empty() != expected["empty"].as_bool().unwrap_or(false) { + problems.push(format!("empty: got {}", outcome.report.is_empty())); + } + let mut got_states: Vec<(String, String)> = outcome + .report + .states() + .iter() + .map(|(k, v)| (k.clone(), v.as_str().to_string())) + .collect(); + got_states.sort(); + let mut want_states: Vec<(String, String)> = expected["states"] + .as_object() + .expect("states") + .iter() + .map(|(k, v)| (k.clone(), v.as_str().expect("state").to_string())) + .collect(); + want_states.sort(); + if got_states != want_states { + problems.push(format!( + "states:\n got {got_states:?}\n want {want_states:?}" + )); + } + let mut got_mr = outcome.report.malformed_required().to_vec(); + got_mr.sort(); + let mut want_mr: Vec = expected + .get("malformedRequired") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .map(|v| v.as_str().expect("path").to_string()) + .collect() + }) + .unwrap_or_default(); + want_mr.sort(); + if got_mr != want_mr { + problems.push(format!( + "malformedRequired: got {got_mr:?}, want {want_mr:?}" + )); + } + + let mut leaves = Vec::new(); + flatten("", &Value::Object(outcome.data.clone()), &mut leaves); + let want = expected["data"].as_object().expect("data"); + let mut got_keys: Vec<&String> = leaves.iter().map(|(k, _)| k).collect(); + got_keys.sort(); + let mut want_keys: Vec<&String> = want.keys().collect(); + want_keys.sort(); + if got_keys != want_keys { + problems.push(format!("data leaves: got {got_keys:?}, want {want_keys:?}")); + } else { + for (path, got) in &leaves { + let exp = &want[path]; + let same = match (exp, got) { + (Value::Bool(a), Value::Bool(b)) => a == b, + (Value::Number(a), Value::Number(b)) => { + (a.as_f64().expect("f64") - b.as_f64().expect("f64")).abs() <= 1e-9 + } + (Value::Number(_), _) | (Value::Bool(_), _) => false, + (e, g) => text_of(e) == text_of(g), + }; + if !same { + problems.push(format!("data[{path}]: got {got}, want {exp}")); + } + } + } + if problems.is_empty() { + Ok(()) + } else { + Err(problems.join("\n ")) + } +} + +fn text_of(v: &Value) -> String { + match v { + Value::String(s) => s.clone(), + other => other.to_string(), + } +} + +#[test] +fn extract_conformance_corpus() { + let mut dirs: Vec = std::fs::read_dir(corpus()) + .expect("fixtures/extract-conformance") + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.join("schema.json").is_file()) + .collect(); + dirs.sort(); + assert_eq!(dirs.len(), CASES, "extract-conformance case count"); + let failures: Vec = dirs + .iter() + .filter_map(|d| { + run_case(d) + .err() + .map(|e| format!("FAIL {}:\n {e}", d.file_name().unwrap().to_string_lossy())) + }) + .collect(); + assert!( + failures.is_empty(), + "{} failing\n{}", + failures.len(), + failures.join("\n") + ); +} diff --git a/server/rust/metaobjects-render/tests/output_prompt_conformance.rs b/server/rust/metaobjects-render/tests/output_prompt_conformance.rs new file mode 100644 index 0000000000..d992c30a90 --- /dev/null +++ b/server/rust/metaobjects-render/tests/output_prompt_conformance.rs @@ -0,0 +1,176 @@ +//! The shared output-format fragment corpus (`fixtures/output-prompt-conformance/`): each +//! `spec.json` renders byte-exact in all three styles, and a `roundTrip` case's example +//! reads back through the reply parser with no field malformed or lost. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use metaobjects_render::extract::{ + ExtractOptions, ExtractSchema, FieldExtraction, FieldKind, FieldSpec, Format, extract, +}; +use metaobjects_render::prompt::{ + OutputFormatSpec, PromptField, PromptOverrides, PromptStyle, render_output_format, +}; + +/// The corpus size: a deleted case fails here. +const CASES: usize = 17; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/output-prompt-conformance") +} + +fn format_of(c: &Value) -> Format { + match c["format"].as_str() { + Some("json") => Format::Json, + Some("xml") => Format::Xml, + other => panic!("unknown format {other:?}"), + } +} + +fn kind_of(f: &Value) -> FieldKind { + FieldKind::parse(f["kind"].as_str().expect("kind")).expect("known kind") +} + +fn strings(v: &Value) -> Option> { + v.as_array().map(|a| { + a.iter() + .map(|x| x.as_str().expect("string").to_string()) + .collect() + }) +} + +fn output_spec(c: &Value) -> OutputFormatSpec { + let fields = c["fields"] + .as_array() + .expect("fields") + .iter() + .map(|f| PromptField { + array: f["array"].as_bool().unwrap_or(false), + enum_values: strings(&f["enumValues"]), + enum_doc: f["enumDoc"].as_object().map(|m| { + m.iter() + .map(|(k, v)| (k.clone(), v.as_str().expect("doc").to_string())) + .collect() + }), + example: f["example"].as_str().map(str::to_string), + instruction: f["instruction"].as_str().map(str::to_string), + nested: f["nested"] + .is_object() + .then(|| Box::new(output_spec(&f["nested"]))), + ..PromptField::new( + f["name"].as_str().expect("name"), + kind_of(f), + f["required"].as_bool().expect("required"), + ) + }) + .collect(); + OutputFormatSpec { + format: format_of(c), + root_name: c["rootName"].as_str().expect("rootName").to_string(), + style: PromptStyle::Guide, + fields, + } +} + +fn extract_schema(c: &Value) -> ExtractSchema { + let fields = c["fields"] + .as_array() + .expect("fields") + .iter() + .map(|f| { + let name = f["name"].as_str().expect("name"); + let required = f["required"].as_bool().expect("required"); + match kind_of(f) { + FieldKind::Enum => FieldSpec::enumeration( + name, + required, + strings(&f["enumValues"]).unwrap_or_default(), + ), + FieldKind::Object => { + let spec = FieldSpec::object(name, required, extract_schema(&f["nested"])); + if f["array"].as_bool().unwrap_or(false) { + spec.array() + } else { + spec + } + } + kind => FieldSpec::scalar(name, kind, required), + } + }) + .collect(); + ExtractSchema { + format: format_of(c), + root_name: c["rootName"].as_str().expect("rootName").to_string(), + fields, + } +} + +fn run_case(dir: &Path) -> Result<(), String> { + let text = std::fs::read_to_string(dir.join("spec.json")).map_err(|e| e.to_string())?; + let c: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; + let spec = output_spec(&c); + let mut problems = Vec::new(); + for (key, style) in [ + ("guide", PromptStyle::Guide), + ("inline", PromptStyle::Inline), + ("exampleOnly", PromptStyle::ExampleOnly), + ] { + let overrides = PromptOverrides { + style: Some(style), + ..PromptOverrides::default() + }; + let actual = render_output_format(&spec, &overrides); + let expected = std::fs::read_to_string(dir.join(format!("expected.{key}.txt"))) + .map_err(|e| e.to_string())?; + if actual != expected { + problems.push(format!( + "{key}:\n want {expected:?}\n got {actual:?}" + )); + } + } + if c["roundTrip"].as_bool().unwrap_or(false) { + let example = std::fs::read_to_string(dir.join("expected.exampleOnly.txt")) + .map_err(|e| e.to_string())?; + let outcome = extract( + Some(&example), + &extract_schema(&c), + &ExtractOptions::default(), + ); + for (path, state) in outcome.report.states() { + if matches!( + state, + FieldExtraction::Malformed + | FieldExtraction::LostRequired + | FieldExtraction::LostOptional + ) { + problems.push(format!("round trip: {path} is {state}")); + } + } + } + if problems.is_empty() { + Ok(()) + } else { + Err(problems.join("\n ")) + } +} + +#[test] +fn output_prompt_conformance_corpus() { + let mut dirs: Vec = std::fs::read_dir(corpus()) + .expect("fixtures/output-prompt-conformance") + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.join("spec.json").is_file()) + .collect(); + dirs.sort(); + assert_eq!(dirs.len(), CASES, "output-prompt-conformance case count"); + let failures: Vec = dirs + .iter() + .filter_map(|d| { + run_case(d) + .err() + .map(|e| format!("FAIL {}:\n {e}", d.file_name().unwrap().to_string_lossy())) + }) + .collect(); + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/server/rust/metaobjects-render/tests/render_conformance.rs b/server/rust/metaobjects-render/tests/render_conformance.rs new file mode 100644 index 0000000000..2b19db4852 --- /dev/null +++ b/server/rust/metaobjects-render/tests/render_conformance.rs @@ -0,0 +1,83 @@ +//! The shared render corpus (`fixtures/render-conformance/`): the same template, payload, +//! partials and format give the same bytes in every port. +//! +//! Each case directory holds `template.mustache`, `payload.json`, `expected.txt`, an +//! optional `meta.json` (`format`, `maxChars`) and optional `partials/.mustache`, +//! referenced as `{{> partials/}}`. A sub-corpus with no `template.mustache` of its +//! own (`template-generator/`, which drives the codegen `template` generator) has its own +//! harness and is not a render case. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use metaobjects_render::{Body, InMemoryProvider, RenderRequest, render}; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/render-conformance") +} + +fn read(path: &Path) -> String { + std::fs::read_to_string(path).unwrap_or_else(|e| panic!("{path:?}: {e}")) +} + +fn run_case(dir: &Path) -> Result<(), String> { + let template = read(&dir.join("template.mustache")); + let payload: Value = serde_json::from_str(&read(&dir.join("payload.json"))) + .map_err(|e| format!("payload.json: {e}"))?; + let expected = read(&dir.join("expected.txt")); + let meta: Value = if dir.join("meta.json").is_file() { + serde_json::from_str(&read(&dir.join("meta.json"))).map_err(|e| e.to_string())? + } else { + Value::Null + }; + let format = meta["format"].as_str().unwrap_or("text"); + let max_chars = meta["maxChars"] + .as_u64() + .map(|n| usize::try_from(n).expect("maxChars fits")); + + let mut partials = HashMap::new(); + let pdir = dir.join("partials"); + if pdir.is_dir() { + for entry in std::fs::read_dir(&pdir).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 provider = InMemoryProvider::new(partials); + let actual = render( + &RenderRequest::new(Body::Inline(&template), &payload, &provider) + .format(format) + .max_chars(max_chars), + ) + .map_err(|e| e.to_string())?; + if actual == expected { + Ok(()) + } else { + Err(format!("expected {expected:?}\n actual {actual:?}")) + } +} + +#[test] +fn render_conformance_corpus() { + let mut dirs: Vec = std::fs::read_dir(corpus()) + .expect("fixtures/render-conformance") + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.join("template.mustache").is_file()) + .collect(); + dirs.sort(); + assert!(dirs.len() >= 18, "found only {} render cases", dirs.len()); + let failures: Vec = dirs + .iter() + .filter_map(|d| { + run_case(d) + .err() + .map(|e| format!("FAIL {}: {e}", d.file_name().unwrap().to_string_lossy())) + }) + .collect(); + assert!(failures.is_empty(), "{}", failures.join("\n")); +} From 4a321c9692ffa27e04dd462ed6095925435027d6 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 12:00:54 -0500 Subject: [PATCH 2/5] fix(rust): eject --force compares before it writes A forced eject over a copy that already matches the shipped generator byte for byte no longer rewrites it: it reports [unchanged] and the file keeps its bytes and modified time, as every other write path in the port does. A copy that differs is still replaced. --- docs/ports/rust.md | 2 +- server/rust/metaobjects-cli/tests/cli.rs | 19 +++++++++++++++++ server/rust/metaobjects-codegen/src/eject.rs | 22 +++++++++++++------- 3 files changed, 35 insertions(+), 8 deletions(-) diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 45c986892c..357bfc2890 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -54,7 +54,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 eject ...` | Copies a shipped generator into the project to own. `--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). | +| `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 `, `--strict` and `--timings`. `gen` adds `--force` and `--list`. `cargo meta --help` is the reference. diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs index f9b1c147ef..5396154871 100644 --- a/server/rust/metaobjects-cli/tests/cli.rs +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -617,6 +617,25 @@ fn eject_copies_the_generator_never_overwrites_and_undo_takes_back_only_identica .contains("pub struct EntityGenerator") ); + // --force over a copy that already matches the reference compares and writes nothing: + // the file keeps an old modified time it would lose to a rewrite. + let copy = p.0.join("codegen/generators/entity.rs"); + let old = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000_000); + std::fs::File::options() + .write(true) + .open(©) + .and_then(|f| f.set_modified(old)) + .expect("set mtime"); + let out = ok(&p.run(&["meta", "eject", "entity", "--force"])); + assert!(out.contains("[unchanged]"), "{out}"); + assert_eq!( + std::fs::metadata(©) + .and_then(|m| m.modified()) + .expect("mtime"), + old, + "an identical copy is not rewritten" + ); + // Undo: a copy that differs is refused by name; an identical one is removed. p.write("codegen/generators/entity.rs", "// edited\n"); let r = p.run(&["meta", "eject", "--undo", "entity"]); diff --git a/server/rust/metaobjects-codegen/src/eject.rs b/server/rust/metaobjects-codegen/src/eject.rs index 47a6fc8b29..3ec99ba6a9 100644 --- a/server/rust/metaobjects-codegen/src/eject.rs +++ b/server/rust/metaobjects-codegen/src/eject.rs @@ -473,13 +473,21 @@ pub fn eject( let mut lines = Vec::new(); for r in &wanted { let rel = r.owned_path(); - let replaced = project_root.join(&rel).exists(); - write_new(&project_root.join(&rel), r.source)?; - lines.push(format!( - "ejected {} -> {rel} [{}]", - r.name, - if replaced { "replaced" } else { "created" } - )); + let path = project_root.join(&rel); + // A forced copy that already matches the reference byte for byte is not rewritten: + // an unchanged file keeps its bytes and its timestamp, as in every write path. + let outcome = match std::fs::read(&path) { + Ok(bytes) if bytes == r.source.as_bytes() => "unchanged", + Ok(_) => { + write_new(&path, r.source)?; + "replaced" + } + Err(_) => { + write_new(&path, r.source)?; + "created" + } + }; + lines.push(format!("ejected {} -> {rel} [{outcome}]", r.name)); } let manifest = project_root.join(OWNED_MANIFEST); From 1ed7e77230074bbdd1425ede9df61b1dac64af21 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 12:07:27 -0500 Subject: [PATCH 3/5] no-mistakes(review): Bound XML reader recursion depth --- .../src/extract/xml_reader.rs | 37 ++++++++++++++++--- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/server/rust/metaobjects-render/src/extract/xml_reader.rs b/server/rust/metaobjects-render/src/extract/xml_reader.rs index 817fd2aac5..4b194cda89 100644 --- a/server/rust/metaobjects-render/src/extract/xml_reader.rs +++ b/server/rust/metaobjects-render/src/extract/xml_reader.rs @@ -25,6 +25,10 @@ const COMMENT_CLOSE: &str = "-->"; const CDATA_OPEN: &str = ""; +/// Deepest element nesting the reader follows; below it the content is text, as in the JSON +/// reader, so a runaway reply cannot overflow the stack. +const MAX_DEPTH: usize = 100; + fn is_name_start(b: u8) -> bool { b.is_ascii_alphabetic() || b == b'_' } @@ -279,7 +283,7 @@ pub fn read(raw_span: &str, ci: bool) -> IndexMap { Some(root_end) if root_end > gt => root_end, _ => span.len(), }; - parse_children(&span[gt + 1..inner_end], ci, &mut out, None, false); + parse_children(&span[gt + 1..inner_end], ci, &mut out, None, false, 0); out } @@ -290,7 +294,7 @@ pub fn read_rootless(text: &str, ci: bool) -> IndexMap { if text.trim().is_empty() { return out; } - parse_children(&prepare(text), ci, &mut out, None, false); + parse_children(&prepare(text), ci, &mut out, None, false, 0); out } @@ -304,6 +308,7 @@ fn parse_children( out: &mut IndexMap, mut loose: Option<&mut Vec>, literal_unclosed: bool, + depth: usize, ) { let b = inner.as_bytes(); let mut pos = 0; @@ -370,7 +375,7 @@ fn parse_children( next = e; } let content = &inner[content_start..content_end]; - accumulate(out, key, combine(attrs, content, ci, close.is_some())); + accumulate(out, key, combine(attrs, content, ci, close.is_some(), depth)); pos = next; scan = next; } @@ -391,11 +396,17 @@ fn find_stray_close(inner: &str, from: usize, to: usize, ci: bool) -> Option<(us } } -fn combine(attrs: IndexMap, content: &str, ci: bool, closed: bool) -> Raw { - if content.contains('<') { +fn combine( + attrs: IndexMap, + content: &str, + ci: bool, + closed: bool, + depth: usize, +) -> Raw { + if depth < MAX_DEPTH && content.contains('<') { let mut nested = IndexMap::new(); let mut loose = Vec::new(); - parse_children(content, ci, &mut nested, Some(&mut loose), closed); + parse_children(content, ci, &mut nested, Some(&mut loose), closed, depth + 1); if !nested.is_empty() { let mut merged = attrs; for (k, v) in nested { @@ -533,6 +544,20 @@ mod tests { assert_eq!(m["a"], s("x{}", "".repeat(50_000)); + let m = read(&reply, true); + let mut v = &m["a"]; + let mut levels = 1; + while let Raw::Map(inner) = v { + v = &inner["a"]; + levels += 1; + } + assert!(levels <= MAX_DEPTH + 1); + assert!(matches!(v, Raw::Str(t) if t.starts_with(""))); + } + #[test] fn unclosed_leaf_stops_at_sibling() { let m = read("onetwo", true); From 9cf3be260c2b5df67b0d9f4afac6af5198135d5c Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:21:45 -0500 Subject: [PATCH 4/5] no-mistakes(test): Format xml_reader.rs with cargo fmt --- .../metaobjects-render/src/extract/xml_reader.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/server/rust/metaobjects-render/src/extract/xml_reader.rs b/server/rust/metaobjects-render/src/extract/xml_reader.rs index 4b194cda89..9b526b2048 100644 --- a/server/rust/metaobjects-render/src/extract/xml_reader.rs +++ b/server/rust/metaobjects-render/src/extract/xml_reader.rs @@ -375,7 +375,11 @@ fn parse_children( next = e; } let content = &inner[content_start..content_end]; - accumulate(out, key, combine(attrs, content, ci, close.is_some(), depth)); + accumulate( + out, + key, + combine(attrs, content, ci, close.is_some(), depth), + ); pos = next; scan = next; } @@ -406,7 +410,14 @@ fn combine( if depth < MAX_DEPTH && content.contains('<') { let mut nested = IndexMap::new(); let mut loose = Vec::new(); - parse_children(content, ci, &mut nested, Some(&mut loose), closed, depth + 1); + parse_children( + content, + ci, + &mut nested, + Some(&mut loose), + closed, + depth + 1, + ); if !nested.is_empty() { let mut merged = attrs; for (k, v) in nested { From 1c5d92dd55d5d8a9c5171a909670d5a111243b27 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:37:57 -0500 Subject: [PATCH 5/5] no-mistakes(document): Document Rust render crate and eject unchanged --- CHANGELOG.md | 4 +++- README.md | 2 +- docs/README.md | 2 +- docs/features/prerelease.md | 4 ++-- docs/ports/rust.md | 3 +++ fixtures/output-prompt-conformance/README.md | 2 +- server/rust/Cargo.toml | 3 ++- spec/decisions/ADR-0065-rust-is-the-sixth-port.md | 11 ++++++----- 8 files changed, 19 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fc6b97f76..0e1c24535f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,7 +72,9 @@ here.** path of the machine the tool was built on into `codegen/Cargo.toml`: the owned crate names the exact crates.io release by default, and `--engine ` names a checkout or a git revision. The three crates lose `publish = false`, carry their packaging metadata, and the `rust` lane -runs `cargo publish --dry-run`. Nothing is published. `cargo meta verify` now runs the business-rules +runs `cargo publish --dry-run` over all four crates. Nothing is published. The new `metaobjects-render` +crate carries the Rust prompt render, the reply parser and the output-format fragment. `cargo meta eject --force` leaves a +copy that already matches the shipped generator untouched. `cargo meta verify` now runs the business-rules gate (ADR-0066) too: the same five findings, severities and message text as the other ports, under the four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/rules-check-conformance/`. diff --git a/README.md b/README.md index 75f0cfbf70..9f4ae50f8f 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,7 @@ first-week wedge plan — and `meta init` picks up from there. | Kotlin | **Maven Central `8.2.0`** — codegen tier on top of Java: 17 generators (entity, Exposed table, names, relations, repository, output-parser, output-prompt, render-helper, extractor, filter-allowlist, validator, Spring config, storedProc, Spring controller, requirement-tests, api-docs, report-export); 24 / 24 persistence-conformance | [`docs/ports/kotlin.md`](docs/ports/kotlin.md) | [`server/java/codegen-kotlin/`](server/java/codegen-kotlin/) · [`server/java/metadata-ktx/`](server/java/metadata-ktx/) | | C# | **NuGet `1.2.0`** — loader + conformance + EF Core codegen + render engine + `dotnet meta` CLI all shipped | [`docs/ports/csharp.md`](docs/ports/csharp.md) | [`server/csharp/`](server/csharp/) | | Python | **PyPI `1.2.0`** — loader + conformance + render + entity-model codegen + ObjectManager runtime shipped; schema migrations are TS-owned (ADR-0015) | [`docs/ports/python.md`](docs/ports/python.md) | [`server/python/`](server/python/) | -| Rust | **Crates ready to publish, not yet published** — loader (JSON + YAML), project and source resolution, naming and all 41 validation passes; 578 / 578 metamodel conformance; `cargo meta init` / `gen` / `verify` / `eject` with the `entity`, `client` and `commands` generators (ADR-0065). Schema migrations stay with the Node `meta` tool | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | +| Rust | **Crates ready to publish, not yet published** — loader (JSON + YAML), project and source resolution, naming and all 41 validation passes; 578 / 578 metamodel conformance; prompt render and the reply parser (`metaobjects-render`); `cargo meta init` / `gen` / `verify` / `eject` with the `entity`, `client` and `commands` generators (ADR-0065). Schema migrations stay with the Node `meta` tool | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | ## Capability matrix diff --git a/docs/README.md b/docs/README.md index 843b69773a..3512e81306 100644 --- a/docs/README.md +++ b/docs/README.md @@ -61,7 +61,7 @@ docs/ ├── kotlin.md ├── csharp.md ├── python.md - └── rust.md # the Rust port: loader, validation, cargo meta (init/gen/verify/eject) and its three generators + └── rust.md # the Rust port: loader, validation, prompt render and reply parser, cargo meta (init/gen/verify/eject) and its three generators ``` If this list and `ls docs/features/` ever disagree, trust the directory listing — diff --git a/docs/features/prerelease.md b/docs/features/prerelease.md index 3f46c3a581..52af1244ce 100644 --- a/docs/features/prerelease.md +++ b/docs/features/prerelease.md @@ -172,8 +172,8 @@ pushed: a sha nobody can fetch is not a record. ### Rust -There is no Rust candidate on the private registry: the three crates are `publish = false` and -the registry serves npm, PyPI, NuGet and Maven. A Rust consumer **pins the commit** the +There is no Rust candidate on the private registry: the four crates are ready to publish and not +published, and the registry serves npm, PyPI, NuGet and Maven. A Rust consumer **pins the commit** the candidate's row in the log names: ```toml diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 357bfc2890..e4b494e021 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -282,6 +282,9 @@ outright. | `decimal-wire`, `duration-wire` | every vector, against the code the support crate carries | | `writer-conformance` | every `core` case of the code writer ([ADR-0063](../../spec/decisions/ADR-0063-generators-own-layout.md)) | | `generator-registry-conformance` | the shipped generators are exactly the registry's `rust` entries, with its tier and layer, and the eject contract's census, completeness and depth hold (ADR-0034 Amendment 8) | +| `render-conformance` | every case, byte-identical, through `metaobjects_render::render` (the Mustache engine underneath is `mustache-ng`) | +| `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` | Two gates have no corpus of their own: diff --git a/fixtures/output-prompt-conformance/README.md b/fixtures/output-prompt-conformance/README.md index 95aa704fec..e5cc2edde5 100644 --- a/fixtures/output-prompt-conformance/README.md +++ b/fixtures/output-prompt-conformance/README.md @@ -1,7 +1,7 @@ # output-prompt-conformance Pins the FR-010 output-format prompt fragment (`OutputFormatRenderer`) byte-identically -across all five ports. Each case directory holds: +across all six ports. Each case directory holds: - `spec.json` — a unified field descriptor (the cross-port oracle input). - `expected.guide.txt`, `expected.inline.txt`, `expected.exampleOnly.txt` — byte-exact diff --git a/server/rust/Cargo.toml b/server/rust/Cargo.toml index 42dbe9d272..56356073ea 100644 --- a/server/rust/Cargo.toml +++ b/server/rust/Cargo.toml @@ -1,11 +1,12 @@ # The Rust port of MetaObjects. ADR-0065 records why it exists and how it differs from the # other ports; its Amendment 3 records that it is a full, publishable language. # -# Three crates: +# Four crates: # `metaobjects` metamodel registry, loader, canonical serializer. # `metaobjects-codegen` the run engine (skip key, hash manifest, writer) and the # `entity` generator. # `metaobjects-cli` the `cargo-meta` binary, so `cargo meta gen` works. +# `metaobjects-render` prompt render, the reply parser and the output-format fragment. [workspace] resolver = "3" members = ["metaobjects", "metaobjects-codegen", "metaobjects-cli", "metaobjects-render"] 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 f3dc3f66ca..fae8505311 100644 --- a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md +++ b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md @@ -33,17 +33,18 @@ five". (byte-identical) and the shared metamodel corpus. 2. **Layout.** `server/rust/` is one Cargo workspace with a pinned toolchain - (`rust-toolchain.toml`). Three crates, each with code: `metaobjects` (node model, registry, - providers, loader, serializer), `metaobjects-codegen` (the run engine and the generators) and - `metaobjects-cli` (the `cargo-meta` binary). The workspace carries no empty placeholder crates; - a crate joins it with its first code. + (`rust-toolchain.toml`). Four crates, each with code: `metaobjects` (node model, registry, + providers, loader, serializer), `metaobjects-codegen` (the run engine and the generators), + `metaobjects-cli` (the `cargo-meta` binary) and `metaobjects-render` (prompt render, the reply + parser and the output-format fragment, over the `mustache-ng` crate). The workspace carries no + empty placeholder crates; a crate joins it with its first code. 3. **The command is `cargo meta`.** It is a Cargo subcommand (a `cargo-meta` binary), the way the other build-tool-hosted ports spell theirs (`dotnet meta`, `mvn metaobjects:...`). A bare `meta` stays the Node schema CLI's. 4. **Publishable crates on the shared version line.** *(Rewritten by Amendment 3; the first - version of this decision kept the port unpublished, on its own `0.x` line.)* The three crates + version of this decision kept the port unpublished, on its own `0.x` line.)* The four crates carry the packaging metadata crates.io needs, and the lane proves they package. Publishing is a separate step that waits for the owner's go, and joins the convergent-publishing rule (ADR-0035 Amendment 1) as a fifth registry on the version line the other four share.