From 03492d6f8fc9bfa99294784fb0841c1e36ca6191 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 3 Dec 2026 04:42:13 -0500 Subject: [PATCH 1/3] feat(rust): resolve metadata dependencies in the Rust loader resolve_collection loads each declared dependency from its committed snapshot, verified against .metaobjects/deps.lock.json (stale, metamodel and node-collision refusals), and Collection gains the imported, in_scope, in_ledger and in_migrate_scope predicates. cargo meta gen generates nothing for an imported object unless scope.include names its package, and refuses a new node declared into a dependency's package (ERR_DEPENDENCY_PACKAGE_NOT_OWNED). Rust now runs the resolution arm of fixtures/dependency-conformance (all 36 cases, the 7 ledger cases included) and fixtures/scope-conformance. The check arm (verify --deps) is not built yet. SHA-256 moves into the metaobjects crate; metaobjects-codegen re-exports it. --- changelog.d/rust-dependency-resolution.md | 23 + docs/CONFORMANCE.md | 15 +- docs/ports/rust.md | 2 + fixtures/dependency-conformance/README.md | 6 + server/rust/metaobjects-codegen/Cargo.toml | 4 + server/rust/metaobjects-codegen/build.rs | 5 +- .../rust/metaobjects-codegen/src/project.rs | 30 +- server/rust/metaobjects-codegen/src/sha256.rs | 207 +----- .../tests/imported_nodes.rs | 146 ++++ server/rust/metaobjects/src/collection.rs | 117 +++- server/rust/metaobjects/src/dependencies.rs | 643 ++++++++++++++++++ server/rust/metaobjects/src/errors.rs | 15 + server/rust/metaobjects/src/lib.rs | 3 + server/rust/metaobjects/src/scope.rs | 194 ++++++ server/rust/metaobjects/src/sha256.rs | 205 ++++++ .../rust/metaobjects/tests/config_reader.rs | 20 +- .../tests/dependency_conformance.rs | 315 +++++++++ .../metaobjects/tests/scope_conformance.rs | 40 ++ 18 files changed, 1759 insertions(+), 231 deletions(-) create mode 100644 changelog.d/rust-dependency-resolution.md create mode 100644 server/rust/metaobjects-codegen/tests/imported_nodes.rs create mode 100644 server/rust/metaobjects/src/dependencies.rs create mode 100644 server/rust/metaobjects/src/scope.rs create mode 100644 server/rust/metaobjects/src/sha256.rs create mode 100644 server/rust/metaobjects/tests/dependency_conformance.rs create mode 100644 server/rust/metaobjects/tests/scope_conformance.rs diff --git a/changelog.d/rust-dependency-resolution.md b/changelog.d/rust-dependency-resolution.md new file mode 100644 index 0000000000..8e67cfc5e6 --- /dev/null +++ b/changelog.d/rust-dependency-resolution.md @@ -0,0 +1,23 @@ +- **Rust resolves metadata dependencies** (FR-023), as the other ports do. `resolve_collection` + now loads each declared dependency from its committed snapshot + (`.metaobjects/deps//`, under the id `dep:/`), in + dependency-name order ahead of the project's own files, after verifying it against + `.metaobjects/deps.lock.json`: no lock, a lock and a config that disagree, a missing snapshot + or one whose hash differs is `ERR_DEPENDENCY_SNAPSHOT_STALE`, another metamodel major is + `ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE`, and two dependencies exporting one node is + `ERR_DEPENDENCY_NODE_COLLISION`. `Collection` gains `imported`, `in_scope`, `in_ledger` and + `in_migrate_scope`; `cargo meta gen` generates nothing for what a dependency exports unless + `scope.include` names its package, and refuses a new node declared into a dependency's package + (`ERR_DEPENDENCY_PACKAGE_NOT_OWNED`). The new `metaobjects::scope` matcher reads + `migrate.scope`, and `metaobjects::dependencies::requirement_ledger` answers which + requirements are the project's own ledger. Rust now runs the resolution arm of + `fixtures/dependency-conformance/` (all 36 cases, the 7 ledger cases included) and all 10 + `fixtures/scope-conformance/` cases. The check arm (`cargo meta verify --deps`) is not built + yet. SHA-256 moves from `metaobjects_codegen::sha256` to `metaobjects::sha256`; the old path + re-exports it. + + Upgrading: a Rust project that declares `dependencies` must now have the snapshot and lock + `meta deps sync` writes, where before the declaration was read and ignored. `Collection` gains + the public fields `resolved_dependencies`, `file_ids`, `imported_packages` and + `imported_nodes` and one private field, so it can no longer be built with a struct literal; + build it with `resolve_collection`. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 2bc016b3b4..289d5c4f5c 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -50,8 +50,8 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/source-resolution-conformance/`](../fixtures/source-resolution-conformance/) | 30 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | ✓ | | [`fixtures/reference-source-conformance/`](../fixtures/reference-source-conformance/) | 6 cases | ✓ (reference implementation) | ✓ | inherits via Java (plus its own codegen exclusion test) | ✓ | ✓ | ✓ | | [`fixtures/response-verify-conformance/`](../fixtures/response-verify-conformance/) | 7 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | ✓ | -| [`fixtures/scope-conformance/`](../fixtures/scope-conformance/) | 10 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | — | -| [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | — | +| [`fixtures/scope-conformance/`](../fixtures/scope-conformance/) | 10 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | ✓ (`scope_conformance.rs`) | +| [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | ✓ (resolution arm, all 36, ledger included, through the ledger's scan: no requirement gate yet, RS-V2; check arm not yet) | | [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (all 15; `test_shared_model_conformance.py`) | — | | [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) (the static agent files each port's `agent-docs` writes; every port runs all 6 stacks, not only its own) | 6 | ✓ (reference) | ✓ (`metaobjects:agent-docs`) | inherits via Java (the same Maven goal) | ✓ (`dotnet meta agent-docs`) | ✓ | ✓ (`cargo meta agent-docs`) | | [`fixtures/agent-pages-pointer/`](../fixtures/agent-pages-pointer/) (the always-on agent file names the agent pages the last `gen` wrote, from the committed `.hashes/`) | 3 cases | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | ✓ | @@ -652,7 +652,7 @@ matching is case-sensitive.** These are exactly the rules four independent implementations would otherwise each get slightly wrong — the failure mode that produced the cross-port `LIKE`/`ILIKE` divergence fixed in 0.21.6. -**TypeScript, Java, Kotlin, C# and Python run it.** The reference implementation is +**TypeScript, Java, Kotlin, C#, Python and Rust run it.** The reference implementation is [`server/typescript/packages/metadata/src/scope.ts`](../server/typescript/packages/metadata/src/scope.ts) (`compilePattern` / `compileScope` / `matchesScope`; `@metaobjectsdev/sdk` re-exports it unchanged, since it moved there from `sdk` when FR-023 needed it from @@ -663,7 +663,9 @@ Python's port (`server/python/src/metaobjects/scope.py`, `matches_scope` using `-1` limit, because `String.split` would otherwise drop a trailing empty segment and let `acme::` compile instead of failing. C#'s (`MetaObjects.Config.Scope`, run by `ScopeConformanceTests`) anchors with `\A…\z` rather than `^…$`, since .NET's `$` -also matches before a trailing newline. Kotlin has no runner of its own: it inherits +also matches before a trailing newline. Rust's (`metaobjects::scope`, run by +`tests/scope_conformance.rs`) matches segment by segment with no regular expression, +and its unit tests pin the invalid-pattern refusals. Kotlin has no runner of its own: it inherits the Java loader. Each of those two guards is pinned by a test beside the corpus, since the corpus asserts matches only and carries no invalid-pattern case. @@ -678,7 +680,7 @@ no per-port fixture. The corpus has four arms: - **Resolution (36 cases).** Every case's `expectFiles`/`expectImported`/`expectSelected`/ `expectMigrateGoverned`/`expectLoadError` assertions. **TypeScript (the reference - implementation), Python, Java and C# all run all 36, identically**, with no exemption. The two + implementation), Python, Java, C# and Rust all run all 36, identically**, with no exemption. The two overlay cases that need a view child as incidental content use `view.currency` (the one concrete `view.*` subtype registered cross-port), not `view.text` — a prior revision used `view.text`, which Python did not register then, and carried a since-discharged allowlist @@ -689,6 +691,9 @@ no per-port fixture. The corpus has four arms: whether object coverage is measured (never by an imported requirement). Each port asserts it through its requirement gate's scan and again through its requirement-tests walk: TypeScript in `cli/test/dependency-ledger-conformance.test.ts`, the other ports in their resolution runner. + Rust has neither a requirement gate nor a requirement-tests generator yet (RS-V2), so + `tests/dependency_conformance.rs` asserts the ledger through the scan they will read + (`metaobjects::dependencies::requirement_ledger`). An eighth case refuses a new requirement declared into a dependency's package (`ERR_DEPENDENCY_PACKAGE_NOT_OWNED`) on the load-time path. - **Check (11 cases, `expectCheck`).** For each declared dependency, `current`, `drifted` or diff --git a/docs/ports/rust.md b/docs/ports/rust.md index a6cb72b000..195f08e92c 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -621,6 +621,8 @@ outright. | `yaml-conformance` | all 19, and the ledger is empty | | `source-resolution-conformance` | all 30 cases | | `reference-source-conformance` | all 6 cases: a `reference: true` source loads so references resolve against it, a node declared only in reference files is a reference node no generator emits, and a `template.*` declared only there is refused (`ERR_REFERENCE_SOURCE_TEMPLATE`) | +| `dependency-conformance` | the resolution arm, all 36 cases: a declared dependency loads from its committed snapshot (`.metaobjects/deps//`), verified against `.metaobjects/deps.lock.json` (a stale, missing or mismatched snapshot is `ERR_DEPENDENCY_SNAPSHOT_STALE`), its objects are left out of generation unless `scope.include` names their package, and a new node declared into its package is refused (`ERR_DEPENDENCY_PACKAGE_NOT_OWNED`). The 7 ledger cases are asserted through `dependencies::requirement_ledger`, since the port has no requirement gate yet. The check arm waits for `verify --deps` | +| `scope-conformance` | all 10 cases, through `metaobjects::scope`, the matcher `migrate.scope` is read with | | `naming-conformance` | all of it | | `codegen-skip-conformance` | every case the port can meet, on both columns (what `gen` must do and what a local `verify --codegen` may do), including an edited owned generator and a forced CI verify ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)). The one it cannot meet, about the three-way merge, is named with its reason in the runner; the template cases (a body edited, a body added) run. | | `rules-check-conformance` | all 16 cases: the diagnostics (severity, code, node address, message text) and the summary of the `verify` business-rules gate, under each case's `rules` and `verify` settings | diff --git a/fixtures/dependency-conformance/README.md b/fixtures/dependency-conformance/README.md index 5ec191b967..318d46e608 100644 --- a/fixtures/dependency-conformance/README.md +++ b/fixtures/dependency-conformance/README.md @@ -296,6 +296,12 @@ package are `ERR_DEPENDENCY_UNRESOLVED`; a `dir` that exists but holds no `metao (`dotnet meta verify --deps`, through `DependencyResolver.CheckDependencies`), which like Python's resolves the `path` transport only. Not the transport arm: C# never syncs. The runner is `server/csharp/MetaObjects.Conformance.Tests/DependencyConformanceTests.cs`. +- **Rust** — the resolution arm: resolution, load-time failure, lock/snapshot integrity, and + the ledger (`server/rust/metaobjects/tests/dependency_conformance.rs`). `inScope` is Python's + formula. The port has no requirement gate and no requirement-tests generator yet, so the + ledger is asserted through the scan they will read (`dependencies::requirement_ledger`), not + through a requirement-tests walk. Not the check arm yet (`cargo meta verify --deps` exits 2), + and not the transport arm: Rust never syncs. ## Reference implementation diff --git a/server/rust/metaobjects-codegen/Cargo.toml b/server/rust/metaobjects-codegen/Cargo.toml index b457baa8cb..c6dd14fb02 100644 --- a/server/rust/metaobjects-codegen/Cargo.toml +++ b/server/rust/metaobjects-codegen/Cargo.toml @@ -13,6 +13,10 @@ keywords = ["metadata", "codegen", "code-generation", "schema", "rest"] categories = ["development-tools", "development-tools::build-utils"] build = "build.rs" +[build-dependencies] +# The build script hashes the engine's sources with the core crate's SHA-256. +metaobjects = { path = "../metaobjects", version = "1.3.1" } + [dependencies] metaobjects = { path = "../metaobjects", version = "1.3.1" } metaobjects-render = { path = "../metaobjects-render", version = "1.3.1" } diff --git a/server/rust/metaobjects-codegen/build.rs b/server/rust/metaobjects-codegen/build.rs index 53a78f84ec..bdec229fa8 100644 --- a/server/rust/metaobjects-codegen/build.rs +++ b/server/rust/metaobjects-codegen/build.rs @@ -5,10 +5,7 @@ //! only by a release number, so a locally built engine with different content never reuses //! a key a different build stored. For Rust the built code is a function of these sources. -#[path = "src/sha256.rs"] -#[allow(dead_code)] -mod sha256; - +use metaobjects::sha256; use std::path::{Path, PathBuf}; fn collect(dir: &Path, out: &mut Vec) { diff --git a/server/rust/metaobjects-codegen/src/project.rs b/server/rust/metaobjects-codegen/src/project.rs index 25c50b5776..d590d2bfa0 100644 --- a/server/rust/metaobjects-codegen/src/project.rs +++ b/server/rust/metaobjects-codegen/src/project.rs @@ -5,9 +5,11 @@ use std::collections::BTreeSet; use std::path::Path; use metaobjects::collection::{Collection, resolve_collection}; +use metaobjects::dependencies::refuse_unowned_packages; use metaobjects::errors::MetaError; use metaobjects::loader::{LoadResult, Loader}; use metaobjects::naming::NamingRegistry; +use metaobjects::parser::TYPE_OBJECT; use metaobjects::providers::default_registry; use metaobjects::reference::reference_nodes_of; @@ -16,14 +18,16 @@ use metaobjects::reference::reference_nodes_of; pub struct LoadedProject { pub collection: Collection, pub result: LoadResult, - /// The resolution keys of the reference nodes (declared only in reference sources): - /// loaded and resolvable, generated by nobody here. + /// The resolution keys of the top-level nodes this run loads and resolves and does not + /// generate: the reference nodes (declared only in reference sources), and the objects a + /// metadata dependency exports that `scope.include` does not name. pub reference_nodes: BTreeSet, } /// Resolve and load the project that `start_dir` belongs to (or `explicit_dir`, when given). /// Every load error (and every unreadable file) comes back together; the model is only -/// returned when there are none. +/// returned when there are none. A new node declared into a package a dependency owns is +/// refused after the loader's own errors (`ERR_DEPENDENCY_PACKAGE_NOT_OWNED`). pub fn load_project( start_dir: &Path, explicit_dir: Option<&Path>, @@ -42,8 +46,24 @@ pub fn load_project( if !read_errors.is_empty() { return Err(read_errors); } - let reference_nodes = reference_nodes_of(&result.tree, result.root, &collection.reference_ids) - .map_err(|e| vec![e])?; + refuse_unowned_packages( + &result.tree, + result.root, + &collection.imported_packages, + &collection.imported_nodes, + ) + .map_err(|e| vec![e])?; + let mut reference_nodes = + reference_nodes_of(&result.tree, result.root, &collection.reference_ids) + .map_err(|e| vec![e])?; + // ADR-0039 sanctioned own: the metadata root has no super chain, so its own children + // are its top-level nodes. + for &id in result.tree.own_children(result.root) { + let key = result.tree.resolution_key(id); + if result.tree.node(id).type_name == TYPE_OBJECT && !collection.in_scope(&key) { + reference_nodes.insert(key); + } + } Ok(LoadedProject { collection, result, diff --git a/server/rust/metaobjects-codegen/src/sha256.rs b/server/rust/metaobjects-codegen/src/sha256.rs index df0780b471..c5e6b50728 100644 --- a/server/rust/metaobjects-codegen/src/sha256.rs +++ b/server/rust/metaobjects-codegen/src/sha256.rs @@ -1,205 +1,4 @@ -//! SHA-256 (FIPS 180-4), std only. -//! -//! The hash manifest (`.metaobjects/.gen-state/.hashes/`) records the SHA-256 of -//! every generated file, the same digest every port writes, so the Rust port needs -//! the algorithm. It is a few dozen lines, so it lives here rather than as a -//! dependency of a code generator. This file is also compiled into `build.rs` -//! (`#[path]`), which hashes the engine's own sources into the skip key. +//! SHA-256, from the core crate: the hash manifest and the skip key use the same digest the +//! dependency lock does. -const K: [u32; 64] = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, -]; - -const H0: [u32; 8] = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, -]; - -fn compress(state: &mut [u32; 8], block: &[u8]) { - let mut w = [0u32; 64]; - for (i, chunk) in block.chunks_exact(4).enumerate() { - w[i] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); - } - for i in 16..64 { - let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); - let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); - w[i] = w[i - 16] - .wrapping_add(s0) - .wrapping_add(w[i - 7]) - .wrapping_add(s1); - } - let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state; - for i in 0..64 { - let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); - let ch = (e & f) ^ (!e & g); - let t1 = h - .wrapping_add(s1) - .wrapping_add(ch) - .wrapping_add(K[i]) - .wrapping_add(w[i]); - let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); - let maj = (a & b) ^ (a & c) ^ (b & c); - let t2 = s0.wrapping_add(maj); - h = g; - g = f; - f = e; - e = d.wrapping_add(t1); - d = c; - c = b; - b = a; - a = t1.wrapping_add(t2); - } - for (s, v) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) { - *s = s.wrapping_add(v); - } -} - -/// An incremental SHA-256. -#[derive(Clone)] -pub struct Sha256 { - state: [u32; 8], - buffer: [u8; 64], - filled: usize, - length: u64, -} - -impl Default for Sha256 { - fn default() -> Self { - Self::new() - } -} - -impl Sha256 { - pub fn new() -> Self { - Self { - state: H0, - buffer: [0; 64], - filled: 0, - length: 0, - } - } - - pub fn update(&mut self, mut data: &[u8]) { - self.length += data.len() as u64; - if self.filled > 0 { - let take = (64 - self.filled).min(data.len()); - self.buffer[self.filled..self.filled + take].copy_from_slice(&data[..take]); - self.filled += take; - data = &data[take..]; - if self.filled < 64 { - return; - } - let block = self.buffer; - compress(&mut self.state, &block); - self.filled = 0; - } - let mut blocks = data.chunks_exact(64); - for block in &mut blocks { - compress(&mut self.state, block); - } - let rest = blocks.remainder(); - self.buffer[..rest.len()].copy_from_slice(rest); - self.filled = rest.len(); - } - - pub fn finish(mut self) -> [u8; 32] { - let bit_length = self.length.wrapping_mul(8); - let mut tail = [0u8; 72]; - tail[0] = 0x80; - // Pad to 56 mod 64, then the 64-bit big-endian bit length. - let pad = if self.filled < 56 { - 56 - self.filled - } else { - 120 - self.filled - }; - tail[pad..pad + 8].copy_from_slice(&bit_length.to_be_bytes()); - let total_length = self.length; - self.update(&tail[..pad + 8]); - self.length = total_length; - debug_assert_eq!(self.filled, 0); - let mut out = [0u8; 32]; - for (chunk, word) in out.chunks_exact_mut(4).zip(self.state) { - chunk.copy_from_slice(&word.to_be_bytes()); - } - out - } -} - -/// The lowercase hex SHA-256 of `data`. -pub fn sha256_hex(data: &[u8]) -> String { - let mut h = Sha256::new(); - h.update(data); - hex(&h.finish()) -} - -/// Lowercase hex of `bytes`. -pub fn hex(bytes: &[u8]) -> String { - const DIGITS: &[u8; 16] = b"0123456789abcdef"; - let mut out = String::with_capacity(bytes.len() * 2); - for b in bytes { - out.push(DIGITS[(b >> 4) as usize] as char); - out.push(DIGITS[(b & 15) as usize] as char); - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn matches_the_fips_180_4_vectors() { - assert_eq!( - sha256_hex(b""), - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - ); - assert_eq!( - sha256_hex(b"abc"), - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" - ); - assert_eq!( - sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), - "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" - ); - let million_a = vec![b'a'; 1_000_000]; - assert_eq!( - sha256_hex(&million_a), - "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" - ); - } - - #[test] - fn chunked_updates_equal_one_shot_at_every_boundary() { - let data: Vec = (0..300u32).map(|i| (i * 7 + 3) as u8).collect(); - let whole = sha256_hex(&data); - for split in 0..data.len() { - let mut h = Sha256::new(); - h.update(&data[..split]); - h.update(&data[split..]); - assert_eq!(hex(&h.finish()), whole, "split at {split}"); - } - } - - #[test] - fn padding_edges_55_56_63_64_bytes_agree_with_known_digests() { - // 55 bytes fits the length in the same block; 56 spills into a second one. - assert_eq!( - sha256_hex(&[b'a'; 55]), - "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318" - ); - assert_eq!( - sha256_hex(&[b'a'; 56]), - "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a" - ); - assert_eq!( - sha256_hex(&[b'a'; 64]), - "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb" - ); - } -} +pub use metaobjects::sha256::*; diff --git a/server/rust/metaobjects-codegen/tests/imported_nodes.rs b/server/rust/metaobjects-codegen/tests/imported_nodes.rs new file mode 100644 index 0000000000..0314d0cb4d --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/imported_nodes.rs @@ -0,0 +1,146 @@ +//! Metadata dependencies (FR-023): a dependency's snapshot loads and resolves, and the +//! generators emit nothing for what it exports unless `scope.include` names its package. + +mod common; + +use std::path::PathBuf; + +use common::Scratch; +use metaobjects_codegen::generator::GenContext; +use metaobjects_codegen::project::load_project; +use metaobjects_codegen::{EntityGenerator, Generator}; + +/// The corpus's pinned publisher artifact (`acme::common`: `Address`, `Audited`, `Customer`) +/// and the hash its lock records. +const ARTIFACT: &str = "artifacts/acme-common-v1.json"; +const INTEGRITY: &str = "sha256-10fbf886e22faceca32c56e5e647c3ff1c82f503e638cba3bd3aa9390f7c409d"; +const SNAPSHOT: &str = ".metaobjects/deps/acme-common/acme-common.metaobjects.json"; + +const OWN: &str = r#"{ "metadata.root": { "package": "app", "children": [ + { "object.entity": { "name": "Order", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } + ] } } +] } }"#; + +const LOCAL_IN_THEIR_PACKAGE: &str = r#"{ "metadata.root": { "package": "acme::common", "children": [ + { "object.value": { "name": "Note", "children": [ { "field.string": { "name": "text" } } ] } } +] } }"#; + +fn artifact() -> String { + let dir = + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/dependency-conformance"); + std::fs::read_to_string(dir.join(ARTIFACT)).expect("the corpus artifact") +} + +fn config(scope_include: Option<&[&str]>) -> String { + let mut config = serde_json::json!({ + "schema_version": 1, + "sources": [{ "path": "model" }], + "dependencies": [{ "name": "acme-common", "path": "../acme-common/metaobjects" }] + }); + if let Some(include) = scope_include { + config["scope"] = serde_json::json!({ "include": include }); + } + config.to_string() +} + +fn lock() -> String { + serde_json::json!({ + "schema_version": 1, + "dependencies": { "acme-common": { + "version": "1.0.0", "metamodelVersion": "1.0", + "resolvedFrom": { "path": "../acme-common/metaobjects" }, + "artifact": "acme-common.metaobjects.json", + "integrity": INTEGRITY, + "packages": ["acme::common"], + "nodes": ["acme::common::Address", "acme::common::Audited", "acme::common::Customer"] + } } + }) + .to_string() +} + +fn entities(project: &Scratch) -> String { + let loaded = load_project(project.path(), None, false).expect("the model loads clean"); + let ctx = GenContext { + tree: &loaded.result.tree, + root: loaded.result.root, + entities: &[], + collection: &loaded.collection, + reference_nodes: &loaded.reference_nodes, + generated_files: None, + }; + let files = EntityGenerator.generate(&ctx).expect("generates"); + files.iter().map(|f| f.content.as_str()).collect() +} + +#[test] +fn an_imported_entity_is_loaded_and_not_generated() { + let (config, lock, artifact) = (config(None), lock(), artifact()); + let project = Scratch::project( + "imported", + &[ + (".metaobjects/config.json", &config), + (".metaobjects/deps.lock.json", &lock), + (SNAPSHOT, &artifact), + ("model/meta.app.json", OWN), + ], + ); + let all = entities(&project); + assert!(all.contains("Order"), "the project's own entity is emitted"); + assert!( + !all.contains("Customer") && !all.contains("Address"), + "the dependency's objects are not emitted:\n{all}" + ); +} + +#[test] +fn a_scope_include_naming_the_package_generates_its_objects() { + let (config, lock, artifact) = ( + config(Some(&["app::**", "acme::common::**"])), + lock(), + artifact(), + ); + let project = Scratch::project( + "imported-included", + &[ + (".metaobjects/config.json", &config), + (".metaobjects/deps.lock.json", &lock), + (SNAPSHOT, &artifact), + ("model/meta.app.json", OWN), + ], + ); + let all = entities(&project); + assert!(all.contains("Order") && all.contains("Customer"), "{all}"); +} + +#[test] +fn a_new_node_in_a_dependency_package_is_refused_on_load() { + let (config, lock, artifact) = (config(None), lock(), artifact()); + let project = Scratch::project( + "imported-unowned", + &[ + (".metaobjects/config.json", &config), + (".metaobjects/deps.lock.json", &lock), + (SNAPSHOT, &artifact), + ("model/meta.ext.json", LOCAL_IN_THEIR_PACKAGE), + ], + ); + let errors = load_project(project.path(), None, false).expect_err("refused"); + assert_eq!(errors[0].code, "ERR_DEPENDENCY_PACKAGE_NOT_OWNED"); +} + +#[test] +fn a_declared_dependency_with_no_lock_is_stale() { + let (config, artifact) = (config(None), artifact()); + let project = Scratch::project( + "imported-no-lock", + &[ + (".metaobjects/config.json", &config), + (SNAPSHOT, &artifact), + ("model/meta.app.json", OWN), + ], + ); + let errors = load_project(project.path(), None, false).expect_err("stale"); + assert_eq!(errors[0].code, "ERR_DEPENDENCY_SNAPSHOT_STALE"); +} diff --git a/server/rust/metaobjects/src/collection.rs b/server/rust/metaobjects/src/collection.rs index f6079f0100..edf7e32d90 100644 --- a/server/rust/metaobjects/src/collection.rs +++ b/server/rust/metaobjects/src/collection.rs @@ -2,19 +2,25 @@ //! lives, ported from the TypeScript SDK's `collection.ts` and `discovery.ts`. //! //! `metaobjects/` is the DEFAULT value of `sources`, never a requirement. -//! Dependency snapshots are not resolved here: a config that declares -//! `dependencies` gets them back unresolved in [`Collection::dependencies`]. +//! Declared `dependencies` resolve to their committed snapshots +//! (`.metaobjects/deps//`), verified against `.metaobjects/deps.lock.json`; +//! the artifacts lead the file list, and the predicates on [`Collection`] keep what they +//! export out of this project's own output (FR-023). -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use crate::config::{ ApiPagination, Config, DependencySpec, EnumDefaults, HandEditsPolicy, Scope, UnknownFieldsMode, WireFormat, load_config, }; +use crate::dependencies::{ + ResolvedDependency, explicitly_includes, package_of_resolution_key, read_lock, verify_snapshot, +}; use crate::errors::{ERR_COLLECTION_NOT_FOUND, ERR_UNKNOWN, ERR_UNKNOWN_LIBRARY, MetaError}; use crate::library::{known_library_tokens, library_sources, unknown_library_tokens}; use crate::naming::{NamingRegistry, PhysicalNaming}; +use crate::scope::{CompiledScope, compile_scope, matches_scope}; use crate::source::ErrorSource; use crate::sources::{ CONFIG_FILE, DEFAULT_METADATA_DIR, DEFAULT_METAOBJECTS_DIR, ResolvedSource, SourceSpec, @@ -33,10 +39,12 @@ pub struct Collection { /// Directory whose config declared this collection (or the resolved start /// directory, when nothing was discovered and the default applies). pub config_dir: PathBuf, - /// Canonically ordered absolute metadata file paths. With dependencies - /// unresolved this equals [`Collection::own_files`]. + /// Absolute metadata file paths: the dependency artifacts in dependency-NAME order, + /// then the project's own files in canonical order. Equals [`Collection::own_files`] + /// when nothing is imported. pub files: Vec, - /// Same set, carrying the contributing spec. + /// The project's own files, carrying the contributing spec (a dependency artifact is + /// not one of its sources). pub sources: Vec, /// The distinct roots the declared specs resolve to, in canonical order. pub source_roots: Vec, @@ -45,8 +53,19 @@ pub struct Collection { /// The loader ids ([`Collection::read_sources`]) of the REFERENCE files: those only /// `{ "path": …, "reference": true }` sources reach. Empty when none is declared. pub reference_ids: BTreeSet, - /// Declared dependencies, validated but NOT resolved against any snapshot. + /// Declared dependencies, as the config names them. pub dependencies: Vec, + /// The declared dependencies resolved to their verified snapshots, in dependency-NAME + /// order. Empty for a project that declares none. + pub resolved_dependencies: Vec, + /// The loader id of each dependency artifact (`dep:/`), keyed by its + /// path in [`Collection::files`]. A file absent here loads under its absolute path. + pub file_ids: BTreeMap, + /// THE exclusion key: every package a dependency exports. + pub imported_packages: BTreeSet, + /// Every node a dependency exports: read only to tell an overlay of an imported node + /// from a new declaration in its package. Not the exclusion key. + pub imported_nodes: BTreeSet, /// The shipped-library selection as authored. pub libraries: Vec, pub physical_naming: PhysicalNaming, @@ -68,6 +87,8 @@ pub struct Collection { pub migrate_scope: Option>, /// `requirements.inherit` patterns. pub requirements_inherit: Option>, + /// `migrate.scope`, compiled. + compiled_migrate_scope: Option, /// The whole parsed config; the default config when none was found. pub config: Config, /// Warnings reading the config produced (unknown top-level keys). @@ -83,7 +104,11 @@ impl Collection { let mut out = library_sources(&self.libraries); let mut errors = Vec::new(); for file in &self.files { - let id = file.to_string_lossy().into_owned(); + let id = self + .file_ids + .get(file) + .cloned() + .unwrap_or_else(|| file.to_string_lossy().into_owned()); match std::fs::read_to_string(file) { Ok(text) => out.push((id, text)), Err(e) => errors.push(MetaError::at( @@ -95,6 +120,46 @@ impl Collection { } (out, errors) } + + /// Is `fqn` in a package one of this project's dependencies exports? + pub fn imported(&self, fqn: &str) -> bool { + self.imported_packages + .contains(package_of_resolution_key(fqn)) + } + + /// The codegen selection: an imported node is not this project's to generate unless + /// `scope.include` NAMES its package (a wildcard reaches it and names nothing). As in + /// Python, Java and C#, `scope` is not applied to the project's own nodes. + pub fn in_scope(&self, fqn: &str) -> bool { + let pkg = package_of_resolution_key(fqn); + !self.imported_packages.contains(pkg) + || explicitly_includes(self.scope.as_ref().and_then(|s| s.include.as_deref()), pkg) + } + + /// Is the requirement at `fqn` (`::`) part of this project's + /// ledger? Its own always are; a dependency's only when `requirements.inherit` names + /// the dependency's package. + pub fn in_ledger(&self, fqn: &str) -> bool { + let pkg = package_of_resolution_key(fqn); + !self.imported_packages.contains(pkg) + || explicitly_includes(self.requirements_inherit.as_deref(), pkg) + } + + /// Does `meta migrate` govern `fqn`? `migrate.scope` when declared, and an imported + /// node only when `migrate.scope` names its package. With no `migrate.scope` and no + /// dependency it admits everything. + pub fn in_migrate_scope(&self, fqn: &str) -> bool { + if self + .compiled_migrate_scope + .as_ref() + .is_some_and(|s| !matches_scope(fqn, s)) + { + return false; + } + let pkg = package_of_resolution_key(fqn); + !self.imported_packages.contains(pkg) + || explicitly_includes(self.migrate_scope.as_deref(), pkg) + } } fn exists(p: &Path) -> bool { @@ -282,6 +347,33 @@ pub fn resolve_collection( } } + // The snapshot resolves before the predicates, which close over it. With no lock and no + // declared dependency it resolves to nothing. + let lock = read_lock(&config_dir)?; + let resolved_dependencies = verify_snapshot(&config_dir, &config.dependencies, lock.as_ref())?; + let imported_packages: BTreeSet = resolved_dependencies + .iter() + .flat_map(|d| d.packages.iter().cloned()) + .collect(); + let imported_nodes: BTreeSet = resolved_dependencies + .iter() + .flat_map(|d| d.nodes.iter().cloned()) + .collect(); + let file_ids: BTreeMap = resolved_dependencies + .iter() + .map(|d| (d.artifact_path.clone(), d.source_id.clone())) + .collect(); + let files: Vec = resolved_dependencies + .iter() + .map(|d| d.artifact_path.clone()) + .chain(own_files.iter().cloned()) + .collect(); + let migrate_scope = config.migrate.as_ref().and_then(|m| m.scope.clone()); + let compiled_migrate_scope = migrate_scope + .as_deref() + .map(|p| compile_scope(Some(p), None)) + .transpose()?; + let reference_ids: BTreeSet = own_sources .iter() .filter(|s| s.reference) @@ -292,11 +384,16 @@ pub fn resolve_collection( Ok(Collection { config_dir, reference_ids, - files: own_files.clone(), + files, own_files, sources: own_sources, source_roots, dependencies: config.dependencies.clone(), + resolved_dependencies, + file_ids, + imported_packages, + imported_nodes, + compiled_migrate_scope, libraries: config.libraries.clone(), physical_naming: config.physical_naming(), wire_format: config.wire_format(), @@ -312,7 +409,7 @@ pub fn resolve_collection( .is_some_and(|m| m.foreign_key_indexes == Some(true)), hand_edits: config.hand_edits, scope: config.scope.clone(), - migrate_scope: migrate.and_then(|m| m.scope), + migrate_scope, requirements_inherit: config.requirements_inherit.clone(), config, warnings, diff --git a/server/rust/metaobjects/src/dependencies.rs b/server/rust/metaobjects/src/dependencies.rs new file mode 100644 index 0000000000..7b24a65f5a --- /dev/null +++ b/server/rust/metaobjects/src/dependencies.rs @@ -0,0 +1,643 @@ +//! FR-023 metadata dependencies: the committed snapshot a project loads, verified against +//! its lock, and the rules that keep imported metadata out of the project's own output. +//! +//! Node `meta deps sync` is the only writer of `.metaobjects/deps//` and +//! `.metaobjects/deps.lock.json`; this module reads them. Ported from the TypeScript SDK +//! (`sdk/src/dependencies.ts`, `sdk/src/memory.ts`) and Python's +//! `config/dependencies.py`; `fixtures/dependency-conformance/` pins the behaviour. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; + +use serde_json::{Map, Value}; + +use crate::config::DependencySpec; +use crate::errors::{ + ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE, ERR_DEPENDENCY_NODE_COLLISION, + ERR_DEPENDENCY_PACKAGE_NOT_OWNED, ERR_DEPENDENCY_SNAPSHOT_STALE, MetaError, +}; +use crate::library::library_packages; +use crate::manifest::METAMODEL_VERSION; +use crate::node::{NodeId, PACKAGE_SEP, Tree}; +use crate::parser::TYPE_OBJECT; +use crate::sha256::sha256_hex; +use crate::sources::DEFAULT_METAOBJECTS_DIR; + +/// The directory under `.metaobjects/` holding one snapshot directory per dependency. +pub const DEPS_DIR: &str = "deps"; +/// The lock `meta deps sync` writes, under `.metaobjects/`. +pub const LOCK_FILE: &str = "deps.lock.json"; +/// The suffix of a dependency's canonical-JSON artifact. +pub const ARTIFACT_SUFFIX: &str = ".metaobjects.json"; +/// A dependency artifact loads under the id `dep:/`. +pub const DEPENDENCY_SOURCE_ID_PREFIX: &str = "dep:"; +/// The prefix of an `integrity` value: `sha256-` and 64 lowercase hex digits. +pub const INTEGRITY_PREFIX: &str = "sha256-"; + +const TYPE_REQUIREMENT: &str = "requirement"; +const ATTR_STATUS: &str = "status"; + +const LOCK_KEYS: &[&str] = &["schema_version", "dependencies"]; +const LOCK_ENTRY_KEYS: &[&str] = &[ + "version", + "metamodelVersion", + "artifact", + "integrity", + "packages", + "nodes", + "resolvedFrom", +]; +/// The transports a lock entry's `resolvedFrom` may name, exactly one of them. +const RESOLVED_FROM_TRANSPORTS: &[&str] = &["path", "npm", "python", "maven", "nuget"]; +const TRANSPORT_PATH: &str = "path"; +const TRANSPORTS_WITH_VERSION: &[&str] = &["maven", "nuget"]; +const RESOLVED_FROM_DIR: &str = "dir"; +const RESOLVED_FROM_VERSION: &str = "version"; + +/// One entry of a validated lock. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LockEntry { + pub version: String, + pub metamodel_version: String, + pub artifact: String, + pub integrity: String, + pub packages: Vec, + pub nodes: Vec, +} + +/// A validated `.metaobjects/deps.lock.json`, keyed by dependency name. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Lock { + pub dependencies: BTreeMap, +} + +/// A dependency whose snapshot was verified against the lock: the artifact the collection +/// loads first, and what it exports. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResolvedDependency { + pub name: String, + pub version: String, + pub packages: Vec, + pub nodes: Vec, + pub artifact_path: PathBuf, + /// The loader id: `dep:/`. + pub source_id: String, +} + +fn stale(detail: impl std::fmt::Display) -> MetaError { + MetaError::code( + ERR_DEPENDENCY_SNAPSHOT_STALE, + format!("{detail}; run `meta deps sync`"), + ) +} + +/// `sha256-` and the lowercase hex SHA-256 of `data`. +pub fn sha256_integrity(data: &[u8]) -> String { + format!("{INTEGRITY_PREFIX}{}", sha256_hex(data)) +} + +/// `dep:/`. +pub fn dependency_source_id(name: &str, artifact: &str) -> String { + format!("{DEPENDENCY_SOURCE_ID_PREFIX}{name}/{artifact}") +} + +/// The package part of a resolution key (`acme::common::Customer` is `acme::common`), or +/// `""` for a bare name. A dotted tail is part of the last segment. +pub fn package_of_resolution_key(key: &str) -> &str { + key.rfind(PACKAGE_SEP).map_or("", |i| &key[..i]) +} + +/// Does some pattern NAME `pkg`? Drop the pattern's last segment (it names a node); what +/// remains must be wildcard-free and equal to `pkg`. So `acme::common::**` and +/// `acme::common::Address` name `acme::common`, while `acme::**` and `**` reach its nodes +/// and name nothing. A pattern that matches a package's nodes is a weaker statement than +/// one that names the package. +pub fn explicitly_includes(patterns: Option<&[String]>, pkg: &str) -> bool { + if pkg.is_empty() { + return false; + } + patterns.unwrap_or_default().iter().any(|p| { + let named = package_of_resolution_key(p); + !named.is_empty() && !named.contains('*') && named == pkg + }) +} + +fn is_metamodel_version(v: &str) -> bool { + let mut parts = v.split('.'); + let digits = + |s: Option<&str>| s.is_some_and(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())); + digits(parts.next()) && digits(parts.next()) && parts.next().is_none() +} + +fn is_integrity(v: &str) -> bool { + v.strip_prefix(INTEGRITY_PREFIX).is_some_and(|hex| { + hex.len() == 64 + && hex + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) +} + +fn unknown_keys(obj: &Map, allowed: &[&str]) -> Vec { + let mut extra: Vec = obj + .keys() + .filter(|k| !allowed.contains(&k.as_str())) + .cloned() + .collect(); + extra.sort(); + extra +} + +fn strictly_sorted(values: &[String]) -> bool { + values.windows(2).all(|w| w[0] < w[1]) +} + +fn sorted_strings( + obj: &Map, + field: &str, + fail: &dyn Fn(String) -> MetaError, +) -> Result, MetaError> { + let values: Option> = obj.get(field).and_then(Value::as_array).and_then(|a| { + a.iter() + .map(|v| v.as_str().filter(|s| !s.is_empty()).map(str::to_string)) + .collect() + }); + let Some(values) = values else { + return Err(fail(format!( + "'{field}' must be an array of non-empty strings" + ))); + }; + if !strictly_sorted(&values) { + return Err(fail(format!("'{field}' must be sorted"))); + } + Ok(values) +} + +fn non_empty_string<'a>(obj: &'a Map, field: &str) -> Option<&'a str> { + obj.get(field) + .and_then(Value::as_str) + .filter(|s| !s.trim().is_empty()) +} + +/// Validate the fields a publisher's manifest and a lock entry share: `version`, +/// `metamodelVersion`, `artifact`, `integrity`, `packages`, `nodes`. `fail` makes the error +/// (each caller's code and context). +pub fn validate_common_fields( + obj: &Map, + fail: &dyn Fn(String) -> MetaError, +) -> Result { + let version = obj + .get("version") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .ok_or_else(|| fail("'version' must be a non-empty string".into()))?; + let metamodel_version = obj + .get("metamodelVersion") + .and_then(Value::as_str) + .filter(|s| is_metamodel_version(s)) + .ok_or_else(|| fail("'metamodelVersion' must match ^\\d+\\.\\d+$".into()))?; + let artifact = obj + .get("artifact") + .and_then(Value::as_str) + .filter(|s| s.ends_with(ARTIFACT_SUFFIX)) + .ok_or_else(|| fail(format!("'artifact' must end with '{ARTIFACT_SUFFIX}'")))?; + let integrity = obj + .get("integrity") + .and_then(Value::as_str) + .filter(|s| is_integrity(s)) + .ok_or_else(|| fail("'integrity' must match ^sha256-[0-9a-f]{64}$".into()))?; + Ok(LockEntry { + version: version.to_string(), + metamodel_version: metamodel_version.to_string(), + artifact: artifact.to_string(), + integrity: integrity.to_string(), + packages: sorted_strings(obj, "packages", fail)?, + nodes: sorted_strings(obj, "nodes", fail)?, + }) +} + +/// A lock entry's `resolvedFrom`: exactly one transport, `dir` only beside a package +/// transport, and a `version` required beside `maven` and `nuget`. +fn validate_resolved_from( + v: Option<&Value>, + fail: &dyn Fn(String) -> MetaError, +) -> Result<(), MetaError> { + let Some(obj) = v.and_then(Value::as_object) else { + return Err(fail("'resolvedFrom' must be an object".into())); + }; + let transports: Vec<&str> = RESOLVED_FROM_TRANSPORTS + .iter() + .copied() + .filter(|t| obj.contains_key(*t)) + .collect(); + let [transport] = transports[..] else { + return Err(fail( + "'resolvedFrom' must have exactly one of 'path' / 'npm' / 'python' / 'maven' / 'nuget'" + .into(), + )); + }; + if non_empty_string(obj, transport).is_none() { + return Err(fail(format!( + "'resolvedFrom.{transport}' must be a non-empty string" + ))); + } + let mut allowed = vec![transport]; + if transport != TRANSPORT_PATH { + allowed.push(RESOLVED_FROM_DIR); + } + let versioned = TRANSPORTS_WITH_VERSION.contains(&transport); + if versioned { + allowed.push(RESOLVED_FROM_VERSION); + } + let extra = unknown_keys(obj, &allowed); + if !extra.is_empty() { + return Err(fail(format!("'resolvedFrom' unknown key(s): {extra:?}"))); + } + if versioned && non_empty_string(obj, RESOLVED_FROM_VERSION).is_none() { + return Err(fail(format!( + "'resolvedFrom.version' is required beside '{transport}' and must be a non-empty string" + ))); + } + if obj.contains_key(RESOLVED_FROM_DIR) && non_empty_string(obj, RESOLVED_FROM_DIR).is_none() { + return Err(fail("'resolvedFrom.dir' must be a non-empty string".into())); + } + Ok(()) +} + +/// Validate a parsed `.metaobjects/deps.lock.json`. Every shape violation (an unknown key, +/// unsorted dependency names, a malformed entry) is `ERR_DEPENDENCY_SNAPSHOT_STALE`. +pub fn validate_lock(v: &Value) -> Result { + let lock_fail = |m: String| stale(format!("{LOCK_FILE}: {m}")); + let Some(obj) = v.as_object() else { + return Err(lock_fail("must be an object".into())); + }; + let extra = unknown_keys(obj, LOCK_KEYS); + if !extra.is_empty() { + return Err(lock_fail(format!("unknown key(s): {extra:?}"))); + } + if obj.get("schema_version").and_then(Value::as_u64) != Some(1) { + return Err(lock_fail("'schema_version' must be 1".into())); + } + let Some(deps) = obj.get("dependencies").and_then(Value::as_object) else { + return Err(lock_fail("'dependencies' must be an object".into())); + }; + let names: Vec = deps.keys().cloned().collect(); + if !strictly_sorted(&names) { + return Err(lock_fail("dependency keys must be sorted".into())); + } + let mut dependencies = BTreeMap::new(); + for (name, entry) in deps { + let fail = |m: String| stale(format!("{LOCK_FILE} ({name}): {m}")); + let Some(entry) = entry.as_object() else { + return Err(fail("must be an object".into())); + }; + let extra = unknown_keys(entry, LOCK_ENTRY_KEYS); + if !extra.is_empty() { + return Err(fail(format!("unknown key(s): {extra:?}"))); + } + let validated = validate_common_fields(entry, &fail)?; + validate_resolved_from(entry.get("resolvedFrom"), &fail)?; + dependencies.insert(name.clone(), validated); + } + Ok(Lock { dependencies }) +} + +/// Read `.metaobjects/deps.lock.json` under `config_dir`. `None` when there is no lock +/// (a project that declares no dependencies has none); a lock that is not JSON or fails +/// validation is `ERR_DEPENDENCY_SNAPSHOT_STALE`. +pub fn read_lock(config_dir: &Path) -> Result, MetaError> { + let path = config_dir.join(DEFAULT_METAOBJECTS_DIR).join(LOCK_FILE); + if !path.is_file() { + return Ok(None); + } + let parsed = std::fs::read_to_string(&path) + .map_err(|e| e.to_string()) + .and_then(|text| serde_json::from_str::(&text).map_err(|e| e.to_string())); + match parsed { + Ok(v) => validate_lock(&v).map(Some), + Err(e) => Err(stale(format!( + "{} exists but could not be read as JSON: {e}", + path.display() + ))), + } +} + +/// The major half of a `major.minor` metamodel version: the metadata contract is promised +/// on the major alone (ADR-0035 Amendment 2). +fn metamodel_major(v: &str) -> &str { + v.split('.').next().unwrap_or(v) +} + +/// Verify the committed snapshot against the lock, and resolve the dependencies the +/// collection loads first, in dependency NAME order (never the config's order, which must +/// not decide what the loader sees first). +/// +/// Staleness (no lock, a lock entry with no config entry or the reverse, a missing +/// snapshot, a snapshot that does not hash to the lock) is `ERR_DEPENDENCY_SNAPSHOT_STALE`. +/// A dependency published against another metamodel major is +/// `ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE`, and two dependencies exporting one node are +/// `ERR_DEPENDENCY_NODE_COLLISION`. No dependencies and no lock resolve to nothing without +/// touching the disk. +pub fn verify_snapshot( + config_dir: &Path, + specs: &[DependencySpec], + lock: Option<&Lock>, +) -> Result, MetaError> { + let declared: BTreeSet<&str> = specs.iter().map(|d| d.name.as_str()).collect(); + let Some(lock) = lock else { + if declared.is_empty() { + return Ok(Vec::new()); + } + let names: Vec<&str> = specs.iter().map(|d| d.name.as_str()).collect(); + return Err(stale(format!( + "{} dependenc{} declared ({}) but there is no {DEFAULT_METAOBJECTS_DIR}/{LOCK_FILE}", + names.len(), + if names.len() == 1 { "y is" } else { "ies are" }, + names.join(", ") + ))); + }; + if let Some(name) = lock + .dependencies + .keys() + .find(|n| !declared.contains(n.as_str())) + { + return Err(stale(format!( + "{DEFAULT_METAOBJECTS_DIR}/{LOCK_FILE} locks dependency \"{name}\", which {DEFAULT_METAOBJECTS_DIR}/config.json no longer declares" + ))); + } + let mut resolved = Vec::new(); + for name in declared { + let Some(entry) = lock.dependencies.get(name) else { + return Err(stale(format!( + "dependency \"{name}\" is declared but {DEFAULT_METAOBJECTS_DIR}/{LOCK_FILE} has no entry for it" + ))); + }; + let artifact_path = config_dir + .join(DEFAULT_METAOBJECTS_DIR) + .join(DEPS_DIR) + .join(name) + .join(&entry.artifact); + let Ok(data) = std::fs::read(&artifact_path) else { + return Err(stale(format!( + "the committed snapshot for \"{name}\" is missing (expected {})", + artifact_path.display() + ))); + }; + let actual = sha256_integrity(&data); + if actual != entry.integrity { + return Err(stale(format!( + "the committed snapshot for \"{name}\" does not match the lock — {} hashes to {actual}, the lock records {}", + artifact_path.display(), + entry.integrity + ))); + } + if metamodel_major(&entry.metamodel_version) != metamodel_major(METAMODEL_VERSION) { + return Err(MetaError::code( + ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE, + format!( + "dependency \"{name}\" was published against metamodel {}; this toolchain speaks {METAMODEL_VERSION}. A different metamodel MAJOR is a different metadata contract — upgrade the toolchain, or use a release of \"{name}\" built against it.", + entry.metamodel_version + ), + )); + } + resolved.push(ResolvedDependency { + name: name.to_string(), + version: entry.version.clone(), + packages: entry.packages.clone(), + nodes: entry.nodes.clone(), + artifact_path, + source_id: dependency_source_id(name, &entry.artifact), + }); + } + // Checked across the whole set, so the error names the two in name order. + let mut owner: BTreeMap<&str, &str> = BTreeMap::new(); + for dep in &resolved { + for node in &dep.nodes { + if let Some(prior) = owner.insert(node, &dep.name) { + return Err(MetaError::code( + ERR_DEPENDENCY_NODE_COLLISION, + format!( + "dependencies \"{prior}\" and \"{}\" both export \"{node}\" — one fully-qualified node cannot come from two places, and whichever loaded second would silently win", + dep.name + ), + )); + } + } + } + Ok(resolved) +} + +/// Refuse a NEW top-level object or requirement declared into a package a dependency +/// owns (FR-023 §11.5). Imported-ness is decided by package, so such a node would drop out +/// of this project's codegen, migrate and ledger with no output and no error. An overlay +/// of the dependency's own node is not refused: its key is one of `imported_nodes`. +/// +/// Run it AFTER the loader's own errors: an overlay whose target the upstream removed +/// fails first, with its own code. +pub fn refuse_unowned_packages( + tree: &Tree, + root: NodeId, + imported_packages: &BTreeSet, + imported_nodes: &BTreeSet, +) -> Result<(), MetaError> { + if imported_packages.is_empty() { + return Ok(()); + } + // ADR-0039 sanctioned own: the metadata root has no super chain, so its own children + // are its top-level nodes, which is exactly what this asks about. + for &id in tree.own_children(root) { + let node = tree.node(id); + if node.type_name != TYPE_OBJECT && node.type_name != TYPE_REQUIREMENT { + continue; + } + let key = tree.resolution_key(id); + let pkg = package_of_resolution_key(&key); + if !imported_packages.contains(pkg) || imported_nodes.contains(&key) { + continue; + } + return Err(MetaError::at( + ERR_DEPENDENCY_PACKAGE_NOT_OWNED, + format!( + "\"{key}\" is declared here, but the package \"{pkg}\" belongs to a metadata dependency this project imports, and \"{key}\" is not one of the nodes that dependency exports. Declare it in a package this project owns and 'extends' the dependency's node if it needs its shape; if it was meant to AMEND the dependency's node, give it that node's name and 'overlay: true'; if this project really does own \"{pkg}\", name it in 'scope.include' and stop importing it." + ), + node.source.clone(), + )); + } + Ok(()) +} + +/// One requirement and its address: `::`, or the bare path +/// with no package. Only requirements contribute a path segment. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AddressedRequirement { + pub node: NodeId, + pub package: String, + pub path: String, +} + +impl AddressedRequirement { + /// The key a collection predicate reads: `::`, or the bare path. + pub fn fqn(&self) -> String { + if self.package.is_empty() { + self.path.clone() + } else { + format!("{}{PACKAGE_SEP}{}", self.package, self.path) + } + } +} + +/// Every `requirement.*` node at any depth, in document order, each with its dotted path. +/// A non-requirement node is walked through without adding a segment. +pub fn addressed_requirements(tree: &Tree, root: NodeId) -> Vec { + fn walk(tree: &Tree, n: NodeId, prefix: &str, out: &mut Vec) { + for &c in tree.children(n).iter() { + let node = tree.node(c); + let is_req = node.type_name == TYPE_REQUIREMENT; + let path = if !is_req { + prefix.to_string() + } else if prefix.is_empty() { + node.name.clone() + } else { + format!("{prefix}.{}", node.name) + }; + if is_req { + out.push(AddressedRequirement { + node: c, + package: tree.effective_package(c), + path: path.clone(), + }); + } + walk(tree, c, &path, out); + } + } + let mut out = Vec::new(); + walk(tree, root, "", &mut out); + out +} + +/// A project's requirement ledger: the requirements that are its own to answer for, and +/// whether object coverage is measured. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Ledger { + pub requirements: Vec, + /// Only a requirement the project wrote itself switches coverage on: one in a shipped + /// library's package, or a dependency's (inherited or not), never does. + pub measure_coverage: bool, +} + +impl Ledger { + /// Each ledger requirement's address and effective `@status` (after overlays). + pub fn statuses(&self, tree: &Tree) -> BTreeMap { + self.requirements + .iter() + .map(|a| { + let status = tree + .attr(a.node, ATTR_STATUS) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + (a.fqn(), status) + }) + .collect() + } +} + +/// The ledger of a loaded model. `in_ledger` keeps a dependency's requirement only when +/// `requirements.inherit` names its package; `imported` tells a dependency's requirement +/// from the project's own. +pub fn requirement_ledger( + tree: &Tree, + root: NodeId, + in_ledger: impl Fn(&str) -> bool, + imported: impl Fn(&str) -> bool, +) -> Ledger { + let requirements: Vec = addressed_requirements(tree, root) + .into_iter() + .filter(|a| in_ledger(&a.fqn())) + .collect(); + let libraries = library_packages(); + let measure_coverage = requirements + .iter() + .any(|a| !libraries.contains(&a.package) && !imported(&a.fqn())); + Ledger { + requirements, + measure_coverage, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pattern_names_a_package_only_without_a_wildcard() { + let p = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + assert!(explicitly_includes( + Some(&p(&["acme::common::**"])), + "acme::common" + )); + assert!(explicitly_includes( + Some(&p(&["acme::common::Address"])), + "acme::common" + )); + assert!(!explicitly_includes( + Some(&p(&["acme::**"])), + "acme::common" + )); + assert!(!explicitly_includes(Some(&p(&["**"])), "acme::common")); + assert!(!explicitly_includes(Some(&p(&["acme::*::X"])), "acme::*")); + assert!(!explicitly_includes(None, "acme::common")); + assert!(!explicitly_includes(Some(&p(&["Address"])), "")); + } + + #[test] + fn the_package_of_a_key_drops_its_last_segment() { + assert_eq!( + package_of_resolution_key("acme::common::Customer"), + "acme::common" + ); + assert_eq!(package_of_resolution_key("acme::Customers.Email"), "acme"); + assert_eq!(package_of_resolution_key("Customer"), ""); + } + + #[test] + fn a_lock_is_validated_strictly() { + let entry = serde_json::json!({ + "version": "1.0.0", "metamodelVersion": "1.0", + "resolvedFrom": { "path": "../x" }, "artifact": "x.metaobjects.json", + "integrity": format!("sha256-{}", "0".repeat(64)), + "packages": ["a"], "nodes": ["a::A", "a::B"] + }); + let ok = serde_json::json!({ "schema_version": 1, "dependencies": { "x": entry } }); + assert_eq!(validate_lock(&ok).unwrap().dependencies.len(), 1); + let bad = |mutate: &dyn Fn(&mut Value)| { + let mut v = ok.clone(); + mutate(&mut v); + validate_lock(&v).unwrap_err().code + }; + let stale = ERR_DEPENDENCY_SNAPSHOT_STALE; + assert_eq!(bad(&|v| v["dependencies"]["x"]["mode"] = "x".into()), stale); + assert_eq!( + bad(&|v| v["dependencies"]["x"]["nodes"] = serde_json::json!(["a::B", "a::A"])), + stale + ); + assert_eq!( + bad(&|v| v["dependencies"]["x"]["integrity"] = "sha256-AB".into()), + stale + ); + assert_eq!( + bad(&|v| v["dependencies"]["x"]["metamodelVersion"] = "1".into()), + stale + ); + assert_eq!( + bad(&|v| v["dependencies"]["x"]["resolvedFrom"]["npm"] = "y".into()), + stale + ); + assert_eq!( + bad(&|v| v["dependencies"]["x"]["resolvedFrom"]["dir"] = "y".into()), + stale + ); + assert_eq!(bad(&|v| v["schema_version"] = 2.into()), stale); + assert_eq!(bad(&|v| v["extra"] = 1.into()), stale); + } +} diff --git a/server/rust/metaobjects/src/errors.rs b/server/rust/metaobjects/src/errors.rs index fa6421a28c..d211007d80 100644 --- a/server/rust/metaobjects/src/errors.rs +++ b/server/rust/metaobjects/src/errors.rs @@ -45,6 +45,16 @@ pub const ERR_SOURCE_KIND_UNSUPPORTED: &str = "ERR_SOURCE_KIND_UNSUPPORTED"; pub const ERR_COLLECTION_NOT_FOUND: &str = "ERR_COLLECTION_NOT_FOUND"; pub const ERR_COLLECTION_NAME_COLLISION: &str = "ERR_COLLECTION_NAME_COLLISION"; pub const ERR_UNKNOWN_LIBRARY: &str = "ERR_UNKNOWN_LIBRARY"; +/// A scope pattern (`scope`, `migrate.scope`, `requirements.inherit`) that does not parse. +pub const ERR_SCOPE_PATTERN_INVALID: &str = "ERR_SCOPE_PATTERN_INVALID"; +/// The committed dependency snapshot and its lock disagree, or one of them is missing. +pub const ERR_DEPENDENCY_SNAPSHOT_STALE: &str = "ERR_DEPENDENCY_SNAPSHOT_STALE"; +/// A dependency published against a different metamodel major. +pub const ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE: &str = "ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE"; +/// Two dependencies export the same fully-qualified node. +pub const ERR_DEPENDENCY_NODE_COLLISION: &str = "ERR_DEPENDENCY_NODE_COLLISION"; +/// A project declares a new top-level node into a package a dependency owns. +pub const ERR_DEPENDENCY_PACKAGE_NOT_OWNED: &str = "ERR_DEPENDENCY_PACKAGE_NOT_OWNED"; /// A `template.*` declared only in reference sources. pub const ERR_REFERENCE_SOURCE_TEMPLATE: &str = "ERR_REFERENCE_SOURCE_TEMPLATE"; /// The reference facet's default code for a value that names no node @@ -89,6 +99,11 @@ pub const ALL_CODES: &[&str] = &[ ERR_COLLECTION_NOT_FOUND, ERR_COLLECTION_NAME_COLLISION, ERR_UNKNOWN_LIBRARY, + ERR_SCOPE_PATTERN_INVALID, + ERR_DEPENDENCY_SNAPSHOT_STALE, + ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE, + ERR_DEPENDENCY_NODE_COLLISION, + ERR_DEPENDENCY_PACKAGE_NOT_OWNED, ERR_REFERENCE_SOURCE_TEMPLATE, ERR_REF_UNRESOLVED, ERR_REF_WRONG_KIND, diff --git a/server/rust/metaobjects/src/lib.rs b/server/rust/metaobjects/src/lib.rs index 55b797339c..4bd7741d43 100644 --- a/server/rust/metaobjects/src/lib.rs +++ b/server/rust/metaobjects/src/lib.rs @@ -8,6 +8,7 @@ pub mod collection; pub mod config; +pub mod dependencies; pub mod docs_view; pub mod errors; pub mod json; @@ -25,7 +26,9 @@ pub mod registry; pub mod report_shape; pub mod rules_check; pub mod rules_names; +pub mod scope; pub mod serializer; +pub mod sha256; pub mod source; pub mod sources; pub mod timing; diff --git a/server/rust/metaobjects/src/scope.rs b/server/rust/metaobjects/src/scope.rs new file mode 100644 index 0000000000..2103a62ab5 --- /dev/null +++ b/server/rust/metaobjects/src/scope.rs @@ -0,0 +1,194 @@ +//! The scope-pattern grammar (FR-023 §4.3): does a fully-qualified node name fall inside +//! an `include` / `exclude` scope? Ported from the TypeScript engine +//! (`metadata/src/scope.ts`) and Python's `scope.py`, which compile a pattern to a regular +//! expression; this port matches the same language segment by segment instead. +//! +//! A pattern is segments joined by `::`. `**` spans one or more whole segments; `*` matches +//! any run of characters inside one segment and never crosses a separator. Every other +//! character is literal. No segment of a name a pattern matches contains a `:`. + +use crate::errors::{ERR_SCOPE_PATTERN_INVALID, MetaError}; +use crate::node::PACKAGE_SEP; + +const SPAN: &str = "**"; +const WILDCARD: char = '*'; + +/// One segment of a compiled pattern. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Segment { + /// `**`: one or more whole segments. + Span, + /// A glob inside one segment: literal parts split at each `*`. + Glob(Vec), +} + +/// A compiled pattern. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pattern(Vec); + +/// A compiled `include` / `exclude` pair. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CompiledScope { + include: Vec, + exclude: Vec, +} + +fn invalid(message: String) -> MetaError { + MetaError::code(ERR_SCOPE_PATTERN_INVALID, message) +} + +/// Compile one pattern. An empty pattern, an empty segment and a single `:` are +/// `ERR_SCOPE_PATTERN_INVALID`. +pub fn compile_pattern(pattern: &str) -> Result { + if pattern.is_empty() { + return Err(invalid("scope pattern must not be empty".into())); + } + let mut segments = Vec::new(); + for segment in pattern.split(PACKAGE_SEP) { + if segment.is_empty() { + return Err(invalid(format!( + "empty segment in scope pattern \"{pattern}\"" + ))); + } + if segment.contains(':') { + return Err(invalid(format!( + "scope pattern \"{pattern}\" has a malformed separator (an odd run of \":\") — segments are joined by \"::\", never a single \":\"" + ))); + } + segments.push(if segment == SPAN { + Segment::Span + } else { + Segment::Glob(segment.split(WILDCARD).map(str::to_string).collect()) + }); + } + Ok(Pattern(segments)) +} + +/// Compile a scope. An absent or empty `include` means everything; `exclude` is applied +/// after it. +pub fn compile_scope( + include: Option<&[String]>, + exclude: Option<&[String]>, +) -> Result { + let compile = |ps: Option<&[String]>| -> Result, MetaError> { + ps.unwrap_or_default() + .iter() + .map(|p| compile_pattern(p)) + .collect() + }; + Ok(CompiledScope { + include: compile(include)?, + exclude: compile(exclude)?, + }) +} + +/// Does a glob (literal parts split at each `*`) match the whole of `text`? +fn glob_matches(parts: &[String], text: &str) -> bool { + let Some((first, rest)) = parts.split_first() else { + return text.is_empty(); + }; + let Some(mut tail) = text.strip_prefix(first.as_str()) else { + return false; + }; + let Some((last, middle)) = rest.split_last() else { + return tail.is_empty(); + }; + for part in middle { + match tail.find(part.as_str()) { + Some(i) => tail = &tail[i + part.len()..], + None => return false, + } + } + tail.len() >= last.len() && tail.ends_with(last.as_str()) +} + +fn segments_match(pattern: &[Segment], name: &[&str]) -> bool { + match pattern.split_first() { + None => name.is_empty(), + Some((Segment::Span, rest)) => { + (1..=name.len()).any(|taken| segments_match(rest, &name[taken..])) + } + Some((Segment::Glob(parts), rest)) => name + .split_first() + .is_some_and(|(first, tail)| glob_matches(parts, first) && segments_match(rest, tail)), + } +} + +impl Pattern { + /// Does the pattern match the whole of `fqn`? + pub fn matches(&self, fqn: &str) -> bool { + let name: Vec<&str> = fqn.split(PACKAGE_SEP).collect(); + // A segment is non-empty and holds no `:`: an odd run of colons, or an empty + // segment, is a name no pattern matches. + if name.iter().any(|s| s.is_empty() || s.contains(':')) { + return false; + } + segments_match(&self.0, &name) + } +} + +/// Is `fqn` inside the scope? An empty `include` means everything. +pub fn matches_scope(fqn: &str, scope: &CompiledScope) -> bool { + let included = scope.include.is_empty() || scope.include.iter().any(|p| p.matches(fqn)); + included && !scope.exclude.iter().any(|p| p.matches(fqn)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn m(pattern: &str, fqn: &str) -> bool { + compile_pattern(pattern).unwrap().matches(fqn) + } + + #[test] + fn a_span_covers_one_or_more_segments() { + assert!(m("acme::**", "acme::Order")); + assert!(m("acme::**", "acme::sales::Order")); + assert!(!m("acme::**", "acme")); + assert!(m("**", "Order")); + assert!(m("**::Order", "a::b::Order")); + assert!(!m("**::Order", "Order")); + } + + #[test] + fn a_star_stays_inside_its_segment() { + assert!(m("acme::Or*", "acme::Order")); + assert!(m("acme::*", "acme::Order")); + assert!(!m("acme::*", "acme::sales::Order")); + assert!(m("a*b*c", "abc")); + assert!(m("a*b*c", "aXbYc")); + assert!(!m("a*b*c", "aXbY")); + assert!(m("*der", "Order")); + assert!(!m("ab*ba", "aba")); + } + + #[test] + fn everything_else_is_literal() { + assert!(m("acme::Order", "acme::Order")); + assert!(!m("acme::Order", "acme::Orders")); + assert!(m("a.b", "a.b")); + assert!(!m("a.b", "aXb")); + } + + #[test] + fn a_malformed_pattern_is_refused() { + for bad in ["", "acme::", "::acme", "acme:Order", "acme:::Order"] { + let e = compile_pattern(bad).unwrap_err(); + assert_eq!(e.code, ERR_SCOPE_PATTERN_INVALID, "{bad}"); + } + } + + #[test] + fn exclude_applies_after_include() { + let s = compile_scope( + Some(&["acme::**".to_string()]), + Some(&["acme::internal::**".to_string()]), + ) + .unwrap(); + assert!(matches_scope("acme::Order", &s)); + assert!(!matches_scope("acme::internal::Audit", &s)); + assert!(!matches_scope("other::Order", &s)); + assert!(matches_scope("anything", &CompiledScope::default())); + } +} diff --git a/server/rust/metaobjects/src/sha256.rs b/server/rust/metaobjects/src/sha256.rs new file mode 100644 index 0000000000..4f90064783 --- /dev/null +++ b/server/rust/metaobjects/src/sha256.rs @@ -0,0 +1,205 @@ +//! SHA-256 (FIPS 180-4), std only. +//! +//! Two contracts hash with it: the dependency lock (`deps.lock.json`'s `integrity`, the +//! digest of a committed snapshot) and the codegen hash manifest +//! (`.metaobjects/.gen-state/.hashes/`), the same digests every port writes. It is a few +//! dozen lines, so it lives here rather than as a dependency. The codegen crate re-exports +//! it, and its `build.rs` uses it to hash the engine's own sources into the skip key. + +const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +const H0: [u32; 8] = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, +]; + +fn compress(state: &mut [u32; 8], block: &[u8]) { + let mut w = [0u32; 64]; + for (i, chunk) in block.chunks_exact(4).enumerate() { + w[i] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + .wrapping_add(s0) + .wrapping_add(w[i - 7]) + .wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state; + for i in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ (!e & g); + let t1 = h + .wrapping_add(s1) + .wrapping_add(ch) + .wrapping_add(K[i]) + .wrapping_add(w[i]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let t2 = s0.wrapping_add(maj); + h = g; + g = f; + f = e; + e = d.wrapping_add(t1); + d = c; + c = b; + b = a; + a = t1.wrapping_add(t2); + } + for (s, v) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) { + *s = s.wrapping_add(v); + } +} + +/// An incremental SHA-256. +#[derive(Clone)] +pub struct Sha256 { + state: [u32; 8], + buffer: [u8; 64], + filled: usize, + length: u64, +} + +impl Default for Sha256 { + fn default() -> Self { + Self::new() + } +} + +impl Sha256 { + pub fn new() -> Self { + Self { + state: H0, + buffer: [0; 64], + filled: 0, + length: 0, + } + } + + pub fn update(&mut self, mut data: &[u8]) { + self.length += data.len() as u64; + if self.filled > 0 { + let take = (64 - self.filled).min(data.len()); + self.buffer[self.filled..self.filled + take].copy_from_slice(&data[..take]); + self.filled += take; + data = &data[take..]; + if self.filled < 64 { + return; + } + let block = self.buffer; + compress(&mut self.state, &block); + self.filled = 0; + } + let mut blocks = data.chunks_exact(64); + for block in &mut blocks { + compress(&mut self.state, block); + } + let rest = blocks.remainder(); + self.buffer[..rest.len()].copy_from_slice(rest); + self.filled = rest.len(); + } + + pub fn finish(mut self) -> [u8; 32] { + let bit_length = self.length.wrapping_mul(8); + let mut tail = [0u8; 72]; + tail[0] = 0x80; + // Pad to 56 mod 64, then the 64-bit big-endian bit length. + let pad = if self.filled < 56 { + 56 - self.filled + } else { + 120 - self.filled + }; + tail[pad..pad + 8].copy_from_slice(&bit_length.to_be_bytes()); + let total_length = self.length; + self.update(&tail[..pad + 8]); + self.length = total_length; + debug_assert_eq!(self.filled, 0); + let mut out = [0u8; 32]; + for (chunk, word) in out.chunks_exact_mut(4).zip(self.state) { + chunk.copy_from_slice(&word.to_be_bytes()); + } + out + } +} + +/// The lowercase hex SHA-256 of `data`. +pub fn sha256_hex(data: &[u8]) -> String { + let mut h = Sha256::new(); + h.update(data); + hex(&h.finish()) +} + +/// Lowercase hex of `bytes`. +pub fn hex(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for b in bytes { + out.push(DIGITS[(b >> 4) as usize] as char); + out.push(DIGITS[(b & 15) as usize] as char); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_the_fips_180_4_vectors() { + assert_eq!( + sha256_hex(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + assert_eq!( + sha256_hex(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + ); + let million_a = vec![b'a'; 1_000_000]; + assert_eq!( + sha256_hex(&million_a), + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" + ); + } + + #[test] + fn chunked_updates_equal_one_shot_at_every_boundary() { + let data: Vec = (0..300u32).map(|i| (i * 7 + 3) as u8).collect(); + let whole = sha256_hex(&data); + for split in 0..data.len() { + let mut h = Sha256::new(); + h.update(&data[..split]); + h.update(&data[split..]); + assert_eq!(hex(&h.finish()), whole, "split at {split}"); + } + } + + #[test] + fn padding_edges_55_56_63_64_bytes_agree_with_known_digests() { + // 55 bytes fits the length in the same block; 56 spills into a second one. + assert_eq!( + sha256_hex(&[b'a'; 55]), + "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318" + ); + assert_eq!( + sha256_hex(&[b'a'; 56]), + "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a" + ); + assert_eq!( + sha256_hex(&[b'a'; 64]), + "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb" + ); + } +} diff --git a/server/rust/metaobjects/tests/config_reader.rs b/server/rust/metaobjects/tests/config_reader.rs index 5639df357e..411f9a60a4 100644 --- a/server/rust/metaobjects/tests/config_reader.rs +++ b/server/rust/metaobjects/tests/config_reader.rs @@ -478,7 +478,7 @@ fn malformed_json_is_a_coded_error() { // --- collection, discovery, walk ---------------------------------------------- #[test] -fn collection_carries_the_declared_settings_and_unresolved_dependencies() { +fn collection_carries_the_declared_settings() { let s = Scratch::new(); s.write("model/meta.a.json", "{}"); s.config(&json!({ @@ -486,7 +486,7 @@ fn collection_carries_the_declared_settings_and_unresolved_dependencies() { "naming": {"columns": "literal"}, "wire": {"decimals": "string"}, "api": {"unknownFields": "drop"}, "enums": {"maxLength": 16}, "migrate": {"conventions": "efcore", "checks": {"skipRedundant": true}, "foreignKeyIndexes": true, "scope": ["a::**"]}, - "verify": {"handEdits": "fail"}, "dependencies": [{"name": "d", "path": "../d"}], "foo": 1 + "verify": {"handEdits": "fail"}, "foo": 1 })); let c = resolve_collection(&s.0, Some(&s.0), &NamingRegistry::builtin()).unwrap(); assert_eq!(c.physical_naming.columns, "literal"); @@ -497,11 +497,25 @@ fn collection_carries_the_declared_settings_and_unresolved_dependencies() { assert!(c.skip_redundant_checks && c.foreign_key_indexes); assert_eq!(c.hand_edits, Some(HandEditsPolicy::Fail)); assert_eq!(c.migrate_scope.as_deref(), Some(&["a::**".to_string()][..])); - assert_eq!(c.dependencies.len(), 1); + assert!(c.dependencies.is_empty() && c.resolved_dependencies.is_empty()); assert_eq!(c.warnings.len(), 1); assert_eq!(c.source_roots, [s.0.join("model")]); } +#[test] +fn a_declared_dependency_resolves_against_its_lock() { + // The dependency corpus (`dependency_conformance.rs`) pins resolution; this pins that + // a declared dependency is no longer handed back unresolved. + let s = Scratch::new(); + s.write("model/meta.a.json", "{}"); + s.config(&json!({ + "schema_version": 1, "sources": [{"path": "model"}], + "dependencies": [{"name": "d", "path": "../d"}] + })); + let e = resolve_collection(&s.0, Some(&s.0), &NamingRegistry::builtin()).unwrap_err(); + assert_eq!(e.code, "ERR_DEPENDENCY_SNAPSHOT_STALE"); +} + #[test] fn discovery_finds_the_nearest_config_and_stops_at_git() { let s = Scratch::new(); diff --git a/server/rust/metaobjects/tests/dependency_conformance.rs b/server/rust/metaobjects/tests/dependency_conformance.rs new file mode 100644 index 0000000000..e70bf0b3ca --- /dev/null +++ b/server/rust/metaobjects/tests/dependency_conformance.rs @@ -0,0 +1,315 @@ +//! The dependency gate (FR-023): the resolution arm of the shared +//! `fixtures/dependency-conformance/cases.json`, ledger included. Each case resolves the +//! same file set (or fails with the same code) as every other port, and, when it asks, +//! loads to the same imported, selected and migrate-governed sets, the same load error and +//! the same requirement ledger. +//! +//! The check arm (`expectCheck`, `verify --deps`) is not run here. Python, Java and C# +//! also assert the ledger through a requirement-tests generator's identities; this port +//! has none, so it asserts the ledger's scan alone. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU32, Ordering}; + +use metaobjects::collection::{Collection, resolve_collection}; +use metaobjects::dependencies::{refuse_unowned_packages, requirement_ledger}; +use metaobjects::loader::{LoadResult, Loader}; +use metaobjects::naming::NamingRegistry; +use metaobjects::parser::TYPE_OBJECT; +use metaobjects::providers::default_registry; +use serde_json::Value; + +fn corpus_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/dependency-conformance") +} + +/// A fresh directory under `$DEV_SCRATCH` (RAM) or the system temp dir, removed on drop. +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + static N: AtomicU32 = AtomicU32::new(0); + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!( + "mo-dependency-{}-{}", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn write(p: &Path, bytes: &[u8]) { + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, bytes).unwrap(); +} + +/// Lay the case out under `root`; returns the directory resolution runs from. +fn materialize(root: &Path, case: &Value) -> PathBuf { + for (rel, content) in case["tree"].as_object().unwrap() { + write(&root.join(rel), content.as_str().unwrap().as_bytes()); + } + if let Some(files) = case.get("treeFiles").and_then(Value::as_object) { + for (rel, corpus_rel) in files { + // Copied byte for byte: the lock pins the artifact's hash. + let bytes = std::fs::read(corpus_dir().join(corpus_rel.as_str().unwrap())).unwrap(); + write(&root.join(rel), &bytes); + } + } + let from = root.join( + case.get("resolveFrom") + .and_then(Value::as_str) + .unwrap_or("."), + ); + std::fs::create_dir_all(&from).unwrap(); + if !case["config"].is_null() { + let text = serde_json::to_string_pretty(&case["config"]).unwrap(); + write(&from.join(".metaobjects/config.json"), text.as_bytes()); + } + if let Some(lock) = case.get("lock") { + let text = serde_json::to_string_pretty(lock).unwrap(); + write(&from.join(".metaobjects/deps.lock.json"), text.as_bytes()); + } + from +} + +fn load(collection: &Collection) -> LoadResult { + let mut registry = default_registry().expect("the built-in providers compose"); + registry.seal(); + let (sources, read_errors) = collection.read_sources(); + assert!(read_errors.is_empty(), "{read_errors:?}"); + Loader::new(®istry) + .naming( + NamingRegistry::builtin(), + collection.physical_naming.clone(), + ) + .load_sources(&sources) +} + +fn strings(v: &Value) -> BTreeSet { + v.as_array() + .unwrap() + .iter() + .map(|s| s.as_str().unwrap().to_string()) + .collect() +} + +/// Every loaded top-level object's resolution key: the set the corpus's +/// `expectImported` / `expectSelected` / `expectMigrateGoverned` are exhaustive over. +fn top_level_objects(result: &LoadResult) -> Vec { + // ADR-0039 sanctioned own: the metadata root has no super chain, so its own children + // are its top-level nodes. + result + .tree + .own_children(result.root) + .iter() + .filter(|&&id| result.tree.node(id).type_name == TYPE_OBJECT) + .map(|&id| result.tree.resolution_key(id)) + .collect() +} + +fn clean_load(collection: &Collection) -> Result { + let result = load(collection); + if let Some(e) = result.errors.first() { + return Err(format!("the model did not load: {} {}", e.code, e.message)); + } + refuse_unowned_packages( + &result.tree, + result.root, + &collection.imported_packages, + &collection.imported_nodes, + ) + .map_err(|e| format!("refused: {} {}", e.code, e.message))?; + Ok(result) +} + +fn check_set( + what: &str, + case: &Value, + key: &str, + objects: &[String], + keep: impl Fn(&str) -> bool, +) -> Result<(), String> { + let Some(expected) = case.get(key) else { + return Ok(()); + }; + let actual: BTreeSet = objects.iter().filter(|f| keep(f)).cloned().collect(); + let expected = strings(expected); + if actual != expected { + return Err(format!("{what} {actual:?} != expected {expected:?}")); + } + Ok(()) +} + +/// Run one case; `Err` describes how it diverged. +fn run_case(case: &Value) -> Result<(), String> { + let scratch = Scratch::new(); + let root = scratch.0.clone(); + let from = materialize(&root, case); + let resolved = resolve_collection(&from, Some(&from), &NamingRegistry::builtin()); + + if let Some(code) = case.get("expectError").and_then(Value::as_str) { + return match resolved { + Err(e) if e.code == code => Ok(()), + Err(e) => Err(format!("failed with {} not {code}: {}", e.code, e.message)), + Ok(_) => Err(format!("resolved, expected {code}")), + }; + } + let Some(expect_files) = case.get("expectFiles") else { + return Err("the case has neither expectFiles nor expectError".into()); + }; + let collection = resolved.map_err(|e| format!("unexpected error: {} {}", e.code, e.message))?; + let actual: Vec = collection + .files + .iter() + .map(|f| { + f.strip_prefix(&root) + .unwrap_or_else(|_| panic!("{} is outside the case root", f.display())) + .to_string_lossy() + .replace('\\', "/") + }) + .collect(); + let expected = strings(expect_files); + let set: BTreeSet = actual.iter().cloned().collect(); + if set != expected || actual.len() != expected.len() { + return Err(format!("files {actual:?} != expected {expected:?}")); + } + + let needs_load = ["expectImported", "expectSelected", "expectMigrateGoverned"] + .iter() + .any(|k| case.get(*k).is_some()); + if needs_load { + let result = clean_load(&collection)?; + let objects = top_level_objects(&result); + check_set("imported", case, "expectImported", &objects, |f| { + collection.imported(f) + })?; + check_set("selected", case, "expectSelected", &objects, |f| { + collection.in_scope(f) + })?; + check_set( + "migrate-governed", + case, + "expectMigrateGoverned", + &objects, + |f| collection.in_migrate_scope(f), + )?; + } + + if let Some(expected) = case.get("expectLedger") { + let result = clean_load(&collection)?; + let ledger = requirement_ledger( + &result.tree, + result.root, + |f| collection.in_ledger(f), + |f| collection.imported(f), + ); + let actual = ledger.statuses(&result.tree); + let expected: BTreeMap = expected + .as_object() + .unwrap() + .iter() + .map(|(k, v)| (k.clone(), v.as_str().unwrap().to_string())) + .collect(); + if actual != expected { + return Err(format!("ledger {actual:?} != expected {expected:?}")); + } + if ledger.requirements.len() != expected.len() { + return Err(format!( + "{} ledger requirements, a duplicate address collapsed", + ledger.requirements.len() + )); + } + let measured = case + .get("expectCoverageMeasured") + .and_then(Value::as_bool) + .unwrap_or(false); + if ledger.measure_coverage != measured { + return Err(format!( + "coverage measured {} != expected {measured}", + ledger.measure_coverage + )); + } + } + + if let Some(code) = case.get("expectLoadError").and_then(Value::as_str) { + let result = load(&collection); + // The loader's own errors come first; the ownership refusal runs only after a clean + // load (an overlay whose target the upstream removed fails with its own code). + let (got, files) = match result.errors.first() { + Some(e) => (e.code, e.source.files().to_vec()), + None => match refuse_unowned_packages( + &result.tree, + result.root, + &collection.imported_packages, + &collection.imported_nodes, + ) { + Err(e) => (e.code, e.source.files().to_vec()), + Ok(()) => return Err(format!("loaded clean, expected {code}")), + }, + }; + if got != code { + return Err(format!("load failed with {got}, expected {code}")); + } + if let Some(expected) = case.get("expectErrorFiles") { + let expected: Vec = expected + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap().to_string()) + .collect(); + if files.first() != expected.first() { + return Err(format!("the error names {files:?}, expected {expected:?}")); + } + } + } + Ok(()) +} + +#[test] +fn every_resolution_case_resolves_and_loads_as_in_every_port() { + let text = std::fs::read_to_string(corpus_dir().join("cases.json")).unwrap(); + let corpus: Value = serde_json::from_str(&text).unwrap(); + let cases: Vec<&Value> = corpus["cases"] + .as_array() + .unwrap() + .iter() + .filter(|c| c.get("expectCheck").is_none()) + .collect(); + // The corpus README counts 36 resolution cases, 7 of them with a ledger arm: a silently + // shrunk corpus is a failed gate, not a pass. + assert_eq!(cases.len(), 36, "the resolution arm's case count"); + assert_eq!( + cases + .iter() + .filter(|c| c.get("expectLedger").is_some()) + .count(), + 7, + "the ledger arm's case count" + ); + let failures: Vec = cases + .iter() + .filter_map(|case| { + run_case(case) + .err() + .map(|e| format!("{}: {e}", case["name"].as_str().unwrap())) + }) + .collect(); + assert!( + failures.is_empty(), + "{} of {} cases diverged:\n{}", + failures.len(), + cases.len(), + failures.join("\n") + ); +} diff --git a/server/rust/metaobjects/tests/scope_conformance.rs b/server/rust/metaobjects/tests/scope_conformance.rs new file mode 100644 index 0000000000..45926aa1bd --- /dev/null +++ b/server/rust/metaobjects/tests/scope_conformance.rs @@ -0,0 +1,40 @@ +//! The scope-pattern grammar against the shared `fixtures/scope-conformance/cases.json`: +//! every `(fqn, scope)` pair matches as in every other port. The dependency resolver reads +//! `migrate.scope` through this matcher. + +use std::path::PathBuf; + +use metaobjects::scope::{compile_scope, matches_scope}; +use serde_json::Value; + +fn patterns(scope: &Value, key: &str) -> Option> { + scope + .get(key) + .and_then(Value::as_array) + .map(|a| a.iter().map(|v| v.as_str().unwrap().to_string()).collect()) +} + +#[test] +fn every_scope_case_matches_as_in_every_port() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../../fixtures/scope-conformance/cases.json"); + let corpus: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + let cases = corpus["cases"].as_array().unwrap(); + assert!(!cases.is_empty(), "the corpus has no cases"); + let mut failures = Vec::new(); + for case in cases { + let name = case["name"].as_str().unwrap(); + let include = patterns(&case["scope"], "include"); + let exclude = patterns(&case["scope"], "exclude"); + let scope = compile_scope(include.as_deref(), exclude.as_deref()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + for e in case["expect"].as_array().unwrap() { + let fqn = e["fqn"].as_str().unwrap(); + let expected = e["matches"].as_bool().unwrap(); + if matches_scope(fqn, &scope) != expected { + failures.push(format!("{name}: {fqn} should match: {expected}")); + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} From 29676ce7eee7f432b42d388c96911ea3433c2c75 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 3 Dec 2026 04:58:26 -0500 Subject: [PATCH 2/3] no-mistakes(document): note Rust dependency resolution in docs --- docs/CONFORMANCE.md | 8 +++--- docs/features/metadata-dependencies.md | 34 ++++++++++------------- docs/features/metadata-sources.md | 16 +++++------ docs/ports/rust.md | 14 +++++----- fixtures/dependency-conformance/README.md | 3 +- fixtures/docs-page-conformance/README.md | 6 ++-- fixtures/scope-conformance/README.md | 2 ++ server/rust/metaobjects/src/config.rs | 4 ++- spec/roadmap.md | 5 ++-- 9 files changed, 46 insertions(+), 46 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 289d5c4f5c..110d024a3e 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -56,7 +56,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) (the static agent files each port's `agent-docs` writes; every port runs all 6 stacks, not only its own) | 6 | ✓ (reference) | ✓ (`metaobjects:agent-docs`) | inherits via Java (the same Maven goal) | ✓ (`dotnet meta agent-docs`) | ✓ | ✓ (`cargo meta agent-docs`) | | [`fixtures/agent-pages-pointer/`](../fixtures/agent-pages-pointer/) (the always-on agent file names the agent pages the last `gen` wrote, from the committed `.hashes/`) | 3 cases | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | ✓ | | [`fixtures/list-query-conformance/`](../fixtures/list-query-conformance/) (how a list route reads its query string: filter tree, search, sort, page, or the named 400) | 95 cases | ✓ (reference; the source of the expected answers) | planned (R-JV) | planned (R-KT) | ✓ (`ListQueryConformanceTests`) | planned (R-PY) | ✓ (`list_query_conformance.rs`, the parser `meta_http` ships) | -| [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirement pages and the model-only schema page, built from the docs view: each page's rows, data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | ✓ (`DocsPageConformanceTest`) | ✓ (through Java: the Kotlin generators call the JVM page builder) | ✓ | ✓ | ✓ (rows from the view; no requirement ledger, RS-V2) | +| [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirement pages and the model-only schema page, built from the docs view: each page's rows, data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | ✓ (`DocsPageConformanceTest`) | ✓ (through Java: the Kotlin generators call the JVM page builder) | ✓ | ✓ | ✓ (rows from the view; requirement ledger not applied yet, RS-V2) | | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) (the vocabulary reference pages: each page's data and bytes, shared `templates/metamodel/`) | 1 (23 pages) | ✓ (reference; the source of the expected bytes) | ✓ (`MetamodelDocsCorpusTest`) | ✓ (through Java's builder and emitter) | ✓ (`MetamodelDocsTests`) | ✓ (`test_metamodel_docs_conformance.py`) | ✓ (`tests/metamodel_docs.rs`) | | [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | — (no `fmt`) | | [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | — | @@ -423,7 +423,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, reference-source, naming, skip, validation, wire-vector, writer, generator-registry, render, verify, response-verify, extract, output-prompt, template-output-render, list-query, persistence and api-contract corpora, and the `verify --templates` CLI test; the codegen-compile and scale gates, which run `cargo check` on generated crates and drive the generated client over HTTP against a local stub) | — | — | +| Rust | `cd server/rust && cargo test` (registry, metamodel, YAML, source-resolution, reference-source, scope, dependency, naming, skip, validation, wire-vector, writer, generator-registry, render, verify, response-verify, extract, output-prompt, template-output-render, list-query, persistence and api-contract corpora, and the `verify --templates` CLI test; the codegen-compile and scale gates, which run `cargo check` on generated crates and drive the generated client over HTTP against a local stub) | — | — | The `persistence-conformance` corpus is intentionally **on-demand** — none of the unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. @@ -854,8 +854,8 @@ and what it leaves out. `server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java` (Kotlin's generators call the same JVM page builder), `server/python/tests/conformance/test_docs_page_conformance.py` and -`server/rust/metaobjects-codegen/tests/docs_page_conformance.rs`. Rust has no requirement ledger -of its own (RS-V2), so its pages list every requirement the view carries. +`server/rust/metaobjects-codegen/tests/docs_page_conformance.rs`. Rust's page generators do not +apply the requirement ledger yet (RS-V2), so its pages list every requirement the view carries. ### `fixtures/agent-pages-pointer/` (3 cases) diff --git a/docs/features/metadata-dependencies.md b/docs/features/metadata-dependencies.md index 47f2e46caf..46ddff9ed9 100644 --- a/docs/features/metadata-dependencies.md +++ b/docs/features/metadata-dependencies.md @@ -218,8 +218,8 @@ owned packages — with no resolution at all; it just reads ## Every dependency-aware port loads the committed snapshot, never the live path -Once synced, TypeScript's, Python's and Java's collection resolvers (Kotlin loads through -Java's; a Spring app's runtime loader reads the same snapshot off the classpath) load dependency artifacts from the committed +Once synced, TypeScript's, Python's, Java's, C#'s and Rust's collection resolvers (Kotlin loads +through Java's; a Spring app's runtime loader reads the same snapshot off the classpath) load dependency artifacts from the committed snapshot **first**, then your own project files, offline, with no transport involved. At load time it checks the snapshot against the lock and refuses (`ERR_DEPENDENCY_SNAPSHOT_STALE`) when they disagree — a missing lock for a declared @@ -356,7 +356,8 @@ So `scope.include` narrows a Python project's *own* codegen output not at all only ever widens which imported package is let back in. **Java and Kotlin follow Python** (`DependencySet.inScope`, read by `GeneratorUtil`'s selection points and `RestSurfaceGate`): the import-exclusion conjunct only, because those generators have never scoped the project's -own objects either. Do not read the TypeScript formula above as describing every port. +own objects either. **Rust follows Python too** (`Collection::in_scope`, read by `cargo meta`'s +project load). Do not read the TypeScript formula above as describing every port. `migrate`, `verify --db`, and offline generate compose the schema-side twin, which also removes an excluded import from the *expected* schema before drift is computed @@ -408,7 +409,8 @@ with its model: an overlay of one resolves, and `meta verify` can see it. By def stay the **publisher's** ledger, not yours. The requirement gate does not check, count, summarise or lint them, the `requirement-tests` generator writes no test for them, and the requirements pages (`requirementsFile()`'s `requirements.toon`, the agent docs' `agent/requirements.md`, an entity page's -"Required by") do not list them. +"Required by") do not list them. (Rust has no requirement gate or `requirement-tests` +generator yet, and its pages do not apply the ledger: [Rust port](../ports/rust.md).) That is the same default as an imported entity's code generation, for the same reason: you did not declare them. @@ -844,6 +846,8 @@ but **not** built yet — do not assume any of the following exists: ports' check resolves `path` only; any other dependency reports `unresolved` and names the Node `meta deps check`, because resolving it needs the consumer's installed packages or local package caches (a check that cannot check must not pass). +- **A Rust check.** The Rust port loads committed snapshots, but `cargo meta verify --deps` + exits 2; run the Node `meta deps check`. ## Verified by @@ -851,24 +855,14 @@ but **not** built yet — do not assume any of the following exists: cases. 36 pin resolution (including `npm`, `python`, `maven` and `nuget` dependencies loading from their committed snapshot with nothing installed), the exhaustive `imported`/`inScope`/`inMigrateScope` sets, overlay/extends/reference behavior against a synced snapshot, and every load- and - resolution-time error above, run by TypeScript (the reference implementation), - Python and Java (Kotlin loads through the Java loader and Maven plugin, so it inherits the - corpus run and adds a codegen test that an imported entity emits nothing). 11 pin the upstream - check (`current`, `drifted`, `unresolved`), run by TypeScript, Java (Kotlin through the same - `metaobjects:verify` goal), Python (`metaobjects deps check`, `verify --deps`) and C# - (`dotnet meta verify --deps`). + resolution-time error above. 11 pin the upstream check (`current`, `drifted`, `unresolved`). Four artifacts under `fixtures/dependency-conformance/artifacts/` are pinned by sha256 in the README so the corpus itself can never silently drift. - Python's runner asserts all 36 resolution cases identically to TypeScript's, with no - exemptions — the two overlay cases that need a view child as incidental content - use `view.currency` (the one concrete `view.*` subtype registered cross-port, - per `fixtures/registry-conformance/expected-registry.json`), not `view.text`, - so they exercise the full imported/selected/governed assertions like every - other case. Seven resolution cases also pin the ledger (`expectLedger`, `expectCoverageMeasured`): - which requirements are the project's own and whether coverage is measured, asserted in - TypeScript, Python, Java and C# through each port's requirement gate and through its - `requirement-tests` identities walk, and in TypeScript through the rows the requirements - pages list (only the TypeScript runner checks those rows). `transport-cases.json` beside it pins the `npm`, `python`, `maven` and `nuget` transports + Seven resolution cases also pin the ledger (`expectLedger`, `expectCoverageMeasured`): + which requirements are the project's own and whether coverage is measured. Which ports run + which arm, and how each asserts the ledger: + [`CONFORMANCE.md`](../CONFORMANCE.md#fixturesdependency-conformance-47-cases--32-transport-cases). + `transport-cases.json` beside it pins the `npm`, `python`, `maven` and `nuget` transports themselves (32 cases: packages laid out under a temp `node_modules`, on a temp Python import path, as a jar in a temp local Maven repository and as a package in a temp NuGet cache, the directory each resolves to, the exact lock `sync` writes, and diff --git a/docs/features/metadata-sources.md b/docs/features/metadata-sources.md index a53bf9e372..81528c7810 100644 --- a/docs/features/metadata-sources.md +++ b/docs/features/metadata-sources.md @@ -58,9 +58,9 @@ sources.** It answers a different question than the ladder above — not "where my metadata live" but "what does my metadata build on that lives elsewhere" — so a TypeScript project using a declared `sources` list and a Python project using its own `metadata:` key both get their declared dependencies resolved the same way, on -top of whichever rung supplied their own files. **TypeScript, Python, Java, Kotlin and C#** -(Kotlin through Java's loader and Maven plugin) — each reads `dependencies` at every rung -of its own source ladder. See +top of whichever rung supplied their own files. **TypeScript, Python, Java, Kotlin, C# and +Rust** (Kotlin through Java's loader and Maven plugin) — each reads `dependencies` at every +rung of its own source ladder. See [`metadata-dependencies.md`](metadata-dependencies.md). A config file that exists but is malformed is an error at its own rung; it never @@ -121,8 +121,8 @@ and a `.[attr]` predicate. Both are output filters over the same resolved file s they compete rather than layer. No cross-port behavior depends on `scope`; the TypeScript, C#, Python, Kotlin and Rust ports have no separate generator-filter glob (Kotlin runs through the same Maven plugin and so the same ``). (The pattern grammar itself is ported and -corpus-gated in Java, Kotlin and C# as a library, ahead of the cross-repo dependency work; -no command in those ports applies `scope` to its own generated output yet — the +corpus-gated in the other ports as a library ([`CONFORMANCE.md`](../CONFORMANCE.md)); no +command in those ports applies `scope` to its own generated output yet — the neutral-subset reads above (`scope.include`, `migrate.scope`) serve the dependency rules only.) @@ -800,9 +800,9 @@ Design rationale and the full phase plan: - [`fixtures/scope-conformance/`](../../fixtures/scope-conformance/) — 10 cases pinning `*` / `**`, include-union, exclude-after-include, literal metacharacters, - and case sensitivity. All five ports run it (Kotlin inherits Java's); only the Node CLI - applies `scope` to its own output — the other ports read `scope.include` and - `migrate.scope` for the dependency rules alone (see the neutral subset above). See + and case sensitivity. Only the Node CLI applies `scope` to its own output — the other + ports read `scope.include` and `migrate.scope` for the dependency rules alone (see the + neutral subset above). Which ports run the corpus: [`CONFORMANCE.md`](../CONFORMANCE.md). **TypeScript gates** diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 195f08e92c..4708849ed1 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -493,8 +493,8 @@ role) is written to the table and read back through the view, so the fields that `requirements` writes the requirement ledger as `requirements.toon`, for tools; `agent-docs` writes `agent/requirements.md` (the node index and the embedded ledger) and the model-only `agent/schema.md` (tables, views, relationships and enums, without the SQL types, defaults, indexes and checks only the -TypeScript migration engine knows; a reference node's table, view and relationships are left out, -as another run's to generate). Both read the docs view alone and render the shared +TypeScript migration engine knows; the table, view and relationships of a reference node, or of a +dependency's object that `scope.include` does not name, are left out, as not this run's to generate). Both read the docs view alone and render the shared `templates/requirements/` and `templates/agent/` Mustache pages, so the bytes are every port's (`fixtures/docs-page-conformance/`, run by `tests/docs_page_conformance.rs`). A same-path file under the project's `templates/` wins. No `requirement.*` node, no requirement page; no table and no view, @@ -502,10 +502,10 @@ no schema page. The schema page says to change the schema with `meta migrate` wh `.metaobjects/config.json` sets `migrate.dialect`. Nobody reads a human `requirements.md` any more: the explorer shows the ledger. `agent/ui.md` stays a TypeScript page. -What is absent here: this port has no requirement ledger of its own (no `requirements.inherit` -collection and no requirement gate in `cargo meta verify`, the RS-V2 work), so the pages list every -requirement the view carries, an imported package's included, where a port with the ledger lists -only those the collection counts. The always-on agent file comes from +What is absent here: there is no requirement gate in `cargo meta verify`, and these generators do +not yet apply the requirement ledger (`dependencies::requirement_ledger`), the RS-V2 work. So the +pages list every requirement the view carries, an imported package's included, where other ports +list only those the ledger counts. The always-on agent file comes from `cargo meta agent-docs` (no Node), which names these pages once a `gen` has written them. ### `docs-site`: the model explorer @@ -689,7 +689,7 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to fields stored as JSON), `projection`, `report`, `decimal`, `duration`, `api-settings` and `enum-default`. - **Other gates.** `verify --codegen`, `verify --templates` and the business-rules gate are the ones - it has. There is no requirement gate and no `fmt`. + it has. There is no requirement gate, no dependency check (`verify --deps`) and no `fmt`. - **A three-way merge.** A hand-edited generated file is refused by name, as in every port but TypeScript; change the model or own the generator instead. - **A metadata-driven runtime.** No `ObjectManager` and no web adapter over it: data access is the diff --git a/fixtures/dependency-conformance/README.md b/fixtures/dependency-conformance/README.md index 318d46e608..483609e19b 100644 --- a/fixtures/dependency-conformance/README.md +++ b/fixtures/dependency-conformance/README.md @@ -288,7 +288,8 @@ package are `ERR_DEPENDENCY_UNRESOLVED`; a `dir` that exists but holds no `metao Kotlin generators are covered by a codegen test that an imported entity emits nothing. - **The ledger arm** (`expectLedger`) runs in every port but Kotlin, which shares Java's gate: TypeScript `cli/test/dependency-ledger-conformance.test.ts` (the gate lives in the CLI - package), Python, Java and C# in the same runners named below. + package), Python, Java, C# and Rust in their resolution runners (Rust through the ledger's + scan only, see below). - **C#** — the resolution arm: resolution, load-time failure, lock/snapshot integrity, on the neutral source ladder and again through the explicit metadata directory (C# has no native config surface, so `.metaobjects/config.json` is where a dependency is declared at every diff --git a/fixtures/docs-page-conformance/README.md b/fixtures/docs-page-conformance/README.md index 920417a69b..3b79cb973e 100644 --- a/fixtures/docs-page-conformance/README.md +++ b/fixtures/docs-page-conformance/README.md @@ -88,9 +88,9 @@ them), foreign-key constraint names and referential actions. Only the TypeScript written from the expected schema, carries those; `agent/ui.md` stays a TypeScript page. It also leaves out what is not the project's own storage: a dependency's object that -`scope.include` does not name (in Rust, which loads no dependency, a reference node) gives the -page no table, view, relationship or enum, in the physical TypeScript page too. These cases load -no dependency; each port's dependency-import test holds that rule. +`scope.include` does not name gives the page no table, view, relationship or enum, in the +physical TypeScript page too. These cases load no dependency; each port's dependency-import +test holds that rule. One project setting reaches the page: `hasMigrate` is true when the project's `.metaobjects/config.json` sets `migrate.dialect` (it chose `meta migrate`, the reference diff --git a/fixtures/scope-conformance/README.md b/fixtures/scope-conformance/README.md index a1b8c19fe1..94d7339268 100644 --- a/fixtures/scope-conformance/README.md +++ b/fixtures/scope-conformance/README.md @@ -70,6 +70,8 @@ segment matcher) as long as every case in this file passes. - C#: `server/csharp/MetaObjects.Conformance.Tests/ScopeConformanceTests.cs` (against `MetaObjects.Config.Scope`, anchored with `\A…\z` because .NET's `$` also matches before a trailing newline). +- Rust: `server/rust/metaobjects/tests/scope_conformance.rs` (against `metaobjects::scope`, + which matches segment by segment; its unit tests pin the invalid-pattern cases). - Kotlin inherits the Java loader and has no runner of its own. The corpus asserts matches only. Each runner pins the invalid-pattern cases diff --git a/server/rust/metaobjects/src/config.rs b/server/rust/metaobjects/src/config.rs index a86bd1b580..bbfe1875c9 100644 --- a/server/rust/metaobjects/src/config.rs +++ b/server/rust/metaobjects/src/config.rs @@ -256,7 +256,9 @@ pub struct MigrateConfig { pub foreign_key_targets: Option, } -/// One declared metadata dependency (FR-023). Parsed and validated only. +/// One declared metadata dependency (FR-023), as the config names it. This reader only parses +/// and validates it; `crate::dependencies` verifies its committed snapshot. The transport is +/// never resolved here: Node `meta deps sync` does that. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DependencySpec { pub name: String, diff --git a/spec/roadmap.md b/spec/roadmap.md index a3e38d64b6..a72d184bce 100644 --- a/spec/roadmap.md +++ b/spec/roadmap.md @@ -415,7 +415,8 @@ _(FR-032 was developed under the working number "FR-026" — see commit history; snapshot + `.metaobjects/deps.lock.json`, and TypeScript's and Python's collection resolvers — the two ports that consume dependencies in Phase 1a — load the snapshot at every rung of their own source ladder (Java and Kotlin followed in - Phase 2 slice S3; C# in slice S6). Imported metadata is load-only by default — + Phase 2 slice S3; C# in slice S6; Rust's loader since, without the upstream check + yet). Imported metadata is load-only by default — excluded from codegen, schema, and the requirements ledger unless the consumer's own `scope.include` / `migrate.scope` names the package — with a loud refusal (`ERR_DEPENDENCY_PACKAGE_NOT_OWNED`) rather than a silent drop when a consumer @@ -428,7 +429,7 @@ _(FR-032 was developed under the working number "FR-026" — see commit history; codegen imports), a runtime `ObjectManager` scope predicate, and Java/Kotlin/C# as consumers or publishers (Phase 2). Design: `docs/superpowers/specs/2026-09-11-fr-023-metadata-dependencies-design.md` (supersedes the 2026-06-11 sketch). Docs: `docs/features/metadata-dependencies.md`. - Corpus: `fixtures/dependency-conformance/` (23 cases, TS + Python). + Corpus: `fixtures/dependency-conformance/` (per-port arms: `docs/CONFORMANCE.md`). - **FR-026 — Forms completeness: edit forms, view-render parity, validator wiring (TS web client).** Builds on what ships today — create forms (`@emitForm` → `formFile` → `useEntityForm` + Zod `InsertSchema`), field display via `view.*` cell renderers (~10 of 13 subtypes), and client form rules (`required`/`length`/`regex`). **Edit forms shipped in `0.19.2` (#227)** — the generated `Form` switches its resolver from `InsertSchema` to `UpdateSchema` when `defaultValues` are present, so the one form is both create and edit (previously it validated every submit against `InsertSchema`, whose optionals reject `null`, which blocked editing any row holding a NULL optional column). **View-kind form-control dispatch shipped in `0.18.0`** (enum→`