diff --git a/changelog.d/rust-dependency-resolution.md b/changelog.d/rust-dependency-resolution.md index 8e67cfc5e..a5a07db4a 100644 --- a/changelog.d/rust-dependency-resolution.md +++ b/changelog.d/rust-dependency-resolution.md @@ -12,8 +12,7 @@ `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 + `fixtures/scope-conformance/` cases. 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 diff --git a/changelog.d/rust-verify-deps.md b/changelog.d/rust-verify-deps.md new file mode 100644 index 000000000..98f019b51 --- /dev/null +++ b/changelog.d/rust-verify-deps.md @@ -0,0 +1,13 @@ +- **`cargo meta verify --deps` checks the declared dependencies** (FR-023), as `meta deps check`, + `metaobjects verify --deps`, `dotnet meta verify --deps` and the Java and Kotlin + `-Dmeta.verify.mode=deps` do. For each declared dependency it reads the publisher's + `metaobjects.pkg.json`, hashes the artifact beside it and compares it with + `.metaobjects/deps.lock.json`: `current`, `drifted`, or `unresolved` when it cannot compare (a + missing path, a bad manifest, an artifact the manifest does not describe, no lock entry). A + `drifted` or `unresolved` dependency exits 1 with `ERR_DEPENDENCY_UPSTREAM_DRIFT`; an unreadable + config or lock, or a `--project` that is not a project, exits 2. It is opt-in, never part of a + bare `verify`, and resolves the `path` transport only, reporting any other dependency + `unresolved` and naming the Node `meta deps check`. Before, `--deps` exited 2. + Rust now runs the check arm of `fixtures/dependency-conformance/` (all 11 cases), through the new + `metaobjects::dependency_check` module; `metaobjects::dependencies` gains `validate_manifest` and + `MANIFEST_FILE`. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 110d024a3..8e70a0233 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -51,7 +51,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`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 | ✓ | ✓ | ✓ (`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/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, all 11, as `verify --deps`) | | [`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 | ✓ | ✓ | ✓ | @@ -701,8 +701,9 @@ no per-port fixture. The corpus has four arms: by TypeScript, in `cli/test/dependency-check-conformance.test.ts`, by Java in `DependencyCheckConformanceTest` (the engine behind `metaobjects:verify -Dmeta.verify.mode=deps`; Kotlin runs the same goal), by **Python**, in `tests/conformance/test_dependency_conformance.py` - (`metaobjects deps check` and `verify --deps`), and by **C#**, in `DependencyConformanceTests` - (`dotnet meta verify --deps`). The arm exists so that each port's check is written against the + (`metaobjects deps check` and `verify --deps`), by **C#**, in `DependencyConformanceTests` + (`dotnet meta verify --deps`), and by **Rust**, in `tests/dependency_conformance.rs` + (`cargo meta verify --deps`). The arm exists so that each port's check is written against the same edge cases (FR-023 Phase 2, #482, shipped). - **Transport (32 cases, `transport-cases.json`).** The `npm`, `python`, `maven` and `nuget` transports `meta deps sync` uses to find an installed package: npm packages under a temp `node_modules`, Python diff --git a/docs/features/cli.md b/docs/features/cli.md index 8258c73af..29b2890dc 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -43,7 +43,7 @@ command surface splits in two: | Java/Kotlin scaffold | Maven plugin | `mvn metaobjects:init` | writes the port-neutral `.metaobjects/config.json` and an empty `metaobjects/meta.app.json`, each only when missing; it never edits `pom.xml` and wires no generator. Details and the `-Dmeta.init.withDocs=true` opt-in: [docs/ports/java.md](../ports/java.md) | | Java/Kotlin verify | Maven plugin | `mvn metaobjects:verify -Dmeta.verify.mode=codegen\|templates\|deps` (`metaobjects:verify`) | parameter-driven ADR-0021 D2 modes (one goal covers BOTH Java + Kotlin): unset (default — `codegen` and `templates`; the template gate is skipped with a note when `templateRoot` is unset) / `codegen` (regen + fail on drift vs committed output, generator-neutral) / `templates` (`{{field}}`↔payload drift via the render `Verify` engine) / `deps` (opt-in dependency drift, the `path` transport only). `db` rejected ("schema verify is the migrate engine, ADR-0015") | | Python codegen | console-script | `metaobjects gen` / `verify --codegen` / `verify --templates` | `[project.scripts] metaobjects` — **not** `meta` (that's the Node schema CLI); ships the ADR-0021 D2 subverbs (`--db` rejected, exit 2). **The generator list is `metaobjects.config.yaml`** (ADR-0034 Amendment 9, [below](#declarative-config-metaobjectsconfigyaml--python-codegen)): `gen` and `verify --codegen` run each target's `generators` (and its `templateSpec`, the declarative Mustache template-codegen surface shared with C#) into its `outDir`, and with no config they exit 2 and write nothing. `--generators` only narrows the list to declared entries. `metaobjects docs` was removed in 1.1.0: it prints the line that points at [the migration section](migrations/docs-are-generators.md#python) and exits 2 | -| Rust codegen (ADR-0065) | `cargo-meta` (`metaobjects-cli`, published to crates.io with the other Rust crates on the shared release line, [Releasing](../RELEASING.md); also installable from a checkout) | `cargo meta init [--transport]` / `gen` / `verify --codegen` / `verify --templates` / `eject` | A Cargo subcommand, invoked `cargo meta` so it never shadows the Node `meta`. Eleven generators ship, each writing one crate per metadata package: the six ADR-0067 layers (`entity`, `rules-names`, `contract-types`, `repository`, `service`, and the opt-in axum transport `service-routes`, which `init --transport` lists), `client` and `commands` (the last Rust-only by decision, ADR-0065 Amendment 1), and the three prompt-tier generators. The project chooses which run in `metaobjects.config.json`. `gen` skips a run whose key matches (ADR-0064), writes only changed bytes, removes a generated file nothing emits any more, and refuses to overwrite or delete a hand-edited generated file (exit 1). `verify` ships the ADR-0021 D2 subverbs it can: a bare `verify` runs the gates (`--codegen`, which renders in memory and exits 1 on drift, `--templates` and the rules gate) (`--full`, or a set `CI`, never answers from the stored key); `--templates` is the template drift gate (`template.*` bodies under `prompts/`, or `--prompts `, against their payload value objects, plus each prompt's reply), and a bare `verify` runs it too; `--db` and `--deps` are rejected, exit 2. **To own a generator**, `cargo meta eject ` writes a `codegen/` crate (`Cargo.toml`, `main.rs`, `generators/.rs`), and `gen` / `verify` then build and run that crate; `--generators` only narrows the list. No `fmt`, no template generator and no `migrate`. `cargo meta --help` lists the options; [the Rust port page](../ports/rust.md) has the detail | +| Rust codegen (ADR-0065) | `cargo-meta` (`metaobjects-cli`, published to crates.io with the other Rust crates on the shared release line, [Releasing](../RELEASING.md); also installable from a checkout) | `cargo meta init [--transport]` / `gen` / `verify --codegen` / `verify --templates` / `verify --deps` / `eject` | A Cargo subcommand, invoked `cargo meta` so it never shadows the Node `meta`. Eleven generators ship, each writing one crate per metadata package: the six ADR-0067 layers (`entity`, `rules-names`, `contract-types`, `repository`, `service`, and the opt-in axum transport `service-routes`, which `init --transport` lists), `client` and `commands` (the last Rust-only by decision, ADR-0065 Amendment 1), and the three prompt-tier generators. The project chooses which run in `metaobjects.config.json`. `gen` skips a run whose key matches (ADR-0064), writes only changed bytes, removes a generated file nothing emits any more, and refuses to overwrite or delete a hand-edited generated file (exit 1). `verify` ships the ADR-0021 D2 subverbs it can: a bare `verify` runs the gates (`--codegen`, which renders in memory and exits 1 on drift, `--templates` and the rules gate) (`--full`, or a set `CI`, never answers from the stored key); `--templates` is the template drift gate (`template.*` bodies under `prompts/`, or `--prompts `, against their payload value objects, plus each prompt's reply), and a bare `verify` runs it too; `--deps` is the opt-in dependency drift check (`path` transport only); `--db` is rejected, exit 2. **To own a generator**, `cargo meta eject ` writes a `codegen/` crate (`Cargo.toml`, `main.rs`, `generators/.rs`), and `gen` / `verify` then build and run that crate; `--generators` only narrows the list. No `fmt`, no template generator and no `migrate`. `cargo meta --help` lists the options; [the Rust port page](../ports/rust.md) has the detail | ## `verify` is one verb with explicit subverbs (ADR-0021 D2) @@ -60,7 +60,7 @@ vocabulary everywhere, each port implementing the modes it supports. | `verify --codegen` | **Codegen drift** — regenerate from metadata in memory and fail if it differs from the committed generated output. Catches "metadata changed but `meta gen` wasn't re-run". **A hand-edited generated file** (Node `meta`): `meta gen` three-way-merges hand edits, so the gate compares the *generated contribution* against the committed `.gen-state/.hashes/` and reports each edited file separately, by path, with how to see the edit and how to drop it. What that report does to the exit code is the `verify.handEdits` key in `.metaobjects/config.json`: `"fail"` exits 1, `"notice"` (and a project without the key, as before 1.3) prints it and exits 0. `meta init` writes `"fail"` for a new project. `--allow-hand-edits` relaxes `fail` to a notice for one run; `--forbid-hand-edits` makes a hand edit fail for one run whatever the key says. The other ports compare the generated files byte for byte, so any edit is drift and fails: `dotnet meta verify --codegen`, `mvn metaobjects:verify` (Java and Kotlin) and `metaobjects verify --codegen` each exit non-zero and name the file. | no | | `verify --templates` | **Template/prompt drift** — `Renderer.verify` checks each `template.*` node's `{{field}}` references against its payload VO (FR-004). A Jinja body (Python and TypeScript, ADR-0061) is checked the same way. | no | | `verify --docs` | **Removed in 1.1.0** (ADR-0034 Amendment 9). It prints where the check went and exits 2: documentation is written by entries in `generators`, so `verify --codegen` checks it with the rest of the declared output. | — | -| `verify --deps` | **Dependency drift** (FR-023) — re-resolves each declared dependency (its `path`, its installed `npm` / `python` package, or its `maven` / `nuget` package in the local cache) and compares its installed artifact's hash against `.metaobjects/deps.lock.json`, same comparison as `meta deps check`. Needs the publisher reachable, so it is never part of the bare-`verify` default. A `drifted` or `unresolved` dependency fails with `ERR_DEPENDENCY_UPSTREAM_DRIFT`. **Node `meta`; Python (`metaobjects verify --deps`, plus `metaobjects deps check`), C# (`dotnet meta verify --deps`), and Java and Kotlin (`-Dmeta.verify.mode=deps`) have the `path`-only counterpart.** See [`metadata-dependencies.md`](metadata-dependencies.md). | no | +| `verify --deps` | **Dependency drift** (FR-023) — re-resolves each declared dependency (its `path`, its installed `npm` / `python` package, or its `maven` / `nuget` package in the local cache) and compares its installed artifact's hash against `.metaobjects/deps.lock.json`, same comparison as `meta deps check`. Needs the publisher reachable, so it is never part of the bare-`verify` default. A `drifted` or `unresolved` dependency fails with `ERR_DEPENDENCY_UPSTREAM_DRIFT`. **Node `meta`; Python (`metaobjects verify --deps`, plus `metaobjects deps check`), C# (`dotnet meta verify --deps`), Java and Kotlin (`-Dmeta.verify.mode=deps`), and Rust (`cargo meta verify --deps`) have the `path`-only counterpart.** See [`metadata-dependencies.md`](metadata-dependencies.md). | no | Rules of the contract: @@ -253,7 +253,8 @@ and template gates: bare `cargo meta verify` renders the generated crates in mem them (a local run may answer from the stored skip key; `--full`, or a set `CI`, always renders), checks every `template.*` body under `prompts/` (or `--prompts `) against its payload value object plus each prompt's `@responseRef` reply, and runs the business-rules gate; `--codegen` and -`--templates` run one gate alone, and the port has no requirement gate ([the Rust port +`--templates` run one gate alone, `--deps` runs the opt-in dependency drift check (`path` +transport only), and the port has no requirement gate ([the Rust port page](../ports/rust.md)). ## Owned generators: the unchanged-copy notice, `eject --undo`, and `gen --strict` diff --git a/docs/features/metadata-dependencies.md b/docs/features/metadata-dependencies.md index 46ddff9ed..1ac877bc9 100644 --- a/docs/features/metadata-dependencies.md +++ b/docs/features/metadata-dependencies.md @@ -474,11 +474,12 @@ classifies those as breaking automatically — see [Deferred](#deferred). ## What fails at `meta deps check` / `verify --deps` The check ships in TypeScript (`meta deps check`, `meta verify --deps`), Python (`metaobjects deps -check`, `metaobjects verify --deps`) and C# (`dotnet meta verify --deps`), against the same corpus -and with the same three states and the same `ERR_DEPENDENCY_UPSTREAM_DRIFT`. The Python and C# -check resolve the `path` transport only (see [Deferred](#deferred)). Python's `deps check`, like +check`, `metaobjects verify --deps`), C# (`dotnet meta verify --deps`) and Rust (`cargo meta +verify --deps`), against the same corpus and with the same three states and the same +`ERR_DEPENDENCY_UPSTREAM_DRIFT`. The Python, C# and Rust checks resolve the `path` transport only +(see [Deferred](#deferred)). Python's `deps check`, like TypeScript's, also loads the locked snapshots together once the hashes match; `verify --deps` is -the comparison alone in all three. Run `verify --deps` before `verify`'s own load: C# runs it +the comparison alone in every port. Run `verify --deps` before `verify`'s own load: C# runs it first, so a dependency that is declared but not yet synced is reported as `unresolved` (the check exits 1). The load that follows still refuses the missing or stale snapshot with `ERR_DEPENDENCY_SNAPSHOT_STALE` and exit 2. @@ -842,12 +843,10 @@ but **not** built yet — do not assume any of the following exists: - **A JVM classpath read with `"commit": false`** — a Java or Kotlin build reading a dependency's artifact straight off the classpath with no committed snapshot. The committed snapshot is the only shipped path. -- **`npm`, `python`, `maven` and `nuget` transports in the Python, Java and C# check.** Those +- **`npm`, `python`, `maven` and `nuget` transports in the Python, Java, C# and Rust check.** Those 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 diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 4708849ed..fa3bb1434 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -59,7 +59,7 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log |---|---| | `cargo meta init [--project ] [--transport]` | Scaffolds `.metaobjects/config.json`, `.metaobjects/.gitignore` (which keeps `.gen-state/.hashes/` committed), a first `metaobjects/meta.app.yaml` and `metaobjects.config.json`, the list of generators to run (see [Choosing generators](#choosing-generators)). `--transport` adds the opt-in `service-routes` generator to that list. It writes only what is missing, and never adds an empty metadata file to a project that already has metadata. | | `cargo meta gen [ENTITY...]` | Generates the crates. It skips the whole run when the model, the project config and the generators are unchanged ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)), writes only files whose bytes changed, removes a generated file nothing emits any more, and refuses to overwrite or delete a generated file that was edited by hand. It prints what it created, updated and removed, and the crates to re-check. | -| `cargo meta verify [--codegen] [--templates] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. `--codegen` runs that gate alone. `--templates` is the template drift gate: each `template.*` body (under `prompts/`, or `--prompts `) against its payload value object, and each prompt's `@responseRef` reply; a bare `verify` runs it too, and a Jinja body is refused (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`). A bare `verify` also runs the business-rules gate ([ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)) on the loaded model, and prints nothing about it when the model declares no operation and no transition; an error-severity finding (a `rules.permissions.names` of `require`, or `verify.lifecycle.unreachable` of `error`) exits 1. `--db` and `--deps` exit 2 with the reason and where that check lives. | +| `cargo meta verify [--codegen] [--templates] [--deps] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. `--codegen` runs that gate alone. `--templates` is the template drift gate: each `template.*` body (under `prompts/`, or `--prompts `) against its payload value object, and each prompt's `@responseRef` reply; a bare `verify` runs it too, and a Jinja body is refused (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`). A bare `verify` also runs the business-rules gate ([ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)) on the loaded model, and prints nothing about it when the model declares no operation and no transition; an error-severity finding (a `rules.permissions.names` of `require`, or `verify.lifecycle.unreachable` of `error`) exits 1. `--deps` is the dependency check (FR-023), opt-in and never part of a bare `verify`: each declared dependency's publisher artifact (its `metaobjects.pkg.json` and the artifact beside it) is hashed and compared with `.metaobjects/deps.lock.json`, and a `drifted` or `unresolved` one exits 1 with `ERR_DEPENDENCY_UPSTREAM_DRIFT` (an unreadable config or lock, or a `--project` that is not a project, exits 2); it resolves the `path` transport only, and reports any other dependency `unresolved`, naming the Node `meta deps check`. `--db` exits 2 with the reason and where that check lives. | | `cargo meta eject ...` | Copies a shipped generator into the project to own. An existing copy is refused; `--force` replaces it with the reference, and leaves a copy that already matches untouched. `--undo` takes back copies still identical to the shipped source; `--list` shows what can be ejected and how each owned copy compares. See [Owning a generator](#owning-a-generator). | | `cargo meta agent-docs [--server ]... [--client ]... [--out ] [--no-wire-root]` | Writes the static agent files, `.metaobjects/AGENTS.md`, the `metaobjects-*` skills under `.claude/skills/` and the `.metaobjects/.agent-context.json` manifest, byte for byte what every other port's `agent-docs` writes (`fixtures/agent-context-conformance/`), with no Node: the files are embedded in the crate. With no `--server` and no `--client` it reuses the stack the last run recorded, else `rust`. A re-run writes nothing for an unchanged file and puts fresh text beside a hand-edited one as `.new`; it also adds the `@.metaobjects/AGENTS.md` import to the root `AGENTS.md` / `CLAUDE.md` unless `--no-wire-root`. An unknown stack exits 2. | @@ -621,7 +621,7 @@ 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` | +| `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, all 11 cases, through `dependency_check::check_dependencies`, the engine behind `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. | @@ -688,8 +688,8 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to `secret-fields/tph` (single-table inheritance), `m2m` (many-to-many traversal), `jsonb` (object 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, no dependency check (`verify --deps`) and no `fmt`. +- **Other gates.** `verify --codegen`, `verify --templates`, `verify --deps` and the business-rules gate + are the ones it has. There is no requirement gate and no `fmt`. - **A three-way merge.** A hand-edited generated file is refused by name, as in every port but TypeScript; change the model or own the generator instead. - **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 483609e19..a69890142 100644 --- a/fixtures/dependency-conformance/README.md +++ b/fixtures/dependency-conformance/README.md @@ -301,8 +301,9 @@ package are `ERR_DEPENDENCY_UNRESOLVED`; a `dir` that exists but holds no `metao 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. + through a requirement-tests walk. Also the check arm, all 11 cases, through + `dependency_check::check_dependencies` (`cargo meta verify --deps`, `path` transport only). + Not the transport arm: Rust never syncs. ## Reference implementation diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index dd0e0e707..80e153eb1 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -18,7 +18,14 @@ use std::io::Write; use std::path::{Path, PathBuf}; use metaobjects::collection::discover_collection_root; +use metaobjects::config::load_config; +use metaobjects::dependencies::read_lock; +use metaobjects::dependency_check::{ + CheckStatus, check_dependencies, format_check_line, summary_line, +}; +use metaobjects::naming::NamingRegistry; use metaobjects::rules_check::Severity; +use metaobjects::sources::{CONFIG_FILE, DEFAULT_METADATA_DIR, DEFAULT_METAOBJECTS_DIR}; use metaobjects::timing::{LoadTimings, ms, render_table}; use metaobjects_codegen::eject::{self, CopyState, EjectError, EngineSource}; use metaobjects_codegen::engine::{ @@ -40,7 +47,7 @@ cargo meta: MetaObjects for Rust USAGE: cargo meta init [--project ] [--transport] cargo meta gen [OPTIONS] [ENTITY...] - cargo meta verify [--codegen] [--templates] [--full] [OPTIONS] + cargo meta verify [--codegen] [--templates] [--deps] [--full] [OPTIONS] cargo meta eject ... [--force] [--engine ] cargo meta eject --undo [...] [--force] cargo meta eject --list @@ -57,7 +64,8 @@ COMMANDS: to overwrite or delete a generated file that was edited by hand. verify Check that the generated crates are what `gen` would write, in memory and without writing anything, that every template body matches the payload it - renders over, and the business rules. Exits 1 on drift. + renders over, and the business rules. Exits 1 on drift. --deps checks + the declared dependencies against the lock. eject Copy a shipped generator into codegen/generators/ to own and change. --undo takes back copies that are still identical to the shipped generator. The owned crate builds against this release of the engine from crates.io; @@ -92,7 +100,15 @@ OPTIONS (verify): --templates The template gate only: each template.* body against its payload value object (unknown variables, unresolved partials, missing required tags and slots) and each prompt's reply (@responseRef). - A bare `verify` runs every gate; naming one or both runs only those. + --deps The dependency check (FR-023): each declared dependency's + publisher artifact (metaobjects.pkg.json and the artifact beside it) + hashed and compared with .metaobjects/deps.lock.json. Exits 1 when + one drifted or cannot be compared, 2 when the config or lock cannot + be read or --project is not a project. Only the `path` transport is + resolved here; `meta deps check` (Node) resolves the package + transports. + A bare `verify` runs every gate but --deps; naming gates runs only + those. --prompts Where template bodies live, relative to the project root. Default: prompts --full Render and compare even when a local run could answer from the @@ -614,18 +630,17 @@ fn cmd_verify( "`{TOOL} verify --db` does not exist: checking a schema against a live database is the reference migration helper's (`meta migrate`, `meta verify --db`), one option; a native tool is equally good (ADR-0015 Amendment 2)." ))); } - if s.has("--deps") { - return Err(Usage(format!( - "`{TOOL} verify --deps` does not exist: the Rust loader resolves committed dependency snapshots, but the sync and the upstream drift check run only in the Node `meta` command (`meta deps sync`, `meta deps check`)." - ))); - } let mut options = run_options(&s, cwd, generators)?; options.force = s.has("--full") || ci_forces_render(std::env::var_os("CI")); - // Naming a gate runs only the named ones; a bare `verify` runs them all. - let named = s.has("--codegen") || s.has("--templates"); + // Naming a gate runs only the named ones; a bare `verify` runs them all but the + // dependency check, which is opt-in (it reads the publishers' directories). + let named = s.has("--codegen") || s.has("--templates") || s.has("--deps"); let mut code = 0; + if s.has("--deps") { + code = verify_deps(&project_root(&s, cwd), out, err); + } if s.has("--codegen") || !named { - code = verify_codegen(&s, &options, generators, out, err); + code = code.max(verify_codegen(&s, &options, generators, out, err)); } if s.has("--templates") || !named { let prompts = s.value("--prompts").map(PathBuf::from); @@ -640,6 +655,77 @@ fn cmd_verify( Ok(code) } +/// The dependency check (FR-023): each declared dependency's publisher artifact against +/// the lock. 0 when every one is current, 1 when any drifted or could not be compared +/// (`ERR_DEPENDENCY_UPSTREAM_DRIFT`), 2 when the config or the lock cannot be read or `root` +/// is not a project. +fn verify_deps(root: &Path, out: &mut dyn Write, err: &mut dyn Write) -> i32 { + const COMMAND: &str = "verify --deps"; + let meta_root = root.join(DEFAULT_METAOBJECTS_DIR); + let specs = if meta_root.join(CONFIG_FILE).is_file() { + match load_config(&meta_root, &NamingRegistry::builtin()) { + Ok(loaded) => { + // A misspelled key (`dependancies`) is a warning, not an error: show it, or + // the check would pass on a declaration it never read. + print_warnings(err, &loaded.warnings); + loaded.config.dependencies + } + Err(e) => { + let _ = writeln!(err, "{COMMAND}: {e}"); + return 2; + } + } + } else if root.join(DEFAULT_METADATA_DIR).is_dir() { + // A project with no config, on the default sources: it declares nothing. + Vec::new() + } else { + // Not a project at all (a mistyped `--project`, or the metadata directory named in + // place of the root): a check that found nothing to read must not pass. + let _ = writeln!( + err, + "{COMMAND}: {} is not a MetaObjects project: it has no {DEFAULT_METAOBJECTS_DIR}/{CONFIG_FILE} and no {DEFAULT_METADATA_DIR} directory. --project names the project root.", + root.display() + ); + return 2; + }; + if specs.is_empty() { + let _ = writeln!( + out, + "{COMMAND}: no dependencies declared — nothing to check." + ); + return 0; + } + let lock = match read_lock(root) { + Ok(lock) => lock, + Err(e) => { + let _ = writeln!(err, "{COMMAND}: {e}"); + return 2; + } + }; + let results = check_dependencies(root, &specs, lock.as_ref()); + let failing = results + .iter() + .filter(|r| r.status != CheckStatus::Current) + .count(); + for r in &results { + let line = format_check_line(r); + if r.status == CheckStatus::Current { + let _ = writeln!(out, "{line}"); + } else { + let _ = writeln!(err, "{line}"); + } + } + if failing > 0 { + let _ = writeln!(err, "{}", summary_line(COMMAND, failing, results.len())); + return 1; + } + let _ = writeln!( + out, + "{COMMAND}: every dependency's installed artifact matches the lock." + ); + 0 +} + /// The template gate: load the project and check every template body and reply. fn verify_templates( options: &RunOptions, @@ -1131,11 +1217,105 @@ mod tests { } #[test] - fn the_gates_this_port_does_not_ship_say_where_they_live() { + fn the_gate_this_port_does_not_ship_says_where_it_lives() { let (code, _, err) = run_cli(&["meta", "verify", "--db"]); assert_eq!(code, 2); assert!(err.contains("meta verify --db"), "{err}"); - assert_eq!(run_cli(&["meta", "verify", "--deps"]).0, 2); + } + + /// `verify --deps` over a project with one `path` dependency: 0 when current, 1 when + /// the publisher's artifact moved, 2 when the lock is unreadable, 0 with none declared. + #[test] + fn verify_deps_reports_drift_and_exits_by_it() { + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir) + .join(format!("mo-cli-verify-deps-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let write = |rel: &str, text: &str| { + let p = base.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, text).unwrap(); + }; + let artifact = r#"{"metadata.root":{"package":"acme::common","children":[]}}"#; + let integrity = metaobjects::dependencies::sha256_integrity(artifact.as_bytes()); + write("acme/metaobjects/acme.metaobjects.json", artifact); + write( + "acme/metaobjects/metaobjects.pkg.json", + &format!( + r#"{{"schema_version":1,"name":"acme","version":"1.0.0","metamodelVersion":"1.0","artifact":"acme.metaobjects.json","integrity":"{integrity}","packages":["acme::common"],"nodes":[]}}"# + ), + ); + write( + "app/.metaobjects/config.json", + r#"{"schema_version":1,"dependencies":[{"name":"acme","path":"../acme/metaobjects"}]}"#, + ); + let lock = format!( + r#"{{"schema_version":1,"dependencies":{{"acme":{{"version":"1.0.0","metamodelVersion":"1.0","resolvedFrom":{{"path":"../acme/metaobjects"}},"artifact":"acme.metaobjects.json","integrity":"{integrity}","packages":["acme::common"],"nodes":[]}}}}}}"# + ); + write("app/.metaobjects/deps.lock.json", &lock); + let project = base.join("app"); + let verify = || { + run_cli(&[ + "meta", + "verify", + "--deps", + "--project", + project.to_str().unwrap(), + ]) + }; + + let (code, out, err) = verify(); + assert_eq!(code, 0, "{out}{err}"); + assert!(out.contains("acme: current"), "{out}"); + + // The publisher re-published: the manifest still describes its artifact, but the + // lock records the old bytes. + let moved = r#"{"metadata.root":{"package":"acme::common","children":[ ]}}"#; + let moved_integrity = metaobjects::dependencies::sha256_integrity(moved.as_bytes()); + write("acme/metaobjects/acme.metaobjects.json", moved); + write( + "acme/metaobjects/metaobjects.pkg.json", + &format!( + r#"{{"schema_version":1,"name":"acme","version":"1.1.0","metamodelVersion":"1.0","artifact":"acme.metaobjects.json","integrity":"{moved_integrity}","packages":["acme::common"],"nodes":[]}}"# + ), + ); + let (code, _, err) = verify(); + assert_eq!(code, 1, "{err}"); + assert!(err.contains("acme: drifted"), "{err}"); + assert!(err.contains("ERR_DEPENDENCY_UPSTREAM_DRIFT"), "{err}"); + + write("app/.metaobjects/deps.lock.json", "not json"); + let (code, _, err) = verify(); + assert_eq!(code, 2, "{err}"); + assert!(err.contains("ERR_DEPENDENCY_SNAPSHOT_STALE"), "{err}"); + + // A misspelled key is reported, not silently read as "no dependencies". + write( + "app/.metaobjects/config.json", + r#"{"schema_version":1,"dependancies":[]}"#, + ); + let (code, out, err) = verify(); + assert_eq!(code, 0, "{err}"); + assert!(out.contains("no dependencies declared"), "{out}"); + assert!( + err.contains("dependancies"), + "the unknown key is named: {err}" + ); + + // A path that is not a project fails instead of passing on nothing. + for wrong in [base.join("app-typo"), base.join("acme/metaobjects")] { + let (code, _, err) = run_cli(&[ + "meta", + "verify", + "--deps", + "--project", + wrong.to_str().unwrap(), + ]); + assert_eq!(code, 2, "{}: {err}", wrong.display()); + assert!(err.contains("is not a MetaObjects project"), "{err}"); + } + let _ = std::fs::remove_dir_all(&base); } #[test] diff --git a/server/rust/metaobjects/src/config.rs b/server/rust/metaobjects/src/config.rs index bbfe1875c..1d7545f01 100644 --- a/server/rust/metaobjects/src/config.rs +++ b/server/rust/metaobjects/src/config.rs @@ -629,7 +629,8 @@ fn parse_source_spec( spec } -fn dependency_name_ok(name: &str) -> bool { +/// `^[a-z0-9][a-z0-9._-]*$`: a dependency's name, in the config, a manifest and a lock. +pub(crate) fn dependency_name_ok(name: &str) -> bool { let mut chars = name.chars(); chars .next() diff --git a/server/rust/metaobjects/src/dependencies.rs b/server/rust/metaobjects/src/dependencies.rs index 7b24a65f5..bbf8d2d7c 100644 --- a/server/rust/metaobjects/src/dependencies.rs +++ b/server/rust/metaobjects/src/dependencies.rs @@ -12,9 +12,11 @@ use std::path::{Path, PathBuf}; use serde_json::{Map, Value}; use crate::config::DependencySpec; +use crate::config::dependency_name_ok; use crate::errors::{ - ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE, ERR_DEPENDENCY_NODE_COLLISION, - ERR_DEPENDENCY_PACKAGE_NOT_OWNED, ERR_DEPENDENCY_SNAPSHOT_STALE, MetaError, + ERR_DEPENDENCY_MANIFEST_INVALID, 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; @@ -29,6 +31,8 @@ pub const DEPS_DIR: &str = "deps"; pub const LOCK_FILE: &str = "deps.lock.json"; /// The suffix of a dependency's canonical-JSON artifact. pub const ARTIFACT_SUFFIX: &str = ".metaobjects.json"; +/// The publisher's manifest, beside its artifact. +pub const MANIFEST_FILE: &str = "metaobjects.pkg.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. @@ -37,6 +41,16 @@ pub const INTEGRITY_PREFIX: &str = "sha256-"; const TYPE_REQUIREMENT: &str = "requirement"; const ATTR_STATUS: &str = "status"; +const MANIFEST_KEYS: &[&str] = &[ + "schema_version", + "name", + "version", + "metamodelVersion", + "artifact", + "integrity", + "packages", + "nodes", +]; const LOCK_KEYS: &[&str] = &["schema_version", "dependencies"]; const LOCK_ENTRY_KEYS: &[&str] = &[ "version", @@ -264,6 +278,45 @@ fn validate_resolved_from( Ok(()) } +/// A validated publisher manifest (`metaobjects.pkg.json`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Manifest { + pub name: String, + /// The fields a manifest shares with a lock entry. + pub entry: LockEntry, +} + +/// Validate a parsed `metaobjects.pkg.json`. Every shape violation (an unknown key, a +/// resurrected `mode` among them, an unsorted `packages` / `nodes`, a malformed field) is +/// `ERR_DEPENDENCY_MANIFEST_INVALID`. +pub fn validate_manifest(v: &Value) -> Result { + let fail = |m: String| { + MetaError::code( + ERR_DEPENDENCY_MANIFEST_INVALID, + format!("{MANIFEST_FILE}: {m}"), + ) + }; + let Some(obj) = v.as_object() else { + return Err(fail("must be an object".into())); + }; + let extra = unknown_keys(obj, MANIFEST_KEYS); + if !extra.is_empty() { + return Err(fail(format!("unknown key(s): {extra:?}"))); + } + if obj.get("schema_version").and_then(Value::as_u64) != Some(1) { + return Err(fail("'schema_version' must be 1".into())); + } + let name = obj + .get("name") + .and_then(Value::as_str) + .filter(|n| dependency_name_ok(n)) + .ok_or_else(|| fail("'name' must match ^[a-z0-9][a-z0-9._-]*$".into()))?; + Ok(Manifest { + name: name.to_string(), + entry: validate_common_fields(obj, &fail)?, + }) +} + /// 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 { diff --git a/server/rust/metaobjects/src/dependency_check.rs b/server/rust/metaobjects/src/dependency_check.rs new file mode 100644 index 000000000..e41bd4999 --- /dev/null +++ b/server/rust/metaobjects/src/dependency_check.rs @@ -0,0 +1,227 @@ +//! FR-023 phase 2, the upstream dependency check behind `cargo meta verify --deps`. +//! +//! For each declared dependency: resolve its `path`, read and validate the publisher's +//! `metaobjects.pkg.json`, hash the artifact beside it, and compare with the lock. Ported +//! from the TypeScript `checkDependencies` (`cli/src/lib/dependency-sync.ts`) and Python's +//! `config/dependency_check.py`; the `expectCheck` arm of `fixtures/dependency-conformance/` +//! pins the behaviour. +//! +//! The check is a pure function of the config, the lock and the publisher's directory. It +//! writes nothing and needs no loader: Node `meta deps sync`, the only writer of the lock +//! and the snapshot, is what repairs a drift this reports. +//! +//! Only the `path` transport is resolved here. An `npm` / `python` / `maven` / `nuget` +//! dependency is found through the consumer's installed packages or local package caches, +//! which the Node toolchain reads, so this check reports it `unresolved` and names +//! `meta deps check`: a check that cannot check must not pass. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use crate::config::{DependencySpec, DependencyTransport}; +use crate::dependencies::{ + INTEGRITY_PREFIX, Lock, MANIFEST_FILE, Manifest, sha256_integrity, validate_manifest, +}; +use crate::errors::ERR_DEPENDENCY_UPSTREAM_DRIFT; + +/// One dependency's verdict. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CheckStatus { + /// The artifact resolves and hashes to the lock's `integrity`. + Current, + /// The artifact resolves, but hashes to something else. + Drifted, + /// The check could not compare, so it must not pass. + Unresolved, +} + +impl CheckStatus { + /// The corpus's word for the status. + pub fn as_str(self) -> &'static str { + match self { + CheckStatus::Current => "current", + CheckStatus::Drifted => "drifted", + CheckStatus::Unresolved => "unresolved", + } + } +} + +/// One declared dependency's result. `lock_*` are `None` exactly when the lock has no entry +/// for it; `installed_*` are `None` exactly when resolution itself failed; `detail` is the +/// reason, for `Unresolved` only. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DependencyCheckResult { + pub name: String, + pub status: CheckStatus, + pub lock_version: Option, + pub lock_integrity: Option, + pub installed_version: Option, + pub installed_integrity: Option, + pub detail: Option, +} + +/// The transport's key in the config, for the message about a non-path transport. +fn transport_key(t: &DependencyTransport) -> &'static str { + match t { + DependencyTransport::Path(_) => "path", + DependencyTransport::Npm { .. } => "npm", + DependencyTransport::Python { .. } => "python", + DependencyTransport::Maven { .. } => "maven", + DependencyTransport::Nuget { .. } => "nuget", + } +} + +fn resolve_dir(config_dir: &Path, spec: &DependencySpec) -> Result { + let DependencyTransport::Path(path) = &spec.transport else { + return Err(format!( + "the \"{}\" transport is resolved by the Node toolchain; run `meta deps check` to check this dependency", + transport_key(&spec.transport) + )); + }; + let target = config_dir.join(path); + if !target.is_dir() { + return Err(format!( + "the \"path\" transport resolved to {}, but no directory exists there", + target.display() + )); + } + Ok(target) +} + +/// `/metaobjects.pkg.json`, strict, and the artifact bytes beside it, verified to hash +/// to the manifest's own `integrity` (a publisher who bypassed the shared-model generator +/// is caught here). +fn read_manifest(dir: &Path) -> Result<(Manifest, Vec), String> { + let manifest_path = dir.join(MANIFEST_FILE); + let shown = manifest_path.display(); + let raw = std::fs::read(&manifest_path) + .map_err(|_| format!("no {MANIFEST_FILE} found at {shown}"))?; + let parsed: Value = + serde_json::from_slice(&raw).map_err(|e| format!("{shown} is not valid JSON: {e}"))?; + let manifest = validate_manifest(&parsed) + .map_err(|e| format!("{shown} failed schema validation — {}", e.message))?; + + let artifact = &manifest.entry.artifact; + let artifact_path = dir.join(artifact); + let data = std::fs::read(&artifact_path).map_err(|_| { + format!( + "the manifest names artifact \"{artifact}\", but it is missing at {}", + artifact_path.display() + ) + })?; + let actual = sha256_integrity(&data); + if actual != manifest.entry.integrity { + return Err(format!( + "{} hashes to {actual}, but the manifest records {}", + artifact_path.display(), + manifest.entry.integrity + )); + } + Ok((manifest, data)) +} + +/// Resolve each declared dependency and compare its artifact's TRUE hash (re-hashed from +/// the bytes on disk, never the manifest's own field taken on faith) with the lock's. +/// Read-only. One result per declared dependency, in name order. `lock` is `None` when +/// there is no lock file, which makes every dependency `Unresolved`. +pub fn check_dependencies( + config_dir: &Path, + specs: &[DependencySpec], + lock: Option<&Lock>, +) -> Vec { + let mut sorted: Vec<&DependencySpec> = specs.iter().collect(); + sorted.sort_by(|a, b| a.name.cmp(&b.name)); + sorted + .into_iter() + .map(|spec| { + let entry = lock.and_then(|l| l.dependencies.get(&spec.name)); + let lock_version = entry.map(|e| e.version.clone()); + let lock_integrity = entry.map(|e| e.integrity.clone()); + let unresolved = |detail: String, installed: Option<(String, String)>| { + let (installed_version, installed_integrity) = installed.unzip(); + DependencyCheckResult { + name: spec.name.clone(), + status: CheckStatus::Unresolved, + lock_version: lock_version.clone(), + lock_integrity: lock_integrity.clone(), + installed_version, + installed_integrity, + detail: Some(detail), + } + }; + let (manifest, data) = + match resolve_dir(config_dir, spec).and_then(|d| read_manifest(&d)) { + Ok(read) => read, + Err(detail) => return unresolved(detail, None), + }; + let installed = sha256_integrity(&data); + let Some(entry) = entry else { + return unresolved( + "declared, and resolves, but is not in the lock yet".into(), + Some((manifest.entry.version, installed)), + ); + }; + DependencyCheckResult { + name: spec.name.clone(), + status: if installed == entry.integrity { + CheckStatus::Current + } else { + CheckStatus::Drifted + }, + lock_version, + lock_integrity, + installed_version: Some(manifest.entry.version), + installed_integrity: Some(installed), + detail: None, + } + }) + .collect() +} + +/// The first 8 hex digits of an `sha256-` integrity, the report's short form. +pub fn hash8(integrity: &str) -> &str { + let hex = integrity + .strip_prefix(INTEGRITY_PREFIX) + .unwrap_or(integrity); + &hex[..hex.len().min(8)] +} + +fn describe(version: Option<&str>, integrity: Option<&str>) -> String { + format!( + "{} ({})", + version.unwrap_or("(none)"), + integrity.map_or("n/a", hash8) + ) +} + +/// One report line per dependency, the shape every port prints. +pub fn format_check_line(r: &DependencyCheckResult) -> String { + let lock = describe(r.lock_version.as_deref(), r.lock_integrity.as_deref()); + match r.status { + CheckStatus::Current => format!("{}: current — {lock}", r.name), + CheckStatus::Drifted => format!( + "{}: drifted — lock {lock}, installed {}; run meta deps sync and review the artifact diff", + r.name, + describe( + r.installed_version.as_deref(), + r.installed_integrity.as_deref() + ) + ), + CheckStatus::Unresolved => format!( + "{}: unresolved — {}; run meta deps sync once the dependency is reachable", + r.name, + r.detail + .as_deref() + .unwrap_or("could not resolve the dependency") + ), + } +} + +/// The failure summary, naming the one code every non-current result is reported under. +pub fn summary_line(command: &str, failing: usize, total: usize) -> String { + let plural = if total == 1 { "y" } else { "ies" }; + format!( + "{command}: {failing} of {total} dependenc{plural} drifted or unresolved ({ERR_DEPENDENCY_UPSTREAM_DRIFT})." + ) +} diff --git a/server/rust/metaobjects/src/errors.rs b/server/rust/metaobjects/src/errors.rs index d211007d8..3a22ddbe0 100644 --- a/server/rust/metaobjects/src/errors.rs +++ b/server/rust/metaobjects/src/errors.rs @@ -55,6 +55,11 @@ pub const ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE: &str = "ERR_DEPENDENCY_METAMODE 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 publisher's `metaobjects.pkg.json` fails its schema, or names a missing or +/// hash-mismatched artifact. +pub const ERR_DEPENDENCY_MANIFEST_INVALID: &str = "ERR_DEPENDENCY_MANIFEST_INVALID"; +/// `verify --deps` found a dependency drifted from, or not comparable with, its lock. +pub const ERR_DEPENDENCY_UPSTREAM_DRIFT: &str = "ERR_DEPENDENCY_UPSTREAM_DRIFT"; /// 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 @@ -104,6 +109,8 @@ pub const ALL_CODES: &[&str] = &[ ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE, ERR_DEPENDENCY_NODE_COLLISION, ERR_DEPENDENCY_PACKAGE_NOT_OWNED, + ERR_DEPENDENCY_MANIFEST_INVALID, + ERR_DEPENDENCY_UPSTREAM_DRIFT, 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 4bd7741d4..8b5cd00f7 100644 --- a/server/rust/metaobjects/src/lib.rs +++ b/server/rust/metaobjects/src/lib.rs @@ -9,6 +9,7 @@ pub mod collection; pub mod config; pub mod dependencies; +pub mod dependency_check; pub mod docs_view; pub mod errors; pub mod json; diff --git a/server/rust/metaobjects/tests/dependency_conformance.rs b/server/rust/metaobjects/tests/dependency_conformance.rs index e70bf0b3c..5a0583562 100644 --- a/server/rust/metaobjects/tests/dependency_conformance.rs +++ b/server/rust/metaobjects/tests/dependency_conformance.rs @@ -4,7 +4,8 @@ //! 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# +//! The check arm (`expectCheck`, `cargo meta verify --deps`) runs the same cases through +//! `check_dependencies`: one status per declared dependency. 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. @@ -13,7 +14,9 @@ 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::config::load_config; +use metaobjects::dependencies::{read_lock, refuse_unowned_packages, requirement_ledger}; +use metaobjects::dependency_check::check_dependencies; use metaobjects::loader::{LoadResult, Loader}; use metaobjects::naming::NamingRegistry; use metaobjects::parser::TYPE_OBJECT; @@ -313,3 +316,68 @@ fn every_resolution_case_resolves_and_loads_as_in_every_port() { failures.join("\n") ); } + +/// Run one check-arm case; `Err` describes how it diverged. +fn run_check_case(case: &Value) -> Result<(), String> { + let scratch = Scratch::new(); + let from = materialize(&scratch.0, case); + let config = load_config(&from.join(".metaobjects"), &NamingRegistry::builtin()) + .map_err(|e| format!("the config did not load: {} {}", e.code, e.message))?; + let lock = + read_lock(&from).map_err(|e| format!("the lock did not read: {} {}", e.code, e.message))?; + let results = check_dependencies(&from, &config.config.dependencies, lock.as_ref()); + let actual: BTreeMap = results + .iter() + .map(|r| (r.name.clone(), r.status.as_str().to_string())) + .collect(); + let expected: BTreeMap = case["expectCheck"] + .as_object() + .unwrap() + .iter() + .map(|(k, v)| (k.clone(), v.as_str().unwrap().to_string())) + .collect(); + if actual != expected || results.len() != expected.len() { + return Err(format!("check {actual:?} != expected {expected:?}")); + } + // An unresolved result says why; a current or drifted one does not. + for r in &results { + if r.detail.is_some() != (r.status.as_str() == "unresolved") { + return Err(format!( + "{}: detail {:?} beside {}", + r.name, + r.detail, + r.status.as_str() + )); + } + } + Ok(()) +} + +#[test] +fn every_check_case_reports_each_dependency_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_some()) + .collect(); + // The check arm has 11 cases: a silently shrunk corpus is a failed gate, not a pass. + assert_eq!(cases.len(), 11, "the check arm's case count"); + let failures: Vec = cases + .iter() + .filter_map(|case| { + run_check_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/spec/decisions/ADR-0065-rust-is-the-sixth-port.md b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md index 7209efbac..705496cbd 100644 --- a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md +++ b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md @@ -151,7 +151,8 @@ so they are not re-derived. bare `verify` runs it. *(Gates superseded by Amendment 6: the port now ships `verify --templates` too, and a bare `verify` runs the codegen, template and rules gates.)* `--db`, `--templates` and `--deps` exit 2 and say where that check lives. *(The `--templates` refusal is superseded by - Amendment 6; `--db` and `--deps` still exit 2.)* + Amendment 6; `--db` and `--deps` still exit 2. The `--deps` half is superseded by + Amendment 9.)* This corrects Decision 6, which listed `fmt`: the command today is `init`, `gen`, `verify --codegen` and `eject`. `fmt` and the template gate come with the phases that need them. *(The template gate has arrived — Amendment 6; there is still no `fmt`.)* @@ -339,7 +340,8 @@ without a template *generator*: `cargo meta verify --templates` checks every `template.*` body (Mustache, under `prompts/` or `--prompts `) against its payload value object and checks each prompt's `@responseRef` reply, through the new `verify` module of `metaobjects-render`. A bare `verify` runs the codegen, template and rules gates; -`--codegen` or `--templates` alone runs that one gate. `--db` and `--deps` still exit 2, and there is +`--codegen` or `--templates` alone runs that one gate. `--db` and `--deps` still exit 2 (the +`--deps` half is superseded by Amendment 9), and there is still no `fmt`, no `migrate`, no `verify --db` (ADR-0015) and no template generator. A Jinja body is refused (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`), as ruling 6 already stated. The port runs `fixtures/verify-conformance/` (all 45 cases), `fixtures/response-verify-conformance/` (all 7) and @@ -408,3 +410,12 @@ difference: Decision 2's layout is otherwise unchanged. The `render-shadowed-dotted-prefix`, `render-list-length` and `render-zero-falsiness` fixtures run in Rust without a ledger entry (`docs/CONFORMANCE.md`). + +## Amendment 9: the dependency check shipped (2026-12-03) + +The 1.4.0 wave-0 Rust dependency check (Wave 0 row R1b) supersedes the `--deps` refusal of Ruling 4 +and Amendment 6. `cargo meta verify --deps` now runs the FR-023 dependency check, over the `path` +transport only, as the Python, C#, Java and Kotlin checks do. It exits 1 when a dependency is +drifted or unresolved (`ERR_DEPENDENCY_UPSTREAM_DRIFT`), and 2 only when the config or the lock +cannot be read or the directory it is pointed at is not a project (a check that found nothing to +read must not pass). The check is opt-in and never part of a bare `verify`. `--db` still exits 2.